006f913ac7adbd5ecaf98c952df2069d9a02491f
[dragonfly.git] / sys / vm / vm_page.c
1 /*
2  * Copyright (c) 1991 Regents of the University of California.
3  * All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * The Mach Operating System project at Carnegie-Mellon University.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *      from: @(#)vm_page.c     7.4 (Berkeley) 5/7/91
33  * $FreeBSD: src/sys/vm/vm_page.c,v 1.147.2.18 2002/03/10 05:03:19 alc Exp $
34  */
35
36 /*
37  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
38  * All rights reserved.
39  *
40  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
41  *
42  * Permission to use, copy, modify and distribute this software and
43  * its documentation is hereby granted, provided that both the copyright
44  * notice and this permission notice appear in all copies of the
45  * software, derivative works or modified versions, and any portions
46  * thereof, and that both notices appear in supporting documentation.
47  *
48  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
49  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
50  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
51  *
52  * Carnegie Mellon requests users of this software to return to
53  *
54  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
55  *  School of Computer Science
56  *  Carnegie Mellon University
57  *  Pittsburgh PA 15213-3890
58  *
59  * any improvements or extensions that they make and grant Carnegie the
60  * rights to redistribute these changes.
61  */
62 /*
63  * Resident memory management module.  The module manipulates 'VM pages'.
64  * A VM page is the core building block for memory management.
65  */
66
67 #include <sys/param.h>
68 #include <sys/systm.h>
69 #include <sys/malloc.h>
70 #include <sys/proc.h>
71 #include <sys/vmmeter.h>
72 #include <sys/vnode.h>
73 #include <sys/kernel.h>
74 #include <sys/alist.h>
75 #include <sys/sysctl.h>
76 #include <sys/cpu_topology.h>
77
78 #include <vm/vm.h>
79 #include <vm/vm_param.h>
80 #include <sys/lock.h>
81 #include <vm/vm_kern.h>
82 #include <vm/pmap.h>
83 #include <vm/vm_map.h>
84 #include <vm/vm_object.h>
85 #include <vm/vm_page.h>
86 #include <vm/vm_pageout.h>
87 #include <vm/vm_pager.h>
88 #include <vm/vm_extern.h>
89 #include <vm/swap_pager.h>
90
91 #include <machine/inttypes.h>
92 #include <machine/md_var.h>
93 #include <machine/specialreg.h>
94
95 #include <vm/vm_page2.h>
96 #include <sys/spinlock2.h>
97
98 /*
99  * Action hash for user umtx support.
100  */
101 #define VMACTION_HSIZE          256
102 #define VMACTION_HMASK          (VMACTION_HSIZE - 1)
103
104 /*
105  * SET - Minimum required set associative size, must be a power of 2.  We
106  *       want this to match or exceed the set-associativeness of the cpu.
107  *
108  * GRP - A larger set that allows bleed-over into the domains of other
109  *       nearby cpus.  Also must be a power of 2.  Used by the page zeroing
110  *       code to smooth things out a bit.
111  */
112 #define PQ_SET_ASSOC            16
113 #define PQ_SET_ASSOC_MASK       (PQ_SET_ASSOC - 1)
114
115 #define PQ_GRP_ASSOC            (PQ_SET_ASSOC * 2)
116 #define PQ_GRP_ASSOC_MASK       (PQ_GRP_ASSOC - 1)
117
118 static void vm_page_queue_init(void);
119 static void vm_page_free_wakeup(void);
120 static vm_page_t vm_page_select_cache(u_short pg_color);
121 static vm_page_t _vm_page_list_find2(int basequeue, int index);
122 static void _vm_page_deactivate_locked(vm_page_t m, int athead);
123
124 /*
125  * Array of tailq lists
126  */
127 __cachealign struct vpgqueues vm_page_queues[PQ_COUNT];
128
129 LIST_HEAD(vm_page_action_list, vm_page_action);
130 struct vm_page_action_list      action_list[VMACTION_HSIZE];
131 static volatile int vm_pages_waiting;
132
133 static struct alist vm_contig_alist;
134 static struct almeta vm_contig_ameta[ALIST_RECORDS_65536];
135 static struct spinlock vm_contig_spin = SPINLOCK_INITIALIZER(&vm_contig_spin, "vm_contig_spin");
136
137 static u_long vm_dma_reserved = 0;
138 TUNABLE_ULONG("vm.dma_reserved", &vm_dma_reserved);
139 SYSCTL_ULONG(_vm, OID_AUTO, dma_reserved, CTLFLAG_RD, &vm_dma_reserved, 0,
140             "Memory reserved for DMA");
141 SYSCTL_UINT(_vm, OID_AUTO, dma_free_pages, CTLFLAG_RD,
142             &vm_contig_alist.bl_free, 0, "Memory reserved for DMA");
143
144 static int vm_contig_verbose = 0;
145 TUNABLE_INT("vm.contig_verbose", &vm_contig_verbose);
146
147 RB_GENERATE2(vm_page_rb_tree, vm_page, rb_entry, rb_vm_page_compare,
148              vm_pindex_t, pindex);
149
150 static void
151 vm_page_queue_init(void) 
152 {
153         int i;
154
155         for (i = 0; i < PQ_L2_SIZE; i++)
156                 vm_page_queues[PQ_FREE+i].cnt = &vmstats.v_free_count;
157         for (i = 0; i < PQ_L2_SIZE; i++)
158                 vm_page_queues[PQ_CACHE+i].cnt = &vmstats.v_cache_count;
159         for (i = 0; i < PQ_L2_SIZE; i++)
160                 vm_page_queues[PQ_INACTIVE+i].cnt = &vmstats.v_inactive_count;
161         for (i = 0; i < PQ_L2_SIZE; i++)
162                 vm_page_queues[PQ_ACTIVE+i].cnt = &vmstats.v_active_count;
163         for (i = 0; i < PQ_L2_SIZE; i++)
164                 vm_page_queues[PQ_HOLD+i].cnt = &vmstats.v_active_count;
165         /* PQ_NONE has no queue */
166
167         for (i = 0; i < PQ_COUNT; i++) {
168                 TAILQ_INIT(&vm_page_queues[i].pl);
169                 spin_init(&vm_page_queues[i].spin, "vm_page_queue_init");
170         }
171
172         for (i = 0; i < VMACTION_HSIZE; i++)
173                 LIST_INIT(&action_list[i]);
174 }
175
176 /*
177  * note: place in initialized data section?  Is this necessary?
178  */
179 long first_page = 0;
180 int vm_page_array_size = 0;
181 vm_page_t vm_page_array = NULL;
182 vm_paddr_t vm_low_phys_reserved;
183
184 /*
185  * (low level boot)
186  *
187  * Sets the page size, perhaps based upon the memory size.
188  * Must be called before any use of page-size dependent functions.
189  */
190 void
191 vm_set_page_size(void)
192 {
193         if (vmstats.v_page_size == 0)
194                 vmstats.v_page_size = PAGE_SIZE;
195         if (((vmstats.v_page_size - 1) & vmstats.v_page_size) != 0)
196                 panic("vm_set_page_size: page size not a power of two");
197 }
198
199 /*
200  * (low level boot)
201  *
202  * Add a new page to the freelist for use by the system.  New pages
203  * are added to both the head and tail of the associated free page
204  * queue in a bottom-up fashion, so both zero'd and non-zero'd page
205  * requests pull 'recent' adds (higher physical addresses) first.
206  *
207  * Beware that the page zeroing daemon will also be running soon after
208  * boot, moving pages from the head to the tail of the PQ_FREE queues.
209  *
210  * Must be called in a critical section.
211  */
212 static void
213 vm_add_new_page(vm_paddr_t pa)
214 {
215         struct vpgqueues *vpq;
216         vm_page_t m;
217
218         m = PHYS_TO_VM_PAGE(pa);
219         m->phys_addr = pa;
220         m->flags = 0;
221         m->pc = (pa >> PAGE_SHIFT) & PQ_L2_MASK;
222         m->pat_mode = PAT_WRITE_BACK;
223
224         /*
225          * Twist for cpu localization in addition to page coloring, so
226          * different cpus selecting by m->queue get different page colors.
227          */
228         m->pc ^= ((pa >> PAGE_SHIFT) / PQ_L2_SIZE) & PQ_L2_MASK;
229         m->pc ^= ((pa >> PAGE_SHIFT) / (PQ_L2_SIZE * PQ_L2_SIZE)) & PQ_L2_MASK;
230
231         /*
232          * Reserve a certain number of contiguous low memory pages for
233          * contigmalloc() to use.
234          */
235         if (pa < vm_low_phys_reserved) {
236                 atomic_add_int(&vmstats.v_page_count, 1);
237                 atomic_add_int(&vmstats.v_dma_pages, 1);
238                 m->queue = PQ_NONE;
239                 m->wire_count = 1;
240                 atomic_add_int(&vmstats.v_wire_count, 1);
241                 alist_free(&vm_contig_alist, pa >> PAGE_SHIFT, 1);
242                 return;
243         }
244
245         /*
246          * General page
247          */
248         m->queue = m->pc + PQ_FREE;
249         KKASSERT(m->dirty == 0);
250
251         atomic_add_int(&vmstats.v_page_count, 1);
252         atomic_add_int(&vmstats.v_free_count, 1);
253         vpq = &vm_page_queues[m->queue];
254         TAILQ_INSERT_HEAD(&vpq->pl, m, pageq);
255         ++vpq->lcnt;
256 }
257
258 /*
259  * (low level boot)
260  *
261  * Initializes the resident memory module.
262  *
263  * Preallocates memory for critical VM structures and arrays prior to
264  * kernel_map becoming available.
265  *
266  * Memory is allocated from (virtual2_start, virtual2_end) if available,
267  * otherwise memory is allocated from (virtual_start, virtual_end).
268  *
269  * On x86-64 (virtual_start, virtual_end) is only 2GB and may not be
270  * large enough to hold vm_page_array & other structures for machines with
271  * large amounts of ram, so we want to use virtual2* when available.
272  */
273 void
274 vm_page_startup(void)
275 {
276         vm_offset_t vaddr = virtual2_start ? virtual2_start : virtual_start;
277         vm_offset_t mapped;
278         vm_size_t npages;
279         vm_paddr_t page_range;
280         vm_paddr_t new_end;
281         int i;
282         vm_paddr_t pa;
283         vm_paddr_t last_pa;
284         vm_paddr_t end;
285         vm_paddr_t biggestone, biggestsize;
286         vm_paddr_t total;
287
288         total = 0;
289         biggestsize = 0;
290         biggestone = 0;
291         vaddr = round_page(vaddr);
292
293         /*
294          * Make sure ranges are page-aligned.
295          */
296         for (i = 0; phys_avail[i].phys_end; ++i) {
297                 phys_avail[i].phys_beg = round_page64(phys_avail[i].phys_beg);
298                 phys_avail[i].phys_end = trunc_page64(phys_avail[i].phys_end);
299                 if (phys_avail[i].phys_end < phys_avail[i].phys_beg)
300                         phys_avail[i].phys_end = phys_avail[i].phys_beg;
301         }
302
303         /*
304          * Locate largest block
305          */
306         for (i = 0; phys_avail[i].phys_end; ++i) {
307                 vm_paddr_t size = phys_avail[i].phys_end -
308                                   phys_avail[i].phys_beg;
309
310                 if (size > biggestsize) {
311                         biggestone = i;
312                         biggestsize = size;
313                 }
314                 total += size;
315         }
316
317         end = phys_avail[biggestone].phys_end;
318         end = trunc_page(end);
319
320         /*
321          * Initialize the queue headers for the free queue, the active queue
322          * and the inactive queue.
323          */
324         vm_page_queue_init();
325
326 #if !defined(_KERNEL_VIRTUAL)
327         /*
328          * VKERNELs don't support minidumps and as such don't need
329          * vm_page_dump
330          *
331          * Allocate a bitmap to indicate that a random physical page
332          * needs to be included in a minidump.
333          *
334          * The amd64 port needs this to indicate which direct map pages
335          * need to be dumped, via calls to dump_add_page()/dump_drop_page().
336          *
337          * However, i386 still needs this workspace internally within the
338          * minidump code.  In theory, they are not needed on i386, but are
339          * included should the sf_buf code decide to use them.
340          */
341         page_range = phys_avail[i-1].phys_end / PAGE_SIZE;
342         vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
343         end -= vm_page_dump_size;
344         vm_page_dump = (void *)pmap_map(&vaddr, end, end + vm_page_dump_size,
345                                         VM_PROT_READ | VM_PROT_WRITE);
346         bzero((void *)vm_page_dump, vm_page_dump_size);
347 #endif
348         /*
349          * Compute the number of pages of memory that will be available for
350          * use (taking into account the overhead of a page structure per
351          * page).
352          */
353         first_page = phys_avail[0].phys_beg / PAGE_SIZE;
354         page_range = phys_avail[i-1].phys_end / PAGE_SIZE - first_page;
355         npages = (total - (page_range * sizeof(struct vm_page))) / PAGE_SIZE;
356
357 #ifndef _KERNEL_VIRTUAL
358         /*
359          * (only applies to real kernels)
360          *
361          * Reserve a large amount of low memory for potential 32-bit DMA
362          * space allocations.  Once device initialization is complete we
363          * release most of it, but keep (vm_dma_reserved) memory reserved
364          * for later use.  Typically for X / graphics.  Through trial and
365          * error we find that GPUs usually requires ~60-100MB or so.
366          *
367          * By default, 128M is left in reserve on machines with 2G+ of ram.
368          */
369         vm_low_phys_reserved = (vm_paddr_t)65536 << PAGE_SHIFT;
370         if (vm_low_phys_reserved > total / 4)
371                 vm_low_phys_reserved = total / 4;
372         if (vm_dma_reserved == 0) {
373                 vm_dma_reserved = 128 * 1024 * 1024;    /* 128MB */
374                 if (vm_dma_reserved > total / 16)
375                         vm_dma_reserved = total / 16;
376         }
377 #endif
378         alist_init(&vm_contig_alist, 65536, vm_contig_ameta,
379                    ALIST_RECORDS_65536);
380
381         /*
382          * Initialize the mem entry structures now, and put them in the free
383          * queue.
384          */
385         new_end = trunc_page(end - page_range * sizeof(struct vm_page));
386         mapped = pmap_map(&vaddr, new_end, end, VM_PROT_READ | VM_PROT_WRITE);
387         vm_page_array = (vm_page_t)mapped;
388
389 #if defined(__x86_64__) && !defined(_KERNEL_VIRTUAL)
390         /*
391          * since pmap_map on amd64 returns stuff out of a direct-map region,
392          * we have to manually add these pages to the minidump tracking so
393          * that they can be dumped, including the vm_page_array.
394          */
395         for (pa = new_end;
396              pa < phys_avail[biggestone].phys_end;
397              pa += PAGE_SIZE) {
398                 dump_add_page(pa);
399         }
400 #endif
401
402         /*
403          * Clear all of the page structures
404          */
405         bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
406         vm_page_array_size = page_range;
407
408         /*
409          * Construct the free queue(s) in ascending order (by physical
410          * address) so that the first 16MB of physical memory is allocated
411          * last rather than first.  On large-memory machines, this avoids
412          * the exhaustion of low physical memory before isa_dmainit has run.
413          */
414         vmstats.v_page_count = 0;
415         vmstats.v_free_count = 0;
416         for (i = 0; phys_avail[i].phys_end && npages > 0; ++i) {
417                 pa = phys_avail[i].phys_beg;
418                 if (i == biggestone)
419                         last_pa = new_end;
420                 else
421                         last_pa = phys_avail[i].phys_end;
422                 while (pa < last_pa && npages-- > 0) {
423                         vm_add_new_page(pa);
424                         pa += PAGE_SIZE;
425                 }
426         }
427         if (virtual2_start)
428                 virtual2_start = vaddr;
429         else
430                 virtual_start = vaddr;
431 }
432
433 /*
434  * Reorganize VM pages based on numa data.  May be called as many times as
435  * necessary.  Will reorganize the vm_page_t page color and related queue(s)
436  * to allow vm_page_alloc() to choose pages based on socket affinity.
437  *
438  * NOTE: This function is only called while we are still in UP mode, so
439  *       we only need a critical section to protect the queues (which
440  *       saves a lot of time, there are likely a ton of pages).
441  */
442 void
443 vm_numa_organize(vm_paddr_t ran_beg, vm_paddr_t bytes, int physid)
444 {
445         vm_paddr_t scan_beg;
446         vm_paddr_t scan_end;
447         vm_paddr_t ran_end;
448         struct vpgqueues *vpq;
449         vm_page_t m;
450         vm_page_t mend;
451         int i;
452         int socket_mod;
453         int socket_value;
454
455         /*
456          * Check if no physical information, or there was only one socket
457          * (so don't waste time doing nothing!).
458          */
459         if (cpu_topology_phys_ids <= 1 ||
460             cpu_topology_core_ids == 0) {
461                 return;
462         }
463
464         /*
465          * Setup for our iteration.  Note that ACPI may iterate CPU
466          * sockets starting at 0 or 1 or some other number.  The
467          * cpu_topology code mod's it against the socket count.
468          */
469         ran_end = ran_beg + bytes;
470         physid %= cpu_topology_phys_ids;
471
472         socket_mod = PQ_L2_SIZE / cpu_topology_phys_ids;
473         socket_value = physid * socket_mod;
474         mend = &vm_page_array[vm_page_array_size];
475
476         crit_enter();
477
478         /*
479          * Adjust vm_page->pc and requeue all affected pages.  The
480          * allocator will then be able to localize memory allocations
481          * to some degree.
482          */
483         for (i = 0; phys_avail[i].phys_end; ++i) {
484                 scan_beg = phys_avail[i].phys_beg;
485                 scan_end = phys_avail[i].phys_end;
486                 if (scan_end <= ran_beg)
487                         continue;
488                 if (scan_beg >= ran_end)
489                         continue;
490                 if (scan_beg < ran_beg)
491                         scan_beg = ran_beg;
492                 if (scan_end > ran_end)
493                         scan_end = ran_end;
494                 if (atop(scan_end) > first_page + vm_page_array_size)
495                         scan_end = ptoa(first_page + vm_page_array_size);
496
497                 m = PHYS_TO_VM_PAGE(scan_beg);
498                 while (scan_beg < scan_end) {
499                         KKASSERT(m < mend);
500                         if (m->queue != PQ_NONE) {
501                                 vpq = &vm_page_queues[m->queue];
502                                 TAILQ_REMOVE(&vpq->pl, m, pageq);
503                                 --vpq->lcnt;
504                                 /* queue doesn't change, no need to adj cnt */
505                                 /* atomic_add_int(vpq->cnt, -1); */
506                                 m->queue -= m->pc;
507                                 m->pc %= socket_mod;
508                                 m->pc += socket_value;
509                                 m->pc &= PQ_L2_MASK;
510                                 m->queue += m->pc;
511                                 vpq = &vm_page_queues[m->queue];
512                                 TAILQ_INSERT_HEAD(&vpq->pl, m, pageq);
513                                 ++vpq->lcnt;
514                                 /* queue doesn't change, no need to adj cnt */
515                                 /* atomic_add_int(vpq->cnt, 1); */
516                         } else {
517                                 m->pc %= socket_mod;
518                                 m->pc += socket_value;
519                                 m->pc &= PQ_L2_MASK;
520                         }
521                         scan_beg += PAGE_SIZE;
522                         ++m;
523                 }
524         }
525         crit_exit();
526 }
527
528 /*
529  * We tended to reserve a ton of memory for contigmalloc().  Now that most
530  * drivers have initialized we want to return most the remaining free
531  * reserve back to the VM page queues so they can be used for normal
532  * allocations.
533  *
534  * We leave vm_dma_reserved bytes worth of free pages in the reserve pool.
535  */
536 static void
537 vm_page_startup_finish(void *dummy __unused)
538 {
539         alist_blk_t blk;
540         alist_blk_t rblk;
541         alist_blk_t count;
542         alist_blk_t xcount;
543         alist_blk_t bfree;
544         vm_page_t m;
545
546         spin_lock(&vm_contig_spin);
547         for (;;) {
548                 bfree = alist_free_info(&vm_contig_alist, &blk, &count);
549                 if (bfree <= vm_dma_reserved / PAGE_SIZE)
550                         break;
551                 if (count == 0)
552                         break;
553
554                 /*
555                  * Figure out how much of the initial reserve we have to
556                  * free in order to reach our target.
557                  */
558                 bfree -= vm_dma_reserved / PAGE_SIZE;
559                 if (count > bfree) {
560                         blk += count - bfree;
561                         count = bfree;
562                 }
563
564                 /*
565                  * Calculate the nearest power of 2 <= count.
566                  */
567                 for (xcount = 1; xcount <= count; xcount <<= 1)
568                         ;
569                 xcount >>= 1;
570                 blk += count - xcount;
571                 count = xcount;
572
573                 /*
574                  * Allocate the pages from the alist, then free them to
575                  * the normal VM page queues.
576                  *
577                  * Pages allocated from the alist are wired.  We have to
578                  * busy, unwire, and free them.  We must also adjust
579                  * vm_low_phys_reserved before freeing any pages to prevent
580                  * confusion.
581                  */
582                 rblk = alist_alloc(&vm_contig_alist, blk, count);
583                 if (rblk != blk) {
584                         kprintf("vm_page_startup_finish: Unable to return "
585                                 "dma space @0x%08x/%d -> 0x%08x\n",
586                                 blk, count, rblk);
587                         break;
588                 }
589                 atomic_add_int(&vmstats.v_dma_pages, -count);
590                 spin_unlock(&vm_contig_spin);
591
592                 m = PHYS_TO_VM_PAGE((vm_paddr_t)blk << PAGE_SHIFT);
593                 vm_low_phys_reserved = VM_PAGE_TO_PHYS(m);
594                 while (count) {
595                         vm_page_busy_wait(m, FALSE, "cpgfr");
596                         vm_page_unwire(m, 0);
597                         vm_page_free(m);
598                         --count;
599                         ++m;
600                 }
601                 spin_lock(&vm_contig_spin);
602         }
603         spin_unlock(&vm_contig_spin);
604
605         /*
606          * Print out how much DMA space drivers have already allocated and
607          * how much is left over.
608          */
609         kprintf("DMA space used: %jdk, remaining available: %jdk\n",
610                 (intmax_t)(vmstats.v_dma_pages - vm_contig_alist.bl_free) *
611                 (PAGE_SIZE / 1024),
612                 (intmax_t)vm_contig_alist.bl_free * (PAGE_SIZE / 1024));
613 }
614 SYSINIT(vm_pgend, SI_SUB_PROC0_POST, SI_ORDER_ANY,
615         vm_page_startup_finish, NULL);
616
617
618 /*
619  * Scan comparison function for Red-Black tree scans.  An inclusive
620  * (start,end) is expected.  Other fields are not used.
621  */
622 int
623 rb_vm_page_scancmp(struct vm_page *p, void *data)
624 {
625         struct rb_vm_page_scan_info *info = data;
626
627         if (p->pindex < info->start_pindex)
628                 return(-1);
629         if (p->pindex > info->end_pindex)
630                 return(1);
631         return(0);
632 }
633
634 int
635 rb_vm_page_compare(struct vm_page *p1, struct vm_page *p2)
636 {
637         if (p1->pindex < p2->pindex)
638                 return(-1);
639         if (p1->pindex > p2->pindex)
640                 return(1);
641         return(0);
642 }
643
644 void
645 vm_page_init(vm_page_t m)
646 {
647         /* do nothing for now.  Called from pmap_page_init() */
648 }
649
650 /*
651  * Each page queue has its own spin lock, which is fairly optimal for
652  * allocating and freeing pages at least.
653  *
654  * The caller must hold the vm_page_spin_lock() before locking a vm_page's
655  * queue spinlock via this function.  Also note that m->queue cannot change
656  * unless both the page and queue are locked.
657  */
658 static __inline
659 void
660 _vm_page_queue_spin_lock(vm_page_t m)
661 {
662         u_short queue;
663
664         queue = m->queue;
665         if (queue != PQ_NONE) {
666                 spin_lock(&vm_page_queues[queue].spin);
667                 KKASSERT(queue == m->queue);
668         }
669 }
670
671 static __inline
672 void
673 _vm_page_queue_spin_unlock(vm_page_t m)
674 {
675         u_short queue;
676
677         queue = m->queue;
678         cpu_ccfence();
679         if (queue != PQ_NONE)
680                 spin_unlock(&vm_page_queues[queue].spin);
681 }
682
683 static __inline
684 void
685 _vm_page_queues_spin_lock(u_short queue)
686 {
687         cpu_ccfence();
688         if (queue != PQ_NONE)
689                 spin_lock(&vm_page_queues[queue].spin);
690 }
691
692
693 static __inline
694 void
695 _vm_page_queues_spin_unlock(u_short queue)
696 {
697         cpu_ccfence();
698         if (queue != PQ_NONE)
699                 spin_unlock(&vm_page_queues[queue].spin);
700 }
701
702 void
703 vm_page_queue_spin_lock(vm_page_t m)
704 {
705         _vm_page_queue_spin_lock(m);
706 }
707
708 void
709 vm_page_queues_spin_lock(u_short queue)
710 {
711         _vm_page_queues_spin_lock(queue);
712 }
713
714 void
715 vm_page_queue_spin_unlock(vm_page_t m)
716 {
717         _vm_page_queue_spin_unlock(m);
718 }
719
720 void
721 vm_page_queues_spin_unlock(u_short queue)
722 {
723         _vm_page_queues_spin_unlock(queue);
724 }
725
726 /*
727  * This locks the specified vm_page and its queue in the proper order
728  * (page first, then queue).  The queue may change so the caller must
729  * recheck on return.
730  */
731 static __inline
732 void
733 _vm_page_and_queue_spin_lock(vm_page_t m)
734 {
735         vm_page_spin_lock(m);
736         _vm_page_queue_spin_lock(m);
737 }
738
739 static __inline
740 void
741 _vm_page_and_queue_spin_unlock(vm_page_t m)
742 {
743         _vm_page_queues_spin_unlock(m->queue);
744         vm_page_spin_unlock(m);
745 }
746
747 void
748 vm_page_and_queue_spin_unlock(vm_page_t m)
749 {
750         _vm_page_and_queue_spin_unlock(m);
751 }
752
753 void
754 vm_page_and_queue_spin_lock(vm_page_t m)
755 {
756         _vm_page_and_queue_spin_lock(m);
757 }
758
759 /*
760  * Helper function removes vm_page from its current queue.
761  * Returns the base queue the page used to be on.
762  *
763  * The vm_page and the queue must be spinlocked.
764  * This function will unlock the queue but leave the page spinlocked.
765  */
766 static __inline u_short
767 _vm_page_rem_queue_spinlocked(vm_page_t m)
768 {
769         struct vpgqueues *pq;
770         u_short queue;
771         u_short oqueue;
772
773         queue = m->queue;
774         if (queue != PQ_NONE) {
775                 pq = &vm_page_queues[queue];
776                 TAILQ_REMOVE(&pq->pl, m, pageq);
777                 atomic_add_int(pq->cnt, -1);
778                 pq->lcnt--;
779                 m->queue = PQ_NONE;
780                 oqueue = queue;
781                 queue -= m->pc;
782                 vm_page_queues_spin_unlock(oqueue);     /* intended */
783         }
784         return queue;
785 }
786
787 /*
788  * Helper function places the vm_page on the specified queue.
789  *
790  * The vm_page must be spinlocked.
791  * This function will return with both the page and the queue locked.
792  */
793 static __inline void
794 _vm_page_add_queue_spinlocked(vm_page_t m, u_short queue, int athead)
795 {
796         struct vpgqueues *pq;
797
798         KKASSERT(m->queue == PQ_NONE);
799
800         if (queue != PQ_NONE) {
801                 vm_page_queues_spin_lock(queue);
802                 pq = &vm_page_queues[queue];
803                 ++pq->lcnt;
804                 atomic_add_int(pq->cnt, 1);
805                 m->queue = queue;
806
807                 /*
808                  * PQ_FREE is always handled LIFO style to try to provide
809                  * cache-hot pages to programs.
810                  */
811                 if (queue - m->pc == PQ_FREE) {
812                         TAILQ_INSERT_HEAD(&pq->pl, m, pageq);
813                 } else if (athead) {
814                         TAILQ_INSERT_HEAD(&pq->pl, m, pageq);
815                 } else {
816                         TAILQ_INSERT_TAIL(&pq->pl, m, pageq);
817                 }
818                 /* leave the queue spinlocked */
819         }
820 }
821
822 /*
823  * Wait until page is no longer PG_BUSY or (if also_m_busy is TRUE)
824  * m->busy is zero.  Returns TRUE if it had to sleep, FALSE if we
825  * did not.  Only one sleep call will be made before returning.
826  *
827  * This function does NOT busy the page and on return the page is not
828  * guaranteed to be available.
829  */
830 void
831 vm_page_sleep_busy(vm_page_t m, int also_m_busy, const char *msg)
832 {
833         u_int32_t flags;
834
835         for (;;) {
836                 flags = m->flags;
837                 cpu_ccfence();
838
839                 if ((flags & PG_BUSY) == 0 &&
840                     (also_m_busy == 0 || (flags & PG_SBUSY) == 0)) {
841                         break;
842                 }
843                 tsleep_interlock(m, 0);
844                 if (atomic_cmpset_int(&m->flags, flags,
845                                       flags | PG_WANTED | PG_REFERENCED)) {
846                         tsleep(m, PINTERLOCKED, msg, 0);
847                         break;
848                 }
849         }
850 }
851
852 /*
853  * This calculates and returns a page color given an optional VM object and
854  * either a pindex or an iterator.  We attempt to return a cpu-localized
855  * pg_color that is still roughly 16-way set-associative.  The CPU topology
856  * is used if it was probed.
857  *
858  * The caller may use the returned value to index into e.g. PQ_FREE when
859  * allocating a page in order to nominally obtain pages that are hopefully
860  * already localized to the requesting cpu.  This function is not able to
861  * provide any sort of guarantee of this, but does its best to improve
862  * hardware cache management performance.
863  *
864  * WARNING! The caller must mask the returned value with PQ_L2_MASK.
865  */
866 u_short
867 vm_get_pg_color(globaldata_t gd, vm_object_t object, vm_pindex_t pindex)
868 {
869         u_short pg_color;
870         int phys_id;
871         int core_id;
872         int object_pg_color;
873
874         phys_id = get_cpu_phys_id(gd->gd_cpuid);
875         core_id = get_cpu_core_id(gd->gd_cpuid);
876         object_pg_color = object ? object->pg_color : 0;
877
878         if (cpu_topology_phys_ids && cpu_topology_core_ids) {
879                 int grpsize = PQ_L2_SIZE / cpu_topology_phys_ids;
880
881                 if (grpsize / cpu_topology_core_ids >= PQ_SET_ASSOC) {
882                         /*
883                          * Enough space for a full break-down.
884                          */
885                         pg_color = phys_id * grpsize;
886                         pg_color += core_id * grpsize / cpu_topology_core_ids;
887                         pg_color += (pindex + object_pg_color) %
888                                     (grpsize / cpu_topology_core_ids);
889                 } else {
890                         /*
891                          * Not enough space, split up by physical package,
892                          * then split up by core id but only down to a
893                          * 16-set.  If all else fails, force a 16-set.
894                          */
895                         pg_color = phys_id * grpsize;
896                         if (grpsize > 16) {
897                                 pg_color += 16 * (core_id % (grpsize / 16));
898                                 grpsize = 16;
899                         } else {
900                                 grpsize = 16;
901                         }
902                         pg_color += (pindex + object_pg_color) %
903                                     grpsize;
904                 }
905         } else {
906                 /*
907                  * Unknown topology, distribute things evenly.
908                  */
909                 pg_color = gd->gd_cpuid * PQ_L2_SIZE / ncpus;
910                 pg_color += pindex + object_pg_color;
911         }
912         return pg_color;
913 }
914
915 /*
916  * Wait until PG_BUSY can be set, then set it.  If also_m_busy is TRUE we
917  * also wait for m->busy to become 0 before setting PG_BUSY.
918  */
919 void
920 VM_PAGE_DEBUG_EXT(vm_page_busy_wait)(vm_page_t m,
921                                      int also_m_busy, const char *msg
922                                      VM_PAGE_DEBUG_ARGS)
923 {
924         u_int32_t flags;
925
926         for (;;) {
927                 flags = m->flags;
928                 cpu_ccfence();
929                 if (flags & PG_BUSY) {
930                         tsleep_interlock(m, 0);
931                         if (atomic_cmpset_int(&m->flags, flags,
932                                           flags | PG_WANTED | PG_REFERENCED)) {
933                                 tsleep(m, PINTERLOCKED, msg, 0);
934                         }
935                 } else if (also_m_busy && (flags & PG_SBUSY)) {
936                         tsleep_interlock(m, 0);
937                         if (atomic_cmpset_int(&m->flags, flags,
938                                           flags | PG_WANTED | PG_REFERENCED)) {
939                                 tsleep(m, PINTERLOCKED, msg, 0);
940                         }
941                 } else {
942                         if (atomic_cmpset_int(&m->flags, flags,
943                                               flags | PG_BUSY)) {
944 #ifdef VM_PAGE_DEBUG
945                                 m->busy_func = func;
946                                 m->busy_line = lineno;
947 #endif
948                                 break;
949                         }
950                 }
951         }
952 }
953
954 /*
955  * Attempt to set PG_BUSY.  If also_m_busy is TRUE we only succeed if m->busy
956  * is also 0.
957  *
958  * Returns non-zero on failure.
959  */
960 int
961 VM_PAGE_DEBUG_EXT(vm_page_busy_try)(vm_page_t m, int also_m_busy
962                                     VM_PAGE_DEBUG_ARGS)
963 {
964         u_int32_t flags;
965
966         for (;;) {
967                 flags = m->flags;
968                 cpu_ccfence();
969                 if (flags & PG_BUSY)
970                         return TRUE;
971                 if (also_m_busy && (flags & PG_SBUSY))
972                         return TRUE;
973                 if (atomic_cmpset_int(&m->flags, flags, flags | PG_BUSY)) {
974 #ifdef VM_PAGE_DEBUG
975                                 m->busy_func = func;
976                                 m->busy_line = lineno;
977 #endif
978                         return FALSE;
979                 }
980         }
981 }
982
983 /*
984  * Clear the PG_BUSY flag and return non-zero to indicate to the caller
985  * that a wakeup() should be performed.
986  *
987  * The vm_page must be spinlocked and will remain spinlocked on return.
988  * The related queue must NOT be spinlocked (which could deadlock us).
989  *
990  * (inline version)
991  */
992 static __inline
993 int
994 _vm_page_wakeup(vm_page_t m)
995 {
996         u_int32_t flags;
997
998         for (;;) {
999                 flags = m->flags;
1000                 cpu_ccfence();
1001                 if (atomic_cmpset_int(&m->flags, flags,
1002                                       flags & ~(PG_BUSY | PG_WANTED))) {
1003                         break;
1004                 }
1005         }
1006         return(flags & PG_WANTED);
1007 }
1008
1009 /*
1010  * Clear the PG_BUSY flag and wakeup anyone waiting for the page.  This
1011  * is typically the last call you make on a page before moving onto
1012  * other things.
1013  */
1014 void
1015 vm_page_wakeup(vm_page_t m)
1016 {
1017         KASSERT(m->flags & PG_BUSY, ("vm_page_wakeup: page not busy!!!"));
1018         vm_page_spin_lock(m);
1019         if (_vm_page_wakeup(m)) {
1020                 vm_page_spin_unlock(m);
1021                 wakeup(m);
1022         } else {
1023                 vm_page_spin_unlock(m);
1024         }
1025 }
1026
1027 /*
1028  * Holding a page keeps it from being reused.  Other parts of the system
1029  * can still disassociate the page from its current object and free it, or
1030  * perform read or write I/O on it and/or otherwise manipulate the page,
1031  * but if the page is held the VM system will leave the page and its data
1032  * intact and not reuse the page for other purposes until the last hold
1033  * reference is released.  (see vm_page_wire() if you want to prevent the
1034  * page from being disassociated from its object too).
1035  *
1036  * The caller must still validate the contents of the page and, if necessary,
1037  * wait for any pending I/O (e.g. vm_page_sleep_busy() loop) to complete
1038  * before manipulating the page.
1039  *
1040  * XXX get vm_page_spin_lock() here and move FREE->HOLD if necessary
1041  */
1042 void
1043 vm_page_hold(vm_page_t m)
1044 {
1045         vm_page_spin_lock(m);
1046         atomic_add_int(&m->hold_count, 1);
1047         if (m->queue - m->pc == PQ_FREE) {
1048                 _vm_page_queue_spin_lock(m);
1049                 _vm_page_rem_queue_spinlocked(m);
1050                 _vm_page_add_queue_spinlocked(m, PQ_HOLD + m->pc, 0);
1051                 _vm_page_queue_spin_unlock(m);
1052         }
1053         vm_page_spin_unlock(m);
1054 }
1055
1056 /*
1057  * The opposite of vm_page_hold().  If the page is on the HOLD queue
1058  * it was freed while held and must be moved back to the FREE queue.
1059  */
1060 void
1061 vm_page_unhold(vm_page_t m)
1062 {
1063         KASSERT(m->hold_count > 0 && m->queue - m->pc != PQ_FREE,
1064                 ("vm_page_unhold: pg %p illegal hold_count (%d) or on FREE queue (%d)",
1065                  m, m->hold_count, m->queue - m->pc));
1066         vm_page_spin_lock(m);
1067         atomic_add_int(&m->hold_count, -1);
1068         if (m->hold_count == 0 && m->queue - m->pc == PQ_HOLD) {
1069                 _vm_page_queue_spin_lock(m);
1070                 _vm_page_rem_queue_spinlocked(m);
1071                 _vm_page_add_queue_spinlocked(m, PQ_FREE + m->pc, 0);
1072                 _vm_page_queue_spin_unlock(m);
1073         }
1074         vm_page_spin_unlock(m);
1075 }
1076
1077 /*
1078  *      vm_page_getfake:
1079  *
1080  *      Create a fictitious page with the specified physical address and
1081  *      memory attribute.  The memory attribute is the only the machine-
1082  *      dependent aspect of a fictitious page that must be initialized.
1083  */
1084
1085 void
1086 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1087 {
1088
1089         if ((m->flags & PG_FICTITIOUS) != 0) {
1090                 /*
1091                  * The page's memattr might have changed since the
1092                  * previous initialization.  Update the pmap to the
1093                  * new memattr.
1094                  */
1095                 goto memattr;
1096         }
1097         m->phys_addr = paddr;
1098         m->queue = PQ_NONE;
1099         /* Fictitious pages don't use "segind". */
1100         /* Fictitious pages don't use "order" or "pool". */
1101         m->flags = PG_FICTITIOUS | PG_UNMANAGED | PG_BUSY;
1102         m->wire_count = 1;
1103         pmap_page_init(m);
1104 memattr:
1105         pmap_page_set_memattr(m, memattr);
1106 }
1107
1108 /*
1109  * Inserts the given vm_page into the object and object list.
1110  *
1111  * The pagetables are not updated but will presumably fault the page
1112  * in if necessary, or if a kernel page the caller will at some point
1113  * enter the page into the kernel's pmap.  We are not allowed to block
1114  * here so we *can't* do this anyway.
1115  *
1116  * This routine may not block.
1117  * This routine must be called with the vm_object held.
1118  * This routine must be called with a critical section held.
1119  *
1120  * This routine returns TRUE if the page was inserted into the object
1121  * successfully, and FALSE if the page already exists in the object.
1122  */
1123 int
1124 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1125 {
1126         ASSERT_LWKT_TOKEN_HELD_EXCL(vm_object_token(object));
1127         if (m->object != NULL)
1128                 panic("vm_page_insert: already inserted");
1129
1130         object->generation++;
1131
1132         /*
1133          * Record the object/offset pair in this page and add the
1134          * pv_list_count of the page to the object.
1135          *
1136          * The vm_page spin lock is required for interactions with the pmap.
1137          */
1138         vm_page_spin_lock(m);
1139         m->object = object;
1140         m->pindex = pindex;
1141         if (vm_page_rb_tree_RB_INSERT(&object->rb_memq, m)) {
1142                 m->object = NULL;
1143                 m->pindex = 0;
1144                 vm_page_spin_unlock(m);
1145                 return FALSE;
1146         }
1147         ++object->resident_page_count;
1148         ++mycpu->gd_vmtotal.t_rm;
1149         /* atomic_add_int(&object->agg_pv_list_count, m->md.pv_list_count); */
1150         vm_page_spin_unlock(m);
1151
1152         /*
1153          * Since we are inserting a new and possibly dirty page,
1154          * update the object's OBJ_WRITEABLE and OBJ_MIGHTBEDIRTY flags.
1155          */
1156         if ((m->valid & m->dirty) ||
1157             (m->flags & (PG_WRITEABLE | PG_NEED_COMMIT)))
1158                 vm_object_set_writeable_dirty(object);
1159
1160         /*
1161          * Checks for a swap assignment and sets PG_SWAPPED if appropriate.
1162          */
1163         swap_pager_page_inserted(m);
1164         return TRUE;
1165 }
1166
1167 /*
1168  * Removes the given vm_page_t from the (object,index) table
1169  *
1170  * The underlying pmap entry (if any) is NOT removed here.
1171  * This routine may not block.
1172  *
1173  * The page must be BUSY and will remain BUSY on return.
1174  * No other requirements.
1175  *
1176  * NOTE: FreeBSD side effect was to unbusy the page on return.  We leave
1177  *       it busy.
1178  */
1179 void
1180 vm_page_remove(vm_page_t m)
1181 {
1182         vm_object_t object;
1183
1184         if (m->object == NULL) {
1185                 return;
1186         }
1187
1188         if ((m->flags & PG_BUSY) == 0)
1189                 panic("vm_page_remove: page not busy");
1190
1191         object = m->object;
1192
1193         vm_object_hold(object);
1194
1195         /*
1196          * Remove the page from the object and update the object.
1197          *
1198          * The vm_page spin lock is required for interactions with the pmap.
1199          */
1200         vm_page_spin_lock(m);
1201         vm_page_rb_tree_RB_REMOVE(&object->rb_memq, m);
1202         --object->resident_page_count;
1203         --mycpu->gd_vmtotal.t_rm;
1204         /* atomic_add_int(&object->agg_pv_list_count, -m->md.pv_list_count); */
1205         m->object = NULL;
1206         vm_page_spin_unlock(m);
1207
1208         object->generation++;
1209
1210         vm_object_drop(object);
1211 }
1212
1213 /*
1214  * Locate and return the page at (object, pindex), or NULL if the
1215  * page could not be found.
1216  *
1217  * The caller must hold the vm_object token.
1218  */
1219 vm_page_t
1220 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1221 {
1222         vm_page_t m;
1223
1224         /*
1225          * Search the hash table for this object/offset pair
1226          */
1227         ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1228         m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq, pindex);
1229         KKASSERT(m == NULL || (m->object == object && m->pindex == pindex));
1230         return(m);
1231 }
1232
1233 vm_page_t
1234 VM_PAGE_DEBUG_EXT(vm_page_lookup_busy_wait)(struct vm_object *object,
1235                                             vm_pindex_t pindex,
1236                                             int also_m_busy, const char *msg
1237                                             VM_PAGE_DEBUG_ARGS)
1238 {
1239         u_int32_t flags;
1240         vm_page_t m;
1241
1242         ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1243         m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq, pindex);
1244         while (m) {
1245                 KKASSERT(m->object == object && m->pindex == pindex);
1246                 flags = m->flags;
1247                 cpu_ccfence();
1248                 if (flags & PG_BUSY) {
1249                         tsleep_interlock(m, 0);
1250                         if (atomic_cmpset_int(&m->flags, flags,
1251                                           flags | PG_WANTED | PG_REFERENCED)) {
1252                                 tsleep(m, PINTERLOCKED, msg, 0);
1253                                 m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq,
1254                                                               pindex);
1255                         }
1256                 } else if (also_m_busy && (flags & PG_SBUSY)) {
1257                         tsleep_interlock(m, 0);
1258                         if (atomic_cmpset_int(&m->flags, flags,
1259                                           flags | PG_WANTED | PG_REFERENCED)) {
1260                                 tsleep(m, PINTERLOCKED, msg, 0);
1261                                 m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq,
1262                                                               pindex);
1263                         }
1264                 } else if (atomic_cmpset_int(&m->flags, flags,
1265                                              flags | PG_BUSY)) {
1266 #ifdef VM_PAGE_DEBUG
1267                         m->busy_func = func;
1268                         m->busy_line = lineno;
1269 #endif
1270                         break;
1271                 }
1272         }
1273         return m;
1274 }
1275
1276 /*
1277  * Attempt to lookup and busy a page.
1278  *
1279  * Returns NULL if the page could not be found
1280  *
1281  * Returns a vm_page and error == TRUE if the page exists but could not
1282  * be busied.
1283  *
1284  * Returns a vm_page and error == FALSE on success.
1285  */
1286 vm_page_t
1287 VM_PAGE_DEBUG_EXT(vm_page_lookup_busy_try)(struct vm_object *object,
1288                                            vm_pindex_t pindex,
1289                                            int also_m_busy, int *errorp
1290                                            VM_PAGE_DEBUG_ARGS)
1291 {
1292         u_int32_t flags;
1293         vm_page_t m;
1294
1295         ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1296         m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq, pindex);
1297         *errorp = FALSE;
1298         while (m) {
1299                 KKASSERT(m->object == object && m->pindex == pindex);
1300                 flags = m->flags;
1301                 cpu_ccfence();
1302                 if (flags & PG_BUSY) {
1303                         *errorp = TRUE;
1304                         break;
1305                 }
1306                 if (also_m_busy && (flags & PG_SBUSY)) {
1307                         *errorp = TRUE;
1308                         break;
1309                 }
1310                 if (atomic_cmpset_int(&m->flags, flags, flags | PG_BUSY)) {
1311 #ifdef VM_PAGE_DEBUG
1312                         m->busy_func = func;
1313                         m->busy_line = lineno;
1314 #endif
1315                         break;
1316                 }
1317         }
1318         return m;
1319 }
1320
1321 /*
1322  * Attempt to repurpose the passed-in page.  If the passed-in page cannot
1323  * be repurposed it will be released, *must_reenter will be set to 1, and
1324  * this function will fall-through to vm_page_lookup_busy_try().
1325  *
1326  * The passed-in page must be wired and not busy.  The returned page will
1327  * be busied and not wired.
1328  *
1329  * A different page may be returned.  The returned page will be busied and
1330  * not wired.
1331  *
1332  * NULL can be returned.  If so, the required page could not be busied.
1333  * The passed-in page will be unwired.
1334  */
1335 vm_page_t
1336 vm_page_repurpose(struct vm_object *object, vm_pindex_t pindex,
1337                   int also_m_busy, int *errorp, vm_page_t m,
1338                   int *must_reenter, int *iswired)
1339 {
1340         if (m) {
1341                 /*
1342                  * Do not mess with pages in a complex state, such as pages
1343                  * which are mapped, as repurposing such pages can be more
1344                  * expensive than simply allocatin a new one.
1345                  *
1346                  * NOTE: Soft-busying can deadlock against putpages or I/O
1347                  *       so we only allow hard-busying here.
1348                  */
1349                 KKASSERT(also_m_busy == FALSE);
1350                 vm_page_busy_wait(m, also_m_busy, "biodep");
1351
1352                 if ((m->flags & (PG_UNMANAGED | PG_MAPPED |
1353                                  PG_FICTITIOUS | PG_SBUSY)) ||
1354                     m->busy || m->wire_count != 1 || m->hold_count) {
1355                         vm_page_unwire(m, 0);
1356                         vm_page_wakeup(m);
1357                         /* fall through to normal lookup */
1358                 } else if (m->dirty || (m->flags & PG_NEED_COMMIT)) {
1359                         vm_page_unwire(m, 0);
1360                         vm_page_deactivate(m);
1361                         vm_page_wakeup(m);
1362                         /* fall through to normal lookup */
1363                 } else {
1364                         /*
1365                          * We can safely repurpose the page.  It should
1366                          * already be unqueued.
1367                          */
1368                         KKASSERT(m->queue == PQ_NONE && m->dirty == 0);
1369                         vm_page_remove(m);
1370                         m->valid = 0;
1371                         m->act_count = 0;
1372                         if (vm_page_insert(m, object, pindex)) {
1373                                 *errorp = 0;
1374                                 *iswired = 1;
1375
1376                                 return m;
1377                         }
1378                         vm_page_unwire(m, 0);
1379                         vm_page_free(m);
1380                         /* fall through to normal lookup */
1381                 }
1382         }
1383
1384         /*
1385          * Cannot repurpose page, attempt to locate the desired page.  May
1386          * return NULL.
1387          */
1388         *must_reenter = 1;
1389         *iswired = 0;
1390         m = vm_page_lookup_busy_try(object, pindex, also_m_busy, errorp);
1391
1392         return m;
1393 }
1394
1395 /*
1396  * Caller must hold the related vm_object
1397  */
1398 vm_page_t
1399 vm_page_next(vm_page_t m)
1400 {
1401         vm_page_t next;
1402
1403         next = vm_page_rb_tree_RB_NEXT(m);
1404         if (next && next->pindex != m->pindex + 1)
1405                 next = NULL;
1406         return (next);
1407 }
1408
1409 /*
1410  * vm_page_rename()
1411  *
1412  * Move the given vm_page from its current object to the specified
1413  * target object/offset.  The page must be busy and will remain so
1414  * on return.
1415  *
1416  * new_object must be held.
1417  * This routine might block. XXX ?
1418  *
1419  * NOTE: Swap associated with the page must be invalidated by the move.  We
1420  *       have to do this for several reasons:  (1) we aren't freeing the
1421  *       page, (2) we are dirtying the page, (3) the VM system is probably
1422  *       moving the page from object A to B, and will then later move
1423  *       the backing store from A to B and we can't have a conflict.
1424  *
1425  * NOTE: We *always* dirty the page.  It is necessary both for the
1426  *       fact that we moved it, and because we may be invalidating
1427  *       swap.  If the page is on the cache, we have to deactivate it
1428  *       or vm_page_dirty() will panic.  Dirty pages are not allowed
1429  *       on the cache.
1430  */
1431 void
1432 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1433 {
1434         KKASSERT(m->flags & PG_BUSY);
1435         ASSERT_LWKT_TOKEN_HELD_EXCL(vm_object_token(new_object));
1436         if (m->object) {
1437                 ASSERT_LWKT_TOKEN_HELD_EXCL(vm_object_token(m->object));
1438                 vm_page_remove(m);
1439         }
1440         if (vm_page_insert(m, new_object, new_pindex) == FALSE) {
1441                 panic("vm_page_rename: target exists (%p,%"PRIu64")",
1442                       new_object, new_pindex);
1443         }
1444         if (m->queue - m->pc == PQ_CACHE)
1445                 vm_page_deactivate(m);
1446         vm_page_dirty(m);
1447 }
1448
1449 /*
1450  * vm_page_unqueue() without any wakeup.  This routine is used when a page
1451  * is to remain BUSYied by the caller.
1452  *
1453  * This routine may not block.
1454  */
1455 void
1456 vm_page_unqueue_nowakeup(vm_page_t m)
1457 {
1458         vm_page_and_queue_spin_lock(m);
1459         (void)_vm_page_rem_queue_spinlocked(m);
1460         vm_page_spin_unlock(m);
1461 }
1462
1463 /*
1464  * vm_page_unqueue() - Remove a page from its queue, wakeup the pagedemon
1465  * if necessary.
1466  *
1467  * This routine may not block.
1468  */
1469 void
1470 vm_page_unqueue(vm_page_t m)
1471 {
1472         u_short queue;
1473
1474         vm_page_and_queue_spin_lock(m);
1475         queue = _vm_page_rem_queue_spinlocked(m);
1476         if (queue == PQ_FREE || queue == PQ_CACHE) {
1477                 vm_page_spin_unlock(m);
1478                 pagedaemon_wakeup();
1479         } else {
1480                 vm_page_spin_unlock(m);
1481         }
1482 }
1483
1484 /*
1485  * vm_page_list_find()
1486  *
1487  * Find a page on the specified queue with color optimization.
1488  *
1489  * The page coloring optimization attempts to locate a page that does
1490  * not overload other nearby pages in the object in the cpu's L1 or L2
1491  * caches.  We need this optimization because cpu caches tend to be
1492  * physical caches, while object spaces tend to be virtual.
1493  *
1494  * The page coloring optimization also, very importantly, tries to localize
1495  * memory to cpus and physical sockets.
1496  *
1497  * On MP systems each PQ_FREE and PQ_CACHE color queue has its own spinlock
1498  * and the algorithm is adjusted to localize allocations on a per-core basis.
1499  * This is done by 'twisting' the colors.
1500  *
1501  * The page is returned spinlocked and removed from its queue (it will
1502  * be on PQ_NONE), or NULL. The page is not PG_BUSY'd.  The caller
1503  * is responsible for dealing with the busy-page case (usually by
1504  * deactivating the page and looping).
1505  *
1506  * NOTE:  This routine is carefully inlined.  A non-inlined version
1507  *        is available for outside callers but the only critical path is
1508  *        from within this source file.
1509  *
1510  * NOTE:  This routine assumes that the vm_pages found in PQ_CACHE and PQ_FREE
1511  *        represent stable storage, allowing us to order our locks vm_page
1512  *        first, then queue.
1513  */
1514 static __inline
1515 vm_page_t
1516 _vm_page_list_find(int basequeue, int index, boolean_t prefer_zero)
1517 {
1518         vm_page_t m;
1519
1520         for (;;) {
1521                 if (prefer_zero) {
1522                         m = TAILQ_LAST(&vm_page_queues[basequeue+index].pl,
1523                                        pglist);
1524                 } else {
1525                         m = TAILQ_FIRST(&vm_page_queues[basequeue+index].pl);
1526                 }
1527                 if (m == NULL) {
1528                         m = _vm_page_list_find2(basequeue, index);
1529                         return(m);
1530                 }
1531                 vm_page_and_queue_spin_lock(m);
1532                 if (m->queue == basequeue + index) {
1533                         _vm_page_rem_queue_spinlocked(m);
1534                         /* vm_page_t spin held, no queue spin */
1535                         break;
1536                 }
1537                 vm_page_and_queue_spin_unlock(m);
1538         }
1539         return(m);
1540 }
1541
1542 /*
1543  * If we could not find the page in the desired queue try to find it in
1544  * a nearby queue.
1545  */
1546 static vm_page_t
1547 _vm_page_list_find2(int basequeue, int index)
1548 {
1549         struct vpgqueues *pq;
1550         vm_page_t m = NULL;
1551         int pqmask = PQ_SET_ASSOC_MASK >> 1;
1552         int pqi;
1553         int i;
1554
1555         index &= PQ_L2_MASK;
1556         pq = &vm_page_queues[basequeue];
1557
1558         /*
1559          * Run local sets of 16, 32, 64, 128, and the whole queue if all
1560          * else fails (PQ_L2_MASK which is 255).
1561          */
1562         do {
1563                 pqmask = (pqmask << 1) | 1;
1564                 for (i = 0; i <= pqmask; ++i) {
1565                         pqi = (index & ~pqmask) | ((index + i) & pqmask);
1566                         m = TAILQ_FIRST(&pq[pqi].pl);
1567                         if (m) {
1568                                 _vm_page_and_queue_spin_lock(m);
1569                                 if (m->queue == basequeue + pqi) {
1570                                         _vm_page_rem_queue_spinlocked(m);
1571                                         return(m);
1572                                 }
1573                                 _vm_page_and_queue_spin_unlock(m);
1574                                 --i;
1575                                 continue;
1576                         }
1577                 }
1578         } while (pqmask != PQ_L2_MASK);
1579
1580         return(m);
1581 }
1582
1583 /*
1584  * Returns a vm_page candidate for allocation.  The page is not busied so
1585  * it can move around.  The caller must busy the page (and typically
1586  * deactivate it if it cannot be busied!)
1587  *
1588  * Returns a spinlocked vm_page that has been removed from its queue.
1589  */
1590 vm_page_t
1591 vm_page_list_find(int basequeue, int index, boolean_t prefer_zero)
1592 {
1593         return(_vm_page_list_find(basequeue, index, prefer_zero));
1594 }
1595
1596 /*
1597  * Find a page on the cache queue with color optimization, remove it
1598  * from the queue, and busy it.  The returned page will not be spinlocked.
1599  *
1600  * A candidate failure will be deactivated.  Candidates can fail due to
1601  * being busied by someone else, in which case they will be deactivated.
1602  *
1603  * This routine may not block.
1604  *
1605  */
1606 static vm_page_t
1607 vm_page_select_cache(u_short pg_color)
1608 {
1609         vm_page_t m;
1610
1611         for (;;) {
1612                 m = _vm_page_list_find(PQ_CACHE, pg_color & PQ_L2_MASK, FALSE);
1613                 if (m == NULL)
1614                         break;
1615                 /*
1616                  * (m) has been removed from its queue and spinlocked
1617                  */
1618                 if (vm_page_busy_try(m, TRUE)) {
1619                         _vm_page_deactivate_locked(m, 0);
1620                         vm_page_spin_unlock(m);
1621                 } else {
1622                         /*
1623                          * We successfully busied the page
1624                          */
1625                         if ((m->flags & (PG_UNMANAGED | PG_NEED_COMMIT)) == 0 &&
1626                             m->hold_count == 0 &&
1627                             m->wire_count == 0 &&
1628                             (m->dirty & m->valid) == 0) {
1629                                 vm_page_spin_unlock(m);
1630                                 pagedaemon_wakeup();
1631                                 return(m);
1632                         }
1633
1634                         /*
1635                          * The page cannot be recycled, deactivate it.
1636                          */
1637                         _vm_page_deactivate_locked(m, 0);
1638                         if (_vm_page_wakeup(m)) {
1639                                 vm_page_spin_unlock(m);
1640                                 wakeup(m);
1641                         } else {
1642                                 vm_page_spin_unlock(m);
1643                         }
1644                 }
1645         }
1646         return (m);
1647 }
1648
1649 /*
1650  * Find a free or zero page, with specified preference.  We attempt to
1651  * inline the nominal case and fall back to _vm_page_select_free() 
1652  * otherwise.  A busied page is removed from the queue and returned.
1653  *
1654  * This routine may not block.
1655  */
1656 static __inline vm_page_t
1657 vm_page_select_free(u_short pg_color, boolean_t prefer_zero)
1658 {
1659         vm_page_t m;
1660
1661         for (;;) {
1662                 m = _vm_page_list_find(PQ_FREE, pg_color & PQ_L2_MASK,
1663                                        prefer_zero);
1664                 if (m == NULL)
1665                         break;
1666                 if (vm_page_busy_try(m, TRUE)) {
1667                         /*
1668                          * Various mechanisms such as a pmap_collect can
1669                          * result in a busy page on the free queue.  We
1670                          * have to move the page out of the way so we can
1671                          * retry the allocation.  If the other thread is not
1672                          * allocating the page then m->valid will remain 0 and
1673                          * the pageout daemon will free the page later on.
1674                          *
1675                          * Since we could not busy the page, however, we
1676                          * cannot make assumptions as to whether the page
1677                          * will be allocated by the other thread or not,
1678                          * so all we can do is deactivate it to move it out
1679                          * of the way.  In particular, if the other thread
1680                          * wires the page it may wind up on the inactive
1681                          * queue and the pageout daemon will have to deal
1682                          * with that case too.
1683                          */
1684                         _vm_page_deactivate_locked(m, 0);
1685                         vm_page_spin_unlock(m);
1686                 } else {
1687                         /*
1688                          * Theoretically if we are able to busy the page
1689                          * atomic with the queue removal (using the vm_page
1690                          * lock) nobody else should be able to mess with the
1691                          * page before us.
1692                          */
1693                         KKASSERT((m->flags & (PG_UNMANAGED |
1694                                               PG_NEED_COMMIT)) == 0);
1695                         KASSERT(m->hold_count == 0, ("m->hold_count is not zero "
1696                                                      "pg %p q=%d flags=%08x hold=%d wire=%d",
1697                                                      m, m->queue, m->flags, m->hold_count, m->wire_count));
1698                         KKASSERT(m->wire_count == 0);
1699                         vm_page_spin_unlock(m);
1700                         pagedaemon_wakeup();
1701
1702                         /* return busied and removed page */
1703                         return(m);
1704                 }
1705         }
1706         return(m);
1707 }
1708
1709 /*
1710  * vm_page_alloc()
1711  *
1712  * Allocate and return a memory cell associated with this VM object/offset
1713  * pair.  If object is NULL an unassociated page will be allocated.
1714  *
1715  * The returned page will be busied and removed from its queues.  This
1716  * routine can block and may return NULL if a race occurs and the page
1717  * is found to already exist at the specified (object, pindex).
1718  *
1719  *      VM_ALLOC_NORMAL         allow use of cache pages, nominal free drain
1720  *      VM_ALLOC_QUICK          like normal but cannot use cache
1721  *      VM_ALLOC_SYSTEM         greater free drain
1722  *      VM_ALLOC_INTERRUPT      allow free list to be completely drained
1723  *      VM_ALLOC_ZERO           advisory request for pre-zero'd page only
1724  *      VM_ALLOC_FORCE_ZERO     advisory request for pre-zero'd page only
1725  *      VM_ALLOC_NULL_OK        ok to return NULL on insertion collision
1726  *                              (see vm_page_grab())
1727  *      VM_ALLOC_USE_GD         ok to use per-gd cache
1728  *
1729  * The object must be held if not NULL
1730  * This routine may not block
1731  *
1732  * Additional special handling is required when called from an interrupt
1733  * (VM_ALLOC_INTERRUPT).  We are not allowed to mess with the page cache
1734  * in this case.
1735  */
1736 vm_page_t
1737 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int page_req)
1738 {
1739         globaldata_t gd = mycpu;
1740         vm_object_t obj;
1741         vm_page_t m;
1742         u_short pg_color;
1743
1744 #if 0
1745         /*
1746          * Special per-cpu free VM page cache.  The pages are pre-busied
1747          * and pre-zerod for us.
1748          */
1749         if (gd->gd_vmpg_count && (page_req & VM_ALLOC_USE_GD)) {
1750                 crit_enter_gd(gd);
1751                 if (gd->gd_vmpg_count) {
1752                         m = gd->gd_vmpg_array[--gd->gd_vmpg_count];
1753                         crit_exit_gd(gd);
1754                         goto done;
1755                 }
1756                 crit_exit_gd(gd);
1757         }
1758 #endif
1759         m = NULL;
1760
1761         /*
1762          * CPU LOCALIZATION
1763          *
1764          * CPU localization algorithm.  Break the page queues up by physical
1765          * id and core id (note that two cpu threads will have the same core
1766          * id, and core_id != gd_cpuid).
1767          *
1768          * This is nowhere near perfect, for example the last pindex in a
1769          * subgroup will overflow into the next cpu or package.  But this
1770          * should get us good page reuse locality in heavy mixed loads.
1771          */
1772         pg_color = vm_get_pg_color(gd, object, pindex);
1773
1774         KKASSERT(page_req & 
1775                 (VM_ALLOC_NORMAL|VM_ALLOC_QUICK|
1776                  VM_ALLOC_INTERRUPT|VM_ALLOC_SYSTEM));
1777
1778         /*
1779          * Certain system threads (pageout daemon, buf_daemon's) are
1780          * allowed to eat deeper into the free page list.
1781          */
1782         if (curthread->td_flags & TDF_SYSTHREAD)
1783                 page_req |= VM_ALLOC_SYSTEM;
1784
1785         /*
1786          * Impose various limitations.  Note that the v_free_reserved test
1787          * must match the opposite of vm_page_count_target() to avoid
1788          * livelocks, be careful.
1789          */
1790 loop:
1791         if (vmstats.v_free_count >= vmstats.v_free_reserved ||
1792             ((page_req & VM_ALLOC_INTERRUPT) && vmstats.v_free_count > 0) ||
1793             ((page_req & VM_ALLOC_SYSTEM) && vmstats.v_cache_count == 0 &&
1794                 vmstats.v_free_count > vmstats.v_interrupt_free_min)
1795         ) {
1796                 /*
1797                  * The free queue has sufficient free pages to take one out.
1798                  */
1799                 if (page_req & (VM_ALLOC_ZERO | VM_ALLOC_FORCE_ZERO))
1800                         m = vm_page_select_free(pg_color, TRUE);
1801                 else
1802                         m = vm_page_select_free(pg_color, FALSE);
1803         } else if (page_req & VM_ALLOC_NORMAL) {
1804                 /*
1805                  * Allocatable from the cache (non-interrupt only).  On
1806                  * success, we must free the page and try again, thus
1807                  * ensuring that vmstats.v_*_free_min counters are replenished.
1808                  */
1809 #ifdef INVARIANTS
1810                 if (curthread->td_preempted) {
1811                         kprintf("vm_page_alloc(): warning, attempt to allocate"
1812                                 " cache page from preempting interrupt\n");
1813                         m = NULL;
1814                 } else {
1815                         m = vm_page_select_cache(pg_color);
1816                 }
1817 #else
1818                 m = vm_page_select_cache(pg_color);
1819 #endif
1820                 /*
1821                  * On success move the page into the free queue and loop.
1822                  *
1823                  * Only do this if we can safely acquire the vm_object lock,
1824                  * because this is effectively a random page and the caller
1825                  * might be holding the lock shared, we don't want to
1826                  * deadlock.
1827                  */
1828                 if (m != NULL) {
1829                         KASSERT(m->dirty == 0,
1830                                 ("Found dirty cache page %p", m));
1831                         if ((obj = m->object) != NULL) {
1832                                 if (vm_object_hold_try(obj)) {
1833                                         vm_page_protect(m, VM_PROT_NONE);
1834                                         vm_page_free(m);
1835                                         /* m->object NULL here */
1836                                         vm_object_drop(obj);
1837                                 } else {
1838                                         vm_page_deactivate(m);
1839                                         vm_page_wakeup(m);
1840                                 }
1841                         } else {
1842                                 vm_page_protect(m, VM_PROT_NONE);
1843                                 vm_page_free(m);
1844                         }
1845                         goto loop;
1846                 }
1847
1848                 /*
1849                  * On failure return NULL
1850                  */
1851 #if defined(DIAGNOSTIC)
1852                 if (vmstats.v_cache_count > 0)
1853                         kprintf("vm_page_alloc(NORMAL): missing pages on cache queue: %d\n", vmstats.v_cache_count);
1854 #endif
1855                 atomic_add_int(&vm_pageout_deficit, 1);
1856                 pagedaemon_wakeup();
1857                 return (NULL);
1858         } else {
1859                 /*
1860                  * No pages available, wakeup the pageout daemon and give up.
1861                  */
1862                 atomic_add_int(&vm_pageout_deficit, 1);
1863                 pagedaemon_wakeup();
1864                 return (NULL);
1865         }
1866
1867         /*
1868          * v_free_count can race so loop if we don't find the expected
1869          * page.
1870          */
1871         if (m == NULL)
1872                 goto loop;
1873
1874         /*
1875          * Good page found.  The page has already been busied for us and
1876          * removed from its queues.
1877          */
1878         KASSERT(m->dirty == 0,
1879                 ("vm_page_alloc: free/cache page %p was dirty", m));
1880         KKASSERT(m->queue == PQ_NONE);
1881
1882 #if 0
1883 done:
1884 #endif
1885         /*
1886          * Initialize the structure, inheriting some flags but clearing
1887          * all the rest.  The page has already been busied for us.
1888          */
1889         vm_page_flag_clear(m, ~(PG_BUSY | PG_SBUSY));
1890         KKASSERT(m->wire_count == 0);
1891         KKASSERT(m->busy == 0);
1892         m->act_count = 0;
1893         m->valid = 0;
1894
1895         /*
1896          * Caller must be holding the object lock (asserted by
1897          * vm_page_insert()).
1898          *
1899          * NOTE: Inserting a page here does not insert it into any pmaps
1900          *       (which could cause us to block allocating memory).
1901          *
1902          * NOTE: If no object an unassociated page is allocated, m->pindex
1903          *       can be used by the caller for any purpose.
1904          */
1905         if (object) {
1906                 if (vm_page_insert(m, object, pindex) == FALSE) {
1907                         vm_page_free(m);
1908                         if ((page_req & VM_ALLOC_NULL_OK) == 0)
1909                                 panic("PAGE RACE %p[%ld]/%p",
1910                                       object, (long)pindex, m);
1911                         m = NULL;
1912                 }
1913         } else {
1914                 m->pindex = pindex;
1915         }
1916
1917         /*
1918          * Don't wakeup too often - wakeup the pageout daemon when
1919          * we would be nearly out of memory.
1920          */
1921         pagedaemon_wakeup();
1922
1923         /*
1924          * A PG_BUSY page is returned.
1925          */
1926         return (m);
1927 }
1928
1929 /*
1930  * Returns number of pages available in our DMA memory reserve
1931  * (adjusted with vm.dma_reserved=<value>m in /boot/loader.conf)
1932  */
1933 vm_size_t
1934 vm_contig_avail_pages(void)
1935 {
1936         alist_blk_t blk;
1937         alist_blk_t count;
1938         alist_blk_t bfree;
1939         spin_lock(&vm_contig_spin);
1940         bfree = alist_free_info(&vm_contig_alist, &blk, &count);
1941         spin_unlock(&vm_contig_spin);
1942
1943         return bfree;
1944 }
1945
1946 /*
1947  * Attempt to allocate contiguous physical memory with the specified
1948  * requirements.
1949  */
1950 vm_page_t
1951 vm_page_alloc_contig(vm_paddr_t low, vm_paddr_t high,
1952                      unsigned long alignment, unsigned long boundary,
1953                      unsigned long size, vm_memattr_t memattr)
1954 {
1955         alist_blk_t blk;
1956         vm_page_t m;
1957         int i;
1958
1959         alignment >>= PAGE_SHIFT;
1960         if (alignment == 0)
1961                 alignment = 1;
1962         boundary >>= PAGE_SHIFT;
1963         if (boundary == 0)
1964                 boundary = 1;
1965         size = (size + PAGE_MASK) >> PAGE_SHIFT;
1966
1967         spin_lock(&vm_contig_spin);
1968         blk = alist_alloc(&vm_contig_alist, 0, size);
1969         if (blk == ALIST_BLOCK_NONE) {
1970                 spin_unlock(&vm_contig_spin);
1971                 if (bootverbose) {
1972                         kprintf("vm_page_alloc_contig: %ldk nospace\n",
1973                                 (size + PAGE_MASK) * (PAGE_SIZE / 1024));
1974                 }
1975                 return(NULL);
1976         }
1977         if (high && ((vm_paddr_t)(blk + size) << PAGE_SHIFT) > high) {
1978                 alist_free(&vm_contig_alist, blk, size);
1979                 spin_unlock(&vm_contig_spin);
1980                 if (bootverbose) {
1981                         kprintf("vm_page_alloc_contig: %ldk high "
1982                                 "%016jx failed\n",
1983                                 (size + PAGE_MASK) * (PAGE_SIZE / 1024),
1984                                 (intmax_t)high);
1985                 }
1986                 return(NULL);
1987         }
1988         spin_unlock(&vm_contig_spin);
1989         if (vm_contig_verbose) {
1990                 kprintf("vm_page_alloc_contig: %016jx/%ldk\n",
1991                         (intmax_t)(vm_paddr_t)blk << PAGE_SHIFT,
1992                         (size + PAGE_MASK) * (PAGE_SIZE / 1024));
1993         }
1994
1995         m = PHYS_TO_VM_PAGE((vm_paddr_t)blk << PAGE_SHIFT);
1996         if (memattr != VM_MEMATTR_DEFAULT)
1997                 for (i = 0;i < size;i++)
1998                         pmap_page_set_memattr(&m[i], memattr);
1999         return m;
2000 }
2001
2002 /*
2003  * Free contiguously allocated pages.  The pages will be wired but not busy.
2004  * When freeing to the alist we leave them wired and not busy.
2005  */
2006 void
2007 vm_page_free_contig(vm_page_t m, unsigned long size)
2008 {
2009         vm_paddr_t pa = VM_PAGE_TO_PHYS(m);
2010         vm_pindex_t start = pa >> PAGE_SHIFT;
2011         vm_pindex_t pages = (size + PAGE_MASK) >> PAGE_SHIFT;
2012
2013         if (vm_contig_verbose) {
2014                 kprintf("vm_page_free_contig:  %016jx/%ldk\n",
2015                         (intmax_t)pa, size / 1024);
2016         }
2017         if (pa < vm_low_phys_reserved) {
2018                 KKASSERT(pa + size <= vm_low_phys_reserved);
2019                 spin_lock(&vm_contig_spin);
2020                 alist_free(&vm_contig_alist, start, pages);
2021                 spin_unlock(&vm_contig_spin);
2022         } else {
2023                 while (pages) {
2024                         vm_page_busy_wait(m, FALSE, "cpgfr");
2025                         vm_page_unwire(m, 0);
2026                         vm_page_free(m);
2027                         --pages;
2028                         ++m;
2029                 }
2030
2031         }
2032 }
2033
2034
2035 /*
2036  * Wait for sufficient free memory for nominal heavy memory use kernel
2037  * operations.
2038  *
2039  * WARNING!  Be sure never to call this in any vm_pageout code path, which
2040  *           will trivially deadlock the system.
2041  */
2042 void
2043 vm_wait_nominal(void)
2044 {
2045         while (vm_page_count_min(0))
2046                 vm_wait(0);
2047 }
2048
2049 /*
2050  * Test if vm_wait_nominal() would block.
2051  */
2052 int
2053 vm_test_nominal(void)
2054 {
2055         if (vm_page_count_min(0))
2056                 return(1);
2057         return(0);
2058 }
2059
2060 /*
2061  * Block until free pages are available for allocation, called in various
2062  * places before memory allocations.
2063  *
2064  * The caller may loop if vm_page_count_min() == FALSE so we cannot be
2065  * more generous then that.
2066  */
2067 void
2068 vm_wait(int timo)
2069 {
2070         /*
2071          * never wait forever
2072          */
2073         if (timo == 0)
2074                 timo = hz;
2075         lwkt_gettoken(&vm_token);
2076
2077         if (curthread == pagethread) {
2078                 /*
2079                  * The pageout daemon itself needs pages, this is bad.
2080                  */
2081                 if (vm_page_count_min(0)) {
2082                         vm_pageout_pages_needed = 1;
2083                         tsleep(&vm_pageout_pages_needed, 0, "VMWait", timo);
2084                 }
2085         } else {
2086                 /*
2087                  * Wakeup the pageout daemon if necessary and wait.
2088                  *
2089                  * Do not wait indefinitely for the target to be reached,
2090                  * as load might prevent it from being reached any time soon.
2091                  * But wait a little to try to slow down page allocations
2092                  * and to give more important threads (the pagedaemon)
2093                  * allocation priority.
2094                  */
2095                 if (vm_page_count_target()) {
2096                         if (vm_pages_needed == 0) {
2097                                 vm_pages_needed = 1;
2098                                 wakeup(&vm_pages_needed);
2099                         }
2100                         ++vm_pages_waiting;     /* SMP race ok */
2101                         tsleep(&vmstats.v_free_count, 0, "vmwait", timo);
2102                 }
2103         }
2104         lwkt_reltoken(&vm_token);
2105 }
2106
2107 /*
2108  * Block until free pages are available for allocation
2109  *
2110  * Called only from vm_fault so that processes page faulting can be
2111  * easily tracked.
2112  */
2113 void
2114 vm_wait_pfault(void)
2115 {
2116         /*
2117          * Wakeup the pageout daemon if necessary and wait.
2118          *
2119          * Do not wait indefinitely for the target to be reached,
2120          * as load might prevent it from being reached any time soon.
2121          * But wait a little to try to slow down page allocations
2122          * and to give more important threads (the pagedaemon)
2123          * allocation priority.
2124          */
2125         if (vm_page_count_min(0)) {
2126                 lwkt_gettoken(&vm_token);
2127                 while (vm_page_count_severe()) {
2128                         if (vm_page_count_target()) {
2129                                 thread_t td;
2130
2131                                 if (vm_pages_needed == 0) {
2132                                         vm_pages_needed = 1;
2133                                         wakeup(&vm_pages_needed);
2134                                 }
2135                                 ++vm_pages_waiting;     /* SMP race ok */
2136                                 tsleep(&vmstats.v_free_count, 0, "pfault", hz);
2137
2138                                 /*
2139                                  * Do not stay stuck in the loop if the system is trying
2140                                  * to kill the process.
2141                                  */
2142                                 td = curthread;
2143                                 if (td->td_proc && (td->td_proc->p_flags & P_LOWMEMKILL))
2144                                         break;
2145                         }
2146                 }
2147                 lwkt_reltoken(&vm_token);
2148         }
2149 }
2150
2151 /*
2152  * Put the specified page on the active list (if appropriate).  Ensure
2153  * that act_count is at least ACT_INIT but do not otherwise mess with it.
2154  *
2155  * The caller should be holding the page busied ? XXX
2156  * This routine may not block.
2157  */
2158 void
2159 vm_page_activate(vm_page_t m)
2160 {
2161         u_short oqueue;
2162
2163         vm_page_spin_lock(m);
2164         if (m->queue - m->pc != PQ_ACTIVE) {
2165                 _vm_page_queue_spin_lock(m);
2166                 oqueue = _vm_page_rem_queue_spinlocked(m);
2167                 /* page is left spinlocked, queue is unlocked */
2168
2169                 if (oqueue == PQ_CACHE)
2170                         mycpu->gd_cnt.v_reactivated++;
2171                 if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
2172                         if (m->act_count < ACT_INIT)
2173                                 m->act_count = ACT_INIT;
2174                         _vm_page_add_queue_spinlocked(m, PQ_ACTIVE + m->pc, 0);
2175                 }
2176                 _vm_page_and_queue_spin_unlock(m);
2177                 if (oqueue == PQ_CACHE || oqueue == PQ_FREE)
2178                         pagedaemon_wakeup();
2179         } else {
2180                 if (m->act_count < ACT_INIT)
2181                         m->act_count = ACT_INIT;
2182                 vm_page_spin_unlock(m);
2183         }
2184 }
2185
2186 /*
2187  * Helper routine for vm_page_free_toq() and vm_page_cache().  This
2188  * routine is called when a page has been added to the cache or free
2189  * queues.
2190  *
2191  * This routine may not block.
2192  */
2193 static __inline void
2194 vm_page_free_wakeup(void)
2195 {
2196         /*
2197          * If the pageout daemon itself needs pages, then tell it that
2198          * there are some free.
2199          */
2200         if (vm_pageout_pages_needed &&
2201             vmstats.v_cache_count + vmstats.v_free_count >= 
2202             vmstats.v_pageout_free_min
2203         ) {
2204                 vm_pageout_pages_needed = 0;
2205                 wakeup(&vm_pageout_pages_needed);
2206         }
2207
2208         /*
2209          * Wakeup processes that are waiting on memory.
2210          *
2211          * Generally speaking we want to wakeup stuck processes as soon as
2212          * possible.  !vm_page_count_min(0) is the absolute minimum point
2213          * where we can do this.  Wait a bit longer to reduce degenerate
2214          * re-blocking (vm_page_free_hysteresis).  The target check is just
2215          * to make sure the min-check w/hysteresis does not exceed the
2216          * normal target.
2217          */
2218         if (vm_pages_waiting) {
2219                 if (!vm_page_count_min(vm_page_free_hysteresis) ||
2220                     !vm_page_count_target()) {
2221                         vm_pages_waiting = 0;
2222                         wakeup(&vmstats.v_free_count);
2223                         ++mycpu->gd_cnt.v_ppwakeups;
2224                 }
2225 #if 0
2226                 if (!vm_page_count_target()) {
2227                         /*
2228                          * Plenty of pages are free, wakeup everyone.
2229                          */
2230                         vm_pages_waiting = 0;
2231                         wakeup(&vmstats.v_free_count);
2232                         ++mycpu->gd_cnt.v_ppwakeups;
2233                 } else if (!vm_page_count_min(0)) {
2234                         /*
2235                          * Some pages are free, wakeup someone.
2236                          */
2237                         int wcount = vm_pages_waiting;
2238                         if (wcount > 0)
2239                                 --wcount;
2240                         vm_pages_waiting = wcount;
2241                         wakeup_one(&vmstats.v_free_count);
2242                         ++mycpu->gd_cnt.v_ppwakeups;
2243                 }
2244 #endif
2245         }
2246 }
2247
2248 /*
2249  * Returns the given page to the PQ_FREE or PQ_HOLD list and disassociates
2250  * it from its VM object.
2251  *
2252  * The vm_page must be PG_BUSY on entry.  PG_BUSY will be released on
2253  * return (the page will have been freed).
2254  */
2255 void
2256 vm_page_free_toq(vm_page_t m)
2257 {
2258         mycpu->gd_cnt.v_tfree++;
2259         KKASSERT((m->flags & PG_MAPPED) == 0);
2260         KKASSERT(m->flags & PG_BUSY);
2261
2262         if (m->busy || ((m->queue - m->pc) == PQ_FREE)) {
2263                 kprintf("vm_page_free: pindex(%lu), busy(%d), "
2264                         "PG_BUSY(%d), hold(%d)\n",
2265                         (u_long)m->pindex, m->busy,
2266                         ((m->flags & PG_BUSY) ? 1 : 0), m->hold_count);
2267                 if ((m->queue - m->pc) == PQ_FREE)
2268                         panic("vm_page_free: freeing free page");
2269                 else
2270                         panic("vm_page_free: freeing busy page");
2271         }
2272
2273         /*
2274          * Remove from object, spinlock the page and its queues and
2275          * remove from any queue.  No queue spinlock will be held
2276          * after this section (because the page was removed from any
2277          * queue).
2278          */
2279         vm_page_remove(m);
2280         vm_page_and_queue_spin_lock(m);
2281         _vm_page_rem_queue_spinlocked(m);
2282
2283         /*
2284          * No further management of fictitious pages occurs beyond object
2285          * and queue removal.
2286          */
2287         if ((m->flags & PG_FICTITIOUS) != 0) {
2288                 vm_page_spin_unlock(m);
2289                 vm_page_wakeup(m);
2290                 return;
2291         }
2292
2293         m->valid = 0;
2294         vm_page_undirty(m);
2295
2296         if (m->wire_count != 0) {
2297                 if (m->wire_count > 1) {
2298                     panic(
2299                         "vm_page_free: invalid wire count (%d), pindex: 0x%lx",
2300                         m->wire_count, (long)m->pindex);
2301                 }
2302                 panic("vm_page_free: freeing wired page");
2303         }
2304
2305         /*
2306          * Clear the UNMANAGED flag when freeing an unmanaged page.
2307          * Clear the NEED_COMMIT flag
2308          */
2309         if (m->flags & PG_UNMANAGED)
2310                 vm_page_flag_clear(m, PG_UNMANAGED);
2311         if (m->flags & PG_NEED_COMMIT)
2312                 vm_page_flag_clear(m, PG_NEED_COMMIT);
2313
2314         if (m->hold_count != 0) {
2315                 _vm_page_add_queue_spinlocked(m, PQ_HOLD + m->pc, 0);
2316         } else {
2317                 _vm_page_add_queue_spinlocked(m, PQ_FREE + m->pc, 0);
2318         }
2319
2320         /*
2321          * This sequence allows us to clear PG_BUSY while still holding
2322          * its spin lock, which reduces contention vs allocators.  We
2323          * must not leave the queue locked or _vm_page_wakeup() may
2324          * deadlock.
2325          */
2326         _vm_page_queue_spin_unlock(m);
2327         if (_vm_page_wakeup(m)) {
2328                 vm_page_spin_unlock(m);
2329                 wakeup(m);
2330         } else {
2331                 vm_page_spin_unlock(m);
2332         }
2333         vm_page_free_wakeup();
2334 }
2335
2336 /*
2337  * vm_page_unmanage()
2338  *
2339  * Prevent PV management from being done on the page.  The page is
2340  * removed from the paging queues as if it were wired, and as a 
2341  * consequence of no longer being managed the pageout daemon will not
2342  * touch it (since there is no way to locate the pte mappings for the
2343  * page).  madvise() calls that mess with the pmap will also no longer
2344  * operate on the page.
2345  *
2346  * Beyond that the page is still reasonably 'normal'.  Freeing the page
2347  * will clear the flag.
2348  *
2349  * This routine is used by OBJT_PHYS objects - objects using unswappable
2350  * physical memory as backing store rather then swap-backed memory and
2351  * will eventually be extended to support 4MB unmanaged physical 
2352  * mappings.
2353  *
2354  * Caller must be holding the page busy.
2355  */
2356 void
2357 vm_page_unmanage(vm_page_t m)
2358 {
2359         KKASSERT(m->flags & PG_BUSY);
2360         if ((m->flags & PG_UNMANAGED) == 0) {
2361                 if (m->wire_count == 0)
2362                         vm_page_unqueue(m);
2363         }
2364         vm_page_flag_set(m, PG_UNMANAGED);
2365 }
2366
2367 /*
2368  * Mark this page as wired down by yet another map, removing it from
2369  * paging queues as necessary.
2370  *
2371  * Caller must be holding the page busy.
2372  */
2373 void
2374 vm_page_wire(vm_page_t m)
2375 {
2376         /*
2377          * Only bump the wire statistics if the page is not already wired,
2378          * and only unqueue the page if it is on some queue (if it is unmanaged
2379          * it is already off the queues).  Don't do anything with fictitious
2380          * pages because they are always wired.
2381          */
2382         KKASSERT(m->flags & PG_BUSY);
2383         if ((m->flags & PG_FICTITIOUS) == 0) {
2384                 if (atomic_fetchadd_int(&m->wire_count, 1) == 0) {
2385                         if ((m->flags & PG_UNMANAGED) == 0)
2386                                 vm_page_unqueue(m);
2387                         atomic_add_int(&vmstats.v_wire_count, 1);
2388                 }
2389                 KASSERT(m->wire_count != 0,
2390                         ("vm_page_wire: wire_count overflow m=%p", m));
2391         }
2392 }
2393
2394 /*
2395  * Release one wiring of this page, potentially enabling it to be paged again.
2396  *
2397  * Many pages placed on the inactive queue should actually go
2398  * into the cache, but it is difficult to figure out which.  What
2399  * we do instead, if the inactive target is well met, is to put
2400  * clean pages at the head of the inactive queue instead of the tail.
2401  * This will cause them to be moved to the cache more quickly and
2402  * if not actively re-referenced, freed more quickly.  If we just
2403  * stick these pages at the end of the inactive queue, heavy filesystem
2404  * meta-data accesses can cause an unnecessary paging load on memory bound 
2405  * processes.  This optimization causes one-time-use metadata to be
2406  * reused more quickly.
2407  *
2408  * Pages marked PG_NEED_COMMIT are always activated and never placed on
2409  * the inactive queue.  This helps the pageout daemon determine memory
2410  * pressure and act on out-of-memory situations more quickly.
2411  *
2412  * BUT, if we are in a low-memory situation we have no choice but to
2413  * put clean pages on the cache queue.
2414  *
2415  * A number of routines use vm_page_unwire() to guarantee that the page
2416  * will go into either the inactive or active queues, and will NEVER
2417  * be placed in the cache - for example, just after dirtying a page.
2418  * dirty pages in the cache are not allowed.
2419  *
2420  * This routine may not block.
2421  */
2422 void
2423 vm_page_unwire(vm_page_t m, int activate)
2424 {
2425         KKASSERT(m->flags & PG_BUSY);
2426         if (m->flags & PG_FICTITIOUS) {
2427                 /* do nothing */
2428         } else if (m->wire_count <= 0) {
2429                 panic("vm_page_unwire: invalid wire count: %d", m->wire_count);
2430         } else {
2431                 if (atomic_fetchadd_int(&m->wire_count, -1) == 1) {
2432                         atomic_add_int(&vmstats.v_wire_count, -1);
2433                         if (m->flags & PG_UNMANAGED) {
2434                                 ;
2435                         } else if (activate || (m->flags & PG_NEED_COMMIT)) {
2436                                 vm_page_spin_lock(m);
2437                                 _vm_page_add_queue_spinlocked(m,
2438                                                         PQ_ACTIVE + m->pc, 0);
2439                                 _vm_page_and_queue_spin_unlock(m);
2440                         } else {
2441                                 vm_page_spin_lock(m);
2442                                 vm_page_flag_clear(m, PG_WINATCFLS);
2443                                 _vm_page_add_queue_spinlocked(m,
2444                                                         PQ_INACTIVE + m->pc, 0);
2445                                 ++vm_swapcache_inactive_heuristic;
2446                                 _vm_page_and_queue_spin_unlock(m);
2447                         }
2448                 }
2449         }
2450 }
2451
2452 /*
2453  * Move the specified page to the inactive queue.  If the page has
2454  * any associated swap, the swap is deallocated.
2455  *
2456  * Normally athead is 0 resulting in LRU operation.  athead is set
2457  * to 1 if we want this page to be 'as if it were placed in the cache',
2458  * except without unmapping it from the process address space.
2459  *
2460  * vm_page's spinlock must be held on entry and will remain held on return.
2461  * This routine may not block.
2462  */
2463 static void
2464 _vm_page_deactivate_locked(vm_page_t m, int athead)
2465 {
2466         u_short oqueue;
2467
2468         /*
2469          * Ignore if already inactive.
2470          */
2471         if (m->queue - m->pc == PQ_INACTIVE)
2472                 return;
2473         _vm_page_queue_spin_lock(m);
2474         oqueue = _vm_page_rem_queue_spinlocked(m);
2475
2476         if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
2477                 if (oqueue == PQ_CACHE)
2478                         mycpu->gd_cnt.v_reactivated++;
2479                 vm_page_flag_clear(m, PG_WINATCFLS);
2480                 _vm_page_add_queue_spinlocked(m, PQ_INACTIVE + m->pc, athead);
2481                 if (athead == 0)
2482                         ++vm_swapcache_inactive_heuristic;
2483         }
2484         /* NOTE: PQ_NONE if condition not taken */
2485         _vm_page_queue_spin_unlock(m);
2486         /* leaves vm_page spinlocked */
2487 }
2488
2489 /*
2490  * Attempt to deactivate a page.
2491  *
2492  * No requirements.
2493  */
2494 void
2495 vm_page_deactivate(vm_page_t m)
2496 {
2497         vm_page_spin_lock(m);
2498         _vm_page_deactivate_locked(m, 0);
2499         vm_page_spin_unlock(m);
2500 }
2501
2502 void
2503 vm_page_deactivate_locked(vm_page_t m)
2504 {
2505         _vm_page_deactivate_locked(m, 0);
2506 }
2507
2508 /*
2509  * Attempt to move a busied page to PQ_CACHE, then unconditionally unbusy it.
2510  *
2511  * This function returns non-zero if it successfully moved the page to
2512  * PQ_CACHE.
2513  *
2514  * This function unconditionally unbusies the page on return.
2515  */
2516 int
2517 vm_page_try_to_cache(vm_page_t m)
2518 {
2519         vm_page_spin_lock(m);
2520         if (m->dirty || m->hold_count || m->wire_count ||
2521             (m->flags & (PG_UNMANAGED | PG_NEED_COMMIT))) {
2522                 if (_vm_page_wakeup(m)) {
2523                         vm_page_spin_unlock(m);
2524                         wakeup(m);
2525                 } else {
2526                         vm_page_spin_unlock(m);
2527                 }
2528                 return(0);
2529         }
2530         vm_page_spin_unlock(m);
2531
2532         /*
2533          * Page busied by us and no longer spinlocked.  Dirty pages cannot
2534          * be moved to the cache.
2535          */
2536         vm_page_test_dirty(m);
2537         if (m->dirty || (m->flags & PG_NEED_COMMIT)) {
2538                 vm_page_wakeup(m);
2539                 return(0);
2540         }
2541         vm_page_cache(m);
2542         return(1);
2543 }
2544
2545 /*
2546  * Attempt to free the page.  If we cannot free it, we do nothing.
2547  * 1 is returned on success, 0 on failure.
2548  *
2549  * No requirements.
2550  */
2551 int
2552 vm_page_try_to_free(vm_page_t m)
2553 {
2554         vm_page_spin_lock(m);
2555         if (vm_page_busy_try(m, TRUE)) {
2556                 vm_page_spin_unlock(m);
2557                 return(0);
2558         }
2559
2560         /*
2561          * The page can be in any state, including already being on the free
2562          * queue.  Check to see if it really can be freed.
2563          */
2564         if (m->dirty ||                         /* can't free if it is dirty */
2565             m->hold_count ||                    /* or held (XXX may be wrong) */
2566             m->wire_count ||                    /* or wired */
2567             (m->flags & (PG_UNMANAGED |         /* or unmanaged */
2568                          PG_NEED_COMMIT)) ||    /* or needs a commit */
2569             m->queue - m->pc == PQ_FREE ||      /* already on PQ_FREE */
2570             m->queue - m->pc == PQ_HOLD) {      /* already on PQ_HOLD */
2571                 if (_vm_page_wakeup(m)) {
2572                         vm_page_spin_unlock(m);
2573                         wakeup(m);
2574                 } else {
2575                         vm_page_spin_unlock(m);
2576                 }
2577                 return(0);
2578         }
2579         vm_page_spin_unlock(m);
2580
2581         /*
2582          * We can probably free the page.
2583          *
2584          * Page busied by us and no longer spinlocked.  Dirty pages will
2585          * not be freed by this function.    We have to re-test the
2586          * dirty bit after cleaning out the pmaps.
2587          */
2588         vm_page_test_dirty(m);
2589         if (m->dirty || (m->flags & PG_NEED_COMMIT)) {
2590                 vm_page_wakeup(m);
2591                 return(0);
2592         }
2593         vm_page_protect(m, VM_PROT_NONE);
2594         if (m->dirty || (m->flags & PG_NEED_COMMIT)) {
2595                 vm_page_wakeup(m);
2596                 return(0);
2597         }
2598         vm_page_free(m);
2599         return(1);
2600 }
2601
2602 /*
2603  * vm_page_cache
2604  *
2605  * Put the specified page onto the page cache queue (if appropriate).
2606  *
2607  * The page must be busy, and this routine will release the busy and
2608  * possibly even free the page.
2609  */
2610 void
2611 vm_page_cache(vm_page_t m)
2612 {
2613         /*
2614          * Not suitable for the cache
2615          */
2616         if ((m->flags & (PG_UNMANAGED | PG_NEED_COMMIT)) ||
2617             m->busy || m->wire_count || m->hold_count) {
2618                 vm_page_wakeup(m);
2619                 return;
2620         }
2621
2622         /*
2623          * Already in the cache (and thus not mapped)
2624          */
2625         if ((m->queue - m->pc) == PQ_CACHE) {
2626                 KKASSERT((m->flags & PG_MAPPED) == 0);
2627                 vm_page_wakeup(m);
2628                 return;
2629         }
2630
2631         /*
2632          * Caller is required to test m->dirty, but note that the act of
2633          * removing the page from its maps can cause it to become dirty
2634          * on an SMP system due to another cpu running in usermode.
2635          */
2636         if (m->dirty) {
2637                 panic("vm_page_cache: caching a dirty page, pindex: %ld",
2638                         (long)m->pindex);
2639         }
2640
2641         /*
2642          * Remove all pmaps and indicate that the page is not
2643          * writeable or mapped.  Our vm_page_protect() call may
2644          * have blocked (especially w/ VM_PROT_NONE), so recheck
2645          * everything.
2646          */
2647         vm_page_protect(m, VM_PROT_NONE);
2648         if ((m->flags & (PG_UNMANAGED | PG_MAPPED)) ||
2649             m->busy || m->wire_count || m->hold_count) {
2650                 vm_page_wakeup(m);
2651         } else if (m->dirty || (m->flags & PG_NEED_COMMIT)) {
2652                 vm_page_deactivate(m);
2653                 vm_page_wakeup(m);
2654         } else {
2655                 _vm_page_and_queue_spin_lock(m);
2656                 _vm_page_rem_queue_spinlocked(m);
2657                 _vm_page_add_queue_spinlocked(m, PQ_CACHE + m->pc, 0);
2658                 _vm_page_queue_spin_unlock(m);
2659                 if (_vm_page_wakeup(m)) {
2660                         vm_page_spin_unlock(m);
2661                         wakeup(m);
2662                 } else {
2663                         vm_page_spin_unlock(m);
2664                 }
2665                 vm_page_free_wakeup();
2666         }
2667 }
2668
2669 /*
2670  * vm_page_dontneed()
2671  *
2672  * Cache, deactivate, or do nothing as appropriate.  This routine
2673  * is typically used by madvise() MADV_DONTNEED.
2674  *
2675  * Generally speaking we want to move the page into the cache so
2676  * it gets reused quickly.  However, this can result in a silly syndrome
2677  * due to the page recycling too quickly.  Small objects will not be
2678  * fully cached.  On the otherhand, if we move the page to the inactive
2679  * queue we wind up with a problem whereby very large objects 
2680  * unnecessarily blow away our inactive and cache queues.
2681  *
2682  * The solution is to move the pages based on a fixed weighting.  We
2683  * either leave them alone, deactivate them, or move them to the cache,
2684  * where moving them to the cache has the highest weighting.
2685  * By forcing some pages into other queues we eventually force the
2686  * system to balance the queues, potentially recovering other unrelated
2687  * space from active.  The idea is to not force this to happen too
2688  * often.
2689  *
2690  * The page must be busied.
2691  */
2692 void
2693 vm_page_dontneed(vm_page_t m)
2694 {
2695         static int dnweight;
2696         int dnw;
2697         int head;
2698
2699         dnw = ++dnweight;
2700
2701         /*
2702          * occassionally leave the page alone
2703          */
2704         if ((dnw & 0x01F0) == 0 ||
2705             m->queue - m->pc == PQ_INACTIVE ||
2706             m->queue - m->pc == PQ_CACHE
2707         ) {
2708                 if (m->act_count >= ACT_INIT)
2709                         --m->act_count;
2710                 return;
2711         }
2712
2713         /*
2714          * If vm_page_dontneed() is inactivating a page, it must clear
2715          * the referenced flag; otherwise the pagedaemon will see references
2716          * on the page in the inactive queue and reactivate it. Until the 
2717          * page can move to the cache queue, madvise's job is not done.
2718          */
2719         vm_page_flag_clear(m, PG_REFERENCED);
2720         pmap_clear_reference(m);
2721
2722         if (m->dirty == 0)
2723                 vm_page_test_dirty(m);
2724
2725         if (m->dirty || (dnw & 0x0070) == 0) {
2726                 /*
2727                  * Deactivate the page 3 times out of 32.
2728                  */
2729                 head = 0;
2730         } else {
2731                 /*
2732                  * Cache the page 28 times out of every 32.  Note that
2733                  * the page is deactivated instead of cached, but placed
2734                  * at the head of the queue instead of the tail.
2735                  */
2736                 head = 1;
2737         }
2738         vm_page_spin_lock(m);
2739         _vm_page_deactivate_locked(m, head);
2740         vm_page_spin_unlock(m);
2741 }
2742
2743 /*
2744  * These routines manipulate the 'soft busy' count for a page.  A soft busy
2745  * is almost like PG_BUSY except that it allows certain compatible operations
2746  * to occur on the page while it is busy.  For example, a page undergoing a
2747  * write can still be mapped read-only.
2748  *
2749  * Because vm_pages can overlap buffers m->busy can be > 1.  m->busy is only
2750  * adjusted while the vm_page is PG_BUSY so the flash will occur when the
2751  * busy bit is cleared.
2752  */
2753 void
2754 vm_page_io_start(vm_page_t m)
2755 {
2756         KASSERT(m->flags & PG_BUSY, ("vm_page_io_start: page not busy!!!"));
2757         atomic_add_char(&m->busy, 1);
2758         vm_page_flag_set(m, PG_SBUSY);
2759 }
2760
2761 void
2762 vm_page_io_finish(vm_page_t m)
2763 {
2764         KASSERT(m->flags & PG_BUSY, ("vm_page_io_finish: page not busy!!!"));
2765         atomic_subtract_char(&m->busy, 1);
2766         if (m->busy == 0)
2767                 vm_page_flag_clear(m, PG_SBUSY);
2768 }
2769
2770 /*
2771  * Indicate that a clean VM page requires a filesystem commit and cannot
2772  * be reused.  Used by tmpfs.
2773  */
2774 void
2775 vm_page_need_commit(vm_page_t m)
2776 {
2777         vm_page_flag_set(m, PG_NEED_COMMIT);
2778         vm_object_set_writeable_dirty(m->object);
2779 }
2780
2781 void
2782 vm_page_clear_commit(vm_page_t m)
2783 {
2784         vm_page_flag_clear(m, PG_NEED_COMMIT);
2785 }
2786
2787 /*
2788  * Grab a page, blocking if it is busy and allocating a page if necessary.
2789  * A busy page is returned or NULL.  The page may or may not be valid and
2790  * might not be on a queue (the caller is responsible for the disposition of
2791  * the page).
2792  *
2793  * If VM_ALLOC_ZERO is specified and the grab must allocate a new page, the
2794  * page will be zero'd and marked valid.
2795  *
2796  * If VM_ALLOC_FORCE_ZERO is specified the page will be zero'd and marked
2797  * valid even if it already exists.
2798  *
2799  * If VM_ALLOC_RETRY is specified this routine will never return NULL.  Also
2800  * note that VM_ALLOC_NORMAL must be specified if VM_ALLOC_RETRY is specified.
2801  * VM_ALLOC_NULL_OK is implied when VM_ALLOC_RETRY is specified.
2802  *
2803  * This routine may block, but if VM_ALLOC_RETRY is not set then NULL is
2804  * always returned if we had blocked.  
2805  *
2806  * This routine may not be called from an interrupt.
2807  *
2808  * No other requirements.
2809  */
2810 vm_page_t
2811 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
2812 {
2813         vm_page_t m;
2814         int error;
2815         int shared = 1;
2816
2817         KKASSERT(allocflags &
2818                 (VM_ALLOC_NORMAL|VM_ALLOC_INTERRUPT|VM_ALLOC_SYSTEM));
2819         vm_object_hold_shared(object);
2820         for (;;) {
2821                 m = vm_page_lookup_busy_try(object, pindex, TRUE, &error);
2822                 if (error) {
2823                         vm_page_sleep_busy(m, TRUE, "pgrbwt");
2824                         if ((allocflags & VM_ALLOC_RETRY) == 0) {
2825                                 m = NULL;
2826                                 break;
2827                         }
2828                         /* retry */
2829                 } else if (m == NULL) {
2830                         if (shared) {
2831                                 vm_object_upgrade(object);
2832                                 shared = 0;
2833                         }
2834                         if (allocflags & VM_ALLOC_RETRY)
2835                                 allocflags |= VM_ALLOC_NULL_OK;
2836                         m = vm_page_alloc(object, pindex,
2837                                           allocflags & ~VM_ALLOC_RETRY);
2838                         if (m)
2839                                 break;
2840                         vm_wait(0);
2841                         if ((allocflags & VM_ALLOC_RETRY) == 0)
2842                                 goto failed;
2843                 } else {
2844                         /* m found */
2845                         break;
2846                 }
2847         }
2848
2849         /*
2850          * If VM_ALLOC_ZERO an invalid page will be zero'd and set valid.
2851          *
2852          * If VM_ALLOC_FORCE_ZERO the page is unconditionally zero'd and set
2853          * valid even if already valid.
2854          *
2855          * NOTE!  We have removed all of the PG_ZERO optimizations and also
2856          *        removed the idle zeroing code.  These optimizations actually
2857          *        slow things down on modern cpus because the zerod area is
2858          *        likely uncached, placing a memory-access burden on the
2859          *        accesors taking the fault.
2860          *
2861          *        By always zeroing the page in-line with the fault, no
2862          *        dynamic ram reads are needed and the caches are hot, ready
2863          *        for userland to access the memory.
2864          */
2865         if (m->valid == 0) {
2866                 if (allocflags & (VM_ALLOC_ZERO | VM_ALLOC_FORCE_ZERO)) {
2867                         pmap_zero_page(VM_PAGE_TO_PHYS(m));
2868                         m->valid = VM_PAGE_BITS_ALL;
2869                 }
2870         } else if (allocflags & VM_ALLOC_FORCE_ZERO) {
2871                 pmap_zero_page(VM_PAGE_TO_PHYS(m));
2872                 m->valid = VM_PAGE_BITS_ALL;
2873         }
2874 failed:
2875         vm_object_drop(object);
2876         return(m);
2877 }
2878
2879 /*
2880  * Mapping function for valid bits or for dirty bits in
2881  * a page.  May not block.
2882  *
2883  * Inputs are required to range within a page.
2884  *
2885  * No requirements.
2886  * Non blocking.
2887  */
2888 int
2889 vm_page_bits(int base, int size)
2890 {
2891         int first_bit;
2892         int last_bit;
2893
2894         KASSERT(
2895             base + size <= PAGE_SIZE,
2896             ("vm_page_bits: illegal base/size %d/%d", base, size)
2897         );
2898
2899         if (size == 0)          /* handle degenerate case */
2900                 return(0);
2901
2902         first_bit = base >> DEV_BSHIFT;
2903         last_bit = (base + size - 1) >> DEV_BSHIFT;
2904
2905         return ((2 << last_bit) - (1 << first_bit));
2906 }
2907
2908 /*
2909  * Sets portions of a page valid and clean.  The arguments are expected
2910  * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2911  * of any partial chunks touched by the range.  The invalid portion of
2912  * such chunks will be zero'd.
2913  *
2914  * NOTE: When truncating a buffer vnode_pager_setsize() will automatically
2915  *       align base to DEV_BSIZE so as not to mark clean a partially
2916  *       truncated device block.  Otherwise the dirty page status might be
2917  *       lost.
2918  *
2919  * This routine may not block.
2920  *
2921  * (base + size) must be less then or equal to PAGE_SIZE.
2922  */
2923 static void
2924 _vm_page_zero_valid(vm_page_t m, int base, int size)
2925 {
2926         int frag;
2927         int endoff;
2928
2929         if (size == 0)  /* handle degenerate case */
2930                 return;
2931
2932         /*
2933          * If the base is not DEV_BSIZE aligned and the valid
2934          * bit is clear, we have to zero out a portion of the
2935          * first block.
2936          */
2937
2938         if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
2939             (m->valid & (1 << (base >> DEV_BSHIFT))) == 0
2940         ) {
2941                 pmap_zero_page_area(
2942                     VM_PAGE_TO_PHYS(m),
2943                     frag,
2944                     base - frag
2945                 );
2946         }
2947
2948         /*
2949          * If the ending offset is not DEV_BSIZE aligned and the 
2950          * valid bit is clear, we have to zero out a portion of
2951          * the last block.
2952          */
2953
2954         endoff = base + size;
2955
2956         if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
2957             (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0
2958         ) {
2959                 pmap_zero_page_area(
2960                     VM_PAGE_TO_PHYS(m),
2961                     endoff,
2962                     DEV_BSIZE - (endoff & (DEV_BSIZE - 1))
2963                 );
2964         }
2965 }
2966
2967 /*
2968  * Set valid, clear dirty bits.  If validating the entire
2969  * page we can safely clear the pmap modify bit.  We also
2970  * use this opportunity to clear the PG_NOSYNC flag.  If a process
2971  * takes a write fault on a MAP_NOSYNC memory area the flag will
2972  * be set again.
2973  *
2974  * We set valid bits inclusive of any overlap, but we can only
2975  * clear dirty bits for DEV_BSIZE chunks that are fully within
2976  * the range.
2977  *
2978  * Page must be busied?
2979  * No other requirements.
2980  */
2981 void
2982 vm_page_set_valid(vm_page_t m, int base, int size)
2983 {
2984         _vm_page_zero_valid(m, base, size);
2985         m->valid |= vm_page_bits(base, size);
2986 }
2987
2988
2989 /*
2990  * Set valid bits and clear dirty bits.
2991  *
2992  * NOTE: This function does not clear the pmap modified bit.
2993  *       Also note that e.g. NFS may use a byte-granular base
2994  *       and size.
2995  *
2996  * WARNING: Page must be busied?  But vfs_clean_one_page() will call
2997  *          this without necessarily busying the page (via bdwrite()).
2998  *          So for now vm_token must also be held.
2999  *
3000  * No other requirements.
3001  */
3002 void
3003 vm_page_set_validclean(vm_page_t m, int base, int size)
3004 {
3005         int pagebits;
3006
3007         _vm_page_zero_valid(m, base, size);
3008         pagebits = vm_page_bits(base, size);
3009         m->valid |= pagebits;
3010         m->dirty &= ~pagebits;
3011         if (base == 0 && size == PAGE_SIZE) {
3012                 /*pmap_clear_modify(m);*/
3013                 vm_page_flag_clear(m, PG_NOSYNC);
3014         }
3015 }
3016
3017 /*
3018  * Set valid & dirty.  Used by buwrite()
3019  *
3020  * WARNING: Page must be busied?  But vfs_dirty_one_page() will
3021  *          call this function in buwrite() so for now vm_token must
3022  *          be held.
3023  *
3024  * No other requirements.
3025  */
3026 void
3027 vm_page_set_validdirty(vm_page_t m, int base, int size)
3028 {
3029         int pagebits;
3030
3031         pagebits = vm_page_bits(base, size);
3032         m->valid |= pagebits;
3033         m->dirty |= pagebits;
3034         if (m->object)
3035                vm_object_set_writeable_dirty(m->object);
3036 }
3037
3038 /*
3039  * Clear dirty bits.
3040  *
3041  * NOTE: This function does not clear the pmap modified bit.
3042  *       Also note that e.g. NFS may use a byte-granular base
3043  *       and size.
3044  *
3045  * Page must be busied?
3046  * No other requirements.
3047  */
3048 void
3049 vm_page_clear_dirty(vm_page_t m, int base, int size)
3050 {
3051         m->dirty &= ~vm_page_bits(base, size);
3052         if (base == 0 && size == PAGE_SIZE) {
3053                 /*pmap_clear_modify(m);*/
3054                 vm_page_flag_clear(m, PG_NOSYNC);
3055         }
3056 }
3057
3058 /*
3059  * Make the page all-dirty.
3060  *
3061  * Also make sure the related object and vnode reflect the fact that the
3062  * object may now contain a dirty page.
3063  *
3064  * Page must be busied?
3065  * No other requirements.
3066  */
3067 void
3068 vm_page_dirty(vm_page_t m)
3069 {
3070 #ifdef INVARIANTS
3071         int pqtype = m->queue - m->pc;
3072 #endif
3073         KASSERT(pqtype != PQ_CACHE && pqtype != PQ_FREE,
3074                 ("vm_page_dirty: page in free/cache queue!"));
3075         if (m->dirty != VM_PAGE_BITS_ALL) {
3076                 m->dirty = VM_PAGE_BITS_ALL;
3077                 if (m->object)
3078                         vm_object_set_writeable_dirty(m->object);
3079         }
3080 }
3081
3082 /*
3083  * Invalidates DEV_BSIZE'd chunks within a page.  Both the
3084  * valid and dirty bits for the effected areas are cleared.
3085  *
3086  * Page must be busied?
3087  * Does not block.
3088  * No other requirements.
3089  */
3090 void
3091 vm_page_set_invalid(vm_page_t m, int base, int size)
3092 {
3093         int bits;
3094
3095         bits = vm_page_bits(base, size);
3096         m->valid &= ~bits;
3097         m->dirty &= ~bits;
3098         m->object->generation++;
3099 }
3100
3101 /*
3102  * The kernel assumes that the invalid portions of a page contain 
3103  * garbage, but such pages can be mapped into memory by user code.
3104  * When this occurs, we must zero out the non-valid portions of the
3105  * page so user code sees what it expects.
3106  *
3107  * Pages are most often semi-valid when the end of a file is mapped 
3108  * into memory and the file's size is not page aligned.
3109  *
3110  * Page must be busied?
3111  * No other requirements.
3112  */
3113 void
3114 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
3115 {
3116         int b;
3117         int i;
3118
3119         /*
3120          * Scan the valid bits looking for invalid sections that
3121          * must be zerod.  Invalid sub-DEV_BSIZE'd areas ( where the
3122          * valid bit may be set ) have already been zerod by
3123          * vm_page_set_validclean().
3124          */
3125         for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
3126                 if (i == (PAGE_SIZE / DEV_BSIZE) || 
3127                     (m->valid & (1 << i))
3128                 ) {
3129                         if (i > b) {
3130                                 pmap_zero_page_area(
3131                                     VM_PAGE_TO_PHYS(m), 
3132                                     b << DEV_BSHIFT,
3133                                     (i - b) << DEV_BSHIFT
3134                                 );
3135                         }
3136                         b = i + 1;
3137                 }
3138         }
3139
3140         /*
3141          * setvalid is TRUE when we can safely set the zero'd areas
3142          * as being valid.  We can do this if there are no cache consistency
3143          * issues.  e.g. it is ok to do with UFS, but not ok to do with NFS.
3144          */
3145         if (setvalid)
3146                 m->valid = VM_PAGE_BITS_ALL;
3147 }
3148
3149 /*
3150  * Is a (partial) page valid?  Note that the case where size == 0
3151  * will return FALSE in the degenerate case where the page is entirely
3152  * invalid, and TRUE otherwise.
3153  *
3154  * Does not block.
3155  * No other requirements.
3156  */
3157 int
3158 vm_page_is_valid(vm_page_t m, int base, int size)
3159 {
3160         int bits = vm_page_bits(base, size);
3161
3162         if (m->valid && ((m->valid & bits) == bits))
3163                 return 1;
3164         else
3165                 return 0;
3166 }
3167
3168 /*
3169  * update dirty bits from pmap/mmu.  May not block.
3170  *
3171  * Caller must hold the page busy
3172  */
3173 void
3174 vm_page_test_dirty(vm_page_t m)
3175 {
3176         if ((m->dirty != VM_PAGE_BITS_ALL) && pmap_is_modified(m)) {
3177                 vm_page_dirty(m);
3178         }
3179 }
3180
3181 /*
3182  * Register an action, associating it with its vm_page
3183  */
3184 void
3185 vm_page_register_action(vm_page_action_t action, vm_page_event_t event)
3186 {
3187         struct vm_page_action_list *list;
3188         int hv;
3189
3190         hv = (int)((intptr_t)action->m >> 8) & VMACTION_HMASK;
3191         list = &action_list[hv];
3192
3193         lwkt_gettoken(&vm_token);
3194         vm_page_flag_set(action->m, PG_ACTIONLIST);
3195         action->event = event;
3196         LIST_INSERT_HEAD(list, action, entry);
3197         lwkt_reltoken(&vm_token);
3198 }
3199
3200 /*
3201  * Unregister an action, disassociating it from its related vm_page
3202  */
3203 void
3204 vm_page_unregister_action(vm_page_action_t action)
3205 {
3206         struct vm_page_action_list *list;
3207         int hv;
3208
3209         lwkt_gettoken(&vm_token);
3210         if (action->event != VMEVENT_NONE) {
3211                 action->event = VMEVENT_NONE;
3212                 LIST_REMOVE(action, entry);
3213
3214                 hv = (int)((intptr_t)action->m >> 8) & VMACTION_HMASK;
3215                 list = &action_list[hv];
3216                 if (LIST_EMPTY(list))
3217                         vm_page_flag_clear(action->m, PG_ACTIONLIST);
3218         }
3219         lwkt_reltoken(&vm_token);
3220 }
3221
3222 /*
3223  * Issue an event on a VM page.  Corresponding action structures are
3224  * removed from the page's list and called.
3225  *
3226  * If the vm_page has no more pending action events we clear its
3227  * PG_ACTIONLIST flag.
3228  */
3229 void
3230 vm_page_event_internal(vm_page_t m, vm_page_event_t event)
3231 {
3232         struct vm_page_action_list *list;
3233         struct vm_page_action *scan;
3234         struct vm_page_action *next;
3235         int hv;
3236         int all;
3237
3238         hv = (int)((intptr_t)m >> 8) & VMACTION_HMASK;
3239         list = &action_list[hv];
3240         all = 1;
3241
3242         lwkt_gettoken(&vm_token);
3243         LIST_FOREACH_MUTABLE(scan, list, entry, next) {
3244                 if (scan->m == m) {
3245                         if (scan->event == event) {
3246                                 scan->event = VMEVENT_NONE;
3247                                 LIST_REMOVE(scan, entry);
3248                                 scan->func(m, scan);
3249                                 /* XXX */
3250                         } else {
3251                                 all = 0;
3252                         }
3253                 }
3254         }
3255         if (all)
3256                 vm_page_flag_clear(m, PG_ACTIONLIST);
3257         lwkt_reltoken(&vm_token);
3258 }
3259
3260 #include "opt_ddb.h"
3261 #ifdef DDB
3262 #include <sys/kernel.h>
3263
3264 #include <ddb/ddb.h>
3265
3266 DB_SHOW_COMMAND(page, vm_page_print_page_info)
3267 {
3268         db_printf("vmstats.v_free_count: %d\n", vmstats.v_free_count);
3269         db_printf("vmstats.v_cache_count: %d\n", vmstats.v_cache_count);
3270         db_printf("vmstats.v_inactive_count: %d\n", vmstats.v_inactive_count);
3271         db_printf("vmstats.v_active_count: %d\n", vmstats.v_active_count);
3272         db_printf("vmstats.v_wire_count: %d\n", vmstats.v_wire_count);
3273         db_printf("vmstats.v_free_reserved: %d\n", vmstats.v_free_reserved);
3274         db_printf("vmstats.v_free_min: %d\n", vmstats.v_free_min);
3275         db_printf("vmstats.v_free_target: %d\n", vmstats.v_free_target);
3276         db_printf("vmstats.v_cache_min: %d\n", vmstats.v_cache_min);
3277         db_printf("vmstats.v_inactive_target: %d\n", vmstats.v_inactive_target);
3278 }
3279
3280 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
3281 {
3282         int i;
3283         db_printf("PQ_FREE:");
3284         for(i=0;i<PQ_L2_SIZE;i++) {
3285                 db_printf(" %d", vm_page_queues[PQ_FREE + i].lcnt);
3286         }
3287         db_printf("\n");
3288                 
3289         db_printf("PQ_CACHE:");
3290         for(i=0;i<PQ_L2_SIZE;i++) {
3291                 db_printf(" %d", vm_page_queues[PQ_CACHE + i].lcnt);
3292         }
3293         db_printf("\n");
3294
3295         db_printf("PQ_ACTIVE:");
3296         for(i=0;i<PQ_L2_SIZE;i++) {
3297                 db_printf(" %d", vm_page_queues[PQ_ACTIVE + i].lcnt);
3298         }
3299         db_printf("\n");
3300
3301         db_printf("PQ_INACTIVE:");
3302         for(i=0;i<PQ_L2_SIZE;i++) {
3303                 db_printf(" %d", vm_page_queues[PQ_INACTIVE + i].lcnt);
3304         }
3305         db_printf("\n");
3306 }
3307 #endif /* DDB */