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