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