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