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