]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/vm/vm_page.c
vm_page_free_invalid(): Relax the xbusy assertion.
[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         KASSERT(m->object != NULL, ("page %p has no object", m));
1375         VM_OBJECT_ASSERT_WLOCKED(m->object);
1376
1377         /*
1378          * We may be attempting to free the page as part of the handling for an
1379          * I/O error, in which case the page was xbusied by a different thread.
1380          */
1381         vm_page_xbusy_claim(m);
1382
1383         /*
1384          * If someone has wired this page while the object lock
1385          * was not held, then the thread that unwires is responsible
1386          * for freeing the page.  Otherwise just free the page now.
1387          * The wire count of this unmapped page cannot change while
1388          * we have the page xbusy and the page's object wlocked.
1389          */
1390         if (vm_page_remove(m))
1391                 vm_page_free(m);
1392 }
1393
1394 /*
1395  *      vm_page_sleep_if_busy:
1396  *
1397  *      Sleep and release the object lock if the page is busied.
1398  *      Returns TRUE if the thread slept.
1399  *
1400  *      The given page must be unlocked and object containing it must
1401  *      be locked.
1402  */
1403 int
1404 vm_page_sleep_if_busy(vm_page_t m, const char *wmesg)
1405 {
1406         vm_object_t obj;
1407
1408         vm_page_lock_assert(m, MA_NOTOWNED);
1409         VM_OBJECT_ASSERT_WLOCKED(m->object);
1410
1411         /*
1412          * The page-specific object must be cached because page
1413          * identity can change during the sleep, causing the
1414          * re-lock of a different object.
1415          * It is assumed that a reference to the object is already
1416          * held by the callers.
1417          */
1418         obj = m->object;
1419         if (_vm_page_busy_sleep(obj, m, m->pindex, wmesg, 0, true)) {
1420                 VM_OBJECT_WLOCK(obj);
1421                 return (TRUE);
1422         }
1423         return (FALSE);
1424 }
1425
1426 /*
1427  *      vm_page_sleep_if_xbusy:
1428  *
1429  *      Sleep and release the object lock if the page is xbusied.
1430  *      Returns TRUE if the thread slept.
1431  *
1432  *      The given page must be unlocked and object containing it must
1433  *      be locked.
1434  */
1435 int
1436 vm_page_sleep_if_xbusy(vm_page_t m, const char *wmesg)
1437 {
1438         vm_object_t obj;
1439
1440         vm_page_lock_assert(m, MA_NOTOWNED);
1441         VM_OBJECT_ASSERT_WLOCKED(m->object);
1442
1443         /*
1444          * The page-specific object must be cached because page
1445          * identity can change during the sleep, causing the
1446          * re-lock of a different object.
1447          * It is assumed that a reference to the object is already
1448          * held by the callers.
1449          */
1450         obj = m->object;
1451         if (_vm_page_busy_sleep(obj, m, m->pindex, wmesg, VM_ALLOC_SBUSY,
1452             true)) {
1453                 VM_OBJECT_WLOCK(obj);
1454                 return (TRUE);
1455         }
1456         return (FALSE);
1457 }
1458
1459 /*
1460  *      vm_page_dirty_KBI:              [ internal use only ]
1461  *
1462  *      Set all bits in the page's dirty field.
1463  *
1464  *      The object containing the specified page must be locked if the
1465  *      call is made from the machine-independent layer.
1466  *
1467  *      See vm_page_clear_dirty_mask().
1468  *
1469  *      This function should only be called by vm_page_dirty().
1470  */
1471 void
1472 vm_page_dirty_KBI(vm_page_t m)
1473 {
1474
1475         /* Refer to this operation by its public name. */
1476         KASSERT(vm_page_all_valid(m), ("vm_page_dirty: page is invalid!"));
1477         m->dirty = VM_PAGE_BITS_ALL;
1478 }
1479
1480 /*
1481  *      vm_page_insert:         [ internal use only ]
1482  *
1483  *      Inserts the given mem entry into the object and object list.
1484  *
1485  *      The object must be locked.
1486  */
1487 int
1488 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1489 {
1490         vm_page_t mpred;
1491
1492         VM_OBJECT_ASSERT_WLOCKED(object);
1493         mpred = vm_radix_lookup_le(&object->rtree, pindex);
1494         return (vm_page_insert_after(m, object, pindex, mpred));
1495 }
1496
1497 /*
1498  *      vm_page_insert_after:
1499  *
1500  *      Inserts the page "m" into the specified object at offset "pindex".
1501  *
1502  *      The page "mpred" must immediately precede the offset "pindex" within
1503  *      the specified object.
1504  *
1505  *      The object must be locked.
1506  */
1507 static int
1508 vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
1509     vm_page_t mpred)
1510 {
1511         vm_page_t msucc;
1512
1513         VM_OBJECT_ASSERT_WLOCKED(object);
1514         KASSERT(m->object == NULL,
1515             ("vm_page_insert_after: page already inserted"));
1516         if (mpred != NULL) {
1517                 KASSERT(mpred->object == object,
1518                     ("vm_page_insert_after: object doesn't contain mpred"));
1519                 KASSERT(mpred->pindex < pindex,
1520                     ("vm_page_insert_after: mpred doesn't precede pindex"));
1521                 msucc = TAILQ_NEXT(mpred, listq);
1522         } else
1523                 msucc = TAILQ_FIRST(&object->memq);
1524         if (msucc != NULL)
1525                 KASSERT(msucc->pindex > pindex,
1526                     ("vm_page_insert_after: msucc doesn't succeed pindex"));
1527
1528         /*
1529          * Record the object/offset pair in this page.
1530          */
1531         m->object = object;
1532         m->pindex = pindex;
1533         m->ref_count |= VPRC_OBJREF;
1534
1535         /*
1536          * Now link into the object's ordered list of backed pages.
1537          */
1538         if (vm_radix_insert(&object->rtree, m)) {
1539                 m->object = NULL;
1540                 m->pindex = 0;
1541                 m->ref_count &= ~VPRC_OBJREF;
1542                 return (1);
1543         }
1544         vm_page_insert_radixdone(m, object, mpred);
1545         return (0);
1546 }
1547
1548 /*
1549  *      vm_page_insert_radixdone:
1550  *
1551  *      Complete page "m" insertion into the specified object after the
1552  *      radix trie hooking.
1553  *
1554  *      The page "mpred" must precede the offset "m->pindex" within the
1555  *      specified object.
1556  *
1557  *      The object must be locked.
1558  */
1559 static void
1560 vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1561 {
1562
1563         VM_OBJECT_ASSERT_WLOCKED(object);
1564         KASSERT(object != NULL && m->object == object,
1565             ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1566         KASSERT((m->ref_count & VPRC_OBJREF) != 0,
1567             ("vm_page_insert_radixdone: page %p is missing object ref", m));
1568         if (mpred != NULL) {
1569                 KASSERT(mpred->object == object,
1570                     ("vm_page_insert_radixdone: object doesn't contain mpred"));
1571                 KASSERT(mpred->pindex < m->pindex,
1572                     ("vm_page_insert_radixdone: mpred doesn't precede pindex"));
1573         }
1574
1575         if (mpred != NULL)
1576                 TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1577         else
1578                 TAILQ_INSERT_HEAD(&object->memq, m, listq);
1579
1580         /*
1581          * Show that the object has one more resident page.
1582          */
1583         object->resident_page_count++;
1584
1585         /*
1586          * Hold the vnode until the last page is released.
1587          */
1588         if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1589                 vhold(object->handle);
1590
1591         /*
1592          * Since we are inserting a new and possibly dirty page,
1593          * update the object's generation count.
1594          */
1595         if (pmap_page_is_write_mapped(m))
1596                 vm_object_set_writeable_dirty(object);
1597 }
1598
1599 /*
1600  * Do the work to remove a page from its object.  The caller is responsible for
1601  * updating the page's fields to reflect this removal.
1602  */
1603 static void
1604 vm_page_object_remove(vm_page_t m)
1605 {
1606         vm_object_t object;
1607         vm_page_t mrem;
1608
1609         vm_page_assert_xbusied(m);
1610         object = m->object;
1611         VM_OBJECT_ASSERT_WLOCKED(object);
1612         KASSERT((m->ref_count & VPRC_OBJREF) != 0,
1613             ("page %p is missing its object ref", m));
1614
1615         /* Deferred free of swap space. */
1616         if ((m->a.flags & PGA_SWAP_FREE) != 0)
1617                 vm_pager_page_unswapped(m);
1618
1619         m->object = NULL;
1620         mrem = vm_radix_remove(&object->rtree, m->pindex);
1621         KASSERT(mrem == m, ("removed page %p, expected page %p", mrem, m));
1622
1623         /*
1624          * Now remove from the object's list of backed pages.
1625          */
1626         TAILQ_REMOVE(&object->memq, m, listq);
1627
1628         /*
1629          * And show that the object has one fewer resident page.
1630          */
1631         object->resident_page_count--;
1632
1633         /*
1634          * The vnode may now be recycled.
1635          */
1636         if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1637                 vdrop(object->handle);
1638 }
1639
1640 /*
1641  *      vm_page_remove:
1642  *
1643  *      Removes the specified page from its containing object, but does not
1644  *      invalidate any backing storage.  Returns true if the object's reference
1645  *      was the last reference to the page, and false otherwise.
1646  *
1647  *      The object must be locked and the page must be exclusively busied.
1648  *      The exclusive busy will be released on return.  If this is not the
1649  *      final ref and the caller does not hold a wire reference it may not
1650  *      continue to access the page.
1651  */
1652 bool
1653 vm_page_remove(vm_page_t m)
1654 {
1655         bool dropped;
1656
1657         dropped = vm_page_remove_xbusy(m);
1658         vm_page_xunbusy(m);
1659
1660         return (dropped);
1661 }
1662
1663 /*
1664  *      vm_page_remove_xbusy
1665  *
1666  *      Removes the page but leaves the xbusy held.  Returns true if this
1667  *      removed the final ref and false otherwise.
1668  */
1669 bool
1670 vm_page_remove_xbusy(vm_page_t m)
1671 {
1672
1673         vm_page_object_remove(m);
1674         return (vm_page_drop(m, VPRC_OBJREF) == VPRC_OBJREF);
1675 }
1676
1677 /*
1678  *      vm_page_lookup:
1679  *
1680  *      Returns the page associated with the object/offset
1681  *      pair specified; if none is found, NULL is returned.
1682  *
1683  *      The object must be locked.
1684  */
1685 vm_page_t
1686 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1687 {
1688
1689         VM_OBJECT_ASSERT_LOCKED(object);
1690         return (vm_radix_lookup(&object->rtree, pindex));
1691 }
1692
1693 /*
1694  *      vm_page_relookup:
1695  *
1696  *      Returns a page that must already have been busied by
1697  *      the caller.  Used for bogus page replacement.
1698  */
1699 vm_page_t
1700 vm_page_relookup(vm_object_t object, vm_pindex_t pindex)
1701 {
1702         vm_page_t m;
1703
1704         m = vm_radix_lookup_unlocked(&object->rtree, pindex);
1705         KASSERT(m != NULL && (vm_page_busied(m) || vm_page_wired(m)) &&
1706             m->object == object && m->pindex == pindex,
1707             ("vm_page_relookup: Invalid page %p", m));
1708         return (m);
1709 }
1710
1711 /*
1712  * This should only be used by lockless functions for releasing transient
1713  * incorrect acquires.  The page may have been freed after we acquired a
1714  * busy lock.  In this case busy_lock == VPB_FREED and we have nothing
1715  * further to do.
1716  */
1717 static void
1718 vm_page_busy_release(vm_page_t m)
1719 {
1720         u_int x;
1721
1722         x = atomic_load_int(&m->busy_lock);
1723         for (;;) {
1724                 if (x == VPB_FREED)
1725                         break;
1726                 if ((x & VPB_BIT_SHARED) != 0 && VPB_SHARERS(x) > 1) {
1727                         if (atomic_fcmpset_int(&m->busy_lock, &x,
1728                             x - VPB_ONE_SHARER))
1729                                 break;
1730                         continue;
1731                 }
1732                 KASSERT((x & VPB_BIT_SHARED) != 0 ||
1733                     (x & ~VPB_BIT_WAITERS) == VPB_CURTHREAD_EXCLUSIVE,
1734                     ("vm_page_busy_release: %p xbusy not owned.", m));
1735                 if (!atomic_fcmpset_rel_int(&m->busy_lock, &x, VPB_UNBUSIED))
1736                         continue;
1737                 if ((x & VPB_BIT_WAITERS) != 0)
1738                         wakeup(m);
1739                 break;
1740         }
1741 }
1742
1743 /*
1744  *      vm_page_find_least:
1745  *
1746  *      Returns the page associated with the object with least pindex
1747  *      greater than or equal to the parameter pindex, or NULL.
1748  *
1749  *      The object must be locked.
1750  */
1751 vm_page_t
1752 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1753 {
1754         vm_page_t m;
1755
1756         VM_OBJECT_ASSERT_LOCKED(object);
1757         if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1758                 m = vm_radix_lookup_ge(&object->rtree, pindex);
1759         return (m);
1760 }
1761
1762 /*
1763  * Returns the given page's successor (by pindex) within the object if it is
1764  * resident; if none is found, NULL is returned.
1765  *
1766  * The object must be locked.
1767  */
1768 vm_page_t
1769 vm_page_next(vm_page_t m)
1770 {
1771         vm_page_t next;
1772
1773         VM_OBJECT_ASSERT_LOCKED(m->object);
1774         if ((next = TAILQ_NEXT(m, listq)) != NULL) {
1775                 MPASS(next->object == m->object);
1776                 if (next->pindex != m->pindex + 1)
1777                         next = NULL;
1778         }
1779         return (next);
1780 }
1781
1782 /*
1783  * Returns the given page's predecessor (by pindex) within the object if it is
1784  * resident; if none is found, NULL is returned.
1785  *
1786  * The object must be locked.
1787  */
1788 vm_page_t
1789 vm_page_prev(vm_page_t m)
1790 {
1791         vm_page_t prev;
1792
1793         VM_OBJECT_ASSERT_LOCKED(m->object);
1794         if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL) {
1795                 MPASS(prev->object == m->object);
1796                 if (prev->pindex != m->pindex - 1)
1797                         prev = NULL;
1798         }
1799         return (prev);
1800 }
1801
1802 /*
1803  * Uses the page mnew as a replacement for an existing page at index
1804  * pindex which must be already present in the object.
1805  *
1806  * Both pages must be exclusively busied on enter.  The old page is
1807  * unbusied on exit.
1808  *
1809  * A return value of true means mold is now free.  If this is not the
1810  * final ref and the caller does not hold a wire reference it may not
1811  * continue to access the page.
1812  */
1813 static bool
1814 vm_page_replace_hold(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex,
1815     vm_page_t mold)
1816 {
1817         vm_page_t mret;
1818         bool dropped;
1819
1820         VM_OBJECT_ASSERT_WLOCKED(object);
1821         vm_page_assert_xbusied(mold);
1822         KASSERT(mnew->object == NULL && (mnew->ref_count & VPRC_OBJREF) == 0,
1823             ("vm_page_replace: page %p already in object", mnew));
1824
1825         /*
1826          * This function mostly follows vm_page_insert() and
1827          * vm_page_remove() without the radix, object count and vnode
1828          * dance.  Double check such functions for more comments.
1829          */
1830
1831         mnew->object = object;
1832         mnew->pindex = pindex;
1833         atomic_set_int(&mnew->ref_count, VPRC_OBJREF);
1834         mret = vm_radix_replace(&object->rtree, mnew);
1835         KASSERT(mret == mold,
1836             ("invalid page replacement, mold=%p, mret=%p", mold, mret));
1837         KASSERT((mold->oflags & VPO_UNMANAGED) ==
1838             (mnew->oflags & VPO_UNMANAGED),
1839             ("vm_page_replace: mismatched VPO_UNMANAGED"));
1840
1841         /* Keep the resident page list in sorted order. */
1842         TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
1843         TAILQ_REMOVE(&object->memq, mold, listq);
1844         mold->object = NULL;
1845
1846         /*
1847          * The object's resident_page_count does not change because we have
1848          * swapped one page for another, but the generation count should
1849          * change if the page is dirty.
1850          */
1851         if (pmap_page_is_write_mapped(mnew))
1852                 vm_object_set_writeable_dirty(object);
1853         dropped = vm_page_drop(mold, VPRC_OBJREF) == VPRC_OBJREF;
1854         vm_page_xunbusy(mold);
1855
1856         return (dropped);
1857 }
1858
1859 void
1860 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex,
1861     vm_page_t mold)
1862 {
1863
1864         vm_page_assert_xbusied(mnew);
1865
1866         if (vm_page_replace_hold(mnew, object, pindex, mold))
1867                 vm_page_free(mold);
1868 }
1869
1870 /*
1871  *      vm_page_rename:
1872  *
1873  *      Move the given memory entry from its
1874  *      current object to the specified target object/offset.
1875  *
1876  *      Note: swap associated with the page must be invalidated by the move.  We
1877  *            have to do this for several reasons:  (1) we aren't freeing the
1878  *            page, (2) we are dirtying the page, (3) the VM system is probably
1879  *            moving the page from object A to B, and will then later move
1880  *            the backing store from A to B and we can't have a conflict.
1881  *
1882  *      Note: we *always* dirty the page.  It is necessary both for the
1883  *            fact that we moved it, and because we may be invalidating
1884  *            swap.
1885  *
1886  *      The objects must be locked.
1887  */
1888 int
1889 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1890 {
1891         vm_page_t mpred;
1892         vm_pindex_t opidx;
1893
1894         VM_OBJECT_ASSERT_WLOCKED(new_object);
1895
1896         KASSERT(m->ref_count != 0, ("vm_page_rename: page %p has no refs", m));
1897         mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1898         KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1899             ("vm_page_rename: pindex already renamed"));
1900
1901         /*
1902          * Create a custom version of vm_page_insert() which does not depend
1903          * by m_prev and can cheat on the implementation aspects of the
1904          * function.
1905          */
1906         opidx = m->pindex;
1907         m->pindex = new_pindex;
1908         if (vm_radix_insert(&new_object->rtree, m)) {
1909                 m->pindex = opidx;
1910                 return (1);
1911         }
1912
1913         /*
1914          * The operation cannot fail anymore.  The removal must happen before
1915          * the listq iterator is tainted.
1916          */
1917         m->pindex = opidx;
1918         vm_page_object_remove(m);
1919
1920         /* Return back to the new pindex to complete vm_page_insert(). */
1921         m->pindex = new_pindex;
1922         m->object = new_object;
1923
1924         vm_page_insert_radixdone(m, new_object, mpred);
1925         vm_page_dirty(m);
1926         return (0);
1927 }
1928
1929 /*
1930  *      vm_page_alloc:
1931  *
1932  *      Allocate and return a page that is associated with the specified
1933  *      object and offset pair.  By default, this page is exclusive busied.
1934  *
1935  *      The caller must always specify an allocation class.
1936  *
1937  *      allocation classes:
1938  *      VM_ALLOC_NORMAL         normal process request
1939  *      VM_ALLOC_SYSTEM         system *really* needs a page
1940  *      VM_ALLOC_INTERRUPT      interrupt time request
1941  *
1942  *      optional allocation flags:
1943  *      VM_ALLOC_COUNT(number)  the number of additional pages that the caller
1944  *                              intends to allocate
1945  *      VM_ALLOC_NOBUSY         do not exclusive busy the page
1946  *      VM_ALLOC_NODUMP         do not include the page in a kernel core dump
1947  *      VM_ALLOC_NOOBJ          page is not associated with an object and
1948  *                              should not be exclusive busy
1949  *      VM_ALLOC_SBUSY          shared busy the allocated page
1950  *      VM_ALLOC_WIRED          wire the allocated page
1951  *      VM_ALLOC_ZERO           prefer a zeroed page
1952  */
1953 vm_page_t
1954 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1955 {
1956
1957         return (vm_page_alloc_after(object, pindex, req, object != NULL ?
1958             vm_radix_lookup_le(&object->rtree, pindex) : NULL));
1959 }
1960
1961 vm_page_t
1962 vm_page_alloc_domain(vm_object_t object, vm_pindex_t pindex, int domain,
1963     int req)
1964 {
1965
1966         return (vm_page_alloc_domain_after(object, pindex, domain, req,
1967             object != NULL ? vm_radix_lookup_le(&object->rtree, pindex) :
1968             NULL));
1969 }
1970
1971 /*
1972  * Allocate a page in the specified object with the given page index.  To
1973  * optimize insertion of the page into the object, the caller must also specifiy
1974  * the resident page in the object with largest index smaller than the given
1975  * page index, or NULL if no such page exists.
1976  */
1977 vm_page_t
1978 vm_page_alloc_after(vm_object_t object, vm_pindex_t pindex,
1979     int req, vm_page_t mpred)
1980 {
1981         struct vm_domainset_iter di;
1982         vm_page_t m;
1983         int domain;
1984
1985         vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
1986         do {
1987                 m = vm_page_alloc_domain_after(object, pindex, domain, req,
1988                     mpred);
1989                 if (m != NULL)
1990                         break;
1991         } while (vm_domainset_iter_page(&di, object, &domain) == 0);
1992
1993         return (m);
1994 }
1995
1996 /*
1997  * Returns true if the number of free pages exceeds the minimum
1998  * for the request class and false otherwise.
1999  */
2000 static int
2001 _vm_domain_allocate(struct vm_domain *vmd, int req_class, int npages)
2002 {
2003         u_int limit, old, new;
2004
2005         if (req_class == VM_ALLOC_INTERRUPT)
2006                 limit = 0;
2007         else if (req_class == VM_ALLOC_SYSTEM)
2008                 limit = vmd->vmd_interrupt_free_min;
2009         else
2010                 limit = vmd->vmd_free_reserved;
2011
2012         /*
2013          * Attempt to reserve the pages.  Fail if we're below the limit.
2014          */
2015         limit += npages;
2016         old = vmd->vmd_free_count;
2017         do {
2018                 if (old < limit)
2019                         return (0);
2020                 new = old - npages;
2021         } while (atomic_fcmpset_int(&vmd->vmd_free_count, &old, new) == 0);
2022
2023         /* Wake the page daemon if we've crossed the threshold. */
2024         if (vm_paging_needed(vmd, new) && !vm_paging_needed(vmd, old))
2025                 pagedaemon_wakeup(vmd->vmd_domain);
2026
2027         /* Only update bitsets on transitions. */
2028         if ((old >= vmd->vmd_free_min && new < vmd->vmd_free_min) ||
2029             (old >= vmd->vmd_free_severe && new < vmd->vmd_free_severe))
2030                 vm_domain_set(vmd);
2031
2032         return (1);
2033 }
2034
2035 int
2036 vm_domain_allocate(struct vm_domain *vmd, int req, int npages)
2037 {
2038         int req_class;
2039
2040         /*
2041          * The page daemon is allowed to dig deeper into the free page list.
2042          */
2043         req_class = req & VM_ALLOC_CLASS_MASK;
2044         if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2045                 req_class = VM_ALLOC_SYSTEM;
2046         return (_vm_domain_allocate(vmd, req_class, npages));
2047 }
2048
2049 vm_page_t
2050 vm_page_alloc_domain_after(vm_object_t object, vm_pindex_t pindex, int domain,
2051     int req, vm_page_t mpred)
2052 {
2053         struct vm_domain *vmd;
2054         vm_page_t m;
2055         int flags, pool;
2056
2057         KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
2058             (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
2059             ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
2060             (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
2061             ("inconsistent object(%p)/req(%x)", object, req));
2062         KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
2063             ("Can't sleep and retry object insertion."));
2064         KASSERT(mpred == NULL || mpred->pindex < pindex,
2065             ("mpred %p doesn't precede pindex 0x%jx", mpred,
2066             (uintmax_t)pindex));
2067         if (object != NULL)
2068                 VM_OBJECT_ASSERT_WLOCKED(object);
2069
2070         flags = 0;
2071         m = NULL;
2072         pool = object != NULL ? VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT;
2073 again:
2074 #if VM_NRESERVLEVEL > 0
2075         /*
2076          * Can we allocate the page from a reservation?
2077          */
2078         if (vm_object_reserv(object) &&
2079             (m = vm_reserv_alloc_page(object, pindex, domain, req, mpred)) !=
2080             NULL) {
2081                 goto found;
2082         }
2083 #endif
2084         vmd = VM_DOMAIN(domain);
2085         if (vmd->vmd_pgcache[pool].zone != NULL) {
2086                 m = uma_zalloc(vmd->vmd_pgcache[pool].zone, M_NOWAIT | M_NOVM);
2087                 if (m != NULL) {
2088                         flags |= PG_PCPU_CACHE;
2089                         goto found;
2090                 }
2091         }
2092         if (vm_domain_allocate(vmd, req, 1)) {
2093                 /*
2094                  * If not, allocate it from the free page queues.
2095                  */
2096                 vm_domain_free_lock(vmd);
2097                 m = vm_phys_alloc_pages(domain, pool, 0);
2098                 vm_domain_free_unlock(vmd);
2099                 if (m == NULL) {
2100                         vm_domain_freecnt_inc(vmd, 1);
2101 #if VM_NRESERVLEVEL > 0
2102                         if (vm_reserv_reclaim_inactive(domain))
2103                                 goto again;
2104 #endif
2105                 }
2106         }
2107         if (m == NULL) {
2108                 /*
2109                  * Not allocatable, give up.
2110                  */
2111                 if (vm_domain_alloc_fail(vmd, object, req))
2112                         goto again;
2113                 return (NULL);
2114         }
2115
2116         /*
2117          * At this point we had better have found a good page.
2118          */
2119 found:
2120         vm_page_dequeue(m);
2121         vm_page_alloc_check(m);
2122
2123         /*
2124          * Initialize the page.  Only the PG_ZERO flag is inherited.
2125          */
2126         if ((req & VM_ALLOC_ZERO) != 0)
2127                 flags |= (m->flags & PG_ZERO);
2128         if ((req & VM_ALLOC_NODUMP) != 0)
2129                 flags |= PG_NODUMP;
2130         m->flags = flags;
2131         m->a.flags = 0;
2132         m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
2133             VPO_UNMANAGED : 0;
2134         if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
2135                 m->busy_lock = VPB_CURTHREAD_EXCLUSIVE;
2136         else if ((req & VM_ALLOC_SBUSY) != 0)
2137                 m->busy_lock = VPB_SHARERS_WORD(1);
2138         else
2139                 m->busy_lock = VPB_UNBUSIED;
2140         if (req & VM_ALLOC_WIRED) {
2141                 vm_wire_add(1);
2142                 m->ref_count = 1;
2143         }
2144         m->a.act_count = 0;
2145
2146         if (object != NULL) {
2147                 if (vm_page_insert_after(m, object, pindex, mpred)) {
2148                         if (req & VM_ALLOC_WIRED) {
2149                                 vm_wire_sub(1);
2150                                 m->ref_count = 0;
2151                         }
2152                         KASSERT(m->object == NULL, ("page %p has object", m));
2153                         m->oflags = VPO_UNMANAGED;
2154                         m->busy_lock = VPB_UNBUSIED;
2155                         /* Don't change PG_ZERO. */
2156                         vm_page_free_toq(m);
2157                         if (req & VM_ALLOC_WAITFAIL) {
2158                                 VM_OBJECT_WUNLOCK(object);
2159                                 vm_radix_wait();
2160                                 VM_OBJECT_WLOCK(object);
2161                         }
2162                         return (NULL);
2163                 }
2164
2165                 /* Ignore device objects; the pager sets "memattr" for them. */
2166                 if (object->memattr != VM_MEMATTR_DEFAULT &&
2167                     (object->flags & OBJ_FICTITIOUS) == 0)
2168                         pmap_page_set_memattr(m, object->memattr);
2169         } else
2170                 m->pindex = pindex;
2171
2172         return (m);
2173 }
2174
2175 /*
2176  *      vm_page_alloc_contig:
2177  *
2178  *      Allocate a contiguous set of physical pages of the given size "npages"
2179  *      from the free lists.  All of the physical pages must be at or above
2180  *      the given physical address "low" and below the given physical address
2181  *      "high".  The given value "alignment" determines the alignment of the
2182  *      first physical page in the set.  If the given value "boundary" is
2183  *      non-zero, then the set of physical pages cannot cross any physical
2184  *      address boundary that is a multiple of that value.  Both "alignment"
2185  *      and "boundary" must be a power of two.
2186  *
2187  *      If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
2188  *      then the memory attribute setting for the physical pages is configured
2189  *      to the object's memory attribute setting.  Otherwise, the memory
2190  *      attribute setting for the physical pages is configured to "memattr",
2191  *      overriding the object's memory attribute setting.  However, if the
2192  *      object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
2193  *      memory attribute setting for the physical pages cannot be configured
2194  *      to VM_MEMATTR_DEFAULT.
2195  *
2196  *      The specified object may not contain fictitious pages.
2197  *
2198  *      The caller must always specify an allocation class.
2199  *
2200  *      allocation classes:
2201  *      VM_ALLOC_NORMAL         normal process request
2202  *      VM_ALLOC_SYSTEM         system *really* needs a page
2203  *      VM_ALLOC_INTERRUPT      interrupt time request
2204  *
2205  *      optional allocation flags:
2206  *      VM_ALLOC_NOBUSY         do not exclusive busy the page
2207  *      VM_ALLOC_NODUMP         do not include the page in a kernel core dump
2208  *      VM_ALLOC_NOOBJ          page is not associated with an object and
2209  *                              should not be exclusive busy
2210  *      VM_ALLOC_SBUSY          shared busy the allocated page
2211  *      VM_ALLOC_WIRED          wire the allocated page
2212  *      VM_ALLOC_ZERO           prefer a zeroed page
2213  */
2214 vm_page_t
2215 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
2216     u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
2217     vm_paddr_t boundary, vm_memattr_t memattr)
2218 {
2219         struct vm_domainset_iter di;
2220         vm_page_t m;
2221         int domain;
2222
2223         vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
2224         do {
2225                 m = vm_page_alloc_contig_domain(object, pindex, domain, req,
2226                     npages, low, high, alignment, boundary, memattr);
2227                 if (m != NULL)
2228                         break;
2229         } while (vm_domainset_iter_page(&di, object, &domain) == 0);
2230
2231         return (m);
2232 }
2233
2234 vm_page_t
2235 vm_page_alloc_contig_domain(vm_object_t object, vm_pindex_t pindex, int domain,
2236     int req, u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
2237     vm_paddr_t boundary, vm_memattr_t memattr)
2238 {
2239         struct vm_domain *vmd;
2240         vm_page_t m, m_ret, mpred;
2241         u_int busy_lock, flags, oflags;
2242
2243         mpred = NULL;   /* XXX: pacify gcc */
2244         KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
2245             (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
2246             ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
2247             (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
2248             ("vm_page_alloc_contig: inconsistent object(%p)/req(%x)", object,
2249             req));
2250         KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
2251             ("Can't sleep and retry object insertion."));
2252         if (object != NULL) {
2253                 VM_OBJECT_ASSERT_WLOCKED(object);
2254                 KASSERT((object->flags & OBJ_FICTITIOUS) == 0,
2255                     ("vm_page_alloc_contig: object %p has fictitious pages",
2256                     object));
2257         }
2258         KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
2259
2260         if (object != NULL) {
2261                 mpred = vm_radix_lookup_le(&object->rtree, pindex);
2262                 KASSERT(mpred == NULL || mpred->pindex != pindex,
2263                     ("vm_page_alloc_contig: pindex already allocated"));
2264         }
2265
2266         /*
2267          * Can we allocate the pages without the number of free pages falling
2268          * below the lower bound for the allocation class?
2269          */
2270         m_ret = NULL;
2271 again:
2272 #if VM_NRESERVLEVEL > 0
2273         /*
2274          * Can we allocate the pages from a reservation?
2275          */
2276         if (vm_object_reserv(object) &&
2277             (m_ret = vm_reserv_alloc_contig(object, pindex, domain, req,
2278             mpred, npages, low, high, alignment, boundary)) != NULL) {
2279                 goto found;
2280         }
2281 #endif
2282         vmd = VM_DOMAIN(domain);
2283         if (vm_domain_allocate(vmd, req, npages)) {
2284                 /*
2285                  * allocate them from the free page queues.
2286                  */
2287                 vm_domain_free_lock(vmd);
2288                 m_ret = vm_phys_alloc_contig(domain, npages, low, high,
2289                     alignment, boundary);
2290                 vm_domain_free_unlock(vmd);
2291                 if (m_ret == NULL) {
2292                         vm_domain_freecnt_inc(vmd, npages);
2293 #if VM_NRESERVLEVEL > 0
2294                         if (vm_reserv_reclaim_contig(domain, npages, low,
2295                             high, alignment, boundary))
2296                                 goto again;
2297 #endif
2298                 }
2299         }
2300         if (m_ret == NULL) {
2301                 if (vm_domain_alloc_fail(vmd, object, req))
2302                         goto again;
2303                 return (NULL);
2304         }
2305 #if VM_NRESERVLEVEL > 0
2306 found:
2307 #endif
2308         for (m = m_ret; m < &m_ret[npages]; m++) {
2309                 vm_page_dequeue(m);
2310                 vm_page_alloc_check(m);
2311         }
2312
2313         /*
2314          * Initialize the pages.  Only the PG_ZERO flag is inherited.
2315          */
2316         flags = 0;
2317         if ((req & VM_ALLOC_ZERO) != 0)
2318                 flags = PG_ZERO;
2319         if ((req & VM_ALLOC_NODUMP) != 0)
2320                 flags |= PG_NODUMP;
2321         oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
2322             VPO_UNMANAGED : 0;
2323         if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
2324                 busy_lock = VPB_CURTHREAD_EXCLUSIVE;
2325         else if ((req & VM_ALLOC_SBUSY) != 0)
2326                 busy_lock = VPB_SHARERS_WORD(1);
2327         else
2328                 busy_lock = VPB_UNBUSIED;
2329         if ((req & VM_ALLOC_WIRED) != 0)
2330                 vm_wire_add(npages);
2331         if (object != NULL) {
2332                 if (object->memattr != VM_MEMATTR_DEFAULT &&
2333                     memattr == VM_MEMATTR_DEFAULT)
2334                         memattr = object->memattr;
2335         }
2336         for (m = m_ret; m < &m_ret[npages]; m++) {
2337                 m->a.flags = 0;
2338                 m->flags = (m->flags | PG_NODUMP) & flags;
2339                 m->busy_lock = busy_lock;
2340                 if ((req & VM_ALLOC_WIRED) != 0)
2341                         m->ref_count = 1;
2342                 m->a.act_count = 0;
2343                 m->oflags = oflags;
2344                 if (object != NULL) {
2345                         if (vm_page_insert_after(m, object, pindex, mpred)) {
2346                                 if ((req & VM_ALLOC_WIRED) != 0)
2347                                         vm_wire_sub(npages);
2348                                 KASSERT(m->object == NULL,
2349                                     ("page %p has object", m));
2350                                 mpred = m;
2351                                 for (m = m_ret; m < &m_ret[npages]; m++) {
2352                                         if (m <= mpred &&
2353                                             (req & VM_ALLOC_WIRED) != 0)
2354                                                 m->ref_count = 0;
2355                                         m->oflags = VPO_UNMANAGED;
2356                                         m->busy_lock = VPB_UNBUSIED;
2357                                         /* Don't change PG_ZERO. */
2358                                         vm_page_free_toq(m);
2359                                 }
2360                                 if (req & VM_ALLOC_WAITFAIL) {
2361                                         VM_OBJECT_WUNLOCK(object);
2362                                         vm_radix_wait();
2363                                         VM_OBJECT_WLOCK(object);
2364                                 }
2365                                 return (NULL);
2366                         }
2367                         mpred = m;
2368                 } else
2369                         m->pindex = pindex;
2370                 if (memattr != VM_MEMATTR_DEFAULT)
2371                         pmap_page_set_memattr(m, memattr);
2372                 pindex++;
2373         }
2374         return (m_ret);
2375 }
2376
2377 /*
2378  * Check a page that has been freshly dequeued from a freelist.
2379  */
2380 static void
2381 vm_page_alloc_check(vm_page_t m)
2382 {
2383
2384         KASSERT(m->object == NULL, ("page %p has object", m));
2385         KASSERT(m->a.queue == PQ_NONE &&
2386             (m->a.flags & PGA_QUEUE_STATE_MASK) == 0,
2387             ("page %p has unexpected queue %d, flags %#x",
2388             m, m->a.queue, (m->a.flags & PGA_QUEUE_STATE_MASK)));
2389         KASSERT(m->ref_count == 0, ("page %p has references", m));
2390         KASSERT(vm_page_busy_freed(m), ("page %p is not freed", m));
2391         KASSERT(m->dirty == 0, ("page %p is dirty", m));
2392         KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
2393             ("page %p has unexpected memattr %d",
2394             m, pmap_page_get_memattr(m)));
2395         KASSERT(m->valid == 0, ("free page %p is valid", m));
2396 }
2397
2398 /*
2399  *      vm_page_alloc_freelist:
2400  *
2401  *      Allocate a physical page from the specified free page list.
2402  *
2403  *      The caller must always specify an allocation class.
2404  *
2405  *      allocation classes:
2406  *      VM_ALLOC_NORMAL         normal process request
2407  *      VM_ALLOC_SYSTEM         system *really* needs a page
2408  *      VM_ALLOC_INTERRUPT      interrupt time request
2409  *
2410  *      optional allocation flags:
2411  *      VM_ALLOC_COUNT(number)  the number of additional pages that the caller
2412  *                              intends to allocate
2413  *      VM_ALLOC_WIRED          wire the allocated page
2414  *      VM_ALLOC_ZERO           prefer a zeroed page
2415  */
2416 vm_page_t
2417 vm_page_alloc_freelist(int freelist, int req)
2418 {
2419         struct vm_domainset_iter di;
2420         vm_page_t m;
2421         int domain;
2422
2423         vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2424         do {
2425                 m = vm_page_alloc_freelist_domain(domain, freelist, req);
2426                 if (m != NULL)
2427                         break;
2428         } while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2429
2430         return (m);
2431 }
2432
2433 vm_page_t
2434 vm_page_alloc_freelist_domain(int domain, int freelist, int req)
2435 {
2436         struct vm_domain *vmd;
2437         vm_page_t m;
2438         u_int flags;
2439
2440         m = NULL;
2441         vmd = VM_DOMAIN(domain);
2442 again:
2443         if (vm_domain_allocate(vmd, req, 1)) {
2444                 vm_domain_free_lock(vmd);
2445                 m = vm_phys_alloc_freelist_pages(domain, freelist,
2446                     VM_FREEPOOL_DIRECT, 0);
2447                 vm_domain_free_unlock(vmd);
2448                 if (m == NULL)
2449                         vm_domain_freecnt_inc(vmd, 1);
2450         }
2451         if (m == NULL) {
2452                 if (vm_domain_alloc_fail(vmd, NULL, req))
2453                         goto again;
2454                 return (NULL);
2455         }
2456         vm_page_dequeue(m);
2457         vm_page_alloc_check(m);
2458
2459         /*
2460          * Initialize the page.  Only the PG_ZERO flag is inherited.
2461          */
2462         m->a.flags = 0;
2463         flags = 0;
2464         if ((req & VM_ALLOC_ZERO) != 0)
2465                 flags = PG_ZERO;
2466         m->flags &= flags;
2467         if ((req & VM_ALLOC_WIRED) != 0) {
2468                 vm_wire_add(1);
2469                 m->ref_count = 1;
2470         }
2471         /* Unmanaged pages don't use "act_count". */
2472         m->oflags = VPO_UNMANAGED;
2473         return (m);
2474 }
2475
2476 static int
2477 vm_page_zone_import(void *arg, void **store, int cnt, int domain, int flags)
2478 {
2479         struct vm_domain *vmd;
2480         struct vm_pgcache *pgcache;
2481         int i;
2482
2483         pgcache = arg;
2484         vmd = VM_DOMAIN(pgcache->domain);
2485
2486         /*
2487          * The page daemon should avoid creating extra memory pressure since its
2488          * main purpose is to replenish the store of free pages.
2489          */
2490         if (vmd->vmd_severeset || curproc == pageproc ||
2491             !_vm_domain_allocate(vmd, VM_ALLOC_NORMAL, cnt))
2492                 return (0);
2493         domain = vmd->vmd_domain;
2494         vm_domain_free_lock(vmd);
2495         i = vm_phys_alloc_npages(domain, pgcache->pool, cnt,
2496             (vm_page_t *)store);
2497         vm_domain_free_unlock(vmd);
2498         if (cnt != i)
2499                 vm_domain_freecnt_inc(vmd, cnt - i);
2500
2501         return (i);
2502 }
2503
2504 static void
2505 vm_page_zone_release(void *arg, void **store, int cnt)
2506 {
2507         struct vm_domain *vmd;
2508         struct vm_pgcache *pgcache;
2509         vm_page_t m;
2510         int i;
2511
2512         pgcache = arg;
2513         vmd = VM_DOMAIN(pgcache->domain);
2514         vm_domain_free_lock(vmd);
2515         for (i = 0; i < cnt; i++) {
2516                 m = (vm_page_t)store[i];
2517                 vm_phys_free_pages(m, 0);
2518         }
2519         vm_domain_free_unlock(vmd);
2520         vm_domain_freecnt_inc(vmd, cnt);
2521 }
2522
2523 #define VPSC_ANY        0       /* No restrictions. */
2524 #define VPSC_NORESERV   1       /* Skip reservations; implies VPSC_NOSUPER. */
2525 #define VPSC_NOSUPER    2       /* Skip superpages. */
2526
2527 /*
2528  *      vm_page_scan_contig:
2529  *
2530  *      Scan vm_page_array[] between the specified entries "m_start" and
2531  *      "m_end" for a run of contiguous physical pages that satisfy the
2532  *      specified conditions, and return the lowest page in the run.  The
2533  *      specified "alignment" determines the alignment of the lowest physical
2534  *      page in the run.  If the specified "boundary" is non-zero, then the
2535  *      run of physical pages cannot span a physical address that is a
2536  *      multiple of "boundary".
2537  *
2538  *      "m_end" is never dereferenced, so it need not point to a vm_page
2539  *      structure within vm_page_array[].
2540  *
2541  *      "npages" must be greater than zero.  "m_start" and "m_end" must not
2542  *      span a hole (or discontiguity) in the physical address space.  Both
2543  *      "alignment" and "boundary" must be a power of two.
2544  */
2545 vm_page_t
2546 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
2547     u_long alignment, vm_paddr_t boundary, int options)
2548 {
2549         vm_object_t object;
2550         vm_paddr_t pa;
2551         vm_page_t m, m_run;
2552 #if VM_NRESERVLEVEL > 0
2553         int level;
2554 #endif
2555         int m_inc, order, run_ext, run_len;
2556
2557         KASSERT(npages > 0, ("npages is 0"));
2558         KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2559         KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2560         m_run = NULL;
2561         run_len = 0;
2562         for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2563                 KASSERT((m->flags & PG_MARKER) == 0,
2564                     ("page %p is PG_MARKER", m));
2565                 KASSERT((m->flags & PG_FICTITIOUS) == 0 || m->ref_count >= 1,
2566                     ("fictitious page %p has invalid ref count", m));
2567
2568                 /*
2569                  * If the current page would be the start of a run, check its
2570                  * physical address against the end, alignment, and boundary
2571                  * conditions.  If it doesn't satisfy these conditions, either
2572                  * terminate the scan or advance to the next page that
2573                  * satisfies the failed condition.
2574                  */
2575                 if (run_len == 0) {
2576                         KASSERT(m_run == NULL, ("m_run != NULL"));
2577                         if (m + npages > m_end)
2578                                 break;
2579                         pa = VM_PAGE_TO_PHYS(m);
2580                         if ((pa & (alignment - 1)) != 0) {
2581                                 m_inc = atop(roundup2(pa, alignment) - pa);
2582                                 continue;
2583                         }
2584                         if (rounddown2(pa ^ (pa + ptoa(npages) - 1),
2585                             boundary) != 0) {
2586                                 m_inc = atop(roundup2(pa, boundary) - pa);
2587                                 continue;
2588                         }
2589                 } else
2590                         KASSERT(m_run != NULL, ("m_run == NULL"));
2591
2592 retry:
2593                 m_inc = 1;
2594                 if (vm_page_wired(m))
2595                         run_ext = 0;
2596 #if VM_NRESERVLEVEL > 0
2597                 else if ((level = vm_reserv_level(m)) >= 0 &&
2598                     (options & VPSC_NORESERV) != 0) {
2599                         run_ext = 0;
2600                         /* Advance to the end of the reservation. */
2601                         pa = VM_PAGE_TO_PHYS(m);
2602                         m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2603                             pa);
2604                 }
2605 #endif
2606                 else if ((object = atomic_load_ptr(&m->object)) != NULL) {
2607                         /*
2608                          * The page is considered eligible for relocation if
2609                          * and only if it could be laundered or reclaimed by
2610                          * the page daemon.
2611                          */
2612                         VM_OBJECT_RLOCK(object);
2613                         if (object != m->object) {
2614                                 VM_OBJECT_RUNLOCK(object);
2615                                 goto retry;
2616                         }
2617                         /* Don't care: PG_NODUMP, PG_ZERO. */
2618                         if (object->type != OBJT_DEFAULT &&
2619                             object->type != OBJT_SWAP &&
2620                             object->type != OBJT_VNODE) {
2621                                 run_ext = 0;
2622 #if VM_NRESERVLEVEL > 0
2623                         } else if ((options & VPSC_NOSUPER) != 0 &&
2624                             (level = vm_reserv_level_iffullpop(m)) >= 0) {
2625                                 run_ext = 0;
2626                                 /* Advance to the end of the superpage. */
2627                                 pa = VM_PAGE_TO_PHYS(m);
2628                                 m_inc = atop(roundup2(pa + 1,
2629                                     vm_reserv_size(level)) - pa);
2630 #endif
2631                         } else if (object->memattr == VM_MEMATTR_DEFAULT &&
2632                             vm_page_queue(m) != PQ_NONE && !vm_page_busied(m)) {
2633                                 /*
2634                                  * The page is allocated but eligible for
2635                                  * relocation.  Extend the current run by one
2636                                  * page.
2637                                  */
2638                                 KASSERT(pmap_page_get_memattr(m) ==
2639                                     VM_MEMATTR_DEFAULT,
2640                                     ("page %p has an unexpected memattr", m));
2641                                 KASSERT((m->oflags & (VPO_SWAPINPROG |
2642                                     VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2643                                     ("page %p has unexpected oflags", m));
2644                                 /* Don't care: PGA_NOSYNC. */
2645                                 run_ext = 1;
2646                         } else
2647                                 run_ext = 0;
2648                         VM_OBJECT_RUNLOCK(object);
2649 #if VM_NRESERVLEVEL > 0
2650                 } else if (level >= 0) {
2651                         /*
2652                          * The page is reserved but not yet allocated.  In
2653                          * other words, it is still free.  Extend the current
2654                          * run by one page.
2655                          */
2656                         run_ext = 1;
2657 #endif
2658                 } else if ((order = m->order) < VM_NFREEORDER) {
2659                         /*
2660                          * The page is enqueued in the physical memory
2661                          * allocator's free page queues.  Moreover, it is the
2662                          * first page in a power-of-two-sized run of
2663                          * contiguous free pages.  Add these pages to the end
2664                          * of the current run, and jump ahead.
2665                          */
2666                         run_ext = 1 << order;
2667                         m_inc = 1 << order;
2668                 } else {
2669                         /*
2670                          * Skip the page for one of the following reasons: (1)
2671                          * It is enqueued in the physical memory allocator's
2672                          * free page queues.  However, it is not the first
2673                          * page in a run of contiguous free pages.  (This case
2674                          * rarely occurs because the scan is performed in
2675                          * ascending order.) (2) It is not reserved, and it is
2676                          * transitioning from free to allocated.  (Conversely,
2677                          * the transition from allocated to free for managed
2678                          * pages is blocked by the page lock.) (3) It is
2679                          * allocated but not contained by an object and not
2680                          * wired, e.g., allocated by Xen's balloon driver.
2681                          */
2682                         run_ext = 0;
2683                 }
2684
2685                 /*
2686                  * Extend or reset the current run of pages.
2687                  */
2688                 if (run_ext > 0) {
2689                         if (run_len == 0)
2690                                 m_run = m;
2691                         run_len += run_ext;
2692                 } else {
2693                         if (run_len > 0) {
2694                                 m_run = NULL;
2695                                 run_len = 0;
2696                         }
2697                 }
2698         }
2699         if (run_len >= npages)
2700                 return (m_run);
2701         return (NULL);
2702 }
2703
2704 /*
2705  *      vm_page_reclaim_run:
2706  *
2707  *      Try to relocate each of the allocated virtual pages within the
2708  *      specified run of physical pages to a new physical address.  Free the
2709  *      physical pages underlying the relocated virtual pages.  A virtual page
2710  *      is relocatable if and only if it could be laundered or reclaimed by
2711  *      the page daemon.  Whenever possible, a virtual page is relocated to a
2712  *      physical address above "high".
2713  *
2714  *      Returns 0 if every physical page within the run was already free or
2715  *      just freed by a successful relocation.  Otherwise, returns a non-zero
2716  *      value indicating why the last attempt to relocate a virtual page was
2717  *      unsuccessful.
2718  *
2719  *      "req_class" must be an allocation class.
2720  */
2721 static int
2722 vm_page_reclaim_run(int req_class, int domain, u_long npages, vm_page_t m_run,
2723     vm_paddr_t high)
2724 {
2725         struct vm_domain *vmd;
2726         struct spglist free;
2727         vm_object_t object;
2728         vm_paddr_t pa;
2729         vm_page_t m, m_end, m_new;
2730         int error, order, req;
2731
2732         KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
2733             ("req_class is not an allocation class"));
2734         SLIST_INIT(&free);
2735         error = 0;
2736         m = m_run;
2737         m_end = m_run + npages;
2738         for (; error == 0 && m < m_end; m++) {
2739                 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2740                     ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2741
2742                 /*
2743                  * Racily check for wirings.  Races are handled once the object
2744                  * lock is held and the page is unmapped.
2745                  */
2746                 if (vm_page_wired(m))
2747                         error = EBUSY;
2748                 else if ((object = atomic_load_ptr(&m->object)) != NULL) {
2749                         /*
2750                          * The page is relocated if and only if it could be
2751                          * laundered or reclaimed by the page daemon.
2752                          */
2753                         VM_OBJECT_WLOCK(object);
2754                         /* Don't care: PG_NODUMP, PG_ZERO. */
2755                         if (m->object != object ||
2756                             (object->type != OBJT_DEFAULT &&
2757                             object->type != OBJT_SWAP &&
2758                             object->type != OBJT_VNODE))
2759                                 error = EINVAL;
2760                         else if (object->memattr != VM_MEMATTR_DEFAULT)
2761                                 error = EINVAL;
2762                         else if (vm_page_queue(m) != PQ_NONE &&
2763                             vm_page_tryxbusy(m) != 0) {
2764                                 if (vm_page_wired(m)) {
2765                                         vm_page_xunbusy(m);
2766                                         error = EBUSY;
2767                                         goto unlock;
2768                                 }
2769                                 KASSERT(pmap_page_get_memattr(m) ==
2770                                     VM_MEMATTR_DEFAULT,
2771                                     ("page %p has an unexpected memattr", m));
2772                                 KASSERT(m->oflags == 0,
2773                                     ("page %p has unexpected oflags", m));
2774                                 /* Don't care: PGA_NOSYNC. */
2775                                 if (!vm_page_none_valid(m)) {
2776                                         /*
2777                                          * First, try to allocate a new page
2778                                          * that is above "high".  Failing
2779                                          * that, try to allocate a new page
2780                                          * that is below "m_run".  Allocate
2781                                          * the new page between the end of
2782                                          * "m_run" and "high" only as a last
2783                                          * resort.
2784                                          */
2785                                         req = req_class | VM_ALLOC_NOOBJ;
2786                                         if ((m->flags & PG_NODUMP) != 0)
2787                                                 req |= VM_ALLOC_NODUMP;
2788                                         if (trunc_page(high) !=
2789                                             ~(vm_paddr_t)PAGE_MASK) {
2790                                                 m_new = vm_page_alloc_contig(
2791                                                     NULL, 0, req, 1,
2792                                                     round_page(high),
2793                                                     ~(vm_paddr_t)0,
2794                                                     PAGE_SIZE, 0,
2795                                                     VM_MEMATTR_DEFAULT);
2796                                         } else
2797                                                 m_new = NULL;
2798                                         if (m_new == NULL) {
2799                                                 pa = VM_PAGE_TO_PHYS(m_run);
2800                                                 m_new = vm_page_alloc_contig(
2801                                                     NULL, 0, req, 1,
2802                                                     0, pa - 1, PAGE_SIZE, 0,
2803                                                     VM_MEMATTR_DEFAULT);
2804                                         }
2805                                         if (m_new == NULL) {
2806                                                 pa += ptoa(npages);
2807                                                 m_new = vm_page_alloc_contig(
2808                                                     NULL, 0, req, 1,
2809                                                     pa, high, PAGE_SIZE, 0,
2810                                                     VM_MEMATTR_DEFAULT);
2811                                         }
2812                                         if (m_new == NULL) {
2813                                                 vm_page_xunbusy(m);
2814                                                 error = ENOMEM;
2815                                                 goto unlock;
2816                                         }
2817
2818                                         /*
2819                                          * Unmap the page and check for new
2820                                          * wirings that may have been acquired
2821                                          * through a pmap lookup.
2822                                          */
2823                                         if (object->ref_count != 0 &&
2824                                             !vm_page_try_remove_all(m)) {
2825                                                 vm_page_xunbusy(m);
2826                                                 vm_page_free(m_new);
2827                                                 error = EBUSY;
2828                                                 goto unlock;
2829                                         }
2830
2831                                         /*
2832                                          * Replace "m" with the new page.  For
2833                                          * vm_page_replace(), "m" must be busy
2834                                          * and dequeued.  Finally, change "m"
2835                                          * as if vm_page_free() was called.
2836                                          */
2837                                         m_new->a.flags = m->a.flags &
2838                                             ~PGA_QUEUE_STATE_MASK;
2839                                         KASSERT(m_new->oflags == VPO_UNMANAGED,
2840                                             ("page %p is managed", m_new));
2841                                         m_new->oflags = 0;
2842                                         pmap_copy_page(m, m_new);
2843                                         m_new->valid = m->valid;
2844                                         m_new->dirty = m->dirty;
2845                                         m->flags &= ~PG_ZERO;
2846                                         vm_page_dequeue(m);
2847                                         if (vm_page_replace_hold(m_new, object,
2848                                             m->pindex, m) &&
2849                                             vm_page_free_prep(m))
2850                                                 SLIST_INSERT_HEAD(&free, m,
2851                                                     plinks.s.ss);
2852
2853                                         /*
2854                                          * The new page must be deactivated
2855                                          * before the object is unlocked.
2856                                          */
2857                                         vm_page_deactivate(m_new);
2858                                 } else {
2859                                         m->flags &= ~PG_ZERO;
2860                                         vm_page_dequeue(m);
2861                                         if (vm_page_free_prep(m))
2862                                                 SLIST_INSERT_HEAD(&free, m,
2863                                                     plinks.s.ss);
2864                                         KASSERT(m->dirty == 0,
2865                                             ("page %p is dirty", m));
2866                                 }
2867                         } else
2868                                 error = EBUSY;
2869 unlock:
2870                         VM_OBJECT_WUNLOCK(object);
2871                 } else {
2872                         MPASS(vm_phys_domain(m) == domain);
2873                         vmd = VM_DOMAIN(domain);
2874                         vm_domain_free_lock(vmd);
2875                         order = m->order;
2876                         if (order < VM_NFREEORDER) {
2877                                 /*
2878                                  * The page is enqueued in the physical memory
2879                                  * allocator's free page queues.  Moreover, it
2880                                  * is the first page in a power-of-two-sized
2881                                  * run of contiguous free pages.  Jump ahead
2882                                  * to the last page within that run, and
2883                                  * continue from there.
2884                                  */
2885                                 m += (1 << order) - 1;
2886                         }
2887 #if VM_NRESERVLEVEL > 0
2888                         else if (vm_reserv_is_page_free(m))
2889                                 order = 0;
2890 #endif
2891                         vm_domain_free_unlock(vmd);
2892                         if (order == VM_NFREEORDER)
2893                                 error = EINVAL;
2894                 }
2895         }
2896         if ((m = SLIST_FIRST(&free)) != NULL) {
2897                 int cnt;
2898
2899                 vmd = VM_DOMAIN(domain);
2900                 cnt = 0;
2901                 vm_domain_free_lock(vmd);
2902                 do {
2903                         MPASS(vm_phys_domain(m) == domain);
2904                         SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2905                         vm_phys_free_pages(m, 0);
2906                         cnt++;
2907                 } while ((m = SLIST_FIRST(&free)) != NULL);
2908                 vm_domain_free_unlock(vmd);
2909                 vm_domain_freecnt_inc(vmd, cnt);
2910         }
2911         return (error);
2912 }
2913
2914 #define NRUNS   16
2915
2916 CTASSERT(powerof2(NRUNS));
2917
2918 #define RUN_INDEX(count)        ((count) & (NRUNS - 1))
2919
2920 #define MIN_RECLAIM     8
2921
2922 /*
2923  *      vm_page_reclaim_contig:
2924  *
2925  *      Reclaim allocated, contiguous physical memory satisfying the specified
2926  *      conditions by relocating the virtual pages using that physical memory.
2927  *      Returns true if reclamation is successful and false otherwise.  Since
2928  *      relocation requires the allocation of physical pages, reclamation may
2929  *      fail due to a shortage of free pages.  When reclamation fails, callers
2930  *      are expected to perform vm_wait() before retrying a failed allocation
2931  *      operation, e.g., vm_page_alloc_contig().
2932  *
2933  *      The caller must always specify an allocation class through "req".
2934  *
2935  *      allocation classes:
2936  *      VM_ALLOC_NORMAL         normal process request
2937  *      VM_ALLOC_SYSTEM         system *really* needs a page
2938  *      VM_ALLOC_INTERRUPT      interrupt time request
2939  *
2940  *      The optional allocation flags are ignored.
2941  *
2942  *      "npages" must be greater than zero.  Both "alignment" and "boundary"
2943  *      must be a power of two.
2944  */
2945 bool
2946 vm_page_reclaim_contig_domain(int domain, int req, u_long npages,
2947     vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary)
2948 {
2949         struct vm_domain *vmd;
2950         vm_paddr_t curr_low;
2951         vm_page_t m_run, m_runs[NRUNS];
2952         u_long count, reclaimed;
2953         int error, i, options, req_class;
2954
2955         KASSERT(npages > 0, ("npages is 0"));
2956         KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2957         KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2958         req_class = req & VM_ALLOC_CLASS_MASK;
2959
2960         /*
2961          * The page daemon is allowed to dig deeper into the free page list.
2962          */
2963         if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2964                 req_class = VM_ALLOC_SYSTEM;
2965
2966         /*
2967          * Return if the number of free pages cannot satisfy the requested
2968          * allocation.
2969          */
2970         vmd = VM_DOMAIN(domain);
2971         count = vmd->vmd_free_count;
2972         if (count < npages + vmd->vmd_free_reserved || (count < npages +
2973             vmd->vmd_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
2974             (count < npages && req_class == VM_ALLOC_INTERRUPT))
2975                 return (false);
2976
2977         /*
2978          * Scan up to three times, relaxing the restrictions ("options") on
2979          * the reclamation of reservations and superpages each time.
2980          */
2981         for (options = VPSC_NORESERV;;) {
2982                 /*
2983                  * Find the highest runs that satisfy the given constraints
2984                  * and restrictions, and record them in "m_runs".
2985                  */
2986                 curr_low = low;
2987                 count = 0;
2988                 for (;;) {
2989                         m_run = vm_phys_scan_contig(domain, npages, curr_low,
2990                             high, alignment, boundary, options);
2991                         if (m_run == NULL)
2992                                 break;
2993                         curr_low = VM_PAGE_TO_PHYS(m_run) + ptoa(npages);
2994                         m_runs[RUN_INDEX(count)] = m_run;
2995                         count++;
2996                 }
2997
2998                 /*
2999                  * Reclaim the highest runs in LIFO (descending) order until
3000                  * the number of reclaimed pages, "reclaimed", is at least
3001                  * MIN_RECLAIM.  Reset "reclaimed" each time because each
3002                  * reclamation is idempotent, and runs will (likely) recur
3003                  * from one scan to the next as restrictions are relaxed.
3004                  */
3005                 reclaimed = 0;
3006                 for (i = 0; count > 0 && i < NRUNS; i++) {
3007                         count--;
3008                         m_run = m_runs[RUN_INDEX(count)];
3009                         error = vm_page_reclaim_run(req_class, domain, npages,
3010                             m_run, high);
3011                         if (error == 0) {
3012                                 reclaimed += npages;
3013                                 if (reclaimed >= MIN_RECLAIM)
3014                                         return (true);
3015                         }
3016                 }
3017
3018                 /*
3019                  * Either relax the restrictions on the next scan or return if
3020                  * the last scan had no restrictions.
3021                  */
3022                 if (options == VPSC_NORESERV)
3023                         options = VPSC_NOSUPER;
3024                 else if (options == VPSC_NOSUPER)
3025                         options = VPSC_ANY;
3026                 else if (options == VPSC_ANY)
3027                         return (reclaimed != 0);
3028         }
3029 }
3030
3031 bool
3032 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
3033     u_long alignment, vm_paddr_t boundary)
3034 {
3035         struct vm_domainset_iter di;
3036         int domain;
3037         bool ret;
3038
3039         vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
3040         do {
3041                 ret = vm_page_reclaim_contig_domain(domain, req, npages, low,
3042                     high, alignment, boundary);
3043                 if (ret)
3044                         break;
3045         } while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
3046
3047         return (ret);
3048 }
3049
3050 /*
3051  * Set the domain in the appropriate page level domainset.
3052  */
3053 void
3054 vm_domain_set(struct vm_domain *vmd)
3055 {
3056
3057         mtx_lock(&vm_domainset_lock);
3058         if (!vmd->vmd_minset && vm_paging_min(vmd)) {
3059                 vmd->vmd_minset = 1;
3060                 DOMAINSET_SET(vmd->vmd_domain, &vm_min_domains);
3061         }
3062         if (!vmd->vmd_severeset && vm_paging_severe(vmd)) {
3063                 vmd->vmd_severeset = 1;
3064                 DOMAINSET_SET(vmd->vmd_domain, &vm_severe_domains);
3065         }
3066         mtx_unlock(&vm_domainset_lock);
3067 }
3068
3069 /*
3070  * Clear the domain from the appropriate page level domainset.
3071  */
3072 void
3073 vm_domain_clear(struct vm_domain *vmd)
3074 {
3075
3076         mtx_lock(&vm_domainset_lock);
3077         if (vmd->vmd_minset && !vm_paging_min(vmd)) {
3078                 vmd->vmd_minset = 0;
3079                 DOMAINSET_CLR(vmd->vmd_domain, &vm_min_domains);
3080                 if (vm_min_waiters != 0) {
3081                         vm_min_waiters = 0;
3082                         wakeup(&vm_min_domains);
3083                 }
3084         }
3085         if (vmd->vmd_severeset && !vm_paging_severe(vmd)) {
3086                 vmd->vmd_severeset = 0;
3087                 DOMAINSET_CLR(vmd->vmd_domain, &vm_severe_domains);
3088                 if (vm_severe_waiters != 0) {
3089                         vm_severe_waiters = 0;
3090                         wakeup(&vm_severe_domains);
3091                 }
3092         }
3093
3094         /*
3095          * If pageout daemon needs pages, then tell it that there are
3096          * some free.
3097          */
3098         if (vmd->vmd_pageout_pages_needed &&
3099             vmd->vmd_free_count >= vmd->vmd_pageout_free_min) {
3100                 wakeup(&vmd->vmd_pageout_pages_needed);
3101                 vmd->vmd_pageout_pages_needed = 0;
3102         }
3103
3104         /* See comments in vm_wait_doms(). */
3105         if (vm_pageproc_waiters) {
3106                 vm_pageproc_waiters = 0;
3107                 wakeup(&vm_pageproc_waiters);
3108         }
3109         mtx_unlock(&vm_domainset_lock);
3110 }
3111
3112 /*
3113  * Wait for free pages to exceed the min threshold globally.
3114  */
3115 void
3116 vm_wait_min(void)
3117 {
3118
3119         mtx_lock(&vm_domainset_lock);
3120         while (vm_page_count_min()) {
3121                 vm_min_waiters++;
3122                 msleep(&vm_min_domains, &vm_domainset_lock, PVM, "vmwait", 0);
3123         }
3124         mtx_unlock(&vm_domainset_lock);
3125 }
3126
3127 /*
3128  * Wait for free pages to exceed the severe threshold globally.
3129  */
3130 void
3131 vm_wait_severe(void)
3132 {
3133
3134         mtx_lock(&vm_domainset_lock);
3135         while (vm_page_count_severe()) {
3136                 vm_severe_waiters++;
3137                 msleep(&vm_severe_domains, &vm_domainset_lock, PVM,
3138                     "vmwait", 0);
3139         }
3140         mtx_unlock(&vm_domainset_lock);
3141 }
3142
3143 u_int
3144 vm_wait_count(void)
3145 {
3146
3147         return (vm_severe_waiters + vm_min_waiters + vm_pageproc_waiters);
3148 }
3149
3150 void
3151 vm_wait_doms(const domainset_t *wdoms)
3152 {
3153
3154         /*
3155          * We use racey wakeup synchronization to avoid expensive global
3156          * locking for the pageproc when sleeping with a non-specific vm_wait.
3157          * To handle this, we only sleep for one tick in this instance.  It
3158          * is expected that most allocations for the pageproc will come from
3159          * kmem or vm_page_grab* which will use the more specific and
3160          * race-free vm_wait_domain().
3161          */
3162         if (curproc == pageproc) {
3163                 mtx_lock(&vm_domainset_lock);
3164                 vm_pageproc_waiters++;
3165                 msleep(&vm_pageproc_waiters, &vm_domainset_lock, PVM | PDROP,
3166                     "pageprocwait", 1);
3167         } else {
3168                 /*
3169                  * XXX Ideally we would wait only until the allocation could
3170                  * be satisfied.  This condition can cause new allocators to
3171                  * consume all freed pages while old allocators wait.
3172                  */
3173                 mtx_lock(&vm_domainset_lock);
3174                 if (vm_page_count_min_set(wdoms)) {
3175                         vm_min_waiters++;
3176                         msleep(&vm_min_domains, &vm_domainset_lock,
3177                             PVM | PDROP, "vmwait", 0);
3178                 } else
3179                         mtx_unlock(&vm_domainset_lock);
3180         }
3181 }
3182
3183 /*
3184  *      vm_wait_domain:
3185  *
3186  *      Sleep until free pages are available for allocation.
3187  *      - Called in various places after failed memory allocations.
3188  */
3189 void
3190 vm_wait_domain(int domain)
3191 {
3192         struct vm_domain *vmd;
3193         domainset_t wdom;
3194
3195         vmd = VM_DOMAIN(domain);
3196         vm_domain_free_assert_unlocked(vmd);
3197
3198         if (curproc == pageproc) {
3199                 mtx_lock(&vm_domainset_lock);
3200                 if (vmd->vmd_free_count < vmd->vmd_pageout_free_min) {
3201                         vmd->vmd_pageout_pages_needed = 1;
3202                         msleep(&vmd->vmd_pageout_pages_needed,
3203                             &vm_domainset_lock, PDROP | PSWP, "VMWait", 0);
3204                 } else
3205                         mtx_unlock(&vm_domainset_lock);
3206         } else {
3207                 if (pageproc == NULL)
3208                         panic("vm_wait in early boot");
3209                 DOMAINSET_ZERO(&wdom);
3210                 DOMAINSET_SET(vmd->vmd_domain, &wdom);
3211                 vm_wait_doms(&wdom);
3212         }
3213 }
3214
3215 /*
3216  *      vm_wait:
3217  *
3218  *      Sleep until free pages are available for allocation in the
3219  *      affinity domains of the obj.  If obj is NULL, the domain set
3220  *      for the calling thread is used.
3221  *      Called in various places after failed memory allocations.
3222  */
3223 void
3224 vm_wait(vm_object_t obj)
3225 {
3226         struct domainset *d;
3227
3228         d = NULL;
3229
3230         /*
3231          * Carefully fetch pointers only once: the struct domainset
3232          * itself is ummutable but the pointer might change.
3233          */
3234         if (obj != NULL)
3235                 d = obj->domain.dr_policy;
3236         if (d == NULL)
3237                 d = curthread->td_domain.dr_policy;
3238
3239         vm_wait_doms(&d->ds_mask);
3240 }
3241
3242 /*
3243  *      vm_domain_alloc_fail:
3244  *
3245  *      Called when a page allocation function fails.  Informs the
3246  *      pagedaemon and performs the requested wait.  Requires the
3247  *      domain_free and object lock on entry.  Returns with the
3248  *      object lock held and free lock released.  Returns an error when
3249  *      retry is necessary.
3250  *
3251  */
3252 static int
3253 vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object, int req)
3254 {
3255
3256         vm_domain_free_assert_unlocked(vmd);
3257
3258         atomic_add_int(&vmd->vmd_pageout_deficit,
3259             max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
3260         if (req & (VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL)) {
3261                 if (object != NULL) 
3262                         VM_OBJECT_WUNLOCK(object);
3263                 vm_wait_domain(vmd->vmd_domain);
3264                 if (object != NULL) 
3265                         VM_OBJECT_WLOCK(object);
3266                 if (req & VM_ALLOC_WAITOK)
3267                         return (EAGAIN);
3268         }
3269
3270         return (0);
3271 }
3272
3273 /*
3274  *      vm_waitpfault:
3275  *
3276  *      Sleep until free pages are available for allocation.
3277  *      - Called only in vm_fault so that processes page faulting
3278  *        can be easily tracked.
3279  *      - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
3280  *        processes will be able to grab memory first.  Do not change
3281  *        this balance without careful testing first.
3282  */
3283 void
3284 vm_waitpfault(struct domainset *dset, int timo)
3285 {
3286
3287         /*
3288          * XXX Ideally we would wait only until the allocation could
3289          * be satisfied.  This condition can cause new allocators to
3290          * consume all freed pages while old allocators wait.
3291          */
3292         mtx_lock(&vm_domainset_lock);
3293         if (vm_page_count_min_set(&dset->ds_mask)) {
3294                 vm_min_waiters++;
3295                 msleep(&vm_min_domains, &vm_domainset_lock, PUSER | PDROP,
3296                     "pfault", timo);
3297         } else
3298                 mtx_unlock(&vm_domainset_lock);
3299 }
3300
3301 static struct vm_pagequeue *
3302 _vm_page_pagequeue(vm_page_t m, uint8_t queue)
3303 {
3304
3305         return (&vm_pagequeue_domain(m)->vmd_pagequeues[queue]);
3306 }
3307
3308 #ifdef INVARIANTS
3309 static struct vm_pagequeue *
3310 vm_page_pagequeue(vm_page_t m)
3311 {
3312
3313         return (_vm_page_pagequeue(m, vm_page_astate_load(m).queue));
3314 }
3315 #endif
3316
3317 static __always_inline bool
3318 vm_page_pqstate_fcmpset(vm_page_t m, vm_page_astate_t *old, vm_page_astate_t new)
3319 {
3320         vm_page_astate_t tmp;
3321
3322         tmp = *old;
3323         do {
3324                 if (__predict_true(vm_page_astate_fcmpset(m, old, new)))
3325                         return (true);
3326                 counter_u64_add(pqstate_commit_retries, 1);
3327         } while (old->_bits == tmp._bits);
3328
3329         return (false);
3330 }
3331
3332 /*
3333  * Do the work of committing a queue state update that moves the page out of
3334  * its current queue.
3335  */
3336 static bool
3337 _vm_page_pqstate_commit_dequeue(struct vm_pagequeue *pq, vm_page_t m,
3338     vm_page_astate_t *old, vm_page_astate_t new)
3339 {
3340         vm_page_t next;
3341
3342         vm_pagequeue_assert_locked(pq);
3343         KASSERT(vm_page_pagequeue(m) == pq,
3344             ("%s: queue %p does not match page %p", __func__, pq, m));
3345         KASSERT(old->queue != PQ_NONE && new.queue != old->queue,
3346             ("%s: invalid queue indices %d %d",
3347             __func__, old->queue, new.queue));
3348
3349         /*
3350          * Once the queue index of the page changes there is nothing
3351          * synchronizing with further updates to the page's physical
3352          * queue state.  Therefore we must speculatively remove the page
3353          * from the queue now and be prepared to roll back if the queue
3354          * state update fails.  If the page is not physically enqueued then
3355          * we just update its queue index.
3356          */
3357         if ((old->flags & PGA_ENQUEUED) != 0) {
3358                 new.flags &= ~PGA_ENQUEUED;
3359                 next = TAILQ_NEXT(m, plinks.q);
3360                 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3361                 vm_pagequeue_cnt_dec(pq);
3362                 if (!vm_page_pqstate_fcmpset(m, old, new)) {
3363                         if (next == NULL)
3364                                 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3365                         else
3366                                 TAILQ_INSERT_BEFORE(next, m, plinks.q);
3367                         vm_pagequeue_cnt_inc(pq);
3368                         return (false);
3369                 } else {
3370                         return (true);
3371                 }
3372         } else {
3373                 return (vm_page_pqstate_fcmpset(m, old, new));
3374         }
3375 }
3376
3377 static bool
3378 vm_page_pqstate_commit_dequeue(vm_page_t m, vm_page_astate_t *old,
3379     vm_page_astate_t new)
3380 {
3381         struct vm_pagequeue *pq;
3382         vm_page_astate_t as;
3383         bool ret;
3384
3385         pq = _vm_page_pagequeue(m, old->queue);
3386
3387         /*
3388          * The queue field and PGA_ENQUEUED flag are stable only so long as the
3389          * corresponding page queue lock is held.
3390          */
3391         vm_pagequeue_lock(pq);
3392         as = vm_page_astate_load(m);
3393         if (__predict_false(as._bits != old->_bits)) {
3394                 *old = as;
3395                 ret = false;
3396         } else {
3397                 ret = _vm_page_pqstate_commit_dequeue(pq, m, old, new);
3398         }
3399         vm_pagequeue_unlock(pq);
3400         return (ret);
3401 }
3402
3403 /*
3404  * Commit a queue state update that enqueues or requeues a page.
3405  */
3406 static bool
3407 _vm_page_pqstate_commit_requeue(struct vm_pagequeue *pq, vm_page_t m,
3408     vm_page_astate_t *old, vm_page_astate_t new)
3409 {
3410         struct vm_domain *vmd;
3411
3412         vm_pagequeue_assert_locked(pq);
3413         KASSERT(old->queue != PQ_NONE && new.queue == old->queue,
3414             ("%s: invalid queue indices %d %d",
3415             __func__, old->queue, new.queue));
3416
3417         new.flags |= PGA_ENQUEUED;
3418         if (!vm_page_pqstate_fcmpset(m, old, new))
3419                 return (false);
3420
3421         if ((old->flags & PGA_ENQUEUED) != 0)
3422                 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3423         else
3424                 vm_pagequeue_cnt_inc(pq);
3425
3426         /*
3427          * Give PGA_REQUEUE_HEAD precedence over PGA_REQUEUE.  In particular, if
3428          * both flags are set in close succession, only PGA_REQUEUE_HEAD will be
3429          * applied, even if it was set first.
3430          */
3431         if ((old->flags & PGA_REQUEUE_HEAD) != 0) {
3432                 vmd = vm_pagequeue_domain(m);
3433                 KASSERT(pq == &vmd->vmd_pagequeues[PQ_INACTIVE],
3434                     ("%s: invalid page queue for page %p", __func__, m));
3435                 TAILQ_INSERT_BEFORE(&vmd->vmd_inacthead, m, plinks.q);
3436         } else {
3437                 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3438         }
3439         return (true);
3440 }
3441
3442 /*
3443  * Commit a queue state update that encodes a request for a deferred queue
3444  * operation.
3445  */
3446 static bool
3447 vm_page_pqstate_commit_request(vm_page_t m, vm_page_astate_t *old,
3448     vm_page_astate_t new)
3449 {
3450
3451         KASSERT(old->queue == new.queue || new.queue != PQ_NONE,
3452             ("%s: invalid state, queue %d flags %x",
3453             __func__, new.queue, new.flags));
3454
3455         if (old->_bits != new._bits &&
3456             !vm_page_pqstate_fcmpset(m, old, new))
3457                 return (false);
3458         vm_page_pqbatch_submit(m, new.queue);
3459         return (true);
3460 }
3461
3462 /*
3463  * A generic queue state update function.  This handles more cases than the
3464  * specialized functions above.
3465  */
3466 bool
3467 vm_page_pqstate_commit(vm_page_t m, vm_page_astate_t *old, vm_page_astate_t new)
3468 {
3469
3470         if (old->_bits == new._bits)
3471                 return (true);
3472
3473         if (old->queue != PQ_NONE && new.queue != old->queue) {
3474                 if (!vm_page_pqstate_commit_dequeue(m, old, new))
3475                         return (false);
3476                 if (new.queue != PQ_NONE)
3477                         vm_page_pqbatch_submit(m, new.queue);
3478         } else {
3479                 if (!vm_page_pqstate_fcmpset(m, old, new))
3480                         return (false);
3481                 if (new.queue != PQ_NONE &&
3482                     ((new.flags & ~old->flags) & PGA_QUEUE_OP_MASK) != 0)
3483                         vm_page_pqbatch_submit(m, new.queue);
3484         }
3485         return (true);
3486 }
3487
3488 /*
3489  * Apply deferred queue state updates to a page.
3490  */
3491 static inline void
3492 vm_pqbatch_process_page(struct vm_pagequeue *pq, vm_page_t m, uint8_t queue)
3493 {
3494         vm_page_astate_t new, old;
3495
3496         CRITICAL_ASSERT(curthread);
3497         vm_pagequeue_assert_locked(pq);
3498         KASSERT(queue < PQ_COUNT,
3499             ("%s: invalid queue index %d", __func__, queue));
3500         KASSERT(pq == _vm_page_pagequeue(m, queue),
3501             ("%s: page %p does not belong to queue %p", __func__, m, pq));
3502
3503         for (old = vm_page_astate_load(m);;) {
3504                 if (__predict_false(old.queue != queue ||
3505                     (old.flags & PGA_QUEUE_OP_MASK) == 0)) {
3506                         counter_u64_add(queue_nops, 1);
3507                         break;
3508                 }
3509                 KASSERT(old.queue != PQ_NONE || (old.flags & PGA_QUEUE_STATE_MASK) == 0,
3510                     ("%s: page %p has unexpected queue state", __func__, m));
3511
3512                 new = old;
3513                 if ((old.flags & PGA_DEQUEUE) != 0) {
3514                         new.flags &= ~PGA_QUEUE_OP_MASK;
3515                         new.queue = PQ_NONE;
3516                         if (__predict_true(_vm_page_pqstate_commit_dequeue(pq,
3517                             m, &old, new))) {
3518                                 counter_u64_add(queue_ops, 1);
3519                                 break;
3520                         }
3521                 } else {
3522                         new.flags &= ~(PGA_REQUEUE | PGA_REQUEUE_HEAD);
3523                         if (__predict_true(_vm_page_pqstate_commit_requeue(pq,
3524                             m, &old, new))) {
3525                                 counter_u64_add(queue_ops, 1);
3526                                 break;
3527                         }
3528                 }
3529         }
3530 }
3531
3532 static void
3533 vm_pqbatch_process(struct vm_pagequeue *pq, struct vm_batchqueue *bq,
3534     uint8_t queue)
3535 {
3536         int i;
3537
3538         for (i = 0; i < bq->bq_cnt; i++)
3539                 vm_pqbatch_process_page(pq, bq->bq_pa[i], queue);
3540         vm_batchqueue_init(bq);
3541 }
3542
3543 /*
3544  *      vm_page_pqbatch_submit:         [ internal use only ]
3545  *
3546  *      Enqueue a page in the specified page queue's batched work queue.
3547  *      The caller must have encoded the requested operation in the page
3548  *      structure's a.flags field.
3549  */
3550 void
3551 vm_page_pqbatch_submit(vm_page_t m, uint8_t queue)
3552 {
3553         struct vm_batchqueue *bq;
3554         struct vm_pagequeue *pq;
3555         int domain;
3556
3557         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3558             ("page %p is unmanaged", m));
3559         KASSERT(queue < PQ_COUNT, ("invalid queue %d", queue));
3560
3561         domain = vm_phys_domain(m);
3562         pq = &vm_pagequeue_domain(m)->vmd_pagequeues[queue];
3563
3564         critical_enter();
3565         bq = DPCPU_PTR(pqbatch[domain][queue]);
3566         if (vm_batchqueue_insert(bq, m)) {
3567                 critical_exit();
3568                 return;
3569         }
3570         critical_exit();
3571         vm_pagequeue_lock(pq);
3572         critical_enter();
3573         bq = DPCPU_PTR(pqbatch[domain][queue]);
3574         vm_pqbatch_process(pq, bq, queue);
3575         vm_pqbatch_process_page(pq, m, queue);
3576         vm_pagequeue_unlock(pq);
3577         critical_exit();
3578 }
3579
3580 /*
3581  *      vm_page_pqbatch_drain:          [ internal use only ]
3582  *
3583  *      Force all per-CPU page queue batch queues to be drained.  This is
3584  *      intended for use in severe memory shortages, to ensure that pages
3585  *      do not remain stuck in the batch queues.
3586  */
3587 void
3588 vm_page_pqbatch_drain(void)
3589 {
3590         struct thread *td;
3591         struct vm_domain *vmd;
3592         struct vm_pagequeue *pq;
3593         int cpu, domain, queue;
3594
3595         td = curthread;
3596         CPU_FOREACH(cpu) {
3597                 thread_lock(td);
3598                 sched_bind(td, cpu);
3599                 thread_unlock(td);
3600
3601                 for (domain = 0; domain < vm_ndomains; domain++) {
3602                         vmd = VM_DOMAIN(domain);
3603                         for (queue = 0; queue < PQ_COUNT; queue++) {
3604                                 pq = &vmd->vmd_pagequeues[queue];
3605                                 vm_pagequeue_lock(pq);
3606                                 critical_enter();
3607                                 vm_pqbatch_process(pq,
3608                                     DPCPU_PTR(pqbatch[domain][queue]), queue);
3609                                 critical_exit();
3610                                 vm_pagequeue_unlock(pq);
3611                         }
3612                 }
3613         }
3614         thread_lock(td);
3615         sched_unbind(td);
3616         thread_unlock(td);
3617 }
3618
3619 /*
3620  *      vm_page_dequeue_deferred:       [ internal use only ]
3621  *
3622  *      Request removal of the given page from its current page
3623  *      queue.  Physical removal from the queue may be deferred
3624  *      indefinitely.
3625  *
3626  *      The page must be locked.
3627  */
3628 void
3629 vm_page_dequeue_deferred(vm_page_t m)
3630 {
3631         vm_page_astate_t new, old;
3632
3633         old = vm_page_astate_load(m);
3634         do {
3635                 if (old.queue == PQ_NONE) {
3636                         KASSERT((old.flags & PGA_QUEUE_STATE_MASK) == 0,
3637                             ("%s: page %p has unexpected queue state",
3638                             __func__, m));
3639                         break;
3640                 }
3641                 new = old;
3642                 new.flags |= PGA_DEQUEUE;
3643         } while (!vm_page_pqstate_commit_request(m, &old, new));
3644 }
3645
3646 /*
3647  *      vm_page_dequeue:
3648  *
3649  *      Remove the page from whichever page queue it's in, if any, before
3650  *      returning.
3651  */
3652 void
3653 vm_page_dequeue(vm_page_t m)
3654 {
3655         vm_page_astate_t new, old;
3656
3657         old = vm_page_astate_load(m);
3658         do {
3659                 if (old.queue == PQ_NONE) {
3660                         KASSERT((old.flags & PGA_QUEUE_STATE_MASK) == 0,
3661                             ("%s: page %p has unexpected queue state",
3662                             __func__, m));
3663                         break;
3664                 }
3665                 new = old;
3666                 new.flags &= ~PGA_QUEUE_OP_MASK;
3667                 new.queue = PQ_NONE;
3668         } while (!vm_page_pqstate_commit_dequeue(m, &old, new));
3669
3670 }
3671
3672 /*
3673  * Schedule the given page for insertion into the specified page queue.
3674  * Physical insertion of the page may be deferred indefinitely.
3675  */
3676 static void
3677 vm_page_enqueue(vm_page_t m, uint8_t queue)
3678 {
3679
3680         KASSERT(m->a.queue == PQ_NONE &&
3681             (m->a.flags & PGA_QUEUE_STATE_MASK) == 0,
3682             ("%s: page %p is already enqueued", __func__, m));
3683         KASSERT(m->ref_count > 0,
3684             ("%s: page %p does not carry any references", __func__, m));
3685
3686         m->a.queue = queue;
3687         if ((m->a.flags & PGA_REQUEUE) == 0)
3688                 vm_page_aflag_set(m, PGA_REQUEUE);
3689         vm_page_pqbatch_submit(m, queue);
3690 }
3691
3692 /*
3693  *      vm_page_free_prep:
3694  *
3695  *      Prepares the given page to be put on the free list,
3696  *      disassociating it from any VM object. The caller may return
3697  *      the page to the free list only if this function returns true.
3698  *
3699  *      The object, if it exists, must be locked, and then the page must
3700  *      be xbusy.  Otherwise the page must be not busied.  A managed
3701  *      page must be unmapped.
3702  */
3703 static bool
3704 vm_page_free_prep(vm_page_t m)
3705 {
3706
3707         /*
3708          * Synchronize with threads that have dropped a reference to this
3709          * page.
3710          */
3711         atomic_thread_fence_acq();
3712
3713 #if defined(DIAGNOSTIC) && defined(PHYS_TO_DMAP)
3714         if (PMAP_HAS_DMAP && (m->flags & PG_ZERO) != 0) {
3715                 uint64_t *p;
3716                 int i;
3717                 p = (uint64_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
3718                 for (i = 0; i < PAGE_SIZE / sizeof(uint64_t); i++, p++)
3719                         KASSERT(*p == 0, ("vm_page_free_prep %p PG_ZERO %d %jx",
3720                             m, i, (uintmax_t)*p));
3721         }
3722 #endif
3723         if ((m->oflags & VPO_UNMANAGED) == 0) {
3724                 KASSERT(!pmap_page_is_mapped(m),
3725                     ("vm_page_free_prep: freeing mapped page %p", m));
3726                 KASSERT((m->a.flags & (PGA_EXECUTABLE | PGA_WRITEABLE)) == 0,
3727                     ("vm_page_free_prep: mapping flags set in page %p", m));
3728         } else {
3729                 KASSERT(m->a.queue == PQ_NONE,
3730                     ("vm_page_free_prep: unmanaged page %p is queued", m));
3731         }
3732         VM_CNT_INC(v_tfree);
3733
3734         if (m->object != NULL) {
3735                 KASSERT(((m->oflags & VPO_UNMANAGED) != 0) ==
3736                     ((m->object->flags & OBJ_UNMANAGED) != 0),
3737                     ("vm_page_free_prep: managed flag mismatch for page %p",
3738                     m));
3739                 vm_page_assert_xbusied(m);
3740
3741                 /*
3742                  * The object reference can be released without an atomic
3743                  * operation.
3744                  */
3745                 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
3746                     m->ref_count == VPRC_OBJREF,
3747                     ("vm_page_free_prep: page %p has unexpected ref_count %u",
3748                     m, m->ref_count));
3749                 vm_page_object_remove(m);
3750                 m->ref_count -= VPRC_OBJREF;
3751         } else
3752                 vm_page_assert_unbusied(m);
3753
3754         vm_page_busy_free(m);
3755
3756         /*
3757          * If fictitious remove object association and
3758          * return.
3759          */
3760         if ((m->flags & PG_FICTITIOUS) != 0) {
3761                 KASSERT(m->ref_count == 1,
3762                     ("fictitious page %p is referenced", m));
3763                 KASSERT(m->a.queue == PQ_NONE,
3764                     ("fictitious page %p is queued", m));
3765                 return (false);
3766         }
3767
3768         /*
3769          * Pages need not be dequeued before they are returned to the physical
3770          * memory allocator, but they must at least be marked for a deferred
3771          * dequeue.
3772          */
3773         if ((m->oflags & VPO_UNMANAGED) == 0)
3774                 vm_page_dequeue_deferred(m);
3775
3776         m->valid = 0;
3777         vm_page_undirty(m);
3778
3779         if (m->ref_count != 0)
3780                 panic("vm_page_free_prep: page %p has references", m);
3781
3782         /*
3783          * Restore the default memory attribute to the page.
3784          */
3785         if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
3786                 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
3787
3788 #if VM_NRESERVLEVEL > 0
3789         /*
3790          * Determine whether the page belongs to a reservation.  If the page was
3791          * allocated from a per-CPU cache, it cannot belong to a reservation, so
3792          * as an optimization, we avoid the check in that case.
3793          */
3794         if ((m->flags & PG_PCPU_CACHE) == 0 && vm_reserv_free_page(m))
3795                 return (false);
3796 #endif
3797
3798         return (true);
3799 }
3800
3801 /*
3802  *      vm_page_free_toq:
3803  *
3804  *      Returns the given page to the free list, disassociating it
3805  *      from any VM object.
3806  *
3807  *      The object must be locked.  The page must be locked if it is
3808  *      managed.
3809  */
3810 static void
3811 vm_page_free_toq(vm_page_t m)
3812 {
3813         struct vm_domain *vmd;
3814         uma_zone_t zone;
3815
3816         if (!vm_page_free_prep(m))
3817                 return;
3818
3819         vmd = vm_pagequeue_domain(m);
3820         zone = vmd->vmd_pgcache[m->pool].zone;
3821         if ((m->flags & PG_PCPU_CACHE) != 0 && zone != NULL) {
3822                 uma_zfree(zone, m);
3823                 return;
3824         }
3825         vm_domain_free_lock(vmd);
3826         vm_phys_free_pages(m, 0);
3827         vm_domain_free_unlock(vmd);
3828         vm_domain_freecnt_inc(vmd, 1);
3829 }
3830
3831 /*
3832  *      vm_page_free_pages_toq:
3833  *
3834  *      Returns a list of pages to the free list, disassociating it
3835  *      from any VM object.  In other words, this is equivalent to
3836  *      calling vm_page_free_toq() for each page of a list of VM objects.
3837  *
3838  *      The objects must be locked.  The pages must be locked if it is
3839  *      managed.
3840  */
3841 void
3842 vm_page_free_pages_toq(struct spglist *free, bool update_wire_count)
3843 {
3844         vm_page_t m;
3845         int count;
3846
3847         if (SLIST_EMPTY(free))
3848                 return;
3849
3850         count = 0;
3851         while ((m = SLIST_FIRST(free)) != NULL) {
3852                 count++;
3853                 SLIST_REMOVE_HEAD(free, plinks.s.ss);
3854                 vm_page_free_toq(m);
3855         }
3856
3857         if (update_wire_count)
3858                 vm_wire_sub(count);
3859 }
3860
3861 /*
3862  * Mark this page as wired down, preventing reclamation by the page daemon
3863  * or when the containing object is destroyed.
3864  */
3865 void
3866 vm_page_wire(vm_page_t m)
3867 {
3868         u_int old;
3869
3870         KASSERT(m->object != NULL,
3871             ("vm_page_wire: page %p does not belong to an object", m));
3872         if (!vm_page_busied(m) && !vm_object_busied(m->object))
3873                 VM_OBJECT_ASSERT_LOCKED(m->object);
3874         KASSERT((m->flags & PG_FICTITIOUS) == 0 ||
3875             VPRC_WIRE_COUNT(m->ref_count) >= 1,
3876             ("vm_page_wire: fictitious page %p has zero wirings", m));
3877
3878         old = atomic_fetchadd_int(&m->ref_count, 1);
3879         KASSERT(VPRC_WIRE_COUNT(old) != VPRC_WIRE_COUNT_MAX,
3880             ("vm_page_wire: counter overflow for page %p", m));
3881         if (VPRC_WIRE_COUNT(old) == 0) {
3882                 if ((m->oflags & VPO_UNMANAGED) == 0)
3883                         vm_page_aflag_set(m, PGA_DEQUEUE);
3884                 vm_wire_add(1);
3885         }
3886 }
3887
3888 /*
3889  * Attempt to wire a mapped page following a pmap lookup of that page.
3890  * This may fail if a thread is concurrently tearing down mappings of the page.
3891  * The transient failure is acceptable because it translates to the
3892  * failure of the caller pmap_extract_and_hold(), which should be then
3893  * followed by the vm_fault() fallback, see e.g. vm_fault_quick_hold_pages().
3894  */
3895 bool
3896 vm_page_wire_mapped(vm_page_t m)
3897 {
3898         u_int old;
3899
3900         old = m->ref_count;
3901         do {
3902                 KASSERT(old > 0,
3903                     ("vm_page_wire_mapped: wiring unreferenced page %p", m));
3904                 if ((old & VPRC_BLOCKED) != 0)
3905                         return (false);
3906         } while (!atomic_fcmpset_int(&m->ref_count, &old, old + 1));
3907
3908         if (VPRC_WIRE_COUNT(old) == 0) {
3909                 if ((m->oflags & VPO_UNMANAGED) == 0)
3910                         vm_page_aflag_set(m, PGA_DEQUEUE);
3911                 vm_wire_add(1);
3912         }
3913         return (true);
3914 }
3915
3916 /*
3917  * Release a wiring reference to a managed page.  If the page still belongs to
3918  * an object, update its position in the page queues to reflect the reference.
3919  * If the wiring was the last reference to the page, free the page.
3920  */
3921 static void
3922 vm_page_unwire_managed(vm_page_t m, uint8_t nqueue, bool noreuse)
3923 {
3924         u_int old;
3925
3926         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3927             ("%s: page %p is unmanaged", __func__, m));
3928
3929         /*
3930          * Update LRU state before releasing the wiring reference.
3931          * Use a release store when updating the reference count to
3932          * synchronize with vm_page_free_prep().
3933          */
3934         old = m->ref_count;
3935         do {
3936                 KASSERT(VPRC_WIRE_COUNT(old) > 0,
3937                     ("vm_page_unwire: wire count underflow for page %p", m));
3938
3939                 if (old > VPRC_OBJREF + 1) {
3940                         /*
3941                          * The page has at least one other wiring reference.  An
3942                          * earlier iteration of this loop may have called
3943                          * vm_page_release_toq() and cleared PGA_DEQUEUE, so
3944                          * re-set it if necessary.
3945                          */
3946                         if ((vm_page_astate_load(m).flags & PGA_DEQUEUE) == 0)
3947                                 vm_page_aflag_set(m, PGA_DEQUEUE);
3948                 } else if (old == VPRC_OBJREF + 1) {
3949                         /*
3950                          * This is the last wiring.  Clear PGA_DEQUEUE and
3951                          * update the page's queue state to reflect the
3952                          * reference.  If the page does not belong to an object
3953                          * (i.e., the VPRC_OBJREF bit is clear), we only need to
3954                          * clear leftover queue state.
3955                          */
3956                         vm_page_release_toq(m, nqueue, false);
3957                 } else if (old == 1) {
3958                         vm_page_aflag_clear(m, PGA_DEQUEUE);
3959                 }
3960         } while (!atomic_fcmpset_rel_int(&m->ref_count, &old, old - 1));
3961
3962         if (VPRC_WIRE_COUNT(old) == 1) {
3963                 vm_wire_sub(1);
3964                 if (old == 1)
3965                         vm_page_free(m);
3966         }
3967 }
3968
3969 /*
3970  * Release one wiring of the specified page, potentially allowing it to be
3971  * paged out.
3972  *
3973  * Only managed pages belonging to an object can be paged out.  If the number
3974  * of wirings transitions to zero and the page is eligible for page out, then
3975  * the page is added to the specified paging queue.  If the released wiring
3976  * represented the last reference to the page, the page is freed.
3977  *
3978  * A managed page must be locked.
3979  */
3980 void
3981 vm_page_unwire(vm_page_t m, uint8_t nqueue)
3982 {
3983
3984         KASSERT(nqueue < PQ_COUNT,
3985             ("vm_page_unwire: invalid queue %u request for page %p",
3986             nqueue, m));
3987
3988         if ((m->oflags & VPO_UNMANAGED) != 0) {
3989                 if (vm_page_unwire_noq(m) && m->ref_count == 0)
3990                         vm_page_free(m);
3991                 return;
3992         }
3993         vm_page_unwire_managed(m, nqueue, false);
3994 }
3995
3996 /*
3997  * Unwire a page without (re-)inserting it into a page queue.  It is up
3998  * to the caller to enqueue, requeue, or free the page as appropriate.
3999  * In most cases involving managed pages, vm_page_unwire() should be used
4000  * instead.
4001  */
4002 bool
4003 vm_page_unwire_noq(vm_page_t m)
4004 {
4005         u_int old;
4006
4007         old = vm_page_drop(m, 1);
4008         KASSERT(VPRC_WIRE_COUNT(old) != 0,
4009             ("vm_page_unref: counter underflow for page %p", m));
4010         KASSERT((m->flags & PG_FICTITIOUS) == 0 || VPRC_WIRE_COUNT(old) > 1,
4011             ("vm_page_unref: missing ref on fictitious page %p", m));
4012
4013         if (VPRC_WIRE_COUNT(old) > 1)
4014                 return (false);
4015         if ((m->oflags & VPO_UNMANAGED) == 0)
4016                 vm_page_aflag_clear(m, PGA_DEQUEUE);
4017         vm_wire_sub(1);
4018         return (true);
4019 }
4020
4021 /*
4022  * Ensure that the page ends up in the specified page queue.  If the page is
4023  * active or being moved to the active queue, ensure that its act_count is
4024  * at least ACT_INIT but do not otherwise mess with it.
4025  *
4026  * A managed page must be locked.
4027  */
4028 static __always_inline void
4029 vm_page_mvqueue(vm_page_t m, const uint8_t nqueue, const uint16_t nflag)
4030 {
4031         vm_page_astate_t old, new;
4032
4033         KASSERT(m->ref_count > 0,
4034             ("%s: page %p does not carry any references", __func__, m));
4035         KASSERT(nflag == PGA_REQUEUE || nflag == PGA_REQUEUE_HEAD,
4036             ("%s: invalid flags %x", __func__, nflag));
4037
4038         if ((m->oflags & VPO_UNMANAGED) != 0 || vm_page_wired(m))
4039                 return;
4040
4041         old = vm_page_astate_load(m);
4042         do {
4043                 if ((old.flags & PGA_DEQUEUE) != 0)
4044                         break;
4045                 new = old;
4046                 new.flags &= ~PGA_QUEUE_OP_MASK;
4047                 if (nqueue == PQ_ACTIVE)
4048                         new.act_count = max(old.act_count, ACT_INIT);
4049                 if (old.queue == nqueue) {
4050                         if (nqueue != PQ_ACTIVE)
4051                                 new.flags |= nflag;
4052                 } else {
4053                         new.flags |= nflag;
4054                         new.queue = nqueue;
4055                 }
4056         } while (!vm_page_pqstate_commit(m, &old, new));
4057 }
4058
4059 /*
4060  * Put the specified page on the active list (if appropriate).
4061  */
4062 void
4063 vm_page_activate(vm_page_t m)
4064 {
4065
4066         vm_page_mvqueue(m, PQ_ACTIVE, PGA_REQUEUE);
4067 }
4068
4069 /*
4070  * Move the specified page to the tail of the inactive queue, or requeue
4071  * the page if it is already in the inactive queue.
4072  */
4073 void
4074 vm_page_deactivate(vm_page_t m)
4075 {
4076
4077         vm_page_mvqueue(m, PQ_INACTIVE, PGA_REQUEUE);
4078 }
4079
4080 void
4081 vm_page_deactivate_noreuse(vm_page_t m)
4082 {
4083
4084         vm_page_mvqueue(m, PQ_INACTIVE, PGA_REQUEUE_HEAD);
4085 }
4086
4087 /*
4088  * Put a page in the laundry, or requeue it if it is already there.
4089  */
4090 void
4091 vm_page_launder(vm_page_t m)
4092 {
4093
4094         vm_page_mvqueue(m, PQ_LAUNDRY, PGA_REQUEUE);
4095 }
4096
4097 /*
4098  * Put a page in the PQ_UNSWAPPABLE holding queue.
4099  */
4100 void
4101 vm_page_unswappable(vm_page_t m)
4102 {
4103
4104         KASSERT(!vm_page_wired(m) && (m->oflags & VPO_UNMANAGED) == 0,
4105             ("page %p already unswappable", m));
4106
4107         vm_page_dequeue(m);
4108         vm_page_enqueue(m, PQ_UNSWAPPABLE);
4109 }
4110
4111 /*
4112  * Release a page back to the page queues in preparation for unwiring.
4113  */
4114 static void
4115 vm_page_release_toq(vm_page_t m, uint8_t nqueue, const bool noreuse)
4116 {
4117         vm_page_astate_t old, new;
4118         uint16_t nflag;
4119
4120         /*
4121          * Use a check of the valid bits to determine whether we should
4122          * accelerate reclamation of the page.  The object lock might not be
4123          * held here, in which case the check is racy.  At worst we will either
4124          * accelerate reclamation of a valid page and violate LRU, or
4125          * unnecessarily defer reclamation of an invalid page.
4126          *
4127          * If we were asked to not cache the page, place it near the head of the
4128          * inactive queue so that is reclaimed sooner.
4129          */
4130         if (noreuse || m->valid == 0) {
4131                 nqueue = PQ_INACTIVE;
4132                 nflag = PGA_REQUEUE_HEAD;
4133         } else {
4134                 nflag = PGA_REQUEUE;
4135         }
4136
4137         old = vm_page_astate_load(m);
4138         do {
4139                 new = old;
4140
4141                 /*
4142                  * If the page is already in the active queue and we are not
4143                  * trying to accelerate reclamation, simply mark it as
4144                  * referenced and avoid any queue operations.
4145                  */
4146                 new.flags &= ~PGA_QUEUE_OP_MASK;
4147                 if (nflag != PGA_REQUEUE_HEAD && old.queue == PQ_ACTIVE)
4148                         new.flags |= PGA_REFERENCED;
4149                 else {
4150                         new.flags |= nflag;
4151                         new.queue = nqueue;
4152                 }
4153         } while (!vm_page_pqstate_commit(m, &old, new));
4154 }
4155
4156 /*
4157  * Unwire a page and either attempt to free it or re-add it to the page queues.
4158  */
4159 void
4160 vm_page_release(vm_page_t m, int flags)
4161 {
4162         vm_object_t object;
4163
4164         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4165             ("vm_page_release: page %p is unmanaged", m));
4166
4167         if ((flags & VPR_TRYFREE) != 0) {
4168                 for (;;) {
4169                         object = atomic_load_ptr(&m->object);
4170                         if (object == NULL)
4171                                 break;
4172                         /* Depends on type-stability. */
4173                         if (vm_page_busied(m) || !VM_OBJECT_TRYWLOCK(object))
4174                                 break;
4175                         if (object == m->object) {
4176                                 vm_page_release_locked(m, flags);
4177                                 VM_OBJECT_WUNLOCK(object);
4178                                 return;
4179                         }
4180                         VM_OBJECT_WUNLOCK(object);
4181                 }
4182         }
4183         vm_page_unwire_managed(m, PQ_INACTIVE, flags != 0);
4184 }
4185
4186 /* See vm_page_release(). */
4187 void
4188 vm_page_release_locked(vm_page_t m, int flags)
4189 {
4190
4191         VM_OBJECT_ASSERT_WLOCKED(m->object);
4192         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4193             ("vm_page_release_locked: page %p is unmanaged", m));
4194
4195         if (vm_page_unwire_noq(m)) {
4196                 if ((flags & VPR_TRYFREE) != 0 &&
4197                     (m->object->ref_count == 0 || !pmap_page_is_mapped(m)) &&
4198                     m->dirty == 0 && vm_page_tryxbusy(m)) {
4199                         /*
4200                          * An unlocked lookup may have wired the page before the
4201                          * busy lock was acquired, in which case the page must
4202                          * not be freed.
4203                          */
4204                         if (__predict_true(!vm_page_wired(m))) {
4205                                 vm_page_free(m);
4206                                 return;
4207                         }
4208                         vm_page_xunbusy(m);
4209                 } else {
4210                         vm_page_release_toq(m, PQ_INACTIVE, flags != 0);
4211                 }
4212         }
4213 }
4214
4215 static bool
4216 vm_page_try_blocked_op(vm_page_t m, void (*op)(vm_page_t))
4217 {
4218         u_int old;
4219
4220         KASSERT(m->object != NULL && (m->oflags & VPO_UNMANAGED) == 0,
4221             ("vm_page_try_blocked_op: page %p has no object", m));
4222         KASSERT(vm_page_busied(m),
4223             ("vm_page_try_blocked_op: page %p is not busy", m));
4224         VM_OBJECT_ASSERT_LOCKED(m->object);
4225
4226         old = m->ref_count;
4227         do {
4228                 KASSERT(old != 0,
4229                     ("vm_page_try_blocked_op: page %p has no references", m));
4230                 if (VPRC_WIRE_COUNT(old) != 0)
4231                         return (false);
4232         } while (!atomic_fcmpset_int(&m->ref_count, &old, old | VPRC_BLOCKED));
4233
4234         (op)(m);
4235
4236         /*
4237          * If the object is read-locked, new wirings may be created via an
4238          * object lookup.
4239          */
4240         old = vm_page_drop(m, VPRC_BLOCKED);
4241         KASSERT(!VM_OBJECT_WOWNED(m->object) ||
4242             old == (VPRC_BLOCKED | VPRC_OBJREF),
4243             ("vm_page_try_blocked_op: unexpected refcount value %u for %p",
4244             old, m));
4245         return (true);
4246 }
4247
4248 /*
4249  * Atomically check for wirings and remove all mappings of the page.
4250  */
4251 bool
4252 vm_page_try_remove_all(vm_page_t m)
4253 {
4254
4255         return (vm_page_try_blocked_op(m, pmap_remove_all));
4256 }
4257
4258 /*
4259  * Atomically check for wirings and remove all writeable mappings of the page.
4260  */
4261 bool
4262 vm_page_try_remove_write(vm_page_t m)
4263 {
4264
4265         return (vm_page_try_blocked_op(m, pmap_remove_write));
4266 }
4267
4268 /*
4269  * vm_page_advise
4270  *
4271  *      Apply the specified advice to the given page.
4272  *
4273  *      The object and page must be locked.
4274  */
4275 void
4276 vm_page_advise(vm_page_t m, int advice)
4277 {
4278
4279         VM_OBJECT_ASSERT_WLOCKED(m->object);
4280         if (advice == MADV_FREE)
4281                 /*
4282                  * Mark the page clean.  This will allow the page to be freed
4283                  * without first paging it out.  MADV_FREE pages are often
4284                  * quickly reused by malloc(3), so we do not do anything that
4285                  * would result in a page fault on a later access.
4286                  */
4287                 vm_page_undirty(m);
4288         else if (advice != MADV_DONTNEED) {
4289                 if (advice == MADV_WILLNEED)
4290                         vm_page_activate(m);
4291                 return;
4292         }
4293
4294         if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
4295                 vm_page_dirty(m);
4296
4297         /*
4298          * Clear any references to the page.  Otherwise, the page daemon will
4299          * immediately reactivate the page.
4300          */
4301         vm_page_aflag_clear(m, PGA_REFERENCED);
4302
4303         /*
4304          * Place clean pages near the head of the inactive queue rather than
4305          * the tail, thus defeating the queue's LRU operation and ensuring that
4306          * the page will be reused quickly.  Dirty pages not already in the
4307          * laundry are moved there.
4308          */
4309         if (m->dirty == 0)
4310                 vm_page_deactivate_noreuse(m);
4311         else if (!vm_page_in_laundry(m))
4312                 vm_page_launder(m);
4313 }
4314
4315 /*
4316  *      vm_page_grab_release
4317  *
4318  *      Helper routine for grab functions to release busy on return.
4319  */
4320 static inline void
4321 vm_page_grab_release(vm_page_t m, int allocflags)
4322 {
4323
4324         if ((allocflags & VM_ALLOC_NOBUSY) != 0) {
4325                 if ((allocflags & VM_ALLOC_IGN_SBUSY) != 0)
4326                         vm_page_sunbusy(m);
4327                 else
4328                         vm_page_xunbusy(m);
4329         }
4330 }
4331
4332 /*
4333  *      vm_page_grab_sleep
4334  *
4335  *      Sleep for busy according to VM_ALLOC_ parameters.  Returns true
4336  *      if the caller should retry and false otherwise.
4337  *
4338  *      If the object is locked on entry the object will be unlocked with
4339  *      false returns and still locked but possibly having been dropped
4340  *      with true returns.
4341  */
4342 static bool
4343 vm_page_grab_sleep(vm_object_t object, vm_page_t m, vm_pindex_t pindex,
4344     const char *wmesg, int allocflags, bool locked)
4345 {
4346
4347         if ((allocflags & VM_ALLOC_NOWAIT) != 0)
4348                 return (false);
4349
4350         /*
4351          * Reference the page before unlocking and sleeping so that
4352          * the page daemon is less likely to reclaim it.
4353          */
4354         if (locked && (allocflags & VM_ALLOC_NOCREAT) == 0)
4355                 vm_page_reference(m);
4356
4357         if (_vm_page_busy_sleep(object, m, m->pindex, wmesg, allocflags,
4358             locked) && locked)
4359                 VM_OBJECT_WLOCK(object);
4360         if ((allocflags & VM_ALLOC_WAITFAIL) != 0)
4361                 return (false);
4362
4363         return (true);
4364 }
4365
4366 /*
4367  * Assert that the grab flags are valid.
4368  */
4369 static inline void
4370 vm_page_grab_check(int allocflags)
4371 {
4372
4373         KASSERT((allocflags & VM_ALLOC_NOBUSY) == 0 ||
4374             (allocflags & VM_ALLOC_WIRED) != 0,
4375             ("vm_page_grab*: the pages must be busied or wired"));
4376
4377         KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4378             (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4379             ("vm_page_grab*: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
4380 }
4381
4382 /*
4383  * Calculate the page allocation flags for grab.
4384  */
4385 static inline int
4386 vm_page_grab_pflags(int allocflags)
4387 {
4388         int pflags;
4389
4390         pflags = allocflags &
4391             ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL |
4392             VM_ALLOC_NOBUSY);
4393         if ((allocflags & VM_ALLOC_NOWAIT) == 0)
4394                 pflags |= VM_ALLOC_WAITFAIL;
4395         if ((allocflags & VM_ALLOC_IGN_SBUSY) != 0)
4396                 pflags |= VM_ALLOC_SBUSY;
4397
4398         return (pflags);
4399 }
4400
4401 /*
4402  * Grab a page, waiting until we are waken up due to the page
4403  * changing state.  We keep on waiting, if the page continues
4404  * to be in the object.  If the page doesn't exist, first allocate it
4405  * and then conditionally zero it.
4406  *
4407  * This routine may sleep.
4408  *
4409  * The object must be locked on entry.  The lock will, however, be released
4410  * and reacquired if the routine sleeps.
4411  */
4412 vm_page_t
4413 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
4414 {
4415         vm_page_t m;
4416
4417         VM_OBJECT_ASSERT_WLOCKED(object);
4418         vm_page_grab_check(allocflags);
4419
4420 retrylookup:
4421         if ((m = vm_page_lookup(object, pindex)) != NULL) {
4422                 if (!vm_page_tryacquire(m, allocflags)) {
4423                         if (vm_page_grab_sleep(object, m, pindex, "pgrbwt",
4424                             allocflags, true))
4425                                 goto retrylookup;
4426                         return (NULL);
4427                 }
4428                 goto out;
4429         }
4430         if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4431                 return (NULL);
4432         m = vm_page_alloc(object, pindex, vm_page_grab_pflags(allocflags));
4433         if (m == NULL) {
4434                 if ((allocflags & (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL)) != 0)
4435                         return (NULL);
4436                 goto retrylookup;
4437         }
4438         if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
4439                 pmap_zero_page(m);
4440
4441 out:
4442         vm_page_grab_release(m, allocflags);
4443
4444         return (m);
4445 }
4446
4447 /*
4448  * Locklessly attempt to acquire a page given a (object, pindex) tuple
4449  * and an optional previous page to avoid the radix lookup.  The resulting
4450  * page will be validated against the identity tuple and busied or wired
4451  * as requested.  A NULL *mp return guarantees that the page was not in
4452  * radix at the time of the call but callers must perform higher level
4453  * synchronization or retry the operation under a lock if they require
4454  * an atomic answer.  This is the only lock free validation routine,
4455  * other routines can depend on the resulting page state.
4456  *
4457  * The return value indicates whether the operation failed due to caller
4458  * flags.  The return is tri-state with mp:
4459  *
4460  * (true, *mp != NULL) - The operation was successful.
4461  * (true, *mp == NULL) - The page was not found in tree.
4462  * (false, *mp == NULL) - WAITFAIL or NOWAIT prevented acquisition.
4463  */
4464 static bool
4465 vm_page_acquire_unlocked(vm_object_t object, vm_pindex_t pindex,
4466     vm_page_t prev, vm_page_t *mp, int allocflags)
4467 {
4468         vm_page_t m;
4469
4470         vm_page_grab_check(allocflags);
4471         MPASS(prev == NULL || vm_page_busied(prev) || vm_page_wired(prev));
4472
4473         *mp = NULL;
4474         for (;;) {
4475                 /*
4476                  * We may see a false NULL here because the previous page
4477                  * has been removed or just inserted and the list is loaded
4478                  * without barriers.  Switch to radix to verify.
4479                  */
4480                 if (prev == NULL || (m = TAILQ_NEXT(prev, listq)) == NULL ||
4481                     QMD_IS_TRASHED(m) || m->pindex != pindex ||
4482                     atomic_load_ptr(&m->object) != object) {
4483                         prev = NULL;
4484                         /*
4485                          * This guarantees the result is instantaneously
4486                          * correct.
4487                          */
4488                         m = vm_radix_lookup_unlocked(&object->rtree, pindex);
4489                 }
4490                 if (m == NULL)
4491                         return (true);
4492                 if (vm_page_trybusy(m, allocflags)) {
4493                         if (m->object == object && m->pindex == pindex)
4494                                 break;
4495                         /* relookup. */
4496                         vm_page_busy_release(m);
4497                         cpu_spinwait();
4498                         continue;
4499                 }
4500                 if (!vm_page_grab_sleep(object, m, pindex, "pgnslp",
4501                     allocflags, false))
4502                         return (false);
4503         }
4504         if ((allocflags & VM_ALLOC_WIRED) != 0)
4505                 vm_page_wire(m);
4506         vm_page_grab_release(m, allocflags);
4507         *mp = m;
4508         return (true);
4509 }
4510
4511 /*
4512  * Try to locklessly grab a page and fall back to the object lock if NOCREAT
4513  * is not set.
4514  */
4515 vm_page_t
4516 vm_page_grab_unlocked(vm_object_t object, vm_pindex_t pindex, int allocflags)
4517 {
4518         vm_page_t m;
4519
4520         vm_page_grab_check(allocflags);
4521
4522         if (!vm_page_acquire_unlocked(object, pindex, NULL, &m, allocflags))
4523                 return (NULL);
4524         if (m != NULL)
4525                 return (m);
4526
4527         /*
4528          * The radix lockless lookup should never return a false negative
4529          * errors.  If the user specifies NOCREAT they are guaranteed there
4530          * was no page present at the instant of the call.  A NOCREAT caller
4531          * must handle create races gracefully.
4532          */
4533         if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4534                 return (NULL);
4535
4536         VM_OBJECT_WLOCK(object);
4537         m = vm_page_grab(object, pindex, allocflags);
4538         VM_OBJECT_WUNLOCK(object);
4539
4540         return (m);
4541 }
4542
4543 /*
4544  * Grab a page and make it valid, paging in if necessary.  Pages missing from
4545  * their pager are zero filled and validated.  If a VM_ALLOC_COUNT is supplied
4546  * and the page is not valid as many as VM_INITIAL_PAGEIN pages can be brought
4547  * in simultaneously.  Additional pages will be left on a paging queue but
4548  * will neither be wired nor busy regardless of allocflags.
4549  */
4550 int
4551 vm_page_grab_valid(vm_page_t *mp, vm_object_t object, vm_pindex_t pindex, int allocflags)
4552 {
4553         vm_page_t m;
4554         vm_page_t ma[VM_INITIAL_PAGEIN];
4555         int after, i, pflags, rv;
4556
4557         KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4558             (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4559             ("vm_page_grab_valid: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
4560         KASSERT((allocflags &
4561             (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL | VM_ALLOC_ZERO)) == 0,
4562             ("vm_page_grab_valid: Invalid flags 0x%X", allocflags));
4563         VM_OBJECT_ASSERT_WLOCKED(object);
4564         pflags = allocflags & ~(VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY |
4565             VM_ALLOC_WIRED);
4566         pflags |= VM_ALLOC_WAITFAIL;
4567
4568 retrylookup:
4569         if ((m = vm_page_lookup(object, pindex)) != NULL) {
4570                 /*
4571                  * If the page is fully valid it can only become invalid
4572                  * with the object lock held.  If it is not valid it can
4573                  * become valid with the busy lock held.  Therefore, we
4574                  * may unnecessarily lock the exclusive busy here if we
4575                  * race with I/O completion not using the object lock.
4576                  * However, we will not end up with an invalid page and a
4577                  * shared lock.
4578                  */
4579                 if (!vm_page_trybusy(m,
4580                     vm_page_all_valid(m) ? allocflags : 0)) {
4581                         (void)vm_page_grab_sleep(object, m, pindex, "pgrbwt",
4582                             allocflags, true);
4583                         goto retrylookup;
4584                 }
4585                 if (vm_page_all_valid(m))
4586                         goto out;
4587                 if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
4588                         vm_page_busy_release(m);
4589                         *mp = NULL;
4590                         return (VM_PAGER_FAIL);
4591                 }
4592         } else if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
4593                 *mp = NULL;
4594                 return (VM_PAGER_FAIL);
4595         } else if ((m = vm_page_alloc(object, pindex, pflags)) == NULL) {
4596                 goto retrylookup;
4597         }
4598
4599         vm_page_assert_xbusied(m);
4600         if (vm_pager_has_page(object, pindex, NULL, &after)) {
4601                 after = MIN(after, VM_INITIAL_PAGEIN);
4602                 after = MIN(after, allocflags >> VM_ALLOC_COUNT_SHIFT);
4603                 after = MAX(after, 1);
4604                 ma[0] = m;
4605                 for (i = 1; i < after; i++) {
4606                         if ((ma[i] = vm_page_next(ma[i - 1])) != NULL) {
4607                                 if (ma[i]->valid || !vm_page_tryxbusy(ma[i]))
4608                                         break;
4609                         } else {
4610                                 ma[i] = vm_page_alloc(object, m->pindex + i,
4611                                     VM_ALLOC_NORMAL);
4612                                 if (ma[i] == NULL)
4613                                         break;
4614                         }
4615                 }
4616                 after = i;
4617                 vm_object_pip_add(object, after);
4618                 VM_OBJECT_WUNLOCK(object);
4619                 rv = vm_pager_get_pages(object, ma, after, NULL, NULL);
4620                 VM_OBJECT_WLOCK(object);
4621                 vm_object_pip_wakeupn(object, after);
4622                 /* Pager may have replaced a page. */
4623                 m = ma[0];
4624                 if (rv != VM_PAGER_OK) {
4625                         for (i = 0; i < after; i++) {
4626                                 if (!vm_page_wired(ma[i]))
4627                                         vm_page_free(ma[i]);
4628                                 else
4629                                         vm_page_xunbusy(ma[i]);
4630                         }
4631                         *mp = NULL;
4632                         return (rv);
4633                 }
4634                 for (i = 1; i < after; i++)
4635                         vm_page_readahead_finish(ma[i]);
4636                 MPASS(vm_page_all_valid(m));
4637         } else {
4638                 vm_page_zero_invalid(m, TRUE);
4639         }
4640 out:
4641         if ((allocflags & VM_ALLOC_WIRED) != 0)
4642                 vm_page_wire(m);
4643         if ((allocflags & VM_ALLOC_SBUSY) != 0 && vm_page_xbusied(m))
4644                 vm_page_busy_downgrade(m);
4645         else if ((allocflags & VM_ALLOC_NOBUSY) != 0)
4646                 vm_page_busy_release(m);
4647         *mp = m;
4648         return (VM_PAGER_OK);
4649 }
4650
4651 /*
4652  * Locklessly grab a valid page.  If the page is not valid or not yet
4653  * allocated this will fall back to the object lock method.
4654  */
4655 int
4656 vm_page_grab_valid_unlocked(vm_page_t *mp, vm_object_t object,
4657     vm_pindex_t pindex, int allocflags)
4658 {
4659         vm_page_t m;
4660         int flags;
4661         int error;
4662
4663         KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4664             (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4665             ("vm_page_grab_valid_unlocked: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY "
4666             "mismatch"));
4667         KASSERT((allocflags &
4668             (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL | VM_ALLOC_ZERO)) == 0,
4669             ("vm_page_grab_valid_unlocked: Invalid flags 0x%X", allocflags));
4670
4671         /*
4672          * Attempt a lockless lookup and busy.  We need at least an sbusy
4673          * before we can inspect the valid field and return a wired page.
4674          */
4675         flags = allocflags & ~(VM_ALLOC_NOBUSY | VM_ALLOC_WIRED);
4676         if (!vm_page_acquire_unlocked(object, pindex, NULL, mp, flags))
4677                 return (VM_PAGER_FAIL);
4678         if ((m = *mp) != NULL) {
4679                 if (vm_page_all_valid(m)) {
4680                         if ((allocflags & VM_ALLOC_WIRED) != 0)
4681                                 vm_page_wire(m);
4682                         vm_page_grab_release(m, allocflags);
4683                         return (VM_PAGER_OK);
4684                 }
4685                 vm_page_busy_release(m);
4686         }
4687         if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
4688                 *mp = NULL;
4689                 return (VM_PAGER_FAIL);
4690         }
4691         VM_OBJECT_WLOCK(object);
4692         error = vm_page_grab_valid(mp, object, pindex, allocflags);
4693         VM_OBJECT_WUNLOCK(object);
4694
4695         return (error);
4696 }
4697
4698 /*
4699  * Return the specified range of pages from the given object.  For each
4700  * page offset within the range, if a page already exists within the object
4701  * at that offset and it is busy, then wait for it to change state.  If,
4702  * instead, the page doesn't exist, then allocate it.
4703  *
4704  * The caller must always specify an allocation class.
4705  *
4706  * allocation classes:
4707  *      VM_ALLOC_NORMAL         normal process request
4708  *      VM_ALLOC_SYSTEM         system *really* needs the pages
4709  *
4710  * The caller must always specify that the pages are to be busied and/or
4711  * wired.
4712  *
4713  * optional allocation flags:
4714  *      VM_ALLOC_IGN_SBUSY      do not sleep on soft busy pages
4715  *      VM_ALLOC_NOBUSY         do not exclusive busy the page
4716  *      VM_ALLOC_NOWAIT         do not sleep
4717  *      VM_ALLOC_SBUSY          set page to sbusy state
4718  *      VM_ALLOC_WIRED          wire the pages
4719  *      VM_ALLOC_ZERO           zero and validate any invalid pages
4720  *
4721  * If VM_ALLOC_NOWAIT is not specified, this routine may sleep.  Otherwise, it
4722  * may return a partial prefix of the requested range.
4723  */
4724 int
4725 vm_page_grab_pages(vm_object_t object, vm_pindex_t pindex, int allocflags,
4726     vm_page_t *ma, int count)
4727 {
4728         vm_page_t m, mpred;
4729         int pflags;
4730         int i;
4731
4732         VM_OBJECT_ASSERT_WLOCKED(object);
4733         KASSERT(((u_int)allocflags >> VM_ALLOC_COUNT_SHIFT) == 0,
4734             ("vm_page_grap_pages: VM_ALLOC_COUNT() is not allowed"));
4735         vm_page_grab_check(allocflags);
4736
4737         pflags = vm_page_grab_pflags(allocflags);
4738         if (count == 0)
4739                 return (0);
4740
4741         i = 0;
4742 retrylookup:
4743         m = vm_radix_lookup_le(&object->rtree, pindex + i);
4744         if (m == NULL || m->pindex != pindex + i) {
4745                 mpred = m;
4746                 m = NULL;
4747         } else
4748                 mpred = TAILQ_PREV(m, pglist, listq);
4749         for (; i < count; i++) {
4750                 if (m != NULL) {
4751                         if (!vm_page_tryacquire(m, allocflags)) {
4752                                 if (vm_page_grab_sleep(object, m, pindex,
4753                                     "grbmaw", allocflags, true))
4754                                         goto retrylookup;
4755                                 break;
4756                         }
4757                 } else {
4758                         if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4759                                 break;
4760                         m = vm_page_alloc_after(object, pindex + i,
4761                             pflags | VM_ALLOC_COUNT(count - i), mpred);
4762                         if (m == NULL) {
4763                                 if ((allocflags & (VM_ALLOC_NOWAIT |
4764                                     VM_ALLOC_WAITFAIL)) != 0)
4765                                         break;
4766                                 goto retrylookup;
4767                         }
4768                 }
4769                 if (vm_page_none_valid(m) &&
4770                     (allocflags & VM_ALLOC_ZERO) != 0) {
4771                         if ((m->flags & PG_ZERO) == 0)
4772                                 pmap_zero_page(m);
4773                         vm_page_valid(m);
4774                 }
4775                 vm_page_grab_release(m, allocflags);
4776                 ma[i] = mpred = m;
4777                 m = vm_page_next(m);
4778         }
4779         return (i);
4780 }
4781
4782 /*
4783  * Unlocked variant of vm_page_grab_pages().  This accepts the same flags
4784  * and will fall back to the locked variant to handle allocation.
4785  */
4786 int
4787 vm_page_grab_pages_unlocked(vm_object_t object, vm_pindex_t pindex,
4788     int allocflags, vm_page_t *ma, int count)
4789 {
4790         vm_page_t m, pred;
4791         int flags;
4792         int i;
4793
4794         vm_page_grab_check(allocflags);
4795
4796         /*
4797          * Modify flags for lockless acquire to hold the page until we
4798          * set it valid if necessary.
4799          */
4800         flags = allocflags & ~VM_ALLOC_NOBUSY;
4801         pred = NULL;
4802         for (i = 0; i < count; i++, pindex++) {
4803                 if (!vm_page_acquire_unlocked(object, pindex, pred, &m, flags))
4804                         return (i);
4805                 if (m == NULL)
4806                         break;
4807                 if ((flags & VM_ALLOC_ZERO) != 0 && vm_page_none_valid(m)) {
4808                         if ((m->flags & PG_ZERO) == 0)
4809                                 pmap_zero_page(m);
4810                         vm_page_valid(m);
4811                 }
4812                 /* m will still be wired or busy according to flags. */
4813                 vm_page_grab_release(m, allocflags);
4814                 pred = ma[i] = m;
4815         }
4816         if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4817                 return (i);
4818         count -= i;
4819         VM_OBJECT_WLOCK(object);
4820         i += vm_page_grab_pages(object, pindex, allocflags, &ma[i], count);
4821         VM_OBJECT_WUNLOCK(object);
4822
4823         return (i);
4824 }
4825
4826 /*
4827  * Mapping function for valid or dirty bits in a page.
4828  *
4829  * Inputs are required to range within a page.
4830  */
4831 vm_page_bits_t
4832 vm_page_bits(int base, int size)
4833 {
4834         int first_bit;
4835         int last_bit;
4836
4837         KASSERT(
4838             base + size <= PAGE_SIZE,
4839             ("vm_page_bits: illegal base/size %d/%d", base, size)
4840         );
4841
4842         if (size == 0)          /* handle degenerate case */
4843                 return (0);
4844
4845         first_bit = base >> DEV_BSHIFT;
4846         last_bit = (base + size - 1) >> DEV_BSHIFT;
4847
4848         return (((vm_page_bits_t)2 << last_bit) -
4849             ((vm_page_bits_t)1 << first_bit));
4850 }
4851
4852 void
4853 vm_page_bits_set(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t set)
4854 {
4855
4856 #if PAGE_SIZE == 32768
4857         atomic_set_64((uint64_t *)bits, set);
4858 #elif PAGE_SIZE == 16384
4859         atomic_set_32((uint32_t *)bits, set);
4860 #elif (PAGE_SIZE == 8192) && defined(atomic_set_16)
4861         atomic_set_16((uint16_t *)bits, set);
4862 #elif (PAGE_SIZE == 4096) && defined(atomic_set_8)
4863         atomic_set_8((uint8_t *)bits, set);
4864 #else           /* PAGE_SIZE <= 8192 */
4865         uintptr_t addr;
4866         int shift;
4867
4868         addr = (uintptr_t)bits;
4869         /*
4870          * Use a trick to perform a 32-bit atomic on the
4871          * containing aligned word, to not depend on the existence
4872          * of atomic_{set, clear}_{8, 16}.
4873          */
4874         shift = addr & (sizeof(uint32_t) - 1);
4875 #if BYTE_ORDER == BIG_ENDIAN
4876         shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
4877 #else
4878         shift *= NBBY;
4879 #endif
4880         addr &= ~(sizeof(uint32_t) - 1);
4881         atomic_set_32((uint32_t *)addr, set << shift);
4882 #endif          /* PAGE_SIZE */
4883 }
4884
4885 static inline void
4886 vm_page_bits_clear(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t clear)
4887 {
4888
4889 #if PAGE_SIZE == 32768
4890         atomic_clear_64((uint64_t *)bits, clear);
4891 #elif PAGE_SIZE == 16384
4892         atomic_clear_32((uint32_t *)bits, clear);
4893 #elif (PAGE_SIZE == 8192) && defined(atomic_clear_16)
4894         atomic_clear_16((uint16_t *)bits, clear);
4895 #elif (PAGE_SIZE == 4096) && defined(atomic_clear_8)
4896         atomic_clear_8((uint8_t *)bits, clear);
4897 #else           /* PAGE_SIZE <= 8192 */
4898         uintptr_t addr;
4899         int shift;
4900
4901         addr = (uintptr_t)bits;
4902         /*
4903          * Use a trick to perform a 32-bit atomic on the
4904          * containing aligned word, to not depend on the existence
4905          * of atomic_{set, clear}_{8, 16}.
4906          */
4907         shift = addr & (sizeof(uint32_t) - 1);
4908 #if BYTE_ORDER == BIG_ENDIAN
4909         shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
4910 #else
4911         shift *= NBBY;
4912 #endif
4913         addr &= ~(sizeof(uint32_t) - 1);
4914         atomic_clear_32((uint32_t *)addr, clear << shift);
4915 #endif          /* PAGE_SIZE */
4916 }
4917
4918 static inline vm_page_bits_t
4919 vm_page_bits_swap(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t newbits)
4920 {
4921 #if PAGE_SIZE == 32768
4922         uint64_t old;
4923
4924         old = *bits;
4925         while (atomic_fcmpset_64(bits, &old, newbits) == 0);
4926         return (old);
4927 #elif PAGE_SIZE == 16384
4928         uint32_t old;
4929
4930         old = *bits;
4931         while (atomic_fcmpset_32(bits, &old, newbits) == 0);
4932         return (old);
4933 #elif (PAGE_SIZE == 8192) && defined(atomic_fcmpset_16)
4934         uint16_t old;
4935
4936         old = *bits;
4937         while (atomic_fcmpset_16(bits, &old, newbits) == 0);
4938         return (old);
4939 #elif (PAGE_SIZE == 4096) && defined(atomic_fcmpset_8)
4940         uint8_t old;
4941
4942         old = *bits;
4943         while (atomic_fcmpset_8(bits, &old, newbits) == 0);
4944         return (old);
4945 #else           /* PAGE_SIZE <= 4096*/
4946         uintptr_t addr;
4947         uint32_t old, new, mask;
4948         int shift;
4949
4950         addr = (uintptr_t)bits;
4951         /*
4952          * Use a trick to perform a 32-bit atomic on the
4953          * containing aligned word, to not depend on the existence
4954          * of atomic_{set, swap, clear}_{8, 16}.
4955          */
4956         shift = addr & (sizeof(uint32_t) - 1);
4957 #if BYTE_ORDER == BIG_ENDIAN
4958         shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
4959 #else
4960         shift *= NBBY;
4961 #endif
4962         addr &= ~(sizeof(uint32_t) - 1);
4963         mask = VM_PAGE_BITS_ALL << shift;
4964
4965         old = *bits;
4966         do {
4967                 new = old & ~mask;
4968                 new |= newbits << shift;
4969         } while (atomic_fcmpset_32((uint32_t *)addr, &old, new) == 0);
4970         return (old >> shift);
4971 #endif          /* PAGE_SIZE */
4972 }
4973
4974 /*
4975  *      vm_page_set_valid_range:
4976  *
4977  *      Sets portions of a page valid.  The arguments are expected
4978  *      to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
4979  *      of any partial chunks touched by the range.  The invalid portion of
4980  *      such chunks will be zeroed.
4981  *
4982  *      (base + size) must be less then or equal to PAGE_SIZE.
4983  */
4984 void
4985 vm_page_set_valid_range(vm_page_t m, int base, int size)
4986 {
4987         int endoff, frag;
4988         vm_page_bits_t pagebits;
4989
4990         vm_page_assert_busied(m);
4991         if (size == 0)  /* handle degenerate case */
4992                 return;
4993
4994         /*
4995          * If the base is not DEV_BSIZE aligned and the valid
4996          * bit is clear, we have to zero out a portion of the
4997          * first block.
4998          */
4999         if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
5000             (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
5001                 pmap_zero_page_area(m, frag, base - frag);
5002
5003         /*
5004          * If the ending offset is not DEV_BSIZE aligned and the
5005          * valid bit is clear, we have to zero out a portion of
5006          * the last block.
5007          */
5008         endoff = base + size;
5009         if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
5010             (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
5011                 pmap_zero_page_area(m, endoff,
5012                     DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
5013
5014         /*
5015          * Assert that no previously invalid block that is now being validated
5016          * is already dirty.
5017          */
5018         KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
5019             ("vm_page_set_valid_range: page %p is dirty", m));
5020
5021         /*
5022          * Set valid bits inclusive of any overlap.
5023          */
5024         pagebits = vm_page_bits(base, size);
5025         if (vm_page_xbusied(m))
5026                 m->valid |= pagebits;
5027         else
5028                 vm_page_bits_set(m, &m->valid, pagebits);
5029 }
5030
5031 /*
5032  * Set the page dirty bits and free the invalid swap space if
5033  * present.  Returns the previous dirty bits.
5034  */
5035 vm_page_bits_t
5036 vm_page_set_dirty(vm_page_t m)
5037 {
5038         vm_page_bits_t old;
5039
5040         VM_PAGE_OBJECT_BUSY_ASSERT(m);
5041
5042         if (vm_page_xbusied(m) && !pmap_page_is_write_mapped(m)) {
5043                 old = m->dirty;
5044                 m->dirty = VM_PAGE_BITS_ALL;
5045         } else
5046                 old = vm_page_bits_swap(m, &m->dirty, VM_PAGE_BITS_ALL);
5047         if (old == 0 && (m->a.flags & PGA_SWAP_SPACE) != 0)
5048                 vm_pager_page_unswapped(m);
5049
5050         return (old);
5051 }
5052
5053 /*
5054  * Clear the given bits from the specified page's dirty field.
5055  */
5056 static __inline void
5057 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
5058 {
5059
5060         vm_page_assert_busied(m);
5061
5062         /*
5063          * If the page is xbusied and not write mapped we are the
5064          * only thread that can modify dirty bits.  Otherwise, The pmap
5065          * layer can call vm_page_dirty() without holding a distinguished
5066          * lock.  The combination of page busy and atomic operations
5067          * suffice to guarantee consistency of the page dirty field.
5068          */
5069         if (vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
5070                 m->dirty &= ~pagebits;
5071         else
5072                 vm_page_bits_clear(m, &m->dirty, pagebits);
5073 }
5074
5075 /*
5076  *      vm_page_set_validclean:
5077  *
5078  *      Sets portions of a page valid and clean.  The arguments are expected
5079  *      to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
5080  *      of any partial chunks touched by the range.  The invalid portion of
5081  *      such chunks will be zero'd.
5082  *
5083  *      (base + size) must be less then or equal to PAGE_SIZE.
5084  */
5085 void
5086 vm_page_set_validclean(vm_page_t m, int base, int size)
5087 {
5088         vm_page_bits_t oldvalid, pagebits;
5089         int endoff, frag;
5090
5091         vm_page_assert_busied(m);
5092         if (size == 0)  /* handle degenerate case */
5093                 return;
5094
5095         /*
5096          * If the base is not DEV_BSIZE aligned and the valid
5097          * bit is clear, we have to zero out a portion of the
5098          * first block.
5099          */
5100         if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
5101             (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
5102                 pmap_zero_page_area(m, frag, base - frag);
5103
5104         /*
5105          * If the ending offset is not DEV_BSIZE aligned and the
5106          * valid bit is clear, we have to zero out a portion of
5107          * the last block.
5108          */
5109         endoff = base + size;
5110         if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
5111             (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
5112                 pmap_zero_page_area(m, endoff,
5113                     DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
5114
5115         /*
5116          * Set valid, clear dirty bits.  If validating the entire
5117          * page we can safely clear the pmap modify bit.  We also
5118          * use this opportunity to clear the PGA_NOSYNC flag.  If a process
5119          * takes a write fault on a MAP_NOSYNC memory area the flag will
5120          * be set again.
5121          *
5122          * We set valid bits inclusive of any overlap, but we can only
5123          * clear dirty bits for DEV_BSIZE chunks that are fully within
5124          * the range.
5125          */
5126         oldvalid = m->valid;
5127         pagebits = vm_page_bits(base, size);
5128         if (vm_page_xbusied(m))
5129                 m->valid |= pagebits;
5130         else
5131                 vm_page_bits_set(m, &m->valid, pagebits);
5132 #if 0   /* NOT YET */
5133         if ((frag = base & (DEV_BSIZE - 1)) != 0) {
5134                 frag = DEV_BSIZE - frag;
5135                 base += frag;
5136                 size -= frag;
5137                 if (size < 0)
5138                         size = 0;
5139         }
5140         pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
5141 #endif
5142         if (base == 0 && size == PAGE_SIZE) {
5143                 /*
5144                  * The page can only be modified within the pmap if it is
5145                  * mapped, and it can only be mapped if it was previously
5146                  * fully valid.
5147                  */
5148                 if (oldvalid == VM_PAGE_BITS_ALL)
5149                         /*
5150                          * Perform the pmap_clear_modify() first.  Otherwise,
5151                          * a concurrent pmap operation, such as
5152                          * pmap_protect(), could clear a modification in the
5153                          * pmap and set the dirty field on the page before
5154                          * pmap_clear_modify() had begun and after the dirty
5155                          * field was cleared here.
5156                          */
5157                         pmap_clear_modify(m);
5158                 m->dirty = 0;
5159                 vm_page_aflag_clear(m, PGA_NOSYNC);
5160         } else if (oldvalid != VM_PAGE_BITS_ALL && vm_page_xbusied(m))
5161                 m->dirty &= ~pagebits;
5162         else
5163                 vm_page_clear_dirty_mask(m, pagebits);
5164 }
5165
5166 void
5167 vm_page_clear_dirty(vm_page_t m, int base, int size)
5168 {
5169
5170         vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
5171 }
5172
5173 /*
5174  *      vm_page_set_invalid:
5175  *
5176  *      Invalidates DEV_BSIZE'd chunks within a page.  Both the
5177  *      valid and dirty bits for the effected areas are cleared.
5178  */
5179 void
5180 vm_page_set_invalid(vm_page_t m, int base, int size)
5181 {
5182         vm_page_bits_t bits;
5183         vm_object_t object;
5184
5185         /*
5186          * The object lock is required so that pages can't be mapped
5187          * read-only while we're in the process of invalidating them.
5188          */
5189         object = m->object;
5190         VM_OBJECT_ASSERT_WLOCKED(object);
5191         vm_page_assert_busied(m);
5192
5193         if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
5194             size >= object->un_pager.vnp.vnp_size)
5195                 bits = VM_PAGE_BITS_ALL;
5196         else
5197                 bits = vm_page_bits(base, size);
5198         if (object->ref_count != 0 && vm_page_all_valid(m) && bits != 0)
5199                 pmap_remove_all(m);
5200         KASSERT((bits == 0 && vm_page_all_valid(m)) ||
5201             !pmap_page_is_mapped(m),
5202             ("vm_page_set_invalid: page %p is mapped", m));
5203         if (vm_page_xbusied(m)) {
5204                 m->valid &= ~bits;
5205                 m->dirty &= ~bits;
5206         } else {
5207                 vm_page_bits_clear(m, &m->valid, bits);
5208                 vm_page_bits_clear(m, &m->dirty, bits);
5209         }
5210 }
5211
5212 /*
5213  *      vm_page_invalid:
5214  *
5215  *      Invalidates the entire page.  The page must be busy, unmapped, and
5216  *      the enclosing object must be locked.  The object locks protects
5217  *      against concurrent read-only pmap enter which is done without
5218  *      busy.
5219  */
5220 void
5221 vm_page_invalid(vm_page_t m)
5222 {
5223
5224         vm_page_assert_busied(m);
5225         VM_OBJECT_ASSERT_LOCKED(m->object);
5226         MPASS(!pmap_page_is_mapped(m));
5227
5228         if (vm_page_xbusied(m))
5229                 m->valid = 0;
5230         else
5231                 vm_page_bits_clear(m, &m->valid, VM_PAGE_BITS_ALL);
5232 }
5233
5234 /*
5235  * vm_page_zero_invalid()
5236  *
5237  *      The kernel assumes that the invalid portions of a page contain
5238  *      garbage, but such pages can be mapped into memory by user code.
5239  *      When this occurs, we must zero out the non-valid portions of the
5240  *      page so user code sees what it expects.
5241  *
5242  *      Pages are most often semi-valid when the end of a file is mapped
5243  *      into memory and the file's size is not page aligned.
5244  */
5245 void
5246 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
5247 {
5248         int b;
5249         int i;
5250
5251         /*
5252          * Scan the valid bits looking for invalid sections that
5253          * must be zeroed.  Invalid sub-DEV_BSIZE'd areas ( where the
5254          * valid bit may be set ) have already been zeroed by
5255          * vm_page_set_validclean().
5256          */
5257         for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
5258                 if (i == (PAGE_SIZE / DEV_BSIZE) ||
5259                     (m->valid & ((vm_page_bits_t)1 << i))) {
5260                         if (i > b) {
5261                                 pmap_zero_page_area(m,
5262                                     b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
5263                         }
5264                         b = i + 1;
5265                 }
5266         }
5267
5268         /*
5269          * setvalid is TRUE when we can safely set the zero'd areas
5270          * as being valid.  We can do this if there are no cache consistancy
5271          * issues.  e.g. it is ok to do with UFS, but not ok to do with NFS.
5272          */
5273         if (setvalid)
5274                 vm_page_valid(m);
5275 }
5276
5277 /*
5278  *      vm_page_is_valid:
5279  *
5280  *      Is (partial) page valid?  Note that the case where size == 0
5281  *      will return FALSE in the degenerate case where the page is
5282  *      entirely invalid, and TRUE otherwise.
5283  *
5284  *      Some callers envoke this routine without the busy lock held and
5285  *      handle races via higher level locks.  Typical callers should
5286  *      hold a busy lock to prevent invalidation.
5287  */
5288 int
5289 vm_page_is_valid(vm_page_t m, int base, int size)
5290 {
5291         vm_page_bits_t bits;
5292
5293         bits = vm_page_bits(base, size);
5294         return (m->valid != 0 && (m->valid & bits) == bits);
5295 }
5296
5297 /*
5298  * Returns true if all of the specified predicates are true for the entire
5299  * (super)page and false otherwise.
5300  */
5301 bool
5302 vm_page_ps_test(vm_page_t m, int flags, vm_page_t skip_m)
5303 {
5304         vm_object_t object;
5305         int i, npages;
5306
5307         object = m->object;
5308         if (skip_m != NULL && skip_m->object != object)
5309                 return (false);
5310         VM_OBJECT_ASSERT_LOCKED(object);
5311         npages = atop(pagesizes[m->psind]);
5312
5313         /*
5314          * The physically contiguous pages that make up a superpage, i.e., a
5315          * page with a page size index ("psind") greater than zero, will
5316          * occupy adjacent entries in vm_page_array[].
5317          */
5318         for (i = 0; i < npages; i++) {
5319                 /* Always test object consistency, including "skip_m". */
5320                 if (m[i].object != object)
5321                         return (false);
5322                 if (&m[i] == skip_m)
5323                         continue;
5324                 if ((flags & PS_NONE_BUSY) != 0 && vm_page_busied(&m[i]))
5325                         return (false);
5326                 if ((flags & PS_ALL_DIRTY) != 0) {
5327                         /*
5328                          * Calling vm_page_test_dirty() or pmap_is_modified()
5329                          * might stop this case from spuriously returning
5330                          * "false".  However, that would require a write lock
5331                          * on the object containing "m[i]".
5332                          */
5333                         if (m[i].dirty != VM_PAGE_BITS_ALL)
5334                                 return (false);
5335                 }
5336                 if ((flags & PS_ALL_VALID) != 0 &&
5337                     m[i].valid != VM_PAGE_BITS_ALL)
5338                         return (false);
5339         }
5340         return (true);
5341 }
5342
5343 /*
5344  * Set the page's dirty bits if the page is modified.
5345  */
5346 void
5347 vm_page_test_dirty(vm_page_t m)
5348 {
5349
5350         vm_page_assert_busied(m);
5351         if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
5352                 vm_page_dirty(m);
5353 }
5354
5355 void
5356 vm_page_valid(vm_page_t m)
5357 {
5358
5359         vm_page_assert_busied(m);
5360         if (vm_page_xbusied(m))
5361                 m->valid = VM_PAGE_BITS_ALL;
5362         else
5363                 vm_page_bits_set(m, &m->valid, VM_PAGE_BITS_ALL);
5364 }
5365
5366 void
5367 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
5368 {
5369
5370         mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
5371 }
5372
5373 void
5374 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
5375 {
5376
5377         mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
5378 }
5379
5380 int
5381 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
5382 {
5383
5384         return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
5385 }
5386
5387 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
5388 void
5389 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
5390 {
5391
5392         vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
5393 }
5394
5395 void
5396 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
5397 {
5398
5399         mtx_assert_(vm_page_lockptr(m), a, file, line);
5400 }
5401 #endif
5402
5403 #ifdef INVARIANTS
5404 void
5405 vm_page_object_busy_assert(vm_page_t m)
5406 {
5407
5408         /*
5409          * Certain of the page's fields may only be modified by the
5410          * holder of a page or object busy.
5411          */
5412         if (m->object != NULL && !vm_page_busied(m))
5413                 VM_OBJECT_ASSERT_BUSY(m->object);
5414 }
5415
5416 void
5417 vm_page_assert_pga_writeable(vm_page_t m, uint16_t bits)
5418 {
5419
5420         if ((bits & PGA_WRITEABLE) == 0)
5421                 return;
5422
5423         /*
5424          * The PGA_WRITEABLE flag can only be set if the page is
5425          * managed, is exclusively busied or the object is locked.
5426          * Currently, this flag is only set by pmap_enter().
5427          */
5428         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5429             ("PGA_WRITEABLE on unmanaged page"));
5430         if (!vm_page_xbusied(m))
5431                 VM_OBJECT_ASSERT_BUSY(m->object);
5432 }
5433 #endif
5434
5435 #include "opt_ddb.h"
5436 #ifdef DDB
5437 #include <sys/kernel.h>
5438
5439 #include <ddb/ddb.h>
5440
5441 DB_SHOW_COMMAND(page, vm_page_print_page_info)
5442 {
5443
5444         db_printf("vm_cnt.v_free_count: %d\n", vm_free_count());
5445         db_printf("vm_cnt.v_inactive_count: %d\n", vm_inactive_count());
5446         db_printf("vm_cnt.v_active_count: %d\n", vm_active_count());
5447         db_printf("vm_cnt.v_laundry_count: %d\n", vm_laundry_count());
5448         db_printf("vm_cnt.v_wire_count: %d\n", vm_wire_count());
5449         db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
5450         db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
5451         db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
5452         db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
5453 }
5454
5455 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
5456 {
5457         int dom;
5458
5459         db_printf("pq_free %d\n", vm_free_count());
5460         for (dom = 0; dom < vm_ndomains; dom++) {
5461                 db_printf(
5462     "dom %d page_cnt %d free %d pq_act %d pq_inact %d pq_laund %d pq_unsw %d\n",
5463                     dom,
5464                     vm_dom[dom].vmd_page_count,
5465                     vm_dom[dom].vmd_free_count,
5466                     vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
5467                     vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
5468                     vm_dom[dom].vmd_pagequeues[PQ_LAUNDRY].pq_cnt,
5469                     vm_dom[dom].vmd_pagequeues[PQ_UNSWAPPABLE].pq_cnt);
5470         }
5471 }
5472
5473 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
5474 {
5475         vm_page_t m;
5476         boolean_t phys, virt;
5477
5478         if (!have_addr) {
5479                 db_printf("show pginfo addr\n");
5480                 return;
5481         }
5482
5483         phys = strchr(modif, 'p') != NULL;
5484         virt = strchr(modif, 'v') != NULL;
5485         if (virt)
5486                 m = PHYS_TO_VM_PAGE(pmap_kextract(addr));
5487         else if (phys)
5488                 m = PHYS_TO_VM_PAGE(addr);
5489         else
5490                 m = (vm_page_t)addr;
5491         db_printf(
5492     "page %p obj %p pidx 0x%jx phys 0x%jx q %d ref 0x%x\n"
5493     "  af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
5494             m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
5495             m->a.queue, m->ref_count, m->a.flags, m->oflags,
5496             m->flags, m->a.act_count, m->busy_lock, m->valid, m->dirty);
5497 }
5498 #endif /* DDB */