]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/vm/vm_page.c
This commit was generated by cvs2svn to compensate for changes in r94735,
[FreeBSD/FreeBSD.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. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by the University of
19  *      California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *      from: @(#)vm_page.c     7.4 (Berkeley) 5/7/91
37  * $FreeBSD$
38  */
39
40 /*
41  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
42  * All rights reserved.
43  *
44  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
45  *
46  * Permission to use, copy, modify and distribute this software and
47  * its documentation is hereby granted, provided that both the copyright
48  * notice and this permission notice appear in all copies of the
49  * software, derivative works or modified versions, and any portions
50  * thereof, and that both notices appear in supporting documentation.
51  *
52  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
53  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
54  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
55  *
56  * Carnegie Mellon requests users of this software to return to
57  *
58  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
59  *  School of Computer Science
60  *  Carnegie Mellon University
61  *  Pittsburgh PA 15213-3890
62  *
63  * any improvements or extensions that they make and grant Carnegie the
64  * rights to redistribute these changes.
65  */
66
67 /*
68  *                      GENERAL RULES ON VM_PAGE MANIPULATION
69  *
70  *      - a pageq mutex is required when adding or removing a page from a
71  *        page queue (vm_page_queue[]), regardless of other mutexes or the
72  *        busy state of a page.
73  *
74  *      - a hash chain mutex is required when associating or disassociating
75  *        a page from the VM PAGE CACHE hash table (vm_page_buckets),
76  *        regardless of other mutexes or the busy state of a page.
77  *
78  *      - either a hash chain mutex OR a busied page is required in order
79  *        to modify the page flags.  A hash chain mutex must be obtained in
80  *        order to busy a page.  A page's flags cannot be modified by a
81  *        hash chain mutex if the page is marked busy.
82  *
83  *      - The object memq mutex is held when inserting or removing
84  *        pages from an object (vm_page_insert() or vm_page_remove()).  This
85  *        is different from the object's main mutex.
86  *
87  *      Generally speaking, you have to be aware of side effects when running
88  *      vm_page ops.  A vm_page_lookup() will return with the hash chain
89  *      locked, whether it was able to lookup the page or not.  vm_page_free(),
90  *      vm_page_cache(), vm_page_activate(), and a number of other routines
91  *      will release the hash chain mutex for you.  Intermediate manipulation
92  *      routines such as vm_page_flag_set() expect the hash chain to be held
93  *      on entry and the hash chain will remain held on return.
94  *
95  *      pageq scanning can only occur with the pageq in question locked.
96  *      We have a known bottleneck with the active queue, but the cache
97  *      and free queues are actually arrays already. 
98  */
99
100 /*
101  *      Resident memory management module.
102  */
103
104 #include <sys/param.h>
105 #include <sys/systm.h>
106 #include <sys/lock.h>
107 #include <sys/malloc.h>
108 #include <sys/mutex.h>
109 #include <sys/proc.h>
110 #include <sys/vmmeter.h>
111 #include <sys/vnode.h>
112
113 #include <vm/vm.h>
114 #include <vm/vm_param.h>
115 #include <vm/vm_kern.h>
116 #include <vm/vm_object.h>
117 #include <vm/vm_page.h>
118 #include <vm/vm_pageout.h>
119 #include <vm/vm_pager.h>
120 #include <vm/vm_extern.h>
121 #include <vm/uma.h>
122 #include <vm/uma_int.h>
123
124 /*
125  *      Associated with page of user-allocatable memory is a
126  *      page structure.
127  */
128 static struct vm_page **vm_page_buckets; /* Array of buckets */
129 static int vm_page_bucket_count;        /* How big is array? */
130 static int vm_page_hash_mask;           /* Mask for hash function */
131 static volatile int vm_page_bucket_generation;
132 static struct mtx vm_buckets_mtx[BUCKET_HASH_SIZE];
133
134 vm_page_t vm_page_array = 0;
135 int vm_page_array_size = 0;
136 long first_page = 0;
137 int vm_page_zero_count = 0;
138
139 /*
140  *      vm_set_page_size:
141  *
142  *      Sets the page size, perhaps based upon the memory
143  *      size.  Must be called before any use of page-size
144  *      dependent functions.
145  */
146 void
147 vm_set_page_size(void)
148 {
149         if (cnt.v_page_size == 0)
150                 cnt.v_page_size = PAGE_SIZE;
151         if (((cnt.v_page_size - 1) & cnt.v_page_size) != 0)
152                 panic("vm_set_page_size: page size not a power of two");
153 }
154
155 /*
156  *      vm_page_startup:
157  *
158  *      Initializes the resident memory module.
159  *
160  *      Allocates memory for the page cells, and
161  *      for the object/offset-to-page hash table headers.
162  *      Each page cell is initialized and placed on the free list.
163  */
164 vm_offset_t
165 vm_page_startup(vm_offset_t starta, vm_offset_t enda, vm_offset_t vaddr)
166 {
167         vm_offset_t mapped;
168         struct vm_page **bucket;
169         vm_size_t npages, page_range;
170         vm_offset_t new_end;
171         int i;
172         vm_offset_t pa;
173         int nblocks;
174         vm_offset_t last_pa;
175
176         /* the biggest memory array is the second group of pages */
177         vm_offset_t end;
178         vm_offset_t biggestone, biggestsize;
179
180         vm_offset_t total;
181         vm_size_t bootpages;
182
183         total = 0;
184         biggestsize = 0;
185         biggestone = 0;
186         nblocks = 0;
187         vaddr = round_page(vaddr);
188
189         for (i = 0; phys_avail[i + 1]; i += 2) {
190                 phys_avail[i] = round_page(phys_avail[i]);
191                 phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
192         }
193
194         for (i = 0; phys_avail[i + 1]; i += 2) {
195                 vm_size_t size = phys_avail[i + 1] - phys_avail[i];
196
197                 if (size > biggestsize) {
198                         biggestone = i;
199                         biggestsize = size;
200                 }
201                 ++nblocks;
202                 total += size;
203         }
204
205         end = phys_avail[biggestone+1];
206
207         /*
208          * Initialize the queue headers for the free queue, the active queue
209          * and the inactive queue.
210          */
211         vm_pageq_init();
212
213         /*
214          * Allocate memory for use when boot strapping the kernel memory allocator
215          */
216         bootpages = UMA_BOOT_PAGES * UMA_SLAB_SIZE;
217         new_end = end - bootpages;
218         new_end = trunc_page(new_end);
219         mapped = pmap_map(&vaddr, new_end, end,
220             VM_PROT_READ | VM_PROT_WRITE);
221         bzero((caddr_t) mapped, end - new_end);
222         uma_startup((caddr_t)mapped);
223
224         end = new_end;
225
226         /*
227          * Allocate (and initialize) the hash table buckets.
228          *
229          * The number of buckets MUST BE a power of 2, and the actual value is
230          * the next power of 2 greater than the number of physical pages in
231          * the system.  
232          *
233          * We make the hash table approximately 2x the number of pages to
234          * reduce the chain length.  This is about the same size using the 
235          * singly-linked list as the 1x hash table we were using before 
236          * using TAILQ but the chain length will be smaller.
237          *
238          * Note: This computation can be tweaked if desired.
239          */
240         if (vm_page_bucket_count == 0) {
241                 vm_page_bucket_count = 1;
242                 while (vm_page_bucket_count < atop(total))
243                         vm_page_bucket_count <<= 1;
244         }
245         vm_page_bucket_count <<= 1;
246         vm_page_hash_mask = vm_page_bucket_count - 1;
247
248         /*
249          * Validate these addresses.
250          */
251         new_end = end - vm_page_bucket_count * sizeof(struct vm_page *);
252         new_end = trunc_page(new_end);
253         mapped = pmap_map(&vaddr, new_end, end,
254             VM_PROT_READ | VM_PROT_WRITE);
255         bzero((caddr_t) mapped, end - new_end);
256
257         vm_page_buckets = (struct vm_page **)mapped;
258         bucket = vm_page_buckets;
259         for (i = 0; i < vm_page_bucket_count; i++) {
260                 *bucket = NULL;
261                 bucket++;
262         }
263         for (i = 0; i < BUCKET_HASH_SIZE; ++i)
264                 mtx_init(&vm_buckets_mtx[i],  "vm buckets hash mutexes", NULL,
265                     MTX_DEF);
266
267         /*
268          * Compute the number of pages of memory that will be available for
269          * use (taking into account the overhead of a page structure per
270          * page).
271          */
272         first_page = phys_avail[0] / PAGE_SIZE;
273         page_range = phys_avail[(nblocks - 1) * 2 + 1] / PAGE_SIZE - first_page;
274         npages = (total - (page_range * sizeof(struct vm_page)) -
275             (end - new_end)) / PAGE_SIZE;
276         end = new_end;
277
278         /*
279          * Initialize the mem entry structures now, and put them in the free
280          * queue.
281          */
282         new_end = trunc_page(end - page_range * sizeof(struct vm_page));
283         mapped = pmap_map(&vaddr, new_end, end,
284             VM_PROT_READ | VM_PROT_WRITE);
285         vm_page_array = (vm_page_t) mapped;
286
287         /*
288          * Clear all of the page structures
289          */
290         bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
291         vm_page_array_size = page_range;
292
293         /*
294          * Construct the free queue(s) in descending order (by physical
295          * address) so that the first 16MB of physical memory is allocated
296          * last rather than first.  On large-memory machines, this avoids
297          * the exhaustion of low physical memory before isa_dmainit has run.
298          */
299         cnt.v_page_count = 0;
300         cnt.v_free_count = 0;
301         for (i = 0; phys_avail[i + 1] && npages > 0; i += 2) {
302                 pa = phys_avail[i];
303                 if (i == biggestone)
304                         last_pa = new_end;
305                 else
306                         last_pa = phys_avail[i + 1];
307                 while (pa < last_pa && npages-- > 0) {
308                         vm_pageq_add_new_page(pa);
309                         pa += PAGE_SIZE;
310                 }
311         }
312         return (vaddr);
313 }
314
315 /*
316  *      vm_page_hash:
317  *
318  *      Distributes the object/offset key pair among hash buckets.
319  *
320  *      NOTE:  This macro depends on vm_page_bucket_count being a power of 2.
321  *      This routine may not block.
322  *
323  *      We try to randomize the hash based on the object to spread the pages
324  *      out in the hash table without it costing us too much.
325  */
326 static __inline int
327 vm_page_hash(vm_object_t object, vm_pindex_t pindex)
328 {
329         int i = ((uintptr_t)object + pindex) ^ object->hash_rand;
330
331         return (i & vm_page_hash_mask);
332 }
333
334 void
335 vm_page_flag_set(vm_page_t m, unsigned short bits)
336 {
337         GIANT_REQUIRED;
338         m->flags |= bits;
339
340
341 void
342 vm_page_flag_clear(vm_page_t m, unsigned short bits)
343 {
344         GIANT_REQUIRED;
345         m->flags &= ~bits;
346 }
347
348 void
349 vm_page_busy(vm_page_t m)
350 {
351         KASSERT((m->flags & PG_BUSY) == 0,
352             ("vm_page_busy: page already busy!!!"));
353         vm_page_flag_set(m, PG_BUSY);
354 }
355
356 /*
357  *      vm_page_flash:
358  *
359  *      wakeup anyone waiting for the page.
360  */
361 void
362 vm_page_flash(vm_page_t m)
363 {
364         if (m->flags & PG_WANTED) {
365                 vm_page_flag_clear(m, PG_WANTED);
366                 wakeup(m);
367         }
368 }
369
370 /*
371  *      vm_page_wakeup:
372  *
373  *      clear the PG_BUSY flag and wakeup anyone waiting for the
374  *      page.
375  *
376  */
377 void
378 vm_page_wakeup(vm_page_t m)
379 {
380         KASSERT(m->flags & PG_BUSY, ("vm_page_wakeup: page not busy!!!"));
381         vm_page_flag_clear(m, PG_BUSY);
382         vm_page_flash(m);
383 }
384
385 /*
386  *
387  *
388  */
389 void
390 vm_page_io_start(vm_page_t m)
391 {
392         GIANT_REQUIRED;
393         m->busy++;
394 }
395
396 void
397 vm_page_io_finish(vm_page_t m)
398 {
399         GIANT_REQUIRED;
400         m->busy--;
401         if (m->busy == 0)
402                 vm_page_flash(m);
403 }
404
405 /*
406  * Keep page from being freed by the page daemon
407  * much of the same effect as wiring, except much lower
408  * overhead and should be used only for *very* temporary
409  * holding ("wiring").
410  */
411 void
412 vm_page_hold(vm_page_t mem)
413 {
414         GIANT_REQUIRED;
415         mem->hold_count++;
416 }
417
418 void
419 vm_page_unhold(vm_page_t mem)
420 {
421         GIANT_REQUIRED;
422         --mem->hold_count;
423         KASSERT(mem->hold_count >= 0, ("vm_page_unhold: hold count < 0!!!"));
424         if (mem->hold_count == 0 && mem->queue == PQ_HOLD)
425                 vm_page_free_toq(mem);
426 }
427
428 /*
429  *      vm_page_protect:
430  *
431  *      Reduce the protection of a page.  This routine never raises the
432  *      protection and therefore can be safely called if the page is already
433  *      at VM_PROT_NONE (it will be a NOP effectively ).
434  */
435 void
436 vm_page_protect(vm_page_t mem, int prot)
437 {
438         if (prot == VM_PROT_NONE) {
439                 if (mem->flags & (PG_WRITEABLE|PG_MAPPED)) {
440                         pmap_page_protect(mem, VM_PROT_NONE);
441                         vm_page_flag_clear(mem, PG_WRITEABLE|PG_MAPPED);
442                 }
443         } else if ((prot == VM_PROT_READ) && (mem->flags & PG_WRITEABLE)) {
444                 pmap_page_protect(mem, VM_PROT_READ);
445                 vm_page_flag_clear(mem, PG_WRITEABLE);
446         }
447 }
448 /*
449  *      vm_page_zero_fill:
450  *
451  *      Zero-fill the specified page.
452  *      Written as a standard pagein routine, to
453  *      be used by the zero-fill object.
454  */
455 boolean_t
456 vm_page_zero_fill(vm_page_t m)
457 {
458         pmap_zero_page(VM_PAGE_TO_PHYS(m));
459         return (TRUE);
460 }
461
462 /*
463  *      vm_page_copy:
464  *
465  *      Copy one page to another
466  */
467 void
468 vm_page_copy(vm_page_t src_m, vm_page_t dest_m)
469 {
470         pmap_copy_page(VM_PAGE_TO_PHYS(src_m), VM_PAGE_TO_PHYS(dest_m));
471         dest_m->valid = VM_PAGE_BITS_ALL;
472 }
473
474 /*
475  *      vm_page_free:
476  *
477  *      Free a page
478  *
479  *      The clearing of PG_ZERO is a temporary safety until the code can be
480  *      reviewed to determine that PG_ZERO is being properly cleared on
481  *      write faults or maps.  PG_ZERO was previously cleared in
482  *      vm_page_alloc().
483  */
484 void
485 vm_page_free(vm_page_t m)
486 {
487         vm_page_flag_clear(m, PG_ZERO);
488         vm_page_free_toq(m);
489         vm_page_zero_idle_wakeup();
490 }
491
492 /*
493  *      vm_page_free_zero:
494  *
495  *      Free a page to the zerod-pages queue
496  */
497 void
498 vm_page_free_zero(vm_page_t m)
499 {
500         vm_page_flag_set(m, PG_ZERO);
501         vm_page_free_toq(m);
502 }
503
504 /*
505  *      vm_page_sleep_busy:
506  *
507  *      Wait until page is no longer PG_BUSY or (if also_m_busy is TRUE)
508  *      m->busy is zero.  Returns TRUE if it had to sleep ( including if
509  *      it almost had to sleep and made temporary spl*() mods), FALSE
510  *      otherwise.
511  *
512  *      This routine assumes that interrupts can only remove the busy
513  *      status from a page, not set the busy status or change it from
514  *      PG_BUSY to m->busy or vise versa (which would create a timing
515  *      window).
516  */
517 int
518 vm_page_sleep_busy(vm_page_t m, int also_m_busy, const char *msg)
519 {
520         GIANT_REQUIRED;
521         if ((m->flags & PG_BUSY) || (also_m_busy && m->busy))  {
522                 int s = splvm();
523                 if ((m->flags & PG_BUSY) || (also_m_busy && m->busy)) {
524                         /*
525                          * Page is busy. Wait and retry.
526                          */
527                         vm_page_flag_set(m, PG_WANTED | PG_REFERENCED);
528                         tsleep(m, PVM, msg, 0);
529                 }
530                 splx(s);
531                 return (TRUE);
532                 /* not reached */
533         }
534         return (FALSE);
535 }
536 /*
537  *      vm_page_dirty:
538  *
539  *      make page all dirty
540  */
541 void
542 vm_page_dirty(vm_page_t m)
543 {
544         KASSERT(m->queue - m->pc != PQ_CACHE,
545             ("vm_page_dirty: page in cache!"));
546         m->dirty = VM_PAGE_BITS_ALL;
547 }
548
549 /*
550  *      vm_page_undirty:
551  *
552  *      Set page to not be dirty.  Note: does not clear pmap modify bits
553  */
554 void
555 vm_page_undirty(vm_page_t m)
556 {
557         m->dirty = 0;
558 }
559
560 /*
561  *      vm_page_insert:         [ internal use only ]
562  *
563  *      Inserts the given mem entry into the object and object list.
564  *
565  *      The pagetables are not updated but will presumably fault the page
566  *      in if necessary, or if a kernel page the caller will at some point
567  *      enter the page into the kernel's pmap.  We are not allowed to block
568  *      here so we *can't* do this anyway.
569  *
570  *      The object and page must be locked, and must be splhigh.
571  *      This routine may not block.
572  */
573 void
574 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
575 {
576         struct vm_page **bucket;
577
578         GIANT_REQUIRED;
579
580         if (m->object != NULL)
581                 panic("vm_page_insert: already inserted");
582
583         /*
584          * Record the object/offset pair in this page
585          */
586         m->object = object;
587         m->pindex = pindex;
588
589         /*
590          * Insert it into the object_object/offset hash table
591          */
592         bucket = &vm_page_buckets[vm_page_hash(object, pindex)];
593         m->hnext = *bucket;
594         *bucket = m;
595         vm_page_bucket_generation++;
596
597         /*
598          * Now link into the object's list of backed pages.
599          */
600         TAILQ_INSERT_TAIL(&object->memq, m, listq);
601         object->generation++;
602
603         /*
604          * show that the object has one more resident page.
605          */
606         object->resident_page_count++;
607
608         /*
609          * Since we are inserting a new and possibly dirty page,
610          * update the object's OBJ_WRITEABLE and OBJ_MIGHTBEDIRTY flags.
611          */
612         if (m->flags & PG_WRITEABLE)
613                 vm_object_set_writeable_dirty(object);
614 }
615
616 /*
617  *      vm_page_remove:
618  *                              NOTE: used by device pager as well -wfj
619  *
620  *      Removes the given mem entry from the object/offset-page
621  *      table and the object page list, but do not invalidate/terminate
622  *      the backing store.
623  *
624  *      The object and page must be locked, and at splhigh.
625  *      The underlying pmap entry (if any) is NOT removed here.
626  *      This routine may not block.
627  */
628 void
629 vm_page_remove(vm_page_t m)
630 {
631         vm_object_t object;
632
633         GIANT_REQUIRED;
634
635         if (m->object == NULL)
636                 return;
637
638         if ((m->flags & PG_BUSY) == 0) {
639                 panic("vm_page_remove: page not busy");
640         }
641
642         /*
643          * Basically destroy the page.
644          */
645         vm_page_wakeup(m);
646
647         object = m->object;
648
649         /*
650          * Remove from the object_object/offset hash table.  The object
651          * must be on the hash queue, we will panic if it isn't
652          *
653          * Note: we must NULL-out m->hnext to prevent loops in detached
654          * buffers with vm_page_lookup().
655          */
656         {
657                 struct vm_page **bucket;
658
659                 bucket = &vm_page_buckets[vm_page_hash(m->object, m->pindex)];
660                 while (*bucket != m) {
661                         if (*bucket == NULL)
662                                 panic("vm_page_remove(): page not found in hash");
663                         bucket = &(*bucket)->hnext;
664                 }
665                 *bucket = m->hnext;
666                 m->hnext = NULL;
667                 vm_page_bucket_generation++;
668         }
669
670         /*
671          * Now remove from the object's list of backed pages.
672          */
673         TAILQ_REMOVE(&object->memq, m, listq);
674
675         /*
676          * And show that the object has one fewer resident page.
677          */
678         object->resident_page_count--;
679         object->generation++;
680
681         m->object = NULL;
682 }
683
684 /*
685  *      vm_page_lookup:
686  *
687  *      Returns the page associated with the object/offset
688  *      pair specified; if none is found, NULL is returned.
689  *
690  *      NOTE: the code below does not lock.  It will operate properly if
691  *      an interrupt makes a change, but the generation algorithm will not 
692  *      operate properly in an SMP environment where both cpu's are able to run
693  *      kernel code simultaneously.
694  *
695  *      The object must be locked.  No side effects.
696  *      This routine may not block.
697  *      This is a critical path routine
698  */
699 vm_page_t
700 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
701 {
702         vm_page_t m;
703         struct vm_page **bucket;
704         int generation;
705
706         /*
707          * Search the hash table for this object/offset pair
708          */
709 retry:
710         generation = vm_page_bucket_generation;
711         bucket = &vm_page_buckets[vm_page_hash(object, pindex)];
712         for (m = *bucket; m != NULL; m = m->hnext) {
713                 if ((m->object == object) && (m->pindex == pindex)) {
714                         if (vm_page_bucket_generation != generation)
715                                 goto retry;
716                         return (m);
717                 }
718         }
719         if (vm_page_bucket_generation != generation)
720                 goto retry;
721         return (NULL);
722 }
723
724 /*
725  *      vm_page_rename:
726  *
727  *      Move the given memory entry from its
728  *      current object to the specified target object/offset.
729  *
730  *      The object must be locked.
731  *      This routine may not block.
732  *
733  *      Note: this routine will raise itself to splvm(), the caller need not. 
734  *
735  *      Note: swap associated with the page must be invalidated by the move.  We
736  *            have to do this for several reasons:  (1) we aren't freeing the
737  *            page, (2) we are dirtying the page, (3) the VM system is probably
738  *            moving the page from object A to B, and will then later move
739  *            the backing store from A to B and we can't have a conflict.
740  *
741  *      Note: we *always* dirty the page.  It is necessary both for the
742  *            fact that we moved it, and because we may be invalidating
743  *            swap.  If the page is on the cache, we have to deactivate it
744  *            or vm_page_dirty() will panic.  Dirty pages are not allowed
745  *            on the cache.
746  */
747 void
748 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
749 {
750         int s;
751
752         s = splvm();
753         vm_page_remove(m);
754         vm_page_insert(m, new_object, new_pindex);
755         if (m->queue - m->pc == PQ_CACHE)
756                 vm_page_deactivate(m);
757         vm_page_dirty(m);
758         splx(s);
759 }
760
761 /*
762  *      vm_page_select_cache:
763  *
764  *      Find a page on the cache queue with color optimization.  As pages
765  *      might be found, but not applicable, they are deactivated.  This
766  *      keeps us from using potentially busy cached pages.
767  *
768  *      This routine must be called at splvm().
769  *      This routine may not block.
770  */
771 static vm_page_t
772 vm_page_select_cache(vm_object_t object, vm_pindex_t pindex)
773 {
774         vm_page_t m;
775
776         GIANT_REQUIRED;
777         while (TRUE) {
778                 m = vm_pageq_find(
779                     PQ_CACHE,
780                     (pindex + object->pg_color) & PQ_L2_MASK,
781                     FALSE
782                 );
783                 if (m && ((m->flags & (PG_BUSY|PG_UNMANAGED)) || m->busy ||
784                                m->hold_count || m->wire_count)) {
785                         vm_page_deactivate(m);
786                         continue;
787                 }
788                 return m;
789         }
790 }
791
792 /*
793  *      vm_page_select_free:
794  *
795  *      Find a free or zero page, with specified preference. 
796  *
797  *      This routine must be called at splvm().
798  *      This routine may not block.
799  */
800 static __inline vm_page_t
801 vm_page_select_free(vm_object_t object, vm_pindex_t pindex, boolean_t prefer_zero)
802 {
803         vm_page_t m;
804
805         m = vm_pageq_find(
806                 PQ_FREE,
807                 (pindex + object->pg_color) & PQ_L2_MASK,
808                 prefer_zero
809         );
810         return (m);
811 }
812
813 /*
814  *      vm_page_alloc:
815  *
816  *      Allocate and return a memory cell associated
817  *      with this VM object/offset pair.
818  *
819  *      page_req classes:
820  *      VM_ALLOC_NORMAL         normal process request
821  *      VM_ALLOC_SYSTEM         system *really* needs a page
822  *      VM_ALLOC_INTERRUPT      interrupt time request
823  *      VM_ALLOC_ZERO           zero page
824  *
825  *      This routine may not block.
826  *
827  *      Additional special handling is required when called from an
828  *      interrupt (VM_ALLOC_INTERRUPT).  We are not allowed to mess with
829  *      the page cache in this case.
830  */
831 vm_page_t
832 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int page_req)
833 {
834         vm_page_t m = NULL;
835         int s;
836
837         GIANT_REQUIRED;
838
839         KASSERT(!vm_page_lookup(object, pindex),
840                 ("vm_page_alloc: page already allocated"));
841
842         /*
843          * The pager is allowed to eat deeper into the free page list.
844          */
845         if ((curproc == pageproc) && (page_req != VM_ALLOC_INTERRUPT)) {
846                 page_req = VM_ALLOC_SYSTEM;
847         };
848
849         s = splvm();
850
851 loop:
852         if (cnt.v_free_count > cnt.v_free_reserved) {
853                 /*
854                  * Allocate from the free queue if there are plenty of pages
855                  * in it.
856                  */
857                 if (page_req == VM_ALLOC_ZERO)
858                         m = vm_page_select_free(object, pindex, TRUE);
859                 else
860                         m = vm_page_select_free(object, pindex, FALSE);
861         } else if (
862             (page_req == VM_ALLOC_SYSTEM && 
863              cnt.v_cache_count == 0 && 
864              cnt.v_free_count > cnt.v_interrupt_free_min) ||
865             (page_req == VM_ALLOC_INTERRUPT && cnt.v_free_count > 0)
866         ) {
867                 /*
868                  * Interrupt or system, dig deeper into the free list.
869                  */
870                 m = vm_page_select_free(object, pindex, FALSE);
871         } else if (page_req != VM_ALLOC_INTERRUPT) {
872                 /*
873                  * Allocatable from cache (non-interrupt only).  On success,
874                  * we must free the page and try again, thus ensuring that
875                  * cnt.v_*_free_min counters are replenished.
876                  */
877                 m = vm_page_select_cache(object, pindex);
878                 if (m == NULL) {
879                         splx(s);
880 #if defined(DIAGNOSTIC)
881                         if (cnt.v_cache_count > 0)
882                                 printf("vm_page_alloc(NORMAL): missing pages on cache queue: %d\n", cnt.v_cache_count);
883 #endif
884                         vm_pageout_deficit++;
885                         pagedaemon_wakeup();
886                         return (NULL);
887                 }
888                 KASSERT(m->dirty == 0, ("Found dirty cache page %p", m));
889                 vm_page_busy(m);
890                 vm_page_protect(m, VM_PROT_NONE);
891                 vm_page_free(m);
892                 goto loop;
893         } else {
894                 /*
895                  * Not allocatable from cache from interrupt, give up.
896                  */
897                 splx(s);
898                 vm_pageout_deficit++;
899                 pagedaemon_wakeup();
900                 return (NULL);
901         }
902
903         /*
904          *  At this point we had better have found a good page.
905          */
906
907         KASSERT(
908             m != NULL,
909             ("vm_page_alloc(): missing page on free queue\n")
910         );
911
912         /*
913          * Remove from free queue
914          */
915
916         vm_pageq_remove_nowakeup(m);
917
918         /*
919          * Initialize structure.  Only the PG_ZERO flag is inherited.
920          */
921         if (m->flags & PG_ZERO) {
922                 vm_page_zero_count--;
923                 m->flags = PG_ZERO | PG_BUSY;
924         } else {
925                 m->flags = PG_BUSY;
926         }
927         m->wire_count = 0;
928         m->hold_count = 0;
929         m->act_count = 0;
930         m->busy = 0;
931         m->valid = 0;
932         KASSERT(m->dirty == 0, ("vm_page_alloc: free/cache page %p was dirty", m));
933
934         /*
935          * vm_page_insert() is safe prior to the splx().  Note also that
936          * inserting a page here does not insert it into the pmap (which
937          * could cause us to block allocating memory).  We cannot block 
938          * anywhere.
939          */
940         vm_page_insert(m, object, pindex);
941
942         /*
943          * Don't wakeup too often - wakeup the pageout daemon when
944          * we would be nearly out of memory.
945          */
946         if (vm_paging_needed())
947                 pagedaemon_wakeup();
948
949         splx(s);
950         return (m);
951 }
952
953 /*
954  *      vm_wait:        (also see VM_WAIT macro)
955  *
956  *      Block until free pages are available for allocation
957  *      - Called in various places before memory allocations.
958  */
959 void
960 vm_wait(void)
961 {
962         int s;
963
964         s = splvm();
965         if (curproc == pageproc) {
966                 vm_pageout_pages_needed = 1;
967                 tsleep(&vm_pageout_pages_needed, PSWP, "VMWait", 0);
968         } else {
969                 if (!vm_pages_needed) {
970                         vm_pages_needed = 1;
971                         wakeup(&vm_pages_needed);
972                 }
973                 tsleep(&cnt.v_free_count, PVM, "vmwait", 0);
974         }
975         splx(s);
976 }
977
978 /*
979  *      vm_waitpfault:  (also see VM_WAITPFAULT macro)
980  *
981  *      Block until free pages are available for allocation
982  *      - Called only in vm_fault so that processes page faulting
983  *        can be easily tracked.
984  *      - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
985  *        processes will be able to grab memory first.  Do not change
986  *        this balance without careful testing first.
987  */
988 void
989 vm_waitpfault(void)
990 {
991         int s;
992
993         s = splvm();
994         if (!vm_pages_needed) {
995                 vm_pages_needed = 1;
996                 wakeup(&vm_pages_needed);
997         }
998         tsleep(&cnt.v_free_count, PUSER, "pfault", 0);
999         splx(s);
1000 }
1001
1002 /*
1003  *      vm_page_activate:
1004  *
1005  *      Put the specified page on the active list (if appropriate).
1006  *      Ensure that act_count is at least ACT_INIT but do not otherwise
1007  *      mess with it.
1008  *
1009  *      The page queues must be locked.
1010  *      This routine may not block.
1011  */
1012 void
1013 vm_page_activate(vm_page_t m)
1014 {
1015         int s;
1016
1017         GIANT_REQUIRED;
1018         s = splvm();
1019         if (m->queue != PQ_ACTIVE) {
1020                 if ((m->queue - m->pc) == PQ_CACHE)
1021                         cnt.v_reactivated++;
1022                 vm_pageq_remove(m);
1023                 if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
1024                         if (m->act_count < ACT_INIT)
1025                                 m->act_count = ACT_INIT;
1026                         vm_pageq_enqueue(PQ_ACTIVE, m);
1027                 }
1028         } else {
1029                 if (m->act_count < ACT_INIT)
1030                         m->act_count = ACT_INIT;
1031         }
1032         splx(s);
1033 }
1034
1035 /*
1036  *      vm_page_free_wakeup:
1037  *
1038  *      Helper routine for vm_page_free_toq() and vm_page_cache().  This
1039  *      routine is called when a page has been added to the cache or free
1040  *      queues.
1041  *
1042  *      This routine may not block.
1043  *      This routine must be called at splvm()
1044  */
1045 static __inline void
1046 vm_page_free_wakeup(void)
1047 {
1048         /*
1049          * if pageout daemon needs pages, then tell it that there are
1050          * some free.
1051          */
1052         if (vm_pageout_pages_needed &&
1053             cnt.v_cache_count + cnt.v_free_count >= cnt.v_pageout_free_min) {
1054                 wakeup(&vm_pageout_pages_needed);
1055                 vm_pageout_pages_needed = 0;
1056         }
1057         /*
1058          * wakeup processes that are waiting on memory if we hit a
1059          * high water mark. And wakeup scheduler process if we have
1060          * lots of memory. this process will swapin processes.
1061          */
1062         if (vm_pages_needed && !vm_page_count_min()) {
1063                 vm_pages_needed = 0;
1064                 wakeup(&cnt.v_free_count);
1065         }
1066 }
1067
1068 /*
1069  *      vm_page_free_toq:
1070  *
1071  *      Returns the given page to the PQ_FREE list,
1072  *      disassociating it with any VM object.
1073  *
1074  *      Object and page must be locked prior to entry.
1075  *      This routine may not block.
1076  */
1077
1078 void
1079 vm_page_free_toq(vm_page_t m)
1080 {
1081         int s;
1082         struct vpgqueues *pq;
1083         vm_object_t object = m->object;
1084
1085         GIANT_REQUIRED;
1086         s = splvm();
1087         cnt.v_tfree++;
1088
1089         if (m->busy || ((m->queue - m->pc) == PQ_FREE)) {
1090                 printf(
1091                 "vm_page_free: pindex(%lu), busy(%d), PG_BUSY(%d), hold(%d)\n",
1092                     (u_long)m->pindex, m->busy, (m->flags & PG_BUSY) ? 1 : 0,
1093                     m->hold_count);
1094                 if ((m->queue - m->pc) == PQ_FREE)
1095                         panic("vm_page_free: freeing free page");
1096                 else
1097                         panic("vm_page_free: freeing busy page");
1098         }
1099
1100         /*
1101          * unqueue, then remove page.  Note that we cannot destroy
1102          * the page here because we do not want to call the pager's
1103          * callback routine until after we've put the page on the
1104          * appropriate free queue.
1105          */
1106         vm_pageq_remove_nowakeup(m);
1107         vm_page_remove(m);
1108
1109         /*
1110          * If fictitious remove object association and
1111          * return, otherwise delay object association removal.
1112          */
1113         if ((m->flags & PG_FICTITIOUS) != 0) {
1114                 splx(s);
1115                 return;
1116         }
1117
1118         m->valid = 0;
1119         vm_page_undirty(m);
1120
1121         if (m->wire_count != 0) {
1122                 if (m->wire_count > 1) {
1123                         panic("vm_page_free: invalid wire count (%d), pindex: 0x%lx",
1124                                 m->wire_count, (long)m->pindex);
1125                 }
1126                 panic("vm_page_free: freeing wired page\n");
1127         }
1128
1129         /*
1130          * If we've exhausted the object's resident pages we want to free
1131          * it up.
1132          */
1133         if (object && 
1134             (object->type == OBJT_VNODE) &&
1135             ((object->flags & OBJ_DEAD) == 0)
1136         ) {
1137                 struct vnode *vp = (struct vnode *)object->handle;
1138
1139                 if (vp && VSHOULDFREE(vp))
1140                         vfree(vp);
1141         }
1142
1143         /*
1144          * Clear the UNMANAGED flag when freeing an unmanaged page.
1145          */
1146         if (m->flags & PG_UNMANAGED) {
1147                 m->flags &= ~PG_UNMANAGED;
1148         } else {
1149 #ifdef __alpha__
1150                 pmap_page_is_free(m);
1151 #endif
1152         }
1153
1154         if (m->hold_count != 0) {
1155                 m->flags &= ~PG_ZERO;
1156                 m->queue = PQ_HOLD;
1157         } else
1158                 m->queue = PQ_FREE + m->pc;
1159         pq = &vm_page_queues[m->queue];
1160         pq->lcnt++;
1161         ++(*pq->cnt);
1162
1163         /*
1164          * Put zero'd pages on the end ( where we look for zero'd pages
1165          * first ) and non-zerod pages at the head.
1166          */
1167         if (m->flags & PG_ZERO) {
1168                 TAILQ_INSERT_TAIL(&pq->pl, m, pageq);
1169                 ++vm_page_zero_count;
1170         } else {
1171                 TAILQ_INSERT_HEAD(&pq->pl, m, pageq);
1172         }
1173         vm_page_free_wakeup();
1174         splx(s);
1175 }
1176
1177 /*
1178  *      vm_page_unmanage:
1179  *
1180  *      Prevent PV management from being done on the page.  The page is
1181  *      removed from the paging queues as if it were wired, and as a 
1182  *      consequence of no longer being managed the pageout daemon will not
1183  *      touch it (since there is no way to locate the pte mappings for the
1184  *      page).  madvise() calls that mess with the pmap will also no longer
1185  *      operate on the page.
1186  *
1187  *      Beyond that the page is still reasonably 'normal'.  Freeing the page
1188  *      will clear the flag.
1189  *
1190  *      This routine is used by OBJT_PHYS objects - objects using unswappable
1191  *      physical memory as backing store rather then swap-backed memory and
1192  *      will eventually be extended to support 4MB unmanaged physical 
1193  *      mappings.
1194  */
1195 void
1196 vm_page_unmanage(vm_page_t m)
1197 {
1198         int s;
1199
1200         s = splvm();
1201         if ((m->flags & PG_UNMANAGED) == 0) {
1202                 if (m->wire_count == 0)
1203                         vm_pageq_remove(m);
1204         }
1205         vm_page_flag_set(m, PG_UNMANAGED);
1206         splx(s);
1207 }
1208
1209 /*
1210  *      vm_page_wire:
1211  *
1212  *      Mark this page as wired down by yet
1213  *      another map, removing it from paging queues
1214  *      as necessary.
1215  *
1216  *      The page queues must be locked.
1217  *      This routine may not block.
1218  */
1219 void
1220 vm_page_wire(vm_page_t m)
1221 {
1222         int s;
1223
1224         /*
1225          * Only bump the wire statistics if the page is not already wired,
1226          * and only unqueue the page if it is on some queue (if it is unmanaged
1227          * it is already off the queues).
1228          */
1229         s = splvm();
1230         if (m->wire_count == 0) {
1231                 if ((m->flags & PG_UNMANAGED) == 0)
1232                         vm_pageq_remove(m);
1233                 cnt.v_wire_count++;
1234         }
1235         m->wire_count++;
1236         KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
1237         splx(s);
1238         vm_page_flag_set(m, PG_MAPPED);
1239 }
1240
1241 /*
1242  *      vm_page_unwire:
1243  *
1244  *      Release one wiring of this page, potentially
1245  *      enabling it to be paged again.
1246  *
1247  *      Many pages placed on the inactive queue should actually go
1248  *      into the cache, but it is difficult to figure out which.  What
1249  *      we do instead, if the inactive target is well met, is to put
1250  *      clean pages at the head of the inactive queue instead of the tail.
1251  *      This will cause them to be moved to the cache more quickly and
1252  *      if not actively re-referenced, freed more quickly.  If we just
1253  *      stick these pages at the end of the inactive queue, heavy filesystem
1254  *      meta-data accesses can cause an unnecessary paging load on memory bound 
1255  *      processes.  This optimization causes one-time-use metadata to be
1256  *      reused more quickly.
1257  *
1258  *      BUT, if we are in a low-memory situation we have no choice but to
1259  *      put clean pages on the cache queue.
1260  *
1261  *      A number of routines use vm_page_unwire() to guarantee that the page
1262  *      will go into either the inactive or active queues, and will NEVER
1263  *      be placed in the cache - for example, just after dirtying a page.
1264  *      dirty pages in the cache are not allowed.
1265  *
1266  *      The page queues must be locked.
1267  *      This routine may not block.
1268  */
1269 void
1270 vm_page_unwire(vm_page_t m, int activate)
1271 {
1272         int s;
1273
1274         s = splvm();
1275
1276         if (m->wire_count > 0) {
1277                 m->wire_count--;
1278                 if (m->wire_count == 0) {
1279                         cnt.v_wire_count--;
1280                         if (m->flags & PG_UNMANAGED) {
1281                                 ;
1282                         } else if (activate)
1283                                 vm_pageq_enqueue(PQ_ACTIVE, m);
1284                         else {
1285                                 vm_page_flag_clear(m, PG_WINATCFLS);
1286                                 vm_pageq_enqueue(PQ_INACTIVE, m);
1287                         }
1288                 }
1289         } else {
1290                 panic("vm_page_unwire: invalid wire count: %d\n", m->wire_count);
1291         }
1292         splx(s);
1293 }
1294
1295
1296 /*
1297  * Move the specified page to the inactive queue.  If the page has
1298  * any associated swap, the swap is deallocated.
1299  *
1300  * Normally athead is 0 resulting in LRU operation.  athead is set
1301  * to 1 if we want this page to be 'as if it were placed in the cache',
1302  * except without unmapping it from the process address space.
1303  *
1304  * This routine may not block.
1305  */
1306 static __inline void
1307 _vm_page_deactivate(vm_page_t m, int athead)
1308 {
1309         int s;
1310
1311         GIANT_REQUIRED;
1312         /*
1313          * Ignore if already inactive.
1314          */
1315         if (m->queue == PQ_INACTIVE)
1316                 return;
1317
1318         s = splvm();
1319         if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
1320                 if ((m->queue - m->pc) == PQ_CACHE)
1321                         cnt.v_reactivated++;
1322                 vm_page_flag_clear(m, PG_WINATCFLS);
1323                 vm_pageq_remove(m);
1324                 if (athead)
1325                         TAILQ_INSERT_HEAD(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
1326                 else
1327                         TAILQ_INSERT_TAIL(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
1328                 m->queue = PQ_INACTIVE;
1329                 vm_page_queues[PQ_INACTIVE].lcnt++;
1330                 cnt.v_inactive_count++;
1331         }
1332         splx(s);
1333 }
1334
1335 void
1336 vm_page_deactivate(vm_page_t m)
1337 {
1338     _vm_page_deactivate(m, 0);
1339 }
1340
1341 /*
1342  * vm_page_try_to_cache:
1343  *
1344  * Returns 0 on failure, 1 on success
1345  */
1346 int
1347 vm_page_try_to_cache(vm_page_t m)
1348 {
1349         GIANT_REQUIRED;
1350
1351         if (m->dirty || m->hold_count || m->busy || m->wire_count ||
1352             (m->flags & (PG_BUSY|PG_UNMANAGED))) {
1353                 return (0);
1354         }
1355         vm_page_test_dirty(m);
1356         if (m->dirty)
1357                 return (0);
1358         vm_page_cache(m);
1359         return (1);
1360 }
1361
1362 /*
1363  * vm_page_try_to_free()
1364  *
1365  *      Attempt to free the page.  If we cannot free it, we do nothing.
1366  *      1 is returned on success, 0 on failure.
1367  */
1368 int
1369 vm_page_try_to_free(vm_page_t m)
1370 {
1371         if (m->dirty || m->hold_count || m->busy || m->wire_count ||
1372             (m->flags & (PG_BUSY|PG_UNMANAGED))) {
1373                 return (0);
1374         }
1375         vm_page_test_dirty(m);
1376         if (m->dirty)
1377                 return (0);
1378         vm_page_busy(m);
1379         vm_page_protect(m, VM_PROT_NONE);
1380         vm_page_free(m);
1381         return (1);
1382 }
1383
1384 /*
1385  * vm_page_cache
1386  *
1387  * Put the specified page onto the page cache queue (if appropriate).
1388  *
1389  * This routine may not block.
1390  */
1391 void
1392 vm_page_cache(vm_page_t m)
1393 {
1394         int s;
1395
1396         GIANT_REQUIRED;
1397         if ((m->flags & (PG_BUSY|PG_UNMANAGED)) || m->busy || m->wire_count) {
1398                 printf("vm_page_cache: attempting to cache busy page\n");
1399                 return;
1400         }
1401         if ((m->queue - m->pc) == PQ_CACHE)
1402                 return;
1403
1404         /*
1405          * Remove all pmaps and indicate that the page is not
1406          * writeable or mapped.
1407          */
1408         vm_page_protect(m, VM_PROT_NONE);
1409         if (m->dirty != 0) {
1410                 panic("vm_page_cache: caching a dirty page, pindex: %ld",
1411                         (long)m->pindex);
1412         }
1413         s = splvm();
1414         vm_pageq_remove_nowakeup(m);
1415         vm_pageq_enqueue(PQ_CACHE + m->pc, m);
1416         vm_page_free_wakeup();
1417         splx(s);
1418 }
1419
1420 /*
1421  * vm_page_dontneed
1422  *
1423  *      Cache, deactivate, or do nothing as appropriate.  This routine
1424  *      is typically used by madvise() MADV_DONTNEED.
1425  *
1426  *      Generally speaking we want to move the page into the cache so
1427  *      it gets reused quickly.  However, this can result in a silly syndrome
1428  *      due to the page recycling too quickly.  Small objects will not be
1429  *      fully cached.  On the otherhand, if we move the page to the inactive
1430  *      queue we wind up with a problem whereby very large objects 
1431  *      unnecessarily blow away our inactive and cache queues.
1432  *
1433  *      The solution is to move the pages based on a fixed weighting.  We
1434  *      either leave them alone, deactivate them, or move them to the cache,
1435  *      where moving them to the cache has the highest weighting.
1436  *      By forcing some pages into other queues we eventually force the
1437  *      system to balance the queues, potentially recovering other unrelated
1438  *      space from active.  The idea is to not force this to happen too
1439  *      often.
1440  */
1441 void
1442 vm_page_dontneed(vm_page_t m)
1443 {
1444         static int dnweight;
1445         int dnw;
1446         int head;
1447
1448         GIANT_REQUIRED;
1449         dnw = ++dnweight;
1450
1451         /*
1452          * occassionally leave the page alone
1453          */
1454         if ((dnw & 0x01F0) == 0 ||
1455             m->queue == PQ_INACTIVE || 
1456             m->queue - m->pc == PQ_CACHE
1457         ) {
1458                 if (m->act_count >= ACT_INIT)
1459                         --m->act_count;
1460                 return;
1461         }
1462
1463         if (m->dirty == 0)
1464                 vm_page_test_dirty(m);
1465
1466         if (m->dirty || (dnw & 0x0070) == 0) {
1467                 /*
1468                  * Deactivate the page 3 times out of 32.
1469                  */
1470                 head = 0;
1471         } else {
1472                 /*
1473                  * Cache the page 28 times out of every 32.  Note that
1474                  * the page is deactivated instead of cached, but placed
1475                  * at the head of the queue instead of the tail.
1476                  */
1477                 head = 1;
1478         }
1479         _vm_page_deactivate(m, head);
1480 }
1481
1482 /*
1483  * Grab a page, waiting until we are waken up due to the page
1484  * changing state.  We keep on waiting, if the page continues
1485  * to be in the object.  If the page doesn't exist, allocate it.
1486  *
1487  * This routine may block.
1488  */
1489 vm_page_t
1490 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
1491 {
1492         vm_page_t m;
1493         int s, generation;
1494
1495         GIANT_REQUIRED;
1496 retrylookup:
1497         if ((m = vm_page_lookup(object, pindex)) != NULL) {
1498                 if (m->busy || (m->flags & PG_BUSY)) {
1499                         generation = object->generation;
1500
1501                         s = splvm();
1502                         while ((object->generation == generation) &&
1503                                         (m->busy || (m->flags & PG_BUSY))) {
1504                                 vm_page_flag_set(m, PG_WANTED | PG_REFERENCED);
1505                                 tsleep(m, PVM, "pgrbwt", 0);
1506                                 if ((allocflags & VM_ALLOC_RETRY) == 0) {
1507                                         splx(s);
1508                                         return NULL;
1509                                 }
1510                         }
1511                         splx(s);
1512                         goto retrylookup;
1513                 } else {
1514                         vm_page_busy(m);
1515                         return m;
1516                 }
1517         }
1518
1519         m = vm_page_alloc(object, pindex, allocflags & ~VM_ALLOC_RETRY);
1520         if (m == NULL) {
1521                 VM_WAIT;
1522                 if ((allocflags & VM_ALLOC_RETRY) == 0)
1523                         return NULL;
1524                 goto retrylookup;
1525         }
1526
1527         return m;
1528 }
1529
1530 /*
1531  * Mapping function for valid bits or for dirty bits in
1532  * a page.  May not block.
1533  *
1534  * Inputs are required to range within a page.
1535  */
1536 __inline int
1537 vm_page_bits(int base, int size)
1538 {
1539         int first_bit;
1540         int last_bit;
1541
1542         KASSERT(
1543             base + size <= PAGE_SIZE,
1544             ("vm_page_bits: illegal base/size %d/%d", base, size)
1545         );
1546
1547         if (size == 0)          /* handle degenerate case */
1548                 return (0);
1549
1550         first_bit = base >> DEV_BSHIFT;
1551         last_bit = (base + size - 1) >> DEV_BSHIFT;
1552
1553         return ((2 << last_bit) - (1 << first_bit));
1554 }
1555
1556 /*
1557  *      vm_page_set_validclean:
1558  *
1559  *      Sets portions of a page valid and clean.  The arguments are expected
1560  *      to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
1561  *      of any partial chunks touched by the range.  The invalid portion of
1562  *      such chunks will be zero'd.
1563  *
1564  *      This routine may not block.
1565  *
1566  *      (base + size) must be less then or equal to PAGE_SIZE.
1567  */
1568 void
1569 vm_page_set_validclean(vm_page_t m, int base, int size)
1570 {
1571         int pagebits;
1572         int frag;
1573         int endoff;
1574
1575         GIANT_REQUIRED;
1576         if (size == 0)  /* handle degenerate case */
1577                 return;
1578
1579         /*
1580          * If the base is not DEV_BSIZE aligned and the valid
1581          * bit is clear, we have to zero out a portion of the
1582          * first block.
1583          */
1584         if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
1585             (m->valid & (1 << (base >> DEV_BSHIFT))) == 0
1586         ) {
1587                 pmap_zero_page_area(
1588                     VM_PAGE_TO_PHYS(m),
1589                     frag,
1590                     base - frag
1591                 );
1592         }
1593
1594         /*
1595          * If the ending offset is not DEV_BSIZE aligned and the 
1596          * valid bit is clear, we have to zero out a portion of
1597          * the last block.
1598          */
1599         endoff = base + size;
1600         if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
1601             (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0
1602         ) {
1603                 pmap_zero_page_area(
1604                     VM_PAGE_TO_PHYS(m),
1605                     endoff,
1606                     DEV_BSIZE - (endoff & (DEV_BSIZE - 1))
1607                 );
1608         }
1609
1610         /*
1611          * Set valid, clear dirty bits.  If validating the entire
1612          * page we can safely clear the pmap modify bit.  We also
1613          * use this opportunity to clear the PG_NOSYNC flag.  If a process
1614          * takes a write fault on a MAP_NOSYNC memory area the flag will
1615          * be set again.
1616          *
1617          * We set valid bits inclusive of any overlap, but we can only
1618          * clear dirty bits for DEV_BSIZE chunks that are fully within
1619          * the range.
1620          */
1621         pagebits = vm_page_bits(base, size);
1622         m->valid |= pagebits;
1623 #if 0   /* NOT YET */
1624         if ((frag = base & (DEV_BSIZE - 1)) != 0) {
1625                 frag = DEV_BSIZE - frag;
1626                 base += frag;
1627                 size -= frag;
1628                 if (size < 0)
1629                         size = 0;
1630         }
1631         pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
1632 #endif
1633         m->dirty &= ~pagebits;
1634         if (base == 0 && size == PAGE_SIZE) {
1635                 pmap_clear_modify(m);
1636                 vm_page_flag_clear(m, PG_NOSYNC);
1637         }
1638 }
1639
1640 #if 0
1641
1642 void
1643 vm_page_set_dirty(vm_page_t m, int base, int size)
1644 {
1645         m->dirty |= vm_page_bits(base, size);
1646 }
1647
1648 #endif
1649
1650 void
1651 vm_page_clear_dirty(vm_page_t m, int base, int size)
1652 {
1653         GIANT_REQUIRED;
1654         m->dirty &= ~vm_page_bits(base, size);
1655 }
1656
1657 /*
1658  *      vm_page_set_invalid:
1659  *
1660  *      Invalidates DEV_BSIZE'd chunks within a page.  Both the
1661  *      valid and dirty bits for the effected areas are cleared.
1662  *
1663  *      May not block.
1664  */
1665 void
1666 vm_page_set_invalid(vm_page_t m, int base, int size)
1667 {
1668         int bits;
1669
1670         GIANT_REQUIRED;
1671         bits = vm_page_bits(base, size);
1672         m->valid &= ~bits;
1673         m->dirty &= ~bits;
1674         m->object->generation++;
1675 }
1676
1677 /*
1678  * vm_page_zero_invalid()
1679  *
1680  *      The kernel assumes that the invalid portions of a page contain 
1681  *      garbage, but such pages can be mapped into memory by user code.
1682  *      When this occurs, we must zero out the non-valid portions of the
1683  *      page so user code sees what it expects.
1684  *
1685  *      Pages are most often semi-valid when the end of a file is mapped 
1686  *      into memory and the file's size is not page aligned.
1687  */
1688 void
1689 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
1690 {
1691         int b;
1692         int i;
1693
1694         /*
1695          * Scan the valid bits looking for invalid sections that
1696          * must be zerod.  Invalid sub-DEV_BSIZE'd areas ( where the
1697          * valid bit may be set ) have already been zerod by
1698          * vm_page_set_validclean().
1699          */
1700         for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
1701                 if (i == (PAGE_SIZE / DEV_BSIZE) || 
1702                     (m->valid & (1 << i))
1703                 ) {
1704                         if (i > b) {
1705                                 pmap_zero_page_area(
1706                                     VM_PAGE_TO_PHYS(m), 
1707                                     b << DEV_BSHIFT,
1708                                     (i - b) << DEV_BSHIFT
1709                                 );
1710                         }
1711                         b = i + 1;
1712                 }
1713         }
1714
1715         /*
1716          * setvalid is TRUE when we can safely set the zero'd areas
1717          * as being valid.  We can do this if there are no cache consistancy
1718          * issues.  e.g. it is ok to do with UFS, but not ok to do with NFS.
1719          */
1720         if (setvalid)
1721                 m->valid = VM_PAGE_BITS_ALL;
1722 }
1723
1724 /*
1725  *      vm_page_is_valid:
1726  *
1727  *      Is (partial) page valid?  Note that the case where size == 0
1728  *      will return FALSE in the degenerate case where the page is
1729  *      entirely invalid, and TRUE otherwise.
1730  *
1731  *      May not block.
1732  */
1733 int
1734 vm_page_is_valid(vm_page_t m, int base, int size)
1735 {
1736         int bits = vm_page_bits(base, size);
1737
1738         if (m->valid && ((m->valid & bits) == bits))
1739                 return 1;
1740         else
1741                 return 0;
1742 }
1743
1744 /*
1745  * update dirty bits from pmap/mmu.  May not block.
1746  */
1747 void
1748 vm_page_test_dirty(vm_page_t m)
1749 {
1750         if ((m->dirty != VM_PAGE_BITS_ALL) && pmap_is_modified(m)) {
1751                 vm_page_dirty(m);
1752         }
1753 }
1754
1755 #include "opt_ddb.h"
1756 #ifdef DDB
1757 #include <sys/kernel.h>
1758
1759 #include <ddb/ddb.h>
1760
1761 DB_SHOW_COMMAND(page, vm_page_print_page_info)
1762 {
1763         db_printf("cnt.v_free_count: %d\n", cnt.v_free_count);
1764         db_printf("cnt.v_cache_count: %d\n", cnt.v_cache_count);
1765         db_printf("cnt.v_inactive_count: %d\n", cnt.v_inactive_count);
1766         db_printf("cnt.v_active_count: %d\n", cnt.v_active_count);
1767         db_printf("cnt.v_wire_count: %d\n", cnt.v_wire_count);
1768         db_printf("cnt.v_free_reserved: %d\n", cnt.v_free_reserved);
1769         db_printf("cnt.v_free_min: %d\n", cnt.v_free_min);
1770         db_printf("cnt.v_free_target: %d\n", cnt.v_free_target);
1771         db_printf("cnt.v_cache_min: %d\n", cnt.v_cache_min);
1772         db_printf("cnt.v_inactive_target: %d\n", cnt.v_inactive_target);
1773 }
1774
1775 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
1776 {
1777         int i;
1778         db_printf("PQ_FREE:");
1779         for (i = 0; i < PQ_L2_SIZE; i++) {
1780                 db_printf(" %d", vm_page_queues[PQ_FREE + i].lcnt);
1781         }
1782         db_printf("\n");
1783                 
1784         db_printf("PQ_CACHE:");
1785         for (i = 0; i < PQ_L2_SIZE; i++) {
1786                 db_printf(" %d", vm_page_queues[PQ_CACHE + i].lcnt);
1787         }
1788         db_printf("\n");
1789
1790         db_printf("PQ_ACTIVE: %d, PQ_INACTIVE: %d\n",
1791                 vm_page_queues[PQ_ACTIVE].lcnt,
1792                 vm_page_queues[PQ_INACTIVE].lcnt);
1793 }
1794 #endif /* DDB */