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