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