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