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