kernel - Add support for up to 63 cpus & 512G of ram for 64-bit builds.
[dragonfly.git] / sys / vm / vm_page.c
1 /*
2  * (MPSAFE)
3  *
4  * Copyright (c) 1991 Regents of the University of California.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * The Mach Operating System project at Carnegie-Mellon University.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *      from: @(#)vm_page.c     7.4 (Berkeley) 5/7/91
39  * $FreeBSD: src/sys/vm/vm_page.c,v 1.147.2.18 2002/03/10 05:03:19 alc Exp $
40  * $DragonFly: src/sys/vm/vm_page.c,v 1.40 2008/08/25 17:01:42 dillon Exp $
41  */
42
43 /*
44  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
45  * All rights reserved.
46  *
47  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
48  *
49  * Permission to use, copy, modify and distribute this software and
50  * its documentation is hereby granted, provided that both the copyright
51  * notice and this permission notice appear in all copies of the
52  * software, derivative works or modified versions, and any portions
53  * thereof, and that both notices appear in supporting documentation.
54  *
55  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
56  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
57  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
58  *
59  * Carnegie Mellon requests users of this software to return to
60  *
61  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
62  *  School of Computer Science
63  *  Carnegie Mellon University
64  *  Pittsburgh PA 15213-3890
65  *
66  * any improvements or extensions that they make and grant Carnegie the
67  * rights to redistribute these changes.
68  */
69 /*
70  * Resident memory management module.  The module manipulates 'VM pages'.
71  * A VM page is the core building block for memory management.
72  */
73
74 #include <sys/param.h>
75 #include <sys/systm.h>
76 #include <sys/malloc.h>
77 #include <sys/proc.h>
78 #include <sys/vmmeter.h>
79 #include <sys/vnode.h>
80 #include <sys/kernel.h>
81
82 #include <vm/vm.h>
83 #include <vm/vm_param.h>
84 #include <sys/lock.h>
85 #include <vm/vm_kern.h>
86 #include <vm/pmap.h>
87 #include <vm/vm_map.h>
88 #include <vm/vm_object.h>
89 #include <vm/vm_page.h>
90 #include <vm/vm_pageout.h>
91 #include <vm/vm_pager.h>
92 #include <vm/vm_extern.h>
93 #include <vm/swap_pager.h>
94
95 #include <machine/md_var.h>
96
97 #include <vm/vm_page2.h>
98 #include <sys/mplock2.h>
99
100 #define VMACTION_HSIZE  256
101 #define VMACTION_HMASK  (VMACTION_HSIZE - 1)
102
103 static void vm_page_queue_init(void);
104 static void vm_page_free_wakeup(void);
105 static vm_page_t vm_page_select_cache(vm_object_t, vm_pindex_t);
106 static vm_page_t _vm_page_list_find2(int basequeue, int index);
107
108 struct vpgqueues vm_page_queues[PQ_COUNT]; /* Array of tailq lists */
109
110 LIST_HEAD(vm_page_action_list, vm_page_action);
111 struct vm_page_action_list      action_list[VMACTION_HSIZE];
112 static volatile int vm_pages_waiting;
113
114
115 RB_GENERATE2(vm_page_rb_tree, vm_page, rb_entry, rb_vm_page_compare,
116              vm_pindex_t, pindex);
117
118 static void
119 vm_page_queue_init(void) 
120 {
121         int i;
122
123         for (i = 0; i < PQ_L2_SIZE; i++)
124                 vm_page_queues[PQ_FREE+i].cnt = &vmstats.v_free_count;
125         for (i = 0; i < PQ_L2_SIZE; i++)
126                 vm_page_queues[PQ_CACHE+i].cnt = &vmstats.v_cache_count;
127
128         vm_page_queues[PQ_INACTIVE].cnt = &vmstats.v_inactive_count;
129         vm_page_queues[PQ_ACTIVE].cnt = &vmstats.v_active_count;
130         vm_page_queues[PQ_HOLD].cnt = &vmstats.v_active_count;
131         /* PQ_NONE has no queue */
132
133         for (i = 0; i < PQ_COUNT; i++)
134                 TAILQ_INIT(&vm_page_queues[i].pl);
135
136         for (i = 0; i < VMACTION_HSIZE; i++)
137                 LIST_INIT(&action_list[i]);
138 }
139
140 /*
141  * note: place in initialized data section?  Is this necessary?
142  */
143 long first_page = 0;
144 int vm_page_array_size = 0;
145 int vm_page_zero_count = 0;
146 vm_page_t vm_page_array = 0;
147
148 /*
149  * (low level boot)
150  *
151  * Sets the page size, perhaps based upon the memory size.
152  * Must be called before any use of page-size dependent functions.
153  */
154 void
155 vm_set_page_size(void)
156 {
157         if (vmstats.v_page_size == 0)
158                 vmstats.v_page_size = PAGE_SIZE;
159         if (((vmstats.v_page_size - 1) & vmstats.v_page_size) != 0)
160                 panic("vm_set_page_size: page size not a power of two");
161 }
162
163 /*
164  * (low level boot)
165  *
166  * Add a new page to the freelist for use by the system.  New pages
167  * are added to both the head and tail of the associated free page
168  * queue in a bottom-up fashion, so both zero'd and non-zero'd page
169  * requests pull 'recent' adds (higher physical addresses) first.
170  *
171  * Must be called in a critical section.
172  */
173 vm_page_t
174 vm_add_new_page(vm_paddr_t pa)
175 {
176         struct vpgqueues *vpq;
177         vm_page_t m;
178
179         ++vmstats.v_page_count;
180         ++vmstats.v_free_count;
181         m = PHYS_TO_VM_PAGE(pa);
182         m->phys_addr = pa;
183         m->flags = 0;
184         m->pc = (pa >> PAGE_SHIFT) & PQ_L2_MASK;
185         m->queue = m->pc + PQ_FREE;
186         KKASSERT(m->dirty == 0);
187
188         vpq = &vm_page_queues[m->queue];
189         if (vpq->flipflop)
190                 TAILQ_INSERT_TAIL(&vpq->pl, m, pageq);
191         else
192                 TAILQ_INSERT_HEAD(&vpq->pl, m, pageq);
193         vpq->flipflop = 1 - vpq->flipflop;
194
195         vm_page_queues[m->queue].lcnt++;
196         return (m);
197 }
198
199 /*
200  * (low level boot)
201  *
202  * Initializes the resident memory module.
203  *
204  * Preallocates memory for critical VM structures and arrays prior to
205  * kernel_map becoming available.
206  *
207  * Memory is allocated from (virtual2_start, virtual2_end) if available,
208  * otherwise memory is allocated from (virtual_start, virtual_end).
209  *
210  * On x86-64 (virtual_start, virtual_end) is only 2GB and may not be
211  * large enough to hold vm_page_array & other structures for machines with
212  * large amounts of ram, so we want to use virtual2* when available.
213  */
214 void
215 vm_page_startup(void)
216 {
217         vm_offset_t vaddr = virtual2_start ? virtual2_start : virtual_start;
218         vm_offset_t mapped;
219         vm_size_t npages;
220         vm_paddr_t page_range;
221         vm_paddr_t new_end;
222         int i;
223         vm_paddr_t pa;
224         int nblocks;
225         vm_paddr_t last_pa;
226         vm_paddr_t end;
227         vm_paddr_t biggestone, biggestsize;
228         vm_paddr_t total;
229
230         total = 0;
231         biggestsize = 0;
232         biggestone = 0;
233         nblocks = 0;
234         vaddr = round_page(vaddr);
235
236         for (i = 0; phys_avail[i + 1]; i += 2) {
237                 phys_avail[i] = round_page64(phys_avail[i]);
238                 phys_avail[i + 1] = trunc_page64(phys_avail[i + 1]);
239         }
240
241         for (i = 0; phys_avail[i + 1]; i += 2) {
242                 vm_paddr_t size = phys_avail[i + 1] - phys_avail[i];
243
244                 if (size > biggestsize) {
245                         biggestone = i;
246                         biggestsize = size;
247                 }
248                 ++nblocks;
249                 total += size;
250         }
251
252         end = phys_avail[biggestone+1];
253         end = trunc_page(end);
254
255         /*
256          * Initialize the queue headers for the free queue, the active queue
257          * and the inactive queue.
258          */
259
260         vm_page_queue_init();
261
262         /* VKERNELs don't support minidumps and as such don't need vm_page_dump */
263 #if !defined(_KERNEL_VIRTUAL)
264         /*
265          * Allocate a bitmap to indicate that a random physical page
266          * needs to be included in a minidump.
267          *
268          * The amd64 port needs this to indicate which direct map pages
269          * need to be dumped, via calls to dump_add_page()/dump_drop_page().
270          *
271          * However, i386 still needs this workspace internally within the
272          * minidump code.  In theory, they are not needed on i386, but are
273          * included should the sf_buf code decide to use them.
274          */
275         page_range = phys_avail[(nblocks - 1) * 2 + 1] / PAGE_SIZE;
276         vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
277         end -= vm_page_dump_size;
278         vm_page_dump = (void *)pmap_map(&vaddr, end, end + vm_page_dump_size,
279             VM_PROT_READ | VM_PROT_WRITE);
280         bzero((void *)vm_page_dump, vm_page_dump_size);
281 #endif
282
283         /*
284          * Compute the number of pages of memory that will be available for
285          * use (taking into account the overhead of a page structure per
286          * page).
287          */
288         first_page = phys_avail[0] / PAGE_SIZE;
289         page_range = phys_avail[(nblocks - 1) * 2 + 1] / PAGE_SIZE - first_page;
290         npages = (total - (page_range * sizeof(struct vm_page))) / PAGE_SIZE;
291
292         /*
293          * Initialize the mem entry structures now, and put them in the free
294          * queue.
295          */
296         new_end = trunc_page(end - page_range * sizeof(struct vm_page));
297         mapped = pmap_map(&vaddr, new_end, end,
298             VM_PROT_READ | VM_PROT_WRITE);
299         vm_page_array = (vm_page_t)mapped;
300
301 #if defined(__x86_64__) && !defined(_KERNEL_VIRTUAL)
302         /*
303          * since pmap_map on amd64 returns stuff out of a direct-map region,
304          * we have to manually add these pages to the minidump tracking so
305          * that they can be dumped, including the vm_page_array.
306          */
307         for (pa = new_end; pa < phys_avail[biggestone + 1]; pa += PAGE_SIZE)
308                 dump_add_page(pa);
309 #endif
310
311         /*
312          * Clear all of the page structures
313          */
314         bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
315         vm_page_array_size = page_range;
316
317         /*
318          * Construct the free queue(s) in ascending order (by physical
319          * address) so that the first 16MB of physical memory is allocated
320          * last rather than first.  On large-memory machines, this avoids
321          * the exhaustion of low physical memory before isa_dmainit has run.
322          */
323         vmstats.v_page_count = 0;
324         vmstats.v_free_count = 0;
325         for (i = 0; phys_avail[i + 1] && npages > 0; i += 2) {
326                 pa = phys_avail[i];
327                 if (i == biggestone)
328                         last_pa = new_end;
329                 else
330                         last_pa = phys_avail[i + 1];
331                 while (pa < last_pa && npages-- > 0) {
332                         vm_add_new_page(pa);
333                         pa += PAGE_SIZE;
334                 }
335         }
336         if (virtual2_start)
337                 virtual2_start = vaddr;
338         else
339                 virtual_start = vaddr;
340 }
341
342 /*
343  * Scan comparison function for Red-Black tree scans.  An inclusive
344  * (start,end) is expected.  Other fields are not used.
345  */
346 int
347 rb_vm_page_scancmp(struct vm_page *p, void *data)
348 {
349         struct rb_vm_page_scan_info *info = data;
350
351         if (p->pindex < info->start_pindex)
352                 return(-1);
353         if (p->pindex > info->end_pindex)
354                 return(1);
355         return(0);
356 }
357
358 int
359 rb_vm_page_compare(struct vm_page *p1, struct vm_page *p2)
360 {
361         if (p1->pindex < p2->pindex)
362                 return(-1);
363         if (p1->pindex > p2->pindex)
364                 return(1);
365         return(0);
366 }
367
368 /*
369  * Holding a page keeps it from being reused.  Other parts of the system
370  * can still disassociate the page from its current object and free it, or
371  * perform read or write I/O on it and/or otherwise manipulate the page,
372  * but if the page is held the VM system will leave the page and its data
373  * intact and not reuse the page for other purposes until the last hold
374  * reference is released.  (see vm_page_wire() if you want to prevent the
375  * page from being disassociated from its object too).
376  *
377  * The caller must hold vm_token.
378  *
379  * The caller must still validate the contents of the page and, if necessary,
380  * wait for any pending I/O (e.g. vm_page_sleep_busy() loop) to complete
381  * before manipulating the page.
382  */
383 void
384 vm_page_hold(vm_page_t m)
385 {
386         ASSERT_LWKT_TOKEN_HELD(&vm_token);
387         ++m->hold_count;
388 }
389
390 /*
391  * The opposite of vm_page_hold().  A page can be freed while being held,
392  * which places it on the PQ_HOLD queue.  We must call vm_page_free_toq()
393  * in this case to actually free it once the hold count drops to 0.
394  *
395  * The caller must hold vm_token if non-blocking operation is desired,
396  * but otherwise does not need to.
397  */
398 void
399 vm_page_unhold(vm_page_t m)
400 {
401         lwkt_gettoken(&vm_token);
402         --m->hold_count;
403         KASSERT(m->hold_count >= 0, ("vm_page_unhold: hold count < 0!!!"));
404         if (m->hold_count == 0 && m->queue == PQ_HOLD) {
405                 vm_page_busy(m);
406                 vm_page_free_toq(m);
407         }
408         lwkt_reltoken(&vm_token);
409 }
410
411 /*
412  * Inserts the given vm_page into the object and object list.
413  *
414  * The pagetables are not updated but will presumably fault the page
415  * in if necessary, or if a kernel page the caller will at some point
416  * enter the page into the kernel's pmap.  We are not allowed to block
417  * here so we *can't* do this anyway.
418  *
419  * This routine may not block.
420  * This routine must be called with the vm_token held.
421  * This routine must be called with a critical section held.
422  */
423 void
424 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
425 {
426         ASSERT_LWKT_TOKEN_HELD(&vm_token);
427         if (m->object != NULL)
428                 panic("vm_page_insert: already inserted");
429
430         /*
431          * Record the object/offset pair in this page
432          */
433         m->object = object;
434         m->pindex = pindex;
435
436         /*
437          * Insert it into the object.
438          */
439         vm_page_rb_tree_RB_INSERT(&object->rb_memq, m);
440         object->generation++;
441
442         /*
443          * show that the object has one more resident page.
444          */
445         object->resident_page_count++;
446
447         /*
448          * Add the pv_list_cout of the page when its inserted in
449          * the object
450         */
451         object->agg_pv_list_count = object->agg_pv_list_count + m->md.pv_list_count;
452
453         /*
454          * Since we are inserting a new and possibly dirty page,
455          * update the object's OBJ_WRITEABLE and OBJ_MIGHTBEDIRTY flags.
456          */
457         if ((m->valid & m->dirty) || (m->flags & PG_WRITEABLE))
458                 vm_object_set_writeable_dirty(object);
459
460         /*
461          * Checks for a swap assignment and sets PG_SWAPPED if appropriate.
462          */
463         swap_pager_page_inserted(m);
464 }
465
466 /*
467  * Removes the given vm_page_t from the global (object,index) hash table
468  * and from the object's memq.
469  *
470  * The underlying pmap entry (if any) is NOT removed here.
471  * This routine may not block.
472  *
473  * The page must be BUSY and will remain BUSY on return.
474  * No other requirements.
475  *
476  * NOTE: FreeBSD side effect was to unbusy the page on return.  We leave
477  *       it busy.
478  */
479 void
480 vm_page_remove(vm_page_t m)
481 {
482         vm_object_t object;
483
484         lwkt_gettoken(&vm_token);
485         if (m->object == NULL) {
486                 lwkt_reltoken(&vm_token);
487                 return;
488         }
489
490         if ((m->flags & PG_BUSY) == 0)
491                 panic("vm_page_remove: page not busy");
492
493         object = m->object;
494
495         /*
496          * Remove the page from the object and update the object.
497          */
498         vm_page_rb_tree_RB_REMOVE(&object->rb_memq, m);
499         object->resident_page_count--;
500         object->agg_pv_list_count = object->agg_pv_list_count - m->md.pv_list_count;
501         object->generation++;
502         m->object = NULL;
503
504         lwkt_reltoken(&vm_token);
505 }
506
507 /*
508  * Locate and return the page at (object, pindex), or NULL if the
509  * page could not be found.
510  *
511  * The caller must hold vm_token.
512  */
513 vm_page_t
514 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
515 {
516         vm_page_t m;
517
518         /*
519          * Search the hash table for this object/offset pair
520          */
521         ASSERT_LWKT_TOKEN_HELD(&vm_token);
522         m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq, pindex);
523         KKASSERT(m == NULL || (m->object == object && m->pindex == pindex));
524         return(m);
525 }
526
527 /*
528  * vm_page_rename()
529  *
530  * Move the given memory entry from its current object to the specified
531  * target object/offset.
532  *
533  * The object must be locked.
534  * This routine may not block.
535  *
536  * Note: This routine will raise itself to splvm(), the caller need not. 
537  *
538  * Note: Swap associated with the page must be invalidated by the move.  We
539  *       have to do this for several reasons:  (1) we aren't freeing the
540  *       page, (2) we are dirtying the page, (3) the VM system is probably
541  *       moving the page from object A to B, and will then later move
542  *       the backing store from A to B and we can't have a conflict.
543  *
544  * Note: We *always* dirty the page.  It is necessary both for the
545  *       fact that we moved it, and because we may be invalidating
546  *       swap.  If the page is on the cache, we have to deactivate it
547  *       or vm_page_dirty() will panic.  Dirty pages are not allowed
548  *       on the cache.
549  */
550 void
551 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
552 {
553         lwkt_gettoken(&vm_token);
554         vm_page_remove(m);
555         vm_page_insert(m, new_object, new_pindex);
556         if (m->queue - m->pc == PQ_CACHE)
557                 vm_page_deactivate(m);
558         vm_page_dirty(m);
559         vm_page_wakeup(m);
560         lwkt_reltoken(&vm_token);
561 }
562
563 /*
564  * vm_page_unqueue() without any wakeup.  This routine is used when a page
565  * is being moved between queues or otherwise is to remain BUSYied by the
566  * caller.
567  *
568  * The caller must hold vm_token
569  * This routine may not block.
570  */
571 void
572 vm_page_unqueue_nowakeup(vm_page_t m)
573 {
574         int queue = m->queue;
575         struct vpgqueues *pq;
576
577         ASSERT_LWKT_TOKEN_HELD(&vm_token);
578         if (queue != PQ_NONE) {
579                 pq = &vm_page_queues[queue];
580                 m->queue = PQ_NONE;
581                 TAILQ_REMOVE(&pq->pl, m, pageq);
582                 (*pq->cnt)--;
583                 pq->lcnt--;
584         }
585 }
586
587 /*
588  * vm_page_unqueue() - Remove a page from its queue, wakeup the pagedemon
589  * if necessary.
590  *
591  * The caller must hold vm_token
592  * This routine may not block.
593  */
594 void
595 vm_page_unqueue(vm_page_t m)
596 {
597         int queue = m->queue;
598         struct vpgqueues *pq;
599
600         ASSERT_LWKT_TOKEN_HELD(&vm_token);
601         if (queue != PQ_NONE) {
602                 m->queue = PQ_NONE;
603                 pq = &vm_page_queues[queue];
604                 TAILQ_REMOVE(&pq->pl, m, pageq);
605                 (*pq->cnt)--;
606                 pq->lcnt--;
607                 if ((queue - m->pc) == PQ_CACHE || (queue - m->pc) == PQ_FREE)
608                         pagedaemon_wakeup();
609         }
610 }
611
612 /*
613  * vm_page_list_find()
614  *
615  * Find a page on the specified queue with color optimization.
616  *
617  * The page coloring optimization attempts to locate a page that does
618  * not overload other nearby pages in the object in the cpu's L1 or L2
619  * caches.  We need this optimization because cpu caches tend to be
620  * physical caches, while object spaces tend to be virtual.
621  *
622  * Must be called with vm_token held.
623  * This routine may not block.
624  *
625  * Note that this routine is carefully inlined.  A non-inlined version
626  * is available for outside callers but the only critical path is
627  * from within this source file.
628  */
629 static __inline
630 vm_page_t
631 _vm_page_list_find(int basequeue, int index, boolean_t prefer_zero)
632 {
633         vm_page_t m;
634
635         if (prefer_zero)
636                 m = TAILQ_LAST(&vm_page_queues[basequeue+index].pl, pglist);
637         else
638                 m = TAILQ_FIRST(&vm_page_queues[basequeue+index].pl);
639         if (m == NULL)
640                 m = _vm_page_list_find2(basequeue, index);
641         return(m);
642 }
643
644 static vm_page_t
645 _vm_page_list_find2(int basequeue, int index)
646 {
647         int i;
648         vm_page_t m = NULL;
649         struct vpgqueues *pq;
650
651         pq = &vm_page_queues[basequeue];
652
653         /*
654          * Note that for the first loop, index+i and index-i wind up at the
655          * same place.  Even though this is not totally optimal, we've already
656          * blown it by missing the cache case so we do not care.
657          */
658
659         for(i = PQ_L2_SIZE / 2; i > 0; --i) {
660                 if ((m = TAILQ_FIRST(&pq[(index + i) & PQ_L2_MASK].pl)) != NULL)
661                         break;
662
663                 if ((m = TAILQ_FIRST(&pq[(index - i) & PQ_L2_MASK].pl)) != NULL)
664                         break;
665         }
666         return(m);
667 }
668
669 /*
670  * Must be called with vm_token held if the caller desired non-blocking
671  * operation and a stable result.
672  */
673 vm_page_t
674 vm_page_list_find(int basequeue, int index, boolean_t prefer_zero)
675 {
676         return(_vm_page_list_find(basequeue, index, prefer_zero));
677 }
678
679 /*
680  * Find a page on the cache queue with color optimization.  As pages
681  * might be found, but not applicable, they are deactivated.  This
682  * keeps us from using potentially busy cached pages.
683  *
684  * This routine may not block.
685  * Must be called with vm_token held.
686  */
687 vm_page_t
688 vm_page_select_cache(vm_object_t object, vm_pindex_t pindex)
689 {
690         vm_page_t m;
691
692         ASSERT_LWKT_TOKEN_HELD(&vm_token);
693         while (TRUE) {
694                 m = _vm_page_list_find(
695                     PQ_CACHE,
696                     (pindex + object->pg_color) & PQ_L2_MASK,
697                     FALSE
698                 );
699                 if (m && ((m->flags & (PG_BUSY|PG_UNMANAGED)) || m->busy ||
700                                m->hold_count || m->wire_count)) {
701                         vm_page_deactivate(m);
702                         continue;
703                 }
704                 return m;
705         }
706         /* not reached */
707 }
708
709 /*
710  * Find a free or zero page, with specified preference.  We attempt to
711  * inline the nominal case and fall back to _vm_page_select_free() 
712  * otherwise.
713  *
714  * This routine must be called with a critical section held.
715  * This routine may not block.
716  */
717 static __inline vm_page_t
718 vm_page_select_free(vm_object_t object, vm_pindex_t pindex, boolean_t prefer_zero)
719 {
720         vm_page_t m;
721
722         m = _vm_page_list_find(
723                 PQ_FREE,
724                 (pindex + object->pg_color) & PQ_L2_MASK,
725                 prefer_zero
726         );
727         return(m);
728 }
729
730 /*
731  * vm_page_alloc()
732  *
733  * Allocate and return a memory cell associated with this VM object/offset
734  * pair.
735  *
736  *      page_req classes:
737  *
738  *      VM_ALLOC_NORMAL         allow use of cache pages, nominal free drain
739  *      VM_ALLOC_QUICK          like normal but cannot use cache
740  *      VM_ALLOC_SYSTEM         greater free drain
741  *      VM_ALLOC_INTERRUPT      allow free list to be completely drained
742  *      VM_ALLOC_ZERO           advisory request for pre-zero'd page
743  *
744  * The object must be locked.
745  * This routine may not block.
746  * The returned page will be marked PG_BUSY
747  *
748  * Additional special handling is required when called from an interrupt
749  * (VM_ALLOC_INTERRUPT).  We are not allowed to mess with the page cache
750  * in this case.
751  */
752 vm_page_t
753 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int page_req)
754 {
755         vm_page_t m = NULL;
756
757         lwkt_gettoken(&vm_token);
758         
759         KKASSERT(object != NULL);
760         KASSERT(!vm_page_lookup(object, pindex),
761                 ("vm_page_alloc: page already allocated"));
762         KKASSERT(page_req & 
763                 (VM_ALLOC_NORMAL|VM_ALLOC_QUICK|
764                  VM_ALLOC_INTERRUPT|VM_ALLOC_SYSTEM));
765
766         /*
767          * Certain system threads (pageout daemon, buf_daemon's) are
768          * allowed to eat deeper into the free page list.
769          */
770         if (curthread->td_flags & TDF_SYSTHREAD)
771                 page_req |= VM_ALLOC_SYSTEM;
772
773 loop:
774         if (vmstats.v_free_count > vmstats.v_free_reserved ||
775             ((page_req & VM_ALLOC_INTERRUPT) && vmstats.v_free_count > 0) ||
776             ((page_req & VM_ALLOC_SYSTEM) && vmstats.v_cache_count == 0 &&
777                 vmstats.v_free_count > vmstats.v_interrupt_free_min)
778         ) {
779                 /*
780                  * The free queue has sufficient free pages to take one out.
781                  */
782                 if (page_req & VM_ALLOC_ZERO)
783                         m = vm_page_select_free(object, pindex, TRUE);
784                 else
785                         m = vm_page_select_free(object, pindex, FALSE);
786         } else if (page_req & VM_ALLOC_NORMAL) {
787                 /*
788                  * Allocatable from the cache (non-interrupt only).  On
789                  * success, we must free the page and try again, thus
790                  * ensuring that vmstats.v_*_free_min counters are replenished.
791                  */
792 #ifdef INVARIANTS
793                 if (curthread->td_preempted) {
794                         kprintf("vm_page_alloc(): warning, attempt to allocate"
795                                 " cache page from preempting interrupt\n");
796                         m = NULL;
797                 } else {
798                         m = vm_page_select_cache(object, pindex);
799                 }
800 #else
801                 m = vm_page_select_cache(object, pindex);
802 #endif
803                 /*
804                  * On success move the page into the free queue and loop.
805                  */
806                 if (m != NULL) {
807                         KASSERT(m->dirty == 0,
808                             ("Found dirty cache page %p", m));
809                         vm_page_busy(m);
810                         vm_page_protect(m, VM_PROT_NONE);
811                         vm_page_free(m);
812                         goto loop;
813                 }
814
815                 /*
816                  * On failure return NULL
817                  */
818                 lwkt_reltoken(&vm_token);
819 #if defined(DIAGNOSTIC)
820                 if (vmstats.v_cache_count > 0)
821                         kprintf("vm_page_alloc(NORMAL): missing pages on cache queue: %d\n", vmstats.v_cache_count);
822 #endif
823                 vm_pageout_deficit++;
824                 pagedaemon_wakeup();
825                 return (NULL);
826         } else {
827                 /*
828                  * No pages available, wakeup the pageout daemon and give up.
829                  */
830                 lwkt_reltoken(&vm_token);
831                 vm_pageout_deficit++;
832                 pagedaemon_wakeup();
833                 return (NULL);
834         }
835
836         /*
837          * Good page found.  The page has not yet been busied.  We are in
838          * a critical section.
839          */
840         KASSERT(m != NULL, ("vm_page_alloc(): missing page on free queue\n"));
841         KASSERT(m->dirty == 0, 
842                 ("vm_page_alloc: free/cache page %p was dirty", m));
843
844         /*
845          * Remove from free queue
846          */
847         vm_page_unqueue_nowakeup(m);
848
849         /*
850          * Initialize structure.  Only the PG_ZERO flag is inherited.  Set
851          * the page PG_BUSY
852          */
853         if (m->flags & PG_ZERO) {
854                 vm_page_zero_count--;
855                 m->flags = PG_ZERO | PG_BUSY;
856         } else {
857                 m->flags = PG_BUSY;
858         }
859         m->wire_count = 0;
860         m->hold_count = 0;
861         m->act_count = 0;
862         m->busy = 0;
863         m->valid = 0;
864
865         /*
866          * vm_page_insert() is safe while holding vm_token.  Note also that
867          * inserting a page here does not insert it into the pmap (which
868          * could cause us to block allocating memory).  We cannot block 
869          * anywhere.
870          */
871         vm_page_insert(m, object, pindex);
872
873         /*
874          * Don't wakeup too often - wakeup the pageout daemon when
875          * we would be nearly out of memory.
876          */
877         pagedaemon_wakeup();
878
879         lwkt_reltoken(&vm_token);
880
881         /*
882          * A PG_BUSY page is returned.
883          */
884         return (m);
885 }
886
887 /*
888  * Wait for sufficient free memory for nominal heavy memory use kernel
889  * operations.
890  */
891 void
892 vm_wait_nominal(void)
893 {
894         while (vm_page_count_min(0))
895                 vm_wait(0);
896 }
897
898 /*
899  * Test if vm_wait_nominal() would block.
900  */
901 int
902 vm_test_nominal(void)
903 {
904         if (vm_page_count_min(0))
905                 return(1);
906         return(0);
907 }
908
909 /*
910  * Block until free pages are available for allocation, called in various
911  * places before memory allocations.
912  *
913  * The caller may loop if vm_page_count_min() == FALSE so we cannot be
914  * more generous then that.
915  */
916 void
917 vm_wait(int timo)
918 {
919         /*
920          * never wait forever
921          */
922         if (timo == 0)
923                 timo = hz;
924         lwkt_gettoken(&vm_token);
925
926         if (curthread == pagethread) {
927                 /*
928                  * The pageout daemon itself needs pages, this is bad.
929                  */
930                 if (vm_page_count_min(0)) {
931                         vm_pageout_pages_needed = 1;
932                         tsleep(&vm_pageout_pages_needed, 0, "VMWait", timo);
933                 }
934         } else {
935                 /*
936                  * Wakeup the pageout daemon if necessary and wait.
937                  */
938                 if (vm_page_count_target()) {
939                         if (vm_pages_needed == 0) {
940                                 vm_pages_needed = 1;
941                                 wakeup(&vm_pages_needed);
942                         }
943                         ++vm_pages_waiting;     /* SMP race ok */
944                         tsleep(&vmstats.v_free_count, 0, "vmwait", timo);
945                 }
946         }
947         lwkt_reltoken(&vm_token);
948 }
949
950 /*
951  * Block until free pages are available for allocation
952  *
953  * Called only from vm_fault so that processes page faulting can be
954  * easily tracked.
955  */
956 void
957 vm_waitpfault(void)
958 {
959         /*
960          * Wakeup the pageout daemon if necessary and wait.
961          */
962         if (vm_page_count_target()) {
963                 lwkt_gettoken(&vm_token);
964                 if (vm_page_count_target()) {
965                         if (vm_pages_needed == 0) {
966                                 vm_pages_needed = 1;
967                                 wakeup(&vm_pages_needed);
968                         }
969                         ++vm_pages_waiting;     /* SMP race ok */
970                         tsleep(&vmstats.v_free_count, 0, "pfault", hz);
971                 }
972                 lwkt_reltoken(&vm_token);
973         }
974 }
975
976 /*
977  * Put the specified page on the active list (if appropriate).  Ensure
978  * that act_count is at least ACT_INIT but do not otherwise mess with it.
979  *
980  * The page queues must be locked.
981  * This routine may not block.
982  */
983 void
984 vm_page_activate(vm_page_t m)
985 {
986         lwkt_gettoken(&vm_token);
987         if (m->queue != PQ_ACTIVE) {
988                 if ((m->queue - m->pc) == PQ_CACHE)
989                         mycpu->gd_cnt.v_reactivated++;
990
991                 vm_page_unqueue(m);
992
993                 if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
994                         m->queue = PQ_ACTIVE;
995                         vm_page_queues[PQ_ACTIVE].lcnt++;
996                         TAILQ_INSERT_TAIL(&vm_page_queues[PQ_ACTIVE].pl,
997                                             m, pageq);
998                         if (m->act_count < ACT_INIT)
999                                 m->act_count = ACT_INIT;
1000                         vmstats.v_active_count++;
1001                 }
1002         } else {
1003                 if (m->act_count < ACT_INIT)
1004                         m->act_count = ACT_INIT;
1005         }
1006         lwkt_reltoken(&vm_token);
1007 }
1008
1009 /*
1010  * Helper routine for vm_page_free_toq() and vm_page_cache().  This
1011  * routine is called when a page has been added to the cache or free
1012  * queues.
1013  *
1014  * This routine may not block.
1015  * This routine must be called at splvm()
1016  */
1017 static __inline void
1018 vm_page_free_wakeup(void)
1019 {
1020         /*
1021          * If the pageout daemon itself needs pages, then tell it that
1022          * there are some free.
1023          */
1024         if (vm_pageout_pages_needed &&
1025             vmstats.v_cache_count + vmstats.v_free_count >= 
1026             vmstats.v_pageout_free_min
1027         ) {
1028                 wakeup(&vm_pageout_pages_needed);
1029                 vm_pageout_pages_needed = 0;
1030         }
1031
1032         /*
1033          * Wakeup processes that are waiting on memory.
1034          *
1035          * NOTE: vm_paging_target() is the pageout daemon's target, while
1036          *       vm_page_count_target() is somewhere inbetween.  We want
1037          *       to wake processes up prior to the pageout daemon reaching
1038          *       its target to provide some hysteresis.
1039          */
1040         if (vm_pages_waiting) {
1041                 if (!vm_page_count_target()) {
1042                         /*
1043                          * Plenty of pages are free, wakeup everyone.
1044                          */
1045                         vm_pages_waiting = 0;
1046                         wakeup(&vmstats.v_free_count);
1047                         ++mycpu->gd_cnt.v_ppwakeups;
1048                 } else if (!vm_page_count_min(0)) {
1049                         /*
1050                          * Some pages are free, wakeup someone.
1051                          */
1052                         int wcount = vm_pages_waiting;
1053                         if (wcount > 0)
1054                                 --wcount;
1055                         vm_pages_waiting = wcount;
1056                         wakeup_one(&vmstats.v_free_count);
1057                         ++mycpu->gd_cnt.v_ppwakeups;
1058                 }
1059         }
1060 }
1061
1062 /*
1063  *      vm_page_free_toq:
1064  *
1065  *      Returns the given page to the PQ_FREE list, disassociating it with
1066  *      any VM object.
1067  *
1068  *      The vm_page must be PG_BUSY on entry.  PG_BUSY will be released on
1069  *      return (the page will have been freed).  No particular spl is required
1070  *      on entry.
1071  *
1072  *      This routine may not block.
1073  */
1074 void
1075 vm_page_free_toq(vm_page_t m)
1076 {
1077         struct vpgqueues *pq;
1078
1079         lwkt_gettoken(&vm_token);
1080         mycpu->gd_cnt.v_tfree++;
1081
1082         KKASSERT((m->flags & PG_MAPPED) == 0);
1083
1084         if (m->busy || ((m->queue - m->pc) == PQ_FREE)) {
1085                 kprintf(
1086                 "vm_page_free: pindex(%lu), busy(%d), PG_BUSY(%d), hold(%d)\n",
1087                     (u_long)m->pindex, m->busy, (m->flags & PG_BUSY) ? 1 : 0,
1088                     m->hold_count);
1089                 if ((m->queue - m->pc) == PQ_FREE)
1090                         panic("vm_page_free: freeing free page");
1091                 else
1092                         panic("vm_page_free: freeing busy page");
1093         }
1094
1095         /*
1096          * unqueue, then remove page.  Note that we cannot destroy
1097          * the page here because we do not want to call the pager's
1098          * callback routine until after we've put the page on the
1099          * appropriate free queue.
1100          */
1101         vm_page_unqueue_nowakeup(m);
1102         vm_page_remove(m);
1103
1104         /*
1105          * No further management of fictitious pages occurs beyond object
1106          * and queue removal.
1107          */
1108         if ((m->flags & PG_FICTITIOUS) != 0) {
1109                 vm_page_wakeup(m);
1110                 lwkt_reltoken(&vm_token);
1111                 return;
1112         }
1113
1114         m->valid = 0;
1115         vm_page_undirty(m);
1116
1117         if (m->wire_count != 0) {
1118                 if (m->wire_count > 1) {
1119                     panic(
1120                         "vm_page_free: invalid wire count (%d), pindex: 0x%lx",
1121                         m->wire_count, (long)m->pindex);
1122                 }
1123                 panic("vm_page_free: freeing wired page");
1124         }
1125
1126         /*
1127          * Clear the UNMANAGED flag when freeing an unmanaged page.
1128          */
1129         if (m->flags & PG_UNMANAGED) {
1130             m->flags &= ~PG_UNMANAGED;
1131         }
1132
1133         if (m->hold_count != 0) {
1134                 m->flags &= ~PG_ZERO;
1135                 m->queue = PQ_HOLD;
1136         } else {
1137                 m->queue = PQ_FREE + m->pc;
1138         }
1139         pq = &vm_page_queues[m->queue];
1140         pq->lcnt++;
1141         ++(*pq->cnt);
1142
1143         /*
1144          * Put zero'd pages on the end ( where we look for zero'd pages
1145          * first ) and non-zerod pages at the head.
1146          */
1147         if (m->flags & PG_ZERO) {
1148                 TAILQ_INSERT_TAIL(&pq->pl, m, pageq);
1149                 ++vm_page_zero_count;
1150         } else {
1151                 TAILQ_INSERT_HEAD(&pq->pl, m, pageq);
1152         }
1153         vm_page_wakeup(m);
1154         vm_page_free_wakeup();
1155         lwkt_reltoken(&vm_token);
1156 }
1157
1158 /*
1159  * vm_page_free_fromq_fast()
1160  *
1161  * Remove a non-zero page from one of the free queues; the page is removed for
1162  * zeroing, so do not issue a wakeup.
1163  *
1164  * MPUNSAFE
1165  */
1166 vm_page_t
1167 vm_page_free_fromq_fast(void)
1168 {
1169         static int qi;
1170         vm_page_t m;
1171         int i;
1172
1173         lwkt_gettoken(&vm_token);
1174         for (i = 0; i < PQ_L2_SIZE; ++i) {
1175                 m = vm_page_list_find(PQ_FREE, qi, FALSE);
1176                 qi = (qi + PQ_PRIME2) & PQ_L2_MASK;
1177                 if (m && (m->flags & PG_ZERO) == 0) {
1178                         KKASSERT(m->busy == 0 && (m->flags & PG_BUSY) == 0);
1179                         vm_page_unqueue_nowakeup(m);
1180                         vm_page_busy(m);
1181                         break;
1182                 }
1183                 m = NULL;
1184         }
1185         lwkt_reltoken(&vm_token);
1186         return (m);
1187 }
1188
1189 /*
1190  * vm_page_unmanage()
1191  *
1192  * Prevent PV management from being done on the page.  The page is
1193  * removed from the paging queues as if it were wired, and as a 
1194  * consequence of no longer being managed the pageout daemon will not
1195  * touch it (since there is no way to locate the pte mappings for the
1196  * page).  madvise() calls that mess with the pmap will also no longer
1197  * operate on the page.
1198  *
1199  * Beyond that the page is still reasonably 'normal'.  Freeing the page
1200  * will clear the flag.
1201  *
1202  * This routine is used by OBJT_PHYS objects - objects using unswappable
1203  * physical memory as backing store rather then swap-backed memory and
1204  * will eventually be extended to support 4MB unmanaged physical 
1205  * mappings.
1206  *
1207  * Must be called with a critical section held.
1208  * Must be called with vm_token held.
1209  */
1210 void
1211 vm_page_unmanage(vm_page_t m)
1212 {
1213         ASSERT_LWKT_TOKEN_HELD(&vm_token);
1214         if ((m->flags & PG_UNMANAGED) == 0) {
1215                 if (m->wire_count == 0)
1216                         vm_page_unqueue(m);
1217         }
1218         vm_page_flag_set(m, PG_UNMANAGED);
1219 }
1220
1221 /*
1222  * Mark this page as wired down by yet another map, removing it from
1223  * paging queues as necessary.
1224  *
1225  * The page queues must be locked.
1226  * This routine may not block.
1227  */
1228 void
1229 vm_page_wire(vm_page_t m)
1230 {
1231         /*
1232          * Only bump the wire statistics if the page is not already wired,
1233          * and only unqueue the page if it is on some queue (if it is unmanaged
1234          * it is already off the queues).  Don't do anything with fictitious
1235          * pages because they are always wired.
1236          */
1237         lwkt_gettoken(&vm_token);
1238         if ((m->flags & PG_FICTITIOUS) == 0) {
1239                 if (m->wire_count == 0) {
1240                         if ((m->flags & PG_UNMANAGED) == 0)
1241                                 vm_page_unqueue(m);
1242                         vmstats.v_wire_count++;
1243                 }
1244                 m->wire_count++;
1245                 KASSERT(m->wire_count != 0,
1246                         ("vm_page_wire: wire_count overflow m=%p", m));
1247         }
1248         lwkt_reltoken(&vm_token);
1249 }
1250
1251 /*
1252  * Release one wiring of this page, potentially enabling it to be paged again.
1253  *
1254  * Many pages placed on the inactive queue should actually go
1255  * into the cache, but it is difficult to figure out which.  What
1256  * we do instead, if the inactive target is well met, is to put
1257  * clean pages at the head of the inactive queue instead of the tail.
1258  * This will cause them to be moved to the cache more quickly and
1259  * if not actively re-referenced, freed more quickly.  If we just
1260  * stick these pages at the end of the inactive queue, heavy filesystem
1261  * meta-data accesses can cause an unnecessary paging load on memory bound 
1262  * processes.  This optimization causes one-time-use metadata to be
1263  * reused more quickly.
1264  *
1265  * BUT, if we are in a low-memory situation we have no choice but to
1266  * put clean pages on the cache queue.
1267  *
1268  * A number of routines use vm_page_unwire() to guarantee that the page
1269  * will go into either the inactive or active queues, and will NEVER
1270  * be placed in the cache - for example, just after dirtying a page.
1271  * dirty pages in the cache are not allowed.
1272  *
1273  * The page queues must be locked.
1274  * This routine may not block.
1275  */
1276 void
1277 vm_page_unwire(vm_page_t m, int activate)
1278 {
1279         lwkt_gettoken(&vm_token);
1280         if (m->flags & PG_FICTITIOUS) {
1281                 /* do nothing */
1282         } else if (m->wire_count <= 0) {
1283                 panic("vm_page_unwire: invalid wire count: %d", m->wire_count);
1284         } else {
1285                 if (--m->wire_count == 0) {
1286                         --vmstats.v_wire_count;
1287                         if (m->flags & PG_UNMANAGED) {
1288                                 ;
1289                         } else if (activate) {
1290                                 TAILQ_INSERT_TAIL(
1291                                     &vm_page_queues[PQ_ACTIVE].pl, m, pageq);
1292                                 m->queue = PQ_ACTIVE;
1293                                 vm_page_queues[PQ_ACTIVE].lcnt++;
1294                                 vmstats.v_active_count++;
1295                         } else {
1296                                 vm_page_flag_clear(m, PG_WINATCFLS);
1297                                 TAILQ_INSERT_TAIL(
1298                                     &vm_page_queues[PQ_INACTIVE].pl, m, pageq);
1299                                 m->queue = PQ_INACTIVE;
1300                                 vm_page_queues[PQ_INACTIVE].lcnt++;
1301                                 vmstats.v_inactive_count++;
1302                                 ++vm_swapcache_inactive_heuristic;
1303                         }
1304                 }
1305         }
1306         lwkt_reltoken(&vm_token);
1307 }
1308
1309
1310 /*
1311  * Move the specified page to the inactive queue.  If the page has
1312  * any associated swap, the swap is deallocated.
1313  *
1314  * Normally athead is 0 resulting in LRU operation.  athead is set
1315  * to 1 if we want this page to be 'as if it were placed in the cache',
1316  * except without unmapping it from the process address space.
1317  *
1318  * This routine may not block.
1319  * The caller must hold vm_token.
1320  */
1321 static __inline void
1322 _vm_page_deactivate(vm_page_t m, int athead)
1323 {
1324         /*
1325          * Ignore if already inactive.
1326          */
1327         if (m->queue == PQ_INACTIVE)
1328                 return;
1329
1330         if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
1331                 if ((m->queue - m->pc) == PQ_CACHE)
1332                         mycpu->gd_cnt.v_reactivated++;
1333                 vm_page_flag_clear(m, PG_WINATCFLS);
1334                 vm_page_unqueue(m);
1335                 if (athead) {
1336                         TAILQ_INSERT_HEAD(&vm_page_queues[PQ_INACTIVE].pl,
1337                                           m, pageq);
1338                 } else {
1339                         TAILQ_INSERT_TAIL(&vm_page_queues[PQ_INACTIVE].pl,
1340                                           m, pageq);
1341                         ++vm_swapcache_inactive_heuristic;
1342                 }
1343                 m->queue = PQ_INACTIVE;
1344                 vm_page_queues[PQ_INACTIVE].lcnt++;
1345                 vmstats.v_inactive_count++;
1346         }
1347 }
1348
1349 /*
1350  * Attempt to deactivate a page.
1351  *
1352  * No requirements.
1353  */
1354 void
1355 vm_page_deactivate(vm_page_t m)
1356 {
1357         lwkt_gettoken(&vm_token);
1358         _vm_page_deactivate(m, 0);
1359         lwkt_reltoken(&vm_token);
1360 }
1361
1362 /*
1363  * Attempt to move a page to PQ_CACHE.
1364  * Returns 0 on failure, 1 on success
1365  *
1366  * No requirements.
1367  */
1368 int
1369 vm_page_try_to_cache(vm_page_t m)
1370 {
1371         lwkt_gettoken(&vm_token);
1372         if (m->dirty || m->hold_count || m->busy || m->wire_count ||
1373             (m->flags & (PG_BUSY|PG_UNMANAGED))) {
1374                 lwkt_reltoken(&vm_token);
1375                 return(0);
1376         }
1377         vm_page_test_dirty(m);
1378         if (m->dirty) {
1379                 lwkt_reltoken(&vm_token);
1380                 return(0);
1381         }
1382         vm_page_cache(m);
1383         lwkt_reltoken(&vm_token);
1384         return(1);
1385 }
1386
1387 /*
1388  * Attempt to free the page.  If we cannot free it, we do nothing.
1389  * 1 is returned on success, 0 on failure.
1390  *
1391  * No requirements.
1392  */
1393 int
1394 vm_page_try_to_free(vm_page_t m)
1395 {
1396         lwkt_gettoken(&vm_token);
1397         if (m->dirty || m->hold_count || m->busy || m->wire_count ||
1398             (m->flags & (PG_BUSY|PG_UNMANAGED))) {
1399                 lwkt_reltoken(&vm_token);
1400                 return(0);
1401         }
1402         vm_page_test_dirty(m);
1403         if (m->dirty) {
1404                 lwkt_reltoken(&vm_token);
1405                 return(0);
1406         }
1407         vm_page_busy(m);
1408         vm_page_protect(m, VM_PROT_NONE);
1409         vm_page_free(m);
1410         lwkt_reltoken(&vm_token);
1411         return(1);
1412 }
1413
1414 /*
1415  * vm_page_cache
1416  *
1417  * Put the specified page onto the page cache queue (if appropriate).
1418  *
1419  * The caller must hold vm_token.
1420  * This routine may not block.
1421  */
1422 void
1423 vm_page_cache(vm_page_t m)
1424 {
1425         ASSERT_LWKT_TOKEN_HELD(&vm_token);
1426
1427         if ((m->flags & (PG_BUSY|PG_UNMANAGED)) || m->busy ||
1428                         m->wire_count || m->hold_count) {
1429                 kprintf("vm_page_cache: attempting to cache busy/held page\n");
1430                 return;
1431         }
1432
1433         /*
1434          * Already in the cache (and thus not mapped)
1435          */
1436         if ((m->queue - m->pc) == PQ_CACHE) {
1437                 KKASSERT((m->flags & PG_MAPPED) == 0);
1438                 return;
1439         }
1440
1441         /*
1442          * Caller is required to test m->dirty, but note that the act of
1443          * removing the page from its maps can cause it to become dirty
1444          * on an SMP system due to another cpu running in usermode.
1445          */
1446         if (m->dirty) {
1447                 panic("vm_page_cache: caching a dirty page, pindex: %ld",
1448                         (long)m->pindex);
1449         }
1450
1451         /*
1452          * Remove all pmaps and indicate that the page is not
1453          * writeable or mapped.  Our vm_page_protect() call may
1454          * have blocked (especially w/ VM_PROT_NONE), so recheck
1455          * everything.
1456          */
1457         vm_page_busy(m);
1458         vm_page_protect(m, VM_PROT_NONE);
1459         vm_page_wakeup(m);
1460         if ((m->flags & (PG_BUSY|PG_UNMANAGED|PG_MAPPED)) || m->busy ||
1461                         m->wire_count || m->hold_count) {
1462                 /* do nothing */
1463         } else if (m->dirty) {
1464                 vm_page_deactivate(m);
1465         } else {
1466                 vm_page_unqueue_nowakeup(m);
1467                 m->queue = PQ_CACHE + m->pc;
1468                 vm_page_queues[m->queue].lcnt++;
1469                 TAILQ_INSERT_TAIL(&vm_page_queues[m->queue].pl, m, pageq);
1470                 vmstats.v_cache_count++;
1471                 vm_page_free_wakeup();
1472         }
1473 }
1474
1475 /*
1476  * vm_page_dontneed()
1477  *
1478  * Cache, deactivate, or do nothing as appropriate.  This routine
1479  * is typically used by madvise() MADV_DONTNEED.
1480  *
1481  * Generally speaking we want to move the page into the cache so
1482  * it gets reused quickly.  However, this can result in a silly syndrome
1483  * due to the page recycling too quickly.  Small objects will not be
1484  * fully cached.  On the otherhand, if we move the page to the inactive
1485  * queue we wind up with a problem whereby very large objects 
1486  * unnecessarily blow away our inactive and cache queues.
1487  *
1488  * The solution is to move the pages based on a fixed weighting.  We
1489  * either leave them alone, deactivate them, or move them to the cache,
1490  * where moving them to the cache has the highest weighting.
1491  * By forcing some pages into other queues we eventually force the
1492  * system to balance the queues, potentially recovering other unrelated
1493  * space from active.  The idea is to not force this to happen too
1494  * often.
1495  *
1496  * No requirements.
1497  */
1498 void
1499 vm_page_dontneed(vm_page_t m)
1500 {
1501         static int dnweight;
1502         int dnw;
1503         int head;
1504
1505         dnw = ++dnweight;
1506
1507         /*
1508          * occassionally leave the page alone
1509          */
1510         lwkt_gettoken(&vm_token);
1511         if ((dnw & 0x01F0) == 0 ||
1512             m->queue == PQ_INACTIVE || 
1513             m->queue - m->pc == PQ_CACHE
1514         ) {
1515                 if (m->act_count >= ACT_INIT)
1516                         --m->act_count;
1517                 lwkt_reltoken(&vm_token);
1518                 return;
1519         }
1520
1521         if (m->dirty == 0)
1522                 vm_page_test_dirty(m);
1523
1524         if (m->dirty || (dnw & 0x0070) == 0) {
1525                 /*
1526                  * Deactivate the page 3 times out of 32.
1527                  */
1528                 head = 0;
1529         } else {
1530                 /*
1531                  * Cache the page 28 times out of every 32.  Note that
1532                  * the page is deactivated instead of cached, but placed
1533                  * at the head of the queue instead of the tail.
1534                  */
1535                 head = 1;
1536         }
1537         _vm_page_deactivate(m, head);
1538         lwkt_reltoken(&vm_token);
1539 }
1540
1541 /*
1542  * Grab a page, blocking if it is busy and allocating a page if necessary.
1543  * A busy page is returned or NULL.
1544  *
1545  * If VM_ALLOC_RETRY is specified VM_ALLOC_NORMAL must also be specified.
1546  * If VM_ALLOC_RETRY is not specified
1547  *
1548  * This routine may block, but if VM_ALLOC_RETRY is not set then NULL is
1549  * always returned if we had blocked.  
1550  * This routine will never return NULL if VM_ALLOC_RETRY is set.
1551  * This routine may not be called from an interrupt.
1552  * The returned page may not be entirely valid.
1553  *
1554  * This routine may be called from mainline code without spl protection and
1555  * be guarenteed a busied page associated with the object at the specified
1556  * index.
1557  *
1558  * No requirements.
1559  */
1560 vm_page_t
1561 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
1562 {
1563         vm_page_t m;
1564         int generation;
1565
1566         KKASSERT(allocflags &
1567                 (VM_ALLOC_NORMAL|VM_ALLOC_INTERRUPT|VM_ALLOC_SYSTEM));
1568         lwkt_gettoken(&vm_token);
1569 retrylookup:
1570         if ((m = vm_page_lookup(object, pindex)) != NULL) {
1571                 if (m->busy || (m->flags & PG_BUSY)) {
1572                         generation = object->generation;
1573
1574                         while ((object->generation == generation) &&
1575                                         (m->busy || (m->flags & PG_BUSY))) {
1576                                 vm_page_flag_set(m, PG_WANTED | PG_REFERENCED);
1577                                 tsleep(m, 0, "pgrbwt", 0);
1578                                 if ((allocflags & VM_ALLOC_RETRY) == 0) {
1579                                         m = NULL;
1580                                         goto done;
1581                                 }
1582                         }
1583                         goto retrylookup;
1584                 } else {
1585                         vm_page_busy(m);
1586                         goto done;
1587                 }
1588         }
1589         m = vm_page_alloc(object, pindex, allocflags & ~VM_ALLOC_RETRY);
1590         if (m == NULL) {
1591                 vm_wait(0);
1592                 if ((allocflags & VM_ALLOC_RETRY) == 0)
1593                         goto done;
1594                 goto retrylookup;
1595         }
1596 done:
1597         lwkt_reltoken(&vm_token);
1598         return(m);
1599 }
1600
1601 /*
1602  * Mapping function for valid bits or for dirty bits in
1603  * a page.  May not block.
1604  *
1605  * Inputs are required to range within a page.
1606  *
1607  * No requirements.
1608  * Non blocking.
1609  */
1610 int
1611 vm_page_bits(int base, int size)
1612 {
1613         int first_bit;
1614         int last_bit;
1615
1616         KASSERT(
1617             base + size <= PAGE_SIZE,
1618             ("vm_page_bits: illegal base/size %d/%d", base, size)
1619         );
1620
1621         if (size == 0)          /* handle degenerate case */
1622                 return(0);
1623
1624         first_bit = base >> DEV_BSHIFT;
1625         last_bit = (base + size - 1) >> DEV_BSHIFT;
1626
1627         return ((2 << last_bit) - (1 << first_bit));
1628 }
1629
1630 /*
1631  * Sets portions of a page valid and clean.  The arguments are expected
1632  * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
1633  * of any partial chunks touched by the range.  The invalid portion of
1634  * such chunks will be zero'd.
1635  *
1636  * NOTE: When truncating a buffer vnode_pager_setsize() will automatically
1637  *       align base to DEV_BSIZE so as not to mark clean a partially
1638  *       truncated device block.  Otherwise the dirty page status might be
1639  *       lost.
1640  *
1641  * This routine may not block.
1642  *
1643  * (base + size) must be less then or equal to PAGE_SIZE.
1644  */
1645 static void
1646 _vm_page_zero_valid(vm_page_t m, int base, int size)
1647 {
1648         int frag;
1649         int endoff;
1650
1651         if (size == 0)  /* handle degenerate case */
1652                 return;
1653
1654         /*
1655          * If the base is not DEV_BSIZE aligned and the valid
1656          * bit is clear, we have to zero out a portion of the
1657          * first block.
1658          */
1659
1660         if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
1661             (m->valid & (1 << (base >> DEV_BSHIFT))) == 0
1662         ) {
1663                 pmap_zero_page_area(
1664                     VM_PAGE_TO_PHYS(m),
1665                     frag,
1666                     base - frag
1667                 );
1668         }
1669
1670         /*
1671          * If the ending offset is not DEV_BSIZE aligned and the 
1672          * valid bit is clear, we have to zero out a portion of
1673          * the last block.
1674          */
1675
1676         endoff = base + size;
1677
1678         if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
1679             (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0
1680         ) {
1681                 pmap_zero_page_area(
1682                     VM_PAGE_TO_PHYS(m),
1683                     endoff,
1684                     DEV_BSIZE - (endoff & (DEV_BSIZE - 1))
1685                 );
1686         }
1687 }
1688
1689 /*
1690  * Set valid, clear dirty bits.  If validating the entire
1691  * page we can safely clear the pmap modify bit.  We also
1692  * use this opportunity to clear the PG_NOSYNC flag.  If a process
1693  * takes a write fault on a MAP_NOSYNC memory area the flag will
1694  * be set again.
1695  *
1696  * We set valid bits inclusive of any overlap, but we can only
1697  * clear dirty bits for DEV_BSIZE chunks that are fully within
1698  * the range.
1699  *
1700  * Page must be busied?
1701  * No other requirements.
1702  */
1703 void
1704 vm_page_set_valid(vm_page_t m, int base, int size)
1705 {
1706         _vm_page_zero_valid(m, base, size);
1707         m->valid |= vm_page_bits(base, size);
1708 }
1709
1710
1711 /*
1712  * Set valid bits and clear dirty bits.
1713  *
1714  * NOTE: This function does not clear the pmap modified bit.
1715  *       Also note that e.g. NFS may use a byte-granular base
1716  *       and size.
1717  *
1718  * WARNING: Page must be busied?  But vfs_clean_one_page() will call
1719  *          this without necessarily busying the page (via bdwrite()).
1720  *          So for now vm_token must also be held.
1721  *
1722  * No other requirements.
1723  */
1724 void
1725 vm_page_set_validclean(vm_page_t m, int base, int size)
1726 {
1727         int pagebits;
1728
1729         _vm_page_zero_valid(m, base, size);
1730         pagebits = vm_page_bits(base, size);
1731         m->valid |= pagebits;
1732         m->dirty &= ~pagebits;
1733         if (base == 0 && size == PAGE_SIZE) {
1734                 /*pmap_clear_modify(m);*/
1735                 vm_page_flag_clear(m, PG_NOSYNC);
1736         }
1737 }
1738
1739 /*
1740  * Set valid & dirty.  Used by buwrite()
1741  *
1742  * WARNING: Page must be busied?  But vfs_dirty_one_page() will
1743  *          call this function in buwrite() so for now vm_token must
1744  *          be held.
1745  *
1746  * No other requirements.
1747  */
1748 void
1749 vm_page_set_validdirty(vm_page_t m, int base, int size)
1750 {
1751         int pagebits;
1752
1753         pagebits = vm_page_bits(base, size);
1754         m->valid |= pagebits;
1755         m->dirty |= pagebits;
1756         if (m->object)
1757                 vm_object_set_writeable_dirty(m->object);
1758 }
1759
1760 /*
1761  * Clear dirty bits.
1762  *
1763  * NOTE: This function does not clear the pmap modified bit.
1764  *       Also note that e.g. NFS may use a byte-granular base
1765  *       and size.
1766  *
1767  * Page must be busied?
1768  * No other requirements.
1769  */
1770 void
1771 vm_page_clear_dirty(vm_page_t m, int base, int size)
1772 {
1773         m->dirty &= ~vm_page_bits(base, size);
1774         if (base == 0 && size == PAGE_SIZE) {
1775                 /*pmap_clear_modify(m);*/
1776                 vm_page_flag_clear(m, PG_NOSYNC);
1777         }
1778 }
1779
1780 /*
1781  * Make the page all-dirty.
1782  *
1783  * Also make sure the related object and vnode reflect the fact that the
1784  * object may now contain a dirty page.
1785  *
1786  * Page must be busied?
1787  * No other requirements.
1788  */
1789 void
1790 vm_page_dirty(vm_page_t m)
1791 {
1792 #ifdef INVARIANTS
1793         int pqtype = m->queue - m->pc;
1794 #endif
1795         KASSERT(pqtype != PQ_CACHE && pqtype != PQ_FREE,
1796                 ("vm_page_dirty: page in free/cache queue!"));
1797         if (m->dirty != VM_PAGE_BITS_ALL) {
1798                 m->dirty = VM_PAGE_BITS_ALL;
1799                 if (m->object)
1800                         vm_object_set_writeable_dirty(m->object);
1801         }
1802 }
1803
1804 /*
1805  * Invalidates DEV_BSIZE'd chunks within a page.  Both the
1806  * valid and dirty bits for the effected areas are cleared.
1807  *
1808  * Page must be busied?
1809  * Does not block.
1810  * No other requirements.
1811  */
1812 void
1813 vm_page_set_invalid(vm_page_t m, int base, int size)
1814 {
1815         int bits;
1816
1817         bits = vm_page_bits(base, size);
1818         m->valid &= ~bits;
1819         m->dirty &= ~bits;
1820         m->object->generation++;
1821 }
1822
1823 /*
1824  * The kernel assumes that the invalid portions of a page contain 
1825  * garbage, but such pages can be mapped into memory by user code.
1826  * When this occurs, we must zero out the non-valid portions of the
1827  * page so user code sees what it expects.
1828  *
1829  * Pages are most often semi-valid when the end of a file is mapped 
1830  * into memory and the file's size is not page aligned.
1831  *
1832  * Page must be busied?
1833  * No other requirements.
1834  */
1835 void
1836 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
1837 {
1838         int b;
1839         int i;
1840
1841         /*
1842          * Scan the valid bits looking for invalid sections that
1843          * must be zerod.  Invalid sub-DEV_BSIZE'd areas ( where the
1844          * valid bit may be set ) have already been zerod by
1845          * vm_page_set_validclean().
1846          */
1847         for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
1848                 if (i == (PAGE_SIZE / DEV_BSIZE) || 
1849                     (m->valid & (1 << i))
1850                 ) {
1851                         if (i > b) {
1852                                 pmap_zero_page_area(
1853                                     VM_PAGE_TO_PHYS(m), 
1854                                     b << DEV_BSHIFT,
1855                                     (i - b) << DEV_BSHIFT
1856                                 );
1857                         }
1858                         b = i + 1;
1859                 }
1860         }
1861
1862         /*
1863          * setvalid is TRUE when we can safely set the zero'd areas
1864          * as being valid.  We can do this if there are no cache consistency
1865          * issues.  e.g. it is ok to do with UFS, but not ok to do with NFS.
1866          */
1867         if (setvalid)
1868                 m->valid = VM_PAGE_BITS_ALL;
1869 }
1870
1871 /*
1872  * Is a (partial) page valid?  Note that the case where size == 0
1873  * will return FALSE in the degenerate case where the page is entirely
1874  * invalid, and TRUE otherwise.
1875  *
1876  * Does not block.
1877  * No other requirements.
1878  */
1879 int
1880 vm_page_is_valid(vm_page_t m, int base, int size)
1881 {
1882         int bits = vm_page_bits(base, size);
1883
1884         if (m->valid && ((m->valid & bits) == bits))
1885                 return 1;
1886         else
1887                 return 0;
1888 }
1889
1890 /*
1891  * update dirty bits from pmap/mmu.  May not block.
1892  *
1893  * Caller must hold vm_token if non-blocking operation desired.
1894  * No other requirements.
1895  */
1896 void
1897 vm_page_test_dirty(vm_page_t m)
1898 {
1899         if ((m->dirty != VM_PAGE_BITS_ALL) && pmap_is_modified(m)) {
1900                 vm_page_dirty(m);
1901         }
1902 }
1903
1904 /*
1905  * Register an action, associating it with its vm_page
1906  */
1907 void
1908 vm_page_register_action(vm_page_action_t action, vm_page_event_t event)
1909 {
1910         struct vm_page_action_list *list;
1911         int hv;
1912
1913         hv = (int)((intptr_t)action->m >> 8) & VMACTION_HMASK;
1914         list = &action_list[hv];
1915
1916         lwkt_gettoken(&vm_token);
1917         vm_page_flag_set(action->m, PG_ACTIONLIST);
1918         action->event = event;
1919         LIST_INSERT_HEAD(list, action, entry);
1920         lwkt_reltoken(&vm_token);
1921 }
1922
1923 /*
1924  * Unregister an action, disassociating it from its related vm_page
1925  */
1926 void
1927 vm_page_unregister_action(vm_page_action_t action)
1928 {
1929         struct vm_page_action_list *list;
1930         int hv;
1931
1932         lwkt_gettoken(&vm_token);
1933         if (action->event != VMEVENT_NONE) {
1934                 action->event = VMEVENT_NONE;
1935                 LIST_REMOVE(action, entry);
1936
1937                 hv = (int)((intptr_t)action->m >> 8) & VMACTION_HMASK;
1938                 list = &action_list[hv];
1939                 if (LIST_EMPTY(list))
1940                         vm_page_flag_clear(action->m, PG_ACTIONLIST);
1941         }
1942         lwkt_reltoken(&vm_token);
1943 }
1944
1945 /*
1946  * Issue an event on a VM page.  Corresponding action structures are
1947  * removed from the page's list and called.
1948  *
1949  * If the vm_page has no more pending action events we clear its
1950  * PG_ACTIONLIST flag.
1951  */
1952 void
1953 vm_page_event_internal(vm_page_t m, vm_page_event_t event)
1954 {
1955         struct vm_page_action_list *list;
1956         struct vm_page_action *scan;
1957         struct vm_page_action *next;
1958         int hv;
1959         int all;
1960
1961         hv = (int)((intptr_t)m >> 8) & VMACTION_HMASK;
1962         list = &action_list[hv];
1963         all = 1;
1964
1965         lwkt_gettoken(&vm_token);
1966         LIST_FOREACH_MUTABLE(scan, list, entry, next) {
1967                 if (scan->m == m) {
1968                         if (scan->event == event) {
1969                                 scan->event = VMEVENT_NONE;
1970                                 LIST_REMOVE(scan, entry);
1971                                 scan->func(m, scan);
1972                                 /* XXX */
1973                         } else {
1974                                 all = 0;
1975                         }
1976                 }
1977         }
1978         if (all)
1979                 vm_page_flag_clear(m, PG_ACTIONLIST);
1980         lwkt_reltoken(&vm_token);
1981 }
1982
1983
1984 #include "opt_ddb.h"
1985 #ifdef DDB
1986 #include <sys/kernel.h>
1987
1988 #include <ddb/ddb.h>
1989
1990 DB_SHOW_COMMAND(page, vm_page_print_page_info)
1991 {
1992         db_printf("vmstats.v_free_count: %d\n", vmstats.v_free_count);
1993         db_printf("vmstats.v_cache_count: %d\n", vmstats.v_cache_count);
1994         db_printf("vmstats.v_inactive_count: %d\n", vmstats.v_inactive_count);
1995         db_printf("vmstats.v_active_count: %d\n", vmstats.v_active_count);
1996         db_printf("vmstats.v_wire_count: %d\n", vmstats.v_wire_count);
1997         db_printf("vmstats.v_free_reserved: %d\n", vmstats.v_free_reserved);
1998         db_printf("vmstats.v_free_min: %d\n", vmstats.v_free_min);
1999         db_printf("vmstats.v_free_target: %d\n", vmstats.v_free_target);
2000         db_printf("vmstats.v_cache_min: %d\n", vmstats.v_cache_min);
2001         db_printf("vmstats.v_inactive_target: %d\n", vmstats.v_inactive_target);
2002 }
2003
2004 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
2005 {
2006         int i;
2007         db_printf("PQ_FREE:");
2008         for(i=0;i<PQ_L2_SIZE;i++) {
2009                 db_printf(" %d", vm_page_queues[PQ_FREE + i].lcnt);
2010         }
2011         db_printf("\n");
2012                 
2013         db_printf("PQ_CACHE:");
2014         for(i=0;i<PQ_L2_SIZE;i++) {
2015                 db_printf(" %d", vm_page_queues[PQ_CACHE + i].lcnt);
2016         }
2017         db_printf("\n");
2018
2019         db_printf("PQ_ACTIVE: %d, PQ_INACTIVE: %d\n",
2020                 vm_page_queues[PQ_ACTIVE].lcnt,
2021                 vm_page_queues[PQ_INACTIVE].lcnt);
2022 }
2023 #endif /* DDB */