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