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