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