2 * Copyright (c) 1998 Matthew Dillon,
3 * Copyright (c) 1994 John S. Dyson
4 * Copyright (c) 1990 University of Utah.
5 * Copyright (c) 1982, 1986, 1989, 1993
6 * The Regents of the University of California. All rights reserved.
8 * This code is derived from software contributed to Berkeley by
9 * the Systems Programming Group of the University of Utah Computer
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. All advertising materials mentioning features or use of this software
21 * must display the following acknowledgement:
22 * This product includes software developed by the University of
23 * California, Berkeley and its contributors.
24 * 4. Neither the name of the University nor the names of its contributors
25 * may be used to endorse or promote products derived from this software
26 * without specific prior written permission.
28 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
43 * Radix Bitmap 'blists'.
45 * - The new swapper uses the new radix bitmap code. This should scale
46 * to arbitrarily small or arbitrarily large swap spaces and an almost
47 * arbitrary degree of fragmentation.
51 * - on the fly reallocation of swap during putpages. The new system
52 * does not try to keep previously allocated swap blocks for dirty
55 * - on the fly deallocation of swap
57 * - No more garbage collection required. Unnecessarily allocated swap
58 * blocks only exist for dirty vm_page_t's now and these are already
59 * cycled (in a high-load system) by the pager. We also do on-the-fly
60 * removal of invalidated swap blocks when a page is destroyed
63 * from: Utah $Hdr: swap_pager.c 1.4 91/04/30$
65 * @(#)swap_pager.c 8.9 (Berkeley) 3/21/94
66 * @(#)vm_swap.c 8.5 (Berkeley) 2/17/94
69 #include <sys/cdefs.h>
70 __FBSDID("$FreeBSD$");
75 #include <sys/param.h>
76 #include <sys/systm.h>
78 #include <sys/kernel.h>
84 #include <sys/fcntl.h>
85 #include <sys/mount.h>
86 #include <sys/namei.h>
87 #include <sys/vnode.h>
88 #include <sys/malloc.h>
89 #include <sys/resource.h>
90 #include <sys/resourcevar.h>
91 #include <sys/sysctl.h>
92 #include <sys/sysproto.h>
93 #include <sys/blist.h>
96 #include <sys/vmmeter.h>
98 #include <security/mac/mac_framework.h>
102 #include <vm/vm_map.h>
103 #include <vm/vm_kern.h>
104 #include <vm/vm_object.h>
105 #include <vm/vm_page.h>
106 #include <vm/vm_pager.h>
107 #include <vm/vm_pageout.h>
108 #include <vm/vm_param.h>
109 #include <vm/swap_pager.h>
110 #include <vm/vm_extern.h>
113 #include <geom/geom.h>
116 * SWB_NPAGES must be a power of 2. It may be set to 1, 2, 4, 8, 16
117 * or 32 pages per allocation.
118 * The 32-page limit is due to the radix code (kern/subr_blist.c).
120 #ifndef MAX_PAGEOUT_CLUSTER
121 #define MAX_PAGEOUT_CLUSTER 16
124 #if !defined(SWB_NPAGES)
125 #define SWB_NPAGES MAX_PAGEOUT_CLUSTER
129 * The swblock structure maps an object and a small, fixed-size range
130 * of page indices to disk addresses within a swap area.
131 * The collection of these mappings is implemented as a hash table.
132 * Unused disk addresses within a swap area are allocated and managed
135 #define SWCORRECT(n) (sizeof(void *) * (n) / sizeof(daddr_t))
136 #define SWAP_META_PAGES (SWB_NPAGES * 2)
137 #define SWAP_META_MASK (SWAP_META_PAGES - 1)
140 struct swblock *swb_hnext;
141 vm_object_t swb_object;
142 vm_pindex_t swb_index;
144 daddr_t swb_pages[SWAP_META_PAGES];
147 static struct mtx sw_dev_mtx;
148 static TAILQ_HEAD(, swdevt) swtailq = TAILQ_HEAD_INITIALIZER(swtailq);
149 static struct swdevt *swdevhd; /* Allocate from here next */
150 static int nswapdev; /* Number of swap devices */
151 int swap_pager_avail;
152 static int swdev_syscall_active = 0; /* serialize swap(on|off) */
154 static vm_ooffset_t swap_total;
155 SYSCTL_QUAD(_vm, OID_AUTO, swap_total, CTLFLAG_RD, &swap_total, 0, "");
156 static vm_ooffset_t swap_reserved;
157 SYSCTL_QUAD(_vm, OID_AUTO, swap_reserved, CTLFLAG_RD, &swap_reserved, 0, "");
158 static int overcommit = 0;
159 SYSCTL_INT(_vm, OID_AUTO, overcommit, CTLFLAG_RW, &overcommit, 0, "");
161 /* bits from overcommit */
162 #define SWAP_RESERVE_FORCE_ON (1 << 0)
163 #define SWAP_RESERVE_RLIMIT_ON (1 << 1)
164 #define SWAP_RESERVE_ALLOW_NONWIRED (1 << 2)
167 swap_reserve(vm_ooffset_t incr)
170 return (swap_reserve_by_uid(incr, curthread->td_ucred->cr_ruidinfo));
174 swap_reserve_by_uid(vm_ooffset_t incr, struct uidinfo *uip)
179 static struct timeval lastfail;
181 if (incr & PAGE_MASK)
182 panic("swap_reserve: & PAGE_MASK");
185 mtx_lock(&sw_dev_mtx);
186 r = swap_reserved + incr;
187 if (overcommit & SWAP_RESERVE_ALLOW_NONWIRED) {
188 s = cnt.v_page_count - cnt.v_free_reserved - cnt.v_wire_count;
193 if ((overcommit & SWAP_RESERVE_FORCE_ON) == 0 || r <= s ||
194 (error = priv_check(curthread, PRIV_VM_SWAP_NOQUOTA)) == 0) {
198 mtx_unlock(&sw_dev_mtx);
202 UIDINFO_VMSIZE_LOCK(uip);
203 if ((overcommit & SWAP_RESERVE_RLIMIT_ON) != 0 &&
204 uip->ui_vmsize + incr > lim_cur(curproc, RLIMIT_SWAP) &&
205 priv_check(curthread, PRIV_VM_SWAP_NORLIMIT))
208 uip->ui_vmsize += incr;
209 UIDINFO_VMSIZE_UNLOCK(uip);
210 PROC_UNLOCK(curproc);
212 mtx_lock(&sw_dev_mtx);
213 swap_reserved -= incr;
214 mtx_unlock(&sw_dev_mtx);
217 if (!res && ppsratecheck(&lastfail, &curfail, 1)) {
218 printf("uid %d, pid %d: swap reservation for %jd bytes failed\n",
219 uip->ui_uid, curproc->p_pid, incr);
226 swap_reserve_force(vm_ooffset_t incr)
230 mtx_lock(&sw_dev_mtx);
231 swap_reserved += incr;
232 mtx_unlock(&sw_dev_mtx);
234 uip = curthread->td_ucred->cr_ruidinfo;
236 UIDINFO_VMSIZE_LOCK(uip);
237 uip->ui_vmsize += incr;
238 UIDINFO_VMSIZE_UNLOCK(uip);
239 PROC_UNLOCK(curproc);
243 swap_release(vm_ooffset_t decr)
248 uip = curthread->td_ucred->cr_ruidinfo;
249 swap_release_by_uid(decr, uip);
250 PROC_UNLOCK(curproc);
254 swap_release_by_uid(vm_ooffset_t decr, struct uidinfo *uip)
257 if (decr & PAGE_MASK)
258 panic("swap_release: & PAGE_MASK");
260 mtx_lock(&sw_dev_mtx);
261 if (swap_reserved < decr)
262 panic("swap_reserved < decr");
263 swap_reserved -= decr;
264 mtx_unlock(&sw_dev_mtx);
266 UIDINFO_VMSIZE_LOCK(uip);
267 if (uip->ui_vmsize < decr)
268 printf("negative vmsize for uid = %d\n", uip->ui_uid);
269 uip->ui_vmsize -= decr;
270 UIDINFO_VMSIZE_UNLOCK(uip);
273 static void swapdev_strategy(struct buf *, struct swdevt *sw);
275 #define SWM_FREE 0x02 /* free, period */
276 #define SWM_POP 0x04 /* pop out */
278 int swap_pager_full = 2; /* swap space exhaustion (task killing) */
279 static int swap_pager_almost_full = 1; /* swap space exhaustion (w/hysteresis)*/
280 static int nsw_rcount; /* free read buffers */
281 static int nsw_wcount_sync; /* limit write buffers / synchronous */
282 static int nsw_wcount_async; /* limit write buffers / asynchronous */
283 static int nsw_wcount_async_max;/* assigned maximum */
284 static int nsw_cluster_max; /* maximum VOP I/O allowed */
286 static struct swblock **swhash;
287 static int swhash_mask;
288 static struct mtx swhash_mtx;
290 static int swap_async_max = 4; /* maximum in-progress async I/O's */
291 static struct sx sw_alloc_sx;
294 SYSCTL_INT(_vm, OID_AUTO, swap_async_max,
295 CTLFLAG_RW, &swap_async_max, 0, "Maximum running async swap ops");
298 * "named" and "unnamed" anon region objects. Try to reduce the overhead
299 * of searching a named list by hashing it just a little.
304 #define NOBJLIST(handle) \
305 (&swap_pager_object_list[((int)(intptr_t)handle >> 4) & (NOBJLISTS-1)])
307 static struct mtx sw_alloc_mtx; /* protect list manipulation */
308 static struct pagerlst swap_pager_object_list[NOBJLISTS];
309 static uma_zone_t swap_zone;
310 static struct vm_object swap_zone_obj;
313 * pagerops for OBJT_SWAP - "swap pager". Some ops are also global procedure
314 * calls hooked from other parts of the VM system and do not appear here.
315 * (see vm/swap_pager.h).
318 swap_pager_alloc(void *handle, vm_ooffset_t size,
319 vm_prot_t prot, vm_ooffset_t offset, struct ucred *);
320 static void swap_pager_dealloc(vm_object_t object);
321 static int swap_pager_getpages(vm_object_t, vm_page_t *, int, int);
322 static void swap_pager_putpages(vm_object_t, vm_page_t *, int, boolean_t, int *);
324 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before, int *after);
325 static void swap_pager_init(void);
326 static void swap_pager_unswapped(vm_page_t);
327 static void swap_pager_swapoff(struct swdevt *sp);
329 struct pagerops swappagerops = {
330 .pgo_init = swap_pager_init, /* early system initialization of pager */
331 .pgo_alloc = swap_pager_alloc, /* allocate an OBJT_SWAP object */
332 .pgo_dealloc = swap_pager_dealloc, /* deallocate an OBJT_SWAP object */
333 .pgo_getpages = swap_pager_getpages, /* pagein */
334 .pgo_putpages = swap_pager_putpages, /* pageout */
335 .pgo_haspage = swap_pager_haspage, /* get backing store status for page */
336 .pgo_pageunswapped = swap_pager_unswapped, /* remove swap related to page */
340 * dmmax is in page-sized chunks with the new swap system. It was
341 * dev-bsized chunks in the old. dmmax is always a power of 2.
343 * swap_*() routines are externally accessible. swp_*() routines are
347 static int nswap_lowat = 128; /* in pages, swap_pager_almost_full warn */
348 static int nswap_hiwat = 512; /* in pages, swap_pager_almost_full warn */
350 SYSCTL_INT(_vm, OID_AUTO, dmmax,
351 CTLFLAG_RD, &dmmax, 0, "Maximum size of a swap block");
353 static void swp_sizecheck(void);
354 static void swp_pager_async_iodone(struct buf *bp);
355 static int swapongeom(struct thread *, struct vnode *);
356 static int swaponvp(struct thread *, struct vnode *, u_long);
357 static int swapoff_one(struct swdevt *sp, struct ucred *cred);
360 * Swap bitmap functions
362 static void swp_pager_freeswapspace(daddr_t blk, int npages);
363 static daddr_t swp_pager_getswapspace(int npages);
368 static struct swblock **swp_pager_hash(vm_object_t object, vm_pindex_t index);
369 static void swp_pager_meta_build(vm_object_t, vm_pindex_t, daddr_t);
370 static void swp_pager_meta_free(vm_object_t, vm_pindex_t, daddr_t);
371 static void swp_pager_meta_free_all(vm_object_t);
372 static daddr_t swp_pager_meta_ctl(vm_object_t, vm_pindex_t, int);
375 swp_pager_free_nrpage(vm_page_t m)
378 if (m->wire_count == 0)
383 * SWP_SIZECHECK() - update swap_pager_full indication
385 * update the swap_pager_almost_full indication and warn when we are
386 * about to run out of swap space, using lowat/hiwat hysteresis.
388 * Clear swap_pager_full ( task killing ) indication when lowat is met.
390 * No restrictions on call
391 * This routine may not block.
397 if (swap_pager_avail < nswap_lowat) {
398 if (swap_pager_almost_full == 0) {
399 printf("swap_pager: out of swap space\n");
400 swap_pager_almost_full = 1;
404 if (swap_pager_avail > nswap_hiwat)
405 swap_pager_almost_full = 0;
410 * SWP_PAGER_HASH() - hash swap meta data
412 * This is an helper function which hashes the swapblk given
413 * the object and page index. It returns a pointer to a pointer
414 * to the object, or a pointer to a NULL pointer if it could not
417 static struct swblock **
418 swp_pager_hash(vm_object_t object, vm_pindex_t index)
420 struct swblock **pswap;
421 struct swblock *swap;
423 index &= ~(vm_pindex_t)SWAP_META_MASK;
424 pswap = &swhash[(index ^ (int)(intptr_t)object) & swhash_mask];
425 while ((swap = *pswap) != NULL) {
426 if (swap->swb_object == object &&
427 swap->swb_index == index
431 pswap = &swap->swb_hnext;
437 * SWAP_PAGER_INIT() - initialize the swap pager!
439 * Expected to be started from system init. NOTE: This code is run
440 * before much else so be careful what you depend on. Most of the VM
441 * system has yet to be initialized at this point.
444 swap_pager_init(void)
447 * Initialize object lists
451 for (i = 0; i < NOBJLISTS; ++i)
452 TAILQ_INIT(&swap_pager_object_list[i]);
453 mtx_init(&sw_alloc_mtx, "swap_pager list", NULL, MTX_DEF);
454 mtx_init(&sw_dev_mtx, "swapdev", NULL, MTX_DEF);
457 * Device Stripe, in PAGE_SIZE'd blocks
459 dmmax = SWB_NPAGES * 2;
463 * SWAP_PAGER_SWAP_INIT() - swap pager initialization from pageout process
465 * Expected to be started from pageout process once, prior to entering
469 swap_pager_swap_init(void)
474 * Number of in-transit swap bp operations. Don't
475 * exhaust the pbufs completely. Make sure we
476 * initialize workable values (0 will work for hysteresis
477 * but it isn't very efficient).
479 * The nsw_cluster_max is constrained by the bp->b_pages[]
480 * array (MAXPHYS/PAGE_SIZE) and our locally defined
481 * MAX_PAGEOUT_CLUSTER. Also be aware that swap ops are
482 * constrained by the swap device interleave stripe size.
484 * Currently we hardwire nsw_wcount_async to 4. This limit is
485 * designed to prevent other I/O from having high latencies due to
486 * our pageout I/O. The value 4 works well for one or two active swap
487 * devices but is probably a little low if you have more. Even so,
488 * a higher value would probably generate only a limited improvement
489 * with three or four active swap devices since the system does not
490 * typically have to pageout at extreme bandwidths. We will want
491 * at least 2 per swap devices, and 4 is a pretty good value if you
492 * have one NFS swap device due to the command/ack latency over NFS.
493 * So it all works out pretty well.
495 nsw_cluster_max = min((MAXPHYS/PAGE_SIZE), MAX_PAGEOUT_CLUSTER);
498 nsw_rcount = (nswbuf + 1) / 2;
499 nsw_wcount_sync = (nswbuf + 3) / 4;
500 nsw_wcount_async = 4;
501 nsw_wcount_async_max = nsw_wcount_async;
502 mtx_unlock(&pbuf_mtx);
505 * Initialize our zone. Right now I'm just guessing on the number
506 * we need based on the number of pages in the system. Each swblock
507 * can hold 16 pages, so this is probably overkill. This reservation
508 * is typically limited to around 32MB by default.
510 n = cnt.v_page_count / 2;
511 if (maxswzone && n > maxswzone / sizeof(struct swblock))
512 n = maxswzone / sizeof(struct swblock);
514 swap_zone = uma_zcreate("SWAPMETA", sizeof(struct swblock), NULL, NULL,
515 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
516 if (swap_zone == NULL)
517 panic("failed to create swap_zone.");
519 if (uma_zone_set_obj(swap_zone, &swap_zone_obj, n))
522 * if the allocation failed, try a zone two thirds the
523 * size of the previous attempt.
528 printf("Swap zone entries reduced from %d to %d.\n", n2, n);
532 * Initialize our meta-data hash table. The swapper does not need to
533 * be quite as efficient as the VM system, so we do not use an
534 * oversized hash table.
536 * n: size of hash table, must be power of 2
537 * swhash_mask: hash table index mask
539 for (n = 1; n < n2 / 8; n *= 2)
541 swhash = malloc(sizeof(struct swblock *) * n, M_VMPGDATA, M_WAITOK | M_ZERO);
543 mtx_init(&swhash_mtx, "swap_pager swhash", NULL, MTX_DEF);
547 * SWAP_PAGER_ALLOC() - allocate a new OBJT_SWAP VM object and instantiate
548 * its metadata structures.
550 * This routine is called from the mmap and fork code to create a new
551 * OBJT_SWAP object. We do this by creating an OBJT_DEFAULT object
552 * and then converting it with swp_pager_meta_build().
554 * This routine may block in vm_object_allocate() and create a named
555 * object lookup race, so we must interlock.
560 swap_pager_alloc(void *handle, vm_ooffset_t size, vm_prot_t prot,
561 vm_ooffset_t offset, struct ucred *cred)
568 pindex = OFF_TO_IDX(offset + PAGE_MASK + size);
572 * Reference existing named region or allocate new one. There
573 * should not be a race here against swp_pager_meta_build()
574 * as called from vm_page_remove() in regards to the lookup
577 sx_xlock(&sw_alloc_sx);
578 object = vm_pager_object_lookup(NOBJLIST(handle), handle);
579 if (object == NULL) {
581 uip = cred->cr_ruidinfo;
582 if (!swap_reserve_by_uid(size, uip)) {
583 sx_xunlock(&sw_alloc_sx);
589 object = vm_object_allocate(OBJT_DEFAULT, pindex);
590 VM_OBJECT_LOCK(object);
591 object->handle = handle;
594 object->charge = size;
596 swp_pager_meta_build(object, 0, SWAPBLK_NONE);
597 VM_OBJECT_UNLOCK(object);
599 sx_xunlock(&sw_alloc_sx);
603 uip = cred->cr_ruidinfo;
604 if (!swap_reserve_by_uid(size, uip))
608 object = vm_object_allocate(OBJT_DEFAULT, pindex);
609 VM_OBJECT_LOCK(object);
612 object->charge = size;
614 swp_pager_meta_build(object, 0, SWAPBLK_NONE);
615 VM_OBJECT_UNLOCK(object);
621 * SWAP_PAGER_DEALLOC() - remove swap metadata from object
623 * The swap backing for the object is destroyed. The code is
624 * designed such that we can reinstantiate it later, but this
625 * routine is typically called only when the entire object is
626 * about to be destroyed.
628 * The object must be locked.
631 swap_pager_dealloc(vm_object_t object)
635 * Remove from list right away so lookups will fail if we block for
636 * pageout completion.
638 if (object->handle != NULL) {
639 mtx_lock(&sw_alloc_mtx);
640 TAILQ_REMOVE(NOBJLIST(object->handle), object, pager_object_list);
641 mtx_unlock(&sw_alloc_mtx);
644 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
645 vm_object_pip_wait(object, "swpdea");
648 * Free all remaining metadata. We only bother to free it from
649 * the swap meta data. We do not attempt to free swapblk's still
650 * associated with vm_page_t's for this object. We do not care
651 * if paging is still in progress on some objects.
653 swp_pager_meta_free_all(object);
656 /************************************************************************
657 * SWAP PAGER BITMAP ROUTINES *
658 ************************************************************************/
661 * SWP_PAGER_GETSWAPSPACE() - allocate raw swap space
663 * Allocate swap for the requested number of pages. The starting
664 * swap block number (a page index) is returned or SWAPBLK_NONE
665 * if the allocation failed.
667 * Also has the side effect of advising that somebody made a mistake
668 * when they configured swap and didn't configure enough.
670 * This routine may not sleep.
672 * We allocate in round-robin fashion from the configured devices.
675 swp_pager_getswapspace(int npages)
682 mtx_lock(&sw_dev_mtx);
684 for (i = 0; i < nswapdev; i++) {
686 sp = TAILQ_FIRST(&swtailq);
687 if (!(sp->sw_flags & SW_CLOSING)) {
688 blk = blist_alloc(sp->sw_blist, npages);
689 if (blk != SWAPBLK_NONE) {
691 sp->sw_used += npages;
692 swap_pager_avail -= npages;
694 swdevhd = TAILQ_NEXT(sp, sw_list);
698 sp = TAILQ_NEXT(sp, sw_list);
700 if (swap_pager_full != 2) {
701 printf("swap_pager_getswapspace(%d): failed\n", npages);
703 swap_pager_almost_full = 1;
707 mtx_unlock(&sw_dev_mtx);
712 swp_pager_isondev(daddr_t blk, struct swdevt *sp)
715 return (blk >= sp->sw_first && blk < sp->sw_end);
719 swp_pager_strategy(struct buf *bp)
723 mtx_lock(&sw_dev_mtx);
724 TAILQ_FOREACH(sp, &swtailq, sw_list) {
725 if (bp->b_blkno >= sp->sw_first && bp->b_blkno < sp->sw_end) {
726 mtx_unlock(&sw_dev_mtx);
727 sp->sw_strategy(bp, sp);
731 panic("Swapdev not found");
736 * SWP_PAGER_FREESWAPSPACE() - free raw swap space
738 * This routine returns the specified swap blocks back to the bitmap.
740 * This routine may not sleep.
743 swp_pager_freeswapspace(daddr_t blk, int npages)
747 mtx_lock(&sw_dev_mtx);
748 TAILQ_FOREACH(sp, &swtailq, sw_list) {
749 if (blk >= sp->sw_first && blk < sp->sw_end) {
750 sp->sw_used -= npages;
752 * If we are attempting to stop swapping on
753 * this device, we don't want to mark any
754 * blocks free lest they be reused.
756 if ((sp->sw_flags & SW_CLOSING) == 0) {
757 blist_free(sp->sw_blist, blk - sp->sw_first,
759 swap_pager_avail += npages;
762 mtx_unlock(&sw_dev_mtx);
766 panic("Swapdev not found");
770 * SWAP_PAGER_FREESPACE() - frees swap blocks associated with a page
771 * range within an object.
773 * This is a globally accessible routine.
775 * This routine removes swapblk assignments from swap metadata.
777 * The external callers of this routine typically have already destroyed
778 * or renamed vm_page_t's associated with this range in the object so
782 swap_pager_freespace(vm_object_t object, vm_pindex_t start, vm_size_t size)
785 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
786 swp_pager_meta_free(object, start, size);
790 * SWAP_PAGER_RESERVE() - reserve swap blocks in object
792 * Assigns swap blocks to the specified range within the object. The
793 * swap blocks are not zerod. Any previous swap assignment is destroyed.
795 * Returns 0 on success, -1 on failure.
798 swap_pager_reserve(vm_object_t object, vm_pindex_t start, vm_size_t size)
801 daddr_t blk = SWAPBLK_NONE;
802 vm_pindex_t beg = start; /* save start index */
804 VM_OBJECT_LOCK(object);
808 while ((blk = swp_pager_getswapspace(n)) == SWAPBLK_NONE) {
811 swp_pager_meta_free(object, beg, start - beg);
812 VM_OBJECT_UNLOCK(object);
817 swp_pager_meta_build(object, start, blk);
823 swp_pager_meta_free(object, start, n);
824 VM_OBJECT_UNLOCK(object);
829 * SWAP_PAGER_COPY() - copy blocks from source pager to destination pager
830 * and destroy the source.
832 * Copy any valid swapblks from the source to the destination. In
833 * cases where both the source and destination have a valid swapblk,
834 * we keep the destination's.
836 * This routine is allowed to sleep. It may sleep allocating metadata
837 * indirectly through swp_pager_meta_build() or if paging is still in
838 * progress on the source.
840 * The source object contains no vm_page_t's (which is just as well)
842 * The source object is of type OBJT_SWAP.
844 * The source and destination objects must be locked.
845 * Both object locks may temporarily be released.
848 swap_pager_copy(vm_object_t srcobject, vm_object_t dstobject,
849 vm_pindex_t offset, int destroysource)
853 VM_OBJECT_LOCK_ASSERT(srcobject, MA_OWNED);
854 VM_OBJECT_LOCK_ASSERT(dstobject, MA_OWNED);
857 * If destroysource is set, we remove the source object from the
858 * swap_pager internal queue now.
861 if (srcobject->handle != NULL) {
862 mtx_lock(&sw_alloc_mtx);
864 NOBJLIST(srcobject->handle),
868 mtx_unlock(&sw_alloc_mtx);
873 * transfer source to destination.
875 for (i = 0; i < dstobject->size; ++i) {
879 * Locate (without changing) the swapblk on the destination,
880 * unless it is invalid in which case free it silently, or
881 * if the destination is a resident page, in which case the
882 * source is thrown away.
884 dstaddr = swp_pager_meta_ctl(dstobject, i, 0);
886 if (dstaddr == SWAPBLK_NONE) {
888 * Destination has no swapblk and is not resident,
893 srcaddr = swp_pager_meta_ctl(
899 if (srcaddr != SWAPBLK_NONE) {
901 * swp_pager_meta_build() can sleep.
903 vm_object_pip_add(srcobject, 1);
904 VM_OBJECT_UNLOCK(srcobject);
905 vm_object_pip_add(dstobject, 1);
906 swp_pager_meta_build(dstobject, i, srcaddr);
907 vm_object_pip_wakeup(dstobject);
908 VM_OBJECT_LOCK(srcobject);
909 vm_object_pip_wakeup(srcobject);
913 * Destination has valid swapblk or it is represented
914 * by a resident page. We destroy the sourceblock.
917 swp_pager_meta_ctl(srcobject, i + offset, SWM_FREE);
922 * Free left over swap blocks in source.
924 * We have to revert the type to OBJT_DEFAULT so we do not accidently
925 * double-remove the object from the swap queues.
928 swp_pager_meta_free_all(srcobject);
930 * Reverting the type is not necessary, the caller is going
931 * to destroy srcobject directly, but I'm doing it here
932 * for consistency since we've removed the object from its
935 srcobject->type = OBJT_DEFAULT;
940 * SWAP_PAGER_HASPAGE() - determine if we have good backing store for
941 * the requested page.
943 * We determine whether good backing store exists for the requested
944 * page and return TRUE if it does, FALSE if it doesn't.
946 * If TRUE, we also try to determine how much valid, contiguous backing
947 * store exists before and after the requested page within a reasonable
948 * distance. We do not try to restrict it to the swap device stripe
949 * (that is handled in getpages/putpages). It probably isn't worth
953 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before, int *after)
957 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
959 * do we have good backing store at the requested index ?
961 blk0 = swp_pager_meta_ctl(object, pindex, 0);
963 if (blk0 == SWAPBLK_NONE) {
972 * find backwards-looking contiguous good backing store
974 if (before != NULL) {
977 for (i = 1; i < (SWB_NPAGES/2); ++i) {
982 blk = swp_pager_meta_ctl(object, pindex - i, 0);
990 * find forward-looking contiguous good backing store
995 for (i = 1; i < (SWB_NPAGES/2); ++i) {
998 blk = swp_pager_meta_ctl(object, pindex + i, 0);
1008 * SWAP_PAGER_PAGE_UNSWAPPED() - remove swap backing store related to page
1010 * This removes any associated swap backing store, whether valid or
1011 * not, from the page.
1013 * This routine is typically called when a page is made dirty, at
1014 * which point any associated swap can be freed. MADV_FREE also
1015 * calls us in a special-case situation
1017 * NOTE!!! If the page is clean and the swap was valid, the caller
1018 * should make the page dirty before calling this routine. This routine
1019 * does NOT change the m->dirty status of the page. Also: MADV_FREE
1022 * This routine may not sleep.
1025 swap_pager_unswapped(vm_page_t m)
1028 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1029 swp_pager_meta_ctl(m->object, m->pindex, SWM_FREE);
1033 * SWAP_PAGER_GETPAGES() - bring pages in from swap
1035 * Attempt to retrieve (m, count) pages from backing store, but make
1036 * sure we retrieve at least m[reqpage]. We try to load in as large
1037 * a chunk surrounding m[reqpage] as is contiguous in swap and which
1038 * belongs to the same object.
1040 * The code is designed for asynchronous operation and
1041 * immediate-notification of 'reqpage' but tends not to be
1042 * used that way. Please do not optimize-out this algorithmic
1043 * feature, I intend to improve on it in the future.
1045 * The parent has a single vm_object_pip_add() reference prior to
1046 * calling us and we should return with the same.
1048 * The parent has BUSY'd the pages. We should return with 'm'
1049 * left busy, but the others adjusted.
1052 swap_pager_getpages(vm_object_t object, vm_page_t *m, int count, int reqpage)
1062 KASSERT(mreq->object == object,
1063 ("swap_pager_getpages: object mismatch %p/%p",
1064 object, mreq->object));
1067 * Calculate range to retrieve. The pages have already been assigned
1068 * their swapblks. We require a *contiguous* range but we know it to
1069 * not span devices. If we do not supply it, bad things
1070 * happen. Note that blk, iblk & jblk can be SWAPBLK_NONE, but the
1071 * loops are set up such that the case(s) are handled implicitly.
1073 * The swp_*() calls must be made with the object locked.
1075 blk = swp_pager_meta_ctl(mreq->object, mreq->pindex, 0);
1077 for (i = reqpage - 1; i >= 0; --i) {
1080 iblk = swp_pager_meta_ctl(m[i]->object, m[i]->pindex, 0);
1081 if (blk != iblk + (reqpage - i))
1086 for (j = reqpage + 1; j < count; ++j) {
1089 jblk = swp_pager_meta_ctl(m[j]->object, m[j]->pindex, 0);
1090 if (blk != jblk - (j - reqpage))
1095 * free pages outside our collection range. Note: we never free
1096 * mreq, it must remain busy throughout.
1098 if (0 < i || j < count) {
1101 vm_page_lock_queues();
1102 for (k = 0; k < i; ++k)
1103 swp_pager_free_nrpage(m[k]);
1104 for (k = j; k < count; ++k)
1105 swp_pager_free_nrpage(m[k]);
1106 vm_page_unlock_queues();
1110 * Return VM_PAGER_FAIL if we have nothing to do. Return mreq
1111 * still busy, but the others unbusied.
1113 if (blk == SWAPBLK_NONE)
1114 return (VM_PAGER_FAIL);
1117 * Getpbuf() can sleep.
1119 VM_OBJECT_UNLOCK(object);
1121 * Get a swap buffer header to perform the IO
1123 bp = getpbuf(&nsw_rcount);
1124 bp->b_flags |= B_PAGING;
1127 * map our page(s) into kva for input
1129 pmap_qenter((vm_offset_t)bp->b_data, m + i, j - i);
1131 bp->b_iocmd = BIO_READ;
1132 bp->b_iodone = swp_pager_async_iodone;
1133 bp->b_rcred = crhold(thread0.td_ucred);
1134 bp->b_wcred = crhold(thread0.td_ucred);
1135 bp->b_blkno = blk - (reqpage - i);
1136 bp->b_bcount = PAGE_SIZE * (j - i);
1137 bp->b_bufsize = PAGE_SIZE * (j - i);
1138 bp->b_pager.pg_reqpage = reqpage - i;
1140 VM_OBJECT_LOCK(object);
1144 for (k = i; k < j; ++k) {
1145 bp->b_pages[k - i] = m[k];
1146 m[k]->oflags |= VPO_SWAPINPROG;
1149 bp->b_npages = j - i;
1151 PCPU_INC(cnt.v_swapin);
1152 PCPU_ADD(cnt.v_swappgsin, bp->b_npages);
1155 * We still hold the lock on mreq, and our automatic completion routine
1156 * does not remove it.
1158 vm_object_pip_add(object, bp->b_npages);
1159 VM_OBJECT_UNLOCK(object);
1162 * perform the I/O. NOTE!!! bp cannot be considered valid after
1163 * this point because we automatically release it on completion.
1164 * Instead, we look at the one page we are interested in which we
1165 * still hold a lock on even through the I/O completion.
1167 * The other pages in our m[] array are also released on completion,
1168 * so we cannot assume they are valid anymore either.
1170 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1173 swp_pager_strategy(bp);
1176 * wait for the page we want to complete. VPO_SWAPINPROG is always
1177 * cleared on completion. If an I/O error occurs, SWAPBLK_NONE
1178 * is set in the meta-data.
1180 VM_OBJECT_LOCK(object);
1181 while ((mreq->oflags & VPO_SWAPINPROG) != 0) {
1182 mreq->oflags |= VPO_WANTED;
1183 PCPU_INC(cnt.v_intrans);
1184 if (msleep(mreq, VM_OBJECT_MTX(object), PSWP, "swread", hz*20)) {
1186 "swap_pager: indefinite wait buffer: bufobj: %p, blkno: %jd, size: %ld\n",
1187 bp->b_bufobj, (intmax_t)bp->b_blkno, bp->b_bcount);
1192 * mreq is left busied after completion, but all the other pages
1193 * are freed. If we had an unrecoverable read error the page will
1196 if (mreq->valid != VM_PAGE_BITS_ALL) {
1197 return (VM_PAGER_ERROR);
1199 return (VM_PAGER_OK);
1203 * A final note: in a low swap situation, we cannot deallocate swap
1204 * and mark a page dirty here because the caller is likely to mark
1205 * the page clean when we return, causing the page to possibly revert
1206 * to all-zero's later.
1211 * swap_pager_putpages:
1213 * Assign swap (if necessary) and initiate I/O on the specified pages.
1215 * We support both OBJT_DEFAULT and OBJT_SWAP objects. DEFAULT objects
1216 * are automatically converted to SWAP objects.
1218 * In a low memory situation we may block in VOP_STRATEGY(), but the new
1219 * vm_page reservation system coupled with properly written VFS devices
1220 * should ensure that no low-memory deadlock occurs. This is an area
1223 * The parent has N vm_object_pip_add() references prior to
1224 * calling us and will remove references for rtvals[] that are
1225 * not set to VM_PAGER_PEND. We need to remove the rest on I/O
1228 * The parent has soft-busy'd the pages it passes us and will unbusy
1229 * those whos rtvals[] entry is not set to VM_PAGER_PEND on return.
1230 * We need to unbusy the rest on I/O completion.
1233 swap_pager_putpages(vm_object_t object, vm_page_t *m, int count,
1234 boolean_t sync, int *rtvals)
1239 if (count && m[0]->object != object) {
1240 panic("swap_pager_putpages: object mismatch %p/%p",
1249 * Turn object into OBJT_SWAP
1250 * check for bogus sysops
1251 * force sync if not pageout process
1253 if (object->type != OBJT_SWAP)
1254 swp_pager_meta_build(object, 0, SWAPBLK_NONE);
1255 VM_OBJECT_UNLOCK(object);
1257 if (curproc != pageproc)
1263 * Update nsw parameters from swap_async_max sysctl values.
1264 * Do not let the sysop crash the machine with bogus numbers.
1266 mtx_lock(&pbuf_mtx);
1267 if (swap_async_max != nsw_wcount_async_max) {
1273 if ((n = swap_async_max) > nswbuf / 2)
1280 * Adjust difference ( if possible ). If the current async
1281 * count is too low, we may not be able to make the adjustment
1284 n -= nsw_wcount_async_max;
1285 if (nsw_wcount_async + n >= 0) {
1286 nsw_wcount_async += n;
1287 nsw_wcount_async_max += n;
1288 wakeup(&nsw_wcount_async);
1291 mtx_unlock(&pbuf_mtx);
1296 * Assign swap blocks and issue I/O. We reallocate swap on the fly.
1297 * The page is left dirty until the pageout operation completes
1300 for (i = 0; i < count; i += n) {
1306 * Maximum I/O size is limited by a number of factors.
1308 n = min(BLIST_MAX_ALLOC, count - i);
1309 n = min(n, nsw_cluster_max);
1312 * Get biggest block of swap we can. If we fail, fall
1313 * back and try to allocate a smaller block. Don't go
1314 * overboard trying to allocate space if it would overly
1318 (blk = swp_pager_getswapspace(n)) == SWAPBLK_NONE &&
1323 if (blk == SWAPBLK_NONE) {
1324 for (j = 0; j < n; ++j)
1325 rtvals[i+j] = VM_PAGER_FAIL;
1330 * All I/O parameters have been satisfied, build the I/O
1331 * request and assign the swap space.
1334 bp = getpbuf(&nsw_wcount_sync);
1336 bp = getpbuf(&nsw_wcount_async);
1337 bp->b_flags = B_ASYNC;
1339 bp->b_flags |= B_PAGING;
1340 bp->b_iocmd = BIO_WRITE;
1342 pmap_qenter((vm_offset_t)bp->b_data, &m[i], n);
1344 bp->b_rcred = crhold(thread0.td_ucred);
1345 bp->b_wcred = crhold(thread0.td_ucred);
1346 bp->b_bcount = PAGE_SIZE * n;
1347 bp->b_bufsize = PAGE_SIZE * n;
1350 VM_OBJECT_LOCK(object);
1351 for (j = 0; j < n; ++j) {
1352 vm_page_t mreq = m[i+j];
1354 swp_pager_meta_build(
1359 vm_page_dirty(mreq);
1360 rtvals[i+j] = VM_PAGER_OK;
1362 mreq->oflags |= VPO_SWAPINPROG;
1363 bp->b_pages[j] = mreq;
1365 VM_OBJECT_UNLOCK(object);
1368 * Must set dirty range for NFS to work.
1371 bp->b_dirtyend = bp->b_bcount;
1373 PCPU_INC(cnt.v_swapout);
1374 PCPU_ADD(cnt.v_swappgsout, bp->b_npages);
1379 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1381 if (sync == FALSE) {
1382 bp->b_iodone = swp_pager_async_iodone;
1384 swp_pager_strategy(bp);
1386 for (j = 0; j < n; ++j)
1387 rtvals[i+j] = VM_PAGER_PEND;
1388 /* restart outter loop */
1395 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1397 bp->b_iodone = bdone;
1398 swp_pager_strategy(bp);
1401 * Wait for the sync I/O to complete, then update rtvals.
1402 * We just set the rtvals[] to VM_PAGER_PEND so we can call
1403 * our async completion routine at the end, thus avoiding a
1406 bwait(bp, PVM, "swwrt");
1407 for (j = 0; j < n; ++j)
1408 rtvals[i+j] = VM_PAGER_PEND;
1410 * Now that we are through with the bp, we can call the
1411 * normal async completion, which frees everything up.
1413 swp_pager_async_iodone(bp);
1415 VM_OBJECT_LOCK(object);
1419 * swp_pager_async_iodone:
1421 * Completion routine for asynchronous reads and writes from/to swap.
1422 * Also called manually by synchronous code to finish up a bp.
1424 * For READ operations, the pages are VPO_BUSY'd. For WRITE operations,
1425 * the pages are vm_page_t->busy'd. For READ operations, we VPO_BUSY
1426 * unbusy all pages except the 'main' request page. For WRITE
1427 * operations, we vm_page_t->busy'd unbusy all pages ( we can do this
1428 * because we marked them all VM_PAGER_PEND on return from putpages ).
1430 * This routine may not sleep.
1433 swp_pager_async_iodone(struct buf *bp)
1436 vm_object_t object = NULL;
1441 if (bp->b_ioflags & BIO_ERROR) {
1443 "swap_pager: I/O error - %s failed; blkno %ld,"
1444 "size %ld, error %d\n",
1445 ((bp->b_iocmd == BIO_READ) ? "pagein" : "pageout"),
1453 * remove the mapping for kernel virtual
1455 pmap_qremove((vm_offset_t)bp->b_data, bp->b_npages);
1458 object = bp->b_pages[0]->object;
1459 VM_OBJECT_LOCK(object);
1461 vm_page_lock_queues();
1463 * cleanup pages. If an error occurs writing to swap, we are in
1464 * very serious trouble. If it happens to be a disk error, though,
1465 * we may be able to recover by reassigning the swap later on. So
1466 * in this case we remove the m->swapblk assignment for the page
1467 * but do not free it in the rlist. The errornous block(s) are thus
1468 * never reallocated as swap. Redirty the page and continue.
1470 for (i = 0; i < bp->b_npages; ++i) {
1471 vm_page_t m = bp->b_pages[i];
1473 m->oflags &= ~VPO_SWAPINPROG;
1475 if (bp->b_ioflags & BIO_ERROR) {
1477 * If an error occurs I'd love to throw the swapblk
1478 * away without freeing it back to swapspace, so it
1479 * can never be used again. But I can't from an
1482 if (bp->b_iocmd == BIO_READ) {
1484 * When reading, reqpage needs to stay
1485 * locked for the parent, but all other
1486 * pages can be freed. We still want to
1487 * wakeup the parent waiting on the page,
1488 * though. ( also: pg_reqpage can be -1 and
1489 * not match anything ).
1491 * We have to wake specifically requested pages
1492 * up too because we cleared VPO_SWAPINPROG and
1493 * someone may be waiting for that.
1495 * NOTE: for reads, m->dirty will probably
1496 * be overridden by the original caller of
1497 * getpages so don't play cute tricks here.
1500 if (i != bp->b_pager.pg_reqpage)
1501 swp_pager_free_nrpage(m);
1505 * If i == bp->b_pager.pg_reqpage, do not wake
1506 * the page up. The caller needs to.
1510 * If a write error occurs, reactivate page
1511 * so it doesn't clog the inactive list,
1512 * then finish the I/O.
1515 vm_page_activate(m);
1516 vm_page_io_finish(m);
1518 } else if (bp->b_iocmd == BIO_READ) {
1520 * NOTE: for reads, m->dirty will probably be
1521 * overridden by the original caller of getpages so
1522 * we cannot set them in order to free the underlying
1523 * swap in a low-swap situation. I don't think we'd
1524 * want to do that anyway, but it was an optimization
1525 * that existed in the old swapper for a time before
1526 * it got ripped out due to precisely this problem.
1528 * If not the requested page then deactivate it.
1530 * Note that the requested page, reqpage, is left
1531 * busied, but we still have to wake it up. The
1532 * other pages are released (unbusied) by
1535 KASSERT(!pmap_page_is_mapped(m),
1536 ("swp_pager_async_iodone: page %p is mapped", m));
1537 m->valid = VM_PAGE_BITS_ALL;
1538 KASSERT(m->dirty == 0,
1539 ("swp_pager_async_iodone: page %p is dirty", m));
1542 * We have to wake specifically requested pages
1543 * up too because we cleared VPO_SWAPINPROG and
1544 * could be waiting for it in getpages. However,
1545 * be sure to not unbusy getpages specifically
1546 * requested page - getpages expects it to be
1549 if (i != bp->b_pager.pg_reqpage) {
1550 vm_page_deactivate(m);
1557 * For write success, clear the dirty
1558 * status, then finish the I/O ( which decrements the
1559 * busy count and possibly wakes waiter's up ).
1561 KASSERT((m->flags & PG_WRITEABLE) == 0,
1562 ("swp_pager_async_iodone: page %p is not write"
1565 vm_page_io_finish(m);
1566 if (vm_page_count_severe())
1567 vm_page_try_to_cache(m);
1570 vm_page_unlock_queues();
1573 * adjust pip. NOTE: the original parent may still have its own
1574 * pip refs on the object.
1576 if (object != NULL) {
1577 vm_object_pip_wakeupn(object, bp->b_npages);
1578 VM_OBJECT_UNLOCK(object);
1582 * swapdev_strategy() manually sets b_vp and b_bufobj before calling
1583 * bstrategy(). Set them back to NULL now we're done with it, or we'll
1584 * trigger a KASSERT in relpbuf().
1588 bp->b_bufobj = NULL;
1591 * release the physical I/O buffer
1595 ((bp->b_iocmd == BIO_READ) ? &nsw_rcount :
1596 ((bp->b_flags & B_ASYNC) ?
1605 * swap_pager_isswapped:
1607 * Return 1 if at least one page in the given object is paged
1608 * out to the given swap device.
1610 * This routine may not sleep.
1613 swap_pager_isswapped(vm_object_t object, struct swdevt *sp)
1619 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1620 if (object->type != OBJT_SWAP)
1623 mtx_lock(&swhash_mtx);
1624 for (bcount = 0; bcount < object->un_pager.swp.swp_bcount; bcount++) {
1625 struct swblock *swap;
1627 if ((swap = *swp_pager_hash(object, index)) != NULL) {
1628 for (i = 0; i < SWAP_META_PAGES; ++i) {
1629 if (swp_pager_isondev(swap->swb_pages[i], sp)) {
1630 mtx_unlock(&swhash_mtx);
1635 index += SWAP_META_PAGES;
1637 mtx_unlock(&swhash_mtx);
1642 * SWP_PAGER_FORCE_PAGEIN() - force a swap block to be paged in
1644 * This routine dissociates the page at the given index within a
1645 * swap block from its backing store, paging it in if necessary.
1646 * If the page is paged in, it is placed in the inactive queue,
1647 * since it had its backing store ripped out from under it.
1648 * We also attempt to swap in all other pages in the swap block,
1649 * we only guarantee that the one at the specified index is
1652 * XXX - The code to page the whole block in doesn't work, so we
1653 * revert to the one-by-one behavior for now. Sigh.
1656 swp_pager_force_pagein(vm_object_t object, vm_pindex_t pindex)
1660 vm_object_pip_add(object, 1);
1661 m = vm_page_grab(object, pindex, VM_ALLOC_NORMAL|VM_ALLOC_RETRY);
1662 if (m->valid == VM_PAGE_BITS_ALL) {
1663 vm_object_pip_subtract(object, 1);
1664 vm_page_lock_queues();
1665 vm_page_activate(m);
1667 vm_page_unlock_queues();
1669 vm_pager_page_unswapped(m);
1673 if (swap_pager_getpages(object, &m, 1, 0) != VM_PAGER_OK)
1674 panic("swap_pager_force_pagein: read from swap failed");/*XXX*/
1675 vm_object_pip_subtract(object, 1);
1676 vm_page_lock_queues();
1678 vm_page_dontneed(m);
1679 vm_page_unlock_queues();
1681 vm_pager_page_unswapped(m);
1685 * swap_pager_swapoff:
1687 * Page in all of the pages that have been paged out to the
1688 * given device. The corresponding blocks in the bitmap must be
1689 * marked as allocated and the device must be flagged SW_CLOSING.
1690 * There may be no processes swapped out to the device.
1692 * This routine may block.
1695 swap_pager_swapoff(struct swdevt *sp)
1697 struct swblock *swap;
1704 mtx_lock(&swhash_mtx);
1705 for (i = 0; i <= swhash_mask; i++) { /* '<=' is correct here */
1707 for (swap = swhash[i]; swap != NULL; swap = swap->swb_hnext) {
1708 vm_object_t object = swap->swb_object;
1709 vm_pindex_t pindex = swap->swb_index;
1710 for (j = 0; j < SWAP_META_PAGES; ++j) {
1711 if (swp_pager_isondev(swap->swb_pages[j], sp)) {
1712 /* avoid deadlock */
1713 if (!VM_OBJECT_TRYLOCK(object)) {
1716 mtx_unlock(&swhash_mtx);
1717 swp_pager_force_pagein(object,
1719 VM_OBJECT_UNLOCK(object);
1720 mtx_lock(&swhash_mtx);
1727 mtx_unlock(&swhash_mtx);
1730 * Objects may be locked or paging to the device being
1731 * removed, so we will miss their pages and need to
1732 * make another pass. We have marked this device as
1733 * SW_CLOSING, so the activity should finish soon.
1736 if (retries > 100) {
1737 panic("swapoff: failed to locate %d swap blocks",
1740 pause("swpoff", hz / 20);
1745 /************************************************************************
1747 ************************************************************************
1749 * These routines manipulate the swap metadata stored in the
1752 * Swap metadata is implemented with a global hash and not directly
1753 * linked into the object. Instead the object simply contains
1754 * appropriate tracking counters.
1758 * SWP_PAGER_META_BUILD() - add swap block to swap meta data for object
1760 * We first convert the object to a swap object if it is a default
1763 * The specified swapblk is added to the object's swap metadata. If
1764 * the swapblk is not valid, it is freed instead. Any previously
1765 * assigned swapblk is freed.
1768 swp_pager_meta_build(vm_object_t object, vm_pindex_t pindex, daddr_t swapblk)
1770 struct swblock *swap;
1771 struct swblock **pswap;
1774 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1776 * Convert default object to swap object if necessary
1778 if (object->type != OBJT_SWAP) {
1779 object->type = OBJT_SWAP;
1780 object->un_pager.swp.swp_bcount = 0;
1782 if (object->handle != NULL) {
1783 mtx_lock(&sw_alloc_mtx);
1785 NOBJLIST(object->handle),
1789 mtx_unlock(&sw_alloc_mtx);
1794 * Locate hash entry. If not found create, but if we aren't adding
1795 * anything just return. If we run out of space in the map we wait
1796 * and, since the hash table may have changed, retry.
1799 mtx_lock(&swhash_mtx);
1800 pswap = swp_pager_hash(object, pindex);
1802 if ((swap = *pswap) == NULL) {
1805 if (swapblk == SWAPBLK_NONE)
1808 swap = *pswap = uma_zalloc(swap_zone, M_NOWAIT);
1810 mtx_unlock(&swhash_mtx);
1811 VM_OBJECT_UNLOCK(object);
1812 if (uma_zone_exhausted(swap_zone)) {
1813 printf("swap zone exhausted, increase kern.maxswzone\n");
1814 vm_pageout_oom(VM_OOM_SWAPZ);
1815 pause("swzonex", 10);
1818 VM_OBJECT_LOCK(object);
1822 swap->swb_hnext = NULL;
1823 swap->swb_object = object;
1824 swap->swb_index = pindex & ~(vm_pindex_t)SWAP_META_MASK;
1825 swap->swb_count = 0;
1827 ++object->un_pager.swp.swp_bcount;
1829 for (i = 0; i < SWAP_META_PAGES; ++i)
1830 swap->swb_pages[i] = SWAPBLK_NONE;
1834 * Delete prior contents of metadata
1836 idx = pindex & SWAP_META_MASK;
1838 if (swap->swb_pages[idx] != SWAPBLK_NONE) {
1839 swp_pager_freeswapspace(swap->swb_pages[idx], 1);
1844 * Enter block into metadata
1846 swap->swb_pages[idx] = swapblk;
1847 if (swapblk != SWAPBLK_NONE)
1850 mtx_unlock(&swhash_mtx);
1854 * SWP_PAGER_META_FREE() - free a range of blocks in the object's swap metadata
1856 * The requested range of blocks is freed, with any associated swap
1857 * returned to the swap bitmap.
1859 * This routine will free swap metadata structures as they are cleaned
1860 * out. This routine does *NOT* operate on swap metadata associated
1861 * with resident pages.
1864 swp_pager_meta_free(vm_object_t object, vm_pindex_t index, daddr_t count)
1867 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1868 if (object->type != OBJT_SWAP)
1872 struct swblock **pswap;
1873 struct swblock *swap;
1875 mtx_lock(&swhash_mtx);
1876 pswap = swp_pager_hash(object, index);
1878 if ((swap = *pswap) != NULL) {
1879 daddr_t v = swap->swb_pages[index & SWAP_META_MASK];
1881 if (v != SWAPBLK_NONE) {
1882 swp_pager_freeswapspace(v, 1);
1883 swap->swb_pages[index & SWAP_META_MASK] =
1885 if (--swap->swb_count == 0) {
1886 *pswap = swap->swb_hnext;
1887 uma_zfree(swap_zone, swap);
1888 --object->un_pager.swp.swp_bcount;
1894 int n = SWAP_META_PAGES - (index & SWAP_META_MASK);
1898 mtx_unlock(&swhash_mtx);
1903 * SWP_PAGER_META_FREE_ALL() - destroy all swap metadata associated with object
1905 * This routine locates and destroys all swap metadata associated with
1909 swp_pager_meta_free_all(vm_object_t object)
1913 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1914 if (object->type != OBJT_SWAP)
1917 while (object->un_pager.swp.swp_bcount) {
1918 struct swblock **pswap;
1919 struct swblock *swap;
1921 mtx_lock(&swhash_mtx);
1922 pswap = swp_pager_hash(object, index);
1923 if ((swap = *pswap) != NULL) {
1926 for (i = 0; i < SWAP_META_PAGES; ++i) {
1927 daddr_t v = swap->swb_pages[i];
1928 if (v != SWAPBLK_NONE) {
1930 swp_pager_freeswapspace(v, 1);
1933 if (swap->swb_count != 0)
1934 panic("swap_pager_meta_free_all: swb_count != 0");
1935 *pswap = swap->swb_hnext;
1936 uma_zfree(swap_zone, swap);
1937 --object->un_pager.swp.swp_bcount;
1939 mtx_unlock(&swhash_mtx);
1940 index += SWAP_META_PAGES;
1945 * SWP_PAGER_METACTL() - misc control of swap and vm_page_t meta data.
1947 * This routine is capable of looking up, popping, or freeing
1948 * swapblk assignments in the swap meta data or in the vm_page_t.
1949 * The routine typically returns the swapblk being looked-up, or popped,
1950 * or SWAPBLK_NONE if the block was freed, or SWAPBLK_NONE if the block
1951 * was invalid. This routine will automatically free any invalid
1952 * meta-data swapblks.
1954 * It is not possible to store invalid swapblks in the swap meta data
1955 * (other then a literal 'SWAPBLK_NONE'), so we don't bother checking.
1957 * When acting on a busy resident page and paging is in progress, we
1958 * have to wait until paging is complete but otherwise can act on the
1961 * SWM_FREE remove and free swap block from metadata
1962 * SWM_POP remove from meta data but do not free.. pop it out
1965 swp_pager_meta_ctl(vm_object_t object, vm_pindex_t pindex, int flags)
1967 struct swblock **pswap;
1968 struct swblock *swap;
1972 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1974 * The meta data only exists of the object is OBJT_SWAP
1975 * and even then might not be allocated yet.
1977 if (object->type != OBJT_SWAP)
1978 return (SWAPBLK_NONE);
1981 mtx_lock(&swhash_mtx);
1982 pswap = swp_pager_hash(object, pindex);
1984 if ((swap = *pswap) != NULL) {
1985 idx = pindex & SWAP_META_MASK;
1986 r1 = swap->swb_pages[idx];
1988 if (r1 != SWAPBLK_NONE) {
1989 if (flags & SWM_FREE) {
1990 swp_pager_freeswapspace(r1, 1);
1993 if (flags & (SWM_FREE|SWM_POP)) {
1994 swap->swb_pages[idx] = SWAPBLK_NONE;
1995 if (--swap->swb_count == 0) {
1996 *pswap = swap->swb_hnext;
1997 uma_zfree(swap_zone, swap);
1998 --object->un_pager.swp.swp_bcount;
2003 mtx_unlock(&swhash_mtx);
2008 * System call swapon(name) enables swapping on device name,
2009 * which must be in the swdevsw. Return EBUSY
2010 * if already swapping on this device.
2012 #ifndef _SYS_SYSPROTO_H_
2013 struct swapon_args {
2023 swapon(struct thread *td, struct swapon_args *uap)
2027 struct nameidata nd;
2030 error = priv_check(td, PRIV_SWAPON);
2035 while (swdev_syscall_active)
2036 tsleep(&swdev_syscall_active, PUSER - 1, "swpon", 0);
2037 swdev_syscall_active = 1;
2040 * Swap metadata may not fit in the KVM if we have physical
2043 if (swap_zone == NULL) {
2048 NDINIT(&nd, LOOKUP, ISOPEN | FOLLOW | AUDITVNODE1, UIO_USERSPACE,
2054 NDFREE(&nd, NDF_ONLY_PNBUF);
2057 if (vn_isdisk(vp, &error)) {
2058 error = swapongeom(td, vp);
2059 } else if (vp->v_type == VREG &&
2060 (vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
2061 (error = VOP_GETATTR(vp, &attr, td->td_ucred)) == 0) {
2063 * Allow direct swapping to NFS regular files in the same
2064 * way that nfs_mountroot() sets up diskless swapping.
2066 error = swaponvp(td, vp, attr.va_size / DEV_BSIZE);
2072 swdev_syscall_active = 0;
2073 wakeup_one(&swdev_syscall_active);
2079 swaponsomething(struct vnode *vp, void *id, u_long nblks, sw_strategy_t *strategy, sw_close_t *close, dev_t dev)
2081 struct swdevt *sp, *tsp;
2086 * nblks is in DEV_BSIZE'd chunks, convert to PAGE_SIZE'd chunks.
2087 * First chop nblks off to page-align it, then convert.
2089 * sw->sw_nblks is in page-sized chunks now too.
2091 nblks &= ~(ctodb(1) - 1);
2092 nblks = dbtoc(nblks);
2095 * If we go beyond this, we get overflows in the radix
2098 mblocks = 0x40000000 / BLIST_META_RADIX;
2099 if (nblks > mblocks) {
2101 "WARNING: reducing swap size to maximum of %luMB per unit\n",
2102 mblocks / 1024 / 1024 * PAGE_SIZE);
2106 sp = malloc(sizeof *sp, M_VMPGDATA, M_WAITOK | M_ZERO);
2111 sp->sw_nblks = nblks;
2113 sp->sw_strategy = strategy;
2114 sp->sw_close = close;
2116 sp->sw_blist = blist_create(nblks, M_WAITOK);
2118 * Do not free the first two block in order to avoid overwriting
2119 * any bsd label at the front of the partition
2121 blist_free(sp->sw_blist, 2, nblks - 2);
2124 mtx_lock(&sw_dev_mtx);
2125 TAILQ_FOREACH(tsp, &swtailq, sw_list) {
2126 if (tsp->sw_end >= dvbase) {
2128 * We put one uncovered page between the devices
2129 * in order to definitively prevent any cross-device
2132 dvbase = tsp->sw_end + 1;
2135 sp->sw_first = dvbase;
2136 sp->sw_end = dvbase + nblks;
2137 TAILQ_INSERT_TAIL(&swtailq, sp, sw_list);
2139 swap_pager_avail += nblks;
2140 swap_total += (vm_ooffset_t)nblks * PAGE_SIZE;
2142 mtx_unlock(&sw_dev_mtx);
2146 * SYSCALL: swapoff(devname)
2148 * Disable swapping on the given device.
2150 * XXX: Badly designed system call: it should use a device index
2151 * rather than filename as specification. We keep sw_vp around
2152 * only to make this work.
2154 #ifndef _SYS_SYSPROTO_H_
2155 struct swapoff_args {
2165 swapoff(struct thread *td, struct swapoff_args *uap)
2168 struct nameidata nd;
2172 error = priv_check(td, PRIV_SWAPOFF);
2177 while (swdev_syscall_active)
2178 tsleep(&swdev_syscall_active, PUSER - 1, "swpoff", 0);
2179 swdev_syscall_active = 1;
2181 NDINIT(&nd, LOOKUP, FOLLOW | AUDITVNODE1, UIO_USERSPACE, uap->name,
2186 NDFREE(&nd, NDF_ONLY_PNBUF);
2189 mtx_lock(&sw_dev_mtx);
2190 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2191 if (sp->sw_vp == vp)
2194 mtx_unlock(&sw_dev_mtx);
2199 error = swapoff_one(sp, td->td_ucred);
2201 swdev_syscall_active = 0;
2202 wakeup_one(&swdev_syscall_active);
2208 swapoff_one(struct swdevt *sp, struct ucred *cred)
2210 u_long nblks, dvbase;
2215 mtx_assert(&Giant, MA_OWNED);
2217 (void) vn_lock(sp->sw_vp, LK_EXCLUSIVE | LK_RETRY);
2218 error = mac_system_check_swapoff(cred, sp->sw_vp);
2219 (void) VOP_UNLOCK(sp->sw_vp, 0);
2223 nblks = sp->sw_nblks;
2226 * We can turn off this swap device safely only if the
2227 * available virtual memory in the system will fit the amount
2228 * of data we will have to page back in, plus an epsilon so
2229 * the system doesn't become critically low on swap space.
2231 if (cnt.v_free_count + cnt.v_cache_count + swap_pager_avail <
2232 nblks + nswap_lowat) {
2237 * Prevent further allocations on this device.
2239 mtx_lock(&sw_dev_mtx);
2240 sp->sw_flags |= SW_CLOSING;
2241 for (dvbase = 0; dvbase < sp->sw_end; dvbase += dmmax) {
2242 swap_pager_avail -= blist_fill(sp->sw_blist,
2245 swap_total -= (vm_ooffset_t)nblks * PAGE_SIZE;
2246 mtx_unlock(&sw_dev_mtx);
2249 * Page in the contents of the device and close it.
2251 swap_pager_swapoff(sp);
2253 sp->sw_close(curthread, sp);
2255 mtx_lock(&sw_dev_mtx);
2256 TAILQ_REMOVE(&swtailq, sp, sw_list);
2258 if (nswapdev == 0) {
2259 swap_pager_full = 2;
2260 swap_pager_almost_full = 1;
2264 mtx_unlock(&sw_dev_mtx);
2265 blist_destroy(sp->sw_blist);
2266 free(sp, M_VMPGDATA);
2273 struct swdevt *sp, *spt;
2274 const char *devname;
2278 while (swdev_syscall_active)
2279 tsleep(&swdev_syscall_active, PUSER - 1, "swpoff", 0);
2280 swdev_syscall_active = 1;
2282 mtx_lock(&sw_dev_mtx);
2283 TAILQ_FOREACH_SAFE(sp, &swtailq, sw_list, spt) {
2284 mtx_unlock(&sw_dev_mtx);
2285 if (vn_isdisk(sp->sw_vp, NULL))
2286 devname = sp->sw_vp->v_rdev->si_name;
2289 error = swapoff_one(sp, thread0.td_ucred);
2291 printf("Cannot remove swap device %s (error=%d), "
2292 "skipping.\n", devname, error);
2293 } else if (bootverbose) {
2294 printf("Swap device %s removed.\n", devname);
2296 mtx_lock(&sw_dev_mtx);
2298 mtx_unlock(&sw_dev_mtx);
2300 swdev_syscall_active = 0;
2301 wakeup_one(&swdev_syscall_active);
2306 swap_pager_status(int *total, int *used)
2312 mtx_lock(&sw_dev_mtx);
2313 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2314 *total += sp->sw_nblks;
2315 *used += sp->sw_used;
2317 mtx_unlock(&sw_dev_mtx);
2321 swap_dev_info(int name, struct xswdev *xs, char *devname, size_t len)
2329 mtx_lock(&sw_dev_mtx);
2330 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2335 xs->xsw_version = XSWDEV_VERSION;
2336 xs->xsw_dev = sp->sw_dev;
2337 xs->xsw_flags = sp->sw_flags;
2338 xs->xsw_nblks = sp->sw_nblks;
2339 xs->xsw_used = sp->sw_used;
2340 if (devname != NULL) {
2341 if (vn_isdisk(sp->sw_vp, NULL))
2342 tmp_devname = sp->sw_vp->v_rdev->si_name;
2344 tmp_devname = "[file]";
2345 strncpy(devname, tmp_devname, len);
2350 mtx_unlock(&sw_dev_mtx);
2355 sysctl_vm_swap_info(SYSCTL_HANDLER_ARGS)
2360 if (arg2 != 1) /* name length */
2362 error = swap_dev_info(*(int *)arg1, &xs, NULL, 0);
2365 error = SYSCTL_OUT(req, &xs, sizeof(xs));
2369 SYSCTL_INT(_vm, OID_AUTO, nswapdev, CTLFLAG_RD, &nswapdev, 0,
2370 "Number of swap devices");
2371 SYSCTL_NODE(_vm, OID_AUTO, swap_info, CTLFLAG_RD, sysctl_vm_swap_info,
2372 "Swap statistics by device");
2375 * vmspace_swap_count() - count the approximate swap usage in pages for a
2378 * The map must be locked.
2380 * Swap usage is determined by taking the proportional swap used by
2381 * VM objects backing the VM map. To make up for fractional losses,
2382 * if the VM object has any swap use at all the associated map entries
2383 * count for at least 1 swap page.
2386 vmspace_swap_count(struct vmspace *vmspace)
2393 map = &vmspace->vm_map;
2396 for (cur = map->header.next; cur != &map->header; cur = cur->next) {
2397 if ((cur->eflags & MAP_ENTRY_IS_SUB_MAP) == 0 &&
2398 (object = cur->object.vm_object) != NULL) {
2399 VM_OBJECT_LOCK(object);
2400 if (object->type == OBJT_SWAP &&
2401 object->un_pager.swp.swp_bcount != 0) {
2402 n = (cur->end - cur->start) / PAGE_SIZE;
2403 count += object->un_pager.swp.swp_bcount *
2404 SWAP_META_PAGES * n / object->size + 1;
2406 VM_OBJECT_UNLOCK(object);
2415 * Swapping onto disk devices.
2419 static g_orphan_t swapgeom_orphan;
2421 static struct g_class g_swap_class = {
2423 .version = G_VERSION,
2424 .orphan = swapgeom_orphan,
2427 DECLARE_GEOM_CLASS(g_swap_class, g_class);
2431 swapgeom_done(struct bio *bp2)
2435 bp = bp2->bio_caller2;
2436 bp->b_ioflags = bp2->bio_flags;
2438 bp->b_ioflags |= BIO_ERROR;
2439 bp->b_resid = bp->b_bcount - bp2->bio_completed;
2440 bp->b_error = bp2->bio_error;
2446 swapgeom_strategy(struct buf *bp, struct swdevt *sp)
2449 struct g_consumer *cp;
2453 bp->b_error = ENXIO;
2454 bp->b_ioflags |= BIO_ERROR;
2458 if (bp->b_iocmd == BIO_WRITE)
2461 bio = g_alloc_bio();
2463 bp->b_error = ENOMEM;
2464 bp->b_ioflags |= BIO_ERROR;
2469 bio->bio_caller2 = bp;
2470 bio->bio_cmd = bp->b_iocmd;
2471 bio->bio_data = bp->b_data;
2472 bio->bio_offset = (bp->b_blkno - sp->sw_first) * PAGE_SIZE;
2473 bio->bio_length = bp->b_bcount;
2474 bio->bio_done = swapgeom_done;
2475 g_io_request(bio, cp);
2480 swapgeom_orphan(struct g_consumer *cp)
2484 mtx_lock(&sw_dev_mtx);
2485 TAILQ_FOREACH(sp, &swtailq, sw_list)
2486 if (sp->sw_id == cp)
2487 sp->sw_flags |= SW_CLOSING;
2488 mtx_unlock(&sw_dev_mtx);
2492 swapgeom_close_ev(void *arg, int flags)
2494 struct g_consumer *cp;
2497 g_access(cp, -1, -1, 0);
2499 g_destroy_consumer(cp);
2503 swapgeom_close(struct thread *td, struct swdevt *sw)
2506 /* XXX: direct call when Giant untangled */
2507 g_waitfor_event(swapgeom_close_ev, sw->sw_id, M_WAITOK, NULL);
2518 swapongeom_ev(void *arg, int flags)
2521 struct g_provider *pp;
2522 struct g_consumer *cp;
2523 static struct g_geom *gp;
2530 pp = g_dev_getprovider(swh->dev);
2532 swh->error = ENODEV;
2535 mtx_lock(&sw_dev_mtx);
2536 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2538 if (cp != NULL && cp->provider == pp) {
2539 mtx_unlock(&sw_dev_mtx);
2544 mtx_unlock(&sw_dev_mtx);
2546 gp = g_new_geomf(&g_swap_class, "swap", NULL);
2547 cp = g_new_consumer(gp);
2550 * XXX: Everytime you think you can improve the margin for
2551 * footshooting, somebody depends on the ability to do so:
2552 * savecore(8) wants to write to our swapdev so we cannot
2553 * set an exclusive count :-(
2555 error = g_access(cp, 1, 1, 0);
2558 g_destroy_consumer(cp);
2562 nblks = pp->mediasize / DEV_BSIZE;
2563 swaponsomething(swh->vp, cp, nblks, swapgeom_strategy,
2564 swapgeom_close, dev2udev(swh->dev));
2570 swapongeom(struct thread *td, struct vnode *vp)
2575 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2577 swh.dev = vp->v_rdev;
2580 /* XXX: direct call when Giant untangled */
2581 error = g_waitfor_event(swapongeom_ev, &swh, M_WAITOK, NULL);
2591 * This is used mainly for network filesystem (read: probably only tested
2592 * with NFS) swapfiles.
2597 swapdev_strategy(struct buf *bp, struct swdevt *sp)
2601 bp->b_blkno = ctodb(bp->b_blkno - sp->sw_first);
2605 if (bp->b_iocmd == BIO_WRITE) {
2607 bufobj_wdrop(bp->b_bufobj);
2608 bufobj_wref(&vp2->v_bufobj);
2610 if (bp->b_bufobj != &vp2->v_bufobj)
2611 bp->b_bufobj = &vp2->v_bufobj;
2613 bp->b_iooffset = dbtob(bp->b_blkno);
2619 swapdev_close(struct thread *td, struct swdevt *sp)
2622 VOP_CLOSE(sp->sw_vp, FREAD | FWRITE, td->td_ucred, td);
2628 swaponvp(struct thread *td, struct vnode *vp, u_long nblks)
2635 mtx_lock(&sw_dev_mtx);
2636 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2637 if (sp->sw_id == vp) {
2638 mtx_unlock(&sw_dev_mtx);
2642 mtx_unlock(&sw_dev_mtx);
2644 (void) vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2646 error = mac_system_check_swapon(td->td_ucred, vp);
2649 error = VOP_OPEN(vp, FREAD | FWRITE, td->td_ucred, td, NULL);
2650 (void) VOP_UNLOCK(vp, 0);
2654 swaponsomething(vp, vp, nblks, swapdev_strategy, swapdev_close,