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