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