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 * MAX_PAGEOUT_CLUSTER must be a power of 2 between 1 and 64.
119 * The 64-page limit is due to the radix code (kern/subr_blist.c).
121 #ifndef MAX_PAGEOUT_CLUSTER
122 #define MAX_PAGEOUT_CLUSTER 32
125 #if !defined(SWB_NPAGES)
126 #define SWB_NPAGES MAX_PAGEOUT_CLUSTER
130 * The swblock structure maps an object and a small, fixed-size range
131 * of page indices to disk addresses within a swap area.
132 * The collection of these mappings is implemented as a hash table.
133 * Unused disk addresses within a swap area are allocated and managed
136 #define SWAP_META_PAGES 32
137 #define SWAP_META_MASK (SWAP_META_PAGES - 1)
140 struct swblock *swb_hnext;
141 vm_object_t swb_object;
142 vm_pindex_t swb_index;
144 daddr_t swb_pages[SWAP_META_PAGES];
147 static MALLOC_DEFINE(M_VMPGDATA, "vm_pgdata", "swap pager private data");
148 static struct mtx sw_dev_mtx;
149 static TAILQ_HEAD(, swdevt) swtailq = TAILQ_HEAD_INITIALIZER(swtailq);
150 static struct swdevt *swdevhd; /* Allocate from here next */
151 static int nswapdev; /* Number of swap devices */
152 int swap_pager_avail;
153 static struct sx swdev_syscall_lock; /* serialize swap(on|off) */
155 static vm_ooffset_t swap_total;
156 SYSCTL_QUAD(_vm, OID_AUTO, swap_total, CTLFLAG_RD, &swap_total, 0,
157 "Total amount of available swap storage.");
158 static vm_ooffset_t swap_reserved;
159 SYSCTL_QUAD(_vm, OID_AUTO, swap_reserved, CTLFLAG_RD, &swap_reserved, 0,
160 "Amount of swap storage needed to back all allocated anonymous memory.");
161 static int overcommit = 0;
162 SYSCTL_INT(_vm, OID_AUTO, overcommit, CTLFLAG_RW, &overcommit, 0,
163 "Configure virtual memory overcommit behavior. See tuning(7) "
165 static unsigned long swzone;
166 SYSCTL_ULONG(_vm, OID_AUTO, swzone, CTLFLAG_RD, &swzone, 0,
167 "Actual size of swap metadata zone");
168 static unsigned long swap_maxpages;
169 SYSCTL_ULONG(_vm, OID_AUTO, swap_maxpages, CTLFLAG_RD, &swap_maxpages, 0,
170 "Maximum amount of swap supported");
172 /* bits from overcommit */
173 #define SWAP_RESERVE_FORCE_ON (1 << 0)
174 #define SWAP_RESERVE_RLIMIT_ON (1 << 1)
175 #define SWAP_RESERVE_ALLOW_NONWIRED (1 << 2)
178 swap_reserve(vm_ooffset_t incr)
181 return (swap_reserve_by_cred(incr, curthread->td_ucred));
185 swap_reserve_by_cred(vm_ooffset_t incr, struct ucred *cred)
190 static struct timeval lastfail;
193 uip = cred->cr_ruidinfo;
195 if (incr & PAGE_MASK)
196 panic("swap_reserve: & PAGE_MASK");
201 error = racct_add(curproc, RACCT_SWAP, incr);
202 PROC_UNLOCK(curproc);
209 mtx_lock(&sw_dev_mtx);
210 r = swap_reserved + incr;
211 if (overcommit & SWAP_RESERVE_ALLOW_NONWIRED) {
212 s = vm_cnt.v_page_count - vm_cnt.v_free_reserved - vm_cnt.v_wire_count;
217 if ((overcommit & SWAP_RESERVE_FORCE_ON) == 0 || r <= s ||
218 (error = priv_check(curthread, PRIV_VM_SWAP_NOQUOTA)) == 0) {
222 mtx_unlock(&sw_dev_mtx);
225 UIDINFO_VMSIZE_LOCK(uip);
226 if ((overcommit & SWAP_RESERVE_RLIMIT_ON) != 0 &&
227 uip->ui_vmsize + incr > lim_cur(curthread, RLIMIT_SWAP) &&
228 priv_check(curthread, PRIV_VM_SWAP_NORLIMIT))
231 uip->ui_vmsize += incr;
232 UIDINFO_VMSIZE_UNLOCK(uip);
234 mtx_lock(&sw_dev_mtx);
235 swap_reserved -= incr;
236 mtx_unlock(&sw_dev_mtx);
239 if (!res && ppsratecheck(&lastfail, &curfail, 1)) {
240 printf("uid %d, pid %d: swap reservation for %jd bytes failed\n",
241 uip->ui_uid, curproc->p_pid, incr);
247 racct_sub(curproc, RACCT_SWAP, incr);
248 PROC_UNLOCK(curproc);
256 swap_reserve_force(vm_ooffset_t incr)
260 mtx_lock(&sw_dev_mtx);
261 swap_reserved += incr;
262 mtx_unlock(&sw_dev_mtx);
266 racct_add_force(curproc, RACCT_SWAP, incr);
267 PROC_UNLOCK(curproc);
270 uip = curthread->td_ucred->cr_ruidinfo;
272 UIDINFO_VMSIZE_LOCK(uip);
273 uip->ui_vmsize += incr;
274 UIDINFO_VMSIZE_UNLOCK(uip);
275 PROC_UNLOCK(curproc);
279 swap_release(vm_ooffset_t decr)
284 cred = curthread->td_ucred;
285 swap_release_by_cred(decr, cred);
286 PROC_UNLOCK(curproc);
290 swap_release_by_cred(vm_ooffset_t decr, struct ucred *cred)
294 uip = cred->cr_ruidinfo;
296 if (decr & PAGE_MASK)
297 panic("swap_release: & PAGE_MASK");
299 mtx_lock(&sw_dev_mtx);
300 if (swap_reserved < decr)
301 panic("swap_reserved < decr");
302 swap_reserved -= decr;
303 mtx_unlock(&sw_dev_mtx);
305 UIDINFO_VMSIZE_LOCK(uip);
306 if (uip->ui_vmsize < decr)
307 printf("negative vmsize for uid = %d\n", uip->ui_uid);
308 uip->ui_vmsize -= decr;
309 UIDINFO_VMSIZE_UNLOCK(uip);
311 racct_sub_cred(cred, RACCT_SWAP, decr);
314 #define SWM_FREE 0x02 /* free, period */
315 #define SWM_POP 0x04 /* pop out */
317 int swap_pager_full = 2; /* swap space exhaustion (task killing) */
318 static int swap_pager_almost_full = 1; /* swap space exhaustion (w/hysteresis)*/
319 static int nsw_rcount; /* free read buffers */
320 static int nsw_wcount_sync; /* limit write buffers / synchronous */
321 static int nsw_wcount_async; /* limit write buffers / asynchronous */
322 static int nsw_wcount_async_max;/* assigned maximum */
323 static int nsw_cluster_max; /* maximum VOP I/O allowed */
325 static int sysctl_swap_async_max(SYSCTL_HANDLER_ARGS);
326 SYSCTL_PROC(_vm, OID_AUTO, swap_async_max, CTLTYPE_INT | CTLFLAG_RW |
327 CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_async_max, "I",
328 "Maximum running async swap ops");
330 static struct swblock **swhash;
331 static int swhash_mask;
332 static struct mtx swhash_mtx;
334 static struct sx sw_alloc_sx;
337 * "named" and "unnamed" anon region objects. Try to reduce the overhead
338 * of searching a named list by hashing it just a little.
343 #define NOBJLIST(handle) \
344 (&swap_pager_object_list[((int)(intptr_t)handle >> 4) & (NOBJLISTS-1)])
346 static struct pagerlst swap_pager_object_list[NOBJLISTS];
347 static uma_zone_t swap_zone;
350 * pagerops for OBJT_SWAP - "swap pager". Some ops are also global procedure
351 * calls hooked from other parts of the VM system and do not appear here.
352 * (see vm/swap_pager.h).
355 swap_pager_alloc(void *handle, vm_ooffset_t size,
356 vm_prot_t prot, vm_ooffset_t offset, struct ucred *);
357 static void swap_pager_dealloc(vm_object_t object);
358 static int swap_pager_getpages(vm_object_t, vm_page_t *, int, int *,
360 static int swap_pager_getpages_async(vm_object_t, vm_page_t *, int, int *,
361 int *, pgo_getpages_iodone_t, void *);
362 static void swap_pager_putpages(vm_object_t, vm_page_t *, int, boolean_t, int *);
364 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before, int *after);
365 static void swap_pager_init(void);
366 static void swap_pager_unswapped(vm_page_t);
367 static void swap_pager_swapoff(struct swdevt *sp);
369 struct pagerops swappagerops = {
370 .pgo_init = swap_pager_init, /* early system initialization of pager */
371 .pgo_alloc = swap_pager_alloc, /* allocate an OBJT_SWAP object */
372 .pgo_dealloc = swap_pager_dealloc, /* deallocate an OBJT_SWAP object */
373 .pgo_getpages = swap_pager_getpages, /* pagein */
374 .pgo_getpages_async = swap_pager_getpages_async, /* pagein (async) */
375 .pgo_putpages = swap_pager_putpages, /* pageout */
376 .pgo_haspage = swap_pager_haspage, /* get backing store status for page */
377 .pgo_pageunswapped = swap_pager_unswapped, /* remove swap related to page */
381 * swap_*() routines are externally accessible. swp_*() routines are
384 static int nswap_lowat = 128; /* in pages, swap_pager_almost_full warn */
385 static int nswap_hiwat = 512; /* in pages, swap_pager_almost_full warn */
387 SYSCTL_INT(_vm, OID_AUTO, dmmax, CTLFLAG_RD, &nsw_cluster_max, 0,
388 "Maximum size of a swap block in pages");
390 static void swp_sizecheck(void);
391 static void swp_pager_async_iodone(struct buf *bp);
392 static int swapongeom(struct vnode *);
393 static int swaponvp(struct thread *, struct vnode *, u_long);
394 static int swapoff_one(struct swdevt *sp, struct ucred *cred);
397 * Swap bitmap functions
399 static void swp_pager_freeswapspace(daddr_t blk, int npages);
400 static daddr_t swp_pager_getswapspace(int npages);
405 static struct swblock **swp_pager_hash(vm_object_t object, vm_pindex_t index);
406 static void swp_pager_meta_build(vm_object_t, vm_pindex_t, daddr_t);
407 static void swp_pager_meta_free(vm_object_t, vm_pindex_t, vm_pindex_t);
408 static void swp_pager_meta_free_all(vm_object_t);
409 static daddr_t swp_pager_meta_ctl(vm_object_t, vm_pindex_t, int);
412 * SWP_SIZECHECK() - update swap_pager_full indication
414 * update the swap_pager_almost_full indication and warn when we are
415 * about to run out of swap space, using lowat/hiwat hysteresis.
417 * Clear swap_pager_full ( task killing ) indication when lowat is met.
419 * No restrictions on call
420 * This routine may not block.
426 if (swap_pager_avail < nswap_lowat) {
427 if (swap_pager_almost_full == 0) {
428 printf("swap_pager: out of swap space\n");
429 swap_pager_almost_full = 1;
433 if (swap_pager_avail > nswap_hiwat)
434 swap_pager_almost_full = 0;
439 * SWP_PAGER_HASH() - hash swap meta data
441 * This is an helper function which hashes the swapblk given
442 * the object and page index. It returns a pointer to a pointer
443 * to the object, or a pointer to a NULL pointer if it could not
446 static struct swblock **
447 swp_pager_hash(vm_object_t object, vm_pindex_t index)
449 struct swblock **pswap;
450 struct swblock *swap;
452 index &= ~(vm_pindex_t)SWAP_META_MASK;
453 pswap = &swhash[(index ^ (int)(intptr_t)object) & swhash_mask];
454 while ((swap = *pswap) != NULL) {
455 if (swap->swb_object == object &&
456 swap->swb_index == index
460 pswap = &swap->swb_hnext;
466 * SWAP_PAGER_INIT() - initialize the swap pager!
468 * Expected to be started from system init. NOTE: This code is run
469 * before much else so be careful what you depend on. Most of the VM
470 * system has yet to be initialized at this point.
473 swap_pager_init(void)
476 * Initialize object lists
480 for (i = 0; i < NOBJLISTS; ++i)
481 TAILQ_INIT(&swap_pager_object_list[i]);
482 mtx_init(&sw_dev_mtx, "swapdev", NULL, MTX_DEF);
483 sx_init(&sw_alloc_sx, "swspsx");
484 sx_init(&swdev_syscall_lock, "swsysc");
488 * SWAP_PAGER_SWAP_INIT() - swap pager initialization from pageout process
490 * Expected to be started from pageout process once, prior to entering
494 swap_pager_swap_init(void)
499 * Number of in-transit swap bp operations. Don't
500 * exhaust the pbufs completely. Make sure we
501 * initialize workable values (0 will work for hysteresis
502 * but it isn't very efficient).
504 * The nsw_cluster_max is constrained by the bp->b_pages[]
505 * array (MAXPHYS/PAGE_SIZE) and our locally defined
506 * MAX_PAGEOUT_CLUSTER. Also be aware that swap ops are
507 * constrained by the swap device interleave stripe size.
509 * Currently we hardwire nsw_wcount_async to 4. This limit is
510 * designed to prevent other I/O from having high latencies due to
511 * our pageout I/O. The value 4 works well for one or two active swap
512 * devices but is probably a little low if you have more. Even so,
513 * a higher value would probably generate only a limited improvement
514 * with three or four active swap devices since the system does not
515 * typically have to pageout at extreme bandwidths. We will want
516 * at least 2 per swap devices, and 4 is a pretty good value if you
517 * have one NFS swap device due to the command/ack latency over NFS.
518 * So it all works out pretty well.
520 nsw_cluster_max = min((MAXPHYS/PAGE_SIZE), MAX_PAGEOUT_CLUSTER);
523 nsw_rcount = (nswbuf + 1) / 2;
524 nsw_wcount_sync = (nswbuf + 3) / 4;
525 nsw_wcount_async = 4;
526 nsw_wcount_async_max = nsw_wcount_async;
527 mtx_unlock(&pbuf_mtx);
530 * Initialize our zone. Right now I'm just guessing on the number
531 * we need based on the number of pages in the system. Each swblock
532 * can hold 32 pages, so this is probably overkill. This reservation
533 * is typically limited to around 32MB by default.
535 n = vm_cnt.v_page_count / 2;
536 if (maxswzone && n > maxswzone / sizeof(struct swblock))
537 n = maxswzone / sizeof(struct swblock);
539 swap_zone = uma_zcreate("SWAPMETA", sizeof(struct swblock), NULL, NULL,
540 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
541 if (swap_zone == NULL)
542 panic("failed to create swap_zone.");
544 if (uma_zone_reserve_kva(swap_zone, n))
547 * if the allocation failed, try a zone two thirds the
548 * size of the previous attempt.
553 printf("Swap zone entries reduced from %lu to %lu.\n", n2, n);
554 swap_maxpages = n * SWAP_META_PAGES;
555 swzone = n * sizeof(struct swblock);
559 * Initialize our meta-data hash table. The swapper does not need to
560 * be quite as efficient as the VM system, so we do not use an
561 * oversized hash table.
563 * n: size of hash table, must be power of 2
564 * swhash_mask: hash table index mask
566 for (n = 1; n < n2 / 8; n *= 2)
568 swhash = malloc(sizeof(struct swblock *) * n, M_VMPGDATA, M_WAITOK | M_ZERO);
570 mtx_init(&swhash_mtx, "swap_pager swhash", NULL, MTX_DEF);
574 swap_pager_alloc_init(void *handle, struct ucred *cred, vm_ooffset_t size,
580 if (!swap_reserve_by_cred(size, cred))
584 object = vm_object_allocate(OBJT_SWAP, OFF_TO_IDX(offset +
586 object->handle = handle;
589 object->charge = size;
591 object->un_pager.swp.swp_bcount = 0;
596 * SWAP_PAGER_ALLOC() - allocate a new OBJT_SWAP VM object and instantiate
597 * its metadata structures.
599 * This routine is called from the mmap and fork code to create a new
602 * This routine must ensure that no live duplicate is created for
603 * the named object request, which is protected against by
604 * holding the sw_alloc_sx lock in case handle != NULL.
607 swap_pager_alloc(void *handle, vm_ooffset_t size, vm_prot_t prot,
608 vm_ooffset_t offset, struct ucred *cred)
612 if (handle != NULL) {
614 * Reference existing named region or allocate new one. There
615 * should not be a race here against swp_pager_meta_build()
616 * as called from vm_page_remove() in regards to the lookup
619 sx_xlock(&sw_alloc_sx);
620 object = vm_pager_object_lookup(NOBJLIST(handle), handle);
621 if (object == NULL) {
622 object = swap_pager_alloc_init(handle, cred, size,
624 if (object != NULL) {
625 TAILQ_INSERT_TAIL(NOBJLIST(object->handle),
626 object, pager_object_list);
629 sx_xunlock(&sw_alloc_sx);
631 object = swap_pager_alloc_init(handle, cred, size, offset);
637 * SWAP_PAGER_DEALLOC() - remove swap metadata from object
639 * The swap backing for the object is destroyed. The code is
640 * designed such that we can reinstantiate it later, but this
641 * routine is typically called only when the entire object is
642 * about to be destroyed.
644 * The object must be locked.
647 swap_pager_dealloc(vm_object_t object)
650 VM_OBJECT_ASSERT_WLOCKED(object);
651 KASSERT((object->flags & OBJ_DEAD) != 0, ("dealloc of reachable obj"));
654 * Remove from list right away so lookups will fail if we block for
655 * pageout completion.
657 if (object->handle != NULL) {
658 VM_OBJECT_WUNLOCK(object);
659 sx_xlock(&sw_alloc_sx);
660 TAILQ_REMOVE(NOBJLIST(object->handle), object,
662 sx_xunlock(&sw_alloc_sx);
663 VM_OBJECT_WLOCK(object);
666 vm_object_pip_wait(object, "swpdea");
669 * Free all remaining metadata. We only bother to free it from
670 * the swap meta data. We do not attempt to free swapblk's still
671 * associated with vm_page_t's for this object. We do not care
672 * if paging is still in progress on some objects.
674 swp_pager_meta_free_all(object);
675 object->handle = NULL;
676 object->type = OBJT_DEAD;
679 /************************************************************************
680 * SWAP PAGER BITMAP ROUTINES *
681 ************************************************************************/
684 * SWP_PAGER_GETSWAPSPACE() - allocate raw swap space
686 * Allocate swap for the requested number of pages. The starting
687 * swap block number (a page index) is returned or SWAPBLK_NONE
688 * if the allocation failed.
690 * Also has the side effect of advising that somebody made a mistake
691 * when they configured swap and didn't configure enough.
693 * This routine may not sleep.
695 * We allocate in round-robin fashion from the configured devices.
698 swp_pager_getswapspace(int npages)
705 mtx_lock(&sw_dev_mtx);
707 for (i = 0; i < nswapdev; i++) {
709 sp = TAILQ_FIRST(&swtailq);
710 if (!(sp->sw_flags & SW_CLOSING)) {
711 blk = blist_alloc(sp->sw_blist, npages);
712 if (blk != SWAPBLK_NONE) {
714 sp->sw_used += npages;
715 swap_pager_avail -= npages;
717 swdevhd = TAILQ_NEXT(sp, sw_list);
721 sp = TAILQ_NEXT(sp, sw_list);
723 if (swap_pager_full != 2) {
724 printf("swap_pager_getswapspace(%d): failed\n", npages);
726 swap_pager_almost_full = 1;
730 mtx_unlock(&sw_dev_mtx);
735 swp_pager_isondev(daddr_t blk, struct swdevt *sp)
738 return (blk >= sp->sw_first && blk < sp->sw_end);
742 swp_pager_strategy(struct buf *bp)
746 mtx_lock(&sw_dev_mtx);
747 TAILQ_FOREACH(sp, &swtailq, sw_list) {
748 if (bp->b_blkno >= sp->sw_first && bp->b_blkno < sp->sw_end) {
749 mtx_unlock(&sw_dev_mtx);
750 if ((sp->sw_flags & SW_UNMAPPED) != 0 &&
751 unmapped_buf_allowed) {
752 bp->b_data = unmapped_buf;
755 pmap_qenter((vm_offset_t)bp->b_data,
756 &bp->b_pages[0], bp->b_bcount / PAGE_SIZE);
758 sp->sw_strategy(bp, sp);
762 panic("Swapdev not found");
767 * SWP_PAGER_FREESWAPSPACE() - free raw swap space
769 * This routine returns the specified swap blocks back to the bitmap.
771 * This routine may not sleep.
774 swp_pager_freeswapspace(daddr_t blk, int npages)
778 mtx_lock(&sw_dev_mtx);
779 TAILQ_FOREACH(sp, &swtailq, sw_list) {
780 if (blk >= sp->sw_first && blk < sp->sw_end) {
781 sp->sw_used -= npages;
783 * If we are attempting to stop swapping on
784 * this device, we don't want to mark any
785 * blocks free lest they be reused.
787 if ((sp->sw_flags & SW_CLOSING) == 0) {
788 blist_free(sp->sw_blist, blk - sp->sw_first,
790 swap_pager_avail += npages;
793 mtx_unlock(&sw_dev_mtx);
797 panic("Swapdev not found");
801 * SWAP_PAGER_FREESPACE() - frees swap blocks associated with a page
802 * range within an object.
804 * This is a globally accessible routine.
806 * This routine removes swapblk assignments from swap metadata.
808 * The external callers of this routine typically have already destroyed
809 * or renamed vm_page_t's associated with this range in the object so
812 * The object must be locked.
815 swap_pager_freespace(vm_object_t object, vm_pindex_t start, vm_size_t size)
818 swp_pager_meta_free(object, start, size);
822 * SWAP_PAGER_RESERVE() - reserve swap blocks in object
824 * Assigns swap blocks to the specified range within the object. The
825 * swap blocks are not zeroed. Any previous swap assignment is destroyed.
827 * Returns 0 on success, -1 on failure.
830 swap_pager_reserve(vm_object_t object, vm_pindex_t start, vm_size_t size)
833 daddr_t blk = SWAPBLK_NONE;
834 vm_pindex_t beg = start; /* save start index */
836 VM_OBJECT_WLOCK(object);
840 while ((blk = swp_pager_getswapspace(n)) == SWAPBLK_NONE) {
843 swp_pager_meta_free(object, beg, start - beg);
844 VM_OBJECT_WUNLOCK(object);
849 swp_pager_meta_build(object, start, blk);
855 swp_pager_meta_free(object, start, n);
856 VM_OBJECT_WUNLOCK(object);
861 * SWAP_PAGER_COPY() - copy blocks from source pager to destination pager
862 * and destroy the source.
864 * Copy any valid swapblks from the source to the destination. In
865 * cases where both the source and destination have a valid swapblk,
866 * we keep the destination's.
868 * This routine is allowed to sleep. It may sleep allocating metadata
869 * indirectly through swp_pager_meta_build() or if paging is still in
870 * progress on the source.
872 * The source object contains no vm_page_t's (which is just as well)
874 * The source object is of type OBJT_SWAP.
876 * The source and destination objects must be locked.
877 * Both object locks may temporarily be released.
880 swap_pager_copy(vm_object_t srcobject, vm_object_t dstobject,
881 vm_pindex_t offset, int destroysource)
885 VM_OBJECT_ASSERT_WLOCKED(srcobject);
886 VM_OBJECT_ASSERT_WLOCKED(dstobject);
889 * If destroysource is set, we remove the source object from the
890 * swap_pager internal queue now.
892 if (destroysource && srcobject->handle != NULL) {
893 vm_object_pip_add(srcobject, 1);
894 VM_OBJECT_WUNLOCK(srcobject);
895 vm_object_pip_add(dstobject, 1);
896 VM_OBJECT_WUNLOCK(dstobject);
897 sx_xlock(&sw_alloc_sx);
898 TAILQ_REMOVE(NOBJLIST(srcobject->handle), srcobject,
900 sx_xunlock(&sw_alloc_sx);
901 VM_OBJECT_WLOCK(dstobject);
902 vm_object_pip_wakeup(dstobject);
903 VM_OBJECT_WLOCK(srcobject);
904 vm_object_pip_wakeup(srcobject);
908 * transfer source to destination.
910 for (i = 0; i < dstobject->size; ++i) {
914 * Locate (without changing) the swapblk on the destination,
915 * unless it is invalid in which case free it silently, or
916 * if the destination is a resident page, in which case the
917 * source is thrown away.
919 dstaddr = swp_pager_meta_ctl(dstobject, i, 0);
921 if (dstaddr == SWAPBLK_NONE) {
923 * Destination has no swapblk and is not resident,
928 srcaddr = swp_pager_meta_ctl(
934 if (srcaddr != SWAPBLK_NONE) {
936 * swp_pager_meta_build() can sleep.
938 vm_object_pip_add(srcobject, 1);
939 VM_OBJECT_WUNLOCK(srcobject);
940 vm_object_pip_add(dstobject, 1);
941 swp_pager_meta_build(dstobject, i, srcaddr);
942 vm_object_pip_wakeup(dstobject);
943 VM_OBJECT_WLOCK(srcobject);
944 vm_object_pip_wakeup(srcobject);
948 * Destination has valid swapblk or it is represented
949 * by a resident page. We destroy the sourceblock.
952 swp_pager_meta_ctl(srcobject, i + offset, SWM_FREE);
957 * Free left over swap blocks in source.
959 * We have to revert the type to OBJT_DEFAULT so we do not accidentally
960 * double-remove the object from the swap queues.
963 swp_pager_meta_free_all(srcobject);
965 * Reverting the type is not necessary, the caller is going
966 * to destroy srcobject directly, but I'm doing it here
967 * for consistency since we've removed the object from its
970 srcobject->type = OBJT_DEFAULT;
975 * SWAP_PAGER_HASPAGE() - determine if we have good backing store for
976 * the requested page.
978 * We determine whether good backing store exists for the requested
979 * page and return TRUE if it does, FALSE if it doesn't.
981 * If TRUE, we also try to determine how much valid, contiguous backing
982 * store exists before and after the requested page.
985 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before,
991 VM_OBJECT_ASSERT_LOCKED(object);
994 * do we have good backing store at the requested index ?
996 blk0 = swp_pager_meta_ctl(object, pindex, 0);
997 if (blk0 == SWAPBLK_NONE) {
1006 * find backwards-looking contiguous good backing store
1008 if (before != NULL) {
1009 for (i = 1; i < SWB_NPAGES; i++) {
1012 blk = swp_pager_meta_ctl(object, pindex - i, 0);
1013 if (blk != blk0 - i)
1020 * find forward-looking contiguous good backing store
1022 if (after != NULL) {
1023 for (i = 1; i < SWB_NPAGES; i++) {
1024 blk = swp_pager_meta_ctl(object, pindex + i, 0);
1025 if (blk != blk0 + i)
1034 * SWAP_PAGER_PAGE_UNSWAPPED() - remove swap backing store related to page
1036 * This removes any associated swap backing store, whether valid or
1037 * not, from the page.
1039 * This routine is typically called when a page is made dirty, at
1040 * which point any associated swap can be freed. MADV_FREE also
1041 * calls us in a special-case situation
1043 * NOTE!!! If the page is clean and the swap was valid, the caller
1044 * should make the page dirty before calling this routine. This routine
1045 * does NOT change the m->dirty status of the page. Also: MADV_FREE
1048 * This routine may not sleep.
1050 * The object containing the page must be locked.
1053 swap_pager_unswapped(vm_page_t m)
1056 swp_pager_meta_ctl(m->object, m->pindex, SWM_FREE);
1060 * swap_pager_getpages() - bring pages in from swap
1062 * Attempt to page in the pages in array "m" of length "count". The caller
1063 * may optionally specify that additional pages preceding and succeeding
1064 * the specified range be paged in. The number of such pages is returned
1065 * in the "rbehind" and "rahead" parameters, and they will be in the
1066 * inactive queue upon return.
1068 * The pages in "m" must be busied and will remain busied upon return.
1071 swap_pager_getpages(vm_object_t object, vm_page_t *m, int count, int *rbehind,
1075 vm_page_t mpred, msucc, p;
1078 int i, j, maxahead, maxbehind, reqcount, shift;
1082 VM_OBJECT_WUNLOCK(object);
1083 bp = getpbuf(&nsw_rcount);
1084 VM_OBJECT_WLOCK(object);
1086 if (!swap_pager_haspage(object, m[0]->pindex, &maxbehind, &maxahead)) {
1087 relpbuf(bp, &nsw_rcount);
1088 return (VM_PAGER_FAIL);
1092 * Clip the readahead and readbehind ranges to exclude resident pages.
1094 if (rahead != NULL) {
1095 KASSERT(reqcount - 1 <= maxahead,
1096 ("page count %d extends beyond swap block", reqcount));
1097 *rahead = imin(*rahead, maxahead - (reqcount - 1));
1098 pindex = m[reqcount - 1]->pindex;
1099 msucc = TAILQ_NEXT(m[reqcount - 1], listq);
1100 if (msucc != NULL && msucc->pindex - pindex - 1 < *rahead)
1101 *rahead = msucc->pindex - pindex - 1;
1103 if (rbehind != NULL) {
1104 *rbehind = imin(*rbehind, maxbehind);
1105 pindex = m[0]->pindex;
1106 mpred = TAILQ_PREV(m[0], pglist, listq);
1107 if (mpred != NULL && pindex - mpred->pindex - 1 < *rbehind)
1108 *rbehind = pindex - mpred->pindex - 1;
1112 * Allocate readahead and readbehind pages.
1114 shift = rbehind != NULL ? *rbehind : 0;
1116 for (i = 1; i <= shift; i++) {
1117 p = vm_page_alloc(object, m[0]->pindex - i,
1120 /* Shift allocated pages to the left. */
1121 for (j = 0; j < i - 1; j++)
1123 bp->b_pages[j + shift - i + 1];
1126 bp->b_pages[shift - i] = p;
1131 for (i = 0; i < reqcount; i++)
1132 bp->b_pages[i + shift] = m[i];
1133 if (rahead != NULL) {
1134 for (i = 0; i < *rahead; i++) {
1135 p = vm_page_alloc(object,
1136 m[reqcount - 1]->pindex + i + 1, VM_ALLOC_NORMAL);
1139 bp->b_pages[shift + reqcount + i] = p;
1143 if (rbehind != NULL)
1148 vm_object_pip_add(object, count);
1150 for (i = 0; i < count; i++)
1151 bp->b_pages[i]->oflags |= VPO_SWAPINPROG;
1153 pindex = bp->b_pages[0]->pindex;
1154 blk = swp_pager_meta_ctl(object, pindex, 0);
1155 KASSERT(blk != SWAPBLK_NONE,
1156 ("no swap blocking containing %p(%jx)", object, (uintmax_t)pindex));
1158 VM_OBJECT_WUNLOCK(object);
1160 bp->b_flags |= B_PAGING;
1161 bp->b_iocmd = BIO_READ;
1162 bp->b_iodone = swp_pager_async_iodone;
1163 bp->b_rcred = crhold(thread0.td_ucred);
1164 bp->b_wcred = crhold(thread0.td_ucred);
1166 bp->b_bcount = PAGE_SIZE * count;
1167 bp->b_bufsize = PAGE_SIZE * count;
1168 bp->b_npages = count;
1169 bp->b_pgbefore = rbehind != NULL ? *rbehind : 0;
1170 bp->b_pgafter = rahead != NULL ? *rahead : 0;
1172 PCPU_INC(cnt.v_swapin);
1173 PCPU_ADD(cnt.v_swappgsin, count);
1176 * perform the I/O. NOTE!!! bp cannot be considered valid after
1177 * this point because we automatically release it on completion.
1178 * Instead, we look at the one page we are interested in which we
1179 * still hold a lock on even through the I/O completion.
1181 * The other pages in our m[] array are also released on completion,
1182 * so we cannot assume they are valid anymore either.
1184 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1187 swp_pager_strategy(bp);
1190 * Wait for the pages we want to complete. VPO_SWAPINPROG is always
1191 * cleared on completion. If an I/O error occurs, SWAPBLK_NONE
1192 * is set in the metadata for each page in the request.
1194 VM_OBJECT_WLOCK(object);
1195 while ((m[0]->oflags & VPO_SWAPINPROG) != 0) {
1196 m[0]->oflags |= VPO_SWAPSLEEP;
1197 PCPU_INC(cnt.v_intrans);
1198 if (VM_OBJECT_SLEEP(object, &object->paging_in_progress, PSWP,
1199 "swread", hz * 20)) {
1201 "swap_pager: indefinite wait buffer: bufobj: %p, blkno: %jd, size: %ld\n",
1202 bp->b_bufobj, (intmax_t)bp->b_blkno, bp->b_bcount);
1207 * If we had an unrecoverable read error pages will not be valid.
1209 for (i = 0; i < reqcount; i++)
1210 if (m[i]->valid != VM_PAGE_BITS_ALL)
1211 return (VM_PAGER_ERROR);
1213 return (VM_PAGER_OK);
1216 * A final note: in a low swap situation, we cannot deallocate swap
1217 * and mark a page dirty here because the caller is likely to mark
1218 * the page clean when we return, causing the page to possibly revert
1219 * to all-zero's later.
1224 * swap_pager_getpages_async():
1226 * Right now this is emulation of asynchronous operation on top of
1227 * swap_pager_getpages().
1230 swap_pager_getpages_async(vm_object_t object, vm_page_t *m, int count,
1231 int *rbehind, int *rahead, pgo_getpages_iodone_t iodone, void *arg)
1235 r = swap_pager_getpages(object, m, count, rbehind, rahead);
1236 VM_OBJECT_WUNLOCK(object);
1241 case VM_PAGER_ERROR:
1248 panic("unhandled swap_pager_getpages() error %d", r);
1250 (iodone)(arg, m, count, error);
1251 VM_OBJECT_WLOCK(object);
1257 * swap_pager_putpages:
1259 * Assign swap (if necessary) and initiate I/O on the specified pages.
1261 * We support both OBJT_DEFAULT and OBJT_SWAP objects. DEFAULT objects
1262 * are automatically converted to SWAP objects.
1264 * In a low memory situation we may block in VOP_STRATEGY(), but the new
1265 * vm_page reservation system coupled with properly written VFS devices
1266 * should ensure that no low-memory deadlock occurs. This is an area
1269 * The parent has N vm_object_pip_add() references prior to
1270 * calling us and will remove references for rtvals[] that are
1271 * not set to VM_PAGER_PEND. We need to remove the rest on I/O
1274 * The parent has soft-busy'd the pages it passes us and will unbusy
1275 * those whos rtvals[] entry is not set to VM_PAGER_PEND on return.
1276 * We need to unbusy the rest on I/O completion.
1279 swap_pager_putpages(vm_object_t object, vm_page_t *m, int count,
1280 int flags, int *rtvals)
1285 if (count && m[0]->object != object) {
1286 panic("swap_pager_putpages: object mismatch %p/%p",
1295 * Turn object into OBJT_SWAP
1296 * check for bogus sysops
1297 * force sync if not pageout process
1299 if (object->type != OBJT_SWAP)
1300 swp_pager_meta_build(object, 0, SWAPBLK_NONE);
1301 VM_OBJECT_WUNLOCK(object);
1304 if (curproc != pageproc)
1307 sync = (flags & VM_PAGER_PUT_SYNC) != 0;
1312 * Assign swap blocks and issue I/O. We reallocate swap on the fly.
1313 * The page is left dirty until the pageout operation completes
1316 for (i = 0; i < count; i += n) {
1322 * Maximum I/O size is limited by a number of factors.
1324 n = min(BLIST_MAX_ALLOC, count - i);
1325 n = min(n, nsw_cluster_max);
1328 * Get biggest block of swap we can. If we fail, fall
1329 * back and try to allocate a smaller block. Don't go
1330 * overboard trying to allocate space if it would overly
1334 (blk = swp_pager_getswapspace(n)) == SWAPBLK_NONE &&
1339 if (blk == SWAPBLK_NONE) {
1340 for (j = 0; j < n; ++j)
1341 rtvals[i+j] = VM_PAGER_FAIL;
1346 * All I/O parameters have been satisfied, build the I/O
1347 * request and assign the swap space.
1350 bp = getpbuf(&nsw_wcount_sync);
1352 bp = getpbuf(&nsw_wcount_async);
1353 bp->b_flags = B_ASYNC;
1355 bp->b_flags |= B_PAGING;
1356 bp->b_iocmd = BIO_WRITE;
1358 bp->b_rcred = crhold(thread0.td_ucred);
1359 bp->b_wcred = crhold(thread0.td_ucred);
1360 bp->b_bcount = PAGE_SIZE * n;
1361 bp->b_bufsize = PAGE_SIZE * n;
1364 VM_OBJECT_WLOCK(object);
1365 for (j = 0; j < n; ++j) {
1366 vm_page_t mreq = m[i+j];
1368 swp_pager_meta_build(
1373 MPASS(mreq->dirty == VM_PAGE_BITS_ALL);
1374 mreq->oflags |= VPO_SWAPINPROG;
1375 bp->b_pages[j] = mreq;
1377 VM_OBJECT_WUNLOCK(object);
1380 * Must set dirty range for NFS to work.
1383 bp->b_dirtyend = bp->b_bcount;
1385 PCPU_INC(cnt.v_swapout);
1386 PCPU_ADD(cnt.v_swappgsout, bp->b_npages);
1389 * We unconditionally set rtvals[] to VM_PAGER_PEND so that we
1390 * can call the async completion routine at the end of a
1391 * synchronous I/O operation. Otherwise, our caller would
1392 * perform duplicate unbusy and wakeup operations on the page
1393 * and object, respectively.
1395 for (j = 0; j < n; j++)
1396 rtvals[i + j] = VM_PAGER_PEND;
1401 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1403 if (sync == FALSE) {
1404 bp->b_iodone = swp_pager_async_iodone;
1406 swp_pager_strategy(bp);
1413 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1415 bp->b_iodone = bdone;
1416 swp_pager_strategy(bp);
1419 * Wait for the sync I/O to complete.
1421 bwait(bp, PVM, "swwrt");
1424 * Now that we are through with the bp, we can call the
1425 * normal async completion, which frees everything up.
1427 swp_pager_async_iodone(bp);
1429 VM_OBJECT_WLOCK(object);
1433 * swp_pager_async_iodone:
1435 * Completion routine for asynchronous reads and writes from/to swap.
1436 * Also called manually by synchronous code to finish up a bp.
1438 * This routine may not sleep.
1441 swp_pager_async_iodone(struct buf *bp)
1444 vm_object_t object = NULL;
1449 if (bp->b_ioflags & BIO_ERROR) {
1451 "swap_pager: I/O error - %s failed; blkno %ld,"
1452 "size %ld, error %d\n",
1453 ((bp->b_iocmd == BIO_READ) ? "pagein" : "pageout"),
1461 * remove the mapping for kernel virtual
1464 pmap_qremove((vm_offset_t)bp->b_data, bp->b_npages);
1466 bp->b_data = bp->b_kvabase;
1469 object = bp->b_pages[0]->object;
1470 VM_OBJECT_WLOCK(object);
1474 * cleanup pages. If an error occurs writing to swap, we are in
1475 * very serious trouble. If it happens to be a disk error, though,
1476 * we may be able to recover by reassigning the swap later on. So
1477 * in this case we remove the m->swapblk assignment for the page
1478 * but do not free it in the rlist. The errornous block(s) are thus
1479 * never reallocated as swap. Redirty the page and continue.
1481 for (i = 0; i < bp->b_npages; ++i) {
1482 vm_page_t m = bp->b_pages[i];
1484 m->oflags &= ~VPO_SWAPINPROG;
1485 if (m->oflags & VPO_SWAPSLEEP) {
1486 m->oflags &= ~VPO_SWAPSLEEP;
1487 wakeup(&object->paging_in_progress);
1490 if (bp->b_ioflags & BIO_ERROR) {
1492 * If an error occurs I'd love to throw the swapblk
1493 * away without freeing it back to swapspace, so it
1494 * can never be used again. But I can't from an
1497 if (bp->b_iocmd == BIO_READ) {
1499 * NOTE: for reads, m->dirty will probably
1500 * be overridden by the original caller of
1501 * getpages so don't play cute tricks here.
1506 * If a write error occurs, reactivate page
1507 * so it doesn't clog the inactive list,
1508 * then finish the I/O.
1512 vm_page_activate(m);
1516 } else if (bp->b_iocmd == BIO_READ) {
1518 * NOTE: for reads, m->dirty will probably be
1519 * overridden by the original caller of getpages so
1520 * we cannot set them in order to free the underlying
1521 * swap in a low-swap situation. I don't think we'd
1522 * want to do that anyway, but it was an optimization
1523 * that existed in the old swapper for a time before
1524 * it got ripped out due to precisely this problem.
1526 KASSERT(!pmap_page_is_mapped(m),
1527 ("swp_pager_async_iodone: page %p is mapped", m));
1528 KASSERT(m->dirty == 0,
1529 ("swp_pager_async_iodone: page %p is dirty", m));
1531 m->valid = VM_PAGE_BITS_ALL;
1532 if (i < bp->b_pgbefore ||
1533 i >= bp->b_npages - bp->b_pgafter)
1534 vm_page_readahead_finish(m);
1537 * For write success, clear the dirty
1538 * status, then finish the I/O ( which decrements the
1539 * busy count and possibly wakes waiter's up ).
1540 * A page is only written to swap after a period of
1541 * inactivity. Therefore, we do not expect it to be
1544 KASSERT(!pmap_page_is_write_mapped(m),
1545 ("swp_pager_async_iodone: page %p is not write"
1549 vm_page_deactivate_noreuse(m);
1556 * adjust pip. NOTE: the original parent may still have its own
1557 * pip refs on the object.
1559 if (object != NULL) {
1560 vm_object_pip_wakeupn(object, bp->b_npages);
1561 VM_OBJECT_WUNLOCK(object);
1565 * swapdev_strategy() manually sets b_vp and b_bufobj before calling
1566 * bstrategy(). Set them back to NULL now we're done with it, or we'll
1567 * trigger a KASSERT in relpbuf().
1571 bp->b_bufobj = NULL;
1574 * release the physical I/O buffer
1578 ((bp->b_iocmd == BIO_READ) ? &nsw_rcount :
1579 ((bp->b_flags & B_ASYNC) ?
1588 * swap_pager_isswapped:
1590 * Return 1 if at least one page in the given object is paged
1591 * out to the given swap device.
1593 * This routine may not sleep.
1596 swap_pager_isswapped(vm_object_t object, struct swdevt *sp)
1602 VM_OBJECT_ASSERT_WLOCKED(object);
1603 if (object->type != OBJT_SWAP)
1606 mtx_lock(&swhash_mtx);
1607 for (bcount = 0; bcount < object->un_pager.swp.swp_bcount; bcount++) {
1608 struct swblock *swap;
1610 if ((swap = *swp_pager_hash(object, index)) != NULL) {
1611 for (i = 0; i < SWAP_META_PAGES; ++i) {
1612 if (swp_pager_isondev(swap->swb_pages[i], sp)) {
1613 mtx_unlock(&swhash_mtx);
1618 index += SWAP_META_PAGES;
1620 mtx_unlock(&swhash_mtx);
1625 * SWP_PAGER_FORCE_PAGEIN() - force a swap block to be paged in
1627 * This routine dissociates the page at the given index within an object
1628 * from its backing store, paging it in if it does not reside in memory.
1629 * If the page is paged in, it is marked dirty and placed in the laundry
1630 * queue. The page is marked dirty because it no longer has backing
1631 * store. It is placed in the laundry queue because it has not been
1632 * accessed recently. Otherwise, it would already reside in memory.
1634 * We also attempt to swap in all other pages in the swap block.
1635 * However, we only guarantee that the one at the specified index is
1638 * XXX - The code to page the whole block in doesn't work, so we
1639 * revert to the one-by-one behavior for now. Sigh.
1642 swp_pager_force_pagein(vm_object_t object, vm_pindex_t pindex)
1646 vm_object_pip_add(object, 1);
1647 m = vm_page_grab(object, pindex, VM_ALLOC_NORMAL);
1648 if (m->valid == VM_PAGE_BITS_ALL) {
1649 vm_object_pip_wakeup(object);
1652 vm_page_activate(m);
1655 vm_pager_page_unswapped(m);
1659 if (swap_pager_getpages(object, &m, 1, NULL, NULL) != VM_PAGER_OK)
1660 panic("swap_pager_force_pagein: read from swap failed");/*XXX*/
1661 vm_object_pip_wakeup(object);
1667 vm_pager_page_unswapped(m);
1671 * swap_pager_swapoff:
1673 * Page in all of the pages that have been paged out to the
1674 * given device. The corresponding blocks in the bitmap must be
1675 * marked as allocated and the device must be flagged SW_CLOSING.
1676 * There may be no processes swapped out to the device.
1678 * This routine may block.
1681 swap_pager_swapoff(struct swdevt *sp)
1683 struct swblock *swap;
1684 vm_object_t locked_obj, object;
1688 sx_assert(&swdev_syscall_lock, SA_XLOCKED);
1693 mtx_lock(&swhash_mtx);
1694 for (i = 0; i <= swhash_mask; i++) { /* '<=' is correct here */
1696 for (swap = swhash[i]; swap != NULL; swap = swap->swb_hnext) {
1697 object = swap->swb_object;
1698 pindex = swap->swb_index;
1699 for (j = 0; j < SWAP_META_PAGES; ++j) {
1700 if (!swp_pager_isondev(swap->swb_pages[j], sp))
1702 if (locked_obj != object) {
1703 if (locked_obj != NULL)
1704 VM_OBJECT_WUNLOCK(locked_obj);
1705 locked_obj = object;
1706 if (!VM_OBJECT_TRYWLOCK(object)) {
1707 mtx_unlock(&swhash_mtx);
1708 /* Depends on type-stability. */
1709 VM_OBJECT_WLOCK(object);
1710 mtx_lock(&swhash_mtx);
1714 MPASS(locked_obj == object);
1715 mtx_unlock(&swhash_mtx);
1716 swp_pager_force_pagein(object, pindex + j);
1717 mtx_lock(&swhash_mtx);
1722 mtx_unlock(&swhash_mtx);
1723 if (locked_obj != NULL) {
1724 VM_OBJECT_WUNLOCK(locked_obj);
1729 * Objects may be locked or paging to the device being
1730 * removed, so we will miss their pages and need to
1731 * make another pass. We have marked this device as
1732 * SW_CLOSING, so the activity should finish soon.
1735 if (retries > 100) {
1736 panic("swapoff: failed to locate %d swap blocks",
1739 pause("swpoff", hz / 20);
1744 /************************************************************************
1746 ************************************************************************
1748 * These routines manipulate the swap metadata stored in the
1751 * Swap metadata is implemented with a global hash and not directly
1752 * linked into the object. Instead the object simply contains
1753 * appropriate tracking counters.
1757 * SWP_PAGER_META_BUILD() - add swap block to swap meta data for object
1759 * We first convert the object to a swap object if it is a default
1762 * The specified swapblk is added to the object's swap metadata. If
1763 * the swapblk is not valid, it is freed instead. Any previously
1764 * assigned swapblk is freed.
1767 swp_pager_meta_build(vm_object_t object, vm_pindex_t pindex, daddr_t swapblk)
1769 static volatile int exhausted;
1770 struct swblock *swap;
1771 struct swblock **pswap;
1774 VM_OBJECT_ASSERT_WLOCKED(object);
1776 * Convert default object to swap object if necessary
1778 if (object->type != OBJT_SWAP) {
1779 object->type = OBJT_SWAP;
1780 object->un_pager.swp.swp_bcount = 0;
1781 KASSERT(object->handle == NULL, ("default pager with handle"));
1785 * Locate hash entry. If not found create, but if we aren't adding
1786 * anything just return. If we run out of space in the map we wait
1787 * and, since the hash table may have changed, retry.
1790 mtx_lock(&swhash_mtx);
1791 pswap = swp_pager_hash(object, pindex);
1793 if ((swap = *pswap) == NULL) {
1796 if (swapblk == SWAPBLK_NONE)
1799 swap = *pswap = uma_zalloc(swap_zone, M_NOWAIT |
1800 (curproc == pageproc ? M_USE_RESERVE : 0));
1802 mtx_unlock(&swhash_mtx);
1803 VM_OBJECT_WUNLOCK(object);
1804 if (uma_zone_exhausted(swap_zone)) {
1805 if (atomic_cmpset_int(&exhausted, 0, 1))
1806 printf("swap zone exhausted, "
1807 "increase kern.maxswzone\n");
1808 vm_pageout_oom(VM_OOM_SWAPZ);
1809 pause("swzonex", 10);
1812 VM_OBJECT_WLOCK(object);
1816 if (atomic_cmpset_int(&exhausted, 1, 0))
1817 printf("swap zone ok\n");
1819 swap->swb_hnext = NULL;
1820 swap->swb_object = object;
1821 swap->swb_index = pindex & ~(vm_pindex_t)SWAP_META_MASK;
1822 swap->swb_count = 0;
1824 ++object->un_pager.swp.swp_bcount;
1826 for (i = 0; i < SWAP_META_PAGES; ++i)
1827 swap->swb_pages[i] = SWAPBLK_NONE;
1831 * Delete prior contents of metadata
1833 idx = pindex & SWAP_META_MASK;
1835 if (swap->swb_pages[idx] != SWAPBLK_NONE) {
1836 swp_pager_freeswapspace(swap->swb_pages[idx], 1);
1841 * Enter block into metadata
1843 swap->swb_pages[idx] = swapblk;
1844 if (swapblk != SWAPBLK_NONE)
1847 mtx_unlock(&swhash_mtx);
1851 * SWP_PAGER_META_FREE() - free a range of blocks in the object's swap metadata
1853 * The requested range of blocks is freed, with any associated swap
1854 * returned to the swap bitmap.
1856 * This routine will free swap metadata structures as they are cleaned
1857 * out. This routine does *NOT* operate on swap metadata associated
1858 * with resident pages.
1861 swp_pager_meta_free(vm_object_t object, vm_pindex_t index, vm_pindex_t count)
1863 struct swblock **pswap, *swap;
1868 VM_OBJECT_ASSERT_LOCKED(object);
1869 if (object->type != OBJT_SWAP || count == 0)
1872 mtx_lock(&swhash_mtx);
1873 for (c = 0; c < count;) {
1874 pswap = swp_pager_hash(object, index);
1875 sidx = index & SWAP_META_MASK;
1876 n = SWAP_META_PAGES - sidx;
1878 if ((swap = *pswap) == NULL) {
1882 for (; c < count && sidx < SWAP_META_PAGES; ++c, ++sidx) {
1883 if ((v = swap->swb_pages[sidx]) == SWAPBLK_NONE)
1885 swp_pager_freeswapspace(v, 1);
1886 swap->swb_pages[sidx] = SWAPBLK_NONE;
1887 if (--swap->swb_count == 0) {
1888 *pswap = swap->swb_hnext;
1889 uma_zfree(swap_zone, swap);
1890 --object->un_pager.swp.swp_bcount;
1891 c += SWAP_META_PAGES - sidx;
1896 mtx_unlock(&swhash_mtx);
1900 * SWP_PAGER_META_FREE_ALL() - destroy all swap metadata associated with object
1902 * This routine locates and destroys all swap metadata associated with
1906 swp_pager_meta_free_all(vm_object_t object)
1908 struct swblock **pswap, *swap;
1913 VM_OBJECT_ASSERT_WLOCKED(object);
1914 if (object->type != OBJT_SWAP)
1918 while (object->un_pager.swp.swp_bcount != 0) {
1919 mtx_lock(&swhash_mtx);
1920 pswap = swp_pager_hash(object, index);
1921 if ((swap = *pswap) != NULL) {
1922 for (i = 0; i < SWAP_META_PAGES; ++i) {
1923 v = swap->swb_pages[i];
1924 if (v != SWAPBLK_NONE) {
1926 swp_pager_freeswapspace(v, 1);
1929 if (swap->swb_count != 0)
1931 "swap_pager_meta_free_all: swb_count != 0");
1932 *pswap = swap->swb_hnext;
1933 uma_zfree(swap_zone, swap);
1934 --object->un_pager.swp.swp_bcount;
1936 mtx_unlock(&swhash_mtx);
1937 index += SWAP_META_PAGES;
1942 * SWP_PAGER_METACTL() - misc control of swap and vm_page_t meta data.
1944 * This routine is capable of looking up, popping, or freeing
1945 * swapblk assignments in the swap meta data or in the vm_page_t.
1946 * The routine typically returns the swapblk being looked-up, or popped,
1947 * or SWAPBLK_NONE if the block was freed, or SWAPBLK_NONE if the block
1948 * was invalid. This routine will automatically free any invalid
1949 * meta-data swapblks.
1951 * It is not possible to store invalid swapblks in the swap meta data
1952 * (other then a literal 'SWAPBLK_NONE'), so we don't bother checking.
1954 * When acting on a busy resident page and paging is in progress, we
1955 * have to wait until paging is complete but otherwise can act on the
1958 * SWM_FREE remove and free swap block from metadata
1959 * SWM_POP remove from meta data but do not free.. pop it out
1962 swp_pager_meta_ctl(vm_object_t object, vm_pindex_t pindex, int flags)
1964 struct swblock **pswap;
1965 struct swblock *swap;
1969 VM_OBJECT_ASSERT_LOCKED(object);
1971 * The meta data only exists of the object is OBJT_SWAP
1972 * and even then might not be allocated yet.
1974 if (object->type != OBJT_SWAP)
1975 return (SWAPBLK_NONE);
1978 mtx_lock(&swhash_mtx);
1979 pswap = swp_pager_hash(object, pindex);
1981 if ((swap = *pswap) != NULL) {
1982 idx = pindex & SWAP_META_MASK;
1983 r1 = swap->swb_pages[idx];
1985 if (r1 != SWAPBLK_NONE) {
1986 if (flags & SWM_FREE) {
1987 swp_pager_freeswapspace(r1, 1);
1990 if (flags & (SWM_FREE|SWM_POP)) {
1991 swap->swb_pages[idx] = SWAPBLK_NONE;
1992 if (--swap->swb_count == 0) {
1993 *pswap = swap->swb_hnext;
1994 uma_zfree(swap_zone, swap);
1995 --object->un_pager.swp.swp_bcount;
2000 mtx_unlock(&swhash_mtx);
2005 * Returns the least page index which is greater than or equal to the
2006 * parameter pindex and for which there is a swap block allocated.
2007 * Returns object's size if the object's type is not swap or if there
2008 * are no allocated swap blocks for the object after the requested
2012 swap_pager_find_least(vm_object_t object, vm_pindex_t pindex)
2014 struct swblock **pswap, *swap;
2015 vm_pindex_t i, j, lim;
2018 VM_OBJECT_ASSERT_LOCKED(object);
2019 if (object->type != OBJT_SWAP || object->un_pager.swp.swp_bcount == 0)
2020 return (object->size);
2022 mtx_lock(&swhash_mtx);
2023 for (j = pindex; j < object->size; j = lim) {
2024 pswap = swp_pager_hash(object, j);
2025 lim = rounddown2(j + SWAP_META_PAGES, SWAP_META_PAGES);
2026 if (lim > object->size)
2028 if ((swap = *pswap) != NULL) {
2029 for (idx = j & SWAP_META_MASK, i = j; i < lim;
2031 if (swap->swb_pages[idx] != SWAPBLK_NONE)
2038 mtx_unlock(&swhash_mtx);
2043 * System call swapon(name) enables swapping on device name,
2044 * which must be in the swdevsw. Return EBUSY
2045 * if already swapping on this device.
2047 #ifndef _SYS_SYSPROTO_H_
2048 struct swapon_args {
2058 sys_swapon(struct thread *td, struct swapon_args *uap)
2062 struct nameidata nd;
2065 error = priv_check(td, PRIV_SWAPON);
2069 sx_xlock(&swdev_syscall_lock);
2072 * Swap metadata may not fit in the KVM if we have physical
2075 if (swap_zone == NULL) {
2080 NDINIT(&nd, LOOKUP, ISOPEN | FOLLOW | AUDITVNODE1, UIO_USERSPACE,
2086 NDFREE(&nd, NDF_ONLY_PNBUF);
2089 if (vn_isdisk(vp, &error)) {
2090 error = swapongeom(vp);
2091 } else if (vp->v_type == VREG &&
2092 (vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
2093 (error = VOP_GETATTR(vp, &attr, td->td_ucred)) == 0) {
2095 * Allow direct swapping to NFS regular files in the same
2096 * way that nfs_mountroot() sets up diskless swapping.
2098 error = swaponvp(td, vp, attr.va_size / DEV_BSIZE);
2104 sx_xunlock(&swdev_syscall_lock);
2109 * Check that the total amount of swap currently configured does not
2110 * exceed half the theoretical maximum. If it does, print a warning
2111 * message and return -1; otherwise, return 0.
2114 swapon_check_swzone(unsigned long npages)
2116 unsigned long maxpages;
2118 /* absolute maximum we can handle assuming 100% efficiency */
2119 maxpages = uma_zone_get_max(swap_zone) * SWAP_META_PAGES;
2121 /* recommend using no more than half that amount */
2122 if (npages > maxpages / 2) {
2123 printf("warning: total configured swap (%lu pages) "
2124 "exceeds maximum recommended amount (%lu pages).\n",
2125 npages, maxpages / 2);
2126 printf("warning: increase kern.maxswzone "
2127 "or reduce amount of swap.\n");
2134 swaponsomething(struct vnode *vp, void *id, u_long nblks,
2135 sw_strategy_t *strategy, sw_close_t *close, dev_t dev, int flags)
2137 struct swdevt *sp, *tsp;
2142 * nblks is in DEV_BSIZE'd chunks, convert to PAGE_SIZE'd chunks.
2143 * First chop nblks off to page-align it, then convert.
2145 * sw->sw_nblks is in page-sized chunks now too.
2147 nblks &= ~(ctodb(1) - 1);
2148 nblks = dbtoc(nblks);
2151 * If we go beyond this, we get overflows in the radix
2154 mblocks = 0x40000000 / BLIST_META_RADIX;
2155 if (nblks > mblocks) {
2157 "WARNING: reducing swap size to maximum of %luMB per unit\n",
2158 mblocks / 1024 / 1024 * PAGE_SIZE);
2162 sp = malloc(sizeof *sp, M_VMPGDATA, M_WAITOK | M_ZERO);
2167 sp->sw_nblks = nblks;
2169 sp->sw_strategy = strategy;
2170 sp->sw_close = close;
2171 sp->sw_flags = flags;
2173 sp->sw_blist = blist_create(nblks, M_WAITOK);
2175 * Do not free the first two block in order to avoid overwriting
2176 * any bsd label at the front of the partition
2178 blist_free(sp->sw_blist, 2, nblks - 2);
2181 mtx_lock(&sw_dev_mtx);
2182 TAILQ_FOREACH(tsp, &swtailq, sw_list) {
2183 if (tsp->sw_end >= dvbase) {
2185 * We put one uncovered page between the devices
2186 * in order to definitively prevent any cross-device
2189 dvbase = tsp->sw_end + 1;
2192 sp->sw_first = dvbase;
2193 sp->sw_end = dvbase + nblks;
2194 TAILQ_INSERT_TAIL(&swtailq, sp, sw_list);
2196 swap_pager_avail += nblks - 2;
2197 swap_total += (vm_ooffset_t)nblks * PAGE_SIZE;
2198 swapon_check_swzone(swap_total / PAGE_SIZE);
2200 mtx_unlock(&sw_dev_mtx);
2204 * SYSCALL: swapoff(devname)
2206 * Disable swapping on the given device.
2208 * XXX: Badly designed system call: it should use a device index
2209 * rather than filename as specification. We keep sw_vp around
2210 * only to make this work.
2212 #ifndef _SYS_SYSPROTO_H_
2213 struct swapoff_args {
2223 sys_swapoff(struct thread *td, struct swapoff_args *uap)
2226 struct nameidata nd;
2230 error = priv_check(td, PRIV_SWAPOFF);
2234 sx_xlock(&swdev_syscall_lock);
2236 NDINIT(&nd, LOOKUP, FOLLOW | AUDITVNODE1, UIO_USERSPACE, uap->name,
2241 NDFREE(&nd, NDF_ONLY_PNBUF);
2244 mtx_lock(&sw_dev_mtx);
2245 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2246 if (sp->sw_vp == vp)
2249 mtx_unlock(&sw_dev_mtx);
2254 error = swapoff_one(sp, td->td_ucred);
2256 sx_xunlock(&swdev_syscall_lock);
2261 swapoff_one(struct swdevt *sp, struct ucred *cred)
2268 sx_assert(&swdev_syscall_lock, SA_XLOCKED);
2270 (void) vn_lock(sp->sw_vp, LK_EXCLUSIVE | LK_RETRY);
2271 error = mac_system_check_swapoff(cred, sp->sw_vp);
2272 (void) VOP_UNLOCK(sp->sw_vp, 0);
2276 nblks = sp->sw_nblks;
2279 * We can turn off this swap device safely only if the
2280 * available virtual memory in the system will fit the amount
2281 * of data we will have to page back in, plus an epsilon so
2282 * the system doesn't become critically low on swap space.
2284 if (vm_cnt.v_free_count + swap_pager_avail < nblks + nswap_lowat)
2288 * Prevent further allocations on this device.
2290 mtx_lock(&sw_dev_mtx);
2291 sp->sw_flags |= SW_CLOSING;
2292 swap_pager_avail -= blist_fill(sp->sw_blist, 0, nblks);
2293 swap_total -= (vm_ooffset_t)nblks * PAGE_SIZE;
2294 mtx_unlock(&sw_dev_mtx);
2297 * Page in the contents of the device and close it.
2299 swap_pager_swapoff(sp);
2301 sp->sw_close(curthread, sp);
2302 mtx_lock(&sw_dev_mtx);
2304 TAILQ_REMOVE(&swtailq, sp, sw_list);
2306 if (nswapdev == 0) {
2307 swap_pager_full = 2;
2308 swap_pager_almost_full = 1;
2312 mtx_unlock(&sw_dev_mtx);
2313 blist_destroy(sp->sw_blist);
2314 free(sp, M_VMPGDATA);
2321 struct swdevt *sp, *spt;
2322 const char *devname;
2325 sx_xlock(&swdev_syscall_lock);
2327 mtx_lock(&sw_dev_mtx);
2328 TAILQ_FOREACH_SAFE(sp, &swtailq, sw_list, spt) {
2329 mtx_unlock(&sw_dev_mtx);
2330 if (vn_isdisk(sp->sw_vp, NULL))
2331 devname = devtoname(sp->sw_vp->v_rdev);
2334 error = swapoff_one(sp, thread0.td_ucred);
2336 printf("Cannot remove swap device %s (error=%d), "
2337 "skipping.\n", devname, error);
2338 } else if (bootverbose) {
2339 printf("Swap device %s removed.\n", devname);
2341 mtx_lock(&sw_dev_mtx);
2343 mtx_unlock(&sw_dev_mtx);
2345 sx_xunlock(&swdev_syscall_lock);
2349 swap_pager_status(int *total, int *used)
2355 mtx_lock(&sw_dev_mtx);
2356 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2357 *total += sp->sw_nblks;
2358 *used += sp->sw_used;
2360 mtx_unlock(&sw_dev_mtx);
2364 swap_dev_info(int name, struct xswdev *xs, char *devname, size_t len)
2367 const char *tmp_devname;
2372 mtx_lock(&sw_dev_mtx);
2373 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2378 xs->xsw_version = XSWDEV_VERSION;
2379 xs->xsw_dev = sp->sw_dev;
2380 xs->xsw_flags = sp->sw_flags;
2381 xs->xsw_nblks = sp->sw_nblks;
2382 xs->xsw_used = sp->sw_used;
2383 if (devname != NULL) {
2384 if (vn_isdisk(sp->sw_vp, NULL))
2385 tmp_devname = devtoname(sp->sw_vp->v_rdev);
2387 tmp_devname = "[file]";
2388 strncpy(devname, tmp_devname, len);
2393 mtx_unlock(&sw_dev_mtx);
2398 sysctl_vm_swap_info(SYSCTL_HANDLER_ARGS)
2403 if (arg2 != 1) /* name length */
2405 error = swap_dev_info(*(int *)arg1, &xs, NULL, 0);
2408 error = SYSCTL_OUT(req, &xs, sizeof(xs));
2412 SYSCTL_INT(_vm, OID_AUTO, nswapdev, CTLFLAG_RD, &nswapdev, 0,
2413 "Number of swap devices");
2414 SYSCTL_NODE(_vm, OID_AUTO, swap_info, CTLFLAG_RD | CTLFLAG_MPSAFE,
2415 sysctl_vm_swap_info,
2416 "Swap statistics by device");
2419 * vmspace_swap_count() - count the approximate swap usage in pages for a
2422 * The map must be locked.
2424 * Swap usage is determined by taking the proportional swap used by
2425 * VM objects backing the VM map. To make up for fractional losses,
2426 * if the VM object has any swap use at all the associated map entries
2427 * count for at least 1 swap page.
2430 vmspace_swap_count(struct vmspace *vmspace)
2437 map = &vmspace->vm_map;
2440 for (cur = map->header.next; cur != &map->header; cur = cur->next) {
2441 if ((cur->eflags & MAP_ENTRY_IS_SUB_MAP) == 0 &&
2442 (object = cur->object.vm_object) != NULL) {
2443 VM_OBJECT_WLOCK(object);
2444 if (object->type == OBJT_SWAP &&
2445 object->un_pager.swp.swp_bcount != 0) {
2446 n = (cur->end - cur->start) / PAGE_SIZE;
2447 count += object->un_pager.swp.swp_bcount *
2448 SWAP_META_PAGES * n / object->size + 1;
2450 VM_OBJECT_WUNLOCK(object);
2459 * Swapping onto disk devices.
2463 static g_orphan_t swapgeom_orphan;
2465 static struct g_class g_swap_class = {
2467 .version = G_VERSION,
2468 .orphan = swapgeom_orphan,
2471 DECLARE_GEOM_CLASS(g_swap_class, g_class);
2475 swapgeom_close_ev(void *arg, int flags)
2477 struct g_consumer *cp;
2480 g_access(cp, -1, -1, 0);
2482 g_destroy_consumer(cp);
2486 * Add a reference to the g_consumer for an inflight transaction.
2489 swapgeom_acquire(struct g_consumer *cp)
2492 mtx_assert(&sw_dev_mtx, MA_OWNED);
2497 * Remove a reference from the g_consumer. Post a close event if all
2498 * references go away, since the function might be called from the
2502 swapgeom_release(struct g_consumer *cp, struct swdevt *sp)
2505 mtx_assert(&sw_dev_mtx, MA_OWNED);
2507 if (cp->index == 0) {
2508 if (g_post_event(swapgeom_close_ev, cp, M_NOWAIT, NULL) == 0)
2514 swapgeom_done(struct bio *bp2)
2518 struct g_consumer *cp;
2520 bp = bp2->bio_caller2;
2522 bp->b_ioflags = bp2->bio_flags;
2524 bp->b_ioflags |= BIO_ERROR;
2525 bp->b_resid = bp->b_bcount - bp2->bio_completed;
2526 bp->b_error = bp2->bio_error;
2528 sp = bp2->bio_caller1;
2529 mtx_lock(&sw_dev_mtx);
2530 swapgeom_release(cp, sp);
2531 mtx_unlock(&sw_dev_mtx);
2536 swapgeom_strategy(struct buf *bp, struct swdevt *sp)
2539 struct g_consumer *cp;
2541 mtx_lock(&sw_dev_mtx);
2544 mtx_unlock(&sw_dev_mtx);
2545 bp->b_error = ENXIO;
2546 bp->b_ioflags |= BIO_ERROR;
2550 swapgeom_acquire(cp);
2551 mtx_unlock(&sw_dev_mtx);
2552 if (bp->b_iocmd == BIO_WRITE)
2555 bio = g_alloc_bio();
2557 mtx_lock(&sw_dev_mtx);
2558 swapgeom_release(cp, sp);
2559 mtx_unlock(&sw_dev_mtx);
2560 bp->b_error = ENOMEM;
2561 bp->b_ioflags |= BIO_ERROR;
2566 bio->bio_caller1 = sp;
2567 bio->bio_caller2 = bp;
2568 bio->bio_cmd = bp->b_iocmd;
2569 bio->bio_offset = (bp->b_blkno - sp->sw_first) * PAGE_SIZE;
2570 bio->bio_length = bp->b_bcount;
2571 bio->bio_done = swapgeom_done;
2572 if (!buf_mapped(bp)) {
2573 bio->bio_ma = bp->b_pages;
2574 bio->bio_data = unmapped_buf;
2575 bio->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
2576 bio->bio_ma_n = bp->b_npages;
2577 bio->bio_flags |= BIO_UNMAPPED;
2579 bio->bio_data = bp->b_data;
2582 g_io_request(bio, cp);
2587 swapgeom_orphan(struct g_consumer *cp)
2592 mtx_lock(&sw_dev_mtx);
2593 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2594 if (sp->sw_id == cp) {
2595 sp->sw_flags |= SW_CLOSING;
2600 * Drop reference we were created with. Do directly since we're in a
2601 * special context where we don't have to queue the call to
2602 * swapgeom_close_ev().
2605 destroy = ((sp != NULL) && (cp->index == 0));
2608 mtx_unlock(&sw_dev_mtx);
2610 swapgeom_close_ev(cp, 0);
2614 swapgeom_close(struct thread *td, struct swdevt *sw)
2616 struct g_consumer *cp;
2618 mtx_lock(&sw_dev_mtx);
2621 mtx_unlock(&sw_dev_mtx);
2624 * swapgeom_close() may be called from the biodone context,
2625 * where we cannot perform topology changes. Delegate the
2626 * work to the events thread.
2629 g_waitfor_event(swapgeom_close_ev, cp, M_WAITOK, NULL);
2633 swapongeom_locked(struct cdev *dev, struct vnode *vp)
2635 struct g_provider *pp;
2636 struct g_consumer *cp;
2637 static struct g_geom *gp;
2642 pp = g_dev_getprovider(dev);
2645 mtx_lock(&sw_dev_mtx);
2646 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2648 if (cp != NULL && cp->provider == pp) {
2649 mtx_unlock(&sw_dev_mtx);
2653 mtx_unlock(&sw_dev_mtx);
2655 gp = g_new_geomf(&g_swap_class, "swap");
2656 cp = g_new_consumer(gp);
2657 cp->index = 1; /* Number of active I/Os, plus one for being active. */
2658 cp->flags |= G_CF_DIRECT_SEND | G_CF_DIRECT_RECEIVE;
2661 * XXX: Every time you think you can improve the margin for
2662 * footshooting, somebody depends on the ability to do so:
2663 * savecore(8) wants to write to our swapdev so we cannot
2664 * set an exclusive count :-(
2666 error = g_access(cp, 1, 1, 0);
2669 g_destroy_consumer(cp);
2672 nblks = pp->mediasize / DEV_BSIZE;
2673 swaponsomething(vp, cp, nblks, swapgeom_strategy,
2674 swapgeom_close, dev2udev(dev),
2675 (pp->flags & G_PF_ACCEPT_UNMAPPED) != 0 ? SW_UNMAPPED : 0);
2680 swapongeom(struct vnode *vp)
2684 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2685 if (vp->v_type != VCHR || (vp->v_iflag & VI_DOOMED) != 0) {
2689 error = swapongeom_locked(vp->v_rdev, vp);
2690 g_topology_unlock();
2699 * This is used mainly for network filesystem (read: probably only tested
2700 * with NFS) swapfiles.
2705 swapdev_strategy(struct buf *bp, struct swdevt *sp)
2709 bp->b_blkno = ctodb(bp->b_blkno - sp->sw_first);
2713 if (bp->b_iocmd == BIO_WRITE) {
2715 bufobj_wdrop(bp->b_bufobj);
2716 bufobj_wref(&vp2->v_bufobj);
2718 if (bp->b_bufobj != &vp2->v_bufobj)
2719 bp->b_bufobj = &vp2->v_bufobj;
2721 bp->b_iooffset = dbtob(bp->b_blkno);
2727 swapdev_close(struct thread *td, struct swdevt *sp)
2730 VOP_CLOSE(sp->sw_vp, FREAD | FWRITE, td->td_ucred, td);
2736 swaponvp(struct thread *td, struct vnode *vp, u_long nblks)
2743 mtx_lock(&sw_dev_mtx);
2744 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2745 if (sp->sw_id == vp) {
2746 mtx_unlock(&sw_dev_mtx);
2750 mtx_unlock(&sw_dev_mtx);
2752 (void) vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2754 error = mac_system_check_swapon(td->td_ucred, vp);
2757 error = VOP_OPEN(vp, FREAD | FWRITE, td->td_ucred, td, NULL);
2758 (void) VOP_UNLOCK(vp, 0);
2762 swaponsomething(vp, vp, nblks, swapdev_strategy, swapdev_close,
2768 sysctl_swap_async_max(SYSCTL_HANDLER_ARGS)
2772 new = nsw_wcount_async_max;
2773 error = sysctl_handle_int(oidp, &new, 0, req);
2774 if (error != 0 || req->newptr == NULL)
2777 if (new > nswbuf / 2 || new < 1)
2780 mtx_lock(&pbuf_mtx);
2781 while (nsw_wcount_async_max != new) {
2783 * Adjust difference. If the current async count is too low,
2784 * we will need to sqeeze our update slowly in. Sleep with a
2785 * higher priority than getpbuf() to finish faster.
2787 n = new - nsw_wcount_async_max;
2788 if (nsw_wcount_async + n >= 0) {
2789 nsw_wcount_async += n;
2790 nsw_wcount_async_max += n;
2791 wakeup(&nsw_wcount_async);
2793 nsw_wcount_async_max -= nsw_wcount_async;
2794 nsw_wcount_async = 0;
2795 msleep(&nsw_wcount_async, &pbuf_mtx, PSWP,
2799 mtx_unlock(&pbuf_mtx);