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