kernel - TMPFS - Add infrastructure to main kernel to help support TMPFS
[dragonfly.git] / sys / vm / swap_pager.c
blob03f1e0e974b4559a2714863e7eb4392e2f3809e0
1 /*
2 * Copyright (c) 1998,2004 The DragonFly Project. All rights reserved.
3 *
4 * This code is derived from software contributed to The DragonFly Project
5 * by Matthew Dillon <dillon@backplane.com>
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in
15 * the documentation and/or other materials provided with the
16 * distribution.
17 * 3. Neither the name of The DragonFly Project nor the names of its
18 * contributors may be used to endorse or promote products derived
19 * from this software without specific, prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
34 * Copyright (c) 1994 John S. Dyson
35 * Copyright (c) 1990 University of Utah.
36 * Copyright (c) 1991, 1993
37 * The Regents of the University of California. All rights reserved.
39 * This code is derived from software contributed to Berkeley by
40 * the Systems Programming Group of the University of Utah Computer
41 * Science Department.
43 * Redistribution and use in source and binary forms, with or without
44 * modification, are permitted provided that the following conditions
45 * are met:
46 * 1. Redistributions of source code must retain the above copyright
47 * notice, this list of conditions and the following disclaimer.
48 * 2. Redistributions in binary form must reproduce the above copyright
49 * notice, this list of conditions and the following disclaimer in the
50 * documentation and/or other materials provided with the distribution.
51 * 3. All advertising materials mentioning features or use of this software
52 * must display the following acknowledgement:
53 * This product includes software developed by the University of
54 * California, Berkeley and its contributors.
55 * 4. Neither the name of the University nor the names of its contributors
56 * may be used to endorse or promote products derived from this software
57 * without specific prior written permission.
59 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
60 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
63 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69 * SUCH DAMAGE.
71 * New Swap System
72 * Matthew Dillon
74 * Radix Bitmap 'blists'.
76 * - The new swapper uses the new radix bitmap code. This should scale
77 * to arbitrarily small or arbitrarily large swap spaces and an almost
78 * arbitrary degree of fragmentation.
80 * Features:
82 * - on the fly reallocation of swap during putpages. The new system
83 * does not try to keep previously allocated swap blocks for dirty
84 * pages.
86 * - on the fly deallocation of swap
88 * - No more garbage collection required. Unnecessarily allocated swap
89 * blocks only exist for dirty vm_page_t's now and these are already
90 * cycled (in a high-load system) by the pager. We also do on-the-fly
91 * removal of invalidated swap blocks when a page is destroyed
92 * or renamed.
94 * from: Utah $Hdr: swap_pager.c 1.4 91/04/30$
96 * @(#)swap_pager.c 8.9 (Berkeley) 3/21/94
98 * $FreeBSD: src/sys/vm/swap_pager.c,v 1.130.2.12 2002/08/31 21:15:55 dillon Exp $
99 * $DragonFly: src/sys/vm/swap_pager.c,v 1.32 2008/07/01 02:02:56 dillon Exp $
102 #include <sys/param.h>
103 #include <sys/systm.h>
104 #include <sys/conf.h>
105 #include <sys/kernel.h>
106 #include <sys/proc.h>
107 #include <sys/buf.h>
108 #include <sys/vnode.h>
109 #include <sys/malloc.h>
110 #include <sys/vmmeter.h>
111 #include <sys/sysctl.h>
112 #include <sys/blist.h>
113 #include <sys/lock.h>
114 #include <sys/thread2.h>
116 #ifndef MAX_PAGEOUT_CLUSTER
117 #define MAX_PAGEOUT_CLUSTER 16
118 #endif
120 #define SWB_NPAGES MAX_PAGEOUT_CLUSTER
122 #include "opt_swap.h"
123 #include <vm/vm.h>
124 #include <vm/vm_object.h>
125 #include <vm/vm_page.h>
126 #include <vm/vm_pager.h>
127 #include <vm/vm_pageout.h>
128 #include <vm/swap_pager.h>
129 #include <vm/vm_extern.h>
130 #include <vm/vm_zone.h>
131 #include <vm/vnode_pager.h>
133 #include <sys/buf2.h>
134 #include <vm/vm_page2.h>
136 #define SWM_FREE 0x02 /* free, period */
137 #define SWM_POP 0x04 /* pop out */
139 #define SWBIO_READ 0x01
140 #define SWBIO_WRITE 0x02
141 #define SWBIO_SYNC 0x04
143 struct swfreeinfo {
144 vm_object_t object;
145 vm_pindex_t basei;
146 vm_pindex_t begi;
147 vm_pindex_t endi; /* inclusive */
151 * vm_swap_size is in page-sized chunks now. It was DEV_BSIZE'd chunks
152 * in the old system.
155 int swap_pager_full; /* swap space exhaustion (task killing) */
156 int vm_swap_cache_use;
157 int vm_swap_anon_use;
159 static int swap_pager_almost_full; /* swap space exhaustion (w/ hysteresis)*/
160 static int nsw_rcount; /* free read buffers */
161 static int nsw_wcount_sync; /* limit write buffers / synchronous */
162 static int nsw_wcount_async; /* limit write buffers / asynchronous */
163 static int nsw_wcount_async_max;/* assigned maximum */
164 static int nsw_cluster_max; /* maximum VOP I/O allowed */
166 struct blist *swapblist;
167 static int swap_async_max = 4; /* maximum in-progress async I/O's */
168 static int swap_burst_read = 0; /* allow burst reading */
170 extern struct vnode *swapdev_vp; /* from vm_swap.c */
172 SYSCTL_INT(_vm, OID_AUTO, swap_async_max,
173 CTLFLAG_RW, &swap_async_max, 0, "Maximum running async swap ops");
174 SYSCTL_INT(_vm, OID_AUTO, swap_burst_read,
175 CTLFLAG_RW, &swap_burst_read, 0, "Allow burst reads for pageins");
177 SYSCTL_INT(_vm, OID_AUTO, swap_cache_use,
178 CTLFLAG_RD, &vm_swap_cache_use, 0, "");
179 SYSCTL_INT(_vm, OID_AUTO, swap_anon_use,
180 CTLFLAG_RD, &vm_swap_anon_use, 0, "");
182 vm_zone_t swap_zone;
185 * Red-Black tree for swblock entries
187 RB_GENERATE2(swblock_rb_tree, swblock, swb_entry, rb_swblock_compare,
188 vm_pindex_t, swb_index);
191 rb_swblock_compare(struct swblock *swb1, struct swblock *swb2)
193 if (swb1->swb_index < swb2->swb_index)
194 return(-1);
195 if (swb1->swb_index > swb2->swb_index)
196 return(1);
197 return(0);
200 static
202 rb_swblock_scancmp(struct swblock *swb, void *data)
204 struct swfreeinfo *info = data;
206 if (swb->swb_index < info->basei)
207 return(-1);
208 if (swb->swb_index > info->endi)
209 return(1);
210 return(0);
213 static
215 rb_swblock_condcmp(struct swblock *swb, void *data)
217 struct swfreeinfo *info = data;
219 if (swb->swb_index < info->basei)
220 return(-1);
221 return(0);
225 * pagerops for OBJT_SWAP - "swap pager". Some ops are also global procedure
226 * calls hooked from other parts of the VM system and do not appear here.
227 * (see vm/swap_pager.h).
230 static vm_object_t
231 swap_pager_alloc (void *handle, off_t size,
232 vm_prot_t prot, off_t offset);
233 static void swap_pager_dealloc (vm_object_t object);
234 static int swap_pager_getpage (vm_object_t, vm_page_t *, int);
235 static void swap_chain_iodone(struct bio *biox);
237 struct pagerops swappagerops = {
238 swap_pager_alloc, /* allocate an OBJT_SWAP object */
239 swap_pager_dealloc, /* deallocate an OBJT_SWAP object */
240 swap_pager_getpage, /* pagein */
241 swap_pager_putpages, /* pageout */
242 swap_pager_haspage /* get backing store status for page */
246 * dmmax is in page-sized chunks with the new swap system. It was
247 * dev-bsized chunks in the old. dmmax is always a power of 2.
249 * swap_*() routines are externally accessible. swp_*() routines are
250 * internal.
253 int dmmax;
254 static int dmmax_mask;
255 int nswap_lowat = 128; /* in pages, swap_pager_almost_full warn */
256 int nswap_hiwat = 512; /* in pages, swap_pager_almost_full warn */
258 static __inline void swp_sizecheck (void);
259 static void swp_pager_async_iodone (struct bio *bio);
262 * Swap bitmap functions
265 static __inline void swp_pager_freeswapspace (vm_object_t object, daddr_t blk, int npages);
266 static __inline daddr_t swp_pager_getswapspace (vm_object_t object, int npages);
269 * Metadata functions
272 static void swp_pager_meta_convert (vm_object_t);
273 static void swp_pager_meta_build (vm_object_t, vm_pindex_t, daddr_t);
274 static void swp_pager_meta_free (vm_object_t, vm_pindex_t, vm_pindex_t);
275 static void swp_pager_meta_free_all (vm_object_t);
276 static daddr_t swp_pager_meta_ctl (vm_object_t, vm_pindex_t, int);
279 * SWP_SIZECHECK() - update swap_pager_full indication
281 * update the swap_pager_almost_full indication and warn when we are
282 * about to run out of swap space, using lowat/hiwat hysteresis.
284 * Clear swap_pager_full ( task killing ) indication when lowat is met.
286 * No restrictions on call
287 * This routine may not block.
288 * This routine must be called at splvm()
291 static __inline void
292 swp_sizecheck(void)
294 if (vm_swap_size < nswap_lowat) {
295 if (swap_pager_almost_full == 0) {
296 kprintf("swap_pager: out of swap space\n");
297 swap_pager_almost_full = 1;
299 } else {
300 swap_pager_full = 0;
301 if (vm_swap_size > nswap_hiwat)
302 swap_pager_almost_full = 0;
307 * SWAP_PAGER_INIT() - initialize the swap pager!
309 * Expected to be started from system init. NOTE: This code is run
310 * before much else so be careful what you depend on. Most of the VM
311 * system has yet to be initialized at this point.
313 static void
314 swap_pager_init(void *arg __unused)
317 * Device Stripe, in PAGE_SIZE'd blocks
319 dmmax = SWB_NPAGES * 2;
320 dmmax_mask = ~(dmmax - 1);
322 SYSINIT(vm_mem, SI_BOOT1_VM, SI_ORDER_THIRD, swap_pager_init, NULL)
325 * SWAP_PAGER_SWAP_INIT() - swap pager initialization from pageout process
327 * Expected to be started from pageout process once, prior to entering
328 * its main loop.
331 void
332 swap_pager_swap_init(void)
334 int n, n2;
337 * Number of in-transit swap bp operations. Don't
338 * exhaust the pbufs completely. Make sure we
339 * initialize workable values (0 will work for hysteresis
340 * but it isn't very efficient).
342 * The nsw_cluster_max is constrained by the number of pages an XIO
343 * holds, i.e., (MAXPHYS/PAGE_SIZE) and our locally defined
344 * MAX_PAGEOUT_CLUSTER. Also be aware that swap ops are
345 * constrained by the swap device interleave stripe size.
347 * Currently we hardwire nsw_wcount_async to 4. This limit is
348 * designed to prevent other I/O from having high latencies due to
349 * our pageout I/O. The value 4 works well for one or two active swap
350 * devices but is probably a little low if you have more. Even so,
351 * a higher value would probably generate only a limited improvement
352 * with three or four active swap devices since the system does not
353 * typically have to pageout at extreme bandwidths. We will want
354 * at least 2 per swap devices, and 4 is a pretty good value if you
355 * have one NFS swap device due to the command/ack latency over NFS.
356 * So it all works out pretty well.
359 nsw_cluster_max = min((MAXPHYS/PAGE_SIZE), MAX_PAGEOUT_CLUSTER);
361 nsw_rcount = (nswbuf + 1) / 2;
362 nsw_wcount_sync = (nswbuf + 3) / 4;
363 nsw_wcount_async = 4;
364 nsw_wcount_async_max = nsw_wcount_async;
367 * The zone is dynamically allocated so generally size it to
368 * maxswzone (32MB to 512MB of KVM). Set a minimum size based
369 * on physical memory of around 8x (each swblock can hold 16 pages).
371 * With the advent of SSDs (vs HDs) the practical (swap:memory) ratio
372 * has increased dramatically.
374 n = vmstats.v_page_count / 2;
375 if (maxswzone && n < maxswzone / sizeof(struct swblock))
376 n = maxswzone / sizeof(struct swblock);
377 n2 = n;
379 do {
380 swap_zone = zinit(
381 "SWAPMETA",
382 sizeof(struct swblock),
384 ZONE_INTERRUPT,
386 if (swap_zone != NULL)
387 break;
389 * if the allocation failed, try a zone two thirds the
390 * size of the previous attempt.
392 n -= ((n + 2) / 3);
393 } while (n > 0);
395 if (swap_zone == NULL)
396 panic("swap_pager_swap_init: swap_zone == NULL");
397 if (n2 != n)
398 kprintf("Swap zone entries reduced from %d to %d.\n", n2, n);
402 * SWAP_PAGER_ALLOC() - allocate a new OBJT_SWAP VM object and instantiate
403 * its metadata structures.
405 * This routine is called from the mmap and fork code to create a new
406 * OBJT_SWAP object. We do this by creating an OBJT_DEFAULT object
407 * and then converting it with swp_pager_meta_convert().
409 * This routine may block in vm_object_allocate() and create a named
410 * object lookup race, so we must interlock. We must also run at
411 * splvm() for the object lookup to handle races with interrupts, but
412 * we do not have to maintain splvm() in between the lookup and the
413 * add because (I believe) it is not possible to attempt to create
414 * a new swap object w/handle when a default object with that handle
415 * already exists.
418 static vm_object_t
419 swap_pager_alloc(void *handle, off_t size, vm_prot_t prot, off_t offset)
421 vm_object_t object;
423 KKASSERT(handle == NULL);
424 #if 0
425 if (handle) {
427 * Reference existing named region or allocate new one. There
428 * should not be a race here against swp_pager_meta_build()
429 * as called from vm_page_remove() in regards to the lookup
430 * of the handle.
432 while (sw_alloc_interlock) {
433 sw_alloc_interlock = -1;
434 tsleep(&sw_alloc_interlock, 0, "swpalc", 0);
436 sw_alloc_interlock = 1;
438 object = vm_pager_object_lookup(NOBJLIST(handle), handle);
440 if (object != NULL) {
441 vm_object_reference(object);
442 } else {
443 object = vm_object_allocate(OBJT_DEFAULT,
444 OFF_TO_IDX(offset + PAGE_MASK + size));
445 object->handle = handle;
446 swp_pager_meta_convert(object);
449 if (sw_alloc_interlock < 0)
450 wakeup(&sw_alloc_interlock);
451 sw_alloc_interlock = 0;
452 } else { ... }
453 #endif
454 object = vm_object_allocate(OBJT_DEFAULT,
455 OFF_TO_IDX(offset + PAGE_MASK + size));
456 swp_pager_meta_convert(object);
458 return (object);
462 * SWAP_PAGER_DEALLOC() - remove swap metadata from object
464 * The swap backing for the object is destroyed. The code is
465 * designed such that we can reinstantiate it later, but this
466 * routine is typically called only when the entire object is
467 * about to be destroyed.
469 * This routine may block, but no longer does.
471 * The object must be locked or unreferenceable.
474 static void
475 swap_pager_dealloc(vm_object_t object)
477 vm_object_pip_wait(object, "swpdea");
480 * Free all remaining metadata. We only bother to free it from
481 * the swap meta data. We do not attempt to free swapblk's still
482 * associated with vm_page_t's for this object. We do not care
483 * if paging is still in progress on some objects.
485 crit_enter();
486 swp_pager_meta_free_all(object);
487 crit_exit();
490 /************************************************************************
491 * SWAP PAGER BITMAP ROUTINES *
492 ************************************************************************/
495 * SWP_PAGER_GETSWAPSPACE() - allocate raw swap space
497 * Allocate swap for the requested number of pages. The starting
498 * swap block number (a page index) is returned or SWAPBLK_NONE
499 * if the allocation failed.
501 * Also has the side effect of advising that somebody made a mistake
502 * when they configured swap and didn't configure enough.
504 * Must be called at splvm() to avoid races with bitmap frees from
505 * vm_page_remove() aka swap_pager_page_removed().
507 * This routine may not block
508 * This routine must be called at splvm().
510 static __inline daddr_t
511 swp_pager_getswapspace(vm_object_t object, int npages)
513 daddr_t blk;
515 if ((blk = blist_alloc(swapblist, npages)) == SWAPBLK_NONE) {
516 if (swap_pager_full != 2) {
517 kprintf("swap_pager_getswapspace: failed\n");
518 swap_pager_full = 2;
519 swap_pager_almost_full = 1;
521 } else {
522 vm_swap_size -= npages;
523 if (object->type == OBJT_SWAP)
524 vm_swap_anon_use += npages;
525 else
526 vm_swap_cache_use += npages;
527 swp_sizecheck();
529 return(blk);
533 * SWP_PAGER_FREESWAPSPACE() - free raw swap space
535 * This routine returns the specified swap blocks back to the bitmap.
537 * Note: This routine may not block (it could in the old swap code),
538 * and through the use of the new blist routines it does not block.
540 * We must be called at splvm() to avoid races with bitmap frees from
541 * vm_page_remove() aka swap_pager_page_removed().
543 * This routine may not block
544 * This routine must be called at splvm().
547 static __inline void
548 swp_pager_freeswapspace(vm_object_t object, daddr_t blk, int npages)
550 blist_free(swapblist, blk, npages);
551 vm_swap_size += npages;
552 if (object->type == OBJT_SWAP)
553 vm_swap_anon_use -= npages;
554 else
555 vm_swap_cache_use -= npages;
556 swp_sizecheck();
560 * SWAP_PAGER_FREESPACE() - frees swap blocks associated with a page
561 * range within an object.
563 * This is a globally accessible routine.
565 * This routine removes swapblk assignments from swap metadata.
567 * The external callers of this routine typically have already destroyed
568 * or renamed vm_page_t's associated with this range in the object so
569 * we should be ok.
571 * This routine may be called at any spl. We up our spl to splvm
572 * temporarily in order to perform the metadata removal.
574 void
575 swap_pager_freespace(vm_object_t object, vm_pindex_t start, vm_pindex_t size)
577 crit_enter();
578 swp_pager_meta_free(object, start, size);
579 crit_exit();
582 void
583 swap_pager_freespace_all(vm_object_t object)
585 crit_enter();
586 swp_pager_meta_free_all(object);
587 crit_exit();
591 * This function conditionally frees swap cache swap starting at
592 * (*basei) in the object. (count) swap blocks will be nominally freed.
593 * The actual number of blocks freed can be more or less than the
594 * requested number.
596 * This function nominally returns the number of blocks freed. However,
597 * the actual number of blocks freed may be less then the returned value.
598 * If the function is unable to exhaust the object or if it is able to
599 * free (approximately) the requested number of blocks it returns
600 * a value n > count.
602 * If we exhaust the object we will return a value n <= count.
604 * Must be called from a critical section.
606 static int swap_pager_condfree_callback(struct swblock *swap, void *data);
609 swap_pager_condfree(vm_object_t object, vm_pindex_t *basei, int count)
611 struct swfreeinfo info;
613 info.object = object;
614 info.basei = *basei; /* skip up to this page index */
615 info.begi = count; /* max swap pages to destroy */
616 info.endi = count * 8; /* max swblocks to scan */
618 swblock_rb_tree_RB_SCAN(&object->swblock_root, rb_swblock_condcmp,
619 swap_pager_condfree_callback, &info);
620 *basei = info.basei;
621 if (info.endi < 0 && info.begi <= count)
622 info.begi = count + 1;
623 return(count - (int)info.begi);
627 * The idea is to free whole meta-block to avoid fragmenting
628 * the swap space or disk I/O. We only do this if NO VM pages
629 * are present.
631 * We do not have to deal with clearing PG_SWAPPED in related VM
632 * pages because there are no related VM pages.
634 static int
635 swap_pager_condfree_callback(struct swblock *swap, void *data)
637 struct swfreeinfo *info = data;
638 vm_object_t object = info->object;
639 int i;
641 for (i = 0; i < SWAP_META_PAGES; ++i) {
642 if (vm_page_lookup(object, swap->swb_index + i))
643 break;
645 info->basei = swap->swb_index + SWAP_META_PAGES;
646 if (i == SWAP_META_PAGES) {
647 info->begi -= swap->swb_count;
648 swap_pager_freespace(object, swap->swb_index, SWAP_META_PAGES);
650 --info->endi;
651 if ((int)info->begi < 0 || (int)info->endi < 0)
652 return(-1);
653 return(0);
657 * Called by vm_page_alloc() when a new VM page is inserted
658 * into a VM object. Checks whether swap has been assigned to
659 * the page and sets PG_SWAPPED as necessary.
661 void
662 swap_pager_page_inserted(vm_page_t m)
664 if (m->object->swblock_count) {
665 crit_enter();
666 if (swp_pager_meta_ctl(m->object, m->pindex, 0) != SWAPBLK_NONE)
667 vm_page_flag_set(m, PG_SWAPPED);
668 crit_exit();
673 * SWAP_PAGER_RESERVE() - reserve swap blocks in object
675 * Assigns swap blocks to the specified range within the object. The
676 * swap blocks are not zerod. Any previous swap assignment is destroyed.
678 * Returns 0 on success, -1 on failure.
681 swap_pager_reserve(vm_object_t object, vm_pindex_t start, vm_size_t size)
683 int n = 0;
684 daddr_t blk = SWAPBLK_NONE;
685 vm_pindex_t beg = start; /* save start index */
687 crit_enter();
688 while (size) {
689 if (n == 0) {
690 n = BLIST_MAX_ALLOC;
691 while ((blk = swp_pager_getswapspace(object, n)) ==
692 SWAPBLK_NONE)
694 n >>= 1;
695 if (n == 0) {
696 swp_pager_meta_free(object, beg,
697 start - beg);
698 crit_exit();
699 return(-1);
703 swp_pager_meta_build(object, start, blk);
704 --size;
705 ++start;
706 ++blk;
707 --n;
709 swp_pager_meta_free(object, start, n);
710 crit_exit();
711 return(0);
715 * SWAP_PAGER_COPY() - copy blocks from source pager to destination pager
716 * and destroy the source.
718 * Copy any valid swapblks from the source to the destination. In
719 * cases where both the source and destination have a valid swapblk,
720 * we keep the destination's.
722 * This routine is allowed to block. It may block allocating metadata
723 * indirectly through swp_pager_meta_build() or if paging is still in
724 * progress on the source.
726 * This routine can be called at any spl
728 * XXX vm_page_collapse() kinda expects us not to block because we
729 * supposedly do not need to allocate memory, but for the moment we
730 * *may* have to get a little memory from the zone allocator, but
731 * it is taken from the interrupt memory. We should be ok.
733 * The source object contains no vm_page_t's (which is just as well)
735 * The source object is of type OBJT_SWAP.
737 * The source and destination objects must be locked or
738 * inaccessible (XXX are they ?)
741 void
742 swap_pager_copy(vm_object_t srcobject, vm_object_t dstobject,
743 vm_pindex_t base_index, int destroysource)
745 vm_pindex_t i;
747 crit_enter();
750 * transfer source to destination.
752 for (i = 0; i < dstobject->size; ++i) {
753 daddr_t dstaddr;
756 * Locate (without changing) the swapblk on the destination,
757 * unless it is invalid in which case free it silently, or
758 * if the destination is a resident page, in which case the
759 * source is thrown away.
761 dstaddr = swp_pager_meta_ctl(dstobject, i, 0);
763 if (dstaddr == SWAPBLK_NONE) {
765 * Destination has no swapblk and is not resident,
766 * copy source.
768 daddr_t srcaddr;
770 srcaddr = swp_pager_meta_ctl(srcobject,
771 base_index + i, SWM_POP);
773 if (srcaddr != SWAPBLK_NONE)
774 swp_pager_meta_build(dstobject, i, srcaddr);
775 } else {
777 * Destination has valid swapblk or it is represented
778 * by a resident page. We destroy the sourceblock.
780 swp_pager_meta_ctl(srcobject, base_index + i, SWM_FREE);
785 * Free left over swap blocks in source.
787 * We have to revert the type to OBJT_DEFAULT so we do not accidently
788 * double-remove the object from the swap queues.
790 if (destroysource) {
792 * Reverting the type is not necessary, the caller is going
793 * to destroy srcobject directly, but I'm doing it here
794 * for consistency since we've removed the object from its
795 * queues.
797 swp_pager_meta_free_all(srcobject);
798 if (srcobject->type == OBJT_SWAP)
799 srcobject->type = OBJT_DEFAULT;
801 crit_exit();
805 * SWAP_PAGER_HASPAGE() - determine if we have good backing store for
806 * the requested page.
808 * We determine whether good backing store exists for the requested
809 * page and return TRUE if it does, FALSE if it doesn't.
811 * If TRUE, we also try to determine how much valid, contiguous backing
812 * store exists before and after the requested page within a reasonable
813 * distance. We do not try to restrict it to the swap device stripe
814 * (that is handled in getpages/putpages). It probably isn't worth
815 * doing here.
818 boolean_t
819 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex)
821 daddr_t blk0;
824 * do we have good backing store at the requested index ?
827 crit_enter();
828 blk0 = swp_pager_meta_ctl(object, pindex, 0);
830 if (blk0 == SWAPBLK_NONE) {
831 crit_exit();
832 return (FALSE);
835 #if 0
837 * find backwards-looking contiguous good backing store
839 if (before != NULL) {
840 int i;
842 for (i = 1; i < (SWB_NPAGES/2); ++i) {
843 daddr_t blk;
845 if (i > pindex)
846 break;
847 blk = swp_pager_meta_ctl(object, pindex - i, 0);
848 if (blk != blk0 - i)
849 break;
851 *before = (i - 1);
855 * find forward-looking contiguous good backing store
858 if (after != NULL) {
859 int i;
861 for (i = 1; i < (SWB_NPAGES/2); ++i) {
862 daddr_t blk;
864 blk = swp_pager_meta_ctl(object, pindex + i, 0);
865 if (blk != blk0 + i)
866 break;
868 *after = (i - 1);
870 #endif
871 crit_exit();
872 return (TRUE);
876 * SWAP_PAGER_PAGE_UNSWAPPED() - remove swap backing store related to page
878 * This removes any associated swap backing store, whether valid or
879 * not, from the page. This operates on any VM object, not just OBJT_SWAP
880 * objects.
882 * This routine is typically called when a page is made dirty, at
883 * which point any associated swap can be freed. MADV_FREE also
884 * calls us in a special-case situation
886 * NOTE!!! If the page is clean and the swap was valid, the caller
887 * should make the page dirty before calling this routine. This routine
888 * does NOT change the m->dirty status of the page. Also: MADV_FREE
889 * depends on it.
891 * This routine may not block.
893 * The page must be busied or soft-busied.
895 void
896 swap_pager_unswapped(vm_page_t m)
898 if (m->flags & PG_SWAPPED) {
899 crit_enter();
900 KKASSERT(m->flags & PG_SWAPPED);
901 swp_pager_meta_ctl(m->object, m->pindex, SWM_FREE);
902 vm_page_flag_clear(m, PG_SWAPPED);
903 crit_exit();
908 * SWAP_PAGER_STRATEGY() - read, write, free blocks
910 * This implements a VM OBJECT strategy function using swap backing store.
911 * This can operate on any VM OBJECT type, not necessarily just OBJT_SWAP
912 * types.
914 * This is intended to be a cacheless interface (i.e. caching occurs at
915 * higher levels), and is also used as a swap-based SSD cache for vnode
916 * and device objects.
918 * All I/O goes directly to and from the swap device.
920 * We currently attempt to run I/O synchronously or asynchronously as
921 * the caller requests. This isn't perfect because we loose error
922 * sequencing when we run multiple ops in parallel to satisfy a request.
923 * But this is swap, so we let it all hang out.
925 void
926 swap_pager_strategy(vm_object_t object, struct bio *bio)
928 struct buf *bp = bio->bio_buf;
929 struct bio *nbio;
930 vm_pindex_t start;
931 vm_pindex_t biox_blkno = 0;
932 int count;
933 char *data;
934 struct bio *biox;
935 struct buf *bufx;
936 struct bio_track *track;
939 * tracking for swapdev vnode I/Os
941 if (bp->b_cmd == BUF_CMD_READ)
942 track = &swapdev_vp->v_track_read;
943 else
944 track = &swapdev_vp->v_track_write;
946 if (bp->b_bcount & PAGE_MASK) {
947 bp->b_error = EINVAL;
948 bp->b_flags |= B_ERROR | B_INVAL;
949 biodone(bio);
950 kprintf("swap_pager_strategy: bp %p offset %lld size %d, "
951 "not page bounded\n",
952 bp, (long long)bio->bio_offset, (int)bp->b_bcount);
953 return;
957 * Clear error indication, initialize page index, count, data pointer.
959 bp->b_error = 0;
960 bp->b_flags &= ~B_ERROR;
961 bp->b_resid = bp->b_bcount;
963 start = (vm_pindex_t)(bio->bio_offset >> PAGE_SHIFT);
964 count = howmany(bp->b_bcount, PAGE_SIZE);
965 data = bp->b_data;
968 * Deal with BUF_CMD_FREEBLKS
970 if (bp->b_cmd == BUF_CMD_FREEBLKS) {
972 * FREE PAGE(s) - destroy underlying swap that is no longer
973 * needed.
975 crit_enter();
976 swp_pager_meta_free(object, start, count);
977 crit_exit();
978 bp->b_resid = 0;
979 biodone(bio);
980 return;
984 * We need to be able to create a new cluster of I/O's. We cannot
985 * use the caller fields of the passed bio so push a new one.
987 * Because nbio is just a placeholder for the cluster links,
988 * we can biodone() the original bio instead of nbio to make
989 * things a bit more efficient.
991 nbio = push_bio(bio);
992 nbio->bio_offset = bio->bio_offset;
993 nbio->bio_caller_info1.cluster_head = NULL;
994 nbio->bio_caller_info2.cluster_tail = NULL;
996 biox = NULL;
997 bufx = NULL;
1000 * Execute read or write
1002 crit_enter();
1003 while (count > 0) {
1004 daddr_t blk;
1007 * Obtain block. If block not found and writing, allocate a
1008 * new block and build it into the object.
1010 blk = swp_pager_meta_ctl(object, start, 0);
1011 if ((blk == SWAPBLK_NONE) && bp->b_cmd != BUF_CMD_READ) {
1012 blk = swp_pager_getswapspace(object, 1);
1013 if (blk == SWAPBLK_NONE) {
1014 bp->b_error = ENOMEM;
1015 bp->b_flags |= B_ERROR;
1016 break;
1018 swp_pager_meta_build(object, start, blk);
1022 * Do we have to flush our current collection? Yes if:
1024 * - no swap block at this index
1025 * - swap block is not contiguous
1026 * - we cross a physical disk boundry in the
1027 * stripe.
1029 if (
1030 biox && (biox_blkno + btoc(bufx->b_bcount) != blk ||
1031 ((biox_blkno ^ blk) & dmmax_mask)
1034 if (bp->b_cmd == BUF_CMD_READ) {
1035 ++mycpu->gd_cnt.v_swapin;
1036 mycpu->gd_cnt.v_swappgsin += btoc(bufx->b_bcount);
1037 } else {
1038 ++mycpu->gd_cnt.v_swapout;
1039 mycpu->gd_cnt.v_swappgsout += btoc(bufx->b_bcount);
1040 bufx->b_dirtyend = bufx->b_bcount;
1044 * Finished with this buf.
1046 KKASSERT(bufx->b_bcount != 0);
1047 if (bufx->b_cmd != BUF_CMD_READ)
1048 bufx->b_dirtyend = bufx->b_bcount;
1049 biox = NULL;
1050 bufx = NULL;
1054 * Add new swapblk to biox, instantiating biox if necessary.
1055 * Zero-fill reads are able to take a shortcut.
1057 if (blk == SWAPBLK_NONE) {
1059 * We can only get here if we are reading. Since
1060 * we are at splvm() we can safely modify b_resid,
1061 * even if chain ops are in progress.
1063 bzero(data, PAGE_SIZE);
1064 bp->b_resid -= PAGE_SIZE;
1065 } else {
1066 if (biox == NULL) {
1067 /* XXX chain count > 4, wait to <= 4 */
1069 bufx = getpbuf(NULL);
1070 biox = &bufx->b_bio1;
1071 cluster_append(nbio, bufx);
1072 bufx->b_flags |= (bufx->b_flags & B_ORDERED);
1073 bufx->b_cmd = bp->b_cmd;
1074 biox->bio_done = swap_chain_iodone;
1075 biox->bio_offset = (off_t)blk << PAGE_SHIFT;
1076 biox->bio_caller_info1.cluster_parent = nbio;
1077 biox_blkno = blk;
1078 bufx->b_bcount = 0;
1079 bufx->b_data = data;
1081 bufx->b_bcount += PAGE_SIZE;
1083 --count;
1084 ++start;
1085 data += PAGE_SIZE;
1087 crit_exit();
1090 * Flush out last buffer
1092 if (biox) {
1093 if (bufx->b_cmd == BUF_CMD_READ) {
1094 ++mycpu->gd_cnt.v_swapin;
1095 mycpu->gd_cnt.v_swappgsin += btoc(bufx->b_bcount);
1096 } else {
1097 ++mycpu->gd_cnt.v_swapout;
1098 mycpu->gd_cnt.v_swappgsout += btoc(bufx->b_bcount);
1099 bufx->b_dirtyend = bufx->b_bcount;
1101 KKASSERT(bufx->b_bcount);
1102 if (bufx->b_cmd != BUF_CMD_READ)
1103 bufx->b_dirtyend = bufx->b_bcount;
1104 /* biox, bufx = NULL */
1108 * Now initiate all the I/O. Be careful looping on our chain as
1109 * I/O's may complete while we are still initiating them.
1111 * If the request is a 100% sparse read no bios will be present
1112 * and we just biodone() the buffer.
1114 nbio->bio_caller_info2.cluster_tail = NULL;
1115 bufx = nbio->bio_caller_info1.cluster_head;
1117 if (bufx) {
1118 while (bufx) {
1119 biox = &bufx->b_bio1;
1120 BUF_KERNPROC(bufx);
1121 bufx = bufx->b_cluster_next;
1122 vn_strategy(swapdev_vp, biox);
1124 } else {
1125 biodone(bio);
1129 * Completion of the cluster will also call biodone_chain(nbio).
1130 * We never call biodone(nbio) so we don't have to worry about
1131 * setting up a bio_done callback. It's handled in the sub-IO.
1133 /**/
1136 static void
1137 swap_chain_iodone(struct bio *biox)
1139 struct buf **nextp;
1140 struct buf *bufx; /* chained sub-buffer */
1141 struct bio *nbio; /* parent nbio with chain glue */
1142 struct buf *bp; /* original bp associated with nbio */
1143 int chain_empty;
1145 bufx = biox->bio_buf;
1146 nbio = biox->bio_caller_info1.cluster_parent;
1147 bp = nbio->bio_buf;
1150 * Update the original buffer
1152 KKASSERT(bp != NULL);
1153 if (bufx->b_flags & B_ERROR) {
1154 atomic_set_int(&bufx->b_flags, B_ERROR);
1155 bp->b_error = bufx->b_error;
1156 } else if (bufx->b_resid != 0) {
1157 atomic_set_int(&bufx->b_flags, B_ERROR);
1158 bp->b_error = EINVAL;
1159 } else {
1160 atomic_subtract_int(&bp->b_resid, bufx->b_bcount);
1164 * Remove us from the chain.
1166 spin_lock_wr(&bp->b_lock.lk_spinlock);
1167 nextp = &nbio->bio_caller_info1.cluster_head;
1168 while (*nextp != bufx) {
1169 KKASSERT(*nextp != NULL);
1170 nextp = &(*nextp)->b_cluster_next;
1172 *nextp = bufx->b_cluster_next;
1173 chain_empty = (nbio->bio_caller_info1.cluster_head == NULL);
1174 spin_unlock_wr(&bp->b_lock.lk_spinlock);
1177 * Clean up bufx. If the chain is now empty we finish out
1178 * the parent. Note that we may be racing other completions
1179 * so we must use the chain_empty status from above.
1181 if (chain_empty) {
1182 if (bp->b_resid != 0 && !(bp->b_flags & B_ERROR)) {
1183 atomic_set_int(&bp->b_flags, B_ERROR);
1184 bp->b_error = EINVAL;
1186 biodone_chain(nbio);
1188 relpbuf(bufx, NULL);
1192 * SWAP_PAGER_GETPAGES() - bring page in from swap
1194 * The requested page may have to be brought in from swap. Calculate the
1195 * swap block and bring in additional pages if possible. All pages must
1196 * have contiguous swap block assignments and reside in the same object.
1198 * The caller has a single vm_object_pip_add() reference prior to
1199 * calling us and we should return with the same.
1201 * The caller has BUSY'd the page. We should return with (*mpp) left busy,
1202 * and any additinal pages unbusied.
1204 * If the caller encounters a PG_RAM page it will pass it to us even though
1205 * it may be valid and dirty. We cannot overwrite the page in this case!
1206 * The case is used to allow us to issue pure read-aheads.
1208 * NOTE! XXX This code does not entirely pipeline yet due to the fact that
1209 * the PG_RAM page is validated at the same time as mreq. What we
1210 * really need to do is issue a separate read-ahead pbuf.
1212 static int
1213 swap_pager_getpage(vm_object_t object, vm_page_t *mpp, int seqaccess)
1215 struct buf *bp;
1216 struct bio *bio;
1217 vm_page_t mreq;
1218 vm_page_t m;
1219 vm_offset_t kva;
1220 daddr_t blk;
1221 int i;
1222 int j;
1223 int raonly;
1224 vm_page_t marray[XIO_INTERNAL_PAGES];
1226 mreq = *mpp;
1228 if (mreq->object != object) {
1229 panic("swap_pager_getpages: object mismatch %p/%p",
1230 object,
1231 mreq->object
1236 * We don't want to overwrite a fully valid page as it might be
1237 * dirty. This case can occur when e.g. vm_fault hits a perfectly
1238 * valid page with PG_RAM set.
1240 * In this case we see if the next page is a suitable page-in
1241 * candidate and if it is we issue read-ahead. PG_RAM will be
1242 * set on the last page of the read-ahead to continue the pipeline.
1244 if (mreq->valid == VM_PAGE_BITS_ALL) {
1245 if (swap_burst_read == 0 || mreq->pindex + 1 >= object->size)
1246 return(VM_PAGER_OK);
1247 crit_enter();
1248 blk = swp_pager_meta_ctl(object, mreq->pindex + 1, 0);
1249 if (blk == SWAPBLK_NONE) {
1250 crit_exit();
1251 return(VM_PAGER_OK);
1253 m = vm_page_lookup(object, mreq->pindex + 1);
1254 if (m == NULL) {
1255 m = vm_page_alloc(object, mreq->pindex + 1,
1256 VM_ALLOC_QUICK);
1257 if (m == NULL) {
1258 crit_exit();
1259 return(VM_PAGER_OK);
1261 } else {
1262 if ((m->flags & PG_BUSY) || m->busy || m->valid) {
1263 crit_exit();
1264 return(VM_PAGER_OK);
1266 vm_page_unqueue_nowakeup(m);
1267 vm_page_busy(m);
1269 mreq = m;
1270 raonly = 1;
1271 crit_exit();
1272 } else {
1273 raonly = 0;
1277 * Try to block-read contiguous pages from swap if sequential,
1278 * otherwise just read one page. Contiguous pages from swap must
1279 * reside within a single device stripe because the I/O cannot be
1280 * broken up across multiple stripes.
1282 * Note that blk and iblk can be SWAPBLK_NONE but the loop is
1283 * set up such that the case(s) are handled implicitly.
1285 crit_enter();
1286 blk = swp_pager_meta_ctl(mreq->object, mreq->pindex, 0);
1287 marray[0] = mreq;
1289 for (i = 1; swap_burst_read &&
1290 i < XIO_INTERNAL_PAGES &&
1291 mreq->pindex + i < object->size; ++i) {
1292 daddr_t iblk;
1294 iblk = swp_pager_meta_ctl(object, mreq->pindex + i, 0);
1295 if (iblk != blk + i)
1296 break;
1297 if ((blk ^ iblk) & dmmax_mask)
1298 break;
1299 m = vm_page_lookup(object, mreq->pindex + i);
1300 if (m == NULL) {
1301 m = vm_page_alloc(object, mreq->pindex + i,
1302 VM_ALLOC_QUICK);
1303 if (m == NULL)
1304 break;
1305 } else {
1306 if ((m->flags & PG_BUSY) || m->busy || m->valid)
1307 break;
1308 vm_page_unqueue_nowakeup(m);
1309 vm_page_busy(m);
1311 marray[i] = m;
1313 if (i > 1)
1314 vm_page_flag_set(marray[i - 1], PG_RAM);
1316 crit_exit();
1319 * If mreq is the requested page and we have nothing to do return
1320 * VM_PAGER_FAIL. If raonly is set mreq is just another read-ahead
1321 * page and must be cleaned up.
1323 if (blk == SWAPBLK_NONE) {
1324 KKASSERT(i == 1);
1325 if (raonly) {
1326 vnode_pager_freepage(mreq);
1327 return(VM_PAGER_OK);
1328 } else {
1329 return(VM_PAGER_FAIL);
1334 * map our page(s) into kva for input
1336 bp = getpbuf(&nsw_rcount);
1337 bio = &bp->b_bio1;
1338 kva = (vm_offset_t) bp->b_kvabase;
1339 bcopy(marray, bp->b_xio.xio_pages, i * sizeof(vm_page_t));
1340 pmap_qenter(kva, bp->b_xio.xio_pages, i);
1342 bp->b_data = (caddr_t)kva;
1343 bp->b_bcount = PAGE_SIZE * i;
1344 bp->b_xio.xio_npages = i;
1345 bio->bio_done = swp_pager_async_iodone;
1346 bio->bio_offset = (off_t)blk << PAGE_SHIFT;
1347 bio->bio_caller_info1.index = SWBIO_READ;
1350 * Set index. If raonly set the index beyond the array so all
1351 * the pages are treated the same, otherwise the original mreq is
1352 * at index 0.
1354 if (raonly)
1355 bio->bio_driver_info = (void *)(intptr_t)i;
1356 else
1357 bio->bio_driver_info = (void *)(intptr_t)0;
1359 for (j = 0; j < i; ++j)
1360 vm_page_flag_set(bp->b_xio.xio_pages[j], PG_SWAPINPROG);
1362 mycpu->gd_cnt.v_swapin++;
1363 mycpu->gd_cnt.v_swappgsin += bp->b_xio.xio_npages;
1366 * We still hold the lock on mreq, and our automatic completion routine
1367 * does not remove it.
1369 vm_object_pip_add(object, bp->b_xio.xio_npages);
1372 * perform the I/O. NOTE!!! bp cannot be considered valid after
1373 * this point because we automatically release it on completion.
1374 * Instead, we look at the one page we are interested in which we
1375 * still hold a lock on even through the I/O completion.
1377 * The other pages in our m[] array are also released on completion,
1378 * so we cannot assume they are valid anymore either.
1380 bp->b_cmd = BUF_CMD_READ;
1381 BUF_KERNPROC(bp);
1382 vn_strategy(swapdev_vp, bio);
1385 * Wait for the page we want to complete. PG_SWAPINPROG is always
1386 * cleared on completion. If an I/O error occurs, SWAPBLK_NONE
1387 * is set in the meta-data.
1389 * If this is a read-ahead only we return immediately without
1390 * waiting for I/O.
1392 if (raonly)
1393 return(VM_PAGER_OK);
1396 * Read-ahead includes originally requested page case.
1398 crit_enter();
1399 while ((mreq->flags & PG_SWAPINPROG) != 0) {
1400 vm_page_flag_set(mreq, PG_WANTED | PG_REFERENCED);
1401 mycpu->gd_cnt.v_intrans++;
1402 if (tsleep(mreq, 0, "swread", hz*20)) {
1403 kprintf(
1404 "swap_pager: indefinite wait buffer: "
1405 " offset: %lld, size: %ld\n",
1406 (long long)bio->bio_offset,
1407 (long)bp->b_bcount
1411 crit_exit();
1414 * mreq is left bussied after completion, but all the other pages
1415 * are freed. If we had an unrecoverable read error the page will
1416 * not be valid.
1418 if (mreq->valid != VM_PAGE_BITS_ALL)
1419 return(VM_PAGER_ERROR);
1420 else
1421 return(VM_PAGER_OK);
1424 * A final note: in a low swap situation, we cannot deallocate swap
1425 * and mark a page dirty here because the caller is likely to mark
1426 * the page clean when we return, causing the page to possibly revert
1427 * to all-zero's later.
1432 * swap_pager_putpages:
1434 * Assign swap (if necessary) and initiate I/O on the specified pages.
1436 * We support both OBJT_DEFAULT and OBJT_SWAP objects. DEFAULT objects
1437 * are automatically converted to SWAP objects.
1439 * In a low memory situation we may block in vn_strategy(), but the new
1440 * vm_page reservation system coupled with properly written VFS devices
1441 * should ensure that no low-memory deadlock occurs. This is an area
1442 * which needs work.
1444 * The parent has N vm_object_pip_add() references prior to
1445 * calling us and will remove references for rtvals[] that are
1446 * not set to VM_PAGER_PEND. We need to remove the rest on I/O
1447 * completion.
1449 * The parent has soft-busy'd the pages it passes us and will unbusy
1450 * those whos rtvals[] entry is not set to VM_PAGER_PEND on return.
1451 * We need to unbusy the rest on I/O completion.
1453 void
1454 swap_pager_putpages(vm_object_t object, vm_page_t *m, int count,
1455 boolean_t sync, int *rtvals)
1457 int i;
1458 int n = 0;
1460 if (count && m[0]->object != object) {
1461 panic("swap_pager_getpages: object mismatch %p/%p",
1462 object,
1463 m[0]->object
1468 * Step 1
1470 * Turn object into OBJT_SWAP
1471 * check for bogus sysops
1472 * force sync if not pageout process
1474 if (object->type == OBJT_DEFAULT)
1475 swp_pager_meta_convert(object);
1477 if (curthread != pagethread)
1478 sync = TRUE;
1481 * Step 2
1483 * Update nsw parameters from swap_async_max sysctl values.
1484 * Do not let the sysop crash the machine with bogus numbers.
1487 if (swap_async_max != nsw_wcount_async_max) {
1488 int n;
1491 * limit range
1493 if ((n = swap_async_max) > nswbuf / 2)
1494 n = nswbuf / 2;
1495 if (n < 1)
1496 n = 1;
1497 swap_async_max = n;
1500 * Adjust difference ( if possible ). If the current async
1501 * count is too low, we may not be able to make the adjustment
1502 * at this time.
1504 crit_enter();
1505 n -= nsw_wcount_async_max;
1506 if (nsw_wcount_async + n >= 0) {
1507 nsw_wcount_async += n;
1508 nsw_wcount_async_max += n;
1509 wakeup(&nsw_wcount_async);
1511 crit_exit();
1515 * Step 3
1517 * Assign swap blocks and issue I/O. We reallocate swap on the fly.
1518 * The page is left dirty until the pageout operation completes
1519 * successfully.
1522 for (i = 0; i < count; i += n) {
1523 struct buf *bp;
1524 struct bio *bio;
1525 daddr_t blk;
1526 int j;
1529 * Maximum I/O size is limited by a number of factors.
1532 n = min(BLIST_MAX_ALLOC, count - i);
1533 n = min(n, nsw_cluster_max);
1535 crit_enter();
1538 * Get biggest block of swap we can. If we fail, fall
1539 * back and try to allocate a smaller block. Don't go
1540 * overboard trying to allocate space if it would overly
1541 * fragment swap.
1543 while (
1544 (blk = swp_pager_getswapspace(object, n)) == SWAPBLK_NONE &&
1545 n > 4
1547 n >>= 1;
1549 if (blk == SWAPBLK_NONE) {
1550 for (j = 0; j < n; ++j)
1551 rtvals[i+j] = VM_PAGER_FAIL;
1552 crit_exit();
1553 continue;
1557 * The I/O we are constructing cannot cross a physical
1558 * disk boundry in the swap stripe. Note: we are still
1559 * at splvm().
1561 if ((blk ^ (blk + n)) & dmmax_mask) {
1562 j = ((blk + dmmax) & dmmax_mask) - blk;
1563 swp_pager_freeswapspace(object, blk + j, n - j);
1564 n = j;
1568 * All I/O parameters have been satisfied, build the I/O
1569 * request and assign the swap space.
1571 if (sync == TRUE)
1572 bp = getpbuf(&nsw_wcount_sync);
1573 else
1574 bp = getpbuf(&nsw_wcount_async);
1575 bio = &bp->b_bio1;
1577 pmap_qenter((vm_offset_t)bp->b_data, &m[i], n);
1579 bp->b_bcount = PAGE_SIZE * n;
1580 bio->bio_offset = (off_t)blk << PAGE_SHIFT;
1582 for (j = 0; j < n; ++j) {
1583 vm_page_t mreq = m[i+j];
1585 swp_pager_meta_build(mreq->object, mreq->pindex,
1586 blk + j);
1587 if (object->type == OBJT_SWAP)
1588 vm_page_dirty(mreq);
1589 rtvals[i+j] = VM_PAGER_OK;
1591 vm_page_flag_set(mreq, PG_SWAPINPROG);
1592 bp->b_xio.xio_pages[j] = mreq;
1594 bp->b_xio.xio_npages = n;
1596 mycpu->gd_cnt.v_swapout++;
1597 mycpu->gd_cnt.v_swappgsout += bp->b_xio.xio_npages;
1599 crit_exit();
1601 bp->b_dirtyoff = 0; /* req'd for NFS */
1602 bp->b_dirtyend = bp->b_bcount; /* req'd for NFS */
1603 bp->b_cmd = BUF_CMD_WRITE;
1604 bio->bio_caller_info1.index = SWBIO_WRITE;
1607 * asynchronous
1609 if (sync == FALSE) {
1610 bio->bio_done = swp_pager_async_iodone;
1611 BUF_KERNPROC(bp);
1612 vn_strategy(swapdev_vp, bio);
1614 for (j = 0; j < n; ++j)
1615 rtvals[i+j] = VM_PAGER_PEND;
1616 continue;
1620 * Issue synchrnously.
1622 * Wait for the sync I/O to complete, then update rtvals.
1623 * We just set the rtvals[] to VM_PAGER_PEND so we can call
1624 * our async completion routine at the end, thus avoiding a
1625 * double-free.
1627 bio->bio_caller_info1.index |= SWBIO_SYNC;
1628 bio->bio_done = biodone_sync;
1629 bio->bio_flags |= BIO_SYNC;
1630 vn_strategy(swapdev_vp, bio);
1631 biowait(bio, "swwrt");
1633 for (j = 0; j < n; ++j)
1634 rtvals[i+j] = VM_PAGER_PEND;
1637 * Now that we are through with the bp, we can call the
1638 * normal async completion, which frees everything up.
1640 swp_pager_async_iodone(bio);
1644 void
1645 swap_pager_newswap(void)
1647 swp_sizecheck();
1651 * swp_pager_async_iodone:
1653 * Completion routine for asynchronous reads and writes from/to swap.
1654 * Also called manually by synchronous code to finish up a bp.
1656 * For READ operations, the pages are PG_BUSY'd. For WRITE operations,
1657 * the pages are vm_page_t->busy'd. For READ operations, we PG_BUSY
1658 * unbusy all pages except the 'main' request page. For WRITE
1659 * operations, we vm_page_t->busy'd unbusy all pages ( we can do this
1660 * because we marked them all VM_PAGER_PEND on return from putpages ).
1662 * This routine may not block.
1664 static void
1665 swp_pager_async_iodone(struct bio *bio)
1667 struct buf *bp = bio->bio_buf;
1668 vm_object_t object = NULL;
1669 int i;
1670 int *nswptr;
1673 * report error
1675 if (bp->b_flags & B_ERROR) {
1676 kprintf(
1677 "swap_pager: I/O error - %s failed; offset %lld,"
1678 "size %ld, error %d\n",
1679 ((bio->bio_caller_info1.index & SWBIO_READ) ?
1680 "pagein" : "pageout"),
1681 (long long)bio->bio_offset,
1682 (long)bp->b_bcount,
1683 bp->b_error
1688 * set object, raise to splvm().
1690 if (bp->b_xio.xio_npages)
1691 object = bp->b_xio.xio_pages[0]->object;
1692 crit_enter();
1695 * remove the mapping for kernel virtual
1697 pmap_qremove((vm_offset_t)bp->b_data, bp->b_xio.xio_npages);
1700 * cleanup pages. If an error occurs writing to swap, we are in
1701 * very serious trouble. If it happens to be a disk error, though,
1702 * we may be able to recover by reassigning the swap later on. So
1703 * in this case we remove the m->swapblk assignment for the page
1704 * but do not free it in the rlist. The errornous block(s) are thus
1705 * never reallocated as swap. Redirty the page and continue.
1707 for (i = 0; i < bp->b_xio.xio_npages; ++i) {
1708 vm_page_t m = bp->b_xio.xio_pages[i];
1710 if (bp->b_flags & B_ERROR) {
1712 * If an error occurs I'd love to throw the swapblk
1713 * away without freeing it back to swapspace, so it
1714 * can never be used again. But I can't from an
1715 * interrupt.
1718 if (bio->bio_caller_info1.index & SWBIO_READ) {
1720 * When reading, reqpage needs to stay
1721 * locked for the parent, but all other
1722 * pages can be freed. We still want to
1723 * wakeup the parent waiting on the page,
1724 * though. ( also: pg_reqpage can be -1 and
1725 * not match anything ).
1727 * We have to wake specifically requested pages
1728 * up too because we cleared PG_SWAPINPROG and
1729 * someone may be waiting for that.
1731 * NOTE: for reads, m->dirty will probably
1732 * be overridden by the original caller of
1733 * getpages so don't play cute tricks here.
1735 * NOTE: We can't actually free the page from
1736 * here, because this is an interrupt. It
1737 * is not legal to mess with object->memq
1738 * from an interrupt. Deactivate the page
1739 * instead.
1742 m->valid = 0;
1743 vm_page_flag_clear(m, PG_ZERO);
1744 vm_page_flag_clear(m, PG_SWAPINPROG);
1747 * bio_driver_info holds the requested page
1748 * index.
1750 if (i != (int)(intptr_t)bio->bio_driver_info) {
1751 vm_page_deactivate(m);
1752 vm_page_wakeup(m);
1753 } else {
1754 vm_page_flash(m);
1757 * If i == bp->b_pager.pg_reqpage, do not wake
1758 * the page up. The caller needs to.
1760 } else {
1762 * If a write error occurs remove the swap
1763 * assignment (note that PG_SWAPPED may or
1764 * may not be set depending on prior activity).
1766 * Re-dirty OBJT_SWAP pages as there is no
1767 * other backing store, we can't throw the
1768 * page away.
1770 * Non-OBJT_SWAP pages (aka swapcache) must
1771 * not be dirtied since they may not have
1772 * been dirty in the first place, and they
1773 * do have backing store (the vnode).
1775 swp_pager_meta_ctl(m->object, m->pindex,
1776 SWM_FREE);
1777 vm_page_flag_clear(m, PG_SWAPPED);
1778 if (m->object->type == OBJT_SWAP) {
1779 vm_page_dirty(m);
1780 vm_page_activate(m);
1782 vm_page_flag_clear(m, PG_SWAPINPROG);
1783 vm_page_io_finish(m);
1785 } else if (bio->bio_caller_info1.index & SWBIO_READ) {
1787 * NOTE: for reads, m->dirty will probably be
1788 * overridden by the original caller of getpages so
1789 * we cannot set them in order to free the underlying
1790 * swap in a low-swap situation. I don't think we'd
1791 * want to do that anyway, but it was an optimization
1792 * that existed in the old swapper for a time before
1793 * it got ripped out due to precisely this problem.
1795 * clear PG_ZERO in page.
1797 * If not the requested page then deactivate it.
1799 * Note that the requested page, reqpage, is left
1800 * busied, but we still have to wake it up. The
1801 * other pages are released (unbusied) by
1802 * vm_page_wakeup(). We do not set reqpage's
1803 * valid bits here, it is up to the caller.
1807 * NOTE: can't call pmap_clear_modify(m) from an
1808 * interrupt thread, the pmap code may have to map
1809 * non-kernel pmaps and currently asserts the case.
1811 /*pmap_clear_modify(m);*/
1812 m->valid = VM_PAGE_BITS_ALL;
1813 vm_page_undirty(m);
1814 vm_page_flag_clear(m, PG_ZERO | PG_SWAPINPROG);
1815 vm_page_flag_set(m, PG_SWAPPED);
1818 * We have to wake specifically requested pages
1819 * up too because we cleared PG_SWAPINPROG and
1820 * could be waiting for it in getpages. However,
1821 * be sure to not unbusy getpages specifically
1822 * requested page - getpages expects it to be
1823 * left busy.
1825 * bio_driver_info holds the requested page
1827 if (i != (int)(intptr_t)bio->bio_driver_info) {
1828 vm_page_deactivate(m);
1829 vm_page_wakeup(m);
1830 } else {
1831 vm_page_flash(m);
1833 } else {
1835 * Mark the page clean but do not mess with the
1836 * pmap-layer's modified state. That state should
1837 * also be clear since the caller protected the
1838 * page VM_PROT_READ, but allow the case.
1840 * We are in an interrupt, avoid pmap operations.
1842 * If we have a severe page deficit, deactivate the
1843 * page. Do not try to cache it (which would also
1844 * involve a pmap op), because the page might still
1845 * be read-heavy.
1847 * When using the swap to cache clean vnode pages
1848 * we do not mess with the page dirty bits.
1850 if (m->object->type == OBJT_SWAP)
1851 vm_page_undirty(m);
1852 vm_page_flag_clear(m, PG_SWAPINPROG);
1853 vm_page_flag_set(m, PG_SWAPPED);
1854 vm_page_io_finish(m);
1855 if (vm_page_count_severe())
1856 vm_page_deactivate(m);
1857 #if 0
1858 if (!vm_page_count_severe() || !vm_page_try_to_cache(m))
1859 vm_page_protect(m, VM_PROT_READ);
1860 #endif
1865 * adjust pip. NOTE: the original parent may still have its own
1866 * pip refs on the object.
1869 if (object)
1870 vm_object_pip_wakeupn(object, bp->b_xio.xio_npages);
1873 * Release the physical I/O buffer.
1875 * NOTE: Due to synchronous operations in the write case b_cmd may
1876 * already be set to BUF_CMD_DONE and BIO_SYNC may have already
1877 * been cleared.
1879 if (bio->bio_caller_info1.index & SWBIO_READ)
1880 nswptr = &nsw_rcount;
1881 else if (bio->bio_caller_info1.index & SWBIO_SYNC)
1882 nswptr = &nsw_wcount_sync;
1883 else
1884 nswptr = &nsw_wcount_async;
1885 bp->b_cmd = BUF_CMD_DONE;
1886 relpbuf(bp, nswptr);
1887 crit_exit();
1890 /************************************************************************
1891 * SWAP META DATA *
1892 ************************************************************************
1894 * These routines manipulate the swap metadata stored in the
1895 * OBJT_SWAP object. All swp_*() routines must be called at
1896 * splvm() because swap can be freed up by the low level vm_page
1897 * code which might be called from interrupts beyond what splbio() covers.
1899 * Swap metadata is implemented with a global hash and not directly
1900 * linked into the object. Instead the object simply contains
1901 * appropriate tracking counters.
1905 * Lookup the swblock containing the specified swap block index.
1907 static __inline
1908 struct swblock *
1909 swp_pager_lookup(vm_object_t object, vm_pindex_t index)
1911 index &= ~SWAP_META_MASK;
1912 return (RB_LOOKUP(swblock_rb_tree, &object->swblock_root, index));
1916 * Remove a swblock from the RB tree.
1918 static __inline
1919 void
1920 swp_pager_remove(vm_object_t object, struct swblock *swap)
1922 RB_REMOVE(swblock_rb_tree, &object->swblock_root, swap);
1926 * Convert default object to swap object if necessary
1928 static void
1929 swp_pager_meta_convert(vm_object_t object)
1931 if (object->type == OBJT_DEFAULT) {
1932 object->type = OBJT_SWAP;
1933 KKASSERT(object->swblock_count == 0);
1938 * SWP_PAGER_META_BUILD() - add swap block to swap meta data for object
1940 * We first convert the object to a swap object if it is a default
1941 * object. Vnode objects do not need to be converted.
1943 * The specified swapblk is added to the object's swap metadata. If
1944 * the swapblk is not valid, it is freed instead. Any previously
1945 * assigned swapblk is freed.
1947 static void
1948 swp_pager_meta_build(vm_object_t object, vm_pindex_t index, daddr_t swapblk)
1950 struct swblock *swap;
1951 struct swblock *oswap;
1953 KKASSERT(swapblk != SWAPBLK_NONE);
1956 * Convert object if necessary
1958 if (object->type == OBJT_DEFAULT)
1959 swp_pager_meta_convert(object);
1962 * Locate swblock. If not found create, but if we aren't adding
1963 * anything just return. If we run out of space in the map we wait
1964 * and, since the hash table may have changed, retry.
1966 retry:
1967 swap = swp_pager_lookup(object, index);
1969 if (swap == NULL) {
1970 int i;
1972 swap = zalloc(swap_zone);
1973 if (swap == NULL) {
1974 vm_wait(0);
1975 goto retry;
1977 swap->swb_index = index & ~SWAP_META_MASK;
1978 swap->swb_count = 0;
1980 ++object->swblock_count;
1982 for (i = 0; i < SWAP_META_PAGES; ++i)
1983 swap->swb_pages[i] = SWAPBLK_NONE;
1984 oswap = RB_INSERT(swblock_rb_tree, &object->swblock_root, swap);
1985 KKASSERT(oswap == NULL);
1989 * Delete prior contents of metadata
1992 index &= SWAP_META_MASK;
1994 if (swap->swb_pages[index] != SWAPBLK_NONE) {
1995 swp_pager_freeswapspace(object, swap->swb_pages[index], 1);
1996 --swap->swb_count;
2000 * Enter block into metadata
2002 swap->swb_pages[index] = swapblk;
2003 if (swapblk != SWAPBLK_NONE)
2004 ++swap->swb_count;
2008 * SWP_PAGER_META_FREE() - free a range of blocks in the object's swap metadata
2010 * The requested range of blocks is freed, with any associated swap
2011 * returned to the swap bitmap.
2013 * This routine will free swap metadata structures as they are cleaned
2014 * out. This routine does *NOT* operate on swap metadata associated
2015 * with resident pages.
2017 * This routine must be called at splvm()
2019 static int swp_pager_meta_free_callback(struct swblock *swb, void *data);
2021 static void
2022 swp_pager_meta_free(vm_object_t object, vm_pindex_t index, vm_pindex_t count)
2024 struct swfreeinfo info;
2027 * Nothing to do
2029 if (object->swblock_count == 0) {
2030 KKASSERT(RB_EMPTY(&object->swblock_root));
2031 return;
2033 if (count == 0)
2034 return;
2037 * Setup for RB tree scan. Note that the pindex range can be huge
2038 * due to the 64 bit page index space so we cannot safely iterate.
2040 info.object = object;
2041 info.basei = index & ~SWAP_META_MASK;
2042 info.begi = index;
2043 info.endi = index + count - 1;
2044 swblock_rb_tree_RB_SCAN(&object->swblock_root, rb_swblock_scancmp,
2045 swp_pager_meta_free_callback, &info);
2048 static
2050 swp_pager_meta_free_callback(struct swblock *swap, void *data)
2052 struct swfreeinfo *info = data;
2053 vm_object_t object = info->object;
2054 int index;
2055 int eindex;
2058 * Figure out the range within the swblock. The wider scan may
2059 * return edge-case swap blocks when the start and/or end points
2060 * are in the middle of a block.
2062 if (swap->swb_index < info->begi)
2063 index = (int)info->begi & SWAP_META_MASK;
2064 else
2065 index = 0;
2067 if (swap->swb_index + SWAP_META_PAGES > info->endi)
2068 eindex = (int)info->endi & SWAP_META_MASK;
2069 else
2070 eindex = SWAP_META_MASK;
2073 * Scan and free the blocks. The loop terminates early
2074 * if (swap) runs out of blocks and could be freed.
2076 while (index <= eindex) {
2077 daddr_t v = swap->swb_pages[index];
2079 if (v != SWAPBLK_NONE) {
2080 swp_pager_freeswapspace(object, v, 1);
2081 swap->swb_pages[index] = SWAPBLK_NONE;
2082 if (--swap->swb_count == 0) {
2083 swp_pager_remove(object, swap);
2084 zfree(swap_zone, swap);
2085 --object->swblock_count;
2086 break;
2089 ++index;
2091 /* swap may be invalid here due to zfree above */
2092 return(0);
2096 * SWP_PAGER_META_FREE_ALL() - destroy all swap metadata associated with object
2098 * This routine locates and destroys all swap metadata associated with
2099 * an object.
2101 * This routine must be called at splvm()
2103 static void
2104 swp_pager_meta_free_all(vm_object_t object)
2106 struct swblock *swap;
2107 int i;
2109 while ((swap = RB_ROOT(&object->swblock_root)) != NULL) {
2110 swp_pager_remove(object, swap);
2111 for (i = 0; i < SWAP_META_PAGES; ++i) {
2112 daddr_t v = swap->swb_pages[i];
2113 if (v != SWAPBLK_NONE) {
2114 --swap->swb_count;
2115 swp_pager_freeswapspace(object, v, 1);
2118 if (swap->swb_count != 0)
2119 panic("swap_pager_meta_free_all: swb_count != 0");
2120 zfree(swap_zone, swap);
2121 --object->swblock_count;
2123 KKASSERT(object->swblock_count == 0);
2127 * SWP_PAGER_METACTL() - misc control of swap and vm_page_t meta data.
2129 * This routine is capable of looking up, popping, or freeing
2130 * swapblk assignments in the swap meta data or in the vm_page_t.
2131 * The routine typically returns the swapblk being looked-up, or popped,
2132 * or SWAPBLK_NONE if the block was freed, or SWAPBLK_NONE if the block
2133 * was invalid. This routine will automatically free any invalid
2134 * meta-data swapblks.
2136 * It is not possible to store invalid swapblks in the swap meta data
2137 * (other then a literal 'SWAPBLK_NONE'), so we don't bother checking.
2139 * When acting on a busy resident page and paging is in progress, we
2140 * have to wait until paging is complete but otherwise can act on the
2141 * busy page.
2143 * This routine must be called at splvm().
2145 * SWM_FREE remove and free swap block from metadata
2146 * SWM_POP remove from meta data but do not free.. pop it out
2148 static daddr_t
2149 swp_pager_meta_ctl(vm_object_t object, vm_pindex_t index, int flags)
2151 struct swblock *swap;
2152 daddr_t r1;
2154 if (object->swblock_count == 0)
2155 return(SWAPBLK_NONE);
2157 r1 = SWAPBLK_NONE;
2158 swap = swp_pager_lookup(object, index);
2160 if (swap != NULL) {
2161 index &= SWAP_META_MASK;
2162 r1 = swap->swb_pages[index];
2164 if (r1 != SWAPBLK_NONE) {
2165 if (flags & SWM_FREE) {
2166 swp_pager_freeswapspace(object, r1, 1);
2167 r1 = SWAPBLK_NONE;
2169 if (flags & (SWM_FREE|SWM_POP)) {
2170 swap->swb_pages[index] = SWAPBLK_NONE;
2171 if (--swap->swb_count == 0) {
2172 swp_pager_remove(object, swap);
2173 zfree(swap_zone, swap);
2174 --object->swblock_count;
2179 return(r1);