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