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