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