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