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