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