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