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