]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/vm/vm_page.c
Introduce vm_page_alloc_noobj_contig()
[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/vm_dumpset.h>
112 #include <vm/uma.h>
113 #include <vm/uma_int.h>
114
115 #include <machine/md_var.h>
116
117 struct vm_domain vm_dom[MAXMEMDOM];
118
119 DPCPU_DEFINE_STATIC(struct vm_batchqueue, pqbatch[MAXMEMDOM][PQ_COUNT]);
120
121 struct mtx_padalign __exclusive_cache_line pa_lock[PA_LOCK_COUNT];
122
123 struct mtx_padalign __exclusive_cache_line vm_domainset_lock;
124 /* The following fields are protected by the domainset lock. */
125 domainset_t __exclusive_cache_line vm_min_domains;
126 domainset_t __exclusive_cache_line vm_severe_domains;
127 static int vm_min_waiters;
128 static int vm_severe_waiters;
129 static int vm_pageproc_waiters;
130
131 static SYSCTL_NODE(_vm_stats, OID_AUTO, page, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
132     "VM page statistics");
133
134 static COUNTER_U64_DEFINE_EARLY(pqstate_commit_retries);
135 SYSCTL_COUNTER_U64(_vm_stats_page, OID_AUTO, pqstate_commit_retries,
136     CTLFLAG_RD, &pqstate_commit_retries,
137     "Number of failed per-page atomic queue state updates");
138
139 static COUNTER_U64_DEFINE_EARLY(queue_ops);
140 SYSCTL_COUNTER_U64(_vm_stats_page, OID_AUTO, queue_ops,
141     CTLFLAG_RD, &queue_ops,
142     "Number of batched queue operations");
143
144 static COUNTER_U64_DEFINE_EARLY(queue_nops);
145 SYSCTL_COUNTER_U64(_vm_stats_page, OID_AUTO, queue_nops,
146     CTLFLAG_RD, &queue_nops,
147     "Number of batched queue operations with no effects");
148
149 /*
150  * bogus page -- for I/O to/from partially complete buffers,
151  * or for paging into sparsely invalid regions.
152  */
153 vm_page_t bogus_page;
154
155 vm_page_t vm_page_array;
156 long vm_page_array_size;
157 long first_page;
158
159 struct bitset *vm_page_dump;
160 long vm_page_dump_pages;
161
162 static TAILQ_HEAD(, vm_page) blacklist_head;
163 static int sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS);
164 SYSCTL_PROC(_vm, OID_AUTO, page_blacklist, CTLTYPE_STRING | CTLFLAG_RD |
165     CTLFLAG_MPSAFE, NULL, 0, sysctl_vm_page_blacklist, "A", "Blacklist pages");
166
167 static uma_zone_t fakepg_zone;
168
169 static void vm_page_alloc_check(vm_page_t m);
170 static bool _vm_page_busy_sleep(vm_object_t obj, vm_page_t m,
171     vm_pindex_t pindex, const char *wmesg, int allocflags, bool locked);
172 static void vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits);
173 static void vm_page_enqueue(vm_page_t m, uint8_t queue);
174 static bool vm_page_free_prep(vm_page_t m);
175 static void vm_page_free_toq(vm_page_t m);
176 static void vm_page_init(void *dummy);
177 static int vm_page_insert_after(vm_page_t m, vm_object_t object,
178     vm_pindex_t pindex, vm_page_t mpred);
179 static void vm_page_insert_radixdone(vm_page_t m, vm_object_t object,
180     vm_page_t mpred);
181 static void vm_page_mvqueue(vm_page_t m, const uint8_t queue,
182     const uint16_t nflag);
183 static int vm_page_reclaim_run(int req_class, int domain, u_long npages,
184     vm_page_t m_run, vm_paddr_t high);
185 static void vm_page_release_toq(vm_page_t m, uint8_t nqueue, bool noreuse);
186 static int vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object,
187     int req);
188 static int vm_page_zone_import(void *arg, void **store, int cnt, int domain,
189     int flags);
190 static void vm_page_zone_release(void *arg, void **store, int cnt);
191
192 SYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init, NULL);
193
194 static void
195 vm_page_init(void *dummy)
196 {
197
198         fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
199             NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
200         bogus_page = vm_page_alloc_noobj(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 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         struct vm_domain *vmd;
555         vm_page_t m;
556         char *list, *listend;
557         vm_paddr_t end, high_avail, low_avail, new_end, size;
558         vm_paddr_t page_range __unused;
559         vm_paddr_t last_pa, pa, startp, endp;
560         u_long pagecount;
561 #if MINIDUMP_PAGE_TRACKING
562         u_long vm_page_dump_size;
563 #endif
564         int biggestone, i, segind;
565 #ifdef WITNESS
566         vm_offset_t mapped;
567         int witness_size;
568 #endif
569 #if defined(__i386__) && defined(VM_PHYSSEG_DENSE)
570         long ii;
571 #endif
572
573         vaddr = round_page(vaddr);
574
575         vm_phys_early_startup();
576         biggestone = vm_phys_avail_largest();
577         end = phys_avail[biggestone+1];
578
579         /*
580          * Initialize the page and queue locks.
581          */
582         mtx_init(&vm_domainset_lock, "vm domainset lock", NULL, MTX_DEF);
583         for (i = 0; i < PA_LOCK_COUNT; i++)
584                 mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
585         for (i = 0; i < vm_ndomains; i++)
586                 vm_page_domain_init(i);
587
588         new_end = end;
589 #ifdef WITNESS
590         witness_size = round_page(witness_startup_count());
591         new_end -= witness_size;
592         mapped = pmap_map(&vaddr, new_end, new_end + witness_size,
593             VM_PROT_READ | VM_PROT_WRITE);
594         bzero((void *)mapped, witness_size);
595         witness_startup((void *)mapped);
596 #endif
597
598 #if MINIDUMP_PAGE_TRACKING
599         /*
600          * Allocate a bitmap to indicate that a random physical page
601          * needs to be included in a minidump.
602          *
603          * The amd64 port needs this to indicate which direct map pages
604          * need to be dumped, via calls to dump_add_page()/dump_drop_page().
605          *
606          * However, i386 still needs this workspace internally within the
607          * minidump code.  In theory, they are not needed on i386, but are
608          * included should the sf_buf code decide to use them.
609          */
610         last_pa = 0;
611         vm_page_dump_pages = 0;
612         for (i = 0; dump_avail[i + 1] != 0; i += 2) {
613                 vm_page_dump_pages += howmany(dump_avail[i + 1], PAGE_SIZE) -
614                     dump_avail[i] / PAGE_SIZE;
615                 if (dump_avail[i + 1] > last_pa)
616                         last_pa = dump_avail[i + 1];
617         }
618         vm_page_dump_size = round_page(BITSET_SIZE(vm_page_dump_pages));
619         new_end -= vm_page_dump_size;
620         vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
621             new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
622         bzero((void *)vm_page_dump, vm_page_dump_size);
623 #else
624         (void)last_pa;
625 #endif
626 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
627     defined(__riscv) || defined(__powerpc64__)
628         /*
629          * Include the UMA bootstrap pages, witness pages and vm_page_dump
630          * in a crash dump.  When pmap_map() uses the direct map, they are
631          * not automatically included.
632          */
633         for (pa = new_end; pa < end; pa += PAGE_SIZE)
634                 dump_add_page(pa);
635 #endif
636         phys_avail[biggestone + 1] = new_end;
637 #ifdef __amd64__
638         /*
639          * Request that the physical pages underlying the message buffer be
640          * included in a crash dump.  Since the message buffer is accessed
641          * through the direct map, they are not automatically included.
642          */
643         pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
644         last_pa = pa + round_page(msgbufsize);
645         while (pa < last_pa) {
646                 dump_add_page(pa);
647                 pa += PAGE_SIZE;
648         }
649 #endif
650         /*
651          * Compute the number of pages of memory that will be available for
652          * use, taking into account the overhead of a page structure per page.
653          * In other words, solve
654          *      "available physical memory" - round_page(page_range *
655          *          sizeof(struct vm_page)) = page_range * PAGE_SIZE 
656          * for page_range.  
657          */
658         low_avail = phys_avail[0];
659         high_avail = phys_avail[1];
660         for (i = 0; i < vm_phys_nsegs; i++) {
661                 if (vm_phys_segs[i].start < low_avail)
662                         low_avail = vm_phys_segs[i].start;
663                 if (vm_phys_segs[i].end > high_avail)
664                         high_avail = vm_phys_segs[i].end;
665         }
666         /* Skip the first chunk.  It is already accounted for. */
667         for (i = 2; phys_avail[i + 1] != 0; i += 2) {
668                 if (phys_avail[i] < low_avail)
669                         low_avail = phys_avail[i];
670                 if (phys_avail[i + 1] > high_avail)
671                         high_avail = phys_avail[i + 1];
672         }
673         first_page = low_avail / PAGE_SIZE;
674 #ifdef VM_PHYSSEG_SPARSE
675         size = 0;
676         for (i = 0; i < vm_phys_nsegs; i++)
677                 size += vm_phys_segs[i].end - vm_phys_segs[i].start;
678         for (i = 0; phys_avail[i + 1] != 0; i += 2)
679                 size += phys_avail[i + 1] - phys_avail[i];
680 #elif defined(VM_PHYSSEG_DENSE)
681         size = high_avail - low_avail;
682 #else
683 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
684 #endif
685
686 #ifdef PMAP_HAS_PAGE_ARRAY
687         pmap_page_array_startup(size / PAGE_SIZE);
688         biggestone = vm_phys_avail_largest();
689         end = new_end = phys_avail[biggestone + 1];
690 #else
691 #ifdef VM_PHYSSEG_DENSE
692         /*
693          * In the VM_PHYSSEG_DENSE case, the number of pages can account for
694          * the overhead of a page structure per page only if vm_page_array is
695          * allocated from the last physical memory chunk.  Otherwise, we must
696          * allocate page structures representing the physical memory
697          * underlying vm_page_array, even though they will not be used.
698          */
699         if (new_end != high_avail)
700                 page_range = size / PAGE_SIZE;
701         else
702 #endif
703         {
704                 page_range = size / (PAGE_SIZE + sizeof(struct vm_page));
705
706                 /*
707                  * If the partial bytes remaining are large enough for
708                  * a page (PAGE_SIZE) without a corresponding
709                  * 'struct vm_page', then new_end will contain an
710                  * extra page after subtracting the length of the VM
711                  * page array.  Compensate by subtracting an extra
712                  * page from new_end.
713                  */
714                 if (size % (PAGE_SIZE + sizeof(struct vm_page)) >= PAGE_SIZE) {
715                         if (new_end == high_avail)
716                                 high_avail -= PAGE_SIZE;
717                         new_end -= PAGE_SIZE;
718                 }
719         }
720         end = new_end;
721         new_end = vm_page_array_alloc(&vaddr, end, page_range);
722 #endif
723
724 #if VM_NRESERVLEVEL > 0
725         /*
726          * Allocate physical memory for the reservation management system's
727          * data structures, and map it.
728          */
729         new_end = vm_reserv_startup(&vaddr, new_end);
730 #endif
731 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
732     defined(__riscv) || defined(__powerpc64__)
733         /*
734          * Include vm_page_array and vm_reserv_array in a crash dump.
735          */
736         for (pa = new_end; pa < end; pa += PAGE_SIZE)
737                 dump_add_page(pa);
738 #endif
739         phys_avail[biggestone + 1] = new_end;
740
741         /*
742          * Add physical memory segments corresponding to the available
743          * physical pages.
744          */
745         for (i = 0; phys_avail[i + 1] != 0; i += 2)
746                 if (vm_phys_avail_size(i) != 0)
747                         vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
748
749         /*
750          * Initialize the physical memory allocator.
751          */
752         vm_phys_init();
753
754         /*
755          * Initialize the page structures and add every available page to the
756          * physical memory allocator's free lists.
757          */
758 #if defined(__i386__) && defined(VM_PHYSSEG_DENSE)
759         for (ii = 0; ii < vm_page_array_size; ii++) {
760                 m = &vm_page_array[ii];
761                 vm_page_init_page(m, (first_page + ii) << PAGE_SHIFT, 0);
762                 m->flags = PG_FICTITIOUS;
763         }
764 #endif
765         vm_cnt.v_page_count = 0;
766         for (segind = 0; segind < vm_phys_nsegs; segind++) {
767                 seg = &vm_phys_segs[segind];
768                 for (m = seg->first_page, pa = seg->start; pa < seg->end;
769                     m++, pa += PAGE_SIZE)
770                         vm_page_init_page(m, pa, segind);
771
772                 /*
773                  * Add the segment's pages that are covered by one of
774                  * phys_avail's ranges to the free lists.
775                  */
776                 for (i = 0; phys_avail[i + 1] != 0; i += 2) {
777                         if (seg->end <= phys_avail[i] ||
778                             seg->start >= phys_avail[i + 1])
779                                 continue;
780
781                         startp = MAX(seg->start, phys_avail[i]);
782                         endp = MIN(seg->end, phys_avail[i + 1]);
783                         pagecount = (u_long)atop(endp - startp);
784                         if (pagecount == 0)
785                                 continue;
786
787                         m = seg->first_page + atop(startp - seg->start);
788                         vmd = VM_DOMAIN(seg->domain);
789                         vm_domain_free_lock(vmd);
790                         vm_phys_enqueue_contig(m, pagecount);
791                         vm_domain_free_unlock(vmd);
792                         vm_domain_freecnt_inc(vmd, pagecount);
793                         vm_cnt.v_page_count += (u_int)pagecount;
794                         vmd->vmd_page_count += (u_int)pagecount;
795                         vmd->vmd_segs |= 1UL << segind;
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 = atomic_load_ptr(&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_lookup_unlocked:
1699  *
1700  *      Returns the page associated with the object/offset pair specified;
1701  *      if none is found, NULL is returned.  The page may be no longer be
1702  *      present in the object at the time that this function returns.  Only
1703  *      useful for opportunistic checks such as inmem().
1704  */
1705 vm_page_t
1706 vm_page_lookup_unlocked(vm_object_t object, vm_pindex_t pindex)
1707 {
1708
1709         return (vm_radix_lookup_unlocked(&object->rtree, pindex));
1710 }
1711
1712 /*
1713  *      vm_page_relookup:
1714  *
1715  *      Returns a page that must already have been busied by
1716  *      the caller.  Used for bogus page replacement.
1717  */
1718 vm_page_t
1719 vm_page_relookup(vm_object_t object, vm_pindex_t pindex)
1720 {
1721         vm_page_t m;
1722
1723         m = vm_radix_lookup_unlocked(&object->rtree, pindex);
1724         KASSERT(m != NULL && (vm_page_busied(m) || vm_page_wired(m)) &&
1725             m->object == object && m->pindex == pindex,
1726             ("vm_page_relookup: Invalid page %p", m));
1727         return (m);
1728 }
1729
1730 /*
1731  * This should only be used by lockless functions for releasing transient
1732  * incorrect acquires.  The page may have been freed after we acquired a
1733  * busy lock.  In this case busy_lock == VPB_FREED and we have nothing
1734  * further to do.
1735  */
1736 static void
1737 vm_page_busy_release(vm_page_t m)
1738 {
1739         u_int x;
1740
1741         x = vm_page_busy_fetch(m);
1742         for (;;) {
1743                 if (x == VPB_FREED)
1744                         break;
1745                 if ((x & VPB_BIT_SHARED) != 0 && VPB_SHARERS(x) > 1) {
1746                         if (atomic_fcmpset_int(&m->busy_lock, &x,
1747                             x - VPB_ONE_SHARER))
1748                                 break;
1749                         continue;
1750                 }
1751                 KASSERT((x & VPB_BIT_SHARED) != 0 ||
1752                     (x & ~VPB_BIT_WAITERS) == VPB_CURTHREAD_EXCLUSIVE,
1753                     ("vm_page_busy_release: %p xbusy not owned.", m));
1754                 if (!atomic_fcmpset_rel_int(&m->busy_lock, &x, VPB_UNBUSIED))
1755                         continue;
1756                 if ((x & VPB_BIT_WAITERS) != 0)
1757                         wakeup(m);
1758                 break;
1759         }
1760 }
1761
1762 /*
1763  *      vm_page_find_least:
1764  *
1765  *      Returns the page associated with the object with least pindex
1766  *      greater than or equal to the parameter pindex, or NULL.
1767  *
1768  *      The object must be locked.
1769  */
1770 vm_page_t
1771 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1772 {
1773         vm_page_t m;
1774
1775         VM_OBJECT_ASSERT_LOCKED(object);
1776         if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1777                 m = vm_radix_lookup_ge(&object->rtree, pindex);
1778         return (m);
1779 }
1780
1781 /*
1782  * Returns the given page's successor (by pindex) within the object if it is
1783  * resident; if none is found, NULL is returned.
1784  *
1785  * The object must be locked.
1786  */
1787 vm_page_t
1788 vm_page_next(vm_page_t m)
1789 {
1790         vm_page_t next;
1791
1792         VM_OBJECT_ASSERT_LOCKED(m->object);
1793         if ((next = TAILQ_NEXT(m, listq)) != NULL) {
1794                 MPASS(next->object == m->object);
1795                 if (next->pindex != m->pindex + 1)
1796                         next = NULL;
1797         }
1798         return (next);
1799 }
1800
1801 /*
1802  * Returns the given page's predecessor (by pindex) within the object if it is
1803  * resident; if none is found, NULL is returned.
1804  *
1805  * The object must be locked.
1806  */
1807 vm_page_t
1808 vm_page_prev(vm_page_t m)
1809 {
1810         vm_page_t prev;
1811
1812         VM_OBJECT_ASSERT_LOCKED(m->object);
1813         if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL) {
1814                 MPASS(prev->object == m->object);
1815                 if (prev->pindex != m->pindex - 1)
1816                         prev = NULL;
1817         }
1818         return (prev);
1819 }
1820
1821 /*
1822  * Uses the page mnew as a replacement for an existing page at index
1823  * pindex which must be already present in the object.
1824  *
1825  * Both pages must be exclusively busied on enter.  The old page is
1826  * unbusied on exit.
1827  *
1828  * A return value of true means mold is now free.  If this is not the
1829  * final ref and the caller does not hold a wire reference it may not
1830  * continue to access the page.
1831  */
1832 static bool
1833 vm_page_replace_hold(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex,
1834     vm_page_t mold)
1835 {
1836         vm_page_t mret;
1837         bool dropped;
1838
1839         VM_OBJECT_ASSERT_WLOCKED(object);
1840         vm_page_assert_xbusied(mold);
1841         KASSERT(mnew->object == NULL && (mnew->ref_count & VPRC_OBJREF) == 0,
1842             ("vm_page_replace: page %p already in object", mnew));
1843
1844         /*
1845          * This function mostly follows vm_page_insert() and
1846          * vm_page_remove() without the radix, object count and vnode
1847          * dance.  Double check such functions for more comments.
1848          */
1849
1850         mnew->object = object;
1851         mnew->pindex = pindex;
1852         atomic_set_int(&mnew->ref_count, VPRC_OBJREF);
1853         mret = vm_radix_replace(&object->rtree, mnew);
1854         KASSERT(mret == mold,
1855             ("invalid page replacement, mold=%p, mret=%p", mold, mret));
1856         KASSERT((mold->oflags & VPO_UNMANAGED) ==
1857             (mnew->oflags & VPO_UNMANAGED),
1858             ("vm_page_replace: mismatched VPO_UNMANAGED"));
1859
1860         /* Keep the resident page list in sorted order. */
1861         TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
1862         TAILQ_REMOVE(&object->memq, mold, listq);
1863         mold->object = NULL;
1864
1865         /*
1866          * The object's resident_page_count does not change because we have
1867          * swapped one page for another, but the generation count should
1868          * change if the page is dirty.
1869          */
1870         if (pmap_page_is_write_mapped(mnew))
1871                 vm_object_set_writeable_dirty(object);
1872         dropped = vm_page_drop(mold, VPRC_OBJREF) == VPRC_OBJREF;
1873         vm_page_xunbusy(mold);
1874
1875         return (dropped);
1876 }
1877
1878 void
1879 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex,
1880     vm_page_t mold)
1881 {
1882
1883         vm_page_assert_xbusied(mnew);
1884
1885         if (vm_page_replace_hold(mnew, object, pindex, mold))
1886                 vm_page_free(mold);
1887 }
1888
1889 /*
1890  *      vm_page_rename:
1891  *
1892  *      Move the given memory entry from its
1893  *      current object to the specified target object/offset.
1894  *
1895  *      Note: swap associated with the page must be invalidated by the move.  We
1896  *            have to do this for several reasons:  (1) we aren't freeing the
1897  *            page, (2) we are dirtying the page, (3) the VM system is probably
1898  *            moving the page from object A to B, and will then later move
1899  *            the backing store from A to B and we can't have a conflict.
1900  *
1901  *      Note: we *always* dirty the page.  It is necessary both for the
1902  *            fact that we moved it, and because we may be invalidating
1903  *            swap.
1904  *
1905  *      The objects must be locked.
1906  */
1907 int
1908 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1909 {
1910         vm_page_t mpred;
1911         vm_pindex_t opidx;
1912
1913         VM_OBJECT_ASSERT_WLOCKED(new_object);
1914
1915         KASSERT(m->ref_count != 0, ("vm_page_rename: page %p has no refs", m));
1916         mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1917         KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1918             ("vm_page_rename: pindex already renamed"));
1919
1920         /*
1921          * Create a custom version of vm_page_insert() which does not depend
1922          * by m_prev and can cheat on the implementation aspects of the
1923          * function.
1924          */
1925         opidx = m->pindex;
1926         m->pindex = new_pindex;
1927         if (vm_radix_insert(&new_object->rtree, m)) {
1928                 m->pindex = opidx;
1929                 return (1);
1930         }
1931
1932         /*
1933          * The operation cannot fail anymore.  The removal must happen before
1934          * the listq iterator is tainted.
1935          */
1936         m->pindex = opidx;
1937         vm_page_object_remove(m);
1938
1939         /* Return back to the new pindex to complete vm_page_insert(). */
1940         m->pindex = new_pindex;
1941         m->object = new_object;
1942
1943         vm_page_insert_radixdone(m, new_object, mpred);
1944         vm_page_dirty(m);
1945         return (0);
1946 }
1947
1948 /*
1949  *      vm_page_alloc:
1950  *
1951  *      Allocate and return a page that is associated with the specified
1952  *      object and offset pair.  By default, this page is exclusive busied.
1953  *
1954  *      The caller must always specify an allocation class.
1955  *
1956  *      allocation classes:
1957  *      VM_ALLOC_NORMAL         normal process request
1958  *      VM_ALLOC_SYSTEM         system *really* needs a page
1959  *      VM_ALLOC_INTERRUPT      interrupt time request
1960  *
1961  *      optional allocation flags:
1962  *      VM_ALLOC_COUNT(number)  the number of additional pages that the caller
1963  *                              intends to allocate
1964  *      VM_ALLOC_NOBUSY         do not exclusive busy the page
1965  *      VM_ALLOC_NODUMP         do not include the page in a kernel core dump
1966  *      VM_ALLOC_NOOBJ          page is not associated with an object and
1967  *                              should not be exclusive busy
1968  *      VM_ALLOC_SBUSY          shared busy the allocated page
1969  *      VM_ALLOC_WIRED          wire the allocated page
1970  *      VM_ALLOC_ZERO           prefer a zeroed page
1971  */
1972 vm_page_t
1973 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1974 {
1975
1976         return (vm_page_alloc_after(object, pindex, req, object != NULL ?
1977             vm_radix_lookup_le(&object->rtree, pindex) : NULL));
1978 }
1979
1980 vm_page_t
1981 vm_page_alloc_domain(vm_object_t object, vm_pindex_t pindex, int domain,
1982     int req)
1983 {
1984
1985         return (vm_page_alloc_domain_after(object, pindex, domain, req,
1986             object != NULL ? vm_radix_lookup_le(&object->rtree, pindex) :
1987             NULL));
1988 }
1989
1990 /*
1991  * Allocate a page in the specified object with the given page index.  To
1992  * optimize insertion of the page into the object, the caller must also specifiy
1993  * the resident page in the object with largest index smaller than the given
1994  * page index, or NULL if no such page exists.
1995  */
1996 vm_page_t
1997 vm_page_alloc_after(vm_object_t object, vm_pindex_t pindex,
1998     int req, vm_page_t mpred)
1999 {
2000         struct vm_domainset_iter di;
2001         vm_page_t m;
2002         int domain;
2003
2004         vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
2005         do {
2006                 m = vm_page_alloc_domain_after(object, pindex, domain, req,
2007                     mpred);
2008                 if (m != NULL)
2009                         break;
2010         } while (vm_domainset_iter_page(&di, object, &domain) == 0);
2011
2012         return (m);
2013 }
2014
2015 /*
2016  * Returns true if the number of free pages exceeds the minimum
2017  * for the request class and false otherwise.
2018  */
2019 static int
2020 _vm_domain_allocate(struct vm_domain *vmd, int req_class, int npages)
2021 {
2022         u_int limit, old, new;
2023
2024         if (req_class == VM_ALLOC_INTERRUPT)
2025                 limit = 0;
2026         else if (req_class == VM_ALLOC_SYSTEM)
2027                 limit = vmd->vmd_interrupt_free_min;
2028         else
2029                 limit = vmd->vmd_free_reserved;
2030
2031         /*
2032          * Attempt to reserve the pages.  Fail if we're below the limit.
2033          */
2034         limit += npages;
2035         old = vmd->vmd_free_count;
2036         do {
2037                 if (old < limit)
2038                         return (0);
2039                 new = old - npages;
2040         } while (atomic_fcmpset_int(&vmd->vmd_free_count, &old, new) == 0);
2041
2042         /* Wake the page daemon if we've crossed the threshold. */
2043         if (vm_paging_needed(vmd, new) && !vm_paging_needed(vmd, old))
2044                 pagedaemon_wakeup(vmd->vmd_domain);
2045
2046         /* Only update bitsets on transitions. */
2047         if ((old >= vmd->vmd_free_min && new < vmd->vmd_free_min) ||
2048             (old >= vmd->vmd_free_severe && new < vmd->vmd_free_severe))
2049                 vm_domain_set(vmd);
2050
2051         return (1);
2052 }
2053
2054 int
2055 vm_domain_allocate(struct vm_domain *vmd, int req, int npages)
2056 {
2057         int req_class;
2058
2059         /*
2060          * The page daemon is allowed to dig deeper into the free page list.
2061          */
2062         req_class = req & VM_ALLOC_CLASS_MASK;
2063         if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2064                 req_class = VM_ALLOC_SYSTEM;
2065         return (_vm_domain_allocate(vmd, req_class, npages));
2066 }
2067
2068 vm_page_t
2069 vm_page_alloc_domain_after(vm_object_t object, vm_pindex_t pindex, int domain,
2070     int req, vm_page_t mpred)
2071 {
2072         struct vm_domain *vmd;
2073         vm_page_t m;
2074         int flags, pool;
2075
2076         KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
2077             (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
2078             ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
2079             (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
2080             ("inconsistent object(%p)/req(%x)", object, req));
2081         KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
2082             ("Can't sleep and retry object insertion."));
2083         KASSERT(mpred == NULL || mpred->pindex < pindex,
2084             ("mpred %p doesn't precede pindex 0x%jx", mpred,
2085             (uintmax_t)pindex));
2086         if (object != NULL)
2087                 VM_OBJECT_ASSERT_WLOCKED(object);
2088
2089         flags = 0;
2090         m = NULL;
2091         pool = object != NULL ? VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT;
2092 again:
2093 #if VM_NRESERVLEVEL > 0
2094         /*
2095          * Can we allocate the page from a reservation?
2096          */
2097         if (vm_object_reserv(object) &&
2098             (m = vm_reserv_alloc_page(object, pindex, domain, req, mpred)) !=
2099             NULL) {
2100                 goto found;
2101         }
2102 #endif
2103         vmd = VM_DOMAIN(domain);
2104         if (vmd->vmd_pgcache[pool].zone != NULL) {
2105                 m = uma_zalloc(vmd->vmd_pgcache[pool].zone, M_NOWAIT | M_NOVM);
2106                 if (m != NULL) {
2107                         flags |= PG_PCPU_CACHE;
2108                         goto found;
2109                 }
2110         }
2111         if (vm_domain_allocate(vmd, req, 1)) {
2112                 /*
2113                  * If not, allocate it from the free page queues.
2114                  */
2115                 vm_domain_free_lock(vmd);
2116                 m = vm_phys_alloc_pages(domain, pool, 0);
2117                 vm_domain_free_unlock(vmd);
2118                 if (m == NULL) {
2119                         vm_domain_freecnt_inc(vmd, 1);
2120 #if VM_NRESERVLEVEL > 0
2121                         if (vm_reserv_reclaim_inactive(domain))
2122                                 goto again;
2123 #endif
2124                 }
2125         }
2126         if (m == NULL) {
2127                 /*
2128                  * Not allocatable, give up.
2129                  */
2130                 if (vm_domain_alloc_fail(vmd, object, req))
2131                         goto again;
2132                 return (NULL);
2133         }
2134
2135         /*
2136          * At this point we had better have found a good page.
2137          */
2138 found:
2139         vm_page_dequeue(m);
2140         vm_page_alloc_check(m);
2141
2142         /*
2143          * Initialize the page.  Only the PG_ZERO flag is inherited.
2144          */
2145         if ((req & VM_ALLOC_ZERO) != 0)
2146                 flags |= (m->flags & PG_ZERO);
2147         if ((req & VM_ALLOC_NODUMP) != 0)
2148                 flags |= PG_NODUMP;
2149         m->flags = flags;
2150         m->a.flags = 0;
2151         m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
2152             VPO_UNMANAGED : 0;
2153         if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
2154                 m->busy_lock = VPB_CURTHREAD_EXCLUSIVE;
2155         else if ((req & VM_ALLOC_SBUSY) != 0)
2156                 m->busy_lock = VPB_SHARERS_WORD(1);
2157         else
2158                 m->busy_lock = VPB_UNBUSIED;
2159         if (req & VM_ALLOC_WIRED) {
2160                 vm_wire_add(1);
2161                 m->ref_count = 1;
2162         }
2163         m->a.act_count = 0;
2164
2165         if (object != NULL) {
2166                 if (vm_page_insert_after(m, object, pindex, mpred)) {
2167                         if (req & VM_ALLOC_WIRED) {
2168                                 vm_wire_sub(1);
2169                                 m->ref_count = 0;
2170                         }
2171                         KASSERT(m->object == NULL, ("page %p has object", m));
2172                         m->oflags = VPO_UNMANAGED;
2173                         m->busy_lock = VPB_UNBUSIED;
2174                         /* Don't change PG_ZERO. */
2175                         vm_page_free_toq(m);
2176                         if (req & VM_ALLOC_WAITFAIL) {
2177                                 VM_OBJECT_WUNLOCK(object);
2178                                 vm_radix_wait();
2179                                 VM_OBJECT_WLOCK(object);
2180                         }
2181                         return (NULL);
2182                 }
2183
2184                 /* Ignore device objects; the pager sets "memattr" for them. */
2185                 if (object->memattr != VM_MEMATTR_DEFAULT &&
2186                     (object->flags & OBJ_FICTITIOUS) == 0)
2187                         pmap_page_set_memattr(m, object->memattr);
2188         } else
2189                 m->pindex = pindex;
2190
2191         return (m);
2192 }
2193
2194 /*
2195  *      vm_page_alloc_contig:
2196  *
2197  *      Allocate a contiguous set of physical pages of the given size "npages"
2198  *      from the free lists.  All of the physical pages must be at or above
2199  *      the given physical address "low" and below the given physical address
2200  *      "high".  The given value "alignment" determines the alignment of the
2201  *      first physical page in the set.  If the given value "boundary" is
2202  *      non-zero, then the set of physical pages cannot cross any physical
2203  *      address boundary that is a multiple of that value.  Both "alignment"
2204  *      and "boundary" must be a power of two.
2205  *
2206  *      If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
2207  *      then the memory attribute setting for the physical pages is configured
2208  *      to the object's memory attribute setting.  Otherwise, the memory
2209  *      attribute setting for the physical pages is configured to "memattr",
2210  *      overriding the object's memory attribute setting.  However, if the
2211  *      object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
2212  *      memory attribute setting for the physical pages cannot be configured
2213  *      to VM_MEMATTR_DEFAULT.
2214  *
2215  *      The specified object may not contain fictitious pages.
2216  *
2217  *      The caller must always specify an allocation class.
2218  *
2219  *      allocation classes:
2220  *      VM_ALLOC_NORMAL         normal process request
2221  *      VM_ALLOC_SYSTEM         system *really* needs a page
2222  *      VM_ALLOC_INTERRUPT      interrupt time request
2223  *
2224  *      optional allocation flags:
2225  *      VM_ALLOC_NOBUSY         do not exclusive busy the page
2226  *      VM_ALLOC_NODUMP         do not include the page in a kernel core dump
2227  *      VM_ALLOC_NOOBJ          page is not associated with an object and
2228  *                              should not be exclusive busy
2229  *      VM_ALLOC_SBUSY          shared busy the allocated page
2230  *      VM_ALLOC_WIRED          wire the allocated page
2231  *      VM_ALLOC_ZERO           prefer a zeroed page
2232  */
2233 vm_page_t
2234 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
2235     u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
2236     vm_paddr_t boundary, vm_memattr_t memattr)
2237 {
2238         struct vm_domainset_iter di;
2239         vm_page_t m;
2240         int domain;
2241
2242         vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
2243         do {
2244                 m = vm_page_alloc_contig_domain(object, pindex, domain, req,
2245                     npages, low, high, alignment, boundary, memattr);
2246                 if (m != NULL)
2247                         break;
2248         } while (vm_domainset_iter_page(&di, object, &domain) == 0);
2249
2250         return (m);
2251 }
2252
2253 vm_page_t
2254 vm_page_alloc_contig_domain(vm_object_t object, vm_pindex_t pindex, int domain,
2255     int req, u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
2256     vm_paddr_t boundary, vm_memattr_t memattr)
2257 {
2258         struct vm_domain *vmd;
2259         vm_page_t m, m_ret, mpred;
2260         u_int busy_lock, flags, oflags;
2261
2262         mpred = NULL;   /* XXX: pacify gcc */
2263         KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
2264             (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
2265             ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
2266             (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
2267             ("vm_page_alloc_contig: inconsistent object(%p)/req(%x)", object,
2268             req));
2269         KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
2270             ("Can't sleep and retry object insertion."));
2271         if (object != NULL) {
2272                 VM_OBJECT_ASSERT_WLOCKED(object);
2273                 KASSERT((object->flags & OBJ_FICTITIOUS) == 0,
2274                     ("vm_page_alloc_contig: object %p has fictitious pages",
2275                     object));
2276         }
2277         KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
2278
2279         if (object != NULL) {
2280                 mpred = vm_radix_lookup_le(&object->rtree, pindex);
2281                 KASSERT(mpred == NULL || mpred->pindex != pindex,
2282                     ("vm_page_alloc_contig: pindex already allocated"));
2283         }
2284
2285         /*
2286          * Can we allocate the pages without the number of free pages falling
2287          * below the lower bound for the allocation class?
2288          */
2289         m_ret = NULL;
2290 again:
2291 #if VM_NRESERVLEVEL > 0
2292         /*
2293          * Can we allocate the pages from a reservation?
2294          */
2295         if (vm_object_reserv(object) &&
2296             (m_ret = vm_reserv_alloc_contig(object, pindex, domain, req,
2297             mpred, npages, low, high, alignment, boundary)) != NULL) {
2298                 goto found;
2299         }
2300 #endif
2301         vmd = VM_DOMAIN(domain);
2302         if (vm_domain_allocate(vmd, req, npages)) {
2303                 /*
2304                  * allocate them from the free page queues.
2305                  */
2306                 vm_domain_free_lock(vmd);
2307                 m_ret = vm_phys_alloc_contig(domain, npages, low, high,
2308                     alignment, boundary);
2309                 vm_domain_free_unlock(vmd);
2310                 if (m_ret == NULL) {
2311                         vm_domain_freecnt_inc(vmd, npages);
2312 #if VM_NRESERVLEVEL > 0
2313                         if (vm_reserv_reclaim_contig(domain, npages, low,
2314                             high, alignment, boundary))
2315                                 goto again;
2316 #endif
2317                 }
2318         }
2319         if (m_ret == NULL) {
2320                 if (vm_domain_alloc_fail(vmd, object, req))
2321                         goto again;
2322                 return (NULL);
2323         }
2324 #if VM_NRESERVLEVEL > 0
2325 found:
2326 #endif
2327         for (m = m_ret; m < &m_ret[npages]; m++) {
2328                 vm_page_dequeue(m);
2329                 vm_page_alloc_check(m);
2330         }
2331
2332         /*
2333          * Initialize the pages.  Only the PG_ZERO flag is inherited.
2334          */
2335         flags = 0;
2336         if ((req & VM_ALLOC_ZERO) != 0)
2337                 flags = PG_ZERO;
2338         if ((req & VM_ALLOC_NODUMP) != 0)
2339                 flags |= PG_NODUMP;
2340         oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
2341             VPO_UNMANAGED : 0;
2342         if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
2343                 busy_lock = VPB_CURTHREAD_EXCLUSIVE;
2344         else if ((req & VM_ALLOC_SBUSY) != 0)
2345                 busy_lock = VPB_SHARERS_WORD(1);
2346         else
2347                 busy_lock = VPB_UNBUSIED;
2348         if ((req & VM_ALLOC_WIRED) != 0)
2349                 vm_wire_add(npages);
2350         if (object != NULL) {
2351                 if (object->memattr != VM_MEMATTR_DEFAULT &&
2352                     memattr == VM_MEMATTR_DEFAULT)
2353                         memattr = object->memattr;
2354         }
2355         for (m = m_ret; m < &m_ret[npages]; m++) {
2356                 m->a.flags = 0;
2357                 m->flags = (m->flags | PG_NODUMP) & flags;
2358                 m->busy_lock = busy_lock;
2359                 if ((req & VM_ALLOC_WIRED) != 0)
2360                         m->ref_count = 1;
2361                 m->a.act_count = 0;
2362                 m->oflags = oflags;
2363                 if (object != NULL) {
2364                         if (vm_page_insert_after(m, object, pindex, mpred)) {
2365                                 if ((req & VM_ALLOC_WIRED) != 0)
2366                                         vm_wire_sub(npages);
2367                                 KASSERT(m->object == NULL,
2368                                     ("page %p has object", m));
2369                                 mpred = m;
2370                                 for (m = m_ret; m < &m_ret[npages]; m++) {
2371                                         if (m <= mpred &&
2372                                             (req & VM_ALLOC_WIRED) != 0)
2373                                                 m->ref_count = 0;
2374                                         m->oflags = VPO_UNMANAGED;
2375                                         m->busy_lock = VPB_UNBUSIED;
2376                                         /* Don't change PG_ZERO. */
2377                                         vm_page_free_toq(m);
2378                                 }
2379                                 if (req & VM_ALLOC_WAITFAIL) {
2380                                         VM_OBJECT_WUNLOCK(object);
2381                                         vm_radix_wait();
2382                                         VM_OBJECT_WLOCK(object);
2383                                 }
2384                                 return (NULL);
2385                         }
2386                         mpred = m;
2387                 } else
2388                         m->pindex = pindex;
2389                 if (memattr != VM_MEMATTR_DEFAULT)
2390                         pmap_page_set_memattr(m, memattr);
2391                 pindex++;
2392         }
2393         return (m_ret);
2394 }
2395
2396 /*
2397  * Allocate a physical page that is not intended to be inserted into a VM
2398  * object.  If the "freelist" parameter is not equal to VM_NFREELIST, then only
2399  * pages from the specified vm_phys freelist will be returned.
2400  */
2401 static __always_inline vm_page_t
2402 _vm_page_alloc_noobj_domain(int domain, const int freelist, int req)
2403 {
2404         struct vm_domain *vmd;
2405         vm_page_t m;
2406         int flags;
2407
2408         KASSERT((req & (VM_ALLOC_SBUSY | VM_ALLOC_IGN_SBUSY |
2409             VM_ALLOC_NOOBJ)) == 0,
2410             ("%s: invalid req %#x", __func__, req));
2411
2412         flags = (req & VM_ALLOC_NODUMP) != 0 ? PG_NODUMP : 0;
2413         vmd = VM_DOMAIN(domain);
2414 again:
2415         if (freelist == VM_NFREELIST &&
2416             vmd->vmd_pgcache[VM_FREEPOOL_DIRECT].zone != NULL) {
2417                 m = uma_zalloc(vmd->vmd_pgcache[VM_FREEPOOL_DIRECT].zone,
2418                     M_NOWAIT | M_NOVM);
2419                 if (m != NULL) {
2420                         flags |= PG_PCPU_CACHE;
2421                         goto found;
2422                 }
2423         }
2424
2425         if (vm_domain_allocate(vmd, req, 1)) {
2426                 vm_domain_free_lock(vmd);
2427                 if (freelist == VM_NFREELIST)
2428                         m = vm_phys_alloc_pages(domain, VM_FREEPOOL_DIRECT, 0);
2429                 else
2430                         m = vm_phys_alloc_freelist_pages(domain, freelist,
2431                             VM_FREEPOOL_DIRECT, 0);
2432                 vm_domain_free_unlock(vmd);
2433                 if (m == NULL)
2434                         vm_domain_freecnt_inc(vmd, 1);
2435         }
2436         if (m == NULL) {
2437                 if (vm_domain_alloc_fail(vmd, NULL, req))
2438                         goto again;
2439                 return (NULL);
2440         }
2441
2442 found:
2443         vm_page_dequeue(m);
2444         vm_page_alloc_check(m);
2445
2446         /* Consumers should not rely on a useful default pindex value. */
2447         m->pindex = 0xdeadc0dedeadc0de;
2448         m->flags = (m->flags & PG_ZERO) | flags;
2449         m->a.flags = 0;
2450         m->oflags = VPO_UNMANAGED;
2451         m->busy_lock = VPB_UNBUSIED;
2452         if ((req & VM_ALLOC_WIRED) != 0) {
2453                 vm_wire_add(1);
2454                 m->ref_count = 1;
2455         }
2456
2457         if ((req & VM_ALLOC_ZERO) != 0 && (m->flags & PG_ZERO) == 0)
2458                 pmap_zero_page(m);
2459
2460         return (m);
2461 }
2462
2463 vm_page_t
2464 vm_page_alloc_freelist(int freelist, int req)
2465 {
2466         struct vm_domainset_iter di;
2467         vm_page_t m;
2468         int domain;
2469
2470         vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2471         do {
2472                 m = vm_page_alloc_freelist_domain(domain, freelist, req);
2473                 if (m != NULL)
2474                         break;
2475         } while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2476
2477         return (m);
2478 }
2479
2480 vm_page_t
2481 vm_page_alloc_freelist_domain(int domain, int freelist, int req)
2482 {
2483         KASSERT(freelist >= 0 && freelist < VM_NFREELIST,
2484             ("%s: invalid freelist %d", __func__, freelist));
2485
2486         return (_vm_page_alloc_noobj_domain(domain, freelist, req));
2487 }
2488
2489 vm_page_t
2490 vm_page_alloc_noobj(int req)
2491 {
2492         struct vm_domainset_iter di;
2493         vm_page_t m;
2494         int domain;
2495
2496         vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2497         do {
2498                 m = vm_page_alloc_noobj_domain(domain, req);
2499                 if (m != NULL)
2500                         break;
2501         } while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2502
2503         return (m);
2504 }
2505
2506 vm_page_t
2507 vm_page_alloc_noobj_domain(int domain, int req)
2508 {
2509         return (_vm_page_alloc_noobj_domain(domain, VM_NFREELIST, req));
2510 }
2511
2512 vm_page_t
2513 vm_page_alloc_noobj_contig(int req, u_long npages, vm_paddr_t low,
2514     vm_paddr_t high, u_long alignment, vm_paddr_t boundary,
2515     vm_memattr_t memattr)
2516 {
2517         struct vm_domainset_iter di;
2518         vm_page_t m;
2519         int domain;
2520
2521         vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2522         do {
2523                 m = vm_page_alloc_noobj_contig_domain(domain, req, npages, low,
2524                     high, alignment, boundary, memattr);
2525                 if (m != NULL)
2526                         break;
2527         } while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2528
2529         return (m);
2530 }
2531
2532 vm_page_t
2533 vm_page_alloc_noobj_contig_domain(int domain, int req, u_long npages,
2534     vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary,
2535     vm_memattr_t memattr)
2536 {
2537         vm_page_t m;
2538         u_long i;
2539
2540         KASSERT((req & (VM_ALLOC_SBUSY | VM_ALLOC_IGN_SBUSY |
2541             VM_ALLOC_NOOBJ)) == 0,
2542             ("%s: invalid req %#x", __func__, req));
2543
2544         m = vm_page_alloc_contig_domain(NULL, 0, domain, req | VM_ALLOC_NOOBJ,
2545             npages, low, high, alignment, boundary, memattr);
2546         if (m != NULL && (req & VM_ALLOC_ZERO) != 0) {
2547                 for (i = 0; i < npages; i++) {
2548                         if ((m[i].flags & PG_ZERO) == 0)
2549                                 pmap_zero_page(&m[i]);
2550                 }
2551         }
2552         return (m);
2553 }
2554
2555 /*
2556  * Check a page that has been freshly dequeued from a freelist.
2557  */
2558 static void
2559 vm_page_alloc_check(vm_page_t m)
2560 {
2561
2562         KASSERT(m->object == NULL, ("page %p has object", m));
2563         KASSERT(m->a.queue == PQ_NONE &&
2564             (m->a.flags & PGA_QUEUE_STATE_MASK) == 0,
2565             ("page %p has unexpected queue %d, flags %#x",
2566             m, m->a.queue, (m->a.flags & PGA_QUEUE_STATE_MASK)));
2567         KASSERT(m->ref_count == 0, ("page %p has references", m));
2568         KASSERT(vm_page_busy_freed(m), ("page %p is not freed", m));
2569         KASSERT(m->dirty == 0, ("page %p is dirty", m));
2570         KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
2571             ("page %p has unexpected memattr %d",
2572             m, pmap_page_get_memattr(m)));
2573         KASSERT(m->valid == 0, ("free page %p is valid", m));
2574         pmap_vm_page_alloc_check(m);
2575 }
2576
2577 static int
2578 vm_page_zone_import(void *arg, void **store, int cnt, int domain, int flags)
2579 {
2580         struct vm_domain *vmd;
2581         struct vm_pgcache *pgcache;
2582         int i;
2583
2584         pgcache = arg;
2585         vmd = VM_DOMAIN(pgcache->domain);
2586
2587         /*
2588          * The page daemon should avoid creating extra memory pressure since its
2589          * main purpose is to replenish the store of free pages.
2590          */
2591         if (vmd->vmd_severeset || curproc == pageproc ||
2592             !_vm_domain_allocate(vmd, VM_ALLOC_NORMAL, cnt))
2593                 return (0);
2594         domain = vmd->vmd_domain;
2595         vm_domain_free_lock(vmd);
2596         i = vm_phys_alloc_npages(domain, pgcache->pool, cnt,
2597             (vm_page_t *)store);
2598         vm_domain_free_unlock(vmd);
2599         if (cnt != i)
2600                 vm_domain_freecnt_inc(vmd, cnt - i);
2601
2602         return (i);
2603 }
2604
2605 static void
2606 vm_page_zone_release(void *arg, void **store, int cnt)
2607 {
2608         struct vm_domain *vmd;
2609         struct vm_pgcache *pgcache;
2610         vm_page_t m;
2611         int i;
2612
2613         pgcache = arg;
2614         vmd = VM_DOMAIN(pgcache->domain);
2615         vm_domain_free_lock(vmd);
2616         for (i = 0; i < cnt; i++) {
2617                 m = (vm_page_t)store[i];
2618                 vm_phys_free_pages(m, 0);
2619         }
2620         vm_domain_free_unlock(vmd);
2621         vm_domain_freecnt_inc(vmd, cnt);
2622 }
2623
2624 #define VPSC_ANY        0       /* No restrictions. */
2625 #define VPSC_NORESERV   1       /* Skip reservations; implies VPSC_NOSUPER. */
2626 #define VPSC_NOSUPER    2       /* Skip superpages. */
2627
2628 /*
2629  *      vm_page_scan_contig:
2630  *
2631  *      Scan vm_page_array[] between the specified entries "m_start" and
2632  *      "m_end" for a run of contiguous physical pages that satisfy the
2633  *      specified conditions, and return the lowest page in the run.  The
2634  *      specified "alignment" determines the alignment of the lowest physical
2635  *      page in the run.  If the specified "boundary" is non-zero, then the
2636  *      run of physical pages cannot span a physical address that is a
2637  *      multiple of "boundary".
2638  *
2639  *      "m_end" is never dereferenced, so it need not point to a vm_page
2640  *      structure within vm_page_array[].
2641  *
2642  *      "npages" must be greater than zero.  "m_start" and "m_end" must not
2643  *      span a hole (or discontiguity) in the physical address space.  Both
2644  *      "alignment" and "boundary" must be a power of two.
2645  */
2646 vm_page_t
2647 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
2648     u_long alignment, vm_paddr_t boundary, int options)
2649 {
2650         vm_object_t object;
2651         vm_paddr_t pa;
2652         vm_page_t m, m_run;
2653 #if VM_NRESERVLEVEL > 0
2654         int level;
2655 #endif
2656         int m_inc, order, run_ext, run_len;
2657
2658         KASSERT(npages > 0, ("npages is 0"));
2659         KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2660         KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2661         m_run = NULL;
2662         run_len = 0;
2663         for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2664                 KASSERT((m->flags & PG_MARKER) == 0,
2665                     ("page %p is PG_MARKER", m));
2666                 KASSERT((m->flags & PG_FICTITIOUS) == 0 || m->ref_count >= 1,
2667                     ("fictitious page %p has invalid ref count", m));
2668
2669                 /*
2670                  * If the current page would be the start of a run, check its
2671                  * physical address against the end, alignment, and boundary
2672                  * conditions.  If it doesn't satisfy these conditions, either
2673                  * terminate the scan or advance to the next page that
2674                  * satisfies the failed condition.
2675                  */
2676                 if (run_len == 0) {
2677                         KASSERT(m_run == NULL, ("m_run != NULL"));
2678                         if (m + npages > m_end)
2679                                 break;
2680                         pa = VM_PAGE_TO_PHYS(m);
2681                         if ((pa & (alignment - 1)) != 0) {
2682                                 m_inc = atop(roundup2(pa, alignment) - pa);
2683                                 continue;
2684                         }
2685                         if (rounddown2(pa ^ (pa + ptoa(npages) - 1),
2686                             boundary) != 0) {
2687                                 m_inc = atop(roundup2(pa, boundary) - pa);
2688                                 continue;
2689                         }
2690                 } else
2691                         KASSERT(m_run != NULL, ("m_run == NULL"));
2692
2693 retry:
2694                 m_inc = 1;
2695                 if (vm_page_wired(m))
2696                         run_ext = 0;
2697 #if VM_NRESERVLEVEL > 0
2698                 else if ((level = vm_reserv_level(m)) >= 0 &&
2699                     (options & VPSC_NORESERV) != 0) {
2700                         run_ext = 0;
2701                         /* Advance to the end of the reservation. */
2702                         pa = VM_PAGE_TO_PHYS(m);
2703                         m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2704                             pa);
2705                 }
2706 #endif
2707                 else if ((object = atomic_load_ptr(&m->object)) != NULL) {
2708                         /*
2709                          * The page is considered eligible for relocation if
2710                          * and only if it could be laundered or reclaimed by
2711                          * the page daemon.
2712                          */
2713                         VM_OBJECT_RLOCK(object);
2714                         if (object != m->object) {
2715                                 VM_OBJECT_RUNLOCK(object);
2716                                 goto retry;
2717                         }
2718                         /* Don't care: PG_NODUMP, PG_ZERO. */
2719                         if (object->type != OBJT_DEFAULT &&
2720                             (object->flags & OBJ_SWAP) == 0 &&
2721                             object->type != OBJT_VNODE) {
2722                                 run_ext = 0;
2723 #if VM_NRESERVLEVEL > 0
2724                         } else if ((options & VPSC_NOSUPER) != 0 &&
2725                             (level = vm_reserv_level_iffullpop(m)) >= 0) {
2726                                 run_ext = 0;
2727                                 /* Advance to the end of the superpage. */
2728                                 pa = VM_PAGE_TO_PHYS(m);
2729                                 m_inc = atop(roundup2(pa + 1,
2730                                     vm_reserv_size(level)) - pa);
2731 #endif
2732                         } else if (object->memattr == VM_MEMATTR_DEFAULT &&
2733                             vm_page_queue(m) != PQ_NONE && !vm_page_busied(m)) {
2734                                 /*
2735                                  * The page is allocated but eligible for
2736                                  * relocation.  Extend the current run by one
2737                                  * page.
2738                                  */
2739                                 KASSERT(pmap_page_get_memattr(m) ==
2740                                     VM_MEMATTR_DEFAULT,
2741                                     ("page %p has an unexpected memattr", m));
2742                                 KASSERT((m->oflags & (VPO_SWAPINPROG |
2743                                     VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2744                                     ("page %p has unexpected oflags", m));
2745                                 /* Don't care: PGA_NOSYNC. */
2746                                 run_ext = 1;
2747                         } else
2748                                 run_ext = 0;
2749                         VM_OBJECT_RUNLOCK(object);
2750 #if VM_NRESERVLEVEL > 0
2751                 } else if (level >= 0) {
2752                         /*
2753                          * The page is reserved but not yet allocated.  In
2754                          * other words, it is still free.  Extend the current
2755                          * run by one page.
2756                          */
2757                         run_ext = 1;
2758 #endif
2759                 } else if ((order = m->order) < VM_NFREEORDER) {
2760                         /*
2761                          * The page is enqueued in the physical memory
2762                          * allocator's free page queues.  Moreover, it is the
2763                          * first page in a power-of-two-sized run of
2764                          * contiguous free pages.  Add these pages to the end
2765                          * of the current run, and jump ahead.
2766                          */
2767                         run_ext = 1 << order;
2768                         m_inc = 1 << order;
2769                 } else {
2770                         /*
2771                          * Skip the page for one of the following reasons: (1)
2772                          * It is enqueued in the physical memory allocator's
2773                          * free page queues.  However, it is not the first
2774                          * page in a run of contiguous free pages.  (This case
2775                          * rarely occurs because the scan is performed in
2776                          * ascending order.) (2) It is not reserved, and it is
2777                          * transitioning from free to allocated.  (Conversely,
2778                          * the transition from allocated to free for managed
2779                          * pages is blocked by the page busy lock.) (3) It is
2780                          * allocated but not contained by an object and not
2781                          * wired, e.g., allocated by Xen's balloon driver.
2782                          */
2783                         run_ext = 0;
2784                 }
2785
2786                 /*
2787                  * Extend or reset the current run of pages.
2788                  */
2789                 if (run_ext > 0) {
2790                         if (run_len == 0)
2791                                 m_run = m;
2792                         run_len += run_ext;
2793                 } else {
2794                         if (run_len > 0) {
2795                                 m_run = NULL;
2796                                 run_len = 0;
2797                         }
2798                 }
2799         }
2800         if (run_len >= npages)
2801                 return (m_run);
2802         return (NULL);
2803 }
2804
2805 /*
2806  *      vm_page_reclaim_run:
2807  *
2808  *      Try to relocate each of the allocated virtual pages within the
2809  *      specified run of physical pages to a new physical address.  Free the
2810  *      physical pages underlying the relocated virtual pages.  A virtual page
2811  *      is relocatable if and only if it could be laundered or reclaimed by
2812  *      the page daemon.  Whenever possible, a virtual page is relocated to a
2813  *      physical address above "high".
2814  *
2815  *      Returns 0 if every physical page within the run was already free or
2816  *      just freed by a successful relocation.  Otherwise, returns a non-zero
2817  *      value indicating why the last attempt to relocate a virtual page was
2818  *      unsuccessful.
2819  *
2820  *      "req_class" must be an allocation class.
2821  */
2822 static int
2823 vm_page_reclaim_run(int req_class, int domain, u_long npages, vm_page_t m_run,
2824     vm_paddr_t high)
2825 {
2826         struct vm_domain *vmd;
2827         struct spglist free;
2828         vm_object_t object;
2829         vm_paddr_t pa;
2830         vm_page_t m, m_end, m_new;
2831         int error, order, req;
2832
2833         KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
2834             ("req_class is not an allocation class"));
2835         SLIST_INIT(&free);
2836         error = 0;
2837         m = m_run;
2838         m_end = m_run + npages;
2839         for (; error == 0 && m < m_end; m++) {
2840                 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2841                     ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2842
2843                 /*
2844                  * Racily check for wirings.  Races are handled once the object
2845                  * lock is held and the page is unmapped.
2846                  */
2847                 if (vm_page_wired(m))
2848                         error = EBUSY;
2849                 else if ((object = atomic_load_ptr(&m->object)) != NULL) {
2850                         /*
2851                          * The page is relocated if and only if it could be
2852                          * laundered or reclaimed by the page daemon.
2853                          */
2854                         VM_OBJECT_WLOCK(object);
2855                         /* Don't care: PG_NODUMP, PG_ZERO. */
2856                         if (m->object != object ||
2857                             (object->type != OBJT_DEFAULT &&
2858                             (object->flags & OBJ_SWAP) == 0 &&
2859                             object->type != OBJT_VNODE))
2860                                 error = EINVAL;
2861                         else if (object->memattr != VM_MEMATTR_DEFAULT)
2862                                 error = EINVAL;
2863                         else if (vm_page_queue(m) != PQ_NONE &&
2864                             vm_page_tryxbusy(m) != 0) {
2865                                 if (vm_page_wired(m)) {
2866                                         vm_page_xunbusy(m);
2867                                         error = EBUSY;
2868                                         goto unlock;
2869                                 }
2870                                 KASSERT(pmap_page_get_memattr(m) ==
2871                                     VM_MEMATTR_DEFAULT,
2872                                     ("page %p has an unexpected memattr", m));
2873                                 KASSERT(m->oflags == 0,
2874                                     ("page %p has unexpected oflags", m));
2875                                 /* Don't care: PGA_NOSYNC. */
2876                                 if (!vm_page_none_valid(m)) {
2877                                         /*
2878                                          * First, try to allocate a new page
2879                                          * that is above "high".  Failing
2880                                          * that, try to allocate a new page
2881                                          * that is below "m_run".  Allocate
2882                                          * the new page between the end of
2883                                          * "m_run" and "high" only as a last
2884                                          * resort.
2885                                          */
2886                                         req = req_class | VM_ALLOC_NOOBJ;
2887                                         if ((m->flags & PG_NODUMP) != 0)
2888                                                 req |= VM_ALLOC_NODUMP;
2889                                         if (trunc_page(high) !=
2890                                             ~(vm_paddr_t)PAGE_MASK) {
2891                                                 m_new = vm_page_alloc_contig(
2892                                                     NULL, 0, req, 1,
2893                                                     round_page(high),
2894                                                     ~(vm_paddr_t)0,
2895                                                     PAGE_SIZE, 0,
2896                                                     VM_MEMATTR_DEFAULT);
2897                                         } else
2898                                                 m_new = NULL;
2899                                         if (m_new == NULL) {
2900                                                 pa = VM_PAGE_TO_PHYS(m_run);
2901                                                 m_new = vm_page_alloc_contig(
2902                                                     NULL, 0, req, 1,
2903                                                     0, pa - 1, PAGE_SIZE, 0,
2904                                                     VM_MEMATTR_DEFAULT);
2905                                         }
2906                                         if (m_new == NULL) {
2907                                                 pa += ptoa(npages);
2908                                                 m_new = vm_page_alloc_contig(
2909                                                     NULL, 0, req, 1,
2910                                                     pa, high, PAGE_SIZE, 0,
2911                                                     VM_MEMATTR_DEFAULT);
2912                                         }
2913                                         if (m_new == NULL) {
2914                                                 vm_page_xunbusy(m);
2915                                                 error = ENOMEM;
2916                                                 goto unlock;
2917                                         }
2918
2919                                         /*
2920                                          * Unmap the page and check for new
2921                                          * wirings that may have been acquired
2922                                          * through a pmap lookup.
2923                                          */
2924                                         if (object->ref_count != 0 &&
2925                                             !vm_page_try_remove_all(m)) {
2926                                                 vm_page_xunbusy(m);
2927                                                 vm_page_free(m_new);
2928                                                 error = EBUSY;
2929                                                 goto unlock;
2930                                         }
2931
2932                                         /*
2933                                          * Replace "m" with the new page.  For
2934                                          * vm_page_replace(), "m" must be busy
2935                                          * and dequeued.  Finally, change "m"
2936                                          * as if vm_page_free() was called.
2937                                          */
2938                                         m_new->a.flags = m->a.flags &
2939                                             ~PGA_QUEUE_STATE_MASK;
2940                                         KASSERT(m_new->oflags == VPO_UNMANAGED,
2941                                             ("page %p is managed", m_new));
2942                                         m_new->oflags = 0;
2943                                         pmap_copy_page(m, m_new);
2944                                         m_new->valid = m->valid;
2945                                         m_new->dirty = m->dirty;
2946                                         m->flags &= ~PG_ZERO;
2947                                         vm_page_dequeue(m);
2948                                         if (vm_page_replace_hold(m_new, object,
2949                                             m->pindex, m) &&
2950                                             vm_page_free_prep(m))
2951                                                 SLIST_INSERT_HEAD(&free, m,
2952                                                     plinks.s.ss);
2953
2954                                         /*
2955                                          * The new page must be deactivated
2956                                          * before the object is unlocked.
2957                                          */
2958                                         vm_page_deactivate(m_new);
2959                                 } else {
2960                                         m->flags &= ~PG_ZERO;
2961                                         vm_page_dequeue(m);
2962                                         if (vm_page_free_prep(m))
2963                                                 SLIST_INSERT_HEAD(&free, m,
2964                                                     plinks.s.ss);
2965                                         KASSERT(m->dirty == 0,
2966                                             ("page %p is dirty", m));
2967                                 }
2968                         } else
2969                                 error = EBUSY;
2970 unlock:
2971                         VM_OBJECT_WUNLOCK(object);
2972                 } else {
2973                         MPASS(vm_page_domain(m) == domain);
2974                         vmd = VM_DOMAIN(domain);
2975                         vm_domain_free_lock(vmd);
2976                         order = m->order;
2977                         if (order < VM_NFREEORDER) {
2978                                 /*
2979                                  * The page is enqueued in the physical memory
2980                                  * allocator's free page queues.  Moreover, it
2981                                  * is the first page in a power-of-two-sized
2982                                  * run of contiguous free pages.  Jump ahead
2983                                  * to the last page within that run, and
2984                                  * continue from there.
2985                                  */
2986                                 m += (1 << order) - 1;
2987                         }
2988 #if VM_NRESERVLEVEL > 0
2989                         else if (vm_reserv_is_page_free(m))
2990                                 order = 0;
2991 #endif
2992                         vm_domain_free_unlock(vmd);
2993                         if (order == VM_NFREEORDER)
2994                                 error = EINVAL;
2995                 }
2996         }
2997         if ((m = SLIST_FIRST(&free)) != NULL) {
2998                 int cnt;
2999
3000                 vmd = VM_DOMAIN(domain);
3001                 cnt = 0;
3002                 vm_domain_free_lock(vmd);
3003                 do {
3004                         MPASS(vm_page_domain(m) == domain);
3005                         SLIST_REMOVE_HEAD(&free, plinks.s.ss);
3006                         vm_phys_free_pages(m, 0);
3007                         cnt++;
3008                 } while ((m = SLIST_FIRST(&free)) != NULL);
3009                 vm_domain_free_unlock(vmd);
3010                 vm_domain_freecnt_inc(vmd, cnt);
3011         }
3012         return (error);
3013 }
3014
3015 #define NRUNS   16
3016
3017 CTASSERT(powerof2(NRUNS));
3018
3019 #define RUN_INDEX(count)        ((count) & (NRUNS - 1))
3020
3021 #define MIN_RECLAIM     8
3022
3023 /*
3024  *      vm_page_reclaim_contig:
3025  *
3026  *      Reclaim allocated, contiguous physical memory satisfying the specified
3027  *      conditions by relocating the virtual pages using that physical memory.
3028  *      Returns true if reclamation is successful and false otherwise.  Since
3029  *      relocation requires the allocation of physical pages, reclamation may
3030  *      fail due to a shortage of free pages.  When reclamation fails, callers
3031  *      are expected to perform vm_wait() before retrying a failed allocation
3032  *      operation, e.g., vm_page_alloc_contig().
3033  *
3034  *      The caller must always specify an allocation class through "req".
3035  *
3036  *      allocation classes:
3037  *      VM_ALLOC_NORMAL         normal process request
3038  *      VM_ALLOC_SYSTEM         system *really* needs a page
3039  *      VM_ALLOC_INTERRUPT      interrupt time request
3040  *
3041  *      The optional allocation flags are ignored.
3042  *
3043  *      "npages" must be greater than zero.  Both "alignment" and "boundary"
3044  *      must be a power of two.
3045  */
3046 bool
3047 vm_page_reclaim_contig_domain(int domain, int req, u_long npages,
3048     vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary)
3049 {
3050         struct vm_domain *vmd;
3051         vm_paddr_t curr_low;
3052         vm_page_t m_run, m_runs[NRUNS];
3053         u_long count, minalign, reclaimed;
3054         int error, i, options, req_class;
3055
3056         KASSERT(npages > 0, ("npages is 0"));
3057         KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
3058         KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
3059
3060         /*
3061          * The caller will attempt an allocation after some runs have been
3062          * reclaimed and added to the vm_phys buddy lists.  Due to limitations
3063          * of vm_phys_alloc_contig(), round up the requested length to the next
3064          * power of two or maximum chunk size, and ensure that each run is
3065          * suitably aligned.
3066          */
3067         minalign = 1ul << imin(flsl(npages - 1), VM_NFREEORDER - 1);
3068         npages = roundup2(npages, minalign);
3069         if (alignment < ptoa(minalign))
3070                 alignment = ptoa(minalign);
3071
3072         /*
3073          * The page daemon is allowed to dig deeper into the free page list.
3074          */
3075         req_class = req & VM_ALLOC_CLASS_MASK;
3076         if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
3077                 req_class = VM_ALLOC_SYSTEM;
3078
3079         /*
3080          * Return if the number of free pages cannot satisfy the requested
3081          * allocation.
3082          */
3083         vmd = VM_DOMAIN(domain);
3084         count = vmd->vmd_free_count;
3085         if (count < npages + vmd->vmd_free_reserved || (count < npages +
3086             vmd->vmd_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
3087             (count < npages && req_class == VM_ALLOC_INTERRUPT))
3088                 return (false);
3089
3090         /*
3091          * Scan up to three times, relaxing the restrictions ("options") on
3092          * the reclamation of reservations and superpages each time.
3093          */
3094         for (options = VPSC_NORESERV;;) {
3095                 /*
3096                  * Find the highest runs that satisfy the given constraints
3097                  * and restrictions, and record them in "m_runs".
3098                  */
3099                 curr_low = low;
3100                 count = 0;
3101                 for (;;) {
3102                         m_run = vm_phys_scan_contig(domain, npages, curr_low,
3103                             high, alignment, boundary, options);
3104                         if (m_run == NULL)
3105                                 break;
3106                         curr_low = VM_PAGE_TO_PHYS(m_run) + ptoa(npages);
3107                         m_runs[RUN_INDEX(count)] = m_run;
3108                         count++;
3109                 }
3110
3111                 /*
3112                  * Reclaim the highest runs in LIFO (descending) order until
3113                  * the number of reclaimed pages, "reclaimed", is at least
3114                  * MIN_RECLAIM.  Reset "reclaimed" each time because each
3115                  * reclamation is idempotent, and runs will (likely) recur
3116                  * from one scan to the next as restrictions are relaxed.
3117                  */
3118                 reclaimed = 0;
3119                 for (i = 0; count > 0 && i < NRUNS; i++) {
3120                         count--;
3121                         m_run = m_runs[RUN_INDEX(count)];
3122                         error = vm_page_reclaim_run(req_class, domain, npages,
3123                             m_run, high);
3124                         if (error == 0) {
3125                                 reclaimed += npages;
3126                                 if (reclaimed >= MIN_RECLAIM)
3127                                         return (true);
3128                         }
3129                 }
3130
3131                 /*
3132                  * Either relax the restrictions on the next scan or return if
3133                  * the last scan had no restrictions.
3134                  */
3135                 if (options == VPSC_NORESERV)
3136                         options = VPSC_NOSUPER;
3137                 else if (options == VPSC_NOSUPER)
3138                         options = VPSC_ANY;
3139                 else if (options == VPSC_ANY)
3140                         return (reclaimed != 0);
3141         }
3142 }
3143
3144 bool
3145 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
3146     u_long alignment, vm_paddr_t boundary)
3147 {
3148         struct vm_domainset_iter di;
3149         int domain;
3150         bool ret;
3151
3152         vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
3153         do {
3154                 ret = vm_page_reclaim_contig_domain(domain, req, npages, low,
3155                     high, alignment, boundary);
3156                 if (ret)
3157                         break;
3158         } while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
3159
3160         return (ret);
3161 }
3162
3163 /*
3164  * Set the domain in the appropriate page level domainset.
3165  */
3166 void
3167 vm_domain_set(struct vm_domain *vmd)
3168 {
3169
3170         mtx_lock(&vm_domainset_lock);
3171         if (!vmd->vmd_minset && vm_paging_min(vmd)) {
3172                 vmd->vmd_minset = 1;
3173                 DOMAINSET_SET(vmd->vmd_domain, &vm_min_domains);
3174         }
3175         if (!vmd->vmd_severeset && vm_paging_severe(vmd)) {
3176                 vmd->vmd_severeset = 1;
3177                 DOMAINSET_SET(vmd->vmd_domain, &vm_severe_domains);
3178         }
3179         mtx_unlock(&vm_domainset_lock);
3180 }
3181
3182 /*
3183  * Clear the domain from the appropriate page level domainset.
3184  */
3185 void
3186 vm_domain_clear(struct vm_domain *vmd)
3187 {
3188
3189         mtx_lock(&vm_domainset_lock);
3190         if (vmd->vmd_minset && !vm_paging_min(vmd)) {
3191                 vmd->vmd_minset = 0;
3192                 DOMAINSET_CLR(vmd->vmd_domain, &vm_min_domains);
3193                 if (vm_min_waiters != 0) {
3194                         vm_min_waiters = 0;
3195                         wakeup(&vm_min_domains);
3196                 }
3197         }
3198         if (vmd->vmd_severeset && !vm_paging_severe(vmd)) {
3199                 vmd->vmd_severeset = 0;
3200                 DOMAINSET_CLR(vmd->vmd_domain, &vm_severe_domains);
3201                 if (vm_severe_waiters != 0) {
3202                         vm_severe_waiters = 0;
3203                         wakeup(&vm_severe_domains);
3204                 }
3205         }
3206
3207         /*
3208          * If pageout daemon needs pages, then tell it that there are
3209          * some free.
3210          */
3211         if (vmd->vmd_pageout_pages_needed &&
3212             vmd->vmd_free_count >= vmd->vmd_pageout_free_min) {
3213                 wakeup(&vmd->vmd_pageout_pages_needed);
3214                 vmd->vmd_pageout_pages_needed = 0;
3215         }
3216
3217         /* See comments in vm_wait_doms(). */
3218         if (vm_pageproc_waiters) {
3219                 vm_pageproc_waiters = 0;
3220                 wakeup(&vm_pageproc_waiters);
3221         }
3222         mtx_unlock(&vm_domainset_lock);
3223 }
3224
3225 /*
3226  * Wait for free pages to exceed the min threshold globally.
3227  */
3228 void
3229 vm_wait_min(void)
3230 {
3231
3232         mtx_lock(&vm_domainset_lock);
3233         while (vm_page_count_min()) {
3234                 vm_min_waiters++;
3235                 msleep(&vm_min_domains, &vm_domainset_lock, PVM, "vmwait", 0);
3236         }
3237         mtx_unlock(&vm_domainset_lock);
3238 }
3239
3240 /*
3241  * Wait for free pages to exceed the severe threshold globally.
3242  */
3243 void
3244 vm_wait_severe(void)
3245 {
3246
3247         mtx_lock(&vm_domainset_lock);
3248         while (vm_page_count_severe()) {
3249                 vm_severe_waiters++;
3250                 msleep(&vm_severe_domains, &vm_domainset_lock, PVM,
3251                     "vmwait", 0);
3252         }
3253         mtx_unlock(&vm_domainset_lock);
3254 }
3255
3256 u_int
3257 vm_wait_count(void)
3258 {
3259
3260         return (vm_severe_waiters + vm_min_waiters + vm_pageproc_waiters);
3261 }
3262
3263 int
3264 vm_wait_doms(const domainset_t *wdoms, int mflags)
3265 {
3266         int error;
3267
3268         error = 0;
3269
3270         /*
3271          * We use racey wakeup synchronization to avoid expensive global
3272          * locking for the pageproc when sleeping with a non-specific vm_wait.
3273          * To handle this, we only sleep for one tick in this instance.  It
3274          * is expected that most allocations for the pageproc will come from
3275          * kmem or vm_page_grab* which will use the more specific and
3276          * race-free vm_wait_domain().
3277          */
3278         if (curproc == pageproc) {
3279                 mtx_lock(&vm_domainset_lock);
3280                 vm_pageproc_waiters++;
3281                 error = msleep(&vm_pageproc_waiters, &vm_domainset_lock,
3282                     PVM | PDROP | mflags, "pageprocwait", 1);
3283         } else {
3284                 /*
3285                  * XXX Ideally we would wait only until the allocation could
3286                  * be satisfied.  This condition can cause new allocators to
3287                  * consume all freed pages while old allocators wait.
3288                  */
3289                 mtx_lock(&vm_domainset_lock);
3290                 if (vm_page_count_min_set(wdoms)) {
3291                         vm_min_waiters++;
3292                         error = msleep(&vm_min_domains, &vm_domainset_lock,
3293                             PVM | PDROP | mflags, "vmwait", 0);
3294                 } else
3295                         mtx_unlock(&vm_domainset_lock);
3296         }
3297         return (error);
3298 }
3299
3300 /*
3301  *      vm_wait_domain:
3302  *
3303  *      Sleep until free pages are available for allocation.
3304  *      - Called in various places after failed memory allocations.
3305  */
3306 void
3307 vm_wait_domain(int domain)
3308 {
3309         struct vm_domain *vmd;
3310         domainset_t wdom;
3311
3312         vmd = VM_DOMAIN(domain);
3313         vm_domain_free_assert_unlocked(vmd);
3314
3315         if (curproc == pageproc) {
3316                 mtx_lock(&vm_domainset_lock);
3317                 if (vmd->vmd_free_count < vmd->vmd_pageout_free_min) {
3318                         vmd->vmd_pageout_pages_needed = 1;
3319                         msleep(&vmd->vmd_pageout_pages_needed,
3320                             &vm_domainset_lock, PDROP | PSWP, "VMWait", 0);
3321                 } else
3322                         mtx_unlock(&vm_domainset_lock);
3323         } else {
3324                 if (pageproc == NULL)
3325                         panic("vm_wait in early boot");
3326                 DOMAINSET_ZERO(&wdom);
3327                 DOMAINSET_SET(vmd->vmd_domain, &wdom);
3328                 vm_wait_doms(&wdom, 0);
3329         }
3330 }
3331
3332 static int
3333 vm_wait_flags(vm_object_t obj, int mflags)
3334 {
3335         struct domainset *d;
3336
3337         d = NULL;
3338
3339         /*
3340          * Carefully fetch pointers only once: the struct domainset
3341          * itself is ummutable but the pointer might change.
3342          */
3343         if (obj != NULL)
3344                 d = obj->domain.dr_policy;
3345         if (d == NULL)
3346                 d = curthread->td_domain.dr_policy;
3347
3348         return (vm_wait_doms(&d->ds_mask, mflags));
3349 }
3350
3351 /*
3352  *      vm_wait:
3353  *
3354  *      Sleep until free pages are available for allocation in the
3355  *      affinity domains of the obj.  If obj is NULL, the domain set
3356  *      for the calling thread is used.
3357  *      Called in various places after failed memory allocations.
3358  */
3359 void
3360 vm_wait(vm_object_t obj)
3361 {
3362         (void)vm_wait_flags(obj, 0);
3363 }
3364
3365 int
3366 vm_wait_intr(vm_object_t obj)
3367 {
3368         return (vm_wait_flags(obj, PCATCH));
3369 }
3370
3371 /*
3372  *      vm_domain_alloc_fail:
3373  *
3374  *      Called when a page allocation function fails.  Informs the
3375  *      pagedaemon and performs the requested wait.  Requires the
3376  *      domain_free and object lock on entry.  Returns with the
3377  *      object lock held and free lock released.  Returns an error when
3378  *      retry is necessary.
3379  *
3380  */
3381 static int
3382 vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object, int req)
3383 {
3384
3385         vm_domain_free_assert_unlocked(vmd);
3386
3387         atomic_add_int(&vmd->vmd_pageout_deficit,
3388             max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
3389         if (req & (VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL)) {
3390                 if (object != NULL) 
3391                         VM_OBJECT_WUNLOCK(object);
3392                 vm_wait_domain(vmd->vmd_domain);
3393                 if (object != NULL) 
3394                         VM_OBJECT_WLOCK(object);
3395                 if (req & VM_ALLOC_WAITOK)
3396                         return (EAGAIN);
3397         }
3398
3399         return (0);
3400 }
3401
3402 /*
3403  *      vm_waitpfault:
3404  *
3405  *      Sleep until free pages are available for allocation.
3406  *      - Called only in vm_fault so that processes page faulting
3407  *        can be easily tracked.
3408  *      - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
3409  *        processes will be able to grab memory first.  Do not change
3410  *        this balance without careful testing first.
3411  */
3412 void
3413 vm_waitpfault(struct domainset *dset, int timo)
3414 {
3415
3416         /*
3417          * XXX Ideally we would wait only until the allocation could
3418          * be satisfied.  This condition can cause new allocators to
3419          * consume all freed pages while old allocators wait.
3420          */
3421         mtx_lock(&vm_domainset_lock);
3422         if (vm_page_count_min_set(&dset->ds_mask)) {
3423                 vm_min_waiters++;
3424                 msleep(&vm_min_domains, &vm_domainset_lock, PUSER | PDROP,
3425                     "pfault", timo);
3426         } else
3427                 mtx_unlock(&vm_domainset_lock);
3428 }
3429
3430 static struct vm_pagequeue *
3431 _vm_page_pagequeue(vm_page_t m, uint8_t queue)
3432 {
3433
3434         return (&vm_pagequeue_domain(m)->vmd_pagequeues[queue]);
3435 }
3436
3437 #ifdef INVARIANTS
3438 static struct vm_pagequeue *
3439 vm_page_pagequeue(vm_page_t m)
3440 {
3441
3442         return (_vm_page_pagequeue(m, vm_page_astate_load(m).queue));
3443 }
3444 #endif
3445
3446 static __always_inline bool
3447 vm_page_pqstate_fcmpset(vm_page_t m, vm_page_astate_t *old, vm_page_astate_t new)
3448 {
3449         vm_page_astate_t tmp;
3450
3451         tmp = *old;
3452         do {
3453                 if (__predict_true(vm_page_astate_fcmpset(m, old, new)))
3454                         return (true);
3455                 counter_u64_add(pqstate_commit_retries, 1);
3456         } while (old->_bits == tmp._bits);
3457
3458         return (false);
3459 }
3460
3461 /*
3462  * Do the work of committing a queue state update that moves the page out of
3463  * its current queue.
3464  */
3465 static bool
3466 _vm_page_pqstate_commit_dequeue(struct vm_pagequeue *pq, vm_page_t m,
3467     vm_page_astate_t *old, vm_page_astate_t new)
3468 {
3469         vm_page_t next;
3470
3471         vm_pagequeue_assert_locked(pq);
3472         KASSERT(vm_page_pagequeue(m) == pq,
3473             ("%s: queue %p does not match page %p", __func__, pq, m));
3474         KASSERT(old->queue != PQ_NONE && new.queue != old->queue,
3475             ("%s: invalid queue indices %d %d",
3476             __func__, old->queue, new.queue));
3477
3478         /*
3479          * Once the queue index of the page changes there is nothing
3480          * synchronizing with further updates to the page's physical
3481          * queue state.  Therefore we must speculatively remove the page
3482          * from the queue now and be prepared to roll back if the queue
3483          * state update fails.  If the page is not physically enqueued then
3484          * we just update its queue index.
3485          */
3486         if ((old->flags & PGA_ENQUEUED) != 0) {
3487                 new.flags &= ~PGA_ENQUEUED;
3488                 next = TAILQ_NEXT(m, plinks.q);
3489                 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3490                 vm_pagequeue_cnt_dec(pq);
3491                 if (!vm_page_pqstate_fcmpset(m, old, new)) {
3492                         if (next == NULL)
3493                                 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3494                         else
3495                                 TAILQ_INSERT_BEFORE(next, m, plinks.q);
3496                         vm_pagequeue_cnt_inc(pq);
3497                         return (false);
3498                 } else {
3499                         return (true);
3500                 }
3501         } else {
3502                 return (vm_page_pqstate_fcmpset(m, old, new));
3503         }
3504 }
3505
3506 static bool
3507 vm_page_pqstate_commit_dequeue(vm_page_t m, vm_page_astate_t *old,
3508     vm_page_astate_t new)
3509 {
3510         struct vm_pagequeue *pq;
3511         vm_page_astate_t as;
3512         bool ret;
3513
3514         pq = _vm_page_pagequeue(m, old->queue);
3515
3516         /*
3517          * The queue field and PGA_ENQUEUED flag are stable only so long as the
3518          * corresponding page queue lock is held.
3519          */
3520         vm_pagequeue_lock(pq);
3521         as = vm_page_astate_load(m);
3522         if (__predict_false(as._bits != old->_bits)) {
3523                 *old = as;
3524                 ret = false;
3525         } else {
3526                 ret = _vm_page_pqstate_commit_dequeue(pq, m, old, new);
3527         }
3528         vm_pagequeue_unlock(pq);
3529         return (ret);
3530 }
3531
3532 /*
3533  * Commit a queue state update that enqueues or requeues a page.
3534  */
3535 static bool
3536 _vm_page_pqstate_commit_requeue(struct vm_pagequeue *pq, vm_page_t m,
3537     vm_page_astate_t *old, vm_page_astate_t new)
3538 {
3539         struct vm_domain *vmd;
3540
3541         vm_pagequeue_assert_locked(pq);
3542         KASSERT(old->queue != PQ_NONE && new.queue == old->queue,
3543             ("%s: invalid queue indices %d %d",
3544             __func__, old->queue, new.queue));
3545
3546         new.flags |= PGA_ENQUEUED;
3547         if (!vm_page_pqstate_fcmpset(m, old, new))
3548                 return (false);
3549
3550         if ((old->flags & PGA_ENQUEUED) != 0)
3551                 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3552         else
3553                 vm_pagequeue_cnt_inc(pq);
3554
3555         /*
3556          * Give PGA_REQUEUE_HEAD precedence over PGA_REQUEUE.  In particular, if
3557          * both flags are set in close succession, only PGA_REQUEUE_HEAD will be
3558          * applied, even if it was set first.
3559          */
3560         if ((old->flags & PGA_REQUEUE_HEAD) != 0) {
3561                 vmd = vm_pagequeue_domain(m);
3562                 KASSERT(pq == &vmd->vmd_pagequeues[PQ_INACTIVE],
3563                     ("%s: invalid page queue for page %p", __func__, m));
3564                 TAILQ_INSERT_BEFORE(&vmd->vmd_inacthead, m, plinks.q);
3565         } else {
3566                 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3567         }
3568         return (true);
3569 }
3570
3571 /*
3572  * Commit a queue state update that encodes a request for a deferred queue
3573  * operation.
3574  */
3575 static bool
3576 vm_page_pqstate_commit_request(vm_page_t m, vm_page_astate_t *old,
3577     vm_page_astate_t new)
3578 {
3579
3580         KASSERT(old->queue == new.queue || new.queue != PQ_NONE,
3581             ("%s: invalid state, queue %d flags %x",
3582             __func__, new.queue, new.flags));
3583
3584         if (old->_bits != new._bits &&
3585             !vm_page_pqstate_fcmpset(m, old, new))
3586                 return (false);
3587         vm_page_pqbatch_submit(m, new.queue);
3588         return (true);
3589 }
3590
3591 /*
3592  * A generic queue state update function.  This handles more cases than the
3593  * specialized functions above.
3594  */
3595 bool
3596 vm_page_pqstate_commit(vm_page_t m, vm_page_astate_t *old, vm_page_astate_t new)
3597 {
3598
3599         if (old->_bits == new._bits)
3600                 return (true);
3601
3602         if (old->queue != PQ_NONE && new.queue != old->queue) {
3603                 if (!vm_page_pqstate_commit_dequeue(m, old, new))
3604                         return (false);
3605                 if (new.queue != PQ_NONE)
3606                         vm_page_pqbatch_submit(m, new.queue);
3607         } else {
3608                 if (!vm_page_pqstate_fcmpset(m, old, new))
3609                         return (false);
3610                 if (new.queue != PQ_NONE &&
3611                     ((new.flags & ~old->flags) & PGA_QUEUE_OP_MASK) != 0)
3612                         vm_page_pqbatch_submit(m, new.queue);
3613         }
3614         return (true);
3615 }
3616
3617 /*
3618  * Apply deferred queue state updates to a page.
3619  */
3620 static inline void
3621 vm_pqbatch_process_page(struct vm_pagequeue *pq, vm_page_t m, uint8_t queue)
3622 {
3623         vm_page_astate_t new, old;
3624
3625         CRITICAL_ASSERT(curthread);
3626         vm_pagequeue_assert_locked(pq);
3627         KASSERT(queue < PQ_COUNT,
3628             ("%s: invalid queue index %d", __func__, queue));
3629         KASSERT(pq == _vm_page_pagequeue(m, queue),
3630             ("%s: page %p does not belong to queue %p", __func__, m, pq));
3631
3632         for (old = vm_page_astate_load(m);;) {
3633                 if (__predict_false(old.queue != queue ||
3634                     (old.flags & PGA_QUEUE_OP_MASK) == 0)) {
3635                         counter_u64_add(queue_nops, 1);
3636                         break;
3637                 }
3638                 KASSERT(old.queue != PQ_NONE ||
3639                     (old.flags & PGA_QUEUE_STATE_MASK) == 0,
3640                     ("%s: page %p has unexpected queue state", __func__, m));
3641
3642                 new = old;
3643                 if ((old.flags & PGA_DEQUEUE) != 0) {
3644                         new.flags &= ~PGA_QUEUE_OP_MASK;
3645                         new.queue = PQ_NONE;
3646                         if (__predict_true(_vm_page_pqstate_commit_dequeue(pq,
3647                             m, &old, new))) {
3648                                 counter_u64_add(queue_ops, 1);
3649                                 break;
3650                         }
3651                 } else {
3652                         new.flags &= ~(PGA_REQUEUE | PGA_REQUEUE_HEAD);
3653                         if (__predict_true(_vm_page_pqstate_commit_requeue(pq,
3654                             m, &old, new))) {
3655                                 counter_u64_add(queue_ops, 1);
3656                                 break;
3657                         }
3658                 }
3659         }
3660 }
3661
3662 static void
3663 vm_pqbatch_process(struct vm_pagequeue *pq, struct vm_batchqueue *bq,
3664     uint8_t queue)
3665 {
3666         int i;
3667
3668         for (i = 0; i < bq->bq_cnt; i++)
3669                 vm_pqbatch_process_page(pq, bq->bq_pa[i], queue);
3670         vm_batchqueue_init(bq);
3671 }
3672
3673 /*
3674  *      vm_page_pqbatch_submit:         [ internal use only ]
3675  *
3676  *      Enqueue a page in the specified page queue's batched work queue.
3677  *      The caller must have encoded the requested operation in the page
3678  *      structure's a.flags field.
3679  */
3680 void
3681 vm_page_pqbatch_submit(vm_page_t m, uint8_t queue)
3682 {
3683         struct vm_batchqueue *bq;
3684         struct vm_pagequeue *pq;
3685         int domain;
3686
3687         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3688             ("page %p is unmanaged", m));
3689         KASSERT(queue < PQ_COUNT, ("invalid queue %d", queue));
3690
3691         domain = vm_page_domain(m);
3692         critical_enter();
3693         bq = DPCPU_PTR(pqbatch[domain][queue]);
3694         if (vm_batchqueue_insert(bq, m)) {
3695                 critical_exit();
3696                 return;
3697         }
3698         critical_exit();
3699
3700         pq = &VM_DOMAIN(domain)->vmd_pagequeues[queue];
3701         vm_pagequeue_lock(pq);
3702         critical_enter();
3703         bq = DPCPU_PTR(pqbatch[domain][queue]);
3704         vm_pqbatch_process(pq, bq, queue);
3705         vm_pqbatch_process_page(pq, m, queue);
3706         vm_pagequeue_unlock(pq);
3707         critical_exit();
3708 }
3709
3710 /*
3711  *      vm_page_pqbatch_drain:          [ internal use only ]
3712  *
3713  *      Force all per-CPU page queue batch queues to be drained.  This is
3714  *      intended for use in severe memory shortages, to ensure that pages
3715  *      do not remain stuck in the batch queues.
3716  */
3717 void
3718 vm_page_pqbatch_drain(void)
3719 {
3720         struct thread *td;
3721         struct vm_domain *vmd;
3722         struct vm_pagequeue *pq;
3723         int cpu, domain, queue;
3724
3725         td = curthread;
3726         CPU_FOREACH(cpu) {
3727                 thread_lock(td);
3728                 sched_bind(td, cpu);
3729                 thread_unlock(td);
3730
3731                 for (domain = 0; domain < vm_ndomains; domain++) {
3732                         vmd = VM_DOMAIN(domain);
3733                         for (queue = 0; queue < PQ_COUNT; queue++) {
3734                                 pq = &vmd->vmd_pagequeues[queue];
3735                                 vm_pagequeue_lock(pq);
3736                                 critical_enter();
3737                                 vm_pqbatch_process(pq,
3738                                     DPCPU_PTR(pqbatch[domain][queue]), queue);
3739                                 critical_exit();
3740                                 vm_pagequeue_unlock(pq);
3741                         }
3742                 }
3743         }
3744         thread_lock(td);
3745         sched_unbind(td);
3746         thread_unlock(td);
3747 }
3748
3749 /*
3750  *      vm_page_dequeue_deferred:       [ internal use only ]
3751  *
3752  *      Request removal of the given page from its current page
3753  *      queue.  Physical removal from the queue may be deferred
3754  *      indefinitely.
3755  */
3756 void
3757 vm_page_dequeue_deferred(vm_page_t m)
3758 {
3759         vm_page_astate_t new, old;
3760
3761         old = vm_page_astate_load(m);
3762         do {
3763                 if (old.queue == PQ_NONE) {
3764                         KASSERT((old.flags & PGA_QUEUE_STATE_MASK) == 0,
3765                             ("%s: page %p has unexpected queue state",
3766                             __func__, m));
3767                         break;
3768                 }
3769                 new = old;
3770                 new.flags |= PGA_DEQUEUE;
3771         } while (!vm_page_pqstate_commit_request(m, &old, new));
3772 }
3773
3774 /*
3775  *      vm_page_dequeue:
3776  *
3777  *      Remove the page from whichever page queue it's in, if any, before
3778  *      returning.
3779  */
3780 void
3781 vm_page_dequeue(vm_page_t m)
3782 {
3783         vm_page_astate_t new, old;
3784
3785         old = vm_page_astate_load(m);
3786         do {
3787                 if (old.queue == PQ_NONE) {
3788                         KASSERT((old.flags & PGA_QUEUE_STATE_MASK) == 0,
3789                             ("%s: page %p has unexpected queue state",
3790                             __func__, m));
3791                         break;
3792                 }
3793                 new = old;
3794                 new.flags &= ~PGA_QUEUE_OP_MASK;
3795                 new.queue = PQ_NONE;
3796         } while (!vm_page_pqstate_commit_dequeue(m, &old, new));
3797
3798 }
3799
3800 /*
3801  * Schedule the given page for insertion into the specified page queue.
3802  * Physical insertion of the page may be deferred indefinitely.
3803  */
3804 static void
3805 vm_page_enqueue(vm_page_t m, uint8_t queue)
3806 {
3807
3808         KASSERT(m->a.queue == PQ_NONE &&
3809             (m->a.flags & PGA_QUEUE_STATE_MASK) == 0,
3810             ("%s: page %p is already enqueued", __func__, m));
3811         KASSERT(m->ref_count > 0,
3812             ("%s: page %p does not carry any references", __func__, m));
3813
3814         m->a.queue = queue;
3815         if ((m->a.flags & PGA_REQUEUE) == 0)
3816                 vm_page_aflag_set(m, PGA_REQUEUE);
3817         vm_page_pqbatch_submit(m, queue);
3818 }
3819
3820 /*
3821  *      vm_page_free_prep:
3822  *
3823  *      Prepares the given page to be put on the free list,
3824  *      disassociating it from any VM object. The caller may return
3825  *      the page to the free list only if this function returns true.
3826  *
3827  *      The object, if it exists, must be locked, and then the page must
3828  *      be xbusy.  Otherwise the page must be not busied.  A managed
3829  *      page must be unmapped.
3830  */
3831 static bool
3832 vm_page_free_prep(vm_page_t m)
3833 {
3834
3835         /*
3836          * Synchronize with threads that have dropped a reference to this
3837          * page.
3838          */
3839         atomic_thread_fence_acq();
3840
3841 #if defined(DIAGNOSTIC) && defined(PHYS_TO_DMAP)
3842         if (PMAP_HAS_DMAP && (m->flags & PG_ZERO) != 0) {
3843                 uint64_t *p;
3844                 int i;
3845                 p = (uint64_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
3846                 for (i = 0; i < PAGE_SIZE / sizeof(uint64_t); i++, p++)
3847                         KASSERT(*p == 0, ("vm_page_free_prep %p PG_ZERO %d %jx",
3848                             m, i, (uintmax_t)*p));
3849         }
3850 #endif
3851         if ((m->oflags & VPO_UNMANAGED) == 0) {
3852                 KASSERT(!pmap_page_is_mapped(m),
3853                     ("vm_page_free_prep: freeing mapped page %p", m));
3854                 KASSERT((m->a.flags & (PGA_EXECUTABLE | PGA_WRITEABLE)) == 0,
3855                     ("vm_page_free_prep: mapping flags set in page %p", m));
3856         } else {
3857                 KASSERT(m->a.queue == PQ_NONE,
3858                     ("vm_page_free_prep: unmanaged page %p is queued", m));
3859         }
3860         VM_CNT_INC(v_tfree);
3861
3862         if (m->object != NULL) {
3863                 KASSERT(((m->oflags & VPO_UNMANAGED) != 0) ==
3864                     ((m->object->flags & OBJ_UNMANAGED) != 0),
3865                     ("vm_page_free_prep: managed flag mismatch for page %p",
3866                     m));
3867                 vm_page_assert_xbusied(m);
3868
3869                 /*
3870                  * The object reference can be released without an atomic
3871                  * operation.
3872                  */
3873                 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
3874                     m->ref_count == VPRC_OBJREF,
3875                     ("vm_page_free_prep: page %p has unexpected ref_count %u",
3876                     m, m->ref_count));
3877                 vm_page_object_remove(m);
3878                 m->ref_count -= VPRC_OBJREF;
3879         } else
3880                 vm_page_assert_unbusied(m);
3881
3882         vm_page_busy_free(m);
3883
3884         /*
3885          * If fictitious remove object association and
3886          * return.
3887          */
3888         if ((m->flags & PG_FICTITIOUS) != 0) {
3889                 KASSERT(m->ref_count == 1,
3890                     ("fictitious page %p is referenced", m));
3891                 KASSERT(m->a.queue == PQ_NONE,
3892                     ("fictitious page %p is queued", m));
3893                 return (false);
3894         }
3895
3896         /*
3897          * Pages need not be dequeued before they are returned to the physical
3898          * memory allocator, but they must at least be marked for a deferred
3899          * dequeue.
3900          */
3901         if ((m->oflags & VPO_UNMANAGED) == 0)
3902                 vm_page_dequeue_deferred(m);
3903
3904         m->valid = 0;
3905         vm_page_undirty(m);
3906
3907         if (m->ref_count != 0)
3908                 panic("vm_page_free_prep: page %p has references", m);
3909
3910         /*
3911          * Restore the default memory attribute to the page.
3912          */
3913         if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
3914                 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
3915
3916 #if VM_NRESERVLEVEL > 0
3917         /*
3918          * Determine whether the page belongs to a reservation.  If the page was
3919          * allocated from a per-CPU cache, it cannot belong to a reservation, so
3920          * as an optimization, we avoid the check in that case.
3921          */
3922         if ((m->flags & PG_PCPU_CACHE) == 0 && vm_reserv_free_page(m))
3923                 return (false);
3924 #endif
3925
3926         return (true);
3927 }
3928
3929 /*
3930  *      vm_page_free_toq:
3931  *
3932  *      Returns the given page to the free list, disassociating it
3933  *      from any VM object.
3934  *
3935  *      The object must be locked.  The page must be exclusively busied if it
3936  *      belongs to an object.
3937  */
3938 static void
3939 vm_page_free_toq(vm_page_t m)
3940 {
3941         struct vm_domain *vmd;
3942         uma_zone_t zone;
3943
3944         if (!vm_page_free_prep(m))
3945                 return;
3946
3947         vmd = vm_pagequeue_domain(m);
3948         zone = vmd->vmd_pgcache[m->pool].zone;
3949         if ((m->flags & PG_PCPU_CACHE) != 0 && zone != NULL) {
3950                 uma_zfree(zone, m);
3951                 return;
3952         }
3953         vm_domain_free_lock(vmd);
3954         vm_phys_free_pages(m, 0);
3955         vm_domain_free_unlock(vmd);
3956         vm_domain_freecnt_inc(vmd, 1);
3957 }
3958
3959 /*
3960  *      vm_page_free_pages_toq:
3961  *
3962  *      Returns a list of pages to the free list, disassociating it
3963  *      from any VM object.  In other words, this is equivalent to
3964  *      calling vm_page_free_toq() for each page of a list of VM objects.
3965  */
3966 void
3967 vm_page_free_pages_toq(struct spglist *free, bool update_wire_count)
3968 {
3969         vm_page_t m;
3970         int count;
3971
3972         if (SLIST_EMPTY(free))
3973                 return;
3974
3975         count = 0;
3976         while ((m = SLIST_FIRST(free)) != NULL) {
3977                 count++;
3978                 SLIST_REMOVE_HEAD(free, plinks.s.ss);
3979                 vm_page_free_toq(m);
3980         }
3981
3982         if (update_wire_count)
3983                 vm_wire_sub(count);
3984 }
3985
3986 /*
3987  * Mark this page as wired down.  For managed pages, this prevents reclamation
3988  * by the page daemon, or when the containing object, if any, is destroyed.
3989  */
3990 void
3991 vm_page_wire(vm_page_t m)
3992 {
3993         u_int old;
3994
3995 #ifdef INVARIANTS
3996         if (m->object != NULL && !vm_page_busied(m) &&
3997             !vm_object_busied(m->object))
3998                 VM_OBJECT_ASSERT_LOCKED(m->object);
3999 #endif
4000         KASSERT((m->flags & PG_FICTITIOUS) == 0 ||
4001             VPRC_WIRE_COUNT(m->ref_count) >= 1,
4002             ("vm_page_wire: fictitious page %p has zero wirings", m));
4003
4004         old = atomic_fetchadd_int(&m->ref_count, 1);
4005         KASSERT(VPRC_WIRE_COUNT(old) != VPRC_WIRE_COUNT_MAX,
4006             ("vm_page_wire: counter overflow for page %p", m));
4007         if (VPRC_WIRE_COUNT(old) == 0) {
4008                 if ((m->oflags & VPO_UNMANAGED) == 0)
4009                         vm_page_aflag_set(m, PGA_DEQUEUE);
4010                 vm_wire_add(1);
4011         }
4012 }
4013
4014 /*
4015  * Attempt to wire a mapped page following a pmap lookup of that page.
4016  * This may fail if a thread is concurrently tearing down mappings of the page.
4017  * The transient failure is acceptable because it translates to the
4018  * failure of the caller pmap_extract_and_hold(), which should be then
4019  * followed by the vm_fault() fallback, see e.g. vm_fault_quick_hold_pages().
4020  */
4021 bool
4022 vm_page_wire_mapped(vm_page_t m)
4023 {
4024         u_int old;
4025
4026         old = m->ref_count;
4027         do {
4028                 KASSERT(old > 0,
4029                     ("vm_page_wire_mapped: wiring unreferenced page %p", m));
4030                 if ((old & VPRC_BLOCKED) != 0)
4031                         return (false);
4032         } while (!atomic_fcmpset_int(&m->ref_count, &old, old + 1));
4033
4034         if (VPRC_WIRE_COUNT(old) == 0) {
4035                 if ((m->oflags & VPO_UNMANAGED) == 0)
4036                         vm_page_aflag_set(m, PGA_DEQUEUE);
4037                 vm_wire_add(1);
4038         }
4039         return (true);
4040 }
4041
4042 /*
4043  * Release a wiring reference to a managed page.  If the page still belongs to
4044  * an object, update its position in the page queues to reflect the reference.
4045  * If the wiring was the last reference to the page, free the page.
4046  */
4047 static void
4048 vm_page_unwire_managed(vm_page_t m, uint8_t nqueue, bool noreuse)
4049 {
4050         u_int old;
4051
4052         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4053             ("%s: page %p is unmanaged", __func__, m));
4054
4055         /*
4056          * Update LRU state before releasing the wiring reference.
4057          * Use a release store when updating the reference count to
4058          * synchronize with vm_page_free_prep().
4059          */
4060         old = m->ref_count;
4061         do {
4062                 KASSERT(VPRC_WIRE_COUNT(old) > 0,
4063                     ("vm_page_unwire: wire count underflow for page %p", m));
4064
4065                 if (old > VPRC_OBJREF + 1) {
4066                         /*
4067                          * The page has at least one other wiring reference.  An
4068                          * earlier iteration of this loop may have called
4069                          * vm_page_release_toq() and cleared PGA_DEQUEUE, so
4070                          * re-set it if necessary.
4071                          */
4072                         if ((vm_page_astate_load(m).flags & PGA_DEQUEUE) == 0)
4073                                 vm_page_aflag_set(m, PGA_DEQUEUE);
4074                 } else if (old == VPRC_OBJREF + 1) {
4075                         /*
4076                          * This is the last wiring.  Clear PGA_DEQUEUE and
4077                          * update the page's queue state to reflect the
4078                          * reference.  If the page does not belong to an object
4079                          * (i.e., the VPRC_OBJREF bit is clear), we only need to
4080                          * clear leftover queue state.
4081                          */
4082                         vm_page_release_toq(m, nqueue, noreuse);
4083                 } else if (old == 1) {
4084                         vm_page_aflag_clear(m, PGA_DEQUEUE);
4085                 }
4086         } while (!atomic_fcmpset_rel_int(&m->ref_count, &old, old - 1));
4087
4088         if (VPRC_WIRE_COUNT(old) == 1) {
4089                 vm_wire_sub(1);
4090                 if (old == 1)
4091                         vm_page_free(m);
4092         }
4093 }
4094
4095 /*
4096  * Release one wiring of the specified page, potentially allowing it to be
4097  * paged out.
4098  *
4099  * Only managed pages belonging to an object can be paged out.  If the number
4100  * of wirings transitions to zero and the page is eligible for page out, then
4101  * the page is added to the specified paging queue.  If the released wiring
4102  * represented the last reference to the page, the page is freed.
4103  */
4104 void
4105 vm_page_unwire(vm_page_t m, uint8_t nqueue)
4106 {
4107
4108         KASSERT(nqueue < PQ_COUNT,
4109             ("vm_page_unwire: invalid queue %u request for page %p",
4110             nqueue, m));
4111
4112         if ((m->oflags & VPO_UNMANAGED) != 0) {
4113                 if (vm_page_unwire_noq(m) && m->ref_count == 0)
4114                         vm_page_free(m);
4115                 return;
4116         }
4117         vm_page_unwire_managed(m, nqueue, false);
4118 }
4119
4120 /*
4121  * Unwire a page without (re-)inserting it into a page queue.  It is up
4122  * to the caller to enqueue, requeue, or free the page as appropriate.
4123  * In most cases involving managed pages, vm_page_unwire() should be used
4124  * instead.
4125  */
4126 bool
4127 vm_page_unwire_noq(vm_page_t m)
4128 {
4129         u_int old;
4130
4131         old = vm_page_drop(m, 1);
4132         KASSERT(VPRC_WIRE_COUNT(old) != 0,
4133             ("vm_page_unref: counter underflow for page %p", m));
4134         KASSERT((m->flags & PG_FICTITIOUS) == 0 || VPRC_WIRE_COUNT(old) > 1,
4135             ("vm_page_unref: missing ref on fictitious page %p", m));
4136
4137         if (VPRC_WIRE_COUNT(old) > 1)
4138                 return (false);
4139         if ((m->oflags & VPO_UNMANAGED) == 0)
4140                 vm_page_aflag_clear(m, PGA_DEQUEUE);
4141         vm_wire_sub(1);
4142         return (true);
4143 }
4144
4145 /*
4146  * Ensure that the page ends up in the specified page queue.  If the page is
4147  * active or being moved to the active queue, ensure that its act_count is
4148  * at least ACT_INIT but do not otherwise mess with it.
4149  */
4150 static __always_inline void
4151 vm_page_mvqueue(vm_page_t m, const uint8_t nqueue, const uint16_t nflag)
4152 {
4153         vm_page_astate_t old, new;
4154
4155         KASSERT(m->ref_count > 0,
4156             ("%s: page %p does not carry any references", __func__, m));
4157         KASSERT(nflag == PGA_REQUEUE || nflag == PGA_REQUEUE_HEAD,
4158             ("%s: invalid flags %x", __func__, nflag));
4159
4160         if ((m->oflags & VPO_UNMANAGED) != 0 || vm_page_wired(m))
4161                 return;
4162
4163         old = vm_page_astate_load(m);
4164         do {
4165                 if ((old.flags & PGA_DEQUEUE) != 0)
4166                         break;
4167                 new = old;
4168                 new.flags &= ~PGA_QUEUE_OP_MASK;
4169                 if (nqueue == PQ_ACTIVE)
4170                         new.act_count = max(old.act_count, ACT_INIT);
4171                 if (old.queue == nqueue) {
4172                         if (nqueue != PQ_ACTIVE)
4173                                 new.flags |= nflag;
4174                 } else {
4175                         new.flags |= nflag;
4176                         new.queue = nqueue;
4177                 }
4178         } while (!vm_page_pqstate_commit(m, &old, new));
4179 }
4180
4181 /*
4182  * Put the specified page on the active list (if appropriate).
4183  */
4184 void
4185 vm_page_activate(vm_page_t m)
4186 {
4187
4188         vm_page_mvqueue(m, PQ_ACTIVE, PGA_REQUEUE);
4189 }
4190
4191 /*
4192  * Move the specified page to the tail of the inactive queue, or requeue
4193  * the page if it is already in the inactive queue.
4194  */
4195 void
4196 vm_page_deactivate(vm_page_t m)
4197 {
4198
4199         vm_page_mvqueue(m, PQ_INACTIVE, PGA_REQUEUE);
4200 }
4201
4202 void
4203 vm_page_deactivate_noreuse(vm_page_t m)
4204 {
4205
4206         vm_page_mvqueue(m, PQ_INACTIVE, PGA_REQUEUE_HEAD);
4207 }
4208
4209 /*
4210  * Put a page in the laundry, or requeue it if it is already there.
4211  */
4212 void
4213 vm_page_launder(vm_page_t m)
4214 {
4215
4216         vm_page_mvqueue(m, PQ_LAUNDRY, PGA_REQUEUE);
4217 }
4218
4219 /*
4220  * Put a page in the PQ_UNSWAPPABLE holding queue.
4221  */
4222 void
4223 vm_page_unswappable(vm_page_t m)
4224 {
4225
4226         KASSERT(!vm_page_wired(m) && (m->oflags & VPO_UNMANAGED) == 0,
4227             ("page %p already unswappable", m));
4228
4229         vm_page_dequeue(m);
4230         vm_page_enqueue(m, PQ_UNSWAPPABLE);
4231 }
4232
4233 /*
4234  * Release a page back to the page queues in preparation for unwiring.
4235  */
4236 static void
4237 vm_page_release_toq(vm_page_t m, uint8_t nqueue, const bool noreuse)
4238 {
4239         vm_page_astate_t old, new;
4240         uint16_t nflag;
4241
4242         /*
4243          * Use a check of the valid bits to determine whether we should
4244          * accelerate reclamation of the page.  The object lock might not be
4245          * held here, in which case the check is racy.  At worst we will either
4246          * accelerate reclamation of a valid page and violate LRU, or
4247          * unnecessarily defer reclamation of an invalid page.
4248          *
4249          * If we were asked to not cache the page, place it near the head of the
4250          * inactive queue so that is reclaimed sooner.
4251          */
4252         if (noreuse || m->valid == 0) {
4253                 nqueue = PQ_INACTIVE;
4254                 nflag = PGA_REQUEUE_HEAD;
4255         } else {
4256                 nflag = PGA_REQUEUE;
4257         }
4258
4259         old = vm_page_astate_load(m);
4260         do {
4261                 new = old;
4262
4263                 /*
4264                  * If the page is already in the active queue and we are not
4265                  * trying to accelerate reclamation, simply mark it as
4266                  * referenced and avoid any queue operations.
4267                  */
4268                 new.flags &= ~PGA_QUEUE_OP_MASK;
4269                 if (nflag != PGA_REQUEUE_HEAD && old.queue == PQ_ACTIVE)
4270                         new.flags |= PGA_REFERENCED;
4271                 else {
4272                         new.flags |= nflag;
4273                         new.queue = nqueue;
4274                 }
4275         } while (!vm_page_pqstate_commit(m, &old, new));
4276 }
4277
4278 /*
4279  * Unwire a page and either attempt to free it or re-add it to the page queues.
4280  */
4281 void
4282 vm_page_release(vm_page_t m, int flags)
4283 {
4284         vm_object_t object;
4285
4286         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4287             ("vm_page_release: page %p is unmanaged", m));
4288
4289         if ((flags & VPR_TRYFREE) != 0) {
4290                 for (;;) {
4291                         object = atomic_load_ptr(&m->object);
4292                         if (object == NULL)
4293                                 break;
4294                         /* Depends on type-stability. */
4295                         if (vm_page_busied(m) || !VM_OBJECT_TRYWLOCK(object))
4296                                 break;
4297                         if (object == m->object) {
4298                                 vm_page_release_locked(m, flags);
4299                                 VM_OBJECT_WUNLOCK(object);
4300                                 return;
4301                         }
4302                         VM_OBJECT_WUNLOCK(object);
4303                 }
4304         }
4305         vm_page_unwire_managed(m, PQ_INACTIVE, flags != 0);
4306 }
4307
4308 /* See vm_page_release(). */
4309 void
4310 vm_page_release_locked(vm_page_t m, int flags)
4311 {
4312
4313         VM_OBJECT_ASSERT_WLOCKED(m->object);
4314         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4315             ("vm_page_release_locked: page %p is unmanaged", m));
4316
4317         if (vm_page_unwire_noq(m)) {
4318                 if ((flags & VPR_TRYFREE) != 0 &&
4319                     (m->object->ref_count == 0 || !pmap_page_is_mapped(m)) &&
4320                     m->dirty == 0 && vm_page_tryxbusy(m)) {
4321                         /*
4322                          * An unlocked lookup may have wired the page before the
4323                          * busy lock was acquired, in which case the page must
4324                          * not be freed.
4325                          */
4326                         if (__predict_true(!vm_page_wired(m))) {
4327                                 vm_page_free(m);
4328                                 return;
4329                         }
4330                         vm_page_xunbusy(m);
4331                 } else {
4332                         vm_page_release_toq(m, PQ_INACTIVE, flags != 0);
4333                 }
4334         }
4335 }
4336
4337 static bool
4338 vm_page_try_blocked_op(vm_page_t m, void (*op)(vm_page_t))
4339 {
4340         u_int old;
4341
4342         KASSERT(m->object != NULL && (m->oflags & VPO_UNMANAGED) == 0,
4343             ("vm_page_try_blocked_op: page %p has no object", m));
4344         KASSERT(vm_page_busied(m),
4345             ("vm_page_try_blocked_op: page %p is not busy", m));
4346         VM_OBJECT_ASSERT_LOCKED(m->object);
4347
4348         old = m->ref_count;
4349         do {
4350                 KASSERT(old != 0,
4351                     ("vm_page_try_blocked_op: page %p has no references", m));
4352                 if (VPRC_WIRE_COUNT(old) != 0)
4353                         return (false);
4354         } while (!atomic_fcmpset_int(&m->ref_count, &old, old | VPRC_BLOCKED));
4355
4356         (op)(m);
4357
4358         /*
4359          * If the object is read-locked, new wirings may be created via an
4360          * object lookup.
4361          */
4362         old = vm_page_drop(m, VPRC_BLOCKED);
4363         KASSERT(!VM_OBJECT_WOWNED(m->object) ||
4364             old == (VPRC_BLOCKED | VPRC_OBJREF),
4365             ("vm_page_try_blocked_op: unexpected refcount value %u for %p",
4366             old, m));
4367         return (true);
4368 }
4369
4370 /*
4371  * Atomically check for wirings and remove all mappings of the page.
4372  */
4373 bool
4374 vm_page_try_remove_all(vm_page_t m)
4375 {
4376
4377         return (vm_page_try_blocked_op(m, pmap_remove_all));
4378 }
4379
4380 /*
4381  * Atomically check for wirings and remove all writeable mappings of the page.
4382  */
4383 bool
4384 vm_page_try_remove_write(vm_page_t m)
4385 {
4386
4387         return (vm_page_try_blocked_op(m, pmap_remove_write));
4388 }
4389
4390 /*
4391  * vm_page_advise
4392  *
4393  *      Apply the specified advice to the given page.
4394  */
4395 void
4396 vm_page_advise(vm_page_t m, int advice)
4397 {
4398
4399         VM_OBJECT_ASSERT_WLOCKED(m->object);
4400         vm_page_assert_xbusied(m);
4401
4402         if (advice == MADV_FREE)
4403                 /*
4404                  * Mark the page clean.  This will allow the page to be freed
4405                  * without first paging it out.  MADV_FREE pages are often
4406                  * quickly reused by malloc(3), so we do not do anything that
4407                  * would result in a page fault on a later access.
4408                  */
4409                 vm_page_undirty(m);
4410         else if (advice != MADV_DONTNEED) {
4411                 if (advice == MADV_WILLNEED)
4412                         vm_page_activate(m);
4413                 return;
4414         }
4415
4416         if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
4417                 vm_page_dirty(m);
4418
4419         /*
4420          * Clear any references to the page.  Otherwise, the page daemon will
4421          * immediately reactivate the page.
4422          */
4423         vm_page_aflag_clear(m, PGA_REFERENCED);
4424
4425         /*
4426          * Place clean pages near the head of the inactive queue rather than
4427          * the tail, thus defeating the queue's LRU operation and ensuring that
4428          * the page will be reused quickly.  Dirty pages not already in the
4429          * laundry are moved there.
4430          */
4431         if (m->dirty == 0)
4432                 vm_page_deactivate_noreuse(m);
4433         else if (!vm_page_in_laundry(m))
4434                 vm_page_launder(m);
4435 }
4436
4437 /*
4438  *      vm_page_grab_release
4439  *
4440  *      Helper routine for grab functions to release busy on return.
4441  */
4442 static inline void
4443 vm_page_grab_release(vm_page_t m, int allocflags)
4444 {
4445
4446         if ((allocflags & VM_ALLOC_NOBUSY) != 0) {
4447                 if ((allocflags & VM_ALLOC_IGN_SBUSY) != 0)
4448                         vm_page_sunbusy(m);
4449                 else
4450                         vm_page_xunbusy(m);
4451         }
4452 }
4453
4454 /*
4455  *      vm_page_grab_sleep
4456  *
4457  *      Sleep for busy according to VM_ALLOC_ parameters.  Returns true
4458  *      if the caller should retry and false otherwise.
4459  *
4460  *      If the object is locked on entry the object will be unlocked with
4461  *      false returns and still locked but possibly having been dropped
4462  *      with true returns.
4463  */
4464 static bool
4465 vm_page_grab_sleep(vm_object_t object, vm_page_t m, vm_pindex_t pindex,
4466     const char *wmesg, int allocflags, bool locked)
4467 {
4468
4469         if ((allocflags & VM_ALLOC_NOWAIT) != 0)
4470                 return (false);
4471
4472         /*
4473          * Reference the page before unlocking and sleeping so that
4474          * the page daemon is less likely to reclaim it.
4475          */
4476         if (locked && (allocflags & VM_ALLOC_NOCREAT) == 0)
4477                 vm_page_reference(m);
4478
4479         if (_vm_page_busy_sleep(object, m, pindex, wmesg, allocflags, locked) &&
4480             locked)
4481                 VM_OBJECT_WLOCK(object);
4482         if ((allocflags & VM_ALLOC_WAITFAIL) != 0)
4483                 return (false);
4484
4485         return (true);
4486 }
4487
4488 /*
4489  * Assert that the grab flags are valid.
4490  */
4491 static inline void
4492 vm_page_grab_check(int allocflags)
4493 {
4494
4495         KASSERT((allocflags & VM_ALLOC_NOBUSY) == 0 ||
4496             (allocflags & VM_ALLOC_WIRED) != 0,
4497             ("vm_page_grab*: the pages must be busied or wired"));
4498
4499         KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4500             (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4501             ("vm_page_grab*: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
4502 }
4503
4504 /*
4505  * Calculate the page allocation flags for grab.
4506  */
4507 static inline int
4508 vm_page_grab_pflags(int allocflags)
4509 {
4510         int pflags;
4511
4512         pflags = allocflags &
4513             ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL |
4514             VM_ALLOC_NOBUSY);
4515         if ((allocflags & VM_ALLOC_NOWAIT) == 0)
4516                 pflags |= VM_ALLOC_WAITFAIL;
4517         if ((allocflags & VM_ALLOC_IGN_SBUSY) != 0)
4518                 pflags |= VM_ALLOC_SBUSY;
4519
4520         return (pflags);
4521 }
4522
4523 /*
4524  * Grab a page, waiting until we are waken up due to the page
4525  * changing state.  We keep on waiting, if the page continues
4526  * to be in the object.  If the page doesn't exist, first allocate it
4527  * and then conditionally zero it.
4528  *
4529  * This routine may sleep.
4530  *
4531  * The object must be locked on entry.  The lock will, however, be released
4532  * and reacquired if the routine sleeps.
4533  */
4534 vm_page_t
4535 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
4536 {
4537         vm_page_t m;
4538
4539         VM_OBJECT_ASSERT_WLOCKED(object);
4540         vm_page_grab_check(allocflags);
4541
4542 retrylookup:
4543         if ((m = vm_page_lookup(object, pindex)) != NULL) {
4544                 if (!vm_page_tryacquire(m, allocflags)) {
4545                         if (vm_page_grab_sleep(object, m, pindex, "pgrbwt",
4546                             allocflags, true))
4547                                 goto retrylookup;
4548                         return (NULL);
4549                 }
4550                 goto out;
4551         }
4552         if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4553                 return (NULL);
4554         m = vm_page_alloc(object, pindex, vm_page_grab_pflags(allocflags));
4555         if (m == NULL) {
4556                 if ((allocflags & (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL)) != 0)
4557                         return (NULL);
4558                 goto retrylookup;
4559         }
4560         if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
4561                 pmap_zero_page(m);
4562
4563 out:
4564         vm_page_grab_release(m, allocflags);
4565
4566         return (m);
4567 }
4568
4569 /*
4570  * Locklessly attempt to acquire a page given a (object, pindex) tuple
4571  * and an optional previous page to avoid the radix lookup.  The resulting
4572  * page will be validated against the identity tuple and busied or wired
4573  * as requested.  A NULL *mp return guarantees that the page was not in
4574  * radix at the time of the call but callers must perform higher level
4575  * synchronization or retry the operation under a lock if they require
4576  * an atomic answer.  This is the only lock free validation routine,
4577  * other routines can depend on the resulting page state.
4578  *
4579  * The return value indicates whether the operation failed due to caller
4580  * flags.  The return is tri-state with mp:
4581  *
4582  * (true, *mp != NULL) - The operation was successful.
4583  * (true, *mp == NULL) - The page was not found in tree.
4584  * (false, *mp == NULL) - WAITFAIL or NOWAIT prevented acquisition.
4585  */
4586 static bool
4587 vm_page_acquire_unlocked(vm_object_t object, vm_pindex_t pindex,
4588     vm_page_t prev, vm_page_t *mp, int allocflags)
4589 {
4590         vm_page_t m;
4591
4592         vm_page_grab_check(allocflags);
4593         MPASS(prev == NULL || vm_page_busied(prev) || vm_page_wired(prev));
4594
4595         *mp = NULL;
4596         for (;;) {
4597                 /*
4598                  * We may see a false NULL here because the previous page
4599                  * has been removed or just inserted and the list is loaded
4600                  * without barriers.  Switch to radix to verify.
4601                  */
4602                 if (prev == NULL || (m = TAILQ_NEXT(prev, listq)) == NULL ||
4603                     QMD_IS_TRASHED(m) || m->pindex != pindex ||
4604                     atomic_load_ptr(&m->object) != object) {
4605                         prev = NULL;
4606                         /*
4607                          * This guarantees the result is instantaneously
4608                          * correct.
4609                          */
4610                         m = vm_radix_lookup_unlocked(&object->rtree, pindex);
4611                 }
4612                 if (m == NULL)
4613                         return (true);
4614                 if (vm_page_trybusy(m, allocflags)) {
4615                         if (m->object == object && m->pindex == pindex)
4616                                 break;
4617                         /* relookup. */
4618                         vm_page_busy_release(m);
4619                         cpu_spinwait();
4620                         continue;
4621                 }
4622                 if (!vm_page_grab_sleep(object, m, pindex, "pgnslp",
4623                     allocflags, false))
4624                         return (false);
4625         }
4626         if ((allocflags & VM_ALLOC_WIRED) != 0)
4627                 vm_page_wire(m);
4628         vm_page_grab_release(m, allocflags);
4629         *mp = m;
4630         return (true);
4631 }
4632
4633 /*
4634  * Try to locklessly grab a page and fall back to the object lock if NOCREAT
4635  * is not set.
4636  */
4637 vm_page_t
4638 vm_page_grab_unlocked(vm_object_t object, vm_pindex_t pindex, int allocflags)
4639 {
4640         vm_page_t m;
4641
4642         vm_page_grab_check(allocflags);
4643
4644         if (!vm_page_acquire_unlocked(object, pindex, NULL, &m, allocflags))
4645                 return (NULL);
4646         if (m != NULL)
4647                 return (m);
4648
4649         /*
4650          * The radix lockless lookup should never return a false negative
4651          * errors.  If the user specifies NOCREAT they are guaranteed there
4652          * was no page present at the instant of the call.  A NOCREAT caller
4653          * must handle create races gracefully.
4654          */
4655         if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4656                 return (NULL);
4657
4658         VM_OBJECT_WLOCK(object);
4659         m = vm_page_grab(object, pindex, allocflags);
4660         VM_OBJECT_WUNLOCK(object);
4661
4662         return (m);
4663 }
4664
4665 /*
4666  * Grab a page and make it valid, paging in if necessary.  Pages missing from
4667  * their pager are zero filled and validated.  If a VM_ALLOC_COUNT is supplied
4668  * and the page is not valid as many as VM_INITIAL_PAGEIN pages can be brought
4669  * in simultaneously.  Additional pages will be left on a paging queue but
4670  * will neither be wired nor busy regardless of allocflags.
4671  */
4672 int
4673 vm_page_grab_valid(vm_page_t *mp, vm_object_t object, vm_pindex_t pindex, int allocflags)
4674 {
4675         vm_page_t m;
4676         vm_page_t ma[VM_INITIAL_PAGEIN];
4677         int after, i, pflags, rv;
4678
4679         KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4680             (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4681             ("vm_page_grab_valid: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
4682         KASSERT((allocflags &
4683             (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL | VM_ALLOC_ZERO)) == 0,
4684             ("vm_page_grab_valid: Invalid flags 0x%X", allocflags));
4685         VM_OBJECT_ASSERT_WLOCKED(object);
4686         pflags = allocflags & ~(VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY |
4687             VM_ALLOC_WIRED);
4688         pflags |= VM_ALLOC_WAITFAIL;
4689
4690 retrylookup:
4691         if ((m = vm_page_lookup(object, pindex)) != NULL) {
4692                 /*
4693                  * If the page is fully valid it can only become invalid
4694                  * with the object lock held.  If it is not valid it can
4695                  * become valid with the busy lock held.  Therefore, we
4696                  * may unnecessarily lock the exclusive busy here if we
4697                  * race with I/O completion not using the object lock.
4698                  * However, we will not end up with an invalid page and a
4699                  * shared lock.
4700                  */
4701                 if (!vm_page_trybusy(m,
4702                     vm_page_all_valid(m) ? allocflags : 0)) {
4703                         (void)vm_page_grab_sleep(object, m, pindex, "pgrbwt",
4704                             allocflags, true);
4705                         goto retrylookup;
4706                 }
4707                 if (vm_page_all_valid(m))
4708                         goto out;
4709                 if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
4710                         vm_page_busy_release(m);
4711                         *mp = NULL;
4712                         return (VM_PAGER_FAIL);
4713                 }
4714         } else if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
4715                 *mp = NULL;
4716                 return (VM_PAGER_FAIL);
4717         } else if ((m = vm_page_alloc(object, pindex, pflags)) == NULL) {
4718                 goto retrylookup;
4719         }
4720
4721         vm_page_assert_xbusied(m);
4722         if (vm_pager_has_page(object, pindex, NULL, &after)) {
4723                 after = MIN(after, VM_INITIAL_PAGEIN);
4724                 after = MIN(after, allocflags >> VM_ALLOC_COUNT_SHIFT);
4725                 after = MAX(after, 1);
4726                 ma[0] = m;
4727                 for (i = 1; i < after; i++) {
4728                         if ((ma[i] = vm_page_next(ma[i - 1])) != NULL) {
4729                                 if (ma[i]->valid || !vm_page_tryxbusy(ma[i]))
4730                                         break;
4731                         } else {
4732                                 ma[i] = vm_page_alloc(object, m->pindex + i,
4733                                     VM_ALLOC_NORMAL);
4734                                 if (ma[i] == NULL)
4735                                         break;
4736                         }
4737                 }
4738                 after = i;
4739                 vm_object_pip_add(object, after);
4740                 VM_OBJECT_WUNLOCK(object);
4741                 rv = vm_pager_get_pages(object, ma, after, NULL, NULL);
4742                 VM_OBJECT_WLOCK(object);
4743                 vm_object_pip_wakeupn(object, after);
4744                 /* Pager may have replaced a page. */
4745                 m = ma[0];
4746                 if (rv != VM_PAGER_OK) {
4747                         for (i = 0; i < after; i++) {
4748                                 if (!vm_page_wired(ma[i]))
4749                                         vm_page_free(ma[i]);
4750                                 else
4751                                         vm_page_xunbusy(ma[i]);
4752                         }
4753                         *mp = NULL;
4754                         return (rv);
4755                 }
4756                 for (i = 1; i < after; i++)
4757                         vm_page_readahead_finish(ma[i]);
4758                 MPASS(vm_page_all_valid(m));
4759         } else {
4760                 vm_page_zero_invalid(m, TRUE);
4761         }
4762 out:
4763         if ((allocflags & VM_ALLOC_WIRED) != 0)
4764                 vm_page_wire(m);
4765         if ((allocflags & VM_ALLOC_SBUSY) != 0 && vm_page_xbusied(m))
4766                 vm_page_busy_downgrade(m);
4767         else if ((allocflags & VM_ALLOC_NOBUSY) != 0)
4768                 vm_page_busy_release(m);
4769         *mp = m;
4770         return (VM_PAGER_OK);
4771 }
4772
4773 /*
4774  * Locklessly grab a valid page.  If the page is not valid or not yet
4775  * allocated this will fall back to the object lock method.
4776  */
4777 int
4778 vm_page_grab_valid_unlocked(vm_page_t *mp, vm_object_t object,
4779     vm_pindex_t pindex, int allocflags)
4780 {
4781         vm_page_t m;
4782         int flags;
4783         int error;
4784
4785         KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4786             (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4787             ("vm_page_grab_valid_unlocked: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY "
4788             "mismatch"));
4789         KASSERT((allocflags &
4790             (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL | VM_ALLOC_ZERO)) == 0,
4791             ("vm_page_grab_valid_unlocked: Invalid flags 0x%X", allocflags));
4792
4793         /*
4794          * Attempt a lockless lookup and busy.  We need at least an sbusy
4795          * before we can inspect the valid field and return a wired page.
4796          */
4797         flags = allocflags & ~(VM_ALLOC_NOBUSY | VM_ALLOC_WIRED);
4798         if (!vm_page_acquire_unlocked(object, pindex, NULL, mp, flags))
4799                 return (VM_PAGER_FAIL);
4800         if ((m = *mp) != NULL) {
4801                 if (vm_page_all_valid(m)) {
4802                         if ((allocflags & VM_ALLOC_WIRED) != 0)
4803                                 vm_page_wire(m);
4804                         vm_page_grab_release(m, allocflags);
4805                         return (VM_PAGER_OK);
4806                 }
4807                 vm_page_busy_release(m);
4808         }
4809         if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
4810                 *mp = NULL;
4811                 return (VM_PAGER_FAIL);
4812         }
4813         VM_OBJECT_WLOCK(object);
4814         error = vm_page_grab_valid(mp, object, pindex, allocflags);
4815         VM_OBJECT_WUNLOCK(object);
4816
4817         return (error);
4818 }
4819
4820 /*
4821  * Return the specified range of pages from the given object.  For each
4822  * page offset within the range, if a page already exists within the object
4823  * at that offset and it is busy, then wait for it to change state.  If,
4824  * instead, the page doesn't exist, then allocate it.
4825  *
4826  * The caller must always specify an allocation class.
4827  *
4828  * allocation classes:
4829  *      VM_ALLOC_NORMAL         normal process request
4830  *      VM_ALLOC_SYSTEM         system *really* needs the pages
4831  *
4832  * The caller must always specify that the pages are to be busied and/or
4833  * wired.
4834  *
4835  * optional allocation flags:
4836  *      VM_ALLOC_IGN_SBUSY      do not sleep on soft busy pages
4837  *      VM_ALLOC_NOBUSY         do not exclusive busy the page
4838  *      VM_ALLOC_NOWAIT         do not sleep
4839  *      VM_ALLOC_SBUSY          set page to sbusy state
4840  *      VM_ALLOC_WIRED          wire the pages
4841  *      VM_ALLOC_ZERO           zero and validate any invalid pages
4842  *
4843  * If VM_ALLOC_NOWAIT is not specified, this routine may sleep.  Otherwise, it
4844  * may return a partial prefix of the requested range.
4845  */
4846 int
4847 vm_page_grab_pages(vm_object_t object, vm_pindex_t pindex, int allocflags,
4848     vm_page_t *ma, int count)
4849 {
4850         vm_page_t m, mpred;
4851         int pflags;
4852         int i;
4853
4854         VM_OBJECT_ASSERT_WLOCKED(object);
4855         KASSERT(((u_int)allocflags >> VM_ALLOC_COUNT_SHIFT) == 0,
4856             ("vm_page_grap_pages: VM_ALLOC_COUNT() is not allowed"));
4857         KASSERT(count > 0,
4858             ("vm_page_grab_pages: invalid page count %d", count));
4859         vm_page_grab_check(allocflags);
4860
4861         pflags = vm_page_grab_pflags(allocflags);
4862         i = 0;
4863 retrylookup:
4864         m = vm_radix_lookup_le(&object->rtree, pindex + i);
4865         if (m == NULL || m->pindex != pindex + i) {
4866                 mpred = m;
4867                 m = NULL;
4868         } else
4869                 mpred = TAILQ_PREV(m, pglist, listq);
4870         for (; i < count; i++) {
4871                 if (m != NULL) {
4872                         if (!vm_page_tryacquire(m, allocflags)) {
4873                                 if (vm_page_grab_sleep(object, m, pindex + i,
4874                                     "grbmaw", allocflags, true))
4875                                         goto retrylookup;
4876                                 break;
4877                         }
4878                 } else {
4879                         if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4880                                 break;
4881                         m = vm_page_alloc_after(object, pindex + i,
4882                             pflags | VM_ALLOC_COUNT(count - i), mpred);
4883                         if (m == NULL) {
4884                                 if ((allocflags & (VM_ALLOC_NOWAIT |
4885                                     VM_ALLOC_WAITFAIL)) != 0)
4886                                         break;
4887                                 goto retrylookup;
4888                         }
4889                 }
4890                 if (vm_page_none_valid(m) &&
4891                     (allocflags & VM_ALLOC_ZERO) != 0) {
4892                         if ((m->flags & PG_ZERO) == 0)
4893                                 pmap_zero_page(m);
4894                         vm_page_valid(m);
4895                 }
4896                 vm_page_grab_release(m, allocflags);
4897                 ma[i] = mpred = m;
4898                 m = vm_page_next(m);
4899         }
4900         return (i);
4901 }
4902
4903 /*
4904  * Unlocked variant of vm_page_grab_pages().  This accepts the same flags
4905  * and will fall back to the locked variant to handle allocation.
4906  */
4907 int
4908 vm_page_grab_pages_unlocked(vm_object_t object, vm_pindex_t pindex,
4909     int allocflags, vm_page_t *ma, int count)
4910 {
4911         vm_page_t m, pred;
4912         int flags;
4913         int i;
4914
4915         KASSERT(count > 0,
4916             ("vm_page_grab_pages_unlocked: invalid page count %d", count));
4917         vm_page_grab_check(allocflags);
4918
4919         /*
4920          * Modify flags for lockless acquire to hold the page until we
4921          * set it valid if necessary.
4922          */
4923         flags = allocflags & ~VM_ALLOC_NOBUSY;
4924         pred = NULL;
4925         for (i = 0; i < count; i++, pindex++) {
4926                 if (!vm_page_acquire_unlocked(object, pindex, pred, &m, flags))
4927                         return (i);
4928                 if (m == NULL)
4929                         break;
4930                 if ((flags & VM_ALLOC_ZERO) != 0 && vm_page_none_valid(m)) {
4931                         if ((m->flags & PG_ZERO) == 0)
4932                                 pmap_zero_page(m);
4933                         vm_page_valid(m);
4934                 }
4935                 /* m will still be wired or busy according to flags. */
4936                 vm_page_grab_release(m, allocflags);
4937                 pred = ma[i] = m;
4938         }
4939         if (i == count || (allocflags & VM_ALLOC_NOCREAT) != 0)
4940                 return (i);
4941         count -= i;
4942         VM_OBJECT_WLOCK(object);
4943         i += vm_page_grab_pages(object, pindex, allocflags, &ma[i], count);
4944         VM_OBJECT_WUNLOCK(object);
4945
4946         return (i);
4947 }
4948
4949 /*
4950  * Mapping function for valid or dirty bits in a page.
4951  *
4952  * Inputs are required to range within a page.
4953  */
4954 vm_page_bits_t
4955 vm_page_bits(int base, int size)
4956 {
4957         int first_bit;
4958         int last_bit;
4959
4960         KASSERT(
4961             base + size <= PAGE_SIZE,
4962             ("vm_page_bits: illegal base/size %d/%d", base, size)
4963         );
4964
4965         if (size == 0)          /* handle degenerate case */
4966                 return (0);
4967
4968         first_bit = base >> DEV_BSHIFT;
4969         last_bit = (base + size - 1) >> DEV_BSHIFT;
4970
4971         return (((vm_page_bits_t)2 << last_bit) -
4972             ((vm_page_bits_t)1 << first_bit));
4973 }
4974
4975 void
4976 vm_page_bits_set(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t set)
4977 {
4978
4979 #if PAGE_SIZE == 32768
4980         atomic_set_64((uint64_t *)bits, set);
4981 #elif PAGE_SIZE == 16384
4982         atomic_set_32((uint32_t *)bits, set);
4983 #elif (PAGE_SIZE == 8192) && defined(atomic_set_16)
4984         atomic_set_16((uint16_t *)bits, set);
4985 #elif (PAGE_SIZE == 4096) && defined(atomic_set_8)
4986         atomic_set_8((uint8_t *)bits, set);
4987 #else           /* PAGE_SIZE <= 8192 */
4988         uintptr_t addr;
4989         int shift;
4990
4991         addr = (uintptr_t)bits;
4992         /*
4993          * Use a trick to perform a 32-bit atomic on the
4994          * containing aligned word, to not depend on the existence
4995          * of atomic_{set, clear}_{8, 16}.
4996          */
4997         shift = addr & (sizeof(uint32_t) - 1);
4998 #if BYTE_ORDER == BIG_ENDIAN
4999         shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
5000 #else
5001         shift *= NBBY;
5002 #endif
5003         addr &= ~(sizeof(uint32_t) - 1);
5004         atomic_set_32((uint32_t *)addr, set << shift);
5005 #endif          /* PAGE_SIZE */
5006 }
5007
5008 static inline void
5009 vm_page_bits_clear(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t clear)
5010 {
5011
5012 #if PAGE_SIZE == 32768
5013         atomic_clear_64((uint64_t *)bits, clear);
5014 #elif PAGE_SIZE == 16384
5015         atomic_clear_32((uint32_t *)bits, clear);
5016 #elif (PAGE_SIZE == 8192) && defined(atomic_clear_16)
5017         atomic_clear_16((uint16_t *)bits, clear);
5018 #elif (PAGE_SIZE == 4096) && defined(atomic_clear_8)
5019         atomic_clear_8((uint8_t *)bits, clear);
5020 #else           /* PAGE_SIZE <= 8192 */
5021         uintptr_t addr;
5022         int shift;
5023
5024         addr = (uintptr_t)bits;
5025         /*
5026          * Use a trick to perform a 32-bit atomic on the
5027          * containing aligned word, to not depend on the existence
5028          * of atomic_{set, clear}_{8, 16}.
5029          */
5030         shift = addr & (sizeof(uint32_t) - 1);
5031 #if BYTE_ORDER == BIG_ENDIAN
5032         shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
5033 #else
5034         shift *= NBBY;
5035 #endif
5036         addr &= ~(sizeof(uint32_t) - 1);
5037         atomic_clear_32((uint32_t *)addr, clear << shift);
5038 #endif          /* PAGE_SIZE */
5039 }
5040
5041 static inline vm_page_bits_t
5042 vm_page_bits_swap(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t newbits)
5043 {
5044 #if PAGE_SIZE == 32768
5045         uint64_t old;
5046
5047         old = *bits;
5048         while (atomic_fcmpset_64(bits, &old, newbits) == 0);
5049         return (old);
5050 #elif PAGE_SIZE == 16384
5051         uint32_t old;
5052
5053         old = *bits;
5054         while (atomic_fcmpset_32(bits, &old, newbits) == 0);
5055         return (old);
5056 #elif (PAGE_SIZE == 8192) && defined(atomic_fcmpset_16)
5057         uint16_t old;
5058
5059         old = *bits;
5060         while (atomic_fcmpset_16(bits, &old, newbits) == 0);
5061         return (old);
5062 #elif (PAGE_SIZE == 4096) && defined(atomic_fcmpset_8)
5063         uint8_t old;
5064
5065         old = *bits;
5066         while (atomic_fcmpset_8(bits, &old, newbits) == 0);
5067         return (old);
5068 #else           /* PAGE_SIZE <= 4096*/
5069         uintptr_t addr;
5070         uint32_t old, new, mask;
5071         int shift;
5072
5073         addr = (uintptr_t)bits;
5074         /*
5075          * Use a trick to perform a 32-bit atomic on the
5076          * containing aligned word, to not depend on the existence
5077          * of atomic_{set, swap, clear}_{8, 16}.
5078          */
5079         shift = addr & (sizeof(uint32_t) - 1);
5080 #if BYTE_ORDER == BIG_ENDIAN
5081         shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
5082 #else
5083         shift *= NBBY;
5084 #endif
5085         addr &= ~(sizeof(uint32_t) - 1);
5086         mask = VM_PAGE_BITS_ALL << shift;
5087
5088         old = *bits;
5089         do {
5090                 new = old & ~mask;
5091                 new |= newbits << shift;
5092         } while (atomic_fcmpset_32((uint32_t *)addr, &old, new) == 0);
5093         return (old >> shift);
5094 #endif          /* PAGE_SIZE */
5095 }
5096
5097 /*
5098  *      vm_page_set_valid_range:
5099  *
5100  *      Sets portions of a page valid.  The arguments are expected
5101  *      to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
5102  *      of any partial chunks touched by the range.  The invalid portion of
5103  *      such chunks will be zeroed.
5104  *
5105  *      (base + size) must be less then or equal to PAGE_SIZE.
5106  */
5107 void
5108 vm_page_set_valid_range(vm_page_t m, int base, int size)
5109 {
5110         int endoff, frag;
5111         vm_page_bits_t pagebits;
5112
5113         vm_page_assert_busied(m);
5114         if (size == 0)  /* handle degenerate case */
5115                 return;
5116
5117         /*
5118          * If the base is not DEV_BSIZE aligned and the valid
5119          * bit is clear, we have to zero out a portion of the
5120          * first block.
5121          */
5122         if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
5123             (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
5124                 pmap_zero_page_area(m, frag, base - frag);
5125
5126         /*
5127          * If the ending offset is not DEV_BSIZE aligned and the
5128          * valid bit is clear, we have to zero out a portion of
5129          * the last block.
5130          */
5131         endoff = base + size;
5132         if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
5133             (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
5134                 pmap_zero_page_area(m, endoff,
5135                     DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
5136
5137         /*
5138          * Assert that no previously invalid block that is now being validated
5139          * is already dirty.
5140          */
5141         KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
5142             ("vm_page_set_valid_range: page %p is dirty", m));
5143
5144         /*
5145          * Set valid bits inclusive of any overlap.
5146          */
5147         pagebits = vm_page_bits(base, size);
5148         if (vm_page_xbusied(m))
5149                 m->valid |= pagebits;
5150         else
5151                 vm_page_bits_set(m, &m->valid, pagebits);
5152 }
5153
5154 /*
5155  * Set the page dirty bits and free the invalid swap space if
5156  * present.  Returns the previous dirty bits.
5157  */
5158 vm_page_bits_t
5159 vm_page_set_dirty(vm_page_t m)
5160 {
5161         vm_page_bits_t old;
5162
5163         VM_PAGE_OBJECT_BUSY_ASSERT(m);
5164
5165         if (vm_page_xbusied(m) && !pmap_page_is_write_mapped(m)) {
5166                 old = m->dirty;
5167                 m->dirty = VM_PAGE_BITS_ALL;
5168         } else
5169                 old = vm_page_bits_swap(m, &m->dirty, VM_PAGE_BITS_ALL);
5170         if (old == 0 && (m->a.flags & PGA_SWAP_SPACE) != 0)
5171                 vm_pager_page_unswapped(m);
5172
5173         return (old);
5174 }
5175
5176 /*
5177  * Clear the given bits from the specified page's dirty field.
5178  */
5179 static __inline void
5180 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
5181 {
5182
5183         vm_page_assert_busied(m);
5184
5185         /*
5186          * If the page is xbusied and not write mapped we are the
5187          * only thread that can modify dirty bits.  Otherwise, The pmap
5188          * layer can call vm_page_dirty() without holding a distinguished
5189          * lock.  The combination of page busy and atomic operations
5190          * suffice to guarantee consistency of the page dirty field.
5191          */
5192         if (vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
5193                 m->dirty &= ~pagebits;
5194         else
5195                 vm_page_bits_clear(m, &m->dirty, pagebits);
5196 }
5197
5198 /*
5199  *      vm_page_set_validclean:
5200  *
5201  *      Sets portions of a page valid and clean.  The arguments are expected
5202  *      to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
5203  *      of any partial chunks touched by the range.  The invalid portion of
5204  *      such chunks will be zero'd.
5205  *
5206  *      (base + size) must be less then or equal to PAGE_SIZE.
5207  */
5208 void
5209 vm_page_set_validclean(vm_page_t m, int base, int size)
5210 {
5211         vm_page_bits_t oldvalid, pagebits;
5212         int endoff, frag;
5213
5214         vm_page_assert_busied(m);
5215         if (size == 0)  /* handle degenerate case */
5216                 return;
5217
5218         /*
5219          * If the base is not DEV_BSIZE aligned and the valid
5220          * bit is clear, we have to zero out a portion of the
5221          * first block.
5222          */
5223         if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
5224             (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
5225                 pmap_zero_page_area(m, frag, base - frag);
5226
5227         /*
5228          * If the ending offset is not DEV_BSIZE aligned and the
5229          * valid bit is clear, we have to zero out a portion of
5230          * the last block.
5231          */
5232         endoff = base + size;
5233         if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
5234             (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
5235                 pmap_zero_page_area(m, endoff,
5236                     DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
5237
5238         /*
5239          * Set valid, clear dirty bits.  If validating the entire
5240          * page we can safely clear the pmap modify bit.  We also
5241          * use this opportunity to clear the PGA_NOSYNC flag.  If a process
5242          * takes a write fault on a MAP_NOSYNC memory area the flag will
5243          * be set again.
5244          *
5245          * We set valid bits inclusive of any overlap, but we can only
5246          * clear dirty bits for DEV_BSIZE chunks that are fully within
5247          * the range.
5248          */
5249         oldvalid = m->valid;
5250         pagebits = vm_page_bits(base, size);
5251         if (vm_page_xbusied(m))
5252                 m->valid |= pagebits;
5253         else
5254                 vm_page_bits_set(m, &m->valid, pagebits);
5255 #if 0   /* NOT YET */
5256         if ((frag = base & (DEV_BSIZE - 1)) != 0) {
5257                 frag = DEV_BSIZE - frag;
5258                 base += frag;
5259                 size -= frag;
5260                 if (size < 0)
5261                         size = 0;
5262         }
5263         pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
5264 #endif
5265         if (base == 0 && size == PAGE_SIZE) {
5266                 /*
5267                  * The page can only be modified within the pmap if it is
5268                  * mapped, and it can only be mapped if it was previously
5269                  * fully valid.
5270                  */
5271                 if (oldvalid == VM_PAGE_BITS_ALL)
5272                         /*
5273                          * Perform the pmap_clear_modify() first.  Otherwise,
5274                          * a concurrent pmap operation, such as
5275                          * pmap_protect(), could clear a modification in the
5276                          * pmap and set the dirty field on the page before
5277                          * pmap_clear_modify() had begun and after the dirty
5278                          * field was cleared here.
5279                          */
5280                         pmap_clear_modify(m);
5281                 m->dirty = 0;
5282                 vm_page_aflag_clear(m, PGA_NOSYNC);
5283         } else if (oldvalid != VM_PAGE_BITS_ALL && vm_page_xbusied(m))
5284                 m->dirty &= ~pagebits;
5285         else
5286                 vm_page_clear_dirty_mask(m, pagebits);
5287 }
5288
5289 void
5290 vm_page_clear_dirty(vm_page_t m, int base, int size)
5291 {
5292
5293         vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
5294 }
5295
5296 /*
5297  *      vm_page_set_invalid:
5298  *
5299  *      Invalidates DEV_BSIZE'd chunks within a page.  Both the
5300  *      valid and dirty bits for the effected areas are cleared.
5301  */
5302 void
5303 vm_page_set_invalid(vm_page_t m, int base, int size)
5304 {
5305         vm_page_bits_t bits;
5306         vm_object_t object;
5307
5308         /*
5309          * The object lock is required so that pages can't be mapped
5310          * read-only while we're in the process of invalidating them.
5311          */
5312         object = m->object;
5313         VM_OBJECT_ASSERT_WLOCKED(object);
5314         vm_page_assert_busied(m);
5315
5316         if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
5317             size >= object->un_pager.vnp.vnp_size)
5318                 bits = VM_PAGE_BITS_ALL;
5319         else
5320                 bits = vm_page_bits(base, size);
5321         if (object->ref_count != 0 && vm_page_all_valid(m) && bits != 0)
5322                 pmap_remove_all(m);
5323         KASSERT((bits == 0 && vm_page_all_valid(m)) ||
5324             !pmap_page_is_mapped(m),
5325             ("vm_page_set_invalid: page %p is mapped", m));
5326         if (vm_page_xbusied(m)) {
5327                 m->valid &= ~bits;
5328                 m->dirty &= ~bits;
5329         } else {
5330                 vm_page_bits_clear(m, &m->valid, bits);
5331                 vm_page_bits_clear(m, &m->dirty, bits);
5332         }
5333 }
5334
5335 /*
5336  *      vm_page_invalid:
5337  *
5338  *      Invalidates the entire page.  The page must be busy, unmapped, and
5339  *      the enclosing object must be locked.  The object locks protects
5340  *      against concurrent read-only pmap enter which is done without
5341  *      busy.
5342  */
5343 void
5344 vm_page_invalid(vm_page_t m)
5345 {
5346
5347         vm_page_assert_busied(m);
5348         VM_OBJECT_ASSERT_LOCKED(m->object);
5349         MPASS(!pmap_page_is_mapped(m));
5350
5351         if (vm_page_xbusied(m))
5352                 m->valid = 0;
5353         else
5354                 vm_page_bits_clear(m, &m->valid, VM_PAGE_BITS_ALL);
5355 }
5356
5357 /*
5358  * vm_page_zero_invalid()
5359  *
5360  *      The kernel assumes that the invalid portions of a page contain
5361  *      garbage, but such pages can be mapped into memory by user code.
5362  *      When this occurs, we must zero out the non-valid portions of the
5363  *      page so user code sees what it expects.
5364  *
5365  *      Pages are most often semi-valid when the end of a file is mapped
5366  *      into memory and the file's size is not page aligned.
5367  */
5368 void
5369 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
5370 {
5371         int b;
5372         int i;
5373
5374         /*
5375          * Scan the valid bits looking for invalid sections that
5376          * must be zeroed.  Invalid sub-DEV_BSIZE'd areas ( where the
5377          * valid bit may be set ) have already been zeroed by
5378          * vm_page_set_validclean().
5379          */
5380         for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
5381                 if (i == (PAGE_SIZE / DEV_BSIZE) ||
5382                     (m->valid & ((vm_page_bits_t)1 << i))) {
5383                         if (i > b) {
5384                                 pmap_zero_page_area(m,
5385                                     b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
5386                         }
5387                         b = i + 1;
5388                 }
5389         }
5390
5391         /*
5392          * setvalid is TRUE when we can safely set the zero'd areas
5393          * as being valid.  We can do this if there are no cache consistancy
5394          * issues.  e.g. it is ok to do with UFS, but not ok to do with NFS.
5395          */
5396         if (setvalid)
5397                 vm_page_valid(m);
5398 }
5399
5400 /*
5401  *      vm_page_is_valid:
5402  *
5403  *      Is (partial) page valid?  Note that the case where size == 0
5404  *      will return FALSE in the degenerate case where the page is
5405  *      entirely invalid, and TRUE otherwise.
5406  *
5407  *      Some callers envoke this routine without the busy lock held and
5408  *      handle races via higher level locks.  Typical callers should
5409  *      hold a busy lock to prevent invalidation.
5410  */
5411 int
5412 vm_page_is_valid(vm_page_t m, int base, int size)
5413 {
5414         vm_page_bits_t bits;
5415
5416         bits = vm_page_bits(base, size);
5417         return (m->valid != 0 && (m->valid & bits) == bits);
5418 }
5419
5420 /*
5421  * Returns true if all of the specified predicates are true for the entire
5422  * (super)page and false otherwise.
5423  */
5424 bool
5425 vm_page_ps_test(vm_page_t m, int flags, vm_page_t skip_m)
5426 {
5427         vm_object_t object;
5428         int i, npages;
5429
5430         object = m->object;
5431         if (skip_m != NULL && skip_m->object != object)
5432                 return (false);
5433         VM_OBJECT_ASSERT_LOCKED(object);
5434         npages = atop(pagesizes[m->psind]);
5435
5436         /*
5437          * The physically contiguous pages that make up a superpage, i.e., a
5438          * page with a page size index ("psind") greater than zero, will
5439          * occupy adjacent entries in vm_page_array[].
5440          */
5441         for (i = 0; i < npages; i++) {
5442                 /* Always test object consistency, including "skip_m". */
5443                 if (m[i].object != object)
5444                         return (false);
5445                 if (&m[i] == skip_m)
5446                         continue;
5447                 if ((flags & PS_NONE_BUSY) != 0 && vm_page_busied(&m[i]))
5448                         return (false);
5449                 if ((flags & PS_ALL_DIRTY) != 0) {
5450                         /*
5451                          * Calling vm_page_test_dirty() or pmap_is_modified()
5452                          * might stop this case from spuriously returning
5453                          * "false".  However, that would require a write lock
5454                          * on the object containing "m[i]".
5455                          */
5456                         if (m[i].dirty != VM_PAGE_BITS_ALL)
5457                                 return (false);
5458                 }
5459                 if ((flags & PS_ALL_VALID) != 0 &&
5460                     m[i].valid != VM_PAGE_BITS_ALL)
5461                         return (false);
5462         }
5463         return (true);
5464 }
5465
5466 /*
5467  * Set the page's dirty bits if the page is modified.
5468  */
5469 void
5470 vm_page_test_dirty(vm_page_t m)
5471 {
5472
5473         vm_page_assert_busied(m);
5474         if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
5475                 vm_page_dirty(m);
5476 }
5477
5478 void
5479 vm_page_valid(vm_page_t m)
5480 {
5481
5482         vm_page_assert_busied(m);
5483         if (vm_page_xbusied(m))
5484                 m->valid = VM_PAGE_BITS_ALL;
5485         else
5486                 vm_page_bits_set(m, &m->valid, VM_PAGE_BITS_ALL);
5487 }
5488
5489 void
5490 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
5491 {
5492
5493         mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
5494 }
5495
5496 void
5497 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
5498 {
5499
5500         mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
5501 }
5502
5503 int
5504 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
5505 {
5506
5507         return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
5508 }
5509
5510 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
5511 void
5512 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
5513 {
5514
5515         vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
5516 }
5517
5518 void
5519 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
5520 {
5521
5522         mtx_assert_(vm_page_lockptr(m), a, file, line);
5523 }
5524 #endif
5525
5526 #ifdef INVARIANTS
5527 void
5528 vm_page_object_busy_assert(vm_page_t m)
5529 {
5530
5531         /*
5532          * Certain of the page's fields may only be modified by the
5533          * holder of a page or object busy.
5534          */
5535         if (m->object != NULL && !vm_page_busied(m))
5536                 VM_OBJECT_ASSERT_BUSY(m->object);
5537 }
5538
5539 void
5540 vm_page_assert_pga_writeable(vm_page_t m, uint16_t bits)
5541 {
5542
5543         if ((bits & PGA_WRITEABLE) == 0)
5544                 return;
5545
5546         /*
5547          * The PGA_WRITEABLE flag can only be set if the page is
5548          * managed, is exclusively busied or the object is locked.
5549          * Currently, this flag is only set by pmap_enter().
5550          */
5551         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5552             ("PGA_WRITEABLE on unmanaged page"));
5553         if (!vm_page_xbusied(m))
5554                 VM_OBJECT_ASSERT_BUSY(m->object);
5555 }
5556 #endif
5557
5558 #include "opt_ddb.h"
5559 #ifdef DDB
5560 #include <sys/kernel.h>
5561
5562 #include <ddb/ddb.h>
5563
5564 DB_SHOW_COMMAND(page, vm_page_print_page_info)
5565 {
5566
5567         db_printf("vm_cnt.v_free_count: %d\n", vm_free_count());
5568         db_printf("vm_cnt.v_inactive_count: %d\n", vm_inactive_count());
5569         db_printf("vm_cnt.v_active_count: %d\n", vm_active_count());
5570         db_printf("vm_cnt.v_laundry_count: %d\n", vm_laundry_count());
5571         db_printf("vm_cnt.v_wire_count: %d\n", vm_wire_count());
5572         db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
5573         db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
5574         db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
5575         db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
5576 }
5577
5578 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
5579 {
5580         int dom;
5581
5582         db_printf("pq_free %d\n", vm_free_count());
5583         for (dom = 0; dom < vm_ndomains; dom++) {
5584                 db_printf(
5585     "dom %d page_cnt %d free %d pq_act %d pq_inact %d pq_laund %d pq_unsw %d\n",
5586                     dom,
5587                     vm_dom[dom].vmd_page_count,
5588                     vm_dom[dom].vmd_free_count,
5589                     vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
5590                     vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
5591                     vm_dom[dom].vmd_pagequeues[PQ_LAUNDRY].pq_cnt,
5592                     vm_dom[dom].vmd_pagequeues[PQ_UNSWAPPABLE].pq_cnt);
5593         }
5594 }
5595
5596 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
5597 {
5598         vm_page_t m;
5599         boolean_t phys, virt;
5600
5601         if (!have_addr) {
5602                 db_printf("show pginfo addr\n");
5603                 return;
5604         }
5605
5606         phys = strchr(modif, 'p') != NULL;
5607         virt = strchr(modif, 'v') != NULL;
5608         if (virt)
5609                 m = PHYS_TO_VM_PAGE(pmap_kextract(addr));
5610         else if (phys)
5611                 m = PHYS_TO_VM_PAGE(addr);
5612         else
5613                 m = (vm_page_t)addr;
5614         db_printf(
5615     "page %p obj %p pidx 0x%jx phys 0x%jx q %d ref 0x%x\n"
5616     "  af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
5617             m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
5618             m->a.queue, m->ref_count, m->a.flags, m->oflags,
5619             m->flags, m->a.act_count, m->busy_lock, m->valid, m->dirty);
5620 }
5621 #endif /* DDB */