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/racct.h>
90 #include <sys/resource.h>
91 #include <sys/resourcevar.h>
92 #include <sys/rwlock.h>
93 #include <sys/sysctl.h>
94 #include <sys/sysproto.h>
95 #include <sys/blist.h>
98 #include <sys/vmmeter.h>
100 #include <security/mac/mac_framework.h>
104 #include <vm/vm_map.h>
105 #include <vm/vm_kern.h>
106 #include <vm/vm_object.h>
107 #include <vm/vm_page.h>
108 #include <vm/vm_pager.h>
109 #include <vm/vm_pageout.h>
110 #include <vm/vm_param.h>
111 #include <vm/swap_pager.h>
112 #include <vm/vm_extern.h>
115 #include <geom/geom.h>
118 * SWB_NPAGES must be a power of 2. It may be set to 1, 2, 4, 8, 16
119 * or 32 pages per allocation.
120 * The 32-page limit is due to the radix code (kern/subr_blist.c).
122 #ifndef MAX_PAGEOUT_CLUSTER
123 #define MAX_PAGEOUT_CLUSTER 16
126 #if !defined(SWB_NPAGES)
127 #define SWB_NPAGES MAX_PAGEOUT_CLUSTER
131 * The swblock structure maps an object and a small, fixed-size range
132 * of page indices to disk addresses within a swap area.
133 * The collection of these mappings is implemented as a hash table.
134 * Unused disk addresses within a swap area are allocated and managed
137 #define SWCORRECT(n) (sizeof(void *) * (n) / sizeof(daddr_t))
138 #define SWAP_META_PAGES (SWB_NPAGES * 2)
139 #define SWAP_META_MASK (SWAP_META_PAGES - 1)
142 struct swblock *swb_hnext;
143 vm_object_t swb_object;
144 vm_pindex_t swb_index;
146 daddr_t swb_pages[SWAP_META_PAGES];
149 static MALLOC_DEFINE(M_VMPGDATA, "vm_pgdata", "swap pager private data");
150 static struct mtx sw_dev_mtx;
151 static TAILQ_HEAD(, swdevt) swtailq = TAILQ_HEAD_INITIALIZER(swtailq);
152 static struct swdevt *swdevhd; /* Allocate from here next */
153 static int nswapdev; /* Number of swap devices */
154 int swap_pager_avail;
155 static int swdev_syscall_active = 0; /* serialize swap(on|off) */
157 static vm_ooffset_t swap_total;
158 SYSCTL_QUAD(_vm, OID_AUTO, swap_total, CTLFLAG_RD, &swap_total, 0,
159 "Total amount of available swap storage.");
160 static vm_ooffset_t swap_reserved;
161 SYSCTL_QUAD(_vm, OID_AUTO, swap_reserved, CTLFLAG_RD, &swap_reserved, 0,
162 "Amount of swap storage needed to back all allocated anonymous memory.");
163 static int overcommit = 0;
164 SYSCTL_INT(_vm, OID_AUTO, overcommit, CTLFLAG_RW, &overcommit, 0,
165 "Configure virtual memory overcommit behavior. See tuning(7) "
167 static unsigned long swzone;
168 SYSCTL_ULONG(_vm, OID_AUTO, swzone, CTLFLAG_RD, &swzone, 0,
169 "Actual size of swap metadata zone");
170 static unsigned long swap_maxpages;
171 SYSCTL_ULONG(_vm, OID_AUTO, swap_maxpages, CTLFLAG_RD, &swap_maxpages, 0,
172 "Maximum amount of swap supported");
174 /* bits from overcommit */
175 #define SWAP_RESERVE_FORCE_ON (1 << 0)
176 #define SWAP_RESERVE_RLIMIT_ON (1 << 1)
177 #define SWAP_RESERVE_ALLOW_NONWIRED (1 << 2)
180 swap_reserve(vm_ooffset_t incr)
183 return (swap_reserve_by_cred(incr, curthread->td_ucred));
187 swap_reserve_by_cred(vm_ooffset_t incr, struct ucred *cred)
192 static struct timeval lastfail;
195 uip = cred->cr_ruidinfo;
197 if (incr & PAGE_MASK)
198 panic("swap_reserve: & PAGE_MASK");
203 error = racct_add(curproc, RACCT_SWAP, incr);
204 PROC_UNLOCK(curproc);
211 mtx_lock(&sw_dev_mtx);
212 r = swap_reserved + incr;
213 if (overcommit & SWAP_RESERVE_ALLOW_NONWIRED) {
214 s = vm_cnt.v_page_count - vm_cnt.v_free_reserved - vm_cnt.v_wire_count;
219 if ((overcommit & SWAP_RESERVE_FORCE_ON) == 0 || r <= s ||
220 (error = priv_check(curthread, PRIV_VM_SWAP_NOQUOTA)) == 0) {
224 mtx_unlock(&sw_dev_mtx);
228 UIDINFO_VMSIZE_LOCK(uip);
229 if ((overcommit & SWAP_RESERVE_RLIMIT_ON) != 0 &&
230 uip->ui_vmsize + incr > lim_cur(curproc, RLIMIT_SWAP) &&
231 priv_check(curthread, PRIV_VM_SWAP_NORLIMIT))
234 uip->ui_vmsize += incr;
235 UIDINFO_VMSIZE_UNLOCK(uip);
236 PROC_UNLOCK(curproc);
238 mtx_lock(&sw_dev_mtx);
239 swap_reserved -= incr;
240 mtx_unlock(&sw_dev_mtx);
243 if (!res && ppsratecheck(&lastfail, &curfail, 1)) {
244 printf("uid %d, pid %d: swap reservation for %jd bytes failed\n",
245 uip->ui_uid, curproc->p_pid, incr);
251 racct_sub(curproc, RACCT_SWAP, incr);
252 PROC_UNLOCK(curproc);
260 swap_reserve_force(vm_ooffset_t incr)
264 mtx_lock(&sw_dev_mtx);
265 swap_reserved += incr;
266 mtx_unlock(&sw_dev_mtx);
270 racct_add_force(curproc, RACCT_SWAP, incr);
271 PROC_UNLOCK(curproc);
274 uip = curthread->td_ucred->cr_ruidinfo;
276 UIDINFO_VMSIZE_LOCK(uip);
277 uip->ui_vmsize += incr;
278 UIDINFO_VMSIZE_UNLOCK(uip);
279 PROC_UNLOCK(curproc);
283 swap_release(vm_ooffset_t decr)
288 cred = curthread->td_ucred;
289 swap_release_by_cred(decr, cred);
290 PROC_UNLOCK(curproc);
294 swap_release_by_cred(vm_ooffset_t decr, struct ucred *cred)
298 uip = cred->cr_ruidinfo;
300 if (decr & PAGE_MASK)
301 panic("swap_release: & PAGE_MASK");
303 mtx_lock(&sw_dev_mtx);
304 if (swap_reserved < decr)
305 panic("swap_reserved < decr");
306 swap_reserved -= decr;
307 mtx_unlock(&sw_dev_mtx);
309 UIDINFO_VMSIZE_LOCK(uip);
310 if (uip->ui_vmsize < decr)
311 printf("negative vmsize for uid = %d\n", uip->ui_uid);
312 uip->ui_vmsize -= decr;
313 UIDINFO_VMSIZE_UNLOCK(uip);
315 racct_sub_cred(cred, RACCT_SWAP, decr);
318 static void swapdev_strategy(struct buf *, struct swdevt *sw);
320 #define SWM_FREE 0x02 /* free, period */
321 #define SWM_POP 0x04 /* pop out */
323 int swap_pager_full = 2; /* swap space exhaustion (task killing) */
324 static int swap_pager_almost_full = 1; /* swap space exhaustion (w/hysteresis)*/
325 static int nsw_rcount; /* free read buffers */
326 static int nsw_wcount_sync; /* limit write buffers / synchronous */
327 static int nsw_wcount_async; /* limit write buffers / asynchronous */
328 static int nsw_wcount_async_max;/* assigned maximum */
329 static int nsw_cluster_max; /* maximum VOP I/O allowed */
331 static int sysctl_swap_async_max(SYSCTL_HANDLER_ARGS);
332 SYSCTL_PROC(_vm, OID_AUTO, swap_async_max, CTLTYPE_INT | CTLFLAG_RW,
333 NULL, 0, sysctl_swap_async_max, "I", "Maximum running async swap ops");
335 static struct swblock **swhash;
336 static int swhash_mask;
337 static struct mtx swhash_mtx;
339 static struct sx sw_alloc_sx;
342 * "named" and "unnamed" anon region objects. Try to reduce the overhead
343 * of searching a named list by hashing it just a little.
348 #define NOBJLIST(handle) \
349 (&swap_pager_object_list[((int)(intptr_t)handle >> 4) & (NOBJLISTS-1)])
351 static struct mtx sw_alloc_mtx; /* protect list manipulation */
352 static struct pagerlst swap_pager_object_list[NOBJLISTS];
353 static uma_zone_t swap_zone;
356 * pagerops for OBJT_SWAP - "swap pager". Some ops are also global procedure
357 * calls hooked from other parts of the VM system and do not appear here.
358 * (see vm/swap_pager.h).
361 swap_pager_alloc(void *handle, vm_ooffset_t size,
362 vm_prot_t prot, vm_ooffset_t offset, struct ucred *);
363 static void swap_pager_dealloc(vm_object_t object);
364 static int swap_pager_getpages(vm_object_t, vm_page_t *, int, int);
365 static int swap_pager_getpages_async(vm_object_t, vm_page_t *, int, int,
366 pgo_getpages_iodone_t, void *);
367 static void swap_pager_putpages(vm_object_t, vm_page_t *, int, boolean_t, int *);
369 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before, int *after);
370 static void swap_pager_init(void);
371 static void swap_pager_unswapped(vm_page_t);
372 static void swap_pager_swapoff(struct swdevt *sp);
374 struct pagerops swappagerops = {
375 .pgo_init = swap_pager_init, /* early system initialization of pager */
376 .pgo_alloc = swap_pager_alloc, /* allocate an OBJT_SWAP object */
377 .pgo_dealloc = swap_pager_dealloc, /* deallocate an OBJT_SWAP object */
378 .pgo_getpages = swap_pager_getpages, /* pagein */
379 .pgo_getpages_async = swap_pager_getpages_async, /* pagein (async) */
380 .pgo_putpages = swap_pager_putpages, /* pageout */
381 .pgo_haspage = swap_pager_haspage, /* get backing store status for page */
382 .pgo_pageunswapped = swap_pager_unswapped, /* remove swap related to page */
386 * dmmax is in page-sized chunks with the new swap system. It was
387 * dev-bsized chunks in the old. dmmax is always a power of 2.
389 * swap_*() routines are externally accessible. swp_*() routines are
393 static int nswap_lowat = 128; /* in pages, swap_pager_almost_full warn */
394 static int nswap_hiwat = 512; /* in pages, swap_pager_almost_full warn */
396 SYSCTL_INT(_vm, OID_AUTO, dmmax,
397 CTLFLAG_RD, &dmmax, 0, "Maximum size of a swap block");
399 static void swp_sizecheck(void);
400 static void swp_pager_async_iodone(struct buf *bp);
401 static int swapongeom(struct thread *, struct vnode *);
402 static int swaponvp(struct thread *, struct vnode *, u_long);
403 static int swapoff_one(struct swdevt *sp, struct ucred *cred);
406 * Swap bitmap functions
408 static void swp_pager_freeswapspace(daddr_t blk, int npages);
409 static daddr_t swp_pager_getswapspace(int npages);
414 static struct swblock **swp_pager_hash(vm_object_t object, vm_pindex_t index);
415 static void swp_pager_meta_build(vm_object_t, vm_pindex_t, daddr_t);
416 static void swp_pager_meta_free(vm_object_t, vm_pindex_t, daddr_t);
417 static void swp_pager_meta_free_all(vm_object_t);
418 static daddr_t swp_pager_meta_ctl(vm_object_t, vm_pindex_t, int);
421 swp_pager_free_nrpage(vm_page_t m)
425 if (m->wire_count == 0)
431 * SWP_SIZECHECK() - update swap_pager_full indication
433 * update the swap_pager_almost_full indication and warn when we are
434 * about to run out of swap space, using lowat/hiwat hysteresis.
436 * Clear swap_pager_full ( task killing ) indication when lowat is met.
438 * No restrictions on call
439 * This routine may not block.
445 if (swap_pager_avail < nswap_lowat) {
446 if (swap_pager_almost_full == 0) {
447 printf("swap_pager: out of swap space\n");
448 swap_pager_almost_full = 1;
452 if (swap_pager_avail > nswap_hiwat)
453 swap_pager_almost_full = 0;
458 * SWP_PAGER_HASH() - hash swap meta data
460 * This is an helper function which hashes the swapblk given
461 * the object and page index. It returns a pointer to a pointer
462 * to the object, or a pointer to a NULL pointer if it could not
465 static struct swblock **
466 swp_pager_hash(vm_object_t object, vm_pindex_t index)
468 struct swblock **pswap;
469 struct swblock *swap;
471 index &= ~(vm_pindex_t)SWAP_META_MASK;
472 pswap = &swhash[(index ^ (int)(intptr_t)object) & swhash_mask];
473 while ((swap = *pswap) != NULL) {
474 if (swap->swb_object == object &&
475 swap->swb_index == index
479 pswap = &swap->swb_hnext;
485 * SWAP_PAGER_INIT() - initialize the swap pager!
487 * Expected to be started from system init. NOTE: This code is run
488 * before much else so be careful what you depend on. Most of the VM
489 * system has yet to be initialized at this point.
492 swap_pager_init(void)
495 * Initialize object lists
499 for (i = 0; i < NOBJLISTS; ++i)
500 TAILQ_INIT(&swap_pager_object_list[i]);
501 mtx_init(&sw_alloc_mtx, "swap_pager list", NULL, MTX_DEF);
502 mtx_init(&sw_dev_mtx, "swapdev", NULL, MTX_DEF);
505 * Device Stripe, in PAGE_SIZE'd blocks
507 dmmax = SWB_NPAGES * 2;
511 * SWAP_PAGER_SWAP_INIT() - swap pager initialization from pageout process
513 * Expected to be started from pageout process once, prior to entering
517 swap_pager_swap_init(void)
522 * Number of in-transit swap bp operations. Don't
523 * exhaust the pbufs completely. Make sure we
524 * initialize workable values (0 will work for hysteresis
525 * but it isn't very efficient).
527 * The nsw_cluster_max is constrained by the bp->b_pages[]
528 * array (MAXPHYS/PAGE_SIZE) and our locally defined
529 * MAX_PAGEOUT_CLUSTER. Also be aware that swap ops are
530 * constrained by the swap device interleave stripe size.
532 * Currently we hardwire nsw_wcount_async to 4. This limit is
533 * designed to prevent other I/O from having high latencies due to
534 * our pageout I/O. The value 4 works well for one or two active swap
535 * devices but is probably a little low if you have more. Even so,
536 * a higher value would probably generate only a limited improvement
537 * with three or four active swap devices since the system does not
538 * typically have to pageout at extreme bandwidths. We will want
539 * at least 2 per swap devices, and 4 is a pretty good value if you
540 * have one NFS swap device due to the command/ack latency over NFS.
541 * So it all works out pretty well.
543 nsw_cluster_max = min((MAXPHYS/PAGE_SIZE), MAX_PAGEOUT_CLUSTER);
546 nsw_rcount = (nswbuf + 1) / 2;
547 nsw_wcount_sync = (nswbuf + 3) / 4;
548 nsw_wcount_async = 4;
549 nsw_wcount_async_max = nsw_wcount_async;
550 mtx_unlock(&pbuf_mtx);
553 * Initialize our zone. Right now I'm just guessing on the number
554 * we need based on the number of pages in the system. Each swblock
555 * can hold 32 pages, so this is probably overkill. This reservation
556 * is typically limited to around 32MB by default.
558 n = vm_cnt.v_page_count / 2;
559 if (maxswzone && n > maxswzone / sizeof(struct swblock))
560 n = maxswzone / sizeof(struct swblock);
562 swap_zone = uma_zcreate("SWAPMETA", sizeof(struct swblock), NULL, NULL,
563 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
564 if (swap_zone == NULL)
565 panic("failed to create swap_zone.");
567 if (uma_zone_reserve_kva(swap_zone, n))
570 * if the allocation failed, try a zone two thirds the
571 * size of the previous attempt.
576 printf("Swap zone entries reduced from %lu to %lu.\n", n2, n);
577 swap_maxpages = n * SWAP_META_PAGES;
578 swzone = n * sizeof(struct swblock);
582 * Initialize our meta-data hash table. The swapper does not need to
583 * be quite as efficient as the VM system, so we do not use an
584 * oversized hash table.
586 * n: size of hash table, must be power of 2
587 * swhash_mask: hash table index mask
589 for (n = 1; n < n2 / 8; n *= 2)
591 swhash = malloc(sizeof(struct swblock *) * n, M_VMPGDATA, M_WAITOK | M_ZERO);
593 mtx_init(&swhash_mtx, "swap_pager swhash", NULL, MTX_DEF);
597 * SWAP_PAGER_ALLOC() - allocate a new OBJT_SWAP VM object and instantiate
598 * its metadata structures.
600 * This routine is called from the mmap and fork code to create a new
601 * OBJT_SWAP object. We do this by creating an OBJT_DEFAULT object
602 * and then converting it with swp_pager_meta_build().
604 * This routine may block in vm_object_allocate() and create a named
605 * object lookup race, so we must interlock.
610 swap_pager_alloc(void *handle, vm_ooffset_t size, vm_prot_t prot,
611 vm_ooffset_t offset, struct ucred *cred)
616 pindex = OFF_TO_IDX(offset + PAGE_MASK + size);
620 * Reference existing named region or allocate new one. There
621 * should not be a race here against swp_pager_meta_build()
622 * as called from vm_page_remove() in regards to the lookup
625 sx_xlock(&sw_alloc_sx);
626 object = vm_pager_object_lookup(NOBJLIST(handle), handle);
627 if (object == NULL) {
629 if (!swap_reserve_by_cred(size, cred)) {
630 sx_xunlock(&sw_alloc_sx);
636 object = vm_object_allocate(OBJT_DEFAULT, pindex);
637 VM_OBJECT_WLOCK(object);
638 object->handle = handle;
641 object->charge = size;
643 swp_pager_meta_build(object, 0, SWAPBLK_NONE);
644 VM_OBJECT_WUNLOCK(object);
646 sx_xunlock(&sw_alloc_sx);
650 if (!swap_reserve_by_cred(size, cred))
654 object = vm_object_allocate(OBJT_DEFAULT, pindex);
655 VM_OBJECT_WLOCK(object);
658 object->charge = size;
660 swp_pager_meta_build(object, 0, SWAPBLK_NONE);
661 VM_OBJECT_WUNLOCK(object);
667 * SWAP_PAGER_DEALLOC() - remove swap metadata from object
669 * The swap backing for the object is destroyed. The code is
670 * designed such that we can reinstantiate it later, but this
671 * routine is typically called only when the entire object is
672 * about to be destroyed.
674 * The object must be locked.
677 swap_pager_dealloc(vm_object_t object)
681 * Remove from list right away so lookups will fail if we block for
682 * pageout completion.
684 if (object->handle != NULL) {
685 mtx_lock(&sw_alloc_mtx);
686 TAILQ_REMOVE(NOBJLIST(object->handle), object, pager_object_list);
687 mtx_unlock(&sw_alloc_mtx);
690 VM_OBJECT_ASSERT_WLOCKED(object);
691 vm_object_pip_wait(object, "swpdea");
694 * Free all remaining metadata. We only bother to free it from
695 * the swap meta data. We do not attempt to free swapblk's still
696 * associated with vm_page_t's for this object. We do not care
697 * if paging is still in progress on some objects.
699 swp_pager_meta_free_all(object);
700 object->handle = NULL;
701 object->type = OBJT_DEAD;
704 /************************************************************************
705 * SWAP PAGER BITMAP ROUTINES *
706 ************************************************************************/
709 * SWP_PAGER_GETSWAPSPACE() - allocate raw swap space
711 * Allocate swap for the requested number of pages. The starting
712 * swap block number (a page index) is returned or SWAPBLK_NONE
713 * if the allocation failed.
715 * Also has the side effect of advising that somebody made a mistake
716 * when they configured swap and didn't configure enough.
718 * This routine may not sleep.
720 * We allocate in round-robin fashion from the configured devices.
723 swp_pager_getswapspace(int npages)
730 mtx_lock(&sw_dev_mtx);
732 for (i = 0; i < nswapdev; i++) {
734 sp = TAILQ_FIRST(&swtailq);
735 if (!(sp->sw_flags & SW_CLOSING)) {
736 blk = blist_alloc(sp->sw_blist, npages);
737 if (blk != SWAPBLK_NONE) {
739 sp->sw_used += npages;
740 swap_pager_avail -= npages;
742 swdevhd = TAILQ_NEXT(sp, sw_list);
746 sp = TAILQ_NEXT(sp, sw_list);
748 if (swap_pager_full != 2) {
749 printf("swap_pager_getswapspace(%d): failed\n", npages);
751 swap_pager_almost_full = 1;
755 mtx_unlock(&sw_dev_mtx);
760 swp_pager_isondev(daddr_t blk, struct swdevt *sp)
763 return (blk >= sp->sw_first && blk < sp->sw_end);
767 swp_pager_strategy(struct buf *bp)
771 mtx_lock(&sw_dev_mtx);
772 TAILQ_FOREACH(sp, &swtailq, sw_list) {
773 if (bp->b_blkno >= sp->sw_first && bp->b_blkno < sp->sw_end) {
774 mtx_unlock(&sw_dev_mtx);
775 if ((sp->sw_flags & SW_UNMAPPED) != 0 &&
776 unmapped_buf_allowed) {
777 bp->b_kvaalloc = bp->b_data;
778 bp->b_data = unmapped_buf;
779 bp->b_kvabase = unmapped_buf;
781 bp->b_flags |= B_UNMAPPED;
783 pmap_qenter((vm_offset_t)bp->b_data,
784 &bp->b_pages[0], bp->b_bcount / PAGE_SIZE);
786 sp->sw_strategy(bp, sp);
790 panic("Swapdev not found");
795 * SWP_PAGER_FREESWAPSPACE() - free raw swap space
797 * This routine returns the specified swap blocks back to the bitmap.
799 * This routine may not sleep.
802 swp_pager_freeswapspace(daddr_t blk, int npages)
806 mtx_lock(&sw_dev_mtx);
807 TAILQ_FOREACH(sp, &swtailq, sw_list) {
808 if (blk >= sp->sw_first && blk < sp->sw_end) {
809 sp->sw_used -= npages;
811 * If we are attempting to stop swapping on
812 * this device, we don't want to mark any
813 * blocks free lest they be reused.
815 if ((sp->sw_flags & SW_CLOSING) == 0) {
816 blist_free(sp->sw_blist, blk - sp->sw_first,
818 swap_pager_avail += npages;
821 mtx_unlock(&sw_dev_mtx);
825 panic("Swapdev not found");
829 * SWAP_PAGER_FREESPACE() - frees swap blocks associated with a page
830 * range within an object.
832 * This is a globally accessible routine.
834 * This routine removes swapblk assignments from swap metadata.
836 * The external callers of this routine typically have already destroyed
837 * or renamed vm_page_t's associated with this range in the object so
840 * The object must be locked.
843 swap_pager_freespace(vm_object_t object, vm_pindex_t start, vm_size_t size)
846 swp_pager_meta_free(object, start, size);
850 * SWAP_PAGER_RESERVE() - reserve swap blocks in object
852 * Assigns swap blocks to the specified range within the object. The
853 * swap blocks are not zeroed. Any previous swap assignment is destroyed.
855 * Returns 0 on success, -1 on failure.
858 swap_pager_reserve(vm_object_t object, vm_pindex_t start, vm_size_t size)
861 daddr_t blk = SWAPBLK_NONE;
862 vm_pindex_t beg = start; /* save start index */
864 VM_OBJECT_WLOCK(object);
868 while ((blk = swp_pager_getswapspace(n)) == SWAPBLK_NONE) {
871 swp_pager_meta_free(object, beg, start - beg);
872 VM_OBJECT_WUNLOCK(object);
877 swp_pager_meta_build(object, start, blk);
883 swp_pager_meta_free(object, start, n);
884 VM_OBJECT_WUNLOCK(object);
889 * SWAP_PAGER_COPY() - copy blocks from source pager to destination pager
890 * and destroy the source.
892 * Copy any valid swapblks from the source to the destination. In
893 * cases where both the source and destination have a valid swapblk,
894 * we keep the destination's.
896 * This routine is allowed to sleep. It may sleep allocating metadata
897 * indirectly through swp_pager_meta_build() or if paging is still in
898 * progress on the source.
900 * The source object contains no vm_page_t's (which is just as well)
902 * The source object is of type OBJT_SWAP.
904 * The source and destination objects must be locked.
905 * Both object locks may temporarily be released.
908 swap_pager_copy(vm_object_t srcobject, vm_object_t dstobject,
909 vm_pindex_t offset, int destroysource)
913 VM_OBJECT_ASSERT_WLOCKED(srcobject);
914 VM_OBJECT_ASSERT_WLOCKED(dstobject);
917 * If destroysource is set, we remove the source object from the
918 * swap_pager internal queue now.
921 if (srcobject->handle != NULL) {
922 mtx_lock(&sw_alloc_mtx);
924 NOBJLIST(srcobject->handle),
928 mtx_unlock(&sw_alloc_mtx);
933 * transfer source to destination.
935 for (i = 0; i < dstobject->size; ++i) {
939 * Locate (without changing) the swapblk on the destination,
940 * unless it is invalid in which case free it silently, or
941 * if the destination is a resident page, in which case the
942 * source is thrown away.
944 dstaddr = swp_pager_meta_ctl(dstobject, i, 0);
946 if (dstaddr == SWAPBLK_NONE) {
948 * Destination has no swapblk and is not resident,
953 srcaddr = swp_pager_meta_ctl(
959 if (srcaddr != SWAPBLK_NONE) {
961 * swp_pager_meta_build() can sleep.
963 vm_object_pip_add(srcobject, 1);
964 VM_OBJECT_WUNLOCK(srcobject);
965 vm_object_pip_add(dstobject, 1);
966 swp_pager_meta_build(dstobject, i, srcaddr);
967 vm_object_pip_wakeup(dstobject);
968 VM_OBJECT_WLOCK(srcobject);
969 vm_object_pip_wakeup(srcobject);
973 * Destination has valid swapblk or it is represented
974 * by a resident page. We destroy the sourceblock.
977 swp_pager_meta_ctl(srcobject, i + offset, SWM_FREE);
982 * Free left over swap blocks in source.
984 * We have to revert the type to OBJT_DEFAULT so we do not accidently
985 * double-remove the object from the swap queues.
988 swp_pager_meta_free_all(srcobject);
990 * Reverting the type is not necessary, the caller is going
991 * to destroy srcobject directly, but I'm doing it here
992 * for consistency since we've removed the object from its
995 srcobject->type = OBJT_DEFAULT;
1000 * SWAP_PAGER_HASPAGE() - determine if we have good backing store for
1001 * the requested page.
1003 * We determine whether good backing store exists for the requested
1004 * page and return TRUE if it does, FALSE if it doesn't.
1006 * If TRUE, we also try to determine how much valid, contiguous backing
1007 * store exists before and after the requested page within a reasonable
1008 * distance. We do not try to restrict it to the swap device stripe
1009 * (that is handled in getpages/putpages). It probably isn't worth
1013 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before, int *after)
1017 VM_OBJECT_ASSERT_LOCKED(object);
1019 * do we have good backing store at the requested index ?
1021 blk0 = swp_pager_meta_ctl(object, pindex, 0);
1023 if (blk0 == SWAPBLK_NONE) {
1032 * find backwards-looking contiguous good backing store
1034 if (before != NULL) {
1037 for (i = 1; i < (SWB_NPAGES/2); ++i) {
1042 blk = swp_pager_meta_ctl(object, pindex - i, 0);
1043 if (blk != blk0 - i)
1050 * find forward-looking contiguous good backing store
1052 if (after != NULL) {
1055 for (i = 1; i < (SWB_NPAGES/2); ++i) {
1058 blk = swp_pager_meta_ctl(object, pindex + i, 0);
1059 if (blk != blk0 + i)
1068 * SWAP_PAGER_PAGE_UNSWAPPED() - remove swap backing store related to page
1070 * This removes any associated swap backing store, whether valid or
1071 * not, from the page.
1073 * This routine is typically called when a page is made dirty, at
1074 * which point any associated swap can be freed. MADV_FREE also
1075 * calls us in a special-case situation
1077 * NOTE!!! If the page is clean and the swap was valid, the caller
1078 * should make the page dirty before calling this routine. This routine
1079 * does NOT change the m->dirty status of the page. Also: MADV_FREE
1082 * This routine may not sleep.
1084 * The object containing the page must be locked.
1087 swap_pager_unswapped(vm_page_t m)
1090 swp_pager_meta_ctl(m->object, m->pindex, SWM_FREE);
1094 * SWAP_PAGER_GETPAGES() - bring pages in from swap
1096 * Attempt to retrieve (m, count) pages from backing store, but make
1097 * sure we retrieve at least m[reqpage]. We try to load in as large
1098 * a chunk surrounding m[reqpage] as is contiguous in swap and which
1099 * belongs to the same object.
1101 * The code is designed for asynchronous operation and
1102 * immediate-notification of 'reqpage' but tends not to be
1103 * used that way. Please do not optimize-out this algorithmic
1104 * feature, I intend to improve on it in the future.
1106 * The parent has a single vm_object_pip_add() reference prior to
1107 * calling us and we should return with the same.
1109 * The parent has BUSY'd the pages. We should return with 'm'
1110 * left busy, but the others adjusted.
1113 swap_pager_getpages(vm_object_t object, vm_page_t *m, int count, int reqpage)
1123 KASSERT(mreq->object == object,
1124 ("swap_pager_getpages: object mismatch %p/%p",
1125 object, mreq->object));
1128 * Calculate range to retrieve. The pages have already been assigned
1129 * their swapblks. We require a *contiguous* range but we know it to
1130 * not span devices. If we do not supply it, bad things
1131 * happen. Note that blk, iblk & jblk can be SWAPBLK_NONE, but the
1132 * loops are set up such that the case(s) are handled implicitly.
1134 * The swp_*() calls must be made with the object locked.
1136 blk = swp_pager_meta_ctl(mreq->object, mreq->pindex, 0);
1138 for (i = reqpage - 1; i >= 0; --i) {
1141 iblk = swp_pager_meta_ctl(m[i]->object, m[i]->pindex, 0);
1142 if (blk != iblk + (reqpage - i))
1147 for (j = reqpage + 1; j < count; ++j) {
1150 jblk = swp_pager_meta_ctl(m[j]->object, m[j]->pindex, 0);
1151 if (blk != jblk - (j - reqpage))
1156 * free pages outside our collection range. Note: we never free
1157 * mreq, it must remain busy throughout.
1159 if (0 < i || j < count) {
1162 for (k = 0; k < i; ++k)
1163 swp_pager_free_nrpage(m[k]);
1164 for (k = j; k < count; ++k)
1165 swp_pager_free_nrpage(m[k]);
1169 * Return VM_PAGER_FAIL if we have nothing to do. Return mreq
1170 * still busy, but the others unbusied.
1172 if (blk == SWAPBLK_NONE)
1173 return (VM_PAGER_FAIL);
1176 * Getpbuf() can sleep.
1178 VM_OBJECT_WUNLOCK(object);
1180 * Get a swap buffer header to perform the IO
1182 bp = getpbuf(&nsw_rcount);
1183 bp->b_flags |= B_PAGING;
1185 bp->b_iocmd = BIO_READ;
1186 bp->b_iodone = swp_pager_async_iodone;
1187 bp->b_rcred = crhold(thread0.td_ucred);
1188 bp->b_wcred = crhold(thread0.td_ucred);
1189 bp->b_blkno = blk - (reqpage - i);
1190 bp->b_bcount = PAGE_SIZE * (j - i);
1191 bp->b_bufsize = PAGE_SIZE * (j - i);
1192 bp->b_pager.pg_reqpage = reqpage - i;
1194 VM_OBJECT_WLOCK(object);
1198 for (k = i; k < j; ++k) {
1199 bp->b_pages[k - i] = m[k];
1200 m[k]->oflags |= VPO_SWAPINPROG;
1203 bp->b_npages = j - i;
1205 PCPU_INC(cnt.v_swapin);
1206 PCPU_ADD(cnt.v_swappgsin, bp->b_npages);
1209 * We still hold the lock on mreq, and our automatic completion routine
1210 * does not remove it.
1212 vm_object_pip_add(object, bp->b_npages);
1213 VM_OBJECT_WUNLOCK(object);
1216 * perform the I/O. NOTE!!! bp cannot be considered valid after
1217 * this point because we automatically release it on completion.
1218 * Instead, we look at the one page we are interested in which we
1219 * still hold a lock on even through the I/O completion.
1221 * The other pages in our m[] array are also released on completion,
1222 * so we cannot assume they are valid anymore either.
1224 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1227 swp_pager_strategy(bp);
1230 * wait for the page we want to complete. VPO_SWAPINPROG is always
1231 * cleared on completion. If an I/O error occurs, SWAPBLK_NONE
1232 * is set in the meta-data.
1234 VM_OBJECT_WLOCK(object);
1235 while ((mreq->oflags & VPO_SWAPINPROG) != 0) {
1236 mreq->oflags |= VPO_SWAPSLEEP;
1237 PCPU_INC(cnt.v_intrans);
1238 if (VM_OBJECT_SLEEP(object, &object->paging_in_progress, PSWP,
1239 "swread", hz * 20)) {
1241 "swap_pager: indefinite wait buffer: bufobj: %p, blkno: %jd, size: %ld\n",
1242 bp->b_bufobj, (intmax_t)bp->b_blkno, bp->b_bcount);
1247 * mreq is left busied after completion, but all the other pages
1248 * are freed. If we had an unrecoverable read error the page will
1251 if (mreq->valid != VM_PAGE_BITS_ALL) {
1252 return (VM_PAGER_ERROR);
1254 return (VM_PAGER_OK);
1258 * A final note: in a low swap situation, we cannot deallocate swap
1259 * and mark a page dirty here because the caller is likely to mark
1260 * the page clean when we return, causing the page to possibly revert
1261 * to all-zero's later.
1266 * swap_pager_getpages_async():
1268 * Right now this is emulation of asynchronous operation on top of
1269 * swap_pager_getpages().
1272 swap_pager_getpages_async(vm_object_t object, vm_page_t *m, int count,
1273 int reqpage, pgo_getpages_iodone_t iodone, void *arg)
1277 r = swap_pager_getpages(object, m, count, reqpage);
1278 VM_OBJECT_WUNLOCK(object);
1283 case VM_PAGER_ERROR:
1290 panic("unhandled swap_pager_getpages() error %d", r);
1292 (iodone)(arg, m, count, error);
1293 VM_OBJECT_WLOCK(object);
1299 * swap_pager_putpages:
1301 * Assign swap (if necessary) and initiate I/O on the specified pages.
1303 * We support both OBJT_DEFAULT and OBJT_SWAP objects. DEFAULT objects
1304 * are automatically converted to SWAP objects.
1306 * In a low memory situation we may block in VOP_STRATEGY(), but the new
1307 * vm_page reservation system coupled with properly written VFS devices
1308 * should ensure that no low-memory deadlock occurs. This is an area
1311 * The parent has N vm_object_pip_add() references prior to
1312 * calling us and will remove references for rtvals[] that are
1313 * not set to VM_PAGER_PEND. We need to remove the rest on I/O
1316 * The parent has soft-busy'd the pages it passes us and will unbusy
1317 * those whos rtvals[] entry is not set to VM_PAGER_PEND on return.
1318 * We need to unbusy the rest on I/O completion.
1321 swap_pager_putpages(vm_object_t object, vm_page_t *m, int count,
1322 int flags, int *rtvals)
1327 if (count && m[0]->object != object) {
1328 panic("swap_pager_putpages: object mismatch %p/%p",
1337 * Turn object into OBJT_SWAP
1338 * check for bogus sysops
1339 * force sync if not pageout process
1341 if (object->type != OBJT_SWAP)
1342 swp_pager_meta_build(object, 0, SWAPBLK_NONE);
1343 VM_OBJECT_WUNLOCK(object);
1346 if (curproc != pageproc)
1349 sync = (flags & VM_PAGER_PUT_SYNC) != 0;
1354 * Assign swap blocks and issue I/O. We reallocate swap on the fly.
1355 * The page is left dirty until the pageout operation completes
1358 for (i = 0; i < count; i += n) {
1364 * Maximum I/O size is limited by a number of factors.
1366 n = min(BLIST_MAX_ALLOC, count - i);
1367 n = min(n, nsw_cluster_max);
1370 * Get biggest block of swap we can. If we fail, fall
1371 * back and try to allocate a smaller block. Don't go
1372 * overboard trying to allocate space if it would overly
1376 (blk = swp_pager_getswapspace(n)) == SWAPBLK_NONE &&
1381 if (blk == SWAPBLK_NONE) {
1382 for (j = 0; j < n; ++j)
1383 rtvals[i+j] = VM_PAGER_FAIL;
1388 * All I/O parameters have been satisfied, build the I/O
1389 * request and assign the swap space.
1392 bp = getpbuf(&nsw_wcount_sync);
1394 bp = getpbuf(&nsw_wcount_async);
1395 bp->b_flags = B_ASYNC;
1397 bp->b_flags |= B_PAGING;
1398 bp->b_iocmd = BIO_WRITE;
1400 bp->b_rcred = crhold(thread0.td_ucred);
1401 bp->b_wcred = crhold(thread0.td_ucred);
1402 bp->b_bcount = PAGE_SIZE * n;
1403 bp->b_bufsize = PAGE_SIZE * n;
1406 VM_OBJECT_WLOCK(object);
1407 for (j = 0; j < n; ++j) {
1408 vm_page_t mreq = m[i+j];
1410 swp_pager_meta_build(
1415 vm_page_dirty(mreq);
1416 rtvals[i+j] = VM_PAGER_OK;
1418 mreq->oflags |= VPO_SWAPINPROG;
1419 bp->b_pages[j] = mreq;
1421 VM_OBJECT_WUNLOCK(object);
1424 * Must set dirty range for NFS to work.
1427 bp->b_dirtyend = bp->b_bcount;
1429 PCPU_INC(cnt.v_swapout);
1430 PCPU_ADD(cnt.v_swappgsout, bp->b_npages);
1435 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1437 if (sync == FALSE) {
1438 bp->b_iodone = swp_pager_async_iodone;
1440 swp_pager_strategy(bp);
1442 for (j = 0; j < n; ++j)
1443 rtvals[i+j] = VM_PAGER_PEND;
1444 /* restart outter loop */
1451 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1453 bp->b_iodone = bdone;
1454 swp_pager_strategy(bp);
1457 * Wait for the sync I/O to complete, then update rtvals.
1458 * We just set the rtvals[] to VM_PAGER_PEND so we can call
1459 * our async completion routine at the end, thus avoiding a
1462 bwait(bp, PVM, "swwrt");
1463 for (j = 0; j < n; ++j)
1464 rtvals[i+j] = VM_PAGER_PEND;
1466 * Now that we are through with the bp, we can call the
1467 * normal async completion, which frees everything up.
1469 swp_pager_async_iodone(bp);
1471 VM_OBJECT_WLOCK(object);
1475 * swp_pager_async_iodone:
1477 * Completion routine for asynchronous reads and writes from/to swap.
1478 * Also called manually by synchronous code to finish up a bp.
1480 * This routine may not sleep.
1483 swp_pager_async_iodone(struct buf *bp)
1486 vm_object_t object = NULL;
1491 if (bp->b_ioflags & BIO_ERROR) {
1493 "swap_pager: I/O error - %s failed; blkno %ld,"
1494 "size %ld, error %d\n",
1495 ((bp->b_iocmd == BIO_READ) ? "pagein" : "pageout"),
1503 * remove the mapping for kernel virtual
1505 if ((bp->b_flags & B_UNMAPPED) != 0) {
1506 bp->b_data = bp->b_kvaalloc;
1507 bp->b_kvabase = bp->b_kvaalloc;
1508 bp->b_flags &= ~B_UNMAPPED;
1510 pmap_qremove((vm_offset_t)bp->b_data, bp->b_npages);
1513 object = bp->b_pages[0]->object;
1514 VM_OBJECT_WLOCK(object);
1518 * cleanup pages. If an error occurs writing to swap, we are in
1519 * very serious trouble. If it happens to be a disk error, though,
1520 * we may be able to recover by reassigning the swap later on. So
1521 * in this case we remove the m->swapblk assignment for the page
1522 * but do not free it in the rlist. The errornous block(s) are thus
1523 * never reallocated as swap. Redirty the page and continue.
1525 for (i = 0; i < bp->b_npages; ++i) {
1526 vm_page_t m = bp->b_pages[i];
1528 m->oflags &= ~VPO_SWAPINPROG;
1529 if (m->oflags & VPO_SWAPSLEEP) {
1530 m->oflags &= ~VPO_SWAPSLEEP;
1531 wakeup(&object->paging_in_progress);
1534 if (bp->b_ioflags & BIO_ERROR) {
1536 * If an error occurs I'd love to throw the swapblk
1537 * away without freeing it back to swapspace, so it
1538 * can never be used again. But I can't from an
1541 if (bp->b_iocmd == BIO_READ) {
1543 * When reading, reqpage needs to stay
1544 * locked for the parent, but all other
1545 * pages can be freed. We still want to
1546 * wakeup the parent waiting on the page,
1547 * though. ( also: pg_reqpage can be -1 and
1548 * not match anything ).
1550 * We have to wake specifically requested pages
1551 * up too because we cleared VPO_SWAPINPROG and
1552 * someone may be waiting for that.
1554 * NOTE: for reads, m->dirty will probably
1555 * be overridden by the original caller of
1556 * getpages so don't play cute tricks here.
1559 if (i != bp->b_pager.pg_reqpage)
1560 swp_pager_free_nrpage(m);
1567 * If i == bp->b_pager.pg_reqpage, do not wake
1568 * the page up. The caller needs to.
1572 * If a write error occurs, reactivate page
1573 * so it doesn't clog the inactive list,
1574 * then finish the I/O.
1578 vm_page_activate(m);
1582 } else if (bp->b_iocmd == BIO_READ) {
1584 * NOTE: for reads, m->dirty will probably be
1585 * overridden by the original caller of getpages so
1586 * we cannot set them in order to free the underlying
1587 * swap in a low-swap situation. I don't think we'd
1588 * want to do that anyway, but it was an optimization
1589 * that existed in the old swapper for a time before
1590 * it got ripped out due to precisely this problem.
1592 * If not the requested page then deactivate it.
1594 * Note that the requested page, reqpage, is left
1595 * busied, but we still have to wake it up. The
1596 * other pages are released (unbusied) by
1597 * vm_page_xunbusy().
1599 KASSERT(!pmap_page_is_mapped(m),
1600 ("swp_pager_async_iodone: page %p is mapped", m));
1601 m->valid = VM_PAGE_BITS_ALL;
1602 KASSERT(m->dirty == 0,
1603 ("swp_pager_async_iodone: page %p is dirty", m));
1606 * We have to wake specifically requested pages
1607 * up too because we cleared VPO_SWAPINPROG and
1608 * could be waiting for it in getpages. However,
1609 * be sure to not unbusy getpages specifically
1610 * requested page - getpages expects it to be
1613 if (i != bp->b_pager.pg_reqpage) {
1615 vm_page_deactivate(m);
1625 * For write success, clear the dirty
1626 * status, then finish the I/O ( which decrements the
1627 * busy count and possibly wakes waiter's up ).
1629 KASSERT(!pmap_page_is_write_mapped(m),
1630 ("swp_pager_async_iodone: page %p is not write"
1634 if (vm_page_count_severe()) {
1636 vm_page_try_to_cache(m);
1643 * adjust pip. NOTE: the original parent may still have its own
1644 * pip refs on the object.
1646 if (object != NULL) {
1647 vm_object_pip_wakeupn(object, bp->b_npages);
1648 VM_OBJECT_WUNLOCK(object);
1652 * swapdev_strategy() manually sets b_vp and b_bufobj before calling
1653 * bstrategy(). Set them back to NULL now we're done with it, or we'll
1654 * trigger a KASSERT in relpbuf().
1658 bp->b_bufobj = NULL;
1661 * release the physical I/O buffer
1665 ((bp->b_iocmd == BIO_READ) ? &nsw_rcount :
1666 ((bp->b_flags & B_ASYNC) ?
1675 * swap_pager_isswapped:
1677 * Return 1 if at least one page in the given object is paged
1678 * out to the given swap device.
1680 * This routine may not sleep.
1683 swap_pager_isswapped(vm_object_t object, struct swdevt *sp)
1689 VM_OBJECT_ASSERT_WLOCKED(object);
1690 if (object->type != OBJT_SWAP)
1693 mtx_lock(&swhash_mtx);
1694 for (bcount = 0; bcount < object->un_pager.swp.swp_bcount; bcount++) {
1695 struct swblock *swap;
1697 if ((swap = *swp_pager_hash(object, index)) != NULL) {
1698 for (i = 0; i < SWAP_META_PAGES; ++i) {
1699 if (swp_pager_isondev(swap->swb_pages[i], sp)) {
1700 mtx_unlock(&swhash_mtx);
1705 index += SWAP_META_PAGES;
1707 mtx_unlock(&swhash_mtx);
1712 * SWP_PAGER_FORCE_PAGEIN() - force a swap block to be paged in
1714 * This routine dissociates the page at the given index within a
1715 * swap block from its backing store, paging it in if necessary.
1716 * If the page is paged in, it is placed in the inactive queue,
1717 * since it had its backing store ripped out from under it.
1718 * We also attempt to swap in all other pages in the swap block,
1719 * we only guarantee that the one at the specified index is
1722 * XXX - The code to page the whole block in doesn't work, so we
1723 * revert to the one-by-one behavior for now. Sigh.
1726 swp_pager_force_pagein(vm_object_t object, vm_pindex_t pindex)
1730 vm_object_pip_add(object, 1);
1731 m = vm_page_grab(object, pindex, VM_ALLOC_NORMAL);
1732 if (m->valid == VM_PAGE_BITS_ALL) {
1733 vm_object_pip_wakeup(object);
1736 vm_page_activate(m);
1739 vm_pager_page_unswapped(m);
1743 if (swap_pager_getpages(object, &m, 1, 0) != VM_PAGER_OK)
1744 panic("swap_pager_force_pagein: read from swap failed");/*XXX*/
1745 vm_object_pip_wakeup(object);
1748 vm_page_deactivate(m);
1751 vm_pager_page_unswapped(m);
1755 * swap_pager_swapoff:
1757 * Page in all of the pages that have been paged out to the
1758 * given device. The corresponding blocks in the bitmap must be
1759 * marked as allocated and the device must be flagged SW_CLOSING.
1760 * There may be no processes swapped out to the device.
1762 * This routine may block.
1765 swap_pager_swapoff(struct swdevt *sp)
1767 struct swblock *swap;
1774 mtx_lock(&swhash_mtx);
1775 for (i = 0; i <= swhash_mask; i++) { /* '<=' is correct here */
1777 for (swap = swhash[i]; swap != NULL; swap = swap->swb_hnext) {
1778 vm_object_t object = swap->swb_object;
1779 vm_pindex_t pindex = swap->swb_index;
1780 for (j = 0; j < SWAP_META_PAGES; ++j) {
1781 if (swp_pager_isondev(swap->swb_pages[j], sp)) {
1782 /* avoid deadlock */
1783 if (!VM_OBJECT_TRYWLOCK(object)) {
1786 mtx_unlock(&swhash_mtx);
1787 swp_pager_force_pagein(object,
1789 VM_OBJECT_WUNLOCK(object);
1790 mtx_lock(&swhash_mtx);
1797 mtx_unlock(&swhash_mtx);
1800 * Objects may be locked or paging to the device being
1801 * removed, so we will miss their pages and need to
1802 * make another pass. We have marked this device as
1803 * SW_CLOSING, so the activity should finish soon.
1806 if (retries > 100) {
1807 panic("swapoff: failed to locate %d swap blocks",
1810 pause("swpoff", hz / 20);
1815 /************************************************************************
1817 ************************************************************************
1819 * These routines manipulate the swap metadata stored in the
1822 * Swap metadata is implemented with a global hash and not directly
1823 * linked into the object. Instead the object simply contains
1824 * appropriate tracking counters.
1828 * SWP_PAGER_META_BUILD() - add swap block to swap meta data for object
1830 * We first convert the object to a swap object if it is a default
1833 * The specified swapblk is added to the object's swap metadata. If
1834 * the swapblk is not valid, it is freed instead. Any previously
1835 * assigned swapblk is freed.
1838 swp_pager_meta_build(vm_object_t object, vm_pindex_t pindex, daddr_t swapblk)
1840 static volatile int exhausted;
1841 struct swblock *swap;
1842 struct swblock **pswap;
1845 VM_OBJECT_ASSERT_WLOCKED(object);
1847 * Convert default object to swap object if necessary
1849 if (object->type != OBJT_SWAP) {
1850 object->type = OBJT_SWAP;
1851 object->un_pager.swp.swp_bcount = 0;
1853 if (object->handle != NULL) {
1854 mtx_lock(&sw_alloc_mtx);
1856 NOBJLIST(object->handle),
1860 mtx_unlock(&sw_alloc_mtx);
1865 * Locate hash entry. If not found create, but if we aren't adding
1866 * anything just return. If we run out of space in the map we wait
1867 * and, since the hash table may have changed, retry.
1870 mtx_lock(&swhash_mtx);
1871 pswap = swp_pager_hash(object, pindex);
1873 if ((swap = *pswap) == NULL) {
1876 if (swapblk == SWAPBLK_NONE)
1879 swap = *pswap = uma_zalloc(swap_zone, M_NOWAIT |
1880 (curproc == pageproc ? M_USE_RESERVE : 0));
1882 mtx_unlock(&swhash_mtx);
1883 VM_OBJECT_WUNLOCK(object);
1884 if (uma_zone_exhausted(swap_zone)) {
1885 if (atomic_cmpset_int(&exhausted, 0, 1))
1886 printf("swap zone exhausted, "
1887 "increase kern.maxswzone\n");
1888 vm_pageout_oom(VM_OOM_SWAPZ);
1889 pause("swzonex", 10);
1892 VM_OBJECT_WLOCK(object);
1896 if (atomic_cmpset_int(&exhausted, 1, 0))
1897 printf("swap zone ok\n");
1899 swap->swb_hnext = NULL;
1900 swap->swb_object = object;
1901 swap->swb_index = pindex & ~(vm_pindex_t)SWAP_META_MASK;
1902 swap->swb_count = 0;
1904 ++object->un_pager.swp.swp_bcount;
1906 for (i = 0; i < SWAP_META_PAGES; ++i)
1907 swap->swb_pages[i] = SWAPBLK_NONE;
1911 * Delete prior contents of metadata
1913 idx = pindex & SWAP_META_MASK;
1915 if (swap->swb_pages[idx] != SWAPBLK_NONE) {
1916 swp_pager_freeswapspace(swap->swb_pages[idx], 1);
1921 * Enter block into metadata
1923 swap->swb_pages[idx] = swapblk;
1924 if (swapblk != SWAPBLK_NONE)
1927 mtx_unlock(&swhash_mtx);
1931 * SWP_PAGER_META_FREE() - free a range of blocks in the object's swap metadata
1933 * The requested range of blocks is freed, with any associated swap
1934 * returned to the swap bitmap.
1936 * This routine will free swap metadata structures as they are cleaned
1937 * out. This routine does *NOT* operate on swap metadata associated
1938 * with resident pages.
1941 swp_pager_meta_free(vm_object_t object, vm_pindex_t index, daddr_t count)
1944 VM_OBJECT_ASSERT_LOCKED(object);
1945 if (object->type != OBJT_SWAP)
1949 struct swblock **pswap;
1950 struct swblock *swap;
1952 mtx_lock(&swhash_mtx);
1953 pswap = swp_pager_hash(object, index);
1955 if ((swap = *pswap) != NULL) {
1956 daddr_t v = swap->swb_pages[index & SWAP_META_MASK];
1958 if (v != SWAPBLK_NONE) {
1959 swp_pager_freeswapspace(v, 1);
1960 swap->swb_pages[index & SWAP_META_MASK] =
1962 if (--swap->swb_count == 0) {
1963 *pswap = swap->swb_hnext;
1964 uma_zfree(swap_zone, swap);
1965 --object->un_pager.swp.swp_bcount;
1971 int n = SWAP_META_PAGES - (index & SWAP_META_MASK);
1975 mtx_unlock(&swhash_mtx);
1980 * SWP_PAGER_META_FREE_ALL() - destroy all swap metadata associated with object
1982 * This routine locates and destroys all swap metadata associated with
1986 swp_pager_meta_free_all(vm_object_t object)
1990 VM_OBJECT_ASSERT_WLOCKED(object);
1991 if (object->type != OBJT_SWAP)
1994 while (object->un_pager.swp.swp_bcount) {
1995 struct swblock **pswap;
1996 struct swblock *swap;
1998 mtx_lock(&swhash_mtx);
1999 pswap = swp_pager_hash(object, index);
2000 if ((swap = *pswap) != NULL) {
2003 for (i = 0; i < SWAP_META_PAGES; ++i) {
2004 daddr_t v = swap->swb_pages[i];
2005 if (v != SWAPBLK_NONE) {
2007 swp_pager_freeswapspace(v, 1);
2010 if (swap->swb_count != 0)
2011 panic("swap_pager_meta_free_all: swb_count != 0");
2012 *pswap = swap->swb_hnext;
2013 uma_zfree(swap_zone, swap);
2014 --object->un_pager.swp.swp_bcount;
2016 mtx_unlock(&swhash_mtx);
2017 index += SWAP_META_PAGES;
2022 * SWP_PAGER_METACTL() - misc control of swap and vm_page_t meta data.
2024 * This routine is capable of looking up, popping, or freeing
2025 * swapblk assignments in the swap meta data or in the vm_page_t.
2026 * The routine typically returns the swapblk being looked-up, or popped,
2027 * or SWAPBLK_NONE if the block was freed, or SWAPBLK_NONE if the block
2028 * was invalid. This routine will automatically free any invalid
2029 * meta-data swapblks.
2031 * It is not possible to store invalid swapblks in the swap meta data
2032 * (other then a literal 'SWAPBLK_NONE'), so we don't bother checking.
2034 * When acting on a busy resident page and paging is in progress, we
2035 * have to wait until paging is complete but otherwise can act on the
2038 * SWM_FREE remove and free swap block from metadata
2039 * SWM_POP remove from meta data but do not free.. pop it out
2042 swp_pager_meta_ctl(vm_object_t object, vm_pindex_t pindex, int flags)
2044 struct swblock **pswap;
2045 struct swblock *swap;
2049 VM_OBJECT_ASSERT_LOCKED(object);
2051 * The meta data only exists of the object is OBJT_SWAP
2052 * and even then might not be allocated yet.
2054 if (object->type != OBJT_SWAP)
2055 return (SWAPBLK_NONE);
2058 mtx_lock(&swhash_mtx);
2059 pswap = swp_pager_hash(object, pindex);
2061 if ((swap = *pswap) != NULL) {
2062 idx = pindex & SWAP_META_MASK;
2063 r1 = swap->swb_pages[idx];
2065 if (r1 != SWAPBLK_NONE) {
2066 if (flags & SWM_FREE) {
2067 swp_pager_freeswapspace(r1, 1);
2070 if (flags & (SWM_FREE|SWM_POP)) {
2071 swap->swb_pages[idx] = SWAPBLK_NONE;
2072 if (--swap->swb_count == 0) {
2073 *pswap = swap->swb_hnext;
2074 uma_zfree(swap_zone, swap);
2075 --object->un_pager.swp.swp_bcount;
2080 mtx_unlock(&swhash_mtx);
2085 * System call swapon(name) enables swapping on device name,
2086 * which must be in the swdevsw. Return EBUSY
2087 * if already swapping on this device.
2089 #ifndef _SYS_SYSPROTO_H_
2090 struct swapon_args {
2100 sys_swapon(struct thread *td, struct swapon_args *uap)
2104 struct nameidata nd;
2107 error = priv_check(td, PRIV_SWAPON);
2112 while (swdev_syscall_active)
2113 tsleep(&swdev_syscall_active, PUSER - 1, "swpon", 0);
2114 swdev_syscall_active = 1;
2117 * Swap metadata may not fit in the KVM if we have physical
2120 if (swap_zone == NULL) {
2125 NDINIT(&nd, LOOKUP, ISOPEN | FOLLOW | AUDITVNODE1, UIO_USERSPACE,
2131 NDFREE(&nd, NDF_ONLY_PNBUF);
2134 if (vn_isdisk(vp, &error)) {
2135 error = swapongeom(td, vp);
2136 } else if (vp->v_type == VREG &&
2137 (vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
2138 (error = VOP_GETATTR(vp, &attr, td->td_ucred)) == 0) {
2140 * Allow direct swapping to NFS regular files in the same
2141 * way that nfs_mountroot() sets up diskless swapping.
2143 error = swaponvp(td, vp, attr.va_size / DEV_BSIZE);
2149 swdev_syscall_active = 0;
2150 wakeup_one(&swdev_syscall_active);
2156 * Check that the total amount of swap currently configured does not
2157 * exceed half the theoretical maximum. If it does, print a warning
2158 * message and return -1; otherwise, return 0.
2161 swapon_check_swzone(unsigned long npages)
2163 unsigned long maxpages;
2165 /* absolute maximum we can handle assuming 100% efficiency */
2166 maxpages = uma_zone_get_max(swap_zone) * SWAP_META_PAGES;
2168 /* recommend using no more than half that amount */
2169 if (npages > maxpages / 2) {
2170 printf("warning: total configured swap (%lu pages) "
2171 "exceeds maximum recommended amount (%lu pages).\n",
2172 npages, maxpages / 2);
2173 printf("warning: increase kern.maxswzone "
2174 "or reduce amount of swap.\n");
2181 swaponsomething(struct vnode *vp, void *id, u_long nblks,
2182 sw_strategy_t *strategy, sw_close_t *close, dev_t dev, int flags)
2184 struct swdevt *sp, *tsp;
2189 * nblks is in DEV_BSIZE'd chunks, convert to PAGE_SIZE'd chunks.
2190 * First chop nblks off to page-align it, then convert.
2192 * sw->sw_nblks is in page-sized chunks now too.
2194 nblks &= ~(ctodb(1) - 1);
2195 nblks = dbtoc(nblks);
2198 * If we go beyond this, we get overflows in the radix
2201 mblocks = 0x40000000 / BLIST_META_RADIX;
2202 if (nblks > mblocks) {
2204 "WARNING: reducing swap size to maximum of %luMB per unit\n",
2205 mblocks / 1024 / 1024 * PAGE_SIZE);
2209 sp = malloc(sizeof *sp, M_VMPGDATA, M_WAITOK | M_ZERO);
2214 sp->sw_nblks = nblks;
2216 sp->sw_strategy = strategy;
2217 sp->sw_close = close;
2218 sp->sw_flags = flags;
2220 sp->sw_blist = blist_create(nblks, M_WAITOK);
2222 * Do not free the first two block in order to avoid overwriting
2223 * any bsd label at the front of the partition
2225 blist_free(sp->sw_blist, 2, nblks - 2);
2228 mtx_lock(&sw_dev_mtx);
2229 TAILQ_FOREACH(tsp, &swtailq, sw_list) {
2230 if (tsp->sw_end >= dvbase) {
2232 * We put one uncovered page between the devices
2233 * in order to definitively prevent any cross-device
2236 dvbase = tsp->sw_end + 1;
2239 sp->sw_first = dvbase;
2240 sp->sw_end = dvbase + nblks;
2241 TAILQ_INSERT_TAIL(&swtailq, sp, sw_list);
2243 swap_pager_avail += nblks;
2244 swap_total += (vm_ooffset_t)nblks * PAGE_SIZE;
2245 swapon_check_swzone(swap_total / PAGE_SIZE);
2247 mtx_unlock(&sw_dev_mtx);
2251 * SYSCALL: swapoff(devname)
2253 * Disable swapping on the given device.
2255 * XXX: Badly designed system call: it should use a device index
2256 * rather than filename as specification. We keep sw_vp around
2257 * only to make this work.
2259 #ifndef _SYS_SYSPROTO_H_
2260 struct swapoff_args {
2270 sys_swapoff(struct thread *td, struct swapoff_args *uap)
2273 struct nameidata nd;
2277 error = priv_check(td, PRIV_SWAPOFF);
2282 while (swdev_syscall_active)
2283 tsleep(&swdev_syscall_active, PUSER - 1, "swpoff", 0);
2284 swdev_syscall_active = 1;
2286 NDINIT(&nd, LOOKUP, FOLLOW | AUDITVNODE1, UIO_USERSPACE, uap->name,
2291 NDFREE(&nd, NDF_ONLY_PNBUF);
2294 mtx_lock(&sw_dev_mtx);
2295 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2296 if (sp->sw_vp == vp)
2299 mtx_unlock(&sw_dev_mtx);
2304 error = swapoff_one(sp, td->td_ucred);
2306 swdev_syscall_active = 0;
2307 wakeup_one(&swdev_syscall_active);
2313 swapoff_one(struct swdevt *sp, struct ucred *cred)
2315 u_long nblks, dvbase;
2320 mtx_assert(&Giant, MA_OWNED);
2322 (void) vn_lock(sp->sw_vp, LK_EXCLUSIVE | LK_RETRY);
2323 error = mac_system_check_swapoff(cred, sp->sw_vp);
2324 (void) VOP_UNLOCK(sp->sw_vp, 0);
2328 nblks = sp->sw_nblks;
2331 * We can turn off this swap device safely only if the
2332 * available virtual memory in the system will fit the amount
2333 * of data we will have to page back in, plus an epsilon so
2334 * the system doesn't become critically low on swap space.
2336 if (vm_cnt.v_free_count + vm_cnt.v_cache_count + swap_pager_avail <
2337 nblks + nswap_lowat) {
2342 * Prevent further allocations on this device.
2344 mtx_lock(&sw_dev_mtx);
2345 sp->sw_flags |= SW_CLOSING;
2346 for (dvbase = 0; dvbase < sp->sw_end; dvbase += dmmax) {
2347 swap_pager_avail -= blist_fill(sp->sw_blist,
2350 swap_total -= (vm_ooffset_t)nblks * PAGE_SIZE;
2351 mtx_unlock(&sw_dev_mtx);
2354 * Page in the contents of the device and close it.
2356 swap_pager_swapoff(sp);
2358 sp->sw_close(curthread, sp);
2360 mtx_lock(&sw_dev_mtx);
2361 TAILQ_REMOVE(&swtailq, sp, sw_list);
2363 if (nswapdev == 0) {
2364 swap_pager_full = 2;
2365 swap_pager_almost_full = 1;
2369 mtx_unlock(&sw_dev_mtx);
2370 blist_destroy(sp->sw_blist);
2371 free(sp, M_VMPGDATA);
2378 struct swdevt *sp, *spt;
2379 const char *devname;
2383 while (swdev_syscall_active)
2384 tsleep(&swdev_syscall_active, PUSER - 1, "swpoff", 0);
2385 swdev_syscall_active = 1;
2387 mtx_lock(&sw_dev_mtx);
2388 TAILQ_FOREACH_SAFE(sp, &swtailq, sw_list, spt) {
2389 mtx_unlock(&sw_dev_mtx);
2390 if (vn_isdisk(sp->sw_vp, NULL))
2391 devname = devtoname(sp->sw_vp->v_rdev);
2394 error = swapoff_one(sp, thread0.td_ucred);
2396 printf("Cannot remove swap device %s (error=%d), "
2397 "skipping.\n", devname, error);
2398 } else if (bootverbose) {
2399 printf("Swap device %s removed.\n", devname);
2401 mtx_lock(&sw_dev_mtx);
2403 mtx_unlock(&sw_dev_mtx);
2405 swdev_syscall_active = 0;
2406 wakeup_one(&swdev_syscall_active);
2411 swap_pager_status(int *total, int *used)
2417 mtx_lock(&sw_dev_mtx);
2418 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2419 *total += sp->sw_nblks;
2420 *used += sp->sw_used;
2422 mtx_unlock(&sw_dev_mtx);
2426 swap_dev_info(int name, struct xswdev *xs, char *devname, size_t len)
2429 const char *tmp_devname;
2434 mtx_lock(&sw_dev_mtx);
2435 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2440 xs->xsw_version = XSWDEV_VERSION;
2441 xs->xsw_dev = sp->sw_dev;
2442 xs->xsw_flags = sp->sw_flags;
2443 xs->xsw_nblks = sp->sw_nblks;
2444 xs->xsw_used = sp->sw_used;
2445 if (devname != NULL) {
2446 if (vn_isdisk(sp->sw_vp, NULL))
2447 tmp_devname = devtoname(sp->sw_vp->v_rdev);
2449 tmp_devname = "[file]";
2450 strncpy(devname, tmp_devname, len);
2455 mtx_unlock(&sw_dev_mtx);
2460 sysctl_vm_swap_info(SYSCTL_HANDLER_ARGS)
2465 if (arg2 != 1) /* name length */
2467 error = swap_dev_info(*(int *)arg1, &xs, NULL, 0);
2470 error = SYSCTL_OUT(req, &xs, sizeof(xs));
2474 SYSCTL_INT(_vm, OID_AUTO, nswapdev, CTLFLAG_RD, &nswapdev, 0,
2475 "Number of swap devices");
2476 SYSCTL_NODE(_vm, OID_AUTO, swap_info, CTLFLAG_RD, sysctl_vm_swap_info,
2477 "Swap statistics by device");
2480 * vmspace_swap_count() - count the approximate swap usage in pages for a
2483 * The map must be locked.
2485 * Swap usage is determined by taking the proportional swap used by
2486 * VM objects backing the VM map. To make up for fractional losses,
2487 * if the VM object has any swap use at all the associated map entries
2488 * count for at least 1 swap page.
2491 vmspace_swap_count(struct vmspace *vmspace)
2498 map = &vmspace->vm_map;
2501 for (cur = map->header.next; cur != &map->header; cur = cur->next) {
2502 if ((cur->eflags & MAP_ENTRY_IS_SUB_MAP) == 0 &&
2503 (object = cur->object.vm_object) != NULL) {
2504 VM_OBJECT_WLOCK(object);
2505 if (object->type == OBJT_SWAP &&
2506 object->un_pager.swp.swp_bcount != 0) {
2507 n = (cur->end - cur->start) / PAGE_SIZE;
2508 count += object->un_pager.swp.swp_bcount *
2509 SWAP_META_PAGES * n / object->size + 1;
2511 VM_OBJECT_WUNLOCK(object);
2520 * Swapping onto disk devices.
2524 static g_orphan_t swapgeom_orphan;
2526 static struct g_class g_swap_class = {
2528 .version = G_VERSION,
2529 .orphan = swapgeom_orphan,
2532 DECLARE_GEOM_CLASS(g_swap_class, g_class);
2536 swapgeom_close_ev(void *arg, int flags)
2538 struct g_consumer *cp;
2541 g_access(cp, -1, -1, 0);
2543 g_destroy_consumer(cp);
2547 swapgeom_done(struct bio *bp2)
2551 struct g_consumer *cp;
2553 bp = bp2->bio_caller2;
2555 bp->b_ioflags = bp2->bio_flags;
2557 bp->b_ioflags |= BIO_ERROR;
2558 bp->b_resid = bp->b_bcount - bp2->bio_completed;
2559 bp->b_error = bp2->bio_error;
2561 mtx_lock(&sw_dev_mtx);
2562 if ((--cp->index) == 0 && cp->private) {
2563 if (g_post_event(swapgeom_close_ev, cp, M_NOWAIT, NULL) == 0) {
2564 sp = bp2->bio_caller1;
2568 mtx_unlock(&sw_dev_mtx);
2573 swapgeom_strategy(struct buf *bp, struct swdevt *sp)
2576 struct g_consumer *cp;
2578 mtx_lock(&sw_dev_mtx);
2581 mtx_unlock(&sw_dev_mtx);
2582 bp->b_error = ENXIO;
2583 bp->b_ioflags |= BIO_ERROR;
2588 mtx_unlock(&sw_dev_mtx);
2589 if (bp->b_iocmd == BIO_WRITE)
2592 bio = g_alloc_bio();
2594 bp->b_error = ENOMEM;
2595 bp->b_ioflags |= BIO_ERROR;
2600 bio->bio_caller1 = sp;
2601 bio->bio_caller2 = bp;
2602 bio->bio_cmd = bp->b_iocmd;
2603 bio->bio_offset = (bp->b_blkno - sp->sw_first) * PAGE_SIZE;
2604 bio->bio_length = bp->b_bcount;
2605 bio->bio_done = swapgeom_done;
2606 if ((bp->b_flags & B_UNMAPPED) != 0) {
2607 bio->bio_ma = bp->b_pages;
2608 bio->bio_data = unmapped_buf;
2609 bio->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
2610 bio->bio_ma_n = bp->b_npages;
2611 bio->bio_flags |= BIO_UNMAPPED;
2613 bio->bio_data = bp->b_data;
2616 g_io_request(bio, cp);
2621 swapgeom_orphan(struct g_consumer *cp)
2626 mtx_lock(&sw_dev_mtx);
2627 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2628 if (sp->sw_id == cp) {
2629 sp->sw_flags |= SW_CLOSING;
2633 cp->private = (void *)(uintptr_t)1;
2634 destroy = ((sp != NULL) && (cp->index == 0));
2637 mtx_unlock(&sw_dev_mtx);
2639 swapgeom_close_ev(cp, 0);
2643 swapgeom_close(struct thread *td, struct swdevt *sw)
2645 struct g_consumer *cp;
2647 mtx_lock(&sw_dev_mtx);
2650 mtx_unlock(&sw_dev_mtx);
2651 /* XXX: direct call when Giant untangled */
2653 g_waitfor_event(swapgeom_close_ev, cp, M_WAITOK, NULL);
2664 swapongeom_ev(void *arg, int flags)
2667 struct g_provider *pp;
2668 struct g_consumer *cp;
2669 static struct g_geom *gp;
2676 pp = g_dev_getprovider(swh->dev);
2678 swh->error = ENODEV;
2681 mtx_lock(&sw_dev_mtx);
2682 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2684 if (cp != NULL && cp->provider == pp) {
2685 mtx_unlock(&sw_dev_mtx);
2690 mtx_unlock(&sw_dev_mtx);
2692 gp = g_new_geomf(&g_swap_class, "swap");
2693 cp = g_new_consumer(gp);
2694 cp->index = 0; /* Number of active I/Os. */
2695 cp->private = NULL; /* Orphanization flag */
2698 * XXX: Everytime you think you can improve the margin for
2699 * footshooting, somebody depends on the ability to do so:
2700 * savecore(8) wants to write to our swapdev so we cannot
2701 * set an exclusive count :-(
2703 error = g_access(cp, 1, 1, 0);
2706 g_destroy_consumer(cp);
2710 nblks = pp->mediasize / DEV_BSIZE;
2711 swaponsomething(swh->vp, cp, nblks, swapgeom_strategy,
2712 swapgeom_close, dev2udev(swh->dev),
2713 (pp->flags & G_PF_ACCEPT_UNMAPPED) != 0 ? SW_UNMAPPED : 0);
2718 swapongeom(struct thread *td, struct vnode *vp)
2723 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2725 swh.dev = vp->v_rdev;
2728 /* XXX: direct call when Giant untangled */
2729 error = g_waitfor_event(swapongeom_ev, &swh, M_WAITOK, NULL);
2739 * This is used mainly for network filesystem (read: probably only tested
2740 * with NFS) swapfiles.
2745 swapdev_strategy(struct buf *bp, struct swdevt *sp)
2749 bp->b_blkno = ctodb(bp->b_blkno - sp->sw_first);
2753 if (bp->b_iocmd == BIO_WRITE) {
2755 bufobj_wdrop(bp->b_bufobj);
2756 bufobj_wref(&vp2->v_bufobj);
2758 if (bp->b_bufobj != &vp2->v_bufobj)
2759 bp->b_bufobj = &vp2->v_bufobj;
2761 bp->b_iooffset = dbtob(bp->b_blkno);
2767 swapdev_close(struct thread *td, struct swdevt *sp)
2770 VOP_CLOSE(sp->sw_vp, FREAD | FWRITE, td->td_ucred, td);
2776 swaponvp(struct thread *td, struct vnode *vp, u_long nblks)
2783 mtx_lock(&sw_dev_mtx);
2784 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2785 if (sp->sw_id == vp) {
2786 mtx_unlock(&sw_dev_mtx);
2790 mtx_unlock(&sw_dev_mtx);
2792 (void) vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2794 error = mac_system_check_swapon(td->td_ucred, vp);
2797 error = VOP_OPEN(vp, FREAD | FWRITE, td->td_ucred, td, NULL);
2798 (void) VOP_UNLOCK(vp, 0);
2802 swaponsomething(vp, vp, nblks, swapdev_strategy, swapdev_close,
2808 sysctl_swap_async_max(SYSCTL_HANDLER_ARGS)
2812 new = nsw_wcount_async_max;
2813 error = sysctl_handle_int(oidp, &new, 0, req);
2814 if (error != 0 || req->newptr == NULL)
2817 if (new > nswbuf / 2 || new < 1)
2820 mtx_lock(&pbuf_mtx);
2821 while (nsw_wcount_async_max != new) {
2823 * Adjust difference. If the current async count is too low,
2824 * we will need to sqeeze our update slowly in. Sleep with a
2825 * higher priority than getpbuf() to finish faster.
2827 n = new - nsw_wcount_async_max;
2828 if (nsw_wcount_async + n >= 0) {
2829 nsw_wcount_async += n;
2830 nsw_wcount_async_max += n;
2831 wakeup(&nsw_wcount_async);
2833 nsw_wcount_async_max -= nsw_wcount_async;
2834 nsw_wcount_async = 0;
2835 msleep(&nsw_wcount_async, &pbuf_mtx, PSWP,
2839 mtx_unlock(&pbuf_mtx);