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