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