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