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