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$");
72 #include "opt_compat.h"
76 #include <sys/param.h>
77 #include <sys/systm.h>
79 #include <sys/kernel.h>
85 #include <sys/fcntl.h>
86 #include <sys/mount.h>
87 #include <sys/namei.h>
88 #include <sys/vnode.h>
89 #include <sys/malloc.h>
90 #include <sys/racct.h>
91 #include <sys/resource.h>
92 #include <sys/resourcevar.h>
93 #include <sys/rwlock.h>
94 #include <sys/sysctl.h>
95 #include <sys/sysproto.h>
96 #include <sys/blist.h>
99 #include <sys/vmmeter.h>
101 #include <security/mac/mac_framework.h>
105 #include <vm/vm_map.h>
106 #include <vm/vm_kern.h>
107 #include <vm/vm_object.h>
108 #include <vm/vm_page.h>
109 #include <vm/vm_pager.h>
110 #include <vm/vm_pageout.h>
111 #include <vm/vm_param.h>
112 #include <vm/swap_pager.h>
113 #include <vm/vm_extern.h>
116 #include <geom/geom.h>
119 * MAX_PAGEOUT_CLUSTER must be a power of 2 between 1 and 64.
120 * The 64-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 struct sx swdev_syscall_lock; /* 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);
227 UIDINFO_VMSIZE_LOCK(uip);
228 if ((overcommit & SWAP_RESERVE_RLIMIT_ON) != 0 &&
229 uip->ui_vmsize + incr > lim_cur(curthread, RLIMIT_SWAP) &&
230 priv_check(curthread, PRIV_VM_SWAP_NORLIMIT))
233 uip->ui_vmsize += incr;
234 UIDINFO_VMSIZE_UNLOCK(uip);
236 mtx_lock(&sw_dev_mtx);
237 swap_reserved -= incr;
238 mtx_unlock(&sw_dev_mtx);
241 if (!res && ppsratecheck(&lastfail, &curfail, 1)) {
242 printf("uid %d, pid %d: swap reservation for %jd bytes failed\n",
243 uip->ui_uid, curproc->p_pid, incr);
249 racct_sub(curproc, RACCT_SWAP, incr);
250 PROC_UNLOCK(curproc);
258 swap_reserve_force(vm_ooffset_t incr)
262 mtx_lock(&sw_dev_mtx);
263 swap_reserved += incr;
264 mtx_unlock(&sw_dev_mtx);
268 racct_add_force(curproc, RACCT_SWAP, incr);
269 PROC_UNLOCK(curproc);
272 uip = curthread->td_ucred->cr_ruidinfo;
274 UIDINFO_VMSIZE_LOCK(uip);
275 uip->ui_vmsize += incr;
276 UIDINFO_VMSIZE_UNLOCK(uip);
277 PROC_UNLOCK(curproc);
281 swap_release(vm_ooffset_t decr)
286 cred = curthread->td_ucred;
287 swap_release_by_cred(decr, cred);
288 PROC_UNLOCK(curproc);
292 swap_release_by_cred(vm_ooffset_t decr, struct ucred *cred)
296 uip = cred->cr_ruidinfo;
298 if (decr & PAGE_MASK)
299 panic("swap_release: & PAGE_MASK");
301 mtx_lock(&sw_dev_mtx);
302 if (swap_reserved < decr)
303 panic("swap_reserved < decr");
304 swap_reserved -= decr;
305 mtx_unlock(&sw_dev_mtx);
307 UIDINFO_VMSIZE_LOCK(uip);
308 if (uip->ui_vmsize < decr)
309 printf("negative vmsize for uid = %d\n", uip->ui_uid);
310 uip->ui_vmsize -= decr;
311 UIDINFO_VMSIZE_UNLOCK(uip);
313 racct_sub_cred(cred, RACCT_SWAP, decr);
316 #define SWM_FREE 0x02 /* free, period */
317 #define SWM_POP 0x04 /* pop out */
319 int swap_pager_full = 2; /* swap space exhaustion (task killing) */
320 static int swap_pager_almost_full = 1; /* swap space exhaustion (w/hysteresis)*/
321 static int nsw_rcount; /* free read buffers */
322 static int nsw_wcount_sync; /* limit write buffers / synchronous */
323 static int nsw_wcount_async; /* limit write buffers / asynchronous */
324 static int nsw_wcount_async_max;/* assigned maximum */
325 static int nsw_cluster_max; /* maximum VOP I/O allowed */
327 static int sysctl_swap_async_max(SYSCTL_HANDLER_ARGS);
328 SYSCTL_PROC(_vm, OID_AUTO, swap_async_max, CTLTYPE_INT | CTLFLAG_RW |
329 CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_async_max, "I",
330 "Maximum running async swap ops");
332 static struct swblock **swhash;
333 static int swhash_mask;
334 static struct mtx swhash_mtx;
336 static struct sx sw_alloc_sx;
339 * "named" and "unnamed" anon region objects. Try to reduce the overhead
340 * of searching a named list by hashing it just a little.
345 #define NOBJLIST(handle) \
346 (&swap_pager_object_list[((int)(intptr_t)handle >> 4) & (NOBJLISTS-1)])
348 static struct pagerlst swap_pager_object_list[NOBJLISTS];
349 static uma_zone_t swap_zone;
352 * pagerops for OBJT_SWAP - "swap pager". Some ops are also global procedure
353 * calls hooked from other parts of the VM system and do not appear here.
354 * (see vm/swap_pager.h).
357 swap_pager_alloc(void *handle, vm_ooffset_t size,
358 vm_prot_t prot, vm_ooffset_t offset, struct ucred *);
359 static void swap_pager_dealloc(vm_object_t object);
360 static int swap_pager_getpages(vm_object_t, vm_page_t *, int, int *,
362 static int swap_pager_getpages_async(vm_object_t, vm_page_t *, int, int *,
363 int *, pgo_getpages_iodone_t, void *);
364 static void swap_pager_putpages(vm_object_t, vm_page_t *, int, boolean_t, int *);
366 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before, int *after);
367 static void swap_pager_init(void);
368 static void swap_pager_unswapped(vm_page_t);
369 static void swap_pager_swapoff(struct swdevt *sp);
371 struct pagerops swappagerops = {
372 .pgo_init = swap_pager_init, /* early system initialization of pager */
373 .pgo_alloc = swap_pager_alloc, /* allocate an OBJT_SWAP object */
374 .pgo_dealloc = swap_pager_dealloc, /* deallocate an OBJT_SWAP object */
375 .pgo_getpages = swap_pager_getpages, /* pagein */
376 .pgo_getpages_async = swap_pager_getpages_async, /* pagein (async) */
377 .pgo_putpages = swap_pager_putpages, /* pageout */
378 .pgo_haspage = swap_pager_haspage, /* get backing store status for page */
379 .pgo_pageunswapped = swap_pager_unswapped, /* remove swap related to page */
383 * swap_*() routines are externally accessible. swp_*() routines are
386 static int nswap_lowat = 128; /* in pages, swap_pager_almost_full warn */
387 static int nswap_hiwat = 512; /* in pages, swap_pager_almost_full warn */
389 SYSCTL_INT(_vm, OID_AUTO, dmmax, CTLFLAG_RD, &nsw_cluster_max, 0,
390 "Maximum size of a swap block in pages");
392 static void swp_sizecheck(void);
393 static void swp_pager_async_iodone(struct buf *bp);
394 static int swapongeom(struct vnode *);
395 static int swaponvp(struct thread *, struct vnode *, u_long);
396 static int swapoff_one(struct swdevt *sp, struct ucred *cred);
399 * Swap bitmap functions
401 static void swp_pager_freeswapspace(daddr_t blk, int npages);
402 static daddr_t swp_pager_getswapspace(int npages);
407 static struct swblock **swp_pager_hash(vm_object_t object, vm_pindex_t index);
408 static void swp_pager_meta_build(vm_object_t, vm_pindex_t, daddr_t);
409 static void swp_pager_meta_free(vm_object_t, vm_pindex_t, vm_pindex_t);
410 static void swp_pager_meta_free_all(vm_object_t);
411 static daddr_t swp_pager_meta_ctl(vm_object_t, vm_pindex_t, int);
414 * SWP_SIZECHECK() - update swap_pager_full indication
416 * update the swap_pager_almost_full indication and warn when we are
417 * about to run out of swap space, using lowat/hiwat hysteresis.
419 * Clear swap_pager_full ( task killing ) indication when lowat is met.
421 * No restrictions on call
422 * This routine may not block.
428 if (swap_pager_avail < nswap_lowat) {
429 if (swap_pager_almost_full == 0) {
430 printf("swap_pager: out of swap space\n");
431 swap_pager_almost_full = 1;
435 if (swap_pager_avail > nswap_hiwat)
436 swap_pager_almost_full = 0;
441 * SWP_PAGER_HASH() - hash swap meta data
443 * This is an helper function which hashes the swapblk given
444 * the object and page index. It returns a pointer to a pointer
445 * to the object, or a pointer to a NULL pointer if it could not
448 static struct swblock **
449 swp_pager_hash(vm_object_t object, vm_pindex_t index)
451 struct swblock **pswap;
452 struct swblock *swap;
454 index &= ~(vm_pindex_t)SWAP_META_MASK;
455 pswap = &swhash[(index ^ (int)(intptr_t)object) & swhash_mask];
456 while ((swap = *pswap) != NULL) {
457 if (swap->swb_object == object &&
458 swap->swb_index == index
462 pswap = &swap->swb_hnext;
468 * SWAP_PAGER_INIT() - initialize the swap pager!
470 * Expected to be started from system init. NOTE: This code is run
471 * before much else so be careful what you depend on. Most of the VM
472 * system has yet to be initialized at this point.
475 swap_pager_init(void)
478 * Initialize object lists
482 for (i = 0; i < NOBJLISTS; ++i)
483 TAILQ_INIT(&swap_pager_object_list[i]);
484 mtx_init(&sw_dev_mtx, "swapdev", NULL, MTX_DEF);
485 sx_init(&sw_alloc_sx, "swspsx");
486 sx_init(&swdev_syscall_lock, "swsysc");
490 * SWAP_PAGER_SWAP_INIT() - swap pager initialization from pageout process
492 * Expected to be started from pageout process once, prior to entering
496 swap_pager_swap_init(void)
501 * Number of in-transit swap bp operations. Don't
502 * exhaust the pbufs completely. Make sure we
503 * initialize workable values (0 will work for hysteresis
504 * but it isn't very efficient).
506 * The nsw_cluster_max is constrained by the bp->b_pages[]
507 * array (MAXPHYS/PAGE_SIZE) and our locally defined
508 * MAX_PAGEOUT_CLUSTER. Also be aware that swap ops are
509 * constrained by the swap device interleave stripe size.
511 * Currently we hardwire nsw_wcount_async to 4. This limit is
512 * designed to prevent other I/O from having high latencies due to
513 * our pageout I/O. The value 4 works well for one or two active swap
514 * devices but is probably a little low if you have more. Even so,
515 * a higher value would probably generate only a limited improvement
516 * with three or four active swap devices since the system does not
517 * typically have to pageout at extreme bandwidths. We will want
518 * at least 2 per swap devices, and 4 is a pretty good value if you
519 * have one NFS swap device due to the command/ack latency over NFS.
520 * So it all works out pretty well.
522 nsw_cluster_max = min((MAXPHYS/PAGE_SIZE), MAX_PAGEOUT_CLUSTER);
525 nsw_rcount = (nswbuf + 1) / 2;
526 nsw_wcount_sync = (nswbuf + 3) / 4;
527 nsw_wcount_async = 4;
528 nsw_wcount_async_max = nsw_wcount_async;
529 mtx_unlock(&pbuf_mtx);
532 * Initialize our zone. Right now I'm just guessing on the number
533 * we need based on the number of pages in the system. Each swblock
534 * can hold 32 pages, so this is probably overkill. This reservation
535 * is typically limited to around 32MB by default.
537 n = vm_cnt.v_page_count / 2;
538 if (maxswzone && n > maxswzone / sizeof(struct swblock))
539 n = maxswzone / sizeof(struct swblock);
541 swap_zone = uma_zcreate("SWAPMETA", sizeof(struct swblock), NULL, NULL,
542 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
543 if (swap_zone == NULL)
544 panic("failed to create swap_zone.");
546 if (uma_zone_reserve_kva(swap_zone, n))
549 * if the allocation failed, try a zone two thirds the
550 * size of the previous attempt.
555 printf("Swap zone entries reduced from %lu to %lu.\n", n2, n);
556 swap_maxpages = n * SWAP_META_PAGES;
557 swzone = n * sizeof(struct swblock);
561 * Initialize our meta-data hash table. The swapper does not need to
562 * be quite as efficient as the VM system, so we do not use an
563 * oversized hash table.
565 * n: size of hash table, must be power of 2
566 * swhash_mask: hash table index mask
568 for (n = 1; n < n2 / 8; n *= 2)
570 swhash = malloc(sizeof(struct swblock *) * n, M_VMPGDATA, M_WAITOK | M_ZERO);
572 mtx_init(&swhash_mtx, "swap_pager swhash", NULL, MTX_DEF);
576 swap_pager_alloc_init(void *handle, struct ucred *cred, vm_ooffset_t size,
582 if (!swap_reserve_by_cred(size, cred))
586 object = vm_object_allocate(OBJT_SWAP, OFF_TO_IDX(offset +
588 object->handle = handle;
591 object->charge = size;
593 object->un_pager.swp.swp_bcount = 0;
598 * SWAP_PAGER_ALLOC() - allocate a new OBJT_SWAP VM object and instantiate
599 * its metadata structures.
601 * This routine is called from the mmap and fork code to create a new
604 * This routine must ensure that no live duplicate is created for
605 * the named object request, which is protected against by
606 * holding the sw_alloc_sx lock in case handle != NULL.
609 swap_pager_alloc(void *handle, vm_ooffset_t size, vm_prot_t prot,
610 vm_ooffset_t offset, struct ucred *cred)
614 if (handle != NULL) {
616 * Reference existing named region or allocate new one. There
617 * should not be a race here against swp_pager_meta_build()
618 * as called from vm_page_remove() in regards to the lookup
621 sx_xlock(&sw_alloc_sx);
622 object = vm_pager_object_lookup(NOBJLIST(handle), handle);
623 if (object == NULL) {
624 object = swap_pager_alloc_init(handle, cred, size,
626 if (object != NULL) {
627 TAILQ_INSERT_TAIL(NOBJLIST(object->handle),
628 object, pager_object_list);
631 sx_xunlock(&sw_alloc_sx);
633 object = swap_pager_alloc_init(handle, cred, size, offset);
639 * SWAP_PAGER_DEALLOC() - remove swap metadata from object
641 * The swap backing for the object is destroyed. The code is
642 * designed such that we can reinstantiate it later, but this
643 * routine is typically called only when the entire object is
644 * about to be destroyed.
646 * The object must be locked.
649 swap_pager_dealloc(vm_object_t object)
652 VM_OBJECT_ASSERT_WLOCKED(object);
653 KASSERT((object->flags & OBJ_DEAD) != 0, ("dealloc of reachable obj"));
656 * Remove from list right away so lookups will fail if we block for
657 * pageout completion.
659 if (object->handle != NULL) {
660 VM_OBJECT_WUNLOCK(object);
661 sx_xlock(&sw_alloc_sx);
662 TAILQ_REMOVE(NOBJLIST(object->handle), object,
664 sx_xunlock(&sw_alloc_sx);
665 VM_OBJECT_WLOCK(object);
668 vm_object_pip_wait(object, "swpdea");
671 * Free all remaining metadata. We only bother to free it from
672 * the swap meta data. We do not attempt to free swapblk's still
673 * associated with vm_page_t's for this object. We do not care
674 * if paging is still in progress on some objects.
676 swp_pager_meta_free_all(object);
677 object->handle = NULL;
678 object->type = OBJT_DEAD;
681 /************************************************************************
682 * SWAP PAGER BITMAP ROUTINES *
683 ************************************************************************/
686 * SWP_PAGER_GETSWAPSPACE() - allocate raw swap space
688 * Allocate swap for the requested number of pages. The starting
689 * swap block number (a page index) is returned or SWAPBLK_NONE
690 * if the allocation failed.
692 * Also has the side effect of advising that somebody made a mistake
693 * when they configured swap and didn't configure enough.
695 * This routine may not sleep.
697 * We allocate in round-robin fashion from the configured devices.
700 swp_pager_getswapspace(int npages)
707 mtx_lock(&sw_dev_mtx);
709 for (i = 0; i < nswapdev; i++) {
711 sp = TAILQ_FIRST(&swtailq);
712 if (!(sp->sw_flags & SW_CLOSING)) {
713 blk = blist_alloc(sp->sw_blist, npages);
714 if (blk != SWAPBLK_NONE) {
716 sp->sw_used += npages;
717 swap_pager_avail -= npages;
719 swdevhd = TAILQ_NEXT(sp, sw_list);
723 sp = TAILQ_NEXT(sp, sw_list);
725 if (swap_pager_full != 2) {
726 printf("swap_pager_getswapspace(%d): failed\n", npages);
728 swap_pager_almost_full = 1;
732 mtx_unlock(&sw_dev_mtx);
737 swp_pager_isondev(daddr_t blk, struct swdevt *sp)
740 return (blk >= sp->sw_first && blk < sp->sw_end);
744 swp_pager_strategy(struct buf *bp)
748 mtx_lock(&sw_dev_mtx);
749 TAILQ_FOREACH(sp, &swtailq, sw_list) {
750 if (bp->b_blkno >= sp->sw_first && bp->b_blkno < sp->sw_end) {
751 mtx_unlock(&sw_dev_mtx);
752 if ((sp->sw_flags & SW_UNMAPPED) != 0 &&
753 unmapped_buf_allowed) {
754 bp->b_data = unmapped_buf;
757 pmap_qenter((vm_offset_t)bp->b_data,
758 &bp->b_pages[0], bp->b_bcount / PAGE_SIZE);
760 sp->sw_strategy(bp, sp);
764 panic("Swapdev not found");
769 * SWP_PAGER_FREESWAPSPACE() - free raw swap space
771 * This routine returns the specified swap blocks back to the bitmap.
773 * This routine may not sleep.
776 swp_pager_freeswapspace(daddr_t blk, int npages)
780 mtx_lock(&sw_dev_mtx);
781 TAILQ_FOREACH(sp, &swtailq, sw_list) {
782 if (blk >= sp->sw_first && blk < sp->sw_end) {
783 sp->sw_used -= npages;
785 * If we are attempting to stop swapping on
786 * this device, we don't want to mark any
787 * blocks free lest they be reused.
789 if ((sp->sw_flags & SW_CLOSING) == 0) {
790 blist_free(sp->sw_blist, blk - sp->sw_first,
792 swap_pager_avail += npages;
795 mtx_unlock(&sw_dev_mtx);
799 panic("Swapdev not found");
803 * SWAP_PAGER_FREESPACE() - frees swap blocks associated with a page
804 * range within an object.
806 * This is a globally accessible routine.
808 * This routine removes swapblk assignments from swap metadata.
810 * The external callers of this routine typically have already destroyed
811 * or renamed vm_page_t's associated with this range in the object so
814 * The object must be locked.
817 swap_pager_freespace(vm_object_t object, vm_pindex_t start, vm_size_t size)
820 swp_pager_meta_free(object, start, size);
824 * SWAP_PAGER_RESERVE() - reserve swap blocks in object
826 * Assigns swap blocks to the specified range within the object. The
827 * swap blocks are not zeroed. Any previous swap assignment is destroyed.
829 * Returns 0 on success, -1 on failure.
832 swap_pager_reserve(vm_object_t object, vm_pindex_t start, vm_size_t size)
835 daddr_t blk = SWAPBLK_NONE;
836 vm_pindex_t beg = start; /* save start index */
838 VM_OBJECT_WLOCK(object);
842 while ((blk = swp_pager_getswapspace(n)) == SWAPBLK_NONE) {
845 swp_pager_meta_free(object, beg, start - beg);
846 VM_OBJECT_WUNLOCK(object);
851 swp_pager_meta_build(object, start, blk);
857 swp_pager_meta_free(object, start, n);
858 VM_OBJECT_WUNLOCK(object);
863 * SWAP_PAGER_COPY() - copy blocks from source pager to destination pager
864 * and destroy the source.
866 * Copy any valid swapblks from the source to the destination. In
867 * cases where both the source and destination have a valid swapblk,
868 * we keep the destination's.
870 * This routine is allowed to sleep. It may sleep allocating metadata
871 * indirectly through swp_pager_meta_build() or if paging is still in
872 * progress on the source.
874 * The source object contains no vm_page_t's (which is just as well)
876 * The source object is of type OBJT_SWAP.
878 * The source and destination objects must be locked.
879 * Both object locks may temporarily be released.
882 swap_pager_copy(vm_object_t srcobject, vm_object_t dstobject,
883 vm_pindex_t offset, int destroysource)
887 VM_OBJECT_ASSERT_WLOCKED(srcobject);
888 VM_OBJECT_ASSERT_WLOCKED(dstobject);
891 * If destroysource is set, we remove the source object from the
892 * swap_pager internal queue now.
894 if (destroysource && srcobject->handle != NULL) {
895 vm_object_pip_add(srcobject, 1);
896 VM_OBJECT_WUNLOCK(srcobject);
897 vm_object_pip_add(dstobject, 1);
898 VM_OBJECT_WUNLOCK(dstobject);
899 sx_xlock(&sw_alloc_sx);
900 TAILQ_REMOVE(NOBJLIST(srcobject->handle), srcobject,
902 sx_xunlock(&sw_alloc_sx);
903 VM_OBJECT_WLOCK(dstobject);
904 vm_object_pip_wakeup(dstobject);
905 VM_OBJECT_WLOCK(srcobject);
906 vm_object_pip_wakeup(srcobject);
910 * transfer source to destination.
912 for (i = 0; i < dstobject->size; ++i) {
916 * Locate (without changing) the swapblk on the destination,
917 * unless it is invalid in which case free it silently, or
918 * if the destination is a resident page, in which case the
919 * source is thrown away.
921 dstaddr = swp_pager_meta_ctl(dstobject, i, 0);
923 if (dstaddr == SWAPBLK_NONE) {
925 * Destination has no swapblk and is not resident,
930 srcaddr = swp_pager_meta_ctl(
936 if (srcaddr != SWAPBLK_NONE) {
938 * swp_pager_meta_build() can sleep.
940 vm_object_pip_add(srcobject, 1);
941 VM_OBJECT_WUNLOCK(srcobject);
942 vm_object_pip_add(dstobject, 1);
943 swp_pager_meta_build(dstobject, i, srcaddr);
944 vm_object_pip_wakeup(dstobject);
945 VM_OBJECT_WLOCK(srcobject);
946 vm_object_pip_wakeup(srcobject);
950 * Destination has valid swapblk or it is represented
951 * by a resident page. We destroy the sourceblock.
954 swp_pager_meta_ctl(srcobject, i + offset, SWM_FREE);
959 * Free left over swap blocks in source.
961 * We have to revert the type to OBJT_DEFAULT so we do not accidentally
962 * double-remove the object from the swap queues.
965 swp_pager_meta_free_all(srcobject);
967 * Reverting the type is not necessary, the caller is going
968 * to destroy srcobject directly, but I'm doing it here
969 * for consistency since we've removed the object from its
972 srcobject->type = OBJT_DEFAULT;
977 * SWAP_PAGER_HASPAGE() - determine if we have good backing store for
978 * the requested page.
980 * We determine whether good backing store exists for the requested
981 * page and return TRUE if it does, FALSE if it doesn't.
983 * If TRUE, we also try to determine how much valid, contiguous backing
984 * store exists before and after the requested page.
987 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before,
993 VM_OBJECT_ASSERT_LOCKED(object);
996 * do we have good backing store at the requested index ?
998 blk0 = swp_pager_meta_ctl(object, pindex, 0);
999 if (blk0 == SWAPBLK_NONE) {
1008 * find backwards-looking contiguous good backing store
1010 if (before != NULL) {
1011 for (i = 1; i < SWB_NPAGES; i++) {
1014 blk = swp_pager_meta_ctl(object, pindex - i, 0);
1015 if (blk != blk0 - i)
1022 * find forward-looking contiguous good backing store
1024 if (after != NULL) {
1025 for (i = 1; i < SWB_NPAGES; i++) {
1026 blk = swp_pager_meta_ctl(object, pindex + i, 0);
1027 if (blk != blk0 + i)
1036 * SWAP_PAGER_PAGE_UNSWAPPED() - remove swap backing store related to page
1038 * This removes any associated swap backing store, whether valid or
1039 * not, from the page.
1041 * This routine is typically called when a page is made dirty, at
1042 * which point any associated swap can be freed. MADV_FREE also
1043 * calls us in a special-case situation
1045 * NOTE!!! If the page is clean and the swap was valid, the caller
1046 * should make the page dirty before calling this routine. This routine
1047 * does NOT change the m->dirty status of the page. Also: MADV_FREE
1050 * This routine may not sleep.
1052 * The object containing the page must be locked.
1055 swap_pager_unswapped(vm_page_t m)
1058 swp_pager_meta_ctl(m->object, m->pindex, SWM_FREE);
1062 * swap_pager_getpages() - bring pages in from swap
1064 * Attempt to page in the pages in array "m" of length "count". The caller
1065 * may optionally specify that additional pages preceding and succeeding
1066 * the specified range be paged in. The number of such pages is returned
1067 * in the "rbehind" and "rahead" parameters, and they will be in the
1068 * inactive queue upon return.
1070 * The pages in "m" must be busied and will remain busied upon return.
1073 swap_pager_getpages(vm_object_t object, vm_page_t *m, int count, int *rbehind,
1077 vm_page_t mpred, msucc, p;
1080 int i, j, maxahead, maxbehind, reqcount, shift;
1084 VM_OBJECT_WUNLOCK(object);
1085 bp = getpbuf(&nsw_rcount);
1086 VM_OBJECT_WLOCK(object);
1088 if (!swap_pager_haspage(object, m[0]->pindex, &maxbehind, &maxahead)) {
1089 relpbuf(bp, &nsw_rcount);
1090 return (VM_PAGER_FAIL);
1094 * Clip the readahead and readbehind ranges to exclude resident pages.
1096 if (rahead != NULL) {
1097 KASSERT(reqcount - 1 <= maxahead,
1098 ("page count %d extends beyond swap block", reqcount));
1099 *rahead = imin(*rahead, maxahead - (reqcount - 1));
1100 pindex = m[reqcount - 1]->pindex;
1101 msucc = TAILQ_NEXT(m[reqcount - 1], listq);
1102 if (msucc != NULL && msucc->pindex - pindex - 1 < *rahead)
1103 *rahead = msucc->pindex - pindex - 1;
1105 if (rbehind != NULL) {
1106 *rbehind = imin(*rbehind, maxbehind);
1107 pindex = m[0]->pindex;
1108 mpred = TAILQ_PREV(m[0], pglist, listq);
1109 if (mpred != NULL && pindex - mpred->pindex - 1 < *rbehind)
1110 *rbehind = pindex - mpred->pindex - 1;
1114 * Allocate readahead and readbehind pages.
1116 shift = rbehind != NULL ? *rbehind : 0;
1118 for (i = 1; i <= shift; i++) {
1119 p = vm_page_alloc(object, m[0]->pindex - i,
1122 /* Shift allocated pages to the left. */
1123 for (j = 0; j < i - 1; j++)
1125 bp->b_pages[j + shift - i + 1];
1128 bp->b_pages[shift - i] = p;
1133 for (i = 0; i < reqcount; i++)
1134 bp->b_pages[i + shift] = m[i];
1135 if (rahead != NULL) {
1136 for (i = 0; i < *rahead; i++) {
1137 p = vm_page_alloc(object,
1138 m[reqcount - 1]->pindex + i + 1, VM_ALLOC_NORMAL);
1141 bp->b_pages[shift + reqcount + i] = p;
1145 if (rbehind != NULL)
1150 vm_object_pip_add(object, count);
1152 for (i = 0; i < count; i++)
1153 bp->b_pages[i]->oflags |= VPO_SWAPINPROG;
1155 pindex = bp->b_pages[0]->pindex;
1156 blk = swp_pager_meta_ctl(object, pindex, 0);
1157 KASSERT(blk != SWAPBLK_NONE,
1158 ("no swap blocking containing %p(%jx)", object, (uintmax_t)pindex));
1160 VM_OBJECT_WUNLOCK(object);
1162 bp->b_flags |= B_PAGING;
1163 bp->b_iocmd = BIO_READ;
1164 bp->b_iodone = swp_pager_async_iodone;
1165 bp->b_rcred = crhold(thread0.td_ucred);
1166 bp->b_wcred = crhold(thread0.td_ucred);
1168 bp->b_bcount = PAGE_SIZE * count;
1169 bp->b_bufsize = PAGE_SIZE * count;
1170 bp->b_npages = count;
1171 bp->b_pgbefore = rbehind != NULL ? *rbehind : 0;
1172 bp->b_pgafter = rahead != NULL ? *rahead : 0;
1174 VM_CNT_INC(v_swapin);
1175 VM_CNT_ADD(v_swappgsin, count);
1178 * perform the I/O. NOTE!!! bp cannot be considered valid after
1179 * this point because we automatically release it on completion.
1180 * Instead, we look at the one page we are interested in which we
1181 * still hold a lock on even through the I/O completion.
1183 * The other pages in our m[] array are also released on completion,
1184 * so we cannot assume they are valid anymore either.
1186 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1189 swp_pager_strategy(bp);
1192 * Wait for the pages we want to complete. VPO_SWAPINPROG is always
1193 * cleared on completion. If an I/O error occurs, SWAPBLK_NONE
1194 * is set in the metadata for each page in the request.
1196 VM_OBJECT_WLOCK(object);
1197 while ((m[0]->oflags & VPO_SWAPINPROG) != 0) {
1198 m[0]->oflags |= VPO_SWAPSLEEP;
1199 VM_CNT_INC(v_intrans);
1200 if (VM_OBJECT_SLEEP(object, &object->paging_in_progress, PSWP,
1201 "swread", hz * 20)) {
1203 "swap_pager: indefinite wait buffer: bufobj: %p, blkno: %jd, size: %ld\n",
1204 bp->b_bufobj, (intmax_t)bp->b_blkno, bp->b_bcount);
1209 * If we had an unrecoverable read error pages will not be valid.
1211 for (i = 0; i < reqcount; i++)
1212 if (m[i]->valid != VM_PAGE_BITS_ALL)
1213 return (VM_PAGER_ERROR);
1215 return (VM_PAGER_OK);
1218 * A final note: in a low swap situation, we cannot deallocate swap
1219 * and mark a page dirty here because the caller is likely to mark
1220 * the page clean when we return, causing the page to possibly revert
1221 * to all-zero's later.
1226 * swap_pager_getpages_async():
1228 * Right now this is emulation of asynchronous operation on top of
1229 * swap_pager_getpages().
1232 swap_pager_getpages_async(vm_object_t object, vm_page_t *m, int count,
1233 int *rbehind, int *rahead, pgo_getpages_iodone_t iodone, void *arg)
1237 r = swap_pager_getpages(object, m, count, rbehind, rahead);
1238 VM_OBJECT_WUNLOCK(object);
1243 case VM_PAGER_ERROR:
1250 panic("unhandled swap_pager_getpages() error %d", r);
1252 (iodone)(arg, m, count, error);
1253 VM_OBJECT_WLOCK(object);
1259 * swap_pager_putpages:
1261 * Assign swap (if necessary) and initiate I/O on the specified pages.
1263 * We support both OBJT_DEFAULT and OBJT_SWAP objects. DEFAULT objects
1264 * are automatically converted to SWAP objects.
1266 * In a low memory situation we may block in VOP_STRATEGY(), but the new
1267 * vm_page reservation system coupled with properly written VFS devices
1268 * should ensure that no low-memory deadlock occurs. This is an area
1271 * The parent has N vm_object_pip_add() references prior to
1272 * calling us and will remove references for rtvals[] that are
1273 * not set to VM_PAGER_PEND. We need to remove the rest on I/O
1276 * The parent has soft-busy'd the pages it passes us and will unbusy
1277 * those whos rtvals[] entry is not set to VM_PAGER_PEND on return.
1278 * We need to unbusy the rest on I/O completion.
1281 swap_pager_putpages(vm_object_t object, vm_page_t *m, int count,
1282 int flags, int *rtvals)
1287 if (count && m[0]->object != object) {
1288 panic("swap_pager_putpages: object mismatch %p/%p",
1297 * Turn object into OBJT_SWAP
1298 * check for bogus sysops
1299 * force sync if not pageout process
1301 if (object->type != OBJT_SWAP)
1302 swp_pager_meta_build(object, 0, SWAPBLK_NONE);
1303 VM_OBJECT_WUNLOCK(object);
1306 if (curproc != pageproc)
1309 sync = (flags & VM_PAGER_PUT_SYNC) != 0;
1314 * Assign swap blocks and issue I/O. We reallocate swap on the fly.
1315 * The page is left dirty until the pageout operation completes
1318 for (i = 0; i < count; i += n) {
1324 * Maximum I/O size is limited by a number of factors.
1326 n = min(BLIST_MAX_ALLOC, count - i);
1327 n = min(n, nsw_cluster_max);
1330 * Get biggest block of swap we can. If we fail, fall
1331 * back and try to allocate a smaller block. Don't go
1332 * overboard trying to allocate space if it would overly
1336 (blk = swp_pager_getswapspace(n)) == SWAPBLK_NONE &&
1341 if (blk == SWAPBLK_NONE) {
1342 for (j = 0; j < n; ++j)
1343 rtvals[i+j] = VM_PAGER_FAIL;
1348 * All I/O parameters have been satisfied, build the I/O
1349 * request and assign the swap space.
1352 bp = getpbuf(&nsw_wcount_sync);
1354 bp = getpbuf(&nsw_wcount_async);
1355 bp->b_flags = B_ASYNC;
1357 bp->b_flags |= B_PAGING;
1358 bp->b_iocmd = BIO_WRITE;
1360 bp->b_rcred = crhold(thread0.td_ucred);
1361 bp->b_wcred = crhold(thread0.td_ucred);
1362 bp->b_bcount = PAGE_SIZE * n;
1363 bp->b_bufsize = PAGE_SIZE * n;
1366 VM_OBJECT_WLOCK(object);
1367 for (j = 0; j < n; ++j) {
1368 vm_page_t mreq = m[i+j];
1370 swp_pager_meta_build(
1375 vm_page_dirty(mreq);
1376 mreq->oflags |= VPO_SWAPINPROG;
1377 bp->b_pages[j] = mreq;
1379 VM_OBJECT_WUNLOCK(object);
1382 * Must set dirty range for NFS to work.
1385 bp->b_dirtyend = bp->b_bcount;
1387 VM_CNT_INC(v_swapout);
1388 VM_CNT_ADD(v_swappgsout, bp->b_npages);
1391 * We unconditionally set rtvals[] to VM_PAGER_PEND so that we
1392 * can call the async completion routine at the end of a
1393 * synchronous I/O operation. Otherwise, our caller would
1394 * perform duplicate unbusy and wakeup operations on the page
1395 * and object, respectively.
1397 for (j = 0; j < n; j++)
1398 rtvals[i + j] = VM_PAGER_PEND;
1403 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1405 if (sync == FALSE) {
1406 bp->b_iodone = swp_pager_async_iodone;
1408 swp_pager_strategy(bp);
1415 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1417 bp->b_iodone = bdone;
1418 swp_pager_strategy(bp);
1421 * Wait for the sync I/O to complete.
1423 bwait(bp, PVM, "swwrt");
1426 * Now that we are through with the bp, we can call the
1427 * normal async completion, which frees everything up.
1429 swp_pager_async_iodone(bp);
1431 VM_OBJECT_WLOCK(object);
1435 * swp_pager_async_iodone:
1437 * Completion routine for asynchronous reads and writes from/to swap.
1438 * Also called manually by synchronous code to finish up a bp.
1440 * This routine may not sleep.
1443 swp_pager_async_iodone(struct buf *bp)
1446 vm_object_t object = NULL;
1451 if (bp->b_ioflags & BIO_ERROR) {
1453 "swap_pager: I/O error - %s failed; blkno %ld,"
1454 "size %ld, error %d\n",
1455 ((bp->b_iocmd == BIO_READ) ? "pagein" : "pageout"),
1463 * remove the mapping for kernel virtual
1466 pmap_qremove((vm_offset_t)bp->b_data, bp->b_npages);
1468 bp->b_data = bp->b_kvabase;
1471 object = bp->b_pages[0]->object;
1472 VM_OBJECT_WLOCK(object);
1476 * cleanup pages. If an error occurs writing to swap, we are in
1477 * very serious trouble. If it happens to be a disk error, though,
1478 * we may be able to recover by reassigning the swap later on. So
1479 * in this case we remove the m->swapblk assignment for the page
1480 * but do not free it in the rlist. The errornous block(s) are thus
1481 * never reallocated as swap. Redirty the page and continue.
1483 for (i = 0; i < bp->b_npages; ++i) {
1484 vm_page_t m = bp->b_pages[i];
1486 m->oflags &= ~VPO_SWAPINPROG;
1487 if (m->oflags & VPO_SWAPSLEEP) {
1488 m->oflags &= ~VPO_SWAPSLEEP;
1489 wakeup(&object->paging_in_progress);
1492 if (bp->b_ioflags & BIO_ERROR) {
1494 * If an error occurs I'd love to throw the swapblk
1495 * away without freeing it back to swapspace, so it
1496 * can never be used again. But I can't from an
1499 if (bp->b_iocmd == BIO_READ) {
1501 * NOTE: for reads, m->dirty will probably
1502 * be overridden by the original caller of
1503 * getpages so don't play cute tricks here.
1508 * If a write error occurs, reactivate page
1509 * so it doesn't clog the inactive list,
1510 * then finish the I/O.
1514 vm_page_activate(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 KASSERT(!pmap_page_is_mapped(m),
1529 ("swp_pager_async_iodone: page %p is mapped", m));
1530 KASSERT(m->dirty == 0,
1531 ("swp_pager_async_iodone: page %p is dirty", m));
1533 m->valid = VM_PAGE_BITS_ALL;
1534 if (i < bp->b_pgbefore ||
1535 i >= bp->b_npages - bp->b_pgafter)
1536 vm_page_readahead_finish(m);
1539 * For write success, clear the dirty
1540 * status, then finish the I/O ( which decrements the
1541 * busy count and possibly wakes waiter's up ).
1542 * A page is only written to swap after a period of
1543 * inactivity. Therefore, we do not expect it to be
1546 KASSERT(!pmap_page_is_write_mapped(m),
1547 ("swp_pager_async_iodone: page %p is not write"
1551 vm_page_deactivate_noreuse(m);
1558 * adjust pip. NOTE: the original parent may still have its own
1559 * pip refs on the object.
1561 if (object != NULL) {
1562 vm_object_pip_wakeupn(object, bp->b_npages);
1563 VM_OBJECT_WUNLOCK(object);
1567 * swapdev_strategy() manually sets b_vp and b_bufobj before calling
1568 * bstrategy(). Set them back to NULL now we're done with it, or we'll
1569 * trigger a KASSERT in relpbuf().
1573 bp->b_bufobj = NULL;
1576 * release the physical I/O buffer
1580 ((bp->b_iocmd == BIO_READ) ? &nsw_rcount :
1581 ((bp->b_flags & B_ASYNC) ?
1590 * swap_pager_isswapped:
1592 * Return 1 if at least one page in the given object is paged
1593 * out to the given swap device.
1595 * This routine may not sleep.
1598 swap_pager_isswapped(vm_object_t object, struct swdevt *sp)
1604 VM_OBJECT_ASSERT_WLOCKED(object);
1605 if (object->type != OBJT_SWAP)
1608 mtx_lock(&swhash_mtx);
1609 for (bcount = 0; bcount < object->un_pager.swp.swp_bcount; bcount++) {
1610 struct swblock *swap;
1612 if ((swap = *swp_pager_hash(object, index)) != NULL) {
1613 for (i = 0; i < SWAP_META_PAGES; ++i) {
1614 if (swp_pager_isondev(swap->swb_pages[i], sp)) {
1615 mtx_unlock(&swhash_mtx);
1620 index += SWAP_META_PAGES;
1622 mtx_unlock(&swhash_mtx);
1627 swap_pager_nswapdev(void)
1634 * SWP_PAGER_FORCE_PAGEIN() - force a swap block to be paged in
1636 * This routine dissociates the page at the given index within an object
1637 * from its backing store, paging it in if it does not reside in memory.
1638 * If the page is paged in, it is marked dirty and placed in the laundry
1639 * queue. The page is marked dirty because it no longer has backing
1640 * store. It is placed in the laundry queue because it has not been
1641 * accessed recently. Otherwise, it would already reside in memory.
1643 * We also attempt to swap in all other pages in the swap block.
1644 * However, we only guarantee that the one at the specified index is
1647 * XXX - The code to page the whole block in doesn't work, so we
1648 * revert to the one-by-one behavior for now. Sigh.
1651 swp_pager_force_pagein(vm_object_t object, vm_pindex_t pindex)
1655 vm_object_pip_add(object, 1);
1656 m = vm_page_grab(object, pindex, VM_ALLOC_NORMAL);
1657 if (m->valid == VM_PAGE_BITS_ALL) {
1658 vm_object_pip_wakeup(object);
1661 vm_page_activate(m);
1664 vm_pager_page_unswapped(m);
1668 if (swap_pager_getpages(object, &m, 1, NULL, NULL) != VM_PAGER_OK)
1669 panic("swap_pager_force_pagein: read from swap failed");/*XXX*/
1670 vm_object_pip_wakeup(object);
1676 vm_pager_page_unswapped(m);
1680 * swap_pager_swapoff:
1682 * Page in all of the pages that have been paged out to the
1683 * given device. The corresponding blocks in the bitmap must be
1684 * marked as allocated and the device must be flagged SW_CLOSING.
1685 * There may be no processes swapped out to the device.
1687 * This routine may block.
1690 swap_pager_swapoff(struct swdevt *sp)
1692 struct swblock *swap;
1693 vm_object_t locked_obj, object;
1697 sx_assert(&swdev_syscall_lock, SA_XLOCKED);
1702 mtx_lock(&swhash_mtx);
1703 for (i = 0; i <= swhash_mask; i++) { /* '<=' is correct here */
1705 for (swap = swhash[i]; swap != NULL; swap = swap->swb_hnext) {
1706 object = swap->swb_object;
1707 pindex = swap->swb_index;
1708 for (j = 0; j < SWAP_META_PAGES; ++j) {
1709 if (!swp_pager_isondev(swap->swb_pages[j], sp))
1711 if (locked_obj != object) {
1712 if (locked_obj != NULL)
1713 VM_OBJECT_WUNLOCK(locked_obj);
1714 locked_obj = object;
1715 if (!VM_OBJECT_TRYWLOCK(object)) {
1716 mtx_unlock(&swhash_mtx);
1717 /* Depends on type-stability. */
1718 VM_OBJECT_WLOCK(object);
1719 mtx_lock(&swhash_mtx);
1723 MPASS(locked_obj == object);
1724 mtx_unlock(&swhash_mtx);
1725 swp_pager_force_pagein(object, pindex + j);
1726 mtx_lock(&swhash_mtx);
1731 mtx_unlock(&swhash_mtx);
1732 if (locked_obj != NULL) {
1733 VM_OBJECT_WUNLOCK(locked_obj);
1738 * Objects may be locked or paging to the device being
1739 * removed, so we will miss their pages and need to
1740 * make another pass. We have marked this device as
1741 * SW_CLOSING, so the activity should finish soon.
1744 if (retries > 100) {
1745 panic("swapoff: failed to locate %d swap blocks",
1748 pause("swpoff", hz / 20);
1751 EVENTHANDLER_INVOKE(swapoff, sp);
1754 /************************************************************************
1756 ************************************************************************
1758 * These routines manipulate the swap metadata stored in the
1761 * Swap metadata is implemented with a global hash and not directly
1762 * linked into the object. Instead the object simply contains
1763 * appropriate tracking counters.
1767 * SWP_PAGER_META_BUILD() - add swap block to swap meta data for object
1769 * We first convert the object to a swap object if it is a default
1772 * The specified swapblk is added to the object's swap metadata. If
1773 * the swapblk is not valid, it is freed instead. Any previously
1774 * assigned swapblk is freed.
1777 swp_pager_meta_build(vm_object_t object, vm_pindex_t pindex, daddr_t swapblk)
1779 static volatile int exhausted;
1780 struct swblock *swap;
1781 struct swblock **pswap;
1784 VM_OBJECT_ASSERT_WLOCKED(object);
1786 * Convert default object to swap object if necessary
1788 if (object->type != OBJT_SWAP) {
1789 object->type = OBJT_SWAP;
1790 object->un_pager.swp.swp_bcount = 0;
1791 KASSERT(object->handle == NULL, ("default pager with handle"));
1795 * Locate hash entry. If not found create, but if we aren't adding
1796 * anything just return. If we run out of space in the map we wait
1797 * and, since the hash table may have changed, retry.
1800 mtx_lock(&swhash_mtx);
1801 pswap = swp_pager_hash(object, pindex);
1803 if ((swap = *pswap) == NULL) {
1806 if (swapblk == SWAPBLK_NONE)
1809 swap = *pswap = uma_zalloc(swap_zone, M_NOWAIT |
1810 (curproc == pageproc ? M_USE_RESERVE : 0));
1812 mtx_unlock(&swhash_mtx);
1813 VM_OBJECT_WUNLOCK(object);
1814 if (uma_zone_exhausted(swap_zone)) {
1815 if (atomic_cmpset_int(&exhausted, 0, 1))
1816 printf("swap zone exhausted, "
1817 "increase kern.maxswzone\n");
1818 vm_pageout_oom(VM_OOM_SWAPZ);
1819 pause("swzonex", 10);
1822 VM_OBJECT_WLOCK(object);
1826 if (atomic_cmpset_int(&exhausted, 1, 0))
1827 printf("swap zone ok\n");
1829 swap->swb_hnext = NULL;
1830 swap->swb_object = object;
1831 swap->swb_index = pindex & ~(vm_pindex_t)SWAP_META_MASK;
1832 swap->swb_count = 0;
1834 ++object->un_pager.swp.swp_bcount;
1836 for (i = 0; i < SWAP_META_PAGES; ++i)
1837 swap->swb_pages[i] = SWAPBLK_NONE;
1841 * Delete prior contents of metadata
1843 idx = pindex & SWAP_META_MASK;
1845 if (swap->swb_pages[idx] != SWAPBLK_NONE) {
1846 swp_pager_freeswapspace(swap->swb_pages[idx], 1);
1851 * Enter block into metadata
1853 swap->swb_pages[idx] = swapblk;
1854 if (swapblk != SWAPBLK_NONE)
1857 mtx_unlock(&swhash_mtx);
1861 * SWP_PAGER_META_FREE() - free a range of blocks in the object's swap metadata
1863 * The requested range of blocks is freed, with any associated swap
1864 * returned to the swap bitmap.
1866 * This routine will free swap metadata structures as they are cleaned
1867 * out. This routine does *NOT* operate on swap metadata associated
1868 * with resident pages.
1871 swp_pager_meta_free(vm_object_t object, vm_pindex_t index, vm_pindex_t count)
1873 struct swblock **pswap, *swap;
1878 VM_OBJECT_ASSERT_LOCKED(object);
1879 if (object->type != OBJT_SWAP || count == 0)
1882 mtx_lock(&swhash_mtx);
1883 for (c = 0; c < count;) {
1884 pswap = swp_pager_hash(object, index);
1885 sidx = index & SWAP_META_MASK;
1886 n = SWAP_META_PAGES - sidx;
1888 if ((swap = *pswap) == NULL) {
1892 for (; c < count && sidx < SWAP_META_PAGES; ++c, ++sidx) {
1893 if ((v = swap->swb_pages[sidx]) == SWAPBLK_NONE)
1895 swp_pager_freeswapspace(v, 1);
1896 swap->swb_pages[sidx] = SWAPBLK_NONE;
1897 if (--swap->swb_count == 0) {
1898 *pswap = swap->swb_hnext;
1899 uma_zfree(swap_zone, swap);
1900 --object->un_pager.swp.swp_bcount;
1901 c += SWAP_META_PAGES - sidx;
1906 mtx_unlock(&swhash_mtx);
1910 * SWP_PAGER_META_FREE_ALL() - destroy all swap metadata associated with object
1912 * This routine locates and destroys all swap metadata associated with
1916 swp_pager_meta_free_all(vm_object_t object)
1918 struct swblock **pswap, *swap;
1923 VM_OBJECT_ASSERT_WLOCKED(object);
1924 if (object->type != OBJT_SWAP)
1928 while (object->un_pager.swp.swp_bcount != 0) {
1929 mtx_lock(&swhash_mtx);
1930 pswap = swp_pager_hash(object, index);
1931 if ((swap = *pswap) != NULL) {
1932 for (i = 0; i < SWAP_META_PAGES; ++i) {
1933 v = swap->swb_pages[i];
1934 if (v != SWAPBLK_NONE) {
1936 swp_pager_freeswapspace(v, 1);
1939 if (swap->swb_count != 0)
1941 "swap_pager_meta_free_all: swb_count != 0");
1942 *pswap = swap->swb_hnext;
1943 uma_zfree(swap_zone, swap);
1944 --object->un_pager.swp.swp_bcount;
1946 mtx_unlock(&swhash_mtx);
1947 index += SWAP_META_PAGES;
1952 * SWP_PAGER_METACTL() - misc control of swap and vm_page_t meta data.
1954 * This routine is capable of looking up, popping, or freeing
1955 * swapblk assignments in the swap meta data or in the vm_page_t.
1956 * The routine typically returns the swapblk being looked-up, or popped,
1957 * or SWAPBLK_NONE if the block was freed, or SWAPBLK_NONE if the block
1958 * was invalid. This routine will automatically free any invalid
1959 * meta-data swapblks.
1961 * It is not possible to store invalid swapblks in the swap meta data
1962 * (other then a literal 'SWAPBLK_NONE'), so we don't bother checking.
1964 * When acting on a busy resident page and paging is in progress, we
1965 * have to wait until paging is complete but otherwise can act on the
1968 * SWM_FREE remove and free swap block from metadata
1969 * SWM_POP remove from meta data but do not free.. pop it out
1972 swp_pager_meta_ctl(vm_object_t object, vm_pindex_t pindex, int flags)
1974 struct swblock **pswap;
1975 struct swblock *swap;
1979 VM_OBJECT_ASSERT_LOCKED(object);
1981 * The meta data only exists of the object is OBJT_SWAP
1982 * and even then might not be allocated yet.
1984 if (object->type != OBJT_SWAP)
1985 return (SWAPBLK_NONE);
1988 mtx_lock(&swhash_mtx);
1989 pswap = swp_pager_hash(object, pindex);
1991 if ((swap = *pswap) != NULL) {
1992 idx = pindex & SWAP_META_MASK;
1993 r1 = swap->swb_pages[idx];
1995 if (r1 != SWAPBLK_NONE) {
1996 if (flags & SWM_FREE) {
1997 swp_pager_freeswapspace(r1, 1);
2000 if (flags & (SWM_FREE|SWM_POP)) {
2001 swap->swb_pages[idx] = SWAPBLK_NONE;
2002 if (--swap->swb_count == 0) {
2003 *pswap = swap->swb_hnext;
2004 uma_zfree(swap_zone, swap);
2005 --object->un_pager.swp.swp_bcount;
2010 mtx_unlock(&swhash_mtx);
2015 * Returns the least page index which is greater than or equal to the
2016 * parameter pindex and for which there is a swap block allocated.
2017 * Returns object's size if the object's type is not swap or if there
2018 * are no allocated swap blocks for the object after the requested
2022 swap_pager_find_least(vm_object_t object, vm_pindex_t pindex)
2024 struct swblock **pswap, *swap;
2025 vm_pindex_t i, j, lim;
2028 VM_OBJECT_ASSERT_LOCKED(object);
2029 if (object->type != OBJT_SWAP || object->un_pager.swp.swp_bcount == 0)
2030 return (object->size);
2032 mtx_lock(&swhash_mtx);
2033 for (j = pindex; j < object->size; j = lim) {
2034 pswap = swp_pager_hash(object, j);
2035 lim = rounddown2(j + SWAP_META_PAGES, SWAP_META_PAGES);
2036 if (lim > object->size)
2038 if ((swap = *pswap) != NULL) {
2039 for (idx = j & SWAP_META_MASK, i = j; i < lim;
2041 if (swap->swb_pages[idx] != SWAPBLK_NONE)
2048 mtx_unlock(&swhash_mtx);
2053 * System call swapon(name) enables swapping on device name,
2054 * which must be in the swdevsw. Return EBUSY
2055 * if already swapping on this device.
2057 #ifndef _SYS_SYSPROTO_H_
2058 struct swapon_args {
2068 sys_swapon(struct thread *td, struct swapon_args *uap)
2072 struct nameidata nd;
2075 error = priv_check(td, PRIV_SWAPON);
2079 sx_xlock(&swdev_syscall_lock);
2082 * Swap metadata may not fit in the KVM if we have physical
2085 if (swap_zone == NULL) {
2090 NDINIT(&nd, LOOKUP, ISOPEN | FOLLOW | AUDITVNODE1, UIO_USERSPACE,
2096 NDFREE(&nd, NDF_ONLY_PNBUF);
2099 if (vn_isdisk(vp, &error)) {
2100 error = swapongeom(vp);
2101 } else if (vp->v_type == VREG &&
2102 (vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
2103 (error = VOP_GETATTR(vp, &attr, td->td_ucred)) == 0) {
2105 * Allow direct swapping to NFS regular files in the same
2106 * way that nfs_mountroot() sets up diskless swapping.
2108 error = swaponvp(td, vp, attr.va_size / DEV_BSIZE);
2114 sx_xunlock(&swdev_syscall_lock);
2119 * Check that the total amount of swap currently configured does not
2120 * exceed half the theoretical maximum. If it does, print a warning
2121 * message and return -1; otherwise, return 0.
2124 swapon_check_swzone(unsigned long npages)
2126 unsigned long maxpages;
2128 /* absolute maximum we can handle assuming 100% efficiency */
2129 maxpages = uma_zone_get_max(swap_zone) * SWAP_META_PAGES;
2131 /* recommend using no more than half that amount */
2132 if (npages > maxpages / 2) {
2133 printf("warning: total configured swap (%lu pages) "
2134 "exceeds maximum recommended amount (%lu pages).\n",
2135 npages, maxpages / 2);
2136 printf("warning: increase kern.maxswzone "
2137 "or reduce amount of swap.\n");
2144 swaponsomething(struct vnode *vp, void *id, u_long nblks,
2145 sw_strategy_t *strategy, sw_close_t *close, dev_t dev, int flags)
2147 struct swdevt *sp, *tsp;
2152 * nblks is in DEV_BSIZE'd chunks, convert to PAGE_SIZE'd chunks.
2153 * First chop nblks off to page-align it, then convert.
2155 * sw->sw_nblks is in page-sized chunks now too.
2157 nblks &= ~(ctodb(1) - 1);
2158 nblks = dbtoc(nblks);
2161 * If we go beyond this, we get overflows in the radix
2164 mblocks = 0x40000000 / BLIST_META_RADIX;
2165 if (nblks > mblocks) {
2167 "WARNING: reducing swap size to maximum of %luMB per unit\n",
2168 mblocks / 1024 / 1024 * PAGE_SIZE);
2172 sp = malloc(sizeof *sp, M_VMPGDATA, M_WAITOK | M_ZERO);
2177 sp->sw_nblks = nblks;
2179 sp->sw_strategy = strategy;
2180 sp->sw_close = close;
2181 sp->sw_flags = flags;
2183 sp->sw_blist = blist_create(nblks, M_WAITOK);
2185 * Do not free the first two block in order to avoid overwriting
2186 * any bsd label at the front of the partition
2188 blist_free(sp->sw_blist, 2, nblks - 2);
2191 mtx_lock(&sw_dev_mtx);
2192 TAILQ_FOREACH(tsp, &swtailq, sw_list) {
2193 if (tsp->sw_end >= dvbase) {
2195 * We put one uncovered page between the devices
2196 * in order to definitively prevent any cross-device
2199 dvbase = tsp->sw_end + 1;
2202 sp->sw_first = dvbase;
2203 sp->sw_end = dvbase + nblks;
2204 TAILQ_INSERT_TAIL(&swtailq, sp, sw_list);
2206 swap_pager_avail += nblks - 2;
2207 swap_total += (vm_ooffset_t)nblks * PAGE_SIZE;
2208 swapon_check_swzone(swap_total / PAGE_SIZE);
2210 mtx_unlock(&sw_dev_mtx);
2211 EVENTHANDLER_INVOKE(swapon, sp);
2215 * SYSCALL: swapoff(devname)
2217 * Disable swapping on the given device.
2219 * XXX: Badly designed system call: it should use a device index
2220 * rather than filename as specification. We keep sw_vp around
2221 * only to make this work.
2223 #ifndef _SYS_SYSPROTO_H_
2224 struct swapoff_args {
2234 sys_swapoff(struct thread *td, struct swapoff_args *uap)
2237 struct nameidata nd;
2241 error = priv_check(td, PRIV_SWAPOFF);
2245 sx_xlock(&swdev_syscall_lock);
2247 NDINIT(&nd, LOOKUP, FOLLOW | AUDITVNODE1, UIO_USERSPACE, uap->name,
2252 NDFREE(&nd, NDF_ONLY_PNBUF);
2255 mtx_lock(&sw_dev_mtx);
2256 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2257 if (sp->sw_vp == vp)
2260 mtx_unlock(&sw_dev_mtx);
2265 error = swapoff_one(sp, td->td_ucred);
2267 sx_xunlock(&swdev_syscall_lock);
2272 swapoff_one(struct swdevt *sp, struct ucred *cred)
2279 sx_assert(&swdev_syscall_lock, SA_XLOCKED);
2281 (void) vn_lock(sp->sw_vp, LK_EXCLUSIVE | LK_RETRY);
2282 error = mac_system_check_swapoff(cred, sp->sw_vp);
2283 (void) VOP_UNLOCK(sp->sw_vp, 0);
2287 nblks = sp->sw_nblks;
2290 * We can turn off this swap device safely only if the
2291 * available virtual memory in the system will fit the amount
2292 * of data we will have to page back in, plus an epsilon so
2293 * the system doesn't become critically low on swap space.
2295 if (vm_cnt.v_free_count + swap_pager_avail < nblks + nswap_lowat)
2299 * Prevent further allocations on this device.
2301 mtx_lock(&sw_dev_mtx);
2302 sp->sw_flags |= SW_CLOSING;
2303 swap_pager_avail -= blist_fill(sp->sw_blist, 0, nblks);
2304 swap_total -= (vm_ooffset_t)nblks * PAGE_SIZE;
2305 mtx_unlock(&sw_dev_mtx);
2308 * Page in the contents of the device and close it.
2310 swap_pager_swapoff(sp);
2312 sp->sw_close(curthread, sp);
2313 mtx_lock(&sw_dev_mtx);
2315 TAILQ_REMOVE(&swtailq, sp, sw_list);
2317 if (nswapdev == 0) {
2318 swap_pager_full = 2;
2319 swap_pager_almost_full = 1;
2323 mtx_unlock(&sw_dev_mtx);
2324 blist_destroy(sp->sw_blist);
2325 free(sp, M_VMPGDATA);
2332 struct swdevt *sp, *spt;
2333 const char *devname;
2336 sx_xlock(&swdev_syscall_lock);
2338 mtx_lock(&sw_dev_mtx);
2339 TAILQ_FOREACH_SAFE(sp, &swtailq, sw_list, spt) {
2340 mtx_unlock(&sw_dev_mtx);
2341 if (vn_isdisk(sp->sw_vp, NULL))
2342 devname = devtoname(sp->sw_vp->v_rdev);
2345 error = swapoff_one(sp, thread0.td_ucred);
2347 printf("Cannot remove swap device %s (error=%d), "
2348 "skipping.\n", devname, error);
2349 } else if (bootverbose) {
2350 printf("Swap device %s removed.\n", devname);
2352 mtx_lock(&sw_dev_mtx);
2354 mtx_unlock(&sw_dev_mtx);
2356 sx_xunlock(&swdev_syscall_lock);
2360 swap_pager_status(int *total, int *used)
2366 mtx_lock(&sw_dev_mtx);
2367 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2368 *total += sp->sw_nblks;
2369 *used += sp->sw_used;
2371 mtx_unlock(&sw_dev_mtx);
2375 swap_dev_info(int name, struct xswdev *xs, char *devname, size_t len)
2378 const char *tmp_devname;
2383 mtx_lock(&sw_dev_mtx);
2384 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2389 xs->xsw_version = XSWDEV_VERSION;
2390 xs->xsw_dev = sp->sw_dev;
2391 xs->xsw_flags = sp->sw_flags;
2392 xs->xsw_nblks = sp->sw_nblks;
2393 xs->xsw_used = sp->sw_used;
2394 if (devname != NULL) {
2395 if (vn_isdisk(sp->sw_vp, NULL))
2396 tmp_devname = devtoname(sp->sw_vp->v_rdev);
2398 tmp_devname = "[file]";
2399 strncpy(devname, tmp_devname, len);
2404 mtx_unlock(&sw_dev_mtx);
2408 #if defined(COMPAT_FREEBSD11)
2409 #define XSWDEV_VERSION_11 1
2420 sysctl_vm_swap_info(SYSCTL_HANDLER_ARGS)
2423 #if defined(COMPAT_FREEBSD11)
2424 struct xswdev11 xs11;
2428 if (arg2 != 1) /* name length */
2430 error = swap_dev_info(*(int *)arg1, &xs, NULL, 0);
2433 #if defined(COMPAT_FREEBSD11)
2434 if (req->oldlen == sizeof(xs11)) {
2435 xs11.xsw_version = XSWDEV_VERSION_11;
2436 xs11.xsw_dev = xs.xsw_dev; /* truncation */
2437 xs11.xsw_flags = xs.xsw_flags;
2438 xs11.xsw_nblks = xs.xsw_nblks;
2439 xs11.xsw_used = xs.xsw_used;
2440 error = SYSCTL_OUT(req, &xs11, sizeof(xs11));
2443 error = SYSCTL_OUT(req, &xs, sizeof(xs));
2447 SYSCTL_INT(_vm, OID_AUTO, nswapdev, CTLFLAG_RD, &nswapdev, 0,
2448 "Number of swap devices");
2449 SYSCTL_NODE(_vm, OID_AUTO, swap_info, CTLFLAG_RD | CTLFLAG_MPSAFE,
2450 sysctl_vm_swap_info,
2451 "Swap statistics by device");
2454 * vmspace_swap_count() - count the approximate swap usage in pages for a
2457 * The map must be locked.
2459 * Swap usage is determined by taking the proportional swap used by
2460 * VM objects backing the VM map. To make up for fractional losses,
2461 * if the VM object has any swap use at all the associated map entries
2462 * count for at least 1 swap page.
2465 vmspace_swap_count(struct vmspace *vmspace)
2472 map = &vmspace->vm_map;
2475 for (cur = map->header.next; cur != &map->header; cur = cur->next) {
2476 if ((cur->eflags & MAP_ENTRY_IS_SUB_MAP) == 0 &&
2477 (object = cur->object.vm_object) != NULL) {
2478 VM_OBJECT_WLOCK(object);
2479 if (object->type == OBJT_SWAP &&
2480 object->un_pager.swp.swp_bcount != 0) {
2481 n = (cur->end - cur->start) / PAGE_SIZE;
2482 count += object->un_pager.swp.swp_bcount *
2483 SWAP_META_PAGES * n / object->size + 1;
2485 VM_OBJECT_WUNLOCK(object);
2494 * Swapping onto disk devices.
2498 static g_orphan_t swapgeom_orphan;
2500 static struct g_class g_swap_class = {
2502 .version = G_VERSION,
2503 .orphan = swapgeom_orphan,
2506 DECLARE_GEOM_CLASS(g_swap_class, g_class);
2510 swapgeom_close_ev(void *arg, int flags)
2512 struct g_consumer *cp;
2515 g_access(cp, -1, -1, 0);
2517 g_destroy_consumer(cp);
2521 * Add a reference to the g_consumer for an inflight transaction.
2524 swapgeom_acquire(struct g_consumer *cp)
2527 mtx_assert(&sw_dev_mtx, MA_OWNED);
2532 * Remove a reference from the g_consumer. Post a close event if all
2533 * references go away, since the function might be called from the
2537 swapgeom_release(struct g_consumer *cp, struct swdevt *sp)
2540 mtx_assert(&sw_dev_mtx, MA_OWNED);
2542 if (cp->index == 0) {
2543 if (g_post_event(swapgeom_close_ev, cp, M_NOWAIT, NULL) == 0)
2549 swapgeom_done(struct bio *bp2)
2553 struct g_consumer *cp;
2555 bp = bp2->bio_caller2;
2557 bp->b_ioflags = bp2->bio_flags;
2559 bp->b_ioflags |= BIO_ERROR;
2560 bp->b_resid = bp->b_bcount - bp2->bio_completed;
2561 bp->b_error = bp2->bio_error;
2563 sp = bp2->bio_caller1;
2564 mtx_lock(&sw_dev_mtx);
2565 swapgeom_release(cp, sp);
2566 mtx_unlock(&sw_dev_mtx);
2571 swapgeom_strategy(struct buf *bp, struct swdevt *sp)
2574 struct g_consumer *cp;
2576 mtx_lock(&sw_dev_mtx);
2579 mtx_unlock(&sw_dev_mtx);
2580 bp->b_error = ENXIO;
2581 bp->b_ioflags |= BIO_ERROR;
2585 swapgeom_acquire(cp);
2586 mtx_unlock(&sw_dev_mtx);
2587 if (bp->b_iocmd == BIO_WRITE)
2590 bio = g_alloc_bio();
2592 mtx_lock(&sw_dev_mtx);
2593 swapgeom_release(cp, sp);
2594 mtx_unlock(&sw_dev_mtx);
2595 bp->b_error = ENOMEM;
2596 bp->b_ioflags |= BIO_ERROR;
2601 bio->bio_caller1 = sp;
2602 bio->bio_caller2 = bp;
2603 bio->bio_cmd = bp->b_iocmd;
2604 bio->bio_offset = (bp->b_blkno - sp->sw_first) * PAGE_SIZE;
2605 bio->bio_length = bp->b_bcount;
2606 bio->bio_done = swapgeom_done;
2607 if (!buf_mapped(bp)) {
2608 bio->bio_ma = bp->b_pages;
2609 bio->bio_data = unmapped_buf;
2610 bio->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
2611 bio->bio_ma_n = bp->b_npages;
2612 bio->bio_flags |= BIO_UNMAPPED;
2614 bio->bio_data = bp->b_data;
2617 g_io_request(bio, cp);
2622 swapgeom_orphan(struct g_consumer *cp)
2627 mtx_lock(&sw_dev_mtx);
2628 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2629 if (sp->sw_id == cp) {
2630 sp->sw_flags |= SW_CLOSING;
2635 * Drop reference we were created with. Do directly since we're in a
2636 * special context where we don't have to queue the call to
2637 * swapgeom_close_ev().
2640 destroy = ((sp != NULL) && (cp->index == 0));
2643 mtx_unlock(&sw_dev_mtx);
2645 swapgeom_close_ev(cp, 0);
2649 swapgeom_close(struct thread *td, struct swdevt *sw)
2651 struct g_consumer *cp;
2653 mtx_lock(&sw_dev_mtx);
2656 mtx_unlock(&sw_dev_mtx);
2659 * swapgeom_close() may be called from the biodone context,
2660 * where we cannot perform topology changes. Delegate the
2661 * work to the events thread.
2664 g_waitfor_event(swapgeom_close_ev, cp, M_WAITOK, NULL);
2668 swapongeom_locked(struct cdev *dev, struct vnode *vp)
2670 struct g_provider *pp;
2671 struct g_consumer *cp;
2672 static struct g_geom *gp;
2677 pp = g_dev_getprovider(dev);
2680 mtx_lock(&sw_dev_mtx);
2681 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2683 if (cp != NULL && cp->provider == pp) {
2684 mtx_unlock(&sw_dev_mtx);
2688 mtx_unlock(&sw_dev_mtx);
2690 gp = g_new_geomf(&g_swap_class, "swap");
2691 cp = g_new_consumer(gp);
2692 cp->index = 1; /* Number of active I/Os, plus one for being active. */
2693 cp->flags |= G_CF_DIRECT_SEND | G_CF_DIRECT_RECEIVE;
2696 * XXX: Every time you think you can improve the margin for
2697 * footshooting, somebody depends on the ability to do so:
2698 * savecore(8) wants to write to our swapdev so we cannot
2699 * set an exclusive count :-(
2701 error = g_access(cp, 1, 1, 0);
2704 g_destroy_consumer(cp);
2707 nblks = pp->mediasize / DEV_BSIZE;
2708 swaponsomething(vp, cp, nblks, swapgeom_strategy,
2709 swapgeom_close, dev2udev(dev),
2710 (pp->flags & G_PF_ACCEPT_UNMAPPED) != 0 ? SW_UNMAPPED : 0);
2715 swapongeom(struct vnode *vp)
2719 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2720 if (vp->v_type != VCHR || (vp->v_iflag & VI_DOOMED) != 0) {
2724 error = swapongeom_locked(vp->v_rdev, vp);
2725 g_topology_unlock();
2734 * This is used mainly for network filesystem (read: probably only tested
2735 * with NFS) swapfiles.
2740 swapdev_strategy(struct buf *bp, struct swdevt *sp)
2744 bp->b_blkno = ctodb(bp->b_blkno - sp->sw_first);
2748 if (bp->b_iocmd == BIO_WRITE) {
2750 bufobj_wdrop(bp->b_bufobj);
2751 bufobj_wref(&vp2->v_bufobj);
2753 if (bp->b_bufobj != &vp2->v_bufobj)
2754 bp->b_bufobj = &vp2->v_bufobj;
2756 bp->b_iooffset = dbtob(bp->b_blkno);
2762 swapdev_close(struct thread *td, struct swdevt *sp)
2765 VOP_CLOSE(sp->sw_vp, FREAD | FWRITE, td->td_ucred, td);
2771 swaponvp(struct thread *td, struct vnode *vp, u_long nblks)
2778 mtx_lock(&sw_dev_mtx);
2779 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2780 if (sp->sw_id == vp) {
2781 mtx_unlock(&sw_dev_mtx);
2785 mtx_unlock(&sw_dev_mtx);
2787 (void) vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2789 error = mac_system_check_swapon(td->td_ucred, vp);
2792 error = VOP_OPEN(vp, FREAD | FWRITE, td->td_ucred, td, NULL);
2793 (void) VOP_UNLOCK(vp, 0);
2797 swaponsomething(vp, vp, nblks, swapdev_strategy, swapdev_close,
2803 sysctl_swap_async_max(SYSCTL_HANDLER_ARGS)
2807 new = nsw_wcount_async_max;
2808 error = sysctl_handle_int(oidp, &new, 0, req);
2809 if (error != 0 || req->newptr == NULL)
2812 if (new > nswbuf / 2 || new < 1)
2815 mtx_lock(&pbuf_mtx);
2816 while (nsw_wcount_async_max != new) {
2818 * Adjust difference. If the current async count is too low,
2819 * we will need to sqeeze our update slowly in. Sleep with a
2820 * higher priority than getpbuf() to finish faster.
2822 n = new - nsw_wcount_async_max;
2823 if (nsw_wcount_async + n >= 0) {
2824 nsw_wcount_async += n;
2825 nsw_wcount_async_max += n;
2826 wakeup(&nsw_wcount_async);
2828 nsw_wcount_async_max -= nsw_wcount_async;
2829 nsw_wcount_async = 0;
2830 msleep(&nsw_wcount_async, &pbuf_mtx, PSWP,
2834 mtx_unlock(&pbuf_mtx);