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