diff --git a/sys/vm/vm_fault.c b/sys/vm/vm_fault.c index c341661b02de..aa1d0223593d 100644 --- a/sys/vm/vm_fault.c +++ b/sys/vm/vm_fault.c @@ -1,1261 +1,1262 @@ /* * Copyright (c) 1991, 1993 * The Regents of the University of California. All rights reserved. * Copyright (c) 1994 John S. Dyson * All rights reserved. * Copyright (c) 1994 David Greenman * All rights reserved. * * * This code is derived from software contributed to Berkeley by * The Mach Operating System project at Carnegie-Mellon University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * from: @(#)vm_fault.c 8.4 (Berkeley) 1/12/94 * * * Copyright (c) 1987, 1990 Carnegie-Mellon University. * All rights reserved. * * Authors: Avadis Tevanian, Jr., Michael Wayne Young * * Permission to use, copy, modify and distribute this software and * its documentation is hereby granted, provided that both the copyright * notice and this permission notice appear in all copies of the * software, derivative works or modified versions, and any portions * thereof, and that both notices appear in supporting documentation. * * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE. * * Carnegie Mellon requests users of this software to return to * * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU * School of Computer Science * Carnegie Mellon University * Pittsburgh PA 15213-3890 * * any improvements or extensions that they make and grant Carnegie the * rights to redistribute these changes. * * $FreeBSD$ */ /* * Page fault handling module. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static int vm_fault_additional_pages(vm_page_t, int, int, vm_page_t *, int *); #define VM_FAULT_READ_AHEAD 8 #define VM_FAULT_READ_BEHIND 7 #define VM_FAULT_READ (VM_FAULT_READ_AHEAD+VM_FAULT_READ_BEHIND+1) struct faultstate { vm_page_t m; vm_object_t object; vm_pindex_t pindex; vm_page_t first_m; vm_object_t first_object; vm_pindex_t first_pindex; vm_map_t map; vm_map_entry_t entry; int lookup_still_valid; struct vnode *vp; }; static __inline void release_page(struct faultstate *fs) { vm_page_wakeup(fs->m); vm_page_deactivate(fs->m); fs->m = NULL; } static __inline void unlock_map(struct faultstate *fs) { if (fs->lookup_still_valid) { vm_map_lookup_done(fs->map, fs->entry); fs->lookup_still_valid = FALSE; } } static void _unlock_things(struct faultstate *fs, int dealloc) { GIANT_REQUIRED; vm_object_pip_wakeup(fs->object); if (fs->object != fs->first_object) { vm_page_free(fs->first_m); vm_object_pip_wakeup(fs->first_object); fs->first_m = NULL; } if (dealloc) { vm_object_deallocate(fs->first_object); } unlock_map(fs); if (fs->vp != NULL) { vput(fs->vp); fs->vp = NULL; } } #define unlock_things(fs) _unlock_things(fs, 0) #define unlock_and_deallocate(fs) _unlock_things(fs, 1) /* * TRYPAGER - used by vm_fault to calculate whether the pager for the * current object *might* contain the page. * * default objects are zero-fill, there is no real pager. */ #define TRYPAGER (fs.object->type != OBJT_DEFAULT && \ (((fault_flags & VM_FAULT_WIRE_MASK) == 0) || wired)) /* * vm_fault: * * Handle a page fault occurring at the given address, * requiring the given permissions, in the map specified. * If successful, the page is inserted into the * associated physical map. * * NOTE: the given address should be truncated to the * proper page address. * * KERN_SUCCESS is returned if the page fault is handled; otherwise, * a standard error specifying why the fault is fatal is returned. * * * The map in question must be referenced, and remains so. * Caller may hold no locks. */ int vm_fault(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type, int fault_flags) { vm_prot_t prot; int result; boolean_t growstack, wired; int map_generation; vm_object_t next_object; vm_page_t marray[VM_FAULT_READ]; int hardfault; int faultcount; struct faultstate fs; hardfault = 0; growstack = TRUE; atomic_add_int(&cnt.v_vm_faults, 1); mtx_lock(&Giant); RetryFault:; /* * Find the backing store object and offset into it to begin the * search. */ fs.map = map; result = vm_map_lookup(&fs.map, vaddr, fault_type, &fs.entry, &fs.first_object, &fs.first_pindex, &prot, &wired); if (result != KERN_SUCCESS) { if (result != KERN_PROTECTION_FAILURE || (fault_flags & VM_FAULT_WIRE_MASK) != VM_FAULT_USER_WIRE) { if (growstack && result == KERN_INVALID_ADDRESS && map != kernel_map && curproc != NULL) { result = vm_map_growstack(curproc, vaddr); if (result != KERN_SUCCESS) { mtx_unlock(&Giant); return (KERN_FAILURE); } growstack = FALSE; goto RetryFault; } mtx_unlock(&Giant); return (result); } /* * If we are user-wiring a r/w segment, and it is COW, then * we need to do the COW operation. Note that we don't COW * currently RO sections now, because it is NOT desirable * to COW .text. We simply keep .text from ever being COW'ed * and take the heat that one cannot debug wired .text sections. */ result = vm_map_lookup(&fs.map, vaddr, VM_PROT_READ|VM_PROT_WRITE|VM_PROT_OVERRIDE_WRITE, &fs.entry, &fs.first_object, &fs.first_pindex, &prot, &wired); if (result != KERN_SUCCESS) { mtx_unlock(&Giant); return (result); } /* * If we don't COW now, on a user wire, the user will never * be able to write to the mapping. If we don't make this * restriction, the bookkeeping would be nearly impossible. * * XXX The following assignment modifies the map without * holding a write lock on it. */ if ((fs.entry->protection & VM_PROT_WRITE) == 0) fs.entry->max_protection &= ~VM_PROT_WRITE; } map_generation = fs.map->timestamp; if (fs.entry->eflags & MAP_ENTRY_NOFAULT) { panic("vm_fault: fault on nofault entry, addr: %lx", (u_long)vaddr); } /* * Make a reference to this object to prevent its disposal while we * are messing with it. Once we have the reference, the map is free * to be diddled. Since objects reference their shadows (and copies), * they will stay around as well. * * Bump the paging-in-progress count to prevent size changes (e.g. * truncation operations) during I/O. This must be done after * obtaining the vnode lock in order to avoid possible deadlocks. * * XXX vnode_pager_lock() can block without releasing the map lock. */ vm_object_reference(fs.first_object); fs.vp = vnode_pager_lock(fs.first_object); vm_object_pip_add(fs.first_object, 1); #ifdef ENABLE_VFS_IOOPT if ((fault_type & VM_PROT_WRITE) && (fs.first_object->type == OBJT_VNODE)) { vm_freeze_copyopts(fs.first_object, fs.first_pindex, fs.first_pindex + 1); } #endif fs.lookup_still_valid = TRUE; if (wired) fault_type = prot; fs.first_m = NULL; /* * Search for the page at object/offset. */ fs.object = fs.first_object; fs.pindex = fs.first_pindex; while (TRUE) { /* * If the object is dead, we stop here */ if (fs.object->flags & OBJ_DEAD) { unlock_and_deallocate(&fs); mtx_unlock(&Giant); return (KERN_PROTECTION_FAILURE); } /* * See if page is resident */ fs.m = vm_page_lookup(fs.object, fs.pindex); if (fs.m != NULL) { int queue, s; /* * check for page-based copy on write */ if ((fs.m->cow) && (fault_type & VM_PROT_WRITE)) { s = splvm(); vm_page_cowfault(fs.m); splx(s); unlock_things(&fs); goto RetryFault; } /* * Wait/Retry if the page is busy. We have to do this * if the page is busy via either PG_BUSY or * vm_page_t->busy because the vm_pager may be using * vm_page_t->busy for pageouts ( and even pageins if * it is the vnode pager ), and we could end up trying * to pagein and pageout the same page simultaneously. * * We can theoretically allow the busy case on a read * fault if the page is marked valid, but since such * pages are typically already pmap'd, putting that * special case in might be more effort then it is * worth. We cannot under any circumstances mess * around with a vm_page_t->busy page except, perhaps, * to pmap it. */ if ((fs.m->flags & PG_BUSY) || fs.m->busy) { unlock_things(&fs); (void)vm_page_sleep_busy(fs.m, TRUE, "vmpfw"); cnt.v_intrans++; vm_object_deallocate(fs.first_object); goto RetryFault; } queue = fs.m->queue; s = splvm(); vm_pageq_remove_nowakeup(fs.m); splx(s); if ((queue - fs.m->pc) == PQ_CACHE && vm_page_count_severe()) { vm_page_activate(fs.m); unlock_and_deallocate(&fs); VM_WAITPFAULT; goto RetryFault; } /* * Mark page busy for other processes, and the * pagedaemon. If it still isn't completely valid * (readable), jump to readrest, else break-out ( we * found the page ). */ vm_page_busy(fs.m); if (((fs.m->valid & VM_PAGE_BITS_ALL) != VM_PAGE_BITS_ALL) && fs.m->object != kernel_object && fs.m->object != kmem_object) { goto readrest; } break; } /* * Page is not resident, If this is the search termination * or the pager might contain the page, allocate a new page. */ if (TRYPAGER || fs.object == fs.first_object) { if (fs.pindex >= fs.object->size) { unlock_and_deallocate(&fs); mtx_unlock(&Giant); return (KERN_PROTECTION_FAILURE); } /* * Allocate a new page for this object/offset pair. */ fs.m = NULL; if (!vm_page_count_severe()) { fs.m = vm_page_alloc(fs.object, fs.pindex, (fs.vp || fs.object->backing_object)? VM_ALLOC_NORMAL: VM_ALLOC_ZERO); } if (fs.m == NULL) { unlock_and_deallocate(&fs); VM_WAITPFAULT; goto RetryFault; } } readrest: /* * We have found a valid page or we have allocated a new page. * The page thus may not be valid or may not be entirely * valid. * * Attempt to fault-in the page if there is a chance that the * pager has it, and potentially fault in additional pages * at the same time. */ if (TRYPAGER) { int rv; int reqpage; int ahead, behind; u_char behavior = vm_map_entry_behavior(fs.entry); if (behavior == MAP_ENTRY_BEHAV_RANDOM) { ahead = 0; behind = 0; } else { behind = (vaddr - fs.entry->start) >> PAGE_SHIFT; if (behind > VM_FAULT_READ_BEHIND) behind = VM_FAULT_READ_BEHIND; ahead = ((fs.entry->end - vaddr) >> PAGE_SHIFT) - 1; if (ahead > VM_FAULT_READ_AHEAD) ahead = VM_FAULT_READ_AHEAD; } if ((fs.first_object->type != OBJT_DEVICE) && (behavior == MAP_ENTRY_BEHAV_SEQUENTIAL || (behavior != MAP_ENTRY_BEHAV_RANDOM && fs.pindex >= fs.entry->lastr && fs.pindex < fs.entry->lastr + VM_FAULT_READ)) ) { vm_pindex_t firstpindex, tmppindex; if (fs.first_pindex < 2 * VM_FAULT_READ) firstpindex = 0; else firstpindex = fs.first_pindex - 2 * VM_FAULT_READ; + vm_page_lock_queues(); /* * note: partially valid pages cannot be * included in the lookahead - NFS piecemeal * writes will barf on it badly. */ for (tmppindex = fs.first_pindex - 1; tmppindex >= firstpindex; --tmppindex) { vm_page_t mt; mt = vm_page_lookup(fs.first_object, tmppindex); if (mt == NULL || (mt->valid != VM_PAGE_BITS_ALL)) break; if (mt->busy || (mt->flags & (PG_BUSY | PG_FICTITIOUS | PG_UNMANAGED)) || mt->hold_count || mt->wire_count) continue; if (mt->dirty == 0) vm_page_test_dirty(mt); if (mt->dirty) { vm_page_protect(mt, VM_PROT_NONE); vm_page_deactivate(mt); } else { vm_page_cache(mt); } } - + vm_page_unlock_queues(); ahead += behind; behind = 0; } /* * now we find out if any other pages should be paged * in at this time this routine checks to see if the * pages surrounding this fault reside in the same * object as the page for this fault. If they do, * then they are faulted in also into the object. The * array "marray" returned contains an array of * vm_page_t structs where one of them is the * vm_page_t passed to the routine. The reqpage * return value is the index into the marray for the * vm_page_t passed to the routine. * * fs.m plus the additional pages are PG_BUSY'd. * * XXX vm_fault_additional_pages() can block * without releasing the map lock. */ faultcount = vm_fault_additional_pages( fs.m, behind, ahead, marray, &reqpage); /* * update lastr imperfectly (we do not know how much * getpages will actually read), but good enough. * * XXX The following assignment modifies the map * without holding a write lock on it. */ fs.entry->lastr = fs.pindex + faultcount - behind; /* * Call the pager to retrieve the data, if any, after * releasing the lock on the map. We hold a ref on * fs.object and the pages are PG_BUSY'd. */ unlock_map(&fs); rv = faultcount ? vm_pager_get_pages(fs.object, marray, faultcount, reqpage) : VM_PAGER_FAIL; if (rv == VM_PAGER_OK) { /* * Found the page. Leave it busy while we play * with it. */ /* * Relookup in case pager changed page. Pager * is responsible for disposition of old page * if moved. */ fs.m = vm_page_lookup(fs.object, fs.pindex); if (!fs.m) { unlock_and_deallocate(&fs); goto RetryFault; } hardfault++; break; /* break to PAGE HAS BEEN FOUND */ } /* * Remove the bogus page (which does not exist at this * object/offset); before doing so, we must get back * our object lock to preserve our invariant. * * Also wake up any other process that may want to bring * in this page. * * If this is the top-level object, we must leave the * busy page to prevent another process from rushing * past us, and inserting the page in that object at * the same time that we are. */ if (rv == VM_PAGER_ERROR) printf("vm_fault: pager read error, pid %d (%s)\n", curproc->p_pid, curproc->p_comm); /* * Data outside the range of the pager or an I/O error */ /* * XXX - the check for kernel_map is a kludge to work * around having the machine panic on a kernel space * fault w/ I/O error. */ if (((fs.map != kernel_map) && (rv == VM_PAGER_ERROR)) || (rv == VM_PAGER_BAD)) { vm_page_free(fs.m); fs.m = NULL; unlock_and_deallocate(&fs); mtx_unlock(&Giant); return ((rv == VM_PAGER_ERROR) ? KERN_FAILURE : KERN_PROTECTION_FAILURE); } if (fs.object != fs.first_object) { vm_page_free(fs.m); fs.m = NULL; /* * XXX - we cannot just fall out at this * point, m has been freed and is invalid! */ } } /* * We get here if the object has default pager (or unwiring) * or the pager doesn't have the page. */ if (fs.object == fs.first_object) fs.first_m = fs.m; /* * Move on to the next object. Lock the next object before * unlocking the current one. */ fs.pindex += OFF_TO_IDX(fs.object->backing_object_offset); next_object = fs.object->backing_object; if (next_object == NULL) { /* * If there's no object left, fill the page in the top * object with zeros. */ if (fs.object != fs.first_object) { vm_object_pip_wakeup(fs.object); fs.object = fs.first_object; fs.pindex = fs.first_pindex; fs.m = fs.first_m; } fs.first_m = NULL; /* * Zero the page if necessary and mark it valid. */ if ((fs.m->flags & PG_ZERO) == 0) { vm_page_zero_fill(fs.m); } else { cnt.v_ozfod++; } cnt.v_zfod++; fs.m->valid = VM_PAGE_BITS_ALL; break; /* break to PAGE HAS BEEN FOUND */ } else { if (fs.object != fs.first_object) { vm_object_pip_wakeup(fs.object); } KASSERT(fs.object != next_object, ("object loop %p", next_object)); fs.object = next_object; vm_object_pip_add(fs.object, 1); } } KASSERT((fs.m->flags & PG_BUSY) != 0, ("vm_fault: not busy after main loop")); /* * PAGE HAS BEEN FOUND. [Loop invariant still holds -- the object lock * is held.] */ /* * If the page is being written, but isn't already owned by the * top-level object, we have to copy it into a new page owned by the * top-level object. */ if (fs.object != fs.first_object) { /* * We only really need to copy if we want to write it. */ if (fault_type & VM_PROT_WRITE) { /* * This allows pages to be virtually copied from a * backing_object into the first_object, where the * backing object has no other refs to it, and cannot * gain any more refs. Instead of a bcopy, we just * move the page from the backing object to the * first object. Note that we must mark the page * dirty in the first object so that it will go out * to swap when needed. */ if (map_generation == fs.map->timestamp && /* * Only one shadow object */ (fs.object->shadow_count == 1) && /* * No COW refs, except us */ (fs.object->ref_count == 1) && /* * No one else can look this object up */ (fs.object->handle == NULL) && /* * No other ways to look the object up */ ((fs.object->type == OBJT_DEFAULT) || (fs.object->type == OBJT_SWAP)) && /* * We don't chase down the shadow chain */ (fs.object == fs.first_object->backing_object) && /* * grab the lock if we need to */ (fs.lookup_still_valid || vm_map_trylock(fs.map))) { fs.lookup_still_valid = 1; /* * get rid of the unnecessary page */ vm_page_protect(fs.first_m, VM_PROT_NONE); vm_page_free(fs.first_m); fs.first_m = NULL; /* * grab the page and put it into the * process'es object. The page is * automatically made dirty. */ vm_page_rename(fs.m, fs.first_object, fs.first_pindex); fs.first_m = fs.m; vm_page_busy(fs.first_m); fs.m = NULL; cnt.v_cow_optim++; } else { /* * Oh, well, lets copy it. */ vm_page_copy(fs.m, fs.first_m); } if (fs.m) { /* * We no longer need the old page or object. */ release_page(&fs); } /* * fs.object != fs.first_object due to above * conditional */ vm_object_pip_wakeup(fs.object); /* * Only use the new page below... */ cnt.v_cow_faults++; fs.m = fs.first_m; fs.object = fs.first_object; fs.pindex = fs.first_pindex; } else { prot &= ~VM_PROT_WRITE; } } /* * We must verify that the maps have not changed since our last * lookup. */ if (!fs.lookup_still_valid && (fs.map->timestamp != map_generation)) { vm_object_t retry_object; vm_pindex_t retry_pindex; vm_prot_t retry_prot; /* * Since map entries may be pageable, make sure we can take a * page fault on them. */ /* * Unlock vnode before the lookup to avoid deadlock. E.G. * avoid a deadlock between the inode and exec_map that can * occur due to locks being obtained in different orders. */ if (fs.vp != NULL) { vput(fs.vp); fs.vp = NULL; } if (fs.map->infork) { release_page(&fs); unlock_and_deallocate(&fs); goto RetryFault; } /* * To avoid trying to write_lock the map while another process * has it read_locked (in vm_map_pageable), we do not try for * write permission. If the page is still writable, we will * get write permission. If it is not, or has been marked * needs_copy, we enter the mapping without write permission, * and will merely take another fault. */ result = vm_map_lookup(&fs.map, vaddr, fault_type & ~VM_PROT_WRITE, &fs.entry, &retry_object, &retry_pindex, &retry_prot, &wired); map_generation = fs.map->timestamp; /* * If we don't need the page any longer, put it on the active * list (the easiest thing to do here). If no one needs it, * pageout will grab it eventually. */ if (result != KERN_SUCCESS) { release_page(&fs); unlock_and_deallocate(&fs); mtx_unlock(&Giant); return (result); } fs.lookup_still_valid = TRUE; if ((retry_object != fs.first_object) || (retry_pindex != fs.first_pindex)) { release_page(&fs); unlock_and_deallocate(&fs); goto RetryFault; } /* * Check whether the protection has changed or the object has * been copied while we left the map unlocked. Changing from * read to write permission is OK - we leave the page * write-protected, and catch the write fault. Changing from * write to read permission means that we can't mark the page * write-enabled after all. */ prot &= retry_prot; } /* * Put this page into the physical map. We had to do the unlock above * because pmap_enter may cause other faults. We don't put the page * back on the active queue until later so that the page-out daemon * won't find us (yet). */ if (prot & VM_PROT_WRITE) { vm_page_flag_set(fs.m, PG_WRITEABLE); vm_object_set_writeable_dirty(fs.m->object); /* * If the fault is a write, we know that this page is being * written NOW so dirty it explicitly to save on * pmap_is_modified() calls later. * * If this is a NOSYNC mmap we do not want to set PG_NOSYNC * if the page is already dirty to prevent data written with * the expectation of being synced from not being synced. * Likewise if this entry does not request NOSYNC then make * sure the page isn't marked NOSYNC. Applications sharing * data should use the same flags to avoid ping ponging. * * Also tell the backing pager, if any, that it should remove * any swap backing since the page is now dirty. */ if (fs.entry->eflags & MAP_ENTRY_NOSYNC) { if (fs.m->dirty == 0) vm_page_flag_set(fs.m, PG_NOSYNC); } else { vm_page_flag_clear(fs.m, PG_NOSYNC); } if (fault_flags & VM_FAULT_DIRTY) { int s; vm_page_dirty(fs.m); s = splvm(); vm_pager_page_unswapped(fs.m); splx(s); } } /* * Page had better still be busy */ KASSERT(fs.m->flags & PG_BUSY, ("vm_fault: page %p not busy!", fs.m)); unlock_things(&fs); /* * Sanity check: page must be completely valid or it is not fit to * map into user space. vm_pager_get_pages() ensures this. */ if (fs.m->valid != VM_PAGE_BITS_ALL) { vm_page_zero_invalid(fs.m, TRUE); printf("Warning: page %p partially invalid on fault\n", fs.m); } pmap_enter(fs.map->pmap, vaddr, fs.m, prot, wired); if (((fault_flags & VM_FAULT_WIRE_MASK) == 0) && (wired == 0)) { pmap_prefault(fs.map->pmap, vaddr, fs.entry); } vm_page_lock_queues(); vm_page_flag_clear(fs.m, PG_ZERO); vm_page_flag_set(fs.m, PG_MAPPED|PG_REFERENCED); /* * If the page is not wired down, then put it where the pageout daemon * can find it. */ if (fault_flags & VM_FAULT_WIRE_MASK) { if (wired) vm_page_wire(fs.m); else vm_page_unwire(fs.m, 1); } else { vm_page_activate(fs.m); } vm_page_unlock_queues(); mtx_lock_spin(&sched_lock); if (curproc && (curproc->p_sflag & PS_INMEM) && curproc->p_stats) { if (hardfault) { curproc->p_stats->p_ru.ru_majflt++; } else { curproc->p_stats->p_ru.ru_minflt++; } } mtx_unlock_spin(&sched_lock); /* * Unlock everything, and return */ vm_page_wakeup(fs.m); vm_object_deallocate(fs.first_object); mtx_unlock(&Giant); return (KERN_SUCCESS); } /* * vm_fault_wire: * * Wire down a range of virtual addresses in a map. */ int vm_fault_wire(map, start, end) vm_map_t map; vm_offset_t start, end; { vm_offset_t va; pmap_t pmap; int rv; pmap = vm_map_pmap(map); /* * Inform the physical mapping system that the range of addresses may * not fault, so that page tables and such can be locked down as well. */ pmap_pageable(pmap, start, end, FALSE); /* * We simulate a fault to get the page and enter it in the physical * map. */ for (va = start; va < end; va += PAGE_SIZE) { rv = vm_fault(map, va, VM_PROT_READ|VM_PROT_WRITE, VM_FAULT_CHANGE_WIRING); if (rv) { if (va != start) vm_fault_unwire(map, start, va); return (rv); } } return (KERN_SUCCESS); } /* * vm_fault_user_wire: * * Wire down a range of virtual addresses in a map. This * is for user mode though, so we only ask for read access * on currently read only sections. */ int vm_fault_user_wire(map, start, end) vm_map_t map; vm_offset_t start, end; { vm_offset_t va; pmap_t pmap; int rv; pmap = vm_map_pmap(map); /* * Inform the physical mapping system that the range of addresses may * not fault, so that page tables and such can be locked down as well. */ pmap_pageable(pmap, start, end, FALSE); /* * We simulate a fault to get the page and enter it in the physical * map. */ for (va = start; va < end; va += PAGE_SIZE) { rv = vm_fault(map, va, VM_PROT_READ, VM_FAULT_USER_WIRE); if (rv) { if (va != start) vm_fault_unwire(map, start, va); return (rv); } } return (KERN_SUCCESS); } /* * vm_fault_unwire: * * Unwire a range of virtual addresses in a map. */ void vm_fault_unwire(map, start, end) vm_map_t map; vm_offset_t start, end; { vm_offset_t va, pa; pmap_t pmap; pmap = vm_map_pmap(map); mtx_lock(&Giant); /* * Since the pages are wired down, we must be able to get their * mappings from the physical map system. */ for (va = start; va < end; va += PAGE_SIZE) { pa = pmap_extract(pmap, va); if (pa != (vm_offset_t) 0) { pmap_change_wiring(pmap, va, FALSE); vm_page_lock_queues(); vm_page_unwire(PHYS_TO_VM_PAGE(pa), 1); vm_page_unlock_queues(); } } mtx_unlock(&Giant); /* * Inform the physical mapping system that the range of addresses may * fault, so that page tables and such may be unwired themselves. */ pmap_pageable(pmap, start, end, TRUE); } /* * Routine: * vm_fault_copy_entry * Function: * Copy all of the pages from a wired-down map entry to another. * * In/out conditions: * The source and destination maps must be locked for write. * The source map entry must be wired down (or be a sharing map * entry corresponding to a main map entry that is wired down). */ void vm_fault_copy_entry(dst_map, src_map, dst_entry, src_entry) vm_map_t dst_map; vm_map_t src_map; vm_map_entry_t dst_entry; vm_map_entry_t src_entry; { vm_object_t dst_object; vm_object_t src_object; vm_ooffset_t dst_offset; vm_ooffset_t src_offset; vm_prot_t prot; vm_offset_t vaddr; vm_page_t dst_m; vm_page_t src_m; #ifdef lint src_map++; #endif /* lint */ src_object = src_entry->object.vm_object; src_offset = src_entry->offset; /* * Create the top-level object for the destination entry. (Doesn't * actually shadow anything - we copy the pages directly.) */ dst_object = vm_object_allocate(OBJT_DEFAULT, (vm_size_t) OFF_TO_IDX(dst_entry->end - dst_entry->start)); dst_entry->object.vm_object = dst_object; dst_entry->offset = 0; prot = dst_entry->max_protection; /* * Loop through all of the pages in the entry's range, copying each * one from the source object (it should be there) to the destination * object. */ for (vaddr = dst_entry->start, dst_offset = 0; vaddr < dst_entry->end; vaddr += PAGE_SIZE, dst_offset += PAGE_SIZE) { /* * Allocate a page in the destination object */ do { dst_m = vm_page_alloc(dst_object, OFF_TO_IDX(dst_offset), VM_ALLOC_NORMAL); if (dst_m == NULL) { VM_WAIT; } } while (dst_m == NULL); /* * Find the page in the source object, and copy it in. * (Because the source is wired down, the page will be in * memory.) */ src_m = vm_page_lookup(src_object, OFF_TO_IDX(dst_offset + src_offset)); if (src_m == NULL) panic("vm_fault_copy_wired: page missing"); vm_page_copy(src_m, dst_m); /* * Enter it in the pmap... */ vm_page_flag_clear(dst_m, PG_ZERO); pmap_enter(dst_map->pmap, vaddr, dst_m, prot, FALSE); vm_page_flag_set(dst_m, PG_WRITEABLE|PG_MAPPED); /* * Mark it no longer busy, and put it on the active list. */ vm_page_activate(dst_m); vm_page_wakeup(dst_m); } } /* * This routine checks around the requested page for other pages that * might be able to be faulted in. This routine brackets the viable * pages for the pages to be paged in. * * Inputs: * m, rbehind, rahead * * Outputs: * marray (array of vm_page_t), reqpage (index of requested page) * * Return value: * number of pages in marray * * This routine can't block. */ static int vm_fault_additional_pages(m, rbehind, rahead, marray, reqpage) vm_page_t m; int rbehind; int rahead; vm_page_t *marray; int *reqpage; { int i,j; vm_object_t object; vm_pindex_t pindex, startpindex, endpindex, tpindex; vm_page_t rtm; int cbehind, cahead; GIANT_REQUIRED; object = m->object; pindex = m->pindex; /* * we don't fault-ahead for device pager */ if (object->type == OBJT_DEVICE) { *reqpage = 0; marray[0] = m; return 1; } /* * if the requested page is not available, then give up now */ if (!vm_pager_has_page(object, pindex, &cbehind, &cahead)) { return 0; } if ((cbehind == 0) && (cahead == 0)) { *reqpage = 0; marray[0] = m; return 1; } if (rahead > cahead) { rahead = cahead; } if (rbehind > cbehind) { rbehind = cbehind; } /* * try to do any readahead that we might have free pages for. */ if ((rahead + rbehind) > ((cnt.v_free_count + cnt.v_cache_count) - cnt.v_free_reserved)) { pagedaemon_wakeup(); marray[0] = m; *reqpage = 0; return 1; } /* * scan backward for the read behind pages -- in memory */ if (pindex > 0) { if (rbehind > pindex) { rbehind = pindex; startpindex = 0; } else { startpindex = pindex - rbehind; } for (tpindex = pindex - 1; tpindex >= startpindex; tpindex -= 1) { if (vm_page_lookup(object, tpindex)) { startpindex = tpindex + 1; break; } if (tpindex == 0) break; } for (i = 0, tpindex = startpindex; tpindex < pindex; i++, tpindex++) { rtm = vm_page_alloc(object, tpindex, VM_ALLOC_NORMAL); if (rtm == NULL) { for (j = 0; j < i; j++) { vm_page_free(marray[j]); } marray[0] = m; *reqpage = 0; return 1; } marray[i] = rtm; } } else { startpindex = 0; i = 0; } marray[i] = m; /* page offset of the required page */ *reqpage = i; tpindex = pindex + 1; i++; /* * scan forward for the read ahead pages */ endpindex = tpindex + rahead; if (endpindex > object->size) endpindex = object->size; for (; tpindex < endpindex; i++, tpindex++) { if (vm_page_lookup(object, tpindex)) { break; } rtm = vm_page_alloc(object, tpindex, VM_ALLOC_NORMAL); if (rtm == NULL) { break; } marray[i] = rtm; } /* return number of bytes of pages */ return i; } diff --git a/sys/vm/vm_page.c b/sys/vm/vm_page.c index 7a03d4749c8d..831f8c876557 100644 --- a/sys/vm/vm_page.c +++ b/sys/vm/vm_page.c @@ -1,1867 +1,1867 @@ /* * Copyright (c) 1991 Regents of the University of California. * All rights reserved. * * This code is derived from software contributed to Berkeley by * The Mach Operating System project at Carnegie-Mellon University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * from: @(#)vm_page.c 7.4 (Berkeley) 5/7/91 * $FreeBSD$ */ /* * Copyright (c) 1987, 1990 Carnegie-Mellon University. * All rights reserved. * * Authors: Avadis Tevanian, Jr., Michael Wayne Young * * Permission to use, copy, modify and distribute this software and * its documentation is hereby granted, provided that both the copyright * notice and this permission notice appear in all copies of the * software, derivative works or modified versions, and any portions * thereof, and that both notices appear in supporting documentation. * * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE. * * Carnegie Mellon requests users of this software to return to * * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU * School of Computer Science * Carnegie Mellon University * Pittsburgh PA 15213-3890 * * any improvements or extensions that they make and grant Carnegie the * rights to redistribute these changes. */ /* * GENERAL RULES ON VM_PAGE MANIPULATION * * - a pageq mutex is required when adding or removing a page from a * page queue (vm_page_queue[]), regardless of other mutexes or the * busy state of a page. * * - a hash chain mutex is required when associating or disassociating * a page from the VM PAGE CACHE hash table (vm_page_buckets), * regardless of other mutexes or the busy state of a page. * * - either a hash chain mutex OR a busied page is required in order * to modify the page flags. A hash chain mutex must be obtained in * order to busy a page. A page's flags cannot be modified by a * hash chain mutex if the page is marked busy. * * - The object memq mutex is held when inserting or removing * pages from an object (vm_page_insert() or vm_page_remove()). This * is different from the object's main mutex. * * Generally speaking, you have to be aware of side effects when running * vm_page ops. A vm_page_lookup() will return with the hash chain * locked, whether it was able to lookup the page or not. vm_page_free(), * vm_page_cache(), vm_page_activate(), and a number of other routines * will release the hash chain mutex for you. Intermediate manipulation * routines such as vm_page_flag_set() expect the hash chain to be held * on entry and the hash chain will remain held on return. * * pageq scanning can only occur with the pageq in question locked. * We have a known bottleneck with the active queue, but the cache * and free queues are actually arrays already. */ /* * Resident memory management module. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* * Associated with page of user-allocatable memory is a * page structure. */ static struct mtx vm_page_buckets_mtx; static struct vm_page **vm_page_buckets; /* Array of buckets */ static int vm_page_bucket_count; /* How big is array? */ static int vm_page_hash_mask; /* Mask for hash function */ struct mtx vm_page_queue_mtx; struct mtx vm_page_queue_free_mtx; vm_page_t vm_page_array = 0; int vm_page_array_size = 0; long first_page = 0; int vm_page_zero_count = 0; /* * vm_set_page_size: * * Sets the page size, perhaps based upon the memory * size. Must be called before any use of page-size * dependent functions. */ void vm_set_page_size(void) { if (cnt.v_page_size == 0) cnt.v_page_size = PAGE_SIZE; if (((cnt.v_page_size - 1) & cnt.v_page_size) != 0) panic("vm_set_page_size: page size not a power of two"); } /* * vm_page_startup: * * Initializes the resident memory module. * * Allocates memory for the page cells, and * for the object/offset-to-page hash table headers. * Each page cell is initialized and placed on the free list. */ vm_offset_t vm_page_startup(vm_offset_t starta, vm_offset_t enda, vm_offset_t vaddr) { vm_offset_t mapped; struct vm_page **bucket; vm_size_t npages, page_range; vm_offset_t new_end; int i; vm_offset_t pa; int nblocks; vm_offset_t last_pa; /* the biggest memory array is the second group of pages */ vm_offset_t end; vm_offset_t biggestone, biggestsize; vm_offset_t total; vm_size_t bootpages; total = 0; biggestsize = 0; biggestone = 0; nblocks = 0; vaddr = round_page(vaddr); for (i = 0; phys_avail[i + 1]; i += 2) { phys_avail[i] = round_page(phys_avail[i]); phys_avail[i + 1] = trunc_page(phys_avail[i + 1]); } for (i = 0; phys_avail[i + 1]; i += 2) { vm_size_t size = phys_avail[i + 1] - phys_avail[i]; if (size > biggestsize) { biggestone = i; biggestsize = size; } ++nblocks; total += size; } end = phys_avail[biggestone+1]; /* * Initialize the locks. */ mtx_init(&vm_page_queue_mtx, "vm page queue mutex", NULL, MTX_DEF); mtx_init(&vm_page_queue_free_mtx, "vm page queue free mutex", NULL, MTX_SPIN); /* * Initialize the queue headers for the free queue, the active queue * and the inactive queue. */ vm_pageq_init(); /* * Allocate memory for use when boot strapping the kernel memory allocator */ bootpages = UMA_BOOT_PAGES * UMA_SLAB_SIZE; new_end = end - bootpages; new_end = trunc_page(new_end); mapped = pmap_map(&vaddr, new_end, end, VM_PROT_READ | VM_PROT_WRITE); bzero((caddr_t) mapped, end - new_end); uma_startup((caddr_t)mapped); end = new_end; /* * Allocate (and initialize) the hash table buckets. * * The number of buckets MUST BE a power of 2, and the actual value is * the next power of 2 greater than the number of physical pages in * the system. * * We make the hash table approximately 2x the number of pages to * reduce the chain length. This is about the same size using the * singly-linked list as the 1x hash table we were using before * using TAILQ but the chain length will be smaller. * * Note: This computation can be tweaked if desired. */ if (vm_page_bucket_count == 0) { vm_page_bucket_count = 1; while (vm_page_bucket_count < atop(total)) vm_page_bucket_count <<= 1; } vm_page_bucket_count <<= 1; vm_page_hash_mask = vm_page_bucket_count - 1; /* * Validate these addresses. */ new_end = end - vm_page_bucket_count * sizeof(struct vm_page *); new_end = trunc_page(new_end); mapped = pmap_map(&vaddr, new_end, end, VM_PROT_READ | VM_PROT_WRITE); bzero((caddr_t) mapped, end - new_end); mtx_init(&vm_page_buckets_mtx, "vm page buckets mutex", NULL, MTX_SPIN); vm_page_buckets = (struct vm_page **)mapped; bucket = vm_page_buckets; for (i = 0; i < vm_page_bucket_count; i++) { *bucket = NULL; bucket++; } /* * Compute the number of pages of memory that will be available for * use (taking into account the overhead of a page structure per * page). */ first_page = phys_avail[0] / PAGE_SIZE; page_range = phys_avail[(nblocks - 1) * 2 + 1] / PAGE_SIZE - first_page; npages = (total - (page_range * sizeof(struct vm_page)) - (end - new_end)) / PAGE_SIZE; end = new_end; /* * Initialize the mem entry structures now, and put them in the free * queue. */ new_end = trunc_page(end - page_range * sizeof(struct vm_page)); mapped = pmap_map(&vaddr, new_end, end, VM_PROT_READ | VM_PROT_WRITE); vm_page_array = (vm_page_t) mapped; /* * Clear all of the page structures */ bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page)); vm_page_array_size = page_range; /* * Construct the free queue(s) in descending order (by physical * address) so that the first 16MB of physical memory is allocated * last rather than first. On large-memory machines, this avoids * the exhaustion of low physical memory before isa_dmainit has run. */ cnt.v_page_count = 0; cnt.v_free_count = 0; for (i = 0; phys_avail[i + 1] && npages > 0; i += 2) { pa = phys_avail[i]; if (i == biggestone) last_pa = new_end; else last_pa = phys_avail[i + 1]; while (pa < last_pa && npages-- > 0) { vm_pageq_add_new_page(pa); pa += PAGE_SIZE; } } return (vaddr); } /* * vm_page_hash: * * Distributes the object/offset key pair among hash buckets. * * NOTE: This macro depends on vm_page_bucket_count being a power of 2. * This routine may not block. * * We try to randomize the hash based on the object to spread the pages * out in the hash table without it costing us too much. */ static __inline int vm_page_hash(vm_object_t object, vm_pindex_t pindex) { int i = ((uintptr_t)object + pindex) ^ object->hash_rand; return (i & vm_page_hash_mask); } void vm_page_flag_set(vm_page_t m, unsigned short bits) { GIANT_REQUIRED; m->flags |= bits; } void vm_page_flag_clear(vm_page_t m, unsigned short bits) { GIANT_REQUIRED; m->flags &= ~bits; } void vm_page_busy(vm_page_t m) { KASSERT((m->flags & PG_BUSY) == 0, ("vm_page_busy: page already busy!!!")); vm_page_flag_set(m, PG_BUSY); } /* * vm_page_flash: * * wakeup anyone waiting for the page. */ void vm_page_flash(vm_page_t m) { if (m->flags & PG_WANTED) { vm_page_flag_clear(m, PG_WANTED); wakeup(m); } } /* * vm_page_wakeup: * * clear the PG_BUSY flag and wakeup anyone waiting for the * page. * */ void vm_page_wakeup(vm_page_t m) { KASSERT(m->flags & PG_BUSY, ("vm_page_wakeup: page not busy!!!")); vm_page_flag_clear(m, PG_BUSY); vm_page_flash(m); } /* * * */ void vm_page_io_start(vm_page_t m) { GIANT_REQUIRED; m->busy++; } void vm_page_io_finish(vm_page_t m) { GIANT_REQUIRED; m->busy--; if (m->busy == 0) vm_page_flash(m); } /* * Keep page from being freed by the page daemon * much of the same effect as wiring, except much lower * overhead and should be used only for *very* temporary * holding ("wiring"). */ void vm_page_hold(vm_page_t mem) { GIANT_REQUIRED; mem->hold_count++; } void vm_page_unhold(vm_page_t mem) { GIANT_REQUIRED; --mem->hold_count; KASSERT(mem->hold_count >= 0, ("vm_page_unhold: hold count < 0!!!")); if (mem->hold_count == 0 && mem->queue == PQ_HOLD) vm_page_free_toq(mem); } /* * vm_page_protect: * * Reduce the protection of a page. This routine never raises the * protection and therefore can be safely called if the page is already * at VM_PROT_NONE (it will be a NOP effectively ). */ void vm_page_protect(vm_page_t mem, int prot) { if (prot == VM_PROT_NONE) { if (mem->flags & (PG_WRITEABLE|PG_MAPPED)) { pmap_page_protect(mem, VM_PROT_NONE); vm_page_flag_clear(mem, PG_WRITEABLE|PG_MAPPED); } } else if ((prot == VM_PROT_READ) && (mem->flags & PG_WRITEABLE)) { pmap_page_protect(mem, VM_PROT_READ); vm_page_flag_clear(mem, PG_WRITEABLE); } } /* * vm_page_zero_fill: * * Zero-fill the specified page. * Written as a standard pagein routine, to * be used by the zero-fill object. */ boolean_t vm_page_zero_fill(vm_page_t m) { pmap_zero_page(m); return (TRUE); } /* * vm_page_zero_fill_area: * * Like vm_page_zero_fill but only fill the specified area. */ boolean_t vm_page_zero_fill_area(vm_page_t m, int off, int size) { pmap_zero_page_area(m, off, size); return (TRUE); } /* * vm_page_copy: * * Copy one page to another */ void vm_page_copy(vm_page_t src_m, vm_page_t dest_m) { pmap_copy_page(src_m, dest_m); dest_m->valid = VM_PAGE_BITS_ALL; } /* * vm_page_free: * * Free a page * * The clearing of PG_ZERO is a temporary safety until the code can be * reviewed to determine that PG_ZERO is being properly cleared on * write faults or maps. PG_ZERO was previously cleared in * vm_page_alloc(). */ void vm_page_free(vm_page_t m) { vm_page_flag_clear(m, PG_ZERO); vm_page_free_toq(m); vm_page_zero_idle_wakeup(); } /* * vm_page_free_zero: * * Free a page to the zerod-pages queue */ void vm_page_free_zero(vm_page_t m) { vm_page_flag_set(m, PG_ZERO); vm_page_free_toq(m); } /* * vm_page_sleep_busy: * * Wait until page is no longer PG_BUSY or (if also_m_busy is TRUE) * m->busy is zero. Returns TRUE if it had to sleep ( including if * it almost had to sleep and made temporary spl*() mods), FALSE * otherwise. * * This routine assumes that interrupts can only remove the busy * status from a page, not set the busy status or change it from * PG_BUSY to m->busy or vise versa (which would create a timing * window). */ int vm_page_sleep_busy(vm_page_t m, int also_m_busy, const char *msg) { GIANT_REQUIRED; if ((m->flags & PG_BUSY) || (also_m_busy && m->busy)) { int s = splvm(); if ((m->flags & PG_BUSY) || (also_m_busy && m->busy)) { /* * Page is busy. Wait and retry. */ vm_page_flag_set(m, PG_WANTED | PG_REFERENCED); tsleep(m, PVM, msg, 0); } splx(s); return (TRUE); /* not reached */ } return (FALSE); } /* * vm_page_dirty: * * make page all dirty */ void vm_page_dirty(vm_page_t m) { KASSERT(m->queue - m->pc != PQ_CACHE, ("vm_page_dirty: page in cache!")); m->dirty = VM_PAGE_BITS_ALL; } /* * vm_page_undirty: * * Set page to not be dirty. Note: does not clear pmap modify bits */ void vm_page_undirty(vm_page_t m) { m->dirty = 0; } /* * vm_page_insert: [ internal use only ] * * Inserts the given mem entry into the object and object list. * * The pagetables are not updated but will presumably fault the page * in if necessary, or if a kernel page the caller will at some point * enter the page into the kernel's pmap. We are not allowed to block * here so we *can't* do this anyway. * * The object and page must be locked, and must be splhigh. * This routine may not block. */ void vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex) { struct vm_page **bucket; GIANT_REQUIRED; if (m->object != NULL) panic("vm_page_insert: already inserted"); /* * Record the object/offset pair in this page */ m->object = object; m->pindex = pindex; /* * Insert it into the object_object/offset hash table */ bucket = &vm_page_buckets[vm_page_hash(object, pindex)]; mtx_lock_spin(&vm_page_buckets_mtx); m->hnext = *bucket; *bucket = m; mtx_unlock_spin(&vm_page_buckets_mtx); /* * Now link into the object's list of backed pages. */ TAILQ_INSERT_TAIL(&object->memq, m, listq); object->generation++; /* * show that the object has one more resident page. */ object->resident_page_count++; /* * Since we are inserting a new and possibly dirty page, * update the object's OBJ_WRITEABLE and OBJ_MIGHTBEDIRTY flags. */ if (m->flags & PG_WRITEABLE) vm_object_set_writeable_dirty(object); } /* * vm_page_remove: * NOTE: used by device pager as well -wfj * * Removes the given mem entry from the object/offset-page * table and the object page list, but do not invalidate/terminate * the backing store. * * The object and page must be locked, and at splhigh. * The underlying pmap entry (if any) is NOT removed here. * This routine may not block. */ void vm_page_remove(vm_page_t m) { vm_object_t object; vm_page_t *bucket; GIANT_REQUIRED; if (m->object == NULL) return; if ((m->flags & PG_BUSY) == 0) { panic("vm_page_remove: page not busy"); } /* * Basically destroy the page. */ vm_page_wakeup(m); object = m->object; /* * Remove from the object_object/offset hash table. The object * must be on the hash queue, we will panic if it isn't */ bucket = &vm_page_buckets[vm_page_hash(m->object, m->pindex)]; mtx_lock_spin(&vm_page_buckets_mtx); while (*bucket != m) { if (*bucket == NULL) panic("vm_page_remove(): page not found in hash"); bucket = &(*bucket)->hnext; } *bucket = m->hnext; m->hnext = NULL; mtx_unlock_spin(&vm_page_buckets_mtx); /* * Now remove from the object's list of backed pages. */ TAILQ_REMOVE(&object->memq, m, listq); /* * And show that the object has one fewer resident page. */ object->resident_page_count--; object->generation++; m->object = NULL; } /* * vm_page_lookup: * * Returns the page associated with the object/offset * pair specified; if none is found, NULL is returned. * * The object must be locked. No side effects. * This routine may not block. * This is a critical path routine */ vm_page_t vm_page_lookup(vm_object_t object, vm_pindex_t pindex) { vm_page_t m; struct vm_page **bucket; /* * Search the hash table for this object/offset pair */ bucket = &vm_page_buckets[vm_page_hash(object, pindex)]; mtx_lock_spin(&vm_page_buckets_mtx); for (m = *bucket; m != NULL; m = m->hnext) if (m->object == object && m->pindex == pindex) break; mtx_unlock_spin(&vm_page_buckets_mtx); return (m); } /* * vm_page_rename: * * Move the given memory entry from its * current object to the specified target object/offset. * * The object must be locked. * This routine may not block. * * Note: this routine will raise itself to splvm(), the caller need not. * * Note: swap associated with the page must be invalidated by the move. We * have to do this for several reasons: (1) we aren't freeing the * page, (2) we are dirtying the page, (3) the VM system is probably * moving the page from object A to B, and will then later move * the backing store from A to B and we can't have a conflict. * * Note: we *always* dirty the page. It is necessary both for the * fact that we moved it, and because we may be invalidating * swap. If the page is on the cache, we have to deactivate it * or vm_page_dirty() will panic. Dirty pages are not allowed * on the cache. */ void vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex) { int s; s = splvm(); vm_page_lock_queues(); vm_page_remove(m); vm_page_insert(m, new_object, new_pindex); if (m->queue - m->pc == PQ_CACHE) vm_page_deactivate(m); vm_page_dirty(m); vm_page_unlock_queues(); splx(s); } /* * vm_page_select_cache: * * Find a page on the cache queue with color optimization. As pages * might be found, but not applicable, they are deactivated. This * keeps us from using potentially busy cached pages. * * This routine must be called at splvm(). * This routine may not block. */ static vm_page_t vm_page_select_cache(vm_object_t object, vm_pindex_t pindex) { vm_page_t m; mtx_assert(&vm_page_queue_mtx, MA_OWNED); while (TRUE) { m = vm_pageq_find( PQ_CACHE, (pindex + object->pg_color) & PQ_L2_MASK, FALSE ); if (m && ((m->flags & (PG_BUSY|PG_UNMANAGED)) || m->busy || m->hold_count || m->wire_count)) { vm_page_deactivate(m); continue; } return m; } } /* * vm_page_select_free: * * Find a free or zero page, with specified preference. * * This routine must be called at splvm(). * This routine may not block. */ static __inline vm_page_t vm_page_select_free(vm_object_t object, vm_pindex_t pindex, boolean_t prefer_zero) { vm_page_t m; m = vm_pageq_find( PQ_FREE, (pindex + object->pg_color) & PQ_L2_MASK, prefer_zero ); return (m); } /* * vm_page_alloc: * * Allocate and return a memory cell associated * with this VM object/offset pair. * * page_req classes: * VM_ALLOC_NORMAL normal process request * VM_ALLOC_SYSTEM system *really* needs a page * VM_ALLOC_INTERRUPT interrupt time request * VM_ALLOC_ZERO zero page * * This routine may not block. * * Additional special handling is required when called from an * interrupt (VM_ALLOC_INTERRUPT). We are not allowed to mess with * the page cache in this case. */ vm_page_t vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req) { vm_page_t m = NULL; int page_req, s; GIANT_REQUIRED; KASSERT(!vm_page_lookup(object, pindex), ("vm_page_alloc: page already allocated")); page_req = req & VM_ALLOC_CLASS_MASK; /* * The pager is allowed to eat deeper into the free page list. */ if ((curproc == pageproc) && (page_req != VM_ALLOC_INTERRUPT)) { page_req = VM_ALLOC_SYSTEM; }; s = splvm(); loop: mtx_lock_spin(&vm_page_queue_free_mtx); if (cnt.v_free_count > cnt.v_free_reserved) { /* * Allocate from the free queue if there are plenty of pages * in it. */ m = vm_page_select_free(object, pindex, (req & VM_ALLOC_ZERO) != 0); } else if ( (page_req == VM_ALLOC_SYSTEM && cnt.v_cache_count == 0 && cnt.v_free_count > cnt.v_interrupt_free_min) || (page_req == VM_ALLOC_INTERRUPT && cnt.v_free_count > 0) ) { /* * Interrupt or system, dig deeper into the free list. */ m = vm_page_select_free(object, pindex, FALSE); } else if (page_req != VM_ALLOC_INTERRUPT) { mtx_unlock_spin(&vm_page_queue_free_mtx); /* * Allocatable from cache (non-interrupt only). On success, * we must free the page and try again, thus ensuring that * cnt.v_*_free_min counters are replenished. */ vm_page_lock_queues(); if ((m = vm_page_select_cache(object, pindex)) == NULL) { vm_page_unlock_queues(); splx(s); #if defined(DIAGNOSTIC) if (cnt.v_cache_count > 0) printf("vm_page_alloc(NORMAL): missing pages on cache queue: %d\n", cnt.v_cache_count); #endif vm_pageout_deficit++; pagedaemon_wakeup(); return (NULL); } KASSERT(m->dirty == 0, ("Found dirty cache page %p", m)); vm_page_busy(m); vm_page_protect(m, VM_PROT_NONE); vm_page_free(m); vm_page_unlock_queues(); goto loop; } else { /* * Not allocatable from cache from interrupt, give up. */ mtx_unlock_spin(&vm_page_queue_free_mtx); splx(s); vm_pageout_deficit++; pagedaemon_wakeup(); return (NULL); } /* * At this point we had better have found a good page. */ KASSERT( m != NULL, ("vm_page_alloc(): missing page on free queue\n") ); /* * Remove from free queue */ vm_pageq_remove_nowakeup(m); /* * Initialize structure. Only the PG_ZERO flag is inherited. */ if (m->flags & PG_ZERO) { vm_page_zero_count--; m->flags = PG_ZERO | PG_BUSY; } else { m->flags = PG_BUSY; } if (req & VM_ALLOC_WIRED) { cnt.v_wire_count++; m->flags |= PG_MAPPED; /* XXX this does not belong here */ m->wire_count = 1; } else m->wire_count = 0; m->hold_count = 0; m->act_count = 0; m->busy = 0; m->valid = 0; KASSERT(m->dirty == 0, ("vm_page_alloc: free/cache page %p was dirty", m)); mtx_unlock_spin(&vm_page_queue_free_mtx); /* * vm_page_insert() is safe prior to the splx(). Note also that * inserting a page here does not insert it into the pmap (which * could cause us to block allocating memory). We cannot block * anywhere. */ vm_page_insert(m, object, pindex); /* * Don't wakeup too often - wakeup the pageout daemon when * we would be nearly out of memory. */ if (vm_paging_needed()) pagedaemon_wakeup(); splx(s); return (m); } /* * vm_wait: (also see VM_WAIT macro) * * Block until free pages are available for allocation * - Called in various places before memory allocations. */ void vm_wait(void) { int s; s = splvm(); if (curproc == pageproc) { vm_pageout_pages_needed = 1; tsleep(&vm_pageout_pages_needed, PSWP, "VMWait", 0); } else { if (!vm_pages_needed) { vm_pages_needed = 1; wakeup(&vm_pages_needed); } tsleep(&cnt.v_free_count, PVM, "vmwait", 0); } splx(s); } /* * vm_waitpfault: (also see VM_WAITPFAULT macro) * * Block until free pages are available for allocation * - Called only in vm_fault so that processes page faulting * can be easily tracked. * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing * processes will be able to grab memory first. Do not change * this balance without careful testing first. */ void vm_waitpfault(void) { int s; s = splvm(); if (!vm_pages_needed) { vm_pages_needed = 1; wakeup(&vm_pages_needed); } tsleep(&cnt.v_free_count, PUSER, "pfault", 0); splx(s); } /* * vm_page_activate: * * Put the specified page on the active list (if appropriate). * Ensure that act_count is at least ACT_INIT but do not otherwise * mess with it. * * The page queues must be locked. * This routine may not block. */ void vm_page_activate(vm_page_t m) { int s; GIANT_REQUIRED; s = splvm(); if (m->queue != PQ_ACTIVE) { if ((m->queue - m->pc) == PQ_CACHE) cnt.v_reactivated++; vm_pageq_remove(m); if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) { if (m->act_count < ACT_INIT) m->act_count = ACT_INIT; vm_pageq_enqueue(PQ_ACTIVE, m); } } else { if (m->act_count < ACT_INIT) m->act_count = ACT_INIT; } splx(s); } /* * vm_page_free_wakeup: * * Helper routine for vm_page_free_toq() and vm_page_cache(). This * routine is called when a page has been added to the cache or free * queues. * * This routine may not block. * This routine must be called at splvm() */ static __inline void vm_page_free_wakeup(void) { /* * if pageout daemon needs pages, then tell it that there are * some free. */ if (vm_pageout_pages_needed && cnt.v_cache_count + cnt.v_free_count >= cnt.v_pageout_free_min) { wakeup(&vm_pageout_pages_needed); vm_pageout_pages_needed = 0; } /* * wakeup processes that are waiting on memory if we hit a * high water mark. And wakeup scheduler process if we have * lots of memory. this process will swapin processes. */ if (vm_pages_needed && !vm_page_count_min()) { vm_pages_needed = 0; wakeup(&cnt.v_free_count); } } /* * vm_page_free_toq: * * Returns the given page to the PQ_FREE list, * disassociating it with any VM object. * * Object and page must be locked prior to entry. * This routine may not block. */ void vm_page_free_toq(vm_page_t m) { int s; struct vpgqueues *pq; vm_object_t object = m->object; GIANT_REQUIRED; s = splvm(); cnt.v_tfree++; if (m->busy || ((m->queue - m->pc) == PQ_FREE)) { printf( "vm_page_free: pindex(%lu), busy(%d), PG_BUSY(%d), hold(%d)\n", (u_long)m->pindex, m->busy, (m->flags & PG_BUSY) ? 1 : 0, m->hold_count); if ((m->queue - m->pc) == PQ_FREE) panic("vm_page_free: freeing free page"); else panic("vm_page_free: freeing busy page"); } /* * unqueue, then remove page. Note that we cannot destroy * the page here because we do not want to call the pager's * callback routine until after we've put the page on the * appropriate free queue. */ vm_pageq_remove_nowakeup(m); vm_page_remove(m); /* * If fictitious remove object association and * return, otherwise delay object association removal. */ if ((m->flags & PG_FICTITIOUS) != 0) { splx(s); return; } m->valid = 0; vm_page_undirty(m); if (m->wire_count != 0) { if (m->wire_count > 1) { panic("vm_page_free: invalid wire count (%d), pindex: 0x%lx", m->wire_count, (long)m->pindex); } panic("vm_page_free: freeing wired page\n"); } /* * If we've exhausted the object's resident pages we want to free * it up. */ if (object && (object->type == OBJT_VNODE) && ((object->flags & OBJ_DEAD) == 0) ) { struct vnode *vp = (struct vnode *)object->handle; if (vp && VSHOULDFREE(vp)) vfree(vp); } /* * Clear the UNMANAGED flag when freeing an unmanaged page. */ if (m->flags & PG_UNMANAGED) { m->flags &= ~PG_UNMANAGED; } else { #ifdef __alpha__ pmap_page_is_free(m); #endif } if (m->hold_count != 0) { m->flags &= ~PG_ZERO; m->queue = PQ_HOLD; } else m->queue = PQ_FREE + m->pc; pq = &vm_page_queues[m->queue]; mtx_lock_spin(&vm_page_queue_free_mtx); pq->lcnt++; ++(*pq->cnt); /* * Put zero'd pages on the end ( where we look for zero'd pages * first ) and non-zerod pages at the head. */ if (m->flags & PG_ZERO) { TAILQ_INSERT_TAIL(&pq->pl, m, pageq); ++vm_page_zero_count; } else { TAILQ_INSERT_HEAD(&pq->pl, m, pageq); } mtx_unlock_spin(&vm_page_queue_free_mtx); vm_page_free_wakeup(); splx(s); } /* * vm_page_unmanage: * * Prevent PV management from being done on the page. The page is * removed from the paging queues as if it were wired, and as a * consequence of no longer being managed the pageout daemon will not * touch it (since there is no way to locate the pte mappings for the * page). madvise() calls that mess with the pmap will also no longer * operate on the page. * * Beyond that the page is still reasonably 'normal'. Freeing the page * will clear the flag. * * This routine is used by OBJT_PHYS objects - objects using unswappable * physical memory as backing store rather then swap-backed memory and * will eventually be extended to support 4MB unmanaged physical * mappings. */ void vm_page_unmanage(vm_page_t m) { int s; s = splvm(); mtx_assert(&vm_page_queue_mtx, MA_OWNED); if ((m->flags & PG_UNMANAGED) == 0) { if (m->wire_count == 0) vm_pageq_remove(m); } vm_page_flag_set(m, PG_UNMANAGED); splx(s); } /* * vm_page_wire: * * Mark this page as wired down by yet * another map, removing it from paging queues * as necessary. * * The page queues must be locked. * This routine may not block. */ void vm_page_wire(vm_page_t m) { int s; /* * Only bump the wire statistics if the page is not already wired, * and only unqueue the page if it is on some queue (if it is unmanaged * it is already off the queues). */ s = splvm(); mtx_assert(&vm_page_queue_mtx, MA_OWNED); if (m->wire_count == 0) { if ((m->flags & PG_UNMANAGED) == 0) vm_pageq_remove(m); cnt.v_wire_count++; } m->wire_count++; KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m)); splx(s); vm_page_flag_set(m, PG_MAPPED); /* XXX this does not belong here */ } /* * vm_page_unwire: * * Release one wiring of this page, potentially * enabling it to be paged again. * * Many pages placed on the inactive queue should actually go * into the cache, but it is difficult to figure out which. What * we do instead, if the inactive target is well met, is to put * clean pages at the head of the inactive queue instead of the tail. * This will cause them to be moved to the cache more quickly and * if not actively re-referenced, freed more quickly. If we just * stick these pages at the end of the inactive queue, heavy filesystem * meta-data accesses can cause an unnecessary paging load on memory bound * processes. This optimization causes one-time-use metadata to be * reused more quickly. * * BUT, if we are in a low-memory situation we have no choice but to * put clean pages on the cache queue. * * A number of routines use vm_page_unwire() to guarantee that the page * will go into either the inactive or active queues, and will NEVER * be placed in the cache - for example, just after dirtying a page. * dirty pages in the cache are not allowed. * * The page queues must be locked. * This routine may not block. */ void vm_page_unwire(vm_page_t m, int activate) { int s; s = splvm(); mtx_assert(&vm_page_queue_mtx, MA_OWNED); if (m->wire_count > 0) { m->wire_count--; if (m->wire_count == 0) { cnt.v_wire_count--; if (m->flags & PG_UNMANAGED) { ; } else if (activate) vm_pageq_enqueue(PQ_ACTIVE, m); else { vm_page_flag_clear(m, PG_WINATCFLS); vm_pageq_enqueue(PQ_INACTIVE, m); } } } else { panic("vm_page_unwire: invalid wire count: %d\n", m->wire_count); } splx(s); } /* * Move the specified page to the inactive queue. If the page has * any associated swap, the swap is deallocated. * * Normally athead is 0 resulting in LRU operation. athead is set * to 1 if we want this page to be 'as if it were placed in the cache', * except without unmapping it from the process address space. * * This routine may not block. */ static __inline void _vm_page_deactivate(vm_page_t m, int athead) { int s; GIANT_REQUIRED; /* * Ignore if already inactive. */ if (m->queue == PQ_INACTIVE) return; s = splvm(); if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) { if ((m->queue - m->pc) == PQ_CACHE) cnt.v_reactivated++; vm_page_flag_clear(m, PG_WINATCFLS); vm_pageq_remove(m); if (athead) TAILQ_INSERT_HEAD(&vm_page_queues[PQ_INACTIVE].pl, m, pageq); else TAILQ_INSERT_TAIL(&vm_page_queues[PQ_INACTIVE].pl, m, pageq); m->queue = PQ_INACTIVE; vm_page_queues[PQ_INACTIVE].lcnt++; cnt.v_inactive_count++; } splx(s); } void vm_page_deactivate(vm_page_t m) { _vm_page_deactivate(m, 0); } /* * vm_page_try_to_cache: * * Returns 0 on failure, 1 on success */ int vm_page_try_to_cache(vm_page_t m) { GIANT_REQUIRED; if (m->dirty || m->hold_count || m->busy || m->wire_count || (m->flags & (PG_BUSY|PG_UNMANAGED))) { return (0); } vm_page_test_dirty(m); if (m->dirty) return (0); vm_page_cache(m); return (1); } /* * vm_page_try_to_free() * * Attempt to free the page. If we cannot free it, we do nothing. * 1 is returned on success, 0 on failure. */ int vm_page_try_to_free(vm_page_t m) { if (m->dirty || m->hold_count || m->busy || m->wire_count || (m->flags & (PG_BUSY|PG_UNMANAGED))) { return (0); } vm_page_test_dirty(m); if (m->dirty) return (0); vm_page_busy(m); vm_page_protect(m, VM_PROT_NONE); vm_page_free(m); return (1); } /* * vm_page_cache * * Put the specified page onto the page cache queue (if appropriate). * * This routine may not block. */ void vm_page_cache(vm_page_t m) { int s; - GIANT_REQUIRED; + mtx_assert(&vm_page_queue_mtx, MA_OWNED); if ((m->flags & (PG_BUSY|PG_UNMANAGED)) || m->busy || m->wire_count) { printf("vm_page_cache: attempting to cache busy page\n"); return; } if ((m->queue - m->pc) == PQ_CACHE) return; /* * Remove all pmaps and indicate that the page is not * writeable or mapped. */ vm_page_protect(m, VM_PROT_NONE); if (m->dirty != 0) { panic("vm_page_cache: caching a dirty page, pindex: %ld", (long)m->pindex); } s = splvm(); vm_pageq_remove_nowakeup(m); vm_pageq_enqueue(PQ_CACHE + m->pc, m); vm_page_free_wakeup(); splx(s); } /* * vm_page_dontneed * * Cache, deactivate, or do nothing as appropriate. This routine * is typically used by madvise() MADV_DONTNEED. * * Generally speaking we want to move the page into the cache so * it gets reused quickly. However, this can result in a silly syndrome * due to the page recycling too quickly. Small objects will not be * fully cached. On the otherhand, if we move the page to the inactive * queue we wind up with a problem whereby very large objects * unnecessarily blow away our inactive and cache queues. * * The solution is to move the pages based on a fixed weighting. We * either leave them alone, deactivate them, or move them to the cache, * where moving them to the cache has the highest weighting. * By forcing some pages into other queues we eventually force the * system to balance the queues, potentially recovering other unrelated * space from active. The idea is to not force this to happen too * often. */ void vm_page_dontneed(vm_page_t m) { static int dnweight; int dnw; int head; GIANT_REQUIRED; dnw = ++dnweight; /* * occassionally leave the page alone */ if ((dnw & 0x01F0) == 0 || m->queue == PQ_INACTIVE || m->queue - m->pc == PQ_CACHE ) { if (m->act_count >= ACT_INIT) --m->act_count; return; } if (m->dirty == 0) vm_page_test_dirty(m); if (m->dirty || (dnw & 0x0070) == 0) { /* * Deactivate the page 3 times out of 32. */ head = 0; } else { /* * Cache the page 28 times out of every 32. Note that * the page is deactivated instead of cached, but placed * at the head of the queue instead of the tail. */ head = 1; } _vm_page_deactivate(m, head); } /* * Grab a page, waiting until we are waken up due to the page * changing state. We keep on waiting, if the page continues * to be in the object. If the page doesn't exist, allocate it. * * This routine may block. */ vm_page_t vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags) { vm_page_t m; int s, generation; GIANT_REQUIRED; retrylookup: if ((m = vm_page_lookup(object, pindex)) != NULL) { if (m->busy || (m->flags & PG_BUSY)) { generation = object->generation; s = splvm(); while ((object->generation == generation) && (m->busy || (m->flags & PG_BUSY))) { vm_page_flag_set(m, PG_WANTED | PG_REFERENCED); tsleep(m, PVM, "pgrbwt", 0); if ((allocflags & VM_ALLOC_RETRY) == 0) { splx(s); return NULL; } } splx(s); goto retrylookup; } else { vm_page_busy(m); return m; } } m = vm_page_alloc(object, pindex, allocflags & ~VM_ALLOC_RETRY); if (m == NULL) { VM_WAIT; if ((allocflags & VM_ALLOC_RETRY) == 0) return NULL; goto retrylookup; } return m; } /* * Mapping function for valid bits or for dirty bits in * a page. May not block. * * Inputs are required to range within a page. */ __inline int vm_page_bits(int base, int size) { int first_bit; int last_bit; KASSERT( base + size <= PAGE_SIZE, ("vm_page_bits: illegal base/size %d/%d", base, size) ); if (size == 0) /* handle degenerate case */ return (0); first_bit = base >> DEV_BSHIFT; last_bit = (base + size - 1) >> DEV_BSHIFT; return ((2 << last_bit) - (1 << first_bit)); } /* * vm_page_set_validclean: * * Sets portions of a page valid and clean. The arguments are expected * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive * of any partial chunks touched by the range. The invalid portion of * such chunks will be zero'd. * * This routine may not block. * * (base + size) must be less then or equal to PAGE_SIZE. */ void vm_page_set_validclean(vm_page_t m, int base, int size) { int pagebits; int frag; int endoff; GIANT_REQUIRED; if (size == 0) /* handle degenerate case */ return; /* * If the base is not DEV_BSIZE aligned and the valid * bit is clear, we have to zero out a portion of the * first block. */ if ((frag = base & ~(DEV_BSIZE - 1)) != base && (m->valid & (1 << (base >> DEV_BSHIFT))) == 0) pmap_zero_page_area(m, frag, base - frag); /* * If the ending offset is not DEV_BSIZE aligned and the * valid bit is clear, we have to zero out a portion of * the last block. */ endoff = base + size; if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff && (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0) pmap_zero_page_area(m, endoff, DEV_BSIZE - (endoff & (DEV_BSIZE - 1))); /* * Set valid, clear dirty bits. If validating the entire * page we can safely clear the pmap modify bit. We also * use this opportunity to clear the PG_NOSYNC flag. If a process * takes a write fault on a MAP_NOSYNC memory area the flag will * be set again. * * We set valid bits inclusive of any overlap, but we can only * clear dirty bits for DEV_BSIZE chunks that are fully within * the range. */ pagebits = vm_page_bits(base, size); m->valid |= pagebits; #if 0 /* NOT YET */ if ((frag = base & (DEV_BSIZE - 1)) != 0) { frag = DEV_BSIZE - frag; base += frag; size -= frag; if (size < 0) size = 0; } pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1)); #endif m->dirty &= ~pagebits; if (base == 0 && size == PAGE_SIZE) { pmap_clear_modify(m); vm_page_flag_clear(m, PG_NOSYNC); } } #if 0 void vm_page_set_dirty(vm_page_t m, int base, int size) { m->dirty |= vm_page_bits(base, size); } #endif void vm_page_clear_dirty(vm_page_t m, int base, int size) { GIANT_REQUIRED; m->dirty &= ~vm_page_bits(base, size); } /* * vm_page_set_invalid: * * Invalidates DEV_BSIZE'd chunks within a page. Both the * valid and dirty bits for the effected areas are cleared. * * May not block. */ void vm_page_set_invalid(vm_page_t m, int base, int size) { int bits; GIANT_REQUIRED; bits = vm_page_bits(base, size); m->valid &= ~bits; m->dirty &= ~bits; m->object->generation++; } /* * vm_page_zero_invalid() * * The kernel assumes that the invalid portions of a page contain * garbage, but such pages can be mapped into memory by user code. * When this occurs, we must zero out the non-valid portions of the * page so user code sees what it expects. * * Pages are most often semi-valid when the end of a file is mapped * into memory and the file's size is not page aligned. */ void vm_page_zero_invalid(vm_page_t m, boolean_t setvalid) { int b; int i; /* * Scan the valid bits looking for invalid sections that * must be zerod. Invalid sub-DEV_BSIZE'd areas ( where the * valid bit may be set ) have already been zerod by * vm_page_set_validclean(). */ for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) { if (i == (PAGE_SIZE / DEV_BSIZE) || (m->valid & (1 << i)) ) { if (i > b) { pmap_zero_page_area(m, b << DEV_BSHIFT, (i - b) << DEV_BSHIFT); } b = i + 1; } } /* * setvalid is TRUE when we can safely set the zero'd areas * as being valid. We can do this if there are no cache consistancy * issues. e.g. it is ok to do with UFS, but not ok to do with NFS. */ if (setvalid) m->valid = VM_PAGE_BITS_ALL; } /* * vm_page_is_valid: * * Is (partial) page valid? Note that the case where size == 0 * will return FALSE in the degenerate case where the page is * entirely invalid, and TRUE otherwise. * * May not block. */ int vm_page_is_valid(vm_page_t m, int base, int size) { int bits = vm_page_bits(base, size); if (m->valid && ((m->valid & bits) == bits)) return 1; else return 0; } /* * update dirty bits from pmap/mmu. May not block. */ void vm_page_test_dirty(vm_page_t m) { if ((m->dirty != VM_PAGE_BITS_ALL) && pmap_is_modified(m)) { vm_page_dirty(m); } } int so_zerocp_fullpage = 0; void vm_page_cowfault(vm_page_t m) { vm_page_t mnew; vm_object_t object; vm_pindex_t pindex; object = m->object; pindex = m->pindex; vm_page_busy(m); retry_alloc: vm_page_remove(m); mnew = vm_page_alloc(object, pindex, VM_ALLOC_NORMAL); if (mnew == NULL) { vm_page_insert(m, object, pindex); VM_WAIT; goto retry_alloc; } if (m->cow == 0) { /* * check to see if we raced with an xmit complete when * waiting to allocate a page. If so, put things back * the way they were */ vm_page_busy(mnew); vm_page_free(mnew); vm_page_insert(m, object, pindex); } else { /* clear COW & copy page */ if (so_zerocp_fullpage) { mnew->valid = VM_PAGE_BITS_ALL; } else { vm_page_copy(m, mnew); } vm_page_dirty(mnew); vm_page_flag_clear(mnew, PG_BUSY); } } void vm_page_cowclear(vm_page_t m) { /* XXX KDM find out if giant is required here. */ GIANT_REQUIRED; if (m->cow) { atomic_subtract_int(&m->cow, 1); /* * let vm_fault add back write permission lazily */ } /* * sf_buf_free() will free the page, so we needn't do it here */ } void vm_page_cowsetup(vm_page_t m) { /* XXX KDM find out if giant is required here */ GIANT_REQUIRED; atomic_add_int(&m->cow, 1); vm_page_protect(m, VM_PROT_READ); } #include "opt_ddb.h" #ifdef DDB #include #include DB_SHOW_COMMAND(page, vm_page_print_page_info) { db_printf("cnt.v_free_count: %d\n", cnt.v_free_count); db_printf("cnt.v_cache_count: %d\n", cnt.v_cache_count); db_printf("cnt.v_inactive_count: %d\n", cnt.v_inactive_count); db_printf("cnt.v_active_count: %d\n", cnt.v_active_count); db_printf("cnt.v_wire_count: %d\n", cnt.v_wire_count); db_printf("cnt.v_free_reserved: %d\n", cnt.v_free_reserved); db_printf("cnt.v_free_min: %d\n", cnt.v_free_min); db_printf("cnt.v_free_target: %d\n", cnt.v_free_target); db_printf("cnt.v_cache_min: %d\n", cnt.v_cache_min); db_printf("cnt.v_inactive_target: %d\n", cnt.v_inactive_target); } DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info) { int i; db_printf("PQ_FREE:"); for (i = 0; i < PQ_L2_SIZE; i++) { db_printf(" %d", vm_page_queues[PQ_FREE + i].lcnt); } db_printf("\n"); db_printf("PQ_CACHE:"); for (i = 0; i < PQ_L2_SIZE; i++) { db_printf(" %d", vm_page_queues[PQ_CACHE + i].lcnt); } db_printf("\n"); db_printf("PQ_ACTIVE: %d, PQ_INACTIVE: %d\n", vm_page_queues[PQ_ACTIVE].lcnt, vm_page_queues[PQ_INACTIVE].lcnt); } #endif /* DDB */ diff --git a/sys/vm/vm_pageout.c b/sys/vm/vm_pageout.c index 7dce8e890ae8..047fac1ca1c8 100644 --- a/sys/vm/vm_pageout.c +++ b/sys/vm/vm_pageout.c @@ -1,1529 +1,1531 @@ /* * Copyright (c) 1991 Regents of the University of California. * All rights reserved. * Copyright (c) 1994 John S. Dyson * All rights reserved. * Copyright (c) 1994 David Greenman * All rights reserved. * * This code is derived from software contributed to Berkeley by * The Mach Operating System project at Carnegie-Mellon University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * from: @(#)vm_pageout.c 7.4 (Berkeley) 5/7/91 * * * Copyright (c) 1987, 1990 Carnegie-Mellon University. * All rights reserved. * * Authors: Avadis Tevanian, Jr., Michael Wayne Young * * Permission to use, copy, modify and distribute this software and * its documentation is hereby granted, provided that both the copyright * notice and this permission notice appear in all copies of the * software, derivative works or modified versions, and any portions * thereof, and that both notices appear in supporting documentation. * * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE. * * Carnegie Mellon requests users of this software to return to * * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU * School of Computer Science * Carnegie Mellon University * Pittsburgh PA 15213-3890 * * any improvements or extensions that they make and grant Carnegie the * rights to redistribute these changes. * * $FreeBSD$ */ /* * The proverbial page-out daemon. */ #include "opt_vm.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* * System initialization */ /* the kernel process "vm_pageout"*/ static void vm_pageout(void); static int vm_pageout_clean(vm_page_t); static void vm_pageout_scan(int pass); static int vm_pageout_free_page_calc(vm_size_t count); struct proc *pageproc; static struct kproc_desc page_kp = { "pagedaemon", vm_pageout, &pageproc }; SYSINIT(pagedaemon, SI_SUB_KTHREAD_PAGE, SI_ORDER_FIRST, kproc_start, &page_kp) #if !defined(NO_SWAPPING) /* the kernel process "vm_daemon"*/ static void vm_daemon(void); static struct proc *vmproc; static struct kproc_desc vm_kp = { "vmdaemon", vm_daemon, &vmproc }; SYSINIT(vmdaemon, SI_SUB_KTHREAD_VM, SI_ORDER_FIRST, kproc_start, &vm_kp) #endif int vm_pages_needed=0; /* Event on which pageout daemon sleeps */ int vm_pageout_deficit=0; /* Estimated number of pages deficit */ int vm_pageout_pages_needed=0; /* flag saying that the pageout daemon needs pages */ #if !defined(NO_SWAPPING) static int vm_pageout_req_swapout; /* XXX */ static int vm_daemon_needed; #endif extern int vm_swap_size; static int vm_max_launder = 32; static int vm_pageout_stats_max=0, vm_pageout_stats_interval = 0; static int vm_pageout_full_stats_interval = 0; static int vm_pageout_stats_free_max=0, vm_pageout_algorithm=0; static int defer_swap_pageouts=0; static int disable_swap_pageouts=0; #if defined(NO_SWAPPING) static int vm_swap_enabled=0; static int vm_swap_idle_enabled=0; #else static int vm_swap_enabled=1; static int vm_swap_idle_enabled=0; #endif SYSCTL_INT(_vm, VM_PAGEOUT_ALGORITHM, pageout_algorithm, CTLFLAG_RW, &vm_pageout_algorithm, 0, "LRU page mgmt"); SYSCTL_INT(_vm, OID_AUTO, max_launder, CTLFLAG_RW, &vm_max_launder, 0, "Limit dirty flushes in pageout"); SYSCTL_INT(_vm, OID_AUTO, pageout_stats_max, CTLFLAG_RW, &vm_pageout_stats_max, 0, "Max pageout stats scan length"); SYSCTL_INT(_vm, OID_AUTO, pageout_full_stats_interval, CTLFLAG_RW, &vm_pageout_full_stats_interval, 0, "Interval for full stats scan"); SYSCTL_INT(_vm, OID_AUTO, pageout_stats_interval, CTLFLAG_RW, &vm_pageout_stats_interval, 0, "Interval for partial stats scan"); SYSCTL_INT(_vm, OID_AUTO, pageout_stats_free_max, CTLFLAG_RW, &vm_pageout_stats_free_max, 0, "Not implemented"); #if defined(NO_SWAPPING) SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled, CTLFLAG_RD, &vm_swap_enabled, 0, ""); SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled, CTLFLAG_RD, &vm_swap_idle_enabled, 0, ""); #else SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled, CTLFLAG_RW, &vm_swap_enabled, 0, "Enable entire process swapout"); SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled, CTLFLAG_RW, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria"); #endif SYSCTL_INT(_vm, OID_AUTO, defer_swapspace_pageouts, CTLFLAG_RW, &defer_swap_pageouts, 0, "Give preference to dirty pages in mem"); SYSCTL_INT(_vm, OID_AUTO, disable_swapspace_pageouts, CTLFLAG_RW, &disable_swap_pageouts, 0, "Disallow swapout of dirty pages"); static int pageout_lock_miss; SYSCTL_INT(_vm, OID_AUTO, pageout_lock_miss, CTLFLAG_RD, &pageout_lock_miss, 0, "vget() lock misses during pageout"); #define VM_PAGEOUT_PAGE_COUNT 16 int vm_pageout_page_count = VM_PAGEOUT_PAGE_COUNT; int vm_page_max_wired; /* XXX max # of wired pages system-wide */ #if !defined(NO_SWAPPING) typedef void freeer_fcn_t(vm_map_t, vm_object_t, vm_pindex_t, int); static void vm_pageout_map_deactivate_pages(vm_map_t, vm_pindex_t); static freeer_fcn_t vm_pageout_object_deactivate_pages; static void vm_req_vmdaemon(void); #endif static void vm_pageout_page_stats(void); /* * vm_pageout_clean: * * Clean the page and remove it from the laundry. * * We set the busy bit to cause potential page faults on this page to * block. Note the careful timing, however, the busy bit isn't set till * late and we cannot do anything that will mess with the page. */ static int vm_pageout_clean(m) vm_page_t m; { vm_object_t object; vm_page_t mc[2*vm_pageout_page_count]; int pageout_count; int ib, is, page_base; vm_pindex_t pindex = m->pindex; GIANT_REQUIRED; object = m->object; /* * It doesn't cost us anything to pageout OBJT_DEFAULT or OBJT_SWAP * with the new swapper, but we could have serious problems paging * out other object types if there is insufficient memory. * * Unfortunately, checking free memory here is far too late, so the * check has been moved up a procedural level. */ /* * Don't mess with the page if it's busy, held, or special */ if ((m->hold_count != 0) || ((m->busy != 0) || (m->flags & (PG_BUSY|PG_UNMANAGED)))) { return 0; } mc[vm_pageout_page_count] = m; pageout_count = 1; page_base = vm_pageout_page_count; ib = 1; is = 1; /* * Scan object for clusterable pages. * * We can cluster ONLY if: ->> the page is NOT * clean, wired, busy, held, or mapped into a * buffer, and one of the following: * 1) The page is inactive, or a seldom used * active page. * -or- * 2) we force the issue. * * During heavy mmap/modification loads the pageout * daemon can really fragment the underlying file * due to flushing pages out of order and not trying * align the clusters (which leave sporatic out-of-order * holes). To solve this problem we do the reverse scan * first and attempt to align our cluster, then do a * forward scan if room remains. */ more: while (ib && pageout_count < vm_pageout_page_count) { vm_page_t p; if (ib > pindex) { ib = 0; break; } if ((p = vm_page_lookup(object, pindex - ib)) == NULL) { ib = 0; break; } if (((p->queue - p->pc) == PQ_CACHE) || (p->flags & (PG_BUSY|PG_UNMANAGED)) || p->busy) { ib = 0; break; } vm_page_test_dirty(p); if ((p->dirty & p->valid) == 0 || p->queue != PQ_INACTIVE || p->wire_count != 0 || /* may be held by buf cache */ p->hold_count != 0) { /* may be undergoing I/O */ ib = 0; break; } mc[--page_base] = p; ++pageout_count; ++ib; /* * alignment boundry, stop here and switch directions. Do * not clear ib. */ if ((pindex - (ib - 1)) % vm_pageout_page_count == 0) break; } while (pageout_count < vm_pageout_page_count && pindex + is < object->size) { vm_page_t p; if ((p = vm_page_lookup(object, pindex + is)) == NULL) break; if (((p->queue - p->pc) == PQ_CACHE) || (p->flags & (PG_BUSY|PG_UNMANAGED)) || p->busy) { break; } vm_page_test_dirty(p); if ((p->dirty & p->valid) == 0 || p->queue != PQ_INACTIVE || p->wire_count != 0 || /* may be held by buf cache */ p->hold_count != 0) { /* may be undergoing I/O */ break; } mc[page_base + pageout_count] = p; ++pageout_count; ++is; } /* * If we exhausted our forward scan, continue with the reverse scan * when possible, even past a page boundry. This catches boundry * conditions. */ if (ib && pageout_count < vm_pageout_page_count) goto more; /* * we allow reads during pageouts... */ return vm_pageout_flush(&mc[page_base], pageout_count, 0); } /* * vm_pageout_flush() - launder the given pages * * The given pages are laundered. Note that we setup for the start of * I/O ( i.e. busy the page ), mark it read-only, and bump the object * reference count all in here rather then in the parent. If we want * the parent to do more sophisticated things we may have to change * the ordering. */ int vm_pageout_flush(mc, count, flags) vm_page_t *mc; int count; int flags; { vm_object_t object; int pageout_status[count]; int numpagedout = 0; int i; GIANT_REQUIRED; /* * Initiate I/O. Bump the vm_page_t->busy counter and * mark the pages read-only. * * We do not have to fixup the clean/dirty bits here... we can * allow the pager to do it after the I/O completes. * * NOTE! mc[i]->dirty may be partial or fragmented due to an * edge case with file fragments. */ for (i = 0; i < count; i++) { KASSERT(mc[i]->valid == VM_PAGE_BITS_ALL, ("vm_pageout_flush page %p index %d/%d: partially invalid page", mc[i], i, count)); vm_page_io_start(mc[i]); vm_page_protect(mc[i], VM_PROT_READ); } object = mc[0]->object; vm_object_pip_add(object, count); vm_pager_put_pages(object, mc, count, (flags | ((object == kernel_object) ? OBJPC_SYNC : 0)), pageout_status); for (i = 0; i < count; i++) { vm_page_t mt = mc[i]; switch (pageout_status[i]) { case VM_PAGER_OK: numpagedout++; break; case VM_PAGER_PEND: numpagedout++; break; case VM_PAGER_BAD: /* * Page outside of range of object. Right now we * essentially lose the changes by pretending it * worked. */ pmap_clear_modify(mt); vm_page_undirty(mt); break; case VM_PAGER_ERROR: case VM_PAGER_FAIL: /* * If page couldn't be paged out, then reactivate the * page so it doesn't clog the inactive list. (We * will try paging out it again later). */ vm_page_activate(mt); break; case VM_PAGER_AGAIN: break; } /* * If the operation is still going, leave the page busy to * block all other accesses. Also, leave the paging in * progress indicator set so that we don't attempt an object * collapse. */ if (pageout_status[i] != VM_PAGER_PEND) { vm_object_pip_wakeup(object); vm_page_io_finish(mt); if (!vm_page_count_severe() || !vm_page_try_to_cache(mt)) vm_page_protect(mt, VM_PROT_READ); } } return numpagedout; } #if !defined(NO_SWAPPING) /* * vm_pageout_object_deactivate_pages * * deactivate enough pages to satisfy the inactive target * requirements or if vm_page_proc_limit is set, then * deactivate all of the pages in the object and its * backing_objects. * * The object and map must be locked. */ static void vm_pageout_object_deactivate_pages(map, object, desired, map_remove_only) vm_map_t map; vm_object_t object; vm_pindex_t desired; int map_remove_only; { vm_page_t p, next; int rcount; int remove_mode; GIANT_REQUIRED; if (object->type == OBJT_DEVICE || object->type == OBJT_PHYS) return; while (object) { if (pmap_resident_count(vm_map_pmap(map)) <= desired) return; if (object->paging_in_progress) return; remove_mode = map_remove_only; if (object->shadow_count > 1) remove_mode = 1; /* * scan the objects entire memory queue */ rcount = object->resident_page_count; p = TAILQ_FIRST(&object->memq); while (p && (rcount-- > 0)) { int actcount; if (pmap_resident_count(vm_map_pmap(map)) <= desired) return; next = TAILQ_NEXT(p, listq); cnt.v_pdpages++; if (p->wire_count != 0 || p->hold_count != 0 || p->busy != 0 || (p->flags & (PG_BUSY|PG_UNMANAGED)) || !pmap_page_exists_quick(vm_map_pmap(map), p)) { p = next; continue; } actcount = pmap_ts_referenced(p); if (actcount) { vm_page_flag_set(p, PG_REFERENCED); } else if (p->flags & PG_REFERENCED) { actcount = 1; } if ((p->queue != PQ_ACTIVE) && (p->flags & PG_REFERENCED)) { vm_page_activate(p); p->act_count += actcount; vm_page_flag_clear(p, PG_REFERENCED); } else if (p->queue == PQ_ACTIVE) { if ((p->flags & PG_REFERENCED) == 0) { p->act_count -= min(p->act_count, ACT_DECLINE); if (!remove_mode && (vm_pageout_algorithm || (p->act_count == 0))) { vm_page_protect(p, VM_PROT_NONE); vm_page_deactivate(p); } else { vm_pageq_requeue(p); } } else { vm_page_activate(p); vm_page_flag_clear(p, PG_REFERENCED); if (p->act_count < (ACT_MAX - ACT_ADVANCE)) p->act_count += ACT_ADVANCE; vm_pageq_requeue(p); } } else if (p->queue == PQ_INACTIVE) { vm_page_protect(p, VM_PROT_NONE); } p = next; } object = object->backing_object; } return; } /* * deactivate some number of pages in a map, try to do it fairly, but * that is really hard to do. */ static void vm_pageout_map_deactivate_pages(map, desired) vm_map_t map; vm_pindex_t desired; { vm_map_entry_t tmpe; vm_object_t obj, bigobj; int nothingwired; GIANT_REQUIRED; if (!vm_map_trylock(map)) return; bigobj = NULL; nothingwired = TRUE; /* * first, search out the biggest object, and try to free pages from * that. */ tmpe = map->header.next; while (tmpe != &map->header) { if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) { obj = tmpe->object.vm_object; if ((obj != NULL) && (obj->shadow_count <= 1) && ((bigobj == NULL) || (bigobj->resident_page_count < obj->resident_page_count))) { bigobj = obj; } } if (tmpe->wired_count > 0) nothingwired = FALSE; tmpe = tmpe->next; } if (bigobj) vm_pageout_object_deactivate_pages(map, bigobj, desired, 0); /* * Next, hunt around for other pages to deactivate. We actually * do this search sort of wrong -- .text first is not the best idea. */ tmpe = map->header.next; while (tmpe != &map->header) { if (pmap_resident_count(vm_map_pmap(map)) <= desired) break; if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) { obj = tmpe->object.vm_object; if (obj) vm_pageout_object_deactivate_pages(map, obj, desired, 0); } tmpe = tmpe->next; }; /* * Remove all mappings if a process is swapped out, this will free page * table pages. */ if (desired == 0 && nothingwired) pmap_remove(vm_map_pmap(map), VM_MIN_ADDRESS, VM_MAXUSER_ADDRESS); vm_map_unlock(map); return; } #endif /* !defined(NO_SWAPPING) */ /* * Don't try to be fancy - being fancy can lead to VOP_LOCK's and therefore * to vnode deadlocks. We only do it for OBJT_DEFAULT and OBJT_SWAP objects * which we know can be trivially freed. */ void vm_pageout_page_free(vm_page_t m) { vm_object_t object = m->object; int type = object->type; GIANT_REQUIRED; if (type == OBJT_SWAP || type == OBJT_DEFAULT) vm_object_reference(object); vm_page_busy(m); vm_page_protect(m, VM_PROT_NONE); vm_page_free(m); if (type == OBJT_SWAP || type == OBJT_DEFAULT) vm_object_deallocate(object); } /* * vm_pageout_scan does the dirty work for the pageout daemon. */ static void vm_pageout_scan(int pass) { vm_page_t m, next; struct vm_page marker; int save_page_shortage; int save_inactive_count; int page_shortage, maxscan, pcount; int addl_page_shortage, addl_page_shortage_init; struct proc *p, *bigproc; vm_offset_t size, bigsize; vm_object_t object; int actcount; int vnodes_skipped = 0; int maxlaunder; int s; struct thread *td; GIANT_REQUIRED; /* * Do whatever cleanup that the pmap code can. */ pmap_collect(); uma_reclaim(); addl_page_shortage_init = vm_pageout_deficit; vm_pageout_deficit = 0; /* * Calculate the number of pages we want to either free or move * to the cache. */ page_shortage = vm_paging_target() + addl_page_shortage_init; save_page_shortage = page_shortage; save_inactive_count = cnt.v_inactive_count; /* * Initialize our marker */ bzero(&marker, sizeof(marker)); marker.flags = PG_BUSY | PG_FICTITIOUS | PG_MARKER; marker.queue = PQ_INACTIVE; marker.wire_count = 1; /* * Start scanning the inactive queue for pages we can move to the * cache or free. The scan will stop when the target is reached or * we have scanned the entire inactive queue. Note that m->act_count * is not used to form decisions for the inactive queue, only for the * active queue. * * maxlaunder limits the number of dirty pages we flush per scan. * For most systems a smaller value (16 or 32) is more robust under * extreme memory and disk pressure because any unnecessary writes * to disk can result in extreme performance degredation. However, * systems with excessive dirty pages (especially when MAP_NOSYNC is * used) will die horribly with limited laundering. If the pageout * daemon cannot clean enough pages in the first pass, we let it go * all out in succeeding passes. */ if ((maxlaunder = vm_max_launder) <= 1) maxlaunder = 1; if (pass) maxlaunder = 10000; rescan0: addl_page_shortage = addl_page_shortage_init; maxscan = cnt.v_inactive_count; for (m = TAILQ_FIRST(&vm_page_queues[PQ_INACTIVE].pl); m != NULL && maxscan-- > 0 && page_shortage > 0; m = next) { cnt.v_pdpages++; if (m->queue != PQ_INACTIVE) { goto rescan0; } next = TAILQ_NEXT(m, pageq); /* * skip marker pages */ if (m->flags & PG_MARKER) continue; /* * A held page may be undergoing I/O, so skip it. */ if (m->hold_count) { vm_pageq_requeue(m); addl_page_shortage++; continue; } /* * Don't mess with busy pages, keep in the front of the * queue, most likely are being paged out. */ if (m->busy || (m->flags & PG_BUSY)) { addl_page_shortage++; continue; } /* * If the object is not being used, we ignore previous * references. */ if (m->object->ref_count == 0) { vm_page_flag_clear(m, PG_REFERENCED); pmap_clear_reference(m); /* * Otherwise, if the page has been referenced while in the * inactive queue, we bump the "activation count" upwards, * making it less likely that the page will be added back to * the inactive queue prematurely again. Here we check the * page tables (or emulated bits, if any), given the upper * level VM system not knowing anything about existing * references. */ } else if (((m->flags & PG_REFERENCED) == 0) && (actcount = pmap_ts_referenced(m))) { vm_page_activate(m); m->act_count += (actcount + ACT_ADVANCE); continue; } /* * If the upper level VM system knows about any page * references, we activate the page. We also set the * "activation count" higher than normal so that we will less * likely place pages back onto the inactive queue again. */ if ((m->flags & PG_REFERENCED) != 0) { vm_page_flag_clear(m, PG_REFERENCED); actcount = pmap_ts_referenced(m); vm_page_activate(m); m->act_count += (actcount + ACT_ADVANCE + 1); continue; } /* * If the upper level VM system doesn't know anything about * the page being dirty, we have to check for it again. As * far as the VM code knows, any partially dirty pages are * fully dirty. */ if (m->dirty == 0) { vm_page_test_dirty(m); } else { vm_page_dirty(m); } /* * Invalid pages can be easily freed */ if (m->valid == 0) { vm_pageout_page_free(m); cnt.v_dfree++; --page_shortage; /* * Clean pages can be placed onto the cache queue. This * effectively frees them. */ } else if (m->dirty == 0) { + vm_page_lock_queues(); vm_page_cache(m); + vm_page_unlock_queues(); --page_shortage; } else if ((m->flags & PG_WINATCFLS) == 0 && pass == 0) { /* * Dirty pages need to be paged out, but flushing * a page is extremely expensive verses freeing * a clean page. Rather then artificially limiting * the number of pages we can flush, we instead give * dirty pages extra priority on the inactive queue * by forcing them to be cycled through the queue * twice before being flushed, after which the * (now clean) page will cycle through once more * before being freed. This significantly extends * the thrash point for a heavily loaded machine. */ vm_page_flag_set(m, PG_WINATCFLS); vm_pageq_requeue(m); } else if (maxlaunder > 0) { /* * We always want to try to flush some dirty pages if * we encounter them, to keep the system stable. * Normally this number is small, but under extreme * pressure where there are insufficient clean pages * on the inactive queue, we may have to go all out. */ int swap_pageouts_ok; struct vnode *vp = NULL; struct mount *mp; object = m->object; if ((object->type != OBJT_SWAP) && (object->type != OBJT_DEFAULT)) { swap_pageouts_ok = 1; } else { swap_pageouts_ok = !(defer_swap_pageouts || disable_swap_pageouts); swap_pageouts_ok |= (!disable_swap_pageouts && defer_swap_pageouts && vm_page_count_min()); } /* * We don't bother paging objects that are "dead". * Those objects are in a "rundown" state. */ if (!swap_pageouts_ok || (object->flags & OBJ_DEAD)) { vm_pageq_requeue(m); continue; } /* * The object is already known NOT to be dead. It * is possible for the vget() to block the whole * pageout daemon, but the new low-memory handling * code should prevent it. * * The previous code skipped locked vnodes and, worse, * reordered pages in the queue. This results in * completely non-deterministic operation and, on a * busy system, can lead to extremely non-optimal * pageouts. For example, it can cause clean pages * to be freed and dirty pages to be moved to the end * of the queue. Since dirty pages are also moved to * the end of the queue once-cleaned, this gives * way too large a weighting to defering the freeing * of dirty pages. * * We can't wait forever for the vnode lock, we might * deadlock due to a vn_read() getting stuck in * vm_wait while holding this vnode. We skip the * vnode if we can't get it in a reasonable amount * of time. */ if (object->type == OBJT_VNODE) { vp = object->handle; mp = NULL; if (vp->v_type == VREG) vn_start_write(vp, &mp, V_NOWAIT); if (vget(vp, LK_EXCLUSIVE|LK_NOOBJ|LK_TIMELOCK, curthread)) { ++pageout_lock_miss; vn_finished_write(mp); if (object->flags & OBJ_MIGHTBEDIRTY) vnodes_skipped++; continue; } /* * The page might have been moved to another * queue during potential blocking in vget() * above. The page might have been freed and * reused for another vnode. The object might * have been reused for another vnode. */ if (m->queue != PQ_INACTIVE || m->object != object || object->handle != vp) { if (object->flags & OBJ_MIGHTBEDIRTY) vnodes_skipped++; vput(vp); vn_finished_write(mp); continue; } /* * The page may have been busied during the * blocking in vput(); We don't move the * page back onto the end of the queue so that * statistics are more correct if we don't. */ if (m->busy || (m->flags & PG_BUSY)) { vput(vp); vn_finished_write(mp); continue; } /* * If the page has become held it might * be undergoing I/O, so skip it */ if (m->hold_count) { vm_pageq_requeue(m); if (object->flags & OBJ_MIGHTBEDIRTY) vnodes_skipped++; vput(vp); vn_finished_write(mp); continue; } } /* * If a page is dirty, then it is either being washed * (but not yet cleaned) or it is still in the * laundry. If it is still in the laundry, then we * start the cleaning operation. * * This operation may cluster, invalidating the 'next' * pointer. To prevent an inordinate number of * restarts we use our marker to remember our place. * * decrement page_shortage on success to account for * the (future) cleaned page. Otherwise we could wind * up laundering or cleaning too many pages. */ s = splvm(); TAILQ_INSERT_AFTER(&vm_page_queues[PQ_INACTIVE].pl, m, &marker, pageq); splx(s); if (vm_pageout_clean(m) != 0) { --page_shortage; --maxlaunder; } s = splvm(); next = TAILQ_NEXT(&marker, pageq); TAILQ_REMOVE(&vm_page_queues[PQ_INACTIVE].pl, &marker, pageq); splx(s); if (vp) { vput(vp); vn_finished_write(mp); } } } /* * Compute the number of pages we want to try to move from the * active queue to the inactive queue. */ page_shortage = vm_paging_target() + cnt.v_inactive_target - cnt.v_inactive_count; page_shortage += addl_page_shortage; vm_page_lock_queues(); /* * Scan the active queue for things we can deactivate. We nominally * track the per-page activity counter and use it to locate * deactivation candidates. */ pcount = cnt.v_active_count; m = TAILQ_FIRST(&vm_page_queues[PQ_ACTIVE].pl); while ((m != NULL) && (pcount-- > 0) && (page_shortage > 0)) { /* * This is a consistency check, and should likely be a panic * or warning. */ if (m->queue != PQ_ACTIVE) { break; } next = TAILQ_NEXT(m, pageq); /* * Don't deactivate pages that are busy. */ if ((m->busy != 0) || (m->flags & PG_BUSY) || (m->hold_count != 0)) { vm_pageq_requeue(m); m = next; continue; } /* * The count for pagedaemon pages is done after checking the * page for eligibility... */ cnt.v_pdpages++; /* * Check to see "how much" the page has been used. */ actcount = 0; if (m->object->ref_count != 0) { if (m->flags & PG_REFERENCED) { actcount += 1; } actcount += pmap_ts_referenced(m); if (actcount) { m->act_count += ACT_ADVANCE + actcount; if (m->act_count > ACT_MAX) m->act_count = ACT_MAX; } } /* * Since we have "tested" this bit, we need to clear it now. */ vm_page_flag_clear(m, PG_REFERENCED); /* * Only if an object is currently being used, do we use the * page activation count stats. */ if (actcount && (m->object->ref_count != 0)) { vm_pageq_requeue(m); } else { m->act_count -= min(m->act_count, ACT_DECLINE); if (vm_pageout_algorithm || m->object->ref_count == 0 || m->act_count == 0) { page_shortage--; if (m->object->ref_count == 0) { vm_page_protect(m, VM_PROT_NONE); if (m->dirty == 0) vm_page_cache(m); else vm_page_deactivate(m); } else { vm_page_deactivate(m); } } else { vm_pageq_requeue(m); } } m = next; } vm_page_unlock_queues(); s = splvm(); /* * We try to maintain some *really* free pages, this allows interrupt * code to be guaranteed space. Since both cache and free queues * are considered basically 'free', moving pages from cache to free * does not effect other calculations. */ while (cnt.v_free_count < cnt.v_free_reserved) { static int cache_rover = 0; m = vm_pageq_find(PQ_CACHE, cache_rover, FALSE); if (!m) break; if ((m->flags & (PG_BUSY|PG_UNMANAGED)) || m->busy || m->hold_count || m->wire_count) { #ifdef INVARIANTS printf("Warning: busy page %p found in cache\n", m); #endif vm_page_deactivate(m); continue; } cache_rover = (cache_rover + PQ_PRIME2) & PQ_L2_MASK; vm_pageout_page_free(m); cnt.v_dfree++; } splx(s); #if !defined(NO_SWAPPING) /* * Idle process swapout -- run once per second. */ if (vm_swap_idle_enabled) { static long lsec; if (time_second != lsec) { vm_pageout_req_swapout |= VM_SWAP_IDLE; vm_req_vmdaemon(); lsec = time_second; } } #endif /* * If we didn't get enough free pages, and we have skipped a vnode * in a writeable object, wakeup the sync daemon. And kick swapout * if we did not get enough free pages. */ if (vm_paging_target() > 0) { if (vnodes_skipped && vm_page_count_min()) (void) speedup_syncer(); #if !defined(NO_SWAPPING) if (vm_swap_enabled && vm_page_count_target()) { vm_req_vmdaemon(); vm_pageout_req_swapout |= VM_SWAP_NORMAL; } #endif } /* * If we are out of swap and were not able to reach our paging * target, kill the largest process. * * We keep the process bigproc locked once we find it to keep anyone * from messing with it; however, there is a possibility of * deadlock if process B is bigproc and one of it's child processes * attempts to propagate a signal to B while we are waiting for A's * lock while walking this list. To avoid this, we don't block on * the process lock but just skip a process if it is already locked. */ if ((vm_swap_size < 64 && vm_page_count_min()) || (swap_pager_full && vm_paging_target() > 0)) { #if 0 if ((vm_swap_size < 64 || swap_pager_full) && vm_page_count_min()) { #endif bigproc = NULL; bigsize = 0; sx_slock(&allproc_lock); FOREACH_PROC_IN_SYSTEM(p) { int breakout; /* * If this process is already locked, skip it. */ if (PROC_TRYLOCK(p) == 0) continue; /* * if this is a system process, skip it */ if ((p->p_flag & P_SYSTEM) || (p->p_pid == 1) || ((p->p_pid < 48) && (vm_swap_size != 0))) { PROC_UNLOCK(p); continue; } /* * if the process is in a non-running type state, * don't touch it. Check all the threads individually. */ mtx_lock_spin(&sched_lock); breakout = 0; FOREACH_THREAD_IN_PROC(p, td) { if (td->td_state != TDS_RUNQ && td->td_state != TDS_RUNNING && td->td_state != TDS_SLP) { breakout = 1; break; } } if (breakout) { mtx_unlock_spin(&sched_lock); PROC_UNLOCK(p); continue; } mtx_unlock_spin(&sched_lock); /* * get the process size */ size = vmspace_resident_count(p->p_vmspace) + vmspace_swap_count(p->p_vmspace); /* * if the this process is bigger than the biggest one * remember it. */ if (size > bigsize) { if (bigproc != NULL) PROC_UNLOCK(bigproc); bigproc = p; bigsize = size; } else PROC_UNLOCK(p); } sx_sunlock(&allproc_lock); if (bigproc != NULL) { struct ksegrp *kg; killproc(bigproc, "out of swap space"); mtx_lock_spin(&sched_lock); FOREACH_KSEGRP_IN_PROC(bigproc, kg) { kg->kg_estcpu = 0; kg->kg_nice = PRIO_MIN; /* XXXKSE ??? */ resetpriority(kg); } mtx_unlock_spin(&sched_lock); PROC_UNLOCK(bigproc); wakeup(&cnt.v_free_count); } } } /* * This routine tries to maintain the pseudo LRU active queue, * so that during long periods of time where there is no paging, * that some statistic accumulation still occurs. This code * helps the situation where paging just starts to occur. */ static void vm_pageout_page_stats() { vm_page_t m,next; int pcount,tpcount; /* Number of pages to check */ static int fullintervalcount = 0; int page_shortage; int s0; page_shortage = (cnt.v_inactive_target + cnt.v_cache_max + cnt.v_free_min) - (cnt.v_free_count + cnt.v_inactive_count + cnt.v_cache_count); if (page_shortage <= 0) return; s0 = splvm(); vm_page_lock_queues(); pcount = cnt.v_active_count; fullintervalcount += vm_pageout_stats_interval; if (fullintervalcount < vm_pageout_full_stats_interval) { tpcount = (vm_pageout_stats_max * cnt.v_active_count) / cnt.v_page_count; if (pcount > tpcount) pcount = tpcount; } else { fullintervalcount = 0; } m = TAILQ_FIRST(&vm_page_queues[PQ_ACTIVE].pl); while ((m != NULL) && (pcount-- > 0)) { int actcount; if (m->queue != PQ_ACTIVE) { break; } next = TAILQ_NEXT(m, pageq); /* * Don't deactivate pages that are busy. */ if ((m->busy != 0) || (m->flags & PG_BUSY) || (m->hold_count != 0)) { vm_pageq_requeue(m); m = next; continue; } actcount = 0; if (m->flags & PG_REFERENCED) { vm_page_flag_clear(m, PG_REFERENCED); actcount += 1; } actcount += pmap_ts_referenced(m); if (actcount) { m->act_count += ACT_ADVANCE + actcount; if (m->act_count > ACT_MAX) m->act_count = ACT_MAX; vm_pageq_requeue(m); } else { if (m->act_count == 0) { /* * We turn off page access, so that we have * more accurate RSS stats. We don't do this * in the normal page deactivation when the * system is loaded VM wise, because the * cost of the large number of page protect * operations would be higher than the value * of doing the operation. */ vm_page_protect(m, VM_PROT_NONE); vm_page_deactivate(m); } else { m->act_count -= min(m->act_count, ACT_DECLINE); vm_pageq_requeue(m); } } m = next; } vm_page_unlock_queues(); splx(s0); } static int vm_pageout_free_page_calc(count) vm_size_t count; { if (count < cnt.v_page_count) return 0; /* * free_reserved needs to include enough for the largest swap pager * structures plus enough for any pv_entry structs when paging. */ if (cnt.v_page_count > 1024) cnt.v_free_min = 4 + (cnt.v_page_count - 1024) / 200; else cnt.v_free_min = 4; cnt.v_pageout_free_min = (2*MAXBSIZE)/PAGE_SIZE + cnt.v_interrupt_free_min; cnt.v_free_reserved = vm_pageout_page_count + cnt.v_pageout_free_min + (count / 768) + PQ_L2_SIZE; cnt.v_free_severe = cnt.v_free_min / 2; cnt.v_free_min += cnt.v_free_reserved; cnt.v_free_severe += cnt.v_free_reserved; return 1; } /* * vm_pageout is the high level pageout daemon. */ static void vm_pageout() { int pass; mtx_lock(&Giant); /* * Initialize some paging parameters. */ cnt.v_interrupt_free_min = 2; if (cnt.v_page_count < 2000) vm_pageout_page_count = 8; vm_pageout_free_page_calc(cnt.v_page_count); /* * v_free_target and v_cache_min control pageout hysteresis. Note * that these are more a measure of the VM cache queue hysteresis * then the VM free queue. Specifically, v_free_target is the * high water mark (free+cache pages). * * v_free_reserved + v_cache_min (mostly means v_cache_min) is the * low water mark, while v_free_min is the stop. v_cache_min must * be big enough to handle memory needs while the pageout daemon * is signalled and run to free more pages. */ if (cnt.v_free_count > 6144) cnt.v_free_target = 4 * cnt.v_free_min + cnt.v_free_reserved; else cnt.v_free_target = 2 * cnt.v_free_min + cnt.v_free_reserved; if (cnt.v_free_count > 2048) { cnt.v_cache_min = cnt.v_free_target; cnt.v_cache_max = 2 * cnt.v_cache_min; cnt.v_inactive_target = (3 * cnt.v_free_target) / 2; } else { cnt.v_cache_min = 0; cnt.v_cache_max = 0; cnt.v_inactive_target = cnt.v_free_count / 4; } if (cnt.v_inactive_target > cnt.v_free_count / 3) cnt.v_inactive_target = cnt.v_free_count / 3; /* XXX does not really belong here */ if (vm_page_max_wired == 0) vm_page_max_wired = cnt.v_free_count / 3; if (vm_pageout_stats_max == 0) vm_pageout_stats_max = cnt.v_free_target; /* * Set interval in seconds for stats scan. */ if (vm_pageout_stats_interval == 0) vm_pageout_stats_interval = 5; if (vm_pageout_full_stats_interval == 0) vm_pageout_full_stats_interval = vm_pageout_stats_interval * 4; /* * Set maximum free per pass */ if (vm_pageout_stats_free_max == 0) vm_pageout_stats_free_max = 5; swap_pager_swap_init(); pass = 0; /* * The pageout daemon is never done, so loop forever. */ while (TRUE) { int error; int s = splvm(); /* * If we have enough free memory, wakeup waiters. Do * not clear vm_pages_needed until we reach our target, * otherwise we may be woken up over and over again and * waste a lot of cpu. */ if (vm_pages_needed && !vm_page_count_min()) { if (vm_paging_needed() <= 0) vm_pages_needed = 0; wakeup(&cnt.v_free_count); } if (vm_pages_needed) { /* * Still not done, take a second pass without waiting * (unlimited dirty cleaning), otherwise sleep a bit * and try again. */ ++pass; if (pass > 1) tsleep(&vm_pages_needed, PVM, "psleep", hz/2); } else { /* * Good enough, sleep & handle stats. Prime the pass * for the next run. */ if (pass > 1) pass = 1; else pass = 0; error = tsleep(&vm_pages_needed, PVM, "psleep", vm_pageout_stats_interval * hz); if (error && !vm_pages_needed) { splx(s); pass = 0; vm_pageout_page_stats(); continue; } } if (vm_pages_needed) cnt.v_pdwakeups++; splx(s); vm_pageout_scan(pass); vm_pageout_deficit = 0; } } void pagedaemon_wakeup() { if (!vm_pages_needed && curthread->td_proc != pageproc) { vm_pages_needed++; wakeup(&vm_pages_needed); } } #if !defined(NO_SWAPPING) static void vm_req_vmdaemon() { static int lastrun = 0; if ((ticks > (lastrun + hz)) || (ticks < lastrun)) { wakeup(&vm_daemon_needed); lastrun = ticks; } } static void vm_daemon() { struct proc *p; int breakout; struct thread *td; mtx_lock(&Giant); while (TRUE) { tsleep(&vm_daemon_needed, PPAUSE, "psleep", 0); if (vm_pageout_req_swapout) { swapout_procs(vm_pageout_req_swapout); vm_pageout_req_swapout = 0; } /* * scan the processes for exceeding their rlimits or if * process is swapped out -- deactivate pages */ sx_slock(&allproc_lock); LIST_FOREACH(p, &allproc, p_list) { vm_pindex_t limit, size; /* * if this is a system process or if we have already * looked at this process, skip it. */ if (p->p_flag & (P_SYSTEM | P_WEXIT)) { continue; } /* * if the process is in a non-running type state, * don't touch it. */ mtx_lock_spin(&sched_lock); breakout = 0; FOREACH_THREAD_IN_PROC(p, td) { if (td->td_state != TDS_RUNQ && td->td_state != TDS_RUNNING && td->td_state != TDS_SLP) { breakout = 1; break; } } if (breakout) { mtx_unlock_spin(&sched_lock); continue; } /* * get a limit */ limit = OFF_TO_IDX( qmin(p->p_rlimit[RLIMIT_RSS].rlim_cur, p->p_rlimit[RLIMIT_RSS].rlim_max)); /* * let processes that are swapped out really be * swapped out set the limit to nothing (will force a * swap-out.) */ if ((p->p_sflag & PS_INMEM) == 0) limit = 0; /* XXX */ mtx_unlock_spin(&sched_lock); size = vmspace_resident_count(p->p_vmspace); if (limit >= 0 && size >= limit) { vm_pageout_map_deactivate_pages( &p->p_vmspace->vm_map, limit); } } sx_sunlock(&allproc_lock); } } #endif /* !defined(NO_SWAPPING) */