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