1/*-
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.
7 *
8 * This code is derived from software contributed to Berkeley by
9 * the Systems Programming Group of the University of Utah Computer
10 * Science Department.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
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.
27 *
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
38 * SUCH DAMAGE.
39 *
40 * New Swap System
41 * Matthew Dillon
42 *
43 * Radix Bitmap 'blists'.
44 *
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.
48 *
49 * Features:
50 *
51 * - on the fly reallocation of swap during putpages. The new system
52 * does not try to keep previously allocated swap blocks for dirty
53 * pages.
54 *
55 * - on the fly deallocation of swap
56 *
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
61 * or renamed.
62 *
63 * from: Utah $Hdr: swap_pager.c 1.4 91/04/30$
64 *
65 * @(#)swap_pager.c 8.9 (Berkeley) 3/21/94
66 * @(#)vm_swap.c 8.5 (Berkeley) 2/17/94
67 */
68
69#include <sys/cdefs.h>
70__FBSDID("$FreeBSD: head/sys/vm/swap_pager.c 164033 2006-11-06 13:42:10Z rwatson $");
71
72#include "opt_mac.h"
73#include "opt_swap.h"
74#include "opt_vm.h"
75
76#include <sys/param.h>
77#include <sys/systm.h>
78#include <sys/conf.h>
79#include <sys/kernel.h>
80#include <sys/priv.h>
81#include <sys/proc.h>
82#include <sys/bio.h>
83#include <sys/buf.h>
84#include <sys/disk.h>
85#include <sys/fcntl.h>
86#include <sys/mount.h>
87#include <sys/namei.h>
88#include <sys/vnode.h>
89#include <sys/malloc.h>
90#include <sys/sysctl.h>
91#include <sys/sysproto.h>
92#include <sys/blist.h>
93#include <sys/lock.h>
94#include <sys/sx.h>
95#include <sys/vmmeter.h>
96
97#include <security/mac/mac_framework.h>
98
99#include <vm/vm.h>
100#include <vm/pmap.h>
101#include <vm/vm_map.h>
102#include <vm/vm_kern.h>
103#include <vm/vm_object.h>
104#include <vm/vm_page.h>
105#include <vm/vm_pager.h>
106#include <vm/vm_pageout.h>
107#include <vm/vm_param.h>
108#include <vm/swap_pager.h>
109#include <vm/vm_extern.h>
110#include <vm/uma.h>
111
112#include <geom/geom.h>
113
114/*
115 * SWB_NPAGES must be a power of 2. It may be set to 1, 2, 4, 8, or 16
116 * pages per allocation. We recommend you stick with the default of 8.
117 * The 16-page limit is due to the radix code (kern/subr_blist.c).
118 */
119#ifndef MAX_PAGEOUT_CLUSTER
120#define MAX_PAGEOUT_CLUSTER 16
121#endif
122
123#if !defined(SWB_NPAGES)
124#define SWB_NPAGES MAX_PAGEOUT_CLUSTER
125#endif
126
127/*
128 * Piecemeal swap metadata structure. Swap is stored in a radix tree.
129 *
130 * If SWB_NPAGES is 8 and sizeof(char *) == sizeof(daddr_t), our radix
131 * is basically 8. Assuming PAGE_SIZE == 4096, one tree level represents
132 * 32K worth of data, two levels represent 256K, three levels represent
133 * 2 MBytes. This is acceptable.
134 *
135 * Overall memory utilization is about the same as the old swap structure.
136 */
137#define SWCORRECT(n) (sizeof(void *) * (n) / sizeof(daddr_t))
138#define SWAP_META_PAGES (SWB_NPAGES * 2)
139#define SWAP_META_MASK (SWAP_META_PAGES - 1)
140
141typedef int32_t swblk_t; /*
142 * swap offset. This is the type used to
143 * address the "virtual swap device" and
144 * therefore the maximum swap space is
145 * 2^32 pages.
146 */
147
148struct swdevt;
149typedef void sw_strategy_t(struct buf *bp, struct swdevt *sw);
150typedef void sw_close_t(struct thread *td, struct swdevt *sw);
151
152/*
153 * Swap device table
154 */
155struct swdevt {
156 int sw_flags;
157 int sw_nblks;
158 int sw_used;
159 dev_t sw_dev;
160 struct vnode *sw_vp;
161 void *sw_id;
162 swblk_t sw_first;
163 swblk_t sw_end;
164 struct blist *sw_blist;
165 TAILQ_ENTRY(swdevt) sw_list;
166 sw_strategy_t *sw_strategy;
167 sw_close_t *sw_close;
168};
169
170#define SW_CLOSING 0x04
171
172struct swblock {
173 struct swblock *swb_hnext;
174 vm_object_t swb_object;
175 vm_pindex_t swb_index;
176 int swb_count;
177 daddr_t swb_pages[SWAP_META_PAGES];
178};
179
180static struct mtx sw_dev_mtx;
181static TAILQ_HEAD(, swdevt) swtailq = TAILQ_HEAD_INITIALIZER(swtailq);
182static struct swdevt *swdevhd; /* Allocate from here next */
183static int nswapdev; /* Number of swap devices */
184int swap_pager_avail;
185static int swdev_syscall_active = 0; /* serialize swap(on|off) */
186
187static void swapdev_strategy(struct buf *, struct swdevt *sw);
188
189#define SWM_FREE 0x02 /* free, period */
190#define SWM_POP 0x04 /* pop out */
191
192int swap_pager_full = 2; /* swap space exhaustion (task killing) */
193static int swap_pager_almost_full = 1; /* swap space exhaustion (w/hysteresis)*/
194static int nsw_rcount; /* free read buffers */
195static int nsw_wcount_sync; /* limit write buffers / synchronous */
196static int nsw_wcount_async; /* limit write buffers / asynchronous */
197static int nsw_wcount_async_max;/* assigned maximum */
198static int nsw_cluster_max; /* maximum VOP I/O allowed */
199
200static struct swblock **swhash;
201static int swhash_mask;
202static struct mtx swhash_mtx;
203
204static int swap_async_max = 4; /* maximum in-progress async I/O's */
205static struct sx sw_alloc_sx;
206
207
208SYSCTL_INT(_vm, OID_AUTO, swap_async_max,
209 CTLFLAG_RW, &swap_async_max, 0, "Maximum running async swap ops");
210
211/*
212 * "named" and "unnamed" anon region objects. Try to reduce the overhead
213 * of searching a named list by hashing it just a little.
214 */
215
216#define NOBJLISTS 8
217
218#define NOBJLIST(handle) \
219 (&swap_pager_object_list[((int)(intptr_t)handle >> 4) & (NOBJLISTS-1)])
220
221static struct mtx sw_alloc_mtx; /* protect list manipulation */
222static struct pagerlst swap_pager_object_list[NOBJLISTS];
223static uma_zone_t swap_zone;
224static struct vm_object swap_zone_obj;
225
226/*
227 * pagerops for OBJT_SWAP - "swap pager". Some ops are also global procedure
228 * calls hooked from other parts of the VM system and do not appear here.
229 * (see vm/swap_pager.h).
230 */
231static vm_object_t
232 swap_pager_alloc(void *handle, vm_ooffset_t size,
233 vm_prot_t prot, vm_ooffset_t offset);
234static void swap_pager_dealloc(vm_object_t object);
235static int swap_pager_getpages(vm_object_t, vm_page_t *, int, int);
236static void swap_pager_putpages(vm_object_t, vm_page_t *, int, boolean_t, int *);
237static boolean_t
238 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before, int *after);
239static void swap_pager_init(void);
240static void swap_pager_unswapped(vm_page_t);
241static void swap_pager_swapoff(struct swdevt *sp);
242
243struct pagerops swappagerops = {
244 .pgo_init = swap_pager_init, /* early system initialization of pager */
245 .pgo_alloc = swap_pager_alloc, /* allocate an OBJT_SWAP object */
246 .pgo_dealloc = swap_pager_dealloc, /* deallocate an OBJT_SWAP object */
247 .pgo_getpages = swap_pager_getpages, /* pagein */
248 .pgo_putpages = swap_pager_putpages, /* pageout */
249 .pgo_haspage = swap_pager_haspage, /* get backing store status for page */
250 .pgo_pageunswapped = swap_pager_unswapped, /* remove swap related to page */
251};
252
253/*
254 * dmmax is in page-sized chunks with the new swap system. It was
255 * dev-bsized chunks in the old. dmmax is always a power of 2.
256 *
257 * swap_*() routines are externally accessible. swp_*() routines are
258 * internal.
259 */
260static int dmmax;
261static int nswap_lowat = 128; /* in pages, swap_pager_almost_full warn */
262static int nswap_hiwat = 512; /* in pages, swap_pager_almost_full warn */
263
264SYSCTL_INT(_vm, OID_AUTO, dmmax,
265 CTLFLAG_RD, &dmmax, 0, "Maximum size of a swap block");
266
267static void swp_sizecheck(void);
268static void swp_pager_async_iodone(struct buf *bp);
269static int swapongeom(struct thread *, struct vnode *);
270static int swaponvp(struct thread *, struct vnode *, u_long);
271static int swapoff_one(struct swdevt *sp, struct thread *td);
272
273/*
274 * Swap bitmap functions
275 */
276static void swp_pager_freeswapspace(daddr_t blk, int npages);
277static daddr_t swp_pager_getswapspace(int npages);
278
279/*
280 * Metadata functions
281 */
282static struct swblock **swp_pager_hash(vm_object_t object, vm_pindex_t index);
283static void swp_pager_meta_build(vm_object_t, vm_pindex_t, daddr_t);
284static void swp_pager_meta_free(vm_object_t, vm_pindex_t, daddr_t);
285static void swp_pager_meta_free_all(vm_object_t);
286static daddr_t swp_pager_meta_ctl(vm_object_t, vm_pindex_t, int);
287
288/*
289 * SWP_SIZECHECK() - update swap_pager_full indication
290 *
291 * update the swap_pager_almost_full indication and warn when we are
292 * about to run out of swap space, using lowat/hiwat hysteresis.
293 *
294 * Clear swap_pager_full ( task killing ) indication when lowat is met.
295 *
296 * No restrictions on call
297 * This routine may not block.
298 * This routine must be called at splvm()
299 */
300static void
301swp_sizecheck(void)
302{
303
304 if (swap_pager_avail < nswap_lowat) {
305 if (swap_pager_almost_full == 0) {
306 printf("swap_pager: out of swap space\n");
307 swap_pager_almost_full = 1;
308 }
309 } else {
310 swap_pager_full = 0;
311 if (swap_pager_avail > nswap_hiwat)
312 swap_pager_almost_full = 0;
313 }
314}
315
316/*
317 * SWP_PAGER_HASH() - hash swap meta data
318 *
319 * This is an helper function which hashes the swapblk given
320 * the object and page index. It returns a pointer to a pointer
321 * to the object, or a pointer to a NULL pointer if it could not
322 * find a swapblk.
323 *
324 * This routine must be called at splvm().
325 */
326static struct swblock **
327swp_pager_hash(vm_object_t object, vm_pindex_t index)
328{
329 struct swblock **pswap;
330 struct swblock *swap;
331
332 index &= ~(vm_pindex_t)SWAP_META_MASK;
333 pswap = &swhash[(index ^ (int)(intptr_t)object) & swhash_mask];
334 while ((swap = *pswap) != NULL) {
335 if (swap->swb_object == object &&
336 swap->swb_index == index
337 ) {
338 break;
339 }
340 pswap = &swap->swb_hnext;
341 }
342 return (pswap);
343}
344
345/*
346 * SWAP_PAGER_INIT() - initialize the swap pager!
347 *
348 * Expected to be started from system init. NOTE: This code is run
349 * before much else so be careful what you depend on. Most of the VM
350 * system has yet to be initialized at this point.
351 */
352static void
353swap_pager_init(void)
354{
355 /*
356 * Initialize object lists
357 */
358 int i;
359
360 for (i = 0; i < NOBJLISTS; ++i)
361 TAILQ_INIT(&swap_pager_object_list[i]);
362 mtx_init(&sw_alloc_mtx, "swap_pager list", NULL, MTX_DEF);
363 mtx_init(&sw_dev_mtx, "swapdev", NULL, MTX_DEF);
364
365 /*
366 * Device Stripe, in PAGE_SIZE'd blocks
367 */
368 dmmax = SWB_NPAGES * 2;
369}
370
371/*
372 * SWAP_PAGER_SWAP_INIT() - swap pager initialization from pageout process
373 *
374 * Expected to be started from pageout process once, prior to entering
375 * its main loop.
376 */
377void
378swap_pager_swap_init(void)
379{
380 int n, n2;
381
382 /*
383 * Number of in-transit swap bp operations. Don't
384 * exhaust the pbufs completely. Make sure we
385 * initialize workable values (0 will work for hysteresis
386 * but it isn't very efficient).
387 *
388 * The nsw_cluster_max is constrained by the bp->b_pages[]
389 * array (MAXPHYS/PAGE_SIZE) and our locally defined
390 * MAX_PAGEOUT_CLUSTER. Also be aware that swap ops are
391 * constrained by the swap device interleave stripe size.
392 *
393 * Currently we hardwire nsw_wcount_async to 4. This limit is
394 * designed to prevent other I/O from having high latencies due to
395 * our pageout I/O. The value 4 works well for one or two active swap
396 * devices but is probably a little low if you have more. Even so,
397 * a higher value would probably generate only a limited improvement
398 * with three or four active swap devices since the system does not
399 * typically have to pageout at extreme bandwidths. We will want
400 * at least 2 per swap devices, and 4 is a pretty good value if you
401 * have one NFS swap device due to the command/ack latency over NFS.
402 * So it all works out pretty well.
403 */
404 nsw_cluster_max = min((MAXPHYS/PAGE_SIZE), MAX_PAGEOUT_CLUSTER);
405
406 mtx_lock(&pbuf_mtx);
407 nsw_rcount = (nswbuf + 1) / 2;
408 nsw_wcount_sync = (nswbuf + 3) / 4;
409 nsw_wcount_async = 4;
410 nsw_wcount_async_max = nsw_wcount_async;
411 mtx_unlock(&pbuf_mtx);
412
413 /*
414 * Initialize our zone. Right now I'm just guessing on the number
415 * we need based on the number of pages in the system. Each swblock
416 * can hold 16 pages, so this is probably overkill. This reservation
417 * is typically limited to around 32MB by default.
418 */
419 n = cnt.v_page_count / 2;
420 if (maxswzone && n > maxswzone / sizeof(struct swblock))
421 n = maxswzone / sizeof(struct swblock);
422 n2 = n;
423 swap_zone = uma_zcreate("SWAPMETA", sizeof(struct swblock), NULL, NULL,
424 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
425 if (swap_zone == NULL)
426 panic("failed to create swap_zone.");
427 do {
428 if (uma_zone_set_obj(swap_zone, &swap_zone_obj, n))
429 break;
430 /*
431 * if the allocation failed, try a zone two thirds the
432 * size of the previous attempt.
433 */
434 n -= ((n + 2) / 3);
435 } while (n > 0);
436 if (n2 != n)
437 printf("Swap zone entries reduced from %d to %d.\n", n2, n);
438 n2 = n;
439
440 /*
441 * Initialize our meta-data hash table. The swapper does not need to
442 * be quite as efficient as the VM system, so we do not use an
443 * oversized hash table.
444 *
445 * n: size of hash table, must be power of 2
446 * swhash_mask: hash table index mask
447 */
448 for (n = 1; n < n2 / 8; n *= 2)
449 ;
450 swhash = malloc(sizeof(struct swblock *) * n, M_VMPGDATA, M_WAITOK | M_ZERO);
451 swhash_mask = n - 1;
452 mtx_init(&swhash_mtx, "swap_pager swhash", NULL, MTX_DEF);
453}
454
455/*
456 * SWAP_PAGER_ALLOC() - allocate a new OBJT_SWAP VM object and instantiate
457 * its metadata structures.
458 *
459 * This routine is called from the mmap and fork code to create a new
460 * OBJT_SWAP object. We do this by creating an OBJT_DEFAULT object
461 * and then converting it with swp_pager_meta_build().
462 *
463 * This routine may block in vm_object_allocate() and create a named
464 * object lookup race, so we must interlock. We must also run at
465 * splvm() for the object lookup to handle races with interrupts, but
466 * we do not have to maintain splvm() in between the lookup and the
467 * add because (I believe) it is not possible to attempt to create
468 * a new swap object w/handle when a default object with that handle
469 * already exists.
470 *
471 * MPSAFE
472 */
473static vm_object_t
474swap_pager_alloc(void *handle, vm_ooffset_t size, vm_prot_t prot,
475 vm_ooffset_t offset)
476{
477 vm_object_t object;
478 vm_pindex_t pindex;
479
480 pindex = OFF_TO_IDX(offset + PAGE_MASK + size);
481
482 if (handle) {
483 mtx_lock(&Giant);
484 /*
485 * Reference existing named region or allocate new one. There
486 * should not be a race here against swp_pager_meta_build()
487 * as called from vm_page_remove() in regards to the lookup
488 * of the handle.
489 */
490 sx_xlock(&sw_alloc_sx);
491 object = vm_pager_object_lookup(NOBJLIST(handle), handle);
492
493 if (object != NULL) {
494 vm_object_reference(object);
495 } else {
496 object = vm_object_allocate(OBJT_DEFAULT, pindex);
497 object->handle = handle;
498
499 VM_OBJECT_LOCK(object);
500 swp_pager_meta_build(object, 0, SWAPBLK_NONE);
501 VM_OBJECT_UNLOCK(object);
502 }
503 sx_xunlock(&sw_alloc_sx);
504 mtx_unlock(&Giant);
505 } else {
506 object = vm_object_allocate(OBJT_DEFAULT, pindex);
507
508 VM_OBJECT_LOCK(object);
509 swp_pager_meta_build(object, 0, SWAPBLK_NONE);
510 VM_OBJECT_UNLOCK(object);
511 }
512 return (object);
513}
514
515/*
516 * SWAP_PAGER_DEALLOC() - remove swap metadata from object
517 *
518 * The swap backing for the object is destroyed. The code is
519 * designed such that we can reinstantiate it later, but this
520 * routine is typically called only when the entire object is
521 * about to be destroyed.
522 *
523 * This routine may block, but no longer does.
524 *
525 * The object must be locked or unreferenceable.
526 */
527static void
528swap_pager_dealloc(vm_object_t object)
529{
530
531 /*
532 * Remove from list right away so lookups will fail if we block for
533 * pageout completion.
534 */
535 if (object->handle != NULL) {
536 mtx_lock(&sw_alloc_mtx);
537 TAILQ_REMOVE(NOBJLIST(object->handle), object, pager_object_list);
538 mtx_unlock(&sw_alloc_mtx);
539 }
540
541 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
542 vm_object_pip_wait(object, "swpdea");
543
544 /*
545 * Free all remaining metadata. We only bother to free it from
546 * the swap meta data. We do not attempt to free swapblk's still
547 * associated with vm_page_t's for this object. We do not care
548 * if paging is still in progress on some objects.
549 */
550 swp_pager_meta_free_all(object);
551}
552
553/************************************************************************
554 * SWAP PAGER BITMAP ROUTINES *
555 ************************************************************************/
556
557/*
558 * SWP_PAGER_GETSWAPSPACE() - allocate raw swap space
559 *
560 * Allocate swap for the requested number of pages. The starting
561 * swap block number (a page index) is returned or SWAPBLK_NONE
562 * if the allocation failed.
563 *
564 * Also has the side effect of advising that somebody made a mistake
565 * when they configured swap and didn't configure enough.
566 *
567 * Must be called at splvm() to avoid races with bitmap frees from
568 * vm_page_remove() aka swap_pager_page_removed().
569 *
570 * This routine may not block
571 * This routine must be called at splvm().
572 *
573 * We allocate in round-robin fashion from the configured devices.
574 */
575static daddr_t
576swp_pager_getswapspace(int npages)
577{
578 daddr_t blk;
579 struct swdevt *sp;
580 int i;
581
582 blk = SWAPBLK_NONE;
583 mtx_lock(&sw_dev_mtx);
584 sp = swdevhd;
585 for (i = 0; i < nswapdev; i++) {
586 if (sp == NULL)
587 sp = TAILQ_FIRST(&swtailq);
588 if (!(sp->sw_flags & SW_CLOSING)) {
589 blk = blist_alloc(sp->sw_blist, npages);
590 if (blk != SWAPBLK_NONE) {
591 blk += sp->sw_first;
592 sp->sw_used += npages;
593 swap_pager_avail -= npages;
594 swp_sizecheck();
595 swdevhd = TAILQ_NEXT(sp, sw_list);
596 goto done;
597 }
598 }
599 sp = TAILQ_NEXT(sp, sw_list);
600 }
601 if (swap_pager_full != 2) {
602 printf("swap_pager_getswapspace(%d): failed\n", npages);
603 swap_pager_full = 2;
604 swap_pager_almost_full = 1;
605 }
606 swdevhd = NULL;
607done:
608 mtx_unlock(&sw_dev_mtx);
609 return (blk);
610}
611
612static int
613swp_pager_isondev(daddr_t blk, struct swdevt *sp)
614{
615
616 return (blk >= sp->sw_first && blk < sp->sw_end);
617}
618
619static void
620swp_pager_strategy(struct buf *bp)
621{
622 struct swdevt *sp;
623
624 mtx_lock(&sw_dev_mtx);
625 TAILQ_FOREACH(sp, &swtailq, sw_list) {
626 if (bp->b_blkno >= sp->sw_first && bp->b_blkno < sp->sw_end) {
627 mtx_unlock(&sw_dev_mtx);
628 sp->sw_strategy(bp, sp);
629 return;
630 }
631 }
632 panic("Swapdev not found");
633}
634
635
636/*
637 * SWP_PAGER_FREESWAPSPACE() - free raw swap space
638 *
639 * This routine returns the specified swap blocks back to the bitmap.
640 *
641 * Note: This routine may not block (it could in the old swap code),
642 * and through the use of the new blist routines it does not block.
643 *
644 * We must be called at splvm() to avoid races with bitmap frees from
645 * vm_page_remove() aka swap_pager_page_removed().
646 *
647 * This routine may not block
648 * This routine must be called at splvm().
649 */
650static void
651swp_pager_freeswapspace(daddr_t blk, int npages)
652{
653 struct swdevt *sp;
654
655 mtx_lock(&sw_dev_mtx);
656 TAILQ_FOREACH(sp, &swtailq, sw_list) {
657 if (blk >= sp->sw_first && blk < sp->sw_end) {
658 sp->sw_used -= npages;
659 /*
660 * If we are attempting to stop swapping on
661 * this device, we don't want to mark any
662 * blocks free lest they be reused.
663 */
664 if ((sp->sw_flags & SW_CLOSING) == 0) {
665 blist_free(sp->sw_blist, blk - sp->sw_first,
666 npages);
667 swap_pager_avail += npages;
668 swp_sizecheck();
669 }
670 mtx_unlock(&sw_dev_mtx);
671 return;
672 }
673 }
674 panic("Swapdev not found");
675}
676
677/*
678 * SWAP_PAGER_FREESPACE() - frees swap blocks associated with a page
679 * range within an object.
680 *
681 * This is a globally accessible routine.
682 *
683 * This routine removes swapblk assignments from swap metadata.
684 *
685 * The external callers of this routine typically have already destroyed
686 * or renamed vm_page_t's associated with this range in the object so
687 * we should be ok.
688 *
689 * This routine may be called at any spl. We up our spl to splvm temporarily
690 * in order to perform the metadata removal.
691 */
692void
693swap_pager_freespace(vm_object_t object, vm_pindex_t start, vm_size_t size)
694{
695
696 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
697 swp_pager_meta_free(object, start, size);
698}
699
700/*
701 * SWAP_PAGER_RESERVE() - reserve swap blocks in object
702 *
703 * Assigns swap blocks to the specified range within the object. The
704 * swap blocks are not zerod. Any previous swap assignment is destroyed.
705 *
706 * Returns 0 on success, -1 on failure.
707 */
708int
709swap_pager_reserve(vm_object_t object, vm_pindex_t start, vm_size_t size)
710{
711 int n = 0;
712 daddr_t blk = SWAPBLK_NONE;
713 vm_pindex_t beg = start; /* save start index */
714
715 VM_OBJECT_LOCK(object);
716 while (size) {
717 if (n == 0) {
718 n = BLIST_MAX_ALLOC;
719 while ((blk = swp_pager_getswapspace(n)) == SWAPBLK_NONE) {
720 n >>= 1;
721 if (n == 0) {
722 swp_pager_meta_free(object, beg, start - beg);
723 VM_OBJECT_UNLOCK(object);
724 return (-1);
725 }
726 }
727 }
728 swp_pager_meta_build(object, start, blk);
729 --size;
730 ++start;
731 ++blk;
732 --n;
733 }
734 swp_pager_meta_free(object, start, n);
735 VM_OBJECT_UNLOCK(object);
736 return (0);
737}
738
739/*
740 * SWAP_PAGER_COPY() - copy blocks from source pager to destination pager
741 * and destroy the source.
742 *
743 * Copy any valid swapblks from the source to the destination. In
744 * cases where both the source and destination have a valid swapblk,
745 * we keep the destination's.
746 *
747 * This routine is allowed to block. It may block allocating metadata
748 * indirectly through swp_pager_meta_build() or if paging is still in
749 * progress on the source.
750 *
751 * This routine can be called at any spl
752 *
753 * XXX vm_page_collapse() kinda expects us not to block because we
754 * supposedly do not need to allocate memory, but for the moment we
755 * *may* have to get a little memory from the zone allocator, but
756 * it is taken from the interrupt memory. We should be ok.
757 *
758 * The source object contains no vm_page_t's (which is just as well)
759 *
760 * The source object is of type OBJT_SWAP.
761 *
762 * The source and destination objects must be locked or
763 * inaccessible (XXX are they ?)
764 */
765void
766swap_pager_copy(vm_object_t srcobject, vm_object_t dstobject,
767 vm_pindex_t offset, int destroysource)
768{
769 vm_pindex_t i;
770
771 VM_OBJECT_LOCK_ASSERT(srcobject, MA_OWNED);
772 VM_OBJECT_LOCK_ASSERT(dstobject, MA_OWNED);
773
774 /*
775 * If destroysource is set, we remove the source object from the
776 * swap_pager internal queue now.
777 */
778 if (destroysource) {
779 if (srcobject->handle != NULL) {
780 mtx_lock(&sw_alloc_mtx);
781 TAILQ_REMOVE(
782 NOBJLIST(srcobject->handle),
783 srcobject,
784 pager_object_list
785 );
786 mtx_unlock(&sw_alloc_mtx);
787 }
788 }
789
790 /*
791 * transfer source to destination.
792 */
793 for (i = 0; i < dstobject->size; ++i) {
794 daddr_t dstaddr;
795
796 /*
797 * Locate (without changing) the swapblk on the destination,
798 * unless it is invalid in which case free it silently, or
799 * if the destination is a resident page, in which case the
800 * source is thrown away.
801 */
802 dstaddr = swp_pager_meta_ctl(dstobject, i, 0);
803
804 if (dstaddr == SWAPBLK_NONE) {
805 /*
806 * Destination has no swapblk and is not resident,
807 * copy source.
808 */
809 daddr_t srcaddr;
810
811 srcaddr = swp_pager_meta_ctl(
812 srcobject,
813 i + offset,
814 SWM_POP
815 );
816
817 if (srcaddr != SWAPBLK_NONE) {
818 /*
819 * swp_pager_meta_build() can sleep.
820 */
821 vm_object_pip_add(srcobject, 1);
822 VM_OBJECT_UNLOCK(srcobject);
823 vm_object_pip_add(dstobject, 1);
824 swp_pager_meta_build(dstobject, i, srcaddr);
825 vm_object_pip_wakeup(dstobject);
826 VM_OBJECT_LOCK(srcobject);
827 vm_object_pip_wakeup(srcobject);
828 }
829 } else {
830 /*
831 * Destination has valid swapblk or it is represented
832 * by a resident page. We destroy the sourceblock.
833 */
834
835 swp_pager_meta_ctl(srcobject, i + offset, SWM_FREE);
836 }
837 }
838
839 /*
840 * Free left over swap blocks in source.
841 *
842 * We have to revert the type to OBJT_DEFAULT so we do not accidently
843 * double-remove the object from the swap queues.
844 */
845 if (destroysource) {
846 swp_pager_meta_free_all(srcobject);
847 /*
848 * Reverting the type is not necessary, the caller is going
849 * to destroy srcobject directly, but I'm doing it here
850 * for consistency since we've removed the object from its
851 * queues.
852 */
853 srcobject->type = OBJT_DEFAULT;
854 }
855}
856
857/*
858 * SWAP_PAGER_HASPAGE() - determine if we have good backing store for
859 * the requested page.
860 *
861 * We determine whether good backing store exists for the requested
862 * page and return TRUE if it does, FALSE if it doesn't.
863 *
864 * If TRUE, we also try to determine how much valid, contiguous backing
865 * store exists before and after the requested page within a reasonable
866 * distance. We do not try to restrict it to the swap device stripe
867 * (that is handled in getpages/putpages). It probably isn't worth
868 * doing here.
869 */
870static boolean_t
871swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before, int *after)
872{
873 daddr_t blk0;
874
875 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
876 /*
877 * do we have good backing store at the requested index ?
878 */
879 blk0 = swp_pager_meta_ctl(object, pindex, 0);
880
881 if (blk0 == SWAPBLK_NONE) {
882 if (before)
883 *before = 0;
884 if (after)
885 *after = 0;
886 return (FALSE);
887 }
888
889 /*
890 * find backwards-looking contiguous good backing store
891 */
892 if (before != NULL) {
893 int i;
894
895 for (i = 1; i < (SWB_NPAGES/2); ++i) {
896 daddr_t blk;
897
898 if (i > pindex)
899 break;
900 blk = swp_pager_meta_ctl(object, pindex - i, 0);
901 if (blk != blk0 - i)
902 break;
903 }
904 *before = (i - 1);
905 }
906
907 /*
908 * find forward-looking contiguous good backing store
909 */
910 if (after != NULL) {
911 int i;
912
913 for (i = 1; i < (SWB_NPAGES/2); ++i) {
914 daddr_t blk;
915
916 blk = swp_pager_meta_ctl(object, pindex + i, 0);
917 if (blk != blk0 + i)
918 break;
919 }
920 *after = (i - 1);
921 }
922 return (TRUE);
923}
924
925/*
926 * SWAP_PAGER_PAGE_UNSWAPPED() - remove swap backing store related to page
927 *
928 * This removes any associated swap backing store, whether valid or
929 * not, from the page.
930 *
931 * This routine is typically called when a page is made dirty, at
932 * which point any associated swap can be freed. MADV_FREE also
933 * calls us in a special-case situation
934 *
935 * NOTE!!! If the page is clean and the swap was valid, the caller
936 * should make the page dirty before calling this routine. This routine
937 * does NOT change the m->dirty status of the page. Also: MADV_FREE
938 * depends on it.
939 *
940 * This routine may not block
941 * This routine must be called at splvm()
942 */
943static void
944swap_pager_unswapped(vm_page_t m)
945{
946
947 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
948 swp_pager_meta_ctl(m->object, m->pindex, SWM_FREE);
949}
950
951/*
952 * SWAP_PAGER_GETPAGES() - bring pages in from swap
953 *
954 * Attempt to retrieve (m, count) pages from backing store, but make
955 * sure we retrieve at least m[reqpage]. We try to load in as large
956 * a chunk surrounding m[reqpage] as is contiguous in swap and which
957 * belongs to the same object.
958 *
959 * The code is designed for asynchronous operation and
960 * immediate-notification of 'reqpage' but tends not to be
961 * used that way. Please do not optimize-out this algorithmic
962 * feature, I intend to improve on it in the future.
963 *
964 * The parent has a single vm_object_pip_add() reference prior to
965 * calling us and we should return with the same.
966 *
967 * The parent has BUSY'd the pages. We should return with 'm'
968 * left busy, but the others adjusted.
969 */
970static int
971swap_pager_getpages(vm_object_t object, vm_page_t *m, int count, int reqpage)
972{
973 struct buf *bp;
974 vm_page_t mreq;
975 int i;
976 int j;
977 daddr_t blk;
978
979 mreq = m[reqpage];
980
981 KASSERT(mreq->object == object,
982 ("swap_pager_getpages: object mismatch %p/%p",
983 object, mreq->object));
984
985 /*
986 * Calculate range to retrieve. The pages have already been assigned
987 * their swapblks. We require a *contiguous* range but we know it to
988 * not span devices. If we do not supply it, bad things
989 * happen. Note that blk, iblk & jblk can be SWAPBLK_NONE, but the
990 * loops are set up such that the case(s) are handled implicitly.
991 *
992 * The swp_*() calls must be made at splvm(). vm_page_free() does
993 * not need to be, but it will go a little faster if it is.
994 */
995 blk = swp_pager_meta_ctl(mreq->object, mreq->pindex, 0);
996
997 for (i = reqpage - 1; i >= 0; --i) {
998 daddr_t iblk;
999
1000 iblk = swp_pager_meta_ctl(m[i]->object, m[i]->pindex, 0);
1001 if (blk != iblk + (reqpage - i))
1002 break;
1003 }
1004 ++i;
1005
1006 for (j = reqpage + 1; j < count; ++j) {
1007 daddr_t jblk;
1008
1009 jblk = swp_pager_meta_ctl(m[j]->object, m[j]->pindex, 0);
1010 if (blk != jblk - (j - reqpage))
1011 break;
1012 }
1013
1014 /*
1015 * free pages outside our collection range. Note: we never free
1016 * mreq, it must remain busy throughout.
1017 */
1018 if (0 < i || j < count) {
1019 int k;
1020
1021 vm_page_lock_queues();
1022 for (k = 0; k < i; ++k)
1023 vm_page_free(m[k]);
1024 for (k = j; k < count; ++k)
1025 vm_page_free(m[k]);
1026 vm_page_unlock_queues();
1027 }
1028
1029 /*
1030 * Return VM_PAGER_FAIL if we have nothing to do. Return mreq
1031 * still busy, but the others unbusied.
1032 */
1033 if (blk == SWAPBLK_NONE)
1034 return (VM_PAGER_FAIL);
1035
1036 /*
1037 * Getpbuf() can sleep.
1038 */
1039 VM_OBJECT_UNLOCK(object);
1040 /*
1041 * Get a swap buffer header to perform the IO
1042 */
1043 bp = getpbuf(&nsw_rcount);
1044 bp->b_flags |= B_PAGING;
1045
1046 /*
1047 * map our page(s) into kva for input
1048 */
1049 pmap_qenter((vm_offset_t)bp->b_data, m + i, j - i);
1050
1051 bp->b_iocmd = BIO_READ;
1052 bp->b_iodone = swp_pager_async_iodone;
1053 bp->b_rcred = crhold(thread0.td_ucred);
1054 bp->b_wcred = crhold(thread0.td_ucred);
1055 bp->b_blkno = blk - (reqpage - i);
1056 bp->b_bcount = PAGE_SIZE * (j - i);
1057 bp->b_bufsize = PAGE_SIZE * (j - i);
1058 bp->b_pager.pg_reqpage = reqpage - i;
1059
1060 VM_OBJECT_LOCK(object);
1061 {
1062 int k;
1063
1064 for (k = i; k < j; ++k) {
1065 bp->b_pages[k - i] = m[k];
1066 m[k]->oflags |= VPO_SWAPINPROG;
1067 }
1068 }
1069 bp->b_npages = j - i;
1070
1071 cnt.v_swapin++;
1072 cnt.v_swappgsin += bp->b_npages;
1073
1074 /*
1075 * We still hold the lock on mreq, and our automatic completion routine
1076 * does not remove it.
1077 */
1078 vm_object_pip_add(object, bp->b_npages);
1079 VM_OBJECT_UNLOCK(object);
1080
1081 /*
1082 * perform the I/O. NOTE!!! bp cannot be considered valid after
1083 * this point because we automatically release it on completion.
1084 * Instead, we look at the one page we are interested in which we
1085 * still hold a lock on even through the I/O completion.
1086 *
1087 * The other pages in our m[] array are also released on completion,
1088 * so we cannot assume they are valid anymore either.
1089 *
1090 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1091 */
1092 BUF_KERNPROC(bp);
1093 swp_pager_strategy(bp);
1094
1095 /*
1096 * wait for the page we want to complete. VPO_SWAPINPROG is always
1097 * cleared on completion. If an I/O error occurs, SWAPBLK_NONE
1098 * is set in the meta-data.
1099 */
1100 VM_OBJECT_LOCK(object);
1101 while ((mreq->oflags & VPO_SWAPINPROG) != 0) {
1102 mreq->oflags |= VPO_WANTED;
1103 vm_page_lock_queues();
1104 vm_page_flag_set(mreq, PG_REFERENCED);
1105 vm_page_unlock_queues();
1106 cnt.v_intrans++;
1107 if (msleep(mreq, VM_OBJECT_MTX(object), PSWP, "swread", hz*20)) {
1108 printf(
1109"swap_pager: indefinite wait buffer: bufobj: %p, blkno: %jd, size: %ld\n",
1110 bp->b_bufobj, (intmax_t)bp->b_blkno, bp->b_bcount);
1111 }
1112 }
1113
1114 /*
1115 * mreq is left busied after completion, but all the other pages
1116 * are freed. If we had an unrecoverable read error the page will
1117 * not be valid.
1118 */
1119 if (mreq->valid != VM_PAGE_BITS_ALL) {
1120 return (VM_PAGER_ERROR);
1121 } else {
1122 return (VM_PAGER_OK);
1123 }
1124
1125 /*
1126 * A final note: in a low swap situation, we cannot deallocate swap
1127 * and mark a page dirty here because the caller is likely to mark
1128 * the page clean when we return, causing the page to possibly revert
1129 * to all-zero's later.
1130 */
1131}
1132
1133/*
1134 * swap_pager_putpages:
1135 *
1136 * Assign swap (if necessary) and initiate I/O on the specified pages.
1137 *
1138 * We support both OBJT_DEFAULT and OBJT_SWAP objects. DEFAULT objects
1139 * are automatically converted to SWAP objects.
1140 *
1141 * In a low memory situation we may block in VOP_STRATEGY(), but the new
1142 * vm_page reservation system coupled with properly written VFS devices
1143 * should ensure that no low-memory deadlock occurs. This is an area
1144 * which needs work.
1145 *
1146 * The parent has N vm_object_pip_add() references prior to
1147 * calling us and will remove references for rtvals[] that are
1148 * not set to VM_PAGER_PEND. We need to remove the rest on I/O
1149 * completion.
1150 *
1151 * The parent has soft-busy'd the pages it passes us and will unbusy
1152 * those whos rtvals[] entry is not set to VM_PAGER_PEND on return.
1153 * We need to unbusy the rest on I/O completion.
1154 */
1155void
1156swap_pager_putpages(vm_object_t object, vm_page_t *m, int count,
1157 boolean_t sync, int *rtvals)
1158{
1159 int i;
1160 int n = 0;
1161
1162 GIANT_REQUIRED;
1163 if (count && m[0]->object != object) {
1164 panic("swap_pager_getpages: object mismatch %p/%p",
1165 object,
1166 m[0]->object
1167 );
1168 }
1169
1170 /*
1171 * Step 1
1172 *
1173 * Turn object into OBJT_SWAP
1174 * check for bogus sysops
1175 * force sync if not pageout process
1176 */
1177 if (object->type != OBJT_SWAP)
1178 swp_pager_meta_build(object, 0, SWAPBLK_NONE);
1179 VM_OBJECT_UNLOCK(object);
1180
1181 if (curproc != pageproc)
1182 sync = TRUE;
1183
1184 /*
1185 * Step 2
1186 *
1187 * Update nsw parameters from swap_async_max sysctl values.
1188 * Do not let the sysop crash the machine with bogus numbers.
1189 */
1190 mtx_lock(&pbuf_mtx);
1191 if (swap_async_max != nsw_wcount_async_max) {
1192 int n;
1193
1194 /*
1195 * limit range
1196 */
1197 if ((n = swap_async_max) > nswbuf / 2)
1198 n = nswbuf / 2;
1199 if (n < 1)
1200 n = 1;
1201 swap_async_max = n;
1202
1203 /*
1204 * Adjust difference ( if possible ). If the current async
1205 * count is too low, we may not be able to make the adjustment
1206 * at this time.
1207 */
1208 n -= nsw_wcount_async_max;
1209 if (nsw_wcount_async + n >= 0) {
1210 nsw_wcount_async += n;
1211 nsw_wcount_async_max += n;
1212 wakeup(&nsw_wcount_async);
1213 }
1214 }
1215 mtx_unlock(&pbuf_mtx);
1216
1217 /*
1218 * Step 3
1219 *
1220 * Assign swap blocks and issue I/O. We reallocate swap on the fly.
1221 * The page is left dirty until the pageout operation completes
1222 * successfully.
1223 */
1224 for (i = 0; i < count; i += n) {
1225 int j;
1226 struct buf *bp;
1227 daddr_t blk;
1228
1229 /*
1230 * Maximum I/O size is limited by a number of factors.
1231 */
1232 n = min(BLIST_MAX_ALLOC, count - i);
1233 n = min(n, nsw_cluster_max);
1234
1235 /*
1236 * Get biggest block of swap we can. If we fail, fall
1237 * back and try to allocate a smaller block. Don't go
1238 * overboard trying to allocate space if it would overly
1239 * fragment swap.
1240 */
1241 while (
1242 (blk = swp_pager_getswapspace(n)) == SWAPBLK_NONE &&
1243 n > 4
1244 ) {
1245 n >>= 1;
1246 }
1247 if (blk == SWAPBLK_NONE) {
1248 for (j = 0; j < n; ++j)
1249 rtvals[i+j] = VM_PAGER_FAIL;
1250 continue;
1251 }
1252
1253 /*
1254 * All I/O parameters have been satisfied, build the I/O
1255 * request and assign the swap space.
1256 */
1257 if (sync == TRUE) {
1258 bp = getpbuf(&nsw_wcount_sync);
1259 } else {
1260 bp = getpbuf(&nsw_wcount_async);
1261 bp->b_flags = B_ASYNC;
1262 }
1263 bp->b_flags |= B_PAGING;
1264 bp->b_iocmd = BIO_WRITE;
1265
1266 pmap_qenter((vm_offset_t)bp->b_data, &m[i], n);
1267
1268 bp->b_rcred = crhold(thread0.td_ucred);
1269 bp->b_wcred = crhold(thread0.td_ucred);
1270 bp->b_bcount = PAGE_SIZE * n;
1271 bp->b_bufsize = PAGE_SIZE * n;
1272 bp->b_blkno = blk;
1273
1274 VM_OBJECT_LOCK(object);
1275 for (j = 0; j < n; ++j) {
1276 vm_page_t mreq = m[i+j];
1277
1278 swp_pager_meta_build(
1279 mreq->object,
1280 mreq->pindex,
1281 blk + j
1282 );
1283 vm_page_dirty(mreq);
1284 rtvals[i+j] = VM_PAGER_OK;
1285
1286 mreq->oflags |= VPO_SWAPINPROG;
1287 bp->b_pages[j] = mreq;
1288 }
1289 VM_OBJECT_UNLOCK(object);
1290 bp->b_npages = n;
1291 /*
1292 * Must set dirty range for NFS to work.
1293 */
1294 bp->b_dirtyoff = 0;
1295 bp->b_dirtyend = bp->b_bcount;
1296
1297 cnt.v_swapout++;
1298 cnt.v_swappgsout += bp->b_npages;
1299
1300 /*
1301 * asynchronous
1302 *
1303 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1304 */
1305 if (sync == FALSE) {
1306 bp->b_iodone = swp_pager_async_iodone;
1307 BUF_KERNPROC(bp);
1308 swp_pager_strategy(bp);
1309
1310 for (j = 0; j < n; ++j)
1311 rtvals[i+j] = VM_PAGER_PEND;
1312 /* restart outter loop */
1313 continue;
1314 }
1315
1316 /*
1317 * synchronous
1318 *
1319 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1320 */
1321 bp->b_iodone = bdone;
1322 swp_pager_strategy(bp);
1323
1324 /*
1325 * Wait for the sync I/O to complete, then update rtvals.
1326 * We just set the rtvals[] to VM_PAGER_PEND so we can call
1327 * our async completion routine at the end, thus avoiding a
1328 * double-free.
1329 */
1330 bwait(bp, PVM, "swwrt");
1331 for (j = 0; j < n; ++j)
1332 rtvals[i+j] = VM_PAGER_PEND;
1333 /*
1334 * Now that we are through with the bp, we can call the
1335 * normal async completion, which frees everything up.
1336 */
1337 swp_pager_async_iodone(bp);
1338 }
1339 VM_OBJECT_LOCK(object);
1340}
1341
1342/*
1343 * swp_pager_async_iodone:
1344 *
1345 * Completion routine for asynchronous reads and writes from/to swap.
1346 * Also called manually by synchronous code to finish up a bp.
1347 *
1348 * For READ operations, the pages are PG_BUSY'd. For WRITE operations,
1349 * the pages are vm_page_t->busy'd. For READ operations, we PG_BUSY
1350 * unbusy all pages except the 'main' request page. For WRITE
1351 * operations, we vm_page_t->busy'd unbusy all pages ( we can do this
1352 * because we marked them all VM_PAGER_PEND on return from putpages ).
1353 *
1354 * This routine may not block.
1355 * This routine is called at splbio() or better
1356 *
1357 * We up ourselves to splvm() as required for various vm_page related
1358 * calls.
1359 */
1360static void
1361swp_pager_async_iodone(struct buf *bp)
1362{
1363 int i;
1364 vm_object_t object = NULL;
1365
1366 /*
1367 * report error
1368 */
1369 if (bp->b_ioflags & BIO_ERROR) {
1370 printf(
1371 "swap_pager: I/O error - %s failed; blkno %ld,"
1372 "size %ld, error %d\n",
1373 ((bp->b_iocmd == BIO_READ) ? "pagein" : "pageout"),
1374 (long)bp->b_blkno,
1375 (long)bp->b_bcount,
1376 bp->b_error
1377 );
1378 }
1379
1380 /*
1381 * remove the mapping for kernel virtual
1382 */
1383 pmap_qremove((vm_offset_t)bp->b_data, bp->b_npages);
1384
1385 if (bp->b_npages) {
1386 object = bp->b_pages[0]->object;
1387 VM_OBJECT_LOCK(object);
1388 }
1389 vm_page_lock_queues();
1390 /*
1391 * cleanup pages. If an error occurs writing to swap, we are in
1392 * very serious trouble. If it happens to be a disk error, though,
1393 * we may be able to recover by reassigning the swap later on. So
1394 * in this case we remove the m->swapblk assignment for the page
1395 * but do not free it in the rlist. The errornous block(s) are thus
1396 * never reallocated as swap. Redirty the page and continue.
1397 */
1398 for (i = 0; i < bp->b_npages; ++i) {
1399 vm_page_t m = bp->b_pages[i];
1400
1401 m->oflags &= ~VPO_SWAPINPROG;
1402
1403 if (bp->b_ioflags & BIO_ERROR) {
1404 /*
1405 * If an error occurs I'd love to throw the swapblk
1406 * away without freeing it back to swapspace, so it
1407 * can never be used again. But I can't from an
1408 * interrupt.
1409 */
1410 if (bp->b_iocmd == BIO_READ) {
1411 /*
1412 * When reading, reqpage needs to stay
1413 * locked for the parent, but all other
1414 * pages can be freed. We still want to
1415 * wakeup the parent waiting on the page,
1416 * though. ( also: pg_reqpage can be -1 and
1417 * not match anything ).
1418 *
1419 * We have to wake specifically requested pages
1420 * up too because we cleared VPO_SWAPINPROG and
1421 * someone may be waiting for that.
1422 *
1423 * NOTE: for reads, m->dirty will probably
1424 * be overridden by the original caller of
1425 * getpages so don't play cute tricks here.
1426 */
1427 m->valid = 0;
1428 if (i != bp->b_pager.pg_reqpage)
1429 vm_page_free(m);
1430 else
1431 vm_page_flash(m);
1432 /*
1433 * If i == bp->b_pager.pg_reqpage, do not wake
1434 * the page up. The caller needs to.
1435 */
1436 } else {
1437 /*
1438 * If a write error occurs, reactivate page
1439 * so it doesn't clog the inactive list,
1440 * then finish the I/O.
1441 */
1442 vm_page_dirty(m);
1443 vm_page_activate(m);
1444 vm_page_io_finish(m);
1445 }
1446 } else if (bp->b_iocmd == BIO_READ) {
1447 /*
1448 * For read success, clear dirty bits. Nobody should
1449 * have this page mapped but don't take any chances,
1450 * make sure the pmap modify bits are also cleared.
1451 *
1452 * NOTE: for reads, m->dirty will probably be
1453 * overridden by the original caller of getpages so
1454 * we cannot set them in order to free the underlying
1455 * swap in a low-swap situation. I don't think we'd
1456 * want to do that anyway, but it was an optimization
1457 * that existed in the old swapper for a time before
1458 * it got ripped out due to precisely this problem.
1459 *
1460 * If not the requested page then deactivate it.
1461 *
1462 * Note that the requested page, reqpage, is left
1463 * busied, but we still have to wake it up. The
1464 * other pages are released (unbusied) by
1465 * vm_page_wakeup(). We do not set reqpage's
1466 * valid bits here, it is up to the caller.
1467 */
1468 pmap_clear_modify(m);
1469 m->valid = VM_PAGE_BITS_ALL;
1470 vm_page_undirty(m);
1471
1472 /*
1473 * We have to wake specifically requested pages
1474 * up too because we cleared VPO_SWAPINPROG and
1475 * could be waiting for it in getpages. However,
1476 * be sure to not unbusy getpages specifically
1477 * requested page - getpages expects it to be
1478 * left busy.
1479 */
1480 if (i != bp->b_pager.pg_reqpage) {
1481 vm_page_deactivate(m);
1482 vm_page_wakeup(m);
1483 } else {
1484 vm_page_flash(m);
1485 }
1486 } else {
1487 /*
1488 * For write success, clear the modify and dirty
1489 * status, then finish the I/O ( which decrements the
1490 * busy count and possibly wakes waiter's up ).
1491 */
1492 pmap_clear_modify(m);
1493 vm_page_undirty(m);
1494 vm_page_io_finish(m);
1495 if (vm_page_count_severe())
1496 vm_page_try_to_cache(m);
1497 }
1498 }
1499 vm_page_unlock_queues();
1500
1501 /*
1502 * adjust pip. NOTE: the original parent may still have its own
1503 * pip refs on the object.
1504 */
1505 if (object != NULL) {
1506 vm_object_pip_wakeupn(object, bp->b_npages);
1507 VM_OBJECT_UNLOCK(object);
1508 }
1509
1510 /*
1511 * swapdev_strategy() manually sets b_vp and b_bufobj before calling
1512 * bstrategy(). Set them back to NULL now we're done with it, or we'll
1513 * trigger a KASSERT in relpbuf().
1514 */
1515 if (bp->b_vp) {
1516 bp->b_vp = NULL;
1517 bp->b_bufobj = NULL;
1518 }
1519 /*
1520 * release the physical I/O buffer
1521 */
1522 relpbuf(
1523 bp,
1524 ((bp->b_iocmd == BIO_READ) ? &nsw_rcount :
1525 ((bp->b_flags & B_ASYNC) ?
1526 &nsw_wcount_async :
1527 &nsw_wcount_sync
1528 )
1529 )
1530 );
1531}
1532
1533/*
1534 * swap_pager_isswapped:
1535 *
1536 * Return 1 if at least one page in the given object is paged
1537 * out to the given swap device.
1538 *
1539 * This routine may not block.
1540 */
1541int
1542swap_pager_isswapped(vm_object_t object, struct swdevt *sp)
1543{
1544 daddr_t index = 0;
1545 int bcount;
1546 int i;
1547
1548 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1549 if (object->type != OBJT_SWAP)
1550 return (0);
1551
1552 mtx_lock(&swhash_mtx);
1553 for (bcount = 0; bcount < object->un_pager.swp.swp_bcount; bcount++) {
1554 struct swblock *swap;
1555
1556 if ((swap = *swp_pager_hash(object, index)) != NULL) {
1557 for (i = 0; i < SWAP_META_PAGES; ++i) {
1558 if (swp_pager_isondev(swap->swb_pages[i], sp)) {
1559 mtx_unlock(&swhash_mtx);
1560 return (1);
1561 }
1562 }
1563 }
1564 index += SWAP_META_PAGES;
1565 if (index > 0x20000000)
1566 panic("swap_pager_isswapped: failed to locate all swap meta blocks");
1567 }
1568 mtx_unlock(&swhash_mtx);
1569 return (0);
1570}
1571
1572/*
1573 * SWP_PAGER_FORCE_PAGEIN() - force a swap block to be paged in
1574 *
1575 * This routine dissociates the page at the given index within a
1576 * swap block from its backing store, paging it in if necessary.
1577 * If the page is paged in, it is placed in the inactive queue,
1578 * since it had its backing store ripped out from under it.
1579 * We also attempt to swap in all other pages in the swap block,
1580 * we only guarantee that the one at the specified index is
1581 * paged in.
1582 *
1583 * XXX - The code to page the whole block in doesn't work, so we
1584 * revert to the one-by-one behavior for now. Sigh.
1585 */
1586static inline void
1587swp_pager_force_pagein(vm_object_t object, vm_pindex_t pindex)
1588{
1589 vm_page_t m;
1590
1591 vm_object_pip_add(object, 1);
1592 m = vm_page_grab(object, pindex, VM_ALLOC_NORMAL|VM_ALLOC_RETRY);
1593 if (m->valid == VM_PAGE_BITS_ALL) {
1594 vm_object_pip_subtract(object, 1);
1595 vm_page_lock_queues();
1596 vm_page_activate(m);
1597 vm_page_dirty(m);
1598 vm_page_unlock_queues();
1599 vm_page_wakeup(m);
1600 vm_pager_page_unswapped(m);
1601 return;
1602 }
1603
1604 if (swap_pager_getpages(object, &m, 1, 0) != VM_PAGER_OK)
1605 panic("swap_pager_force_pagein: read from swap failed");/*XXX*/
1606 vm_object_pip_subtract(object, 1);
1607 vm_page_lock_queues();
1608 vm_page_dirty(m);
1609 vm_page_dontneed(m);
1610 vm_page_unlock_queues();
1611 vm_page_wakeup(m);
1612 vm_pager_page_unswapped(m);
1613}
1614
1615/*
1616 * swap_pager_swapoff:
1617 *
1618 * Page in all of the pages that have been paged out to the
1619 * given device. The corresponding blocks in the bitmap must be
1620 * marked as allocated and the device must be flagged SW_CLOSING.
1621 * There may be no processes swapped out to the device.
1622 *
1623 * This routine may block.
1624 */
1625static void
1626swap_pager_swapoff(struct swdevt *sp)
1627{
1628 struct swblock *swap;
1629 int i, j, retries;
1630
1631 GIANT_REQUIRED;
1632
1633 retries = 0;
1634full_rescan:
1635 mtx_lock(&swhash_mtx);
1636 for (i = 0; i <= swhash_mask; i++) { /* '<=' is correct here */
1637restart:
1638 for (swap = swhash[i]; swap != NULL; swap = swap->swb_hnext) {
1639 vm_object_t object = swap->swb_object;
1640 vm_pindex_t pindex = swap->swb_index;
1641 for (j = 0; j < SWAP_META_PAGES; ++j) {
1642 if (swp_pager_isondev(swap->swb_pages[j], sp)) {
1643 /* avoid deadlock */
1644 if (!VM_OBJECT_TRYLOCK(object)) {
1645 break;
1646 } else {
1647 mtx_unlock(&swhash_mtx);
1648 swp_pager_force_pagein(object,
1649 pindex + j);
1650 VM_OBJECT_UNLOCK(object);
1651 mtx_lock(&swhash_mtx);
1652 goto restart;
1653 }
1654 }
1655 }
1656 }
1657 }
1658 mtx_unlock(&swhash_mtx);
1659 if (sp->sw_used) {
1660 int dummy;
1661 /*
1662 * Objects may be locked or paging to the device being
1663 * removed, so we will miss their pages and need to
1664 * make another pass. We have marked this device as
1665 * SW_CLOSING, so the activity should finish soon.
1666 */
1667 retries++;
1668 if (retries > 100) {
1669 panic("swapoff: failed to locate %d swap blocks",
1670 sp->sw_used);
1671 }
1672 tsleep(&dummy, PVM, "swpoff", hz / 20);
1673 goto full_rescan;
1674 }
1675}
1676
1677/************************************************************************
1678 * SWAP META DATA *
1679 ************************************************************************
1680 *
1681 * These routines manipulate the swap metadata stored in the
1682 * OBJT_SWAP object. All swp_*() routines must be called at
1683 * splvm() because swap can be freed up by the low level vm_page
1684 * code which might be called from interrupts beyond what splbio() covers.
1685 *
1686 * Swap metadata is implemented with a global hash and not directly
1687 * linked into the object. Instead the object simply contains
1688 * appropriate tracking counters.
1689 */
1690
1691/*
1692 * SWP_PAGER_META_BUILD() - add swap block to swap meta data for object
1693 *
1694 * We first convert the object to a swap object if it is a default
1695 * object.
1696 *
1697 * The specified swapblk is added to the object's swap metadata. If
1698 * the swapblk is not valid, it is freed instead. Any previously
1699 * assigned swapblk is freed.
1700 *
1701 * This routine must be called at splvm(), except when used to convert
1702 * an OBJT_DEFAULT object into an OBJT_SWAP object.
1703 */
1704static void
1705swp_pager_meta_build(vm_object_t object, vm_pindex_t pindex, daddr_t swapblk)
1706{
1707 struct swblock *swap;
1708 struct swblock **pswap;
1709 int idx;
1710
1711 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1712 /*
1713 * Convert default object to swap object if necessary
1714 */
1715 if (object->type != OBJT_SWAP) {
1716 object->type = OBJT_SWAP;
1717 object->un_pager.swp.swp_bcount = 0;
1718
1719 if (object->handle != NULL) {
1720 mtx_lock(&sw_alloc_mtx);
1721 TAILQ_INSERT_TAIL(
1722 NOBJLIST(object->handle),
1723 object,
1724 pager_object_list
1725 );
1726 mtx_unlock(&sw_alloc_mtx);
1727 }
1728 }
1729
1730 /*
1731 * Locate hash entry. If not found create, but if we aren't adding
1732 * anything just return. If we run out of space in the map we wait
1733 * and, since the hash table may have changed, retry.
1734 */
1735retry:
1736 mtx_lock(&swhash_mtx);
1737 pswap = swp_pager_hash(object, pindex);
1738
1739 if ((swap = *pswap) == NULL) {
1740 int i;
1741
1742 if (swapblk == SWAPBLK_NONE)
1743 goto done;
1744
1745 swap = *pswap = uma_zalloc(swap_zone, M_NOWAIT);
1746 if (swap == NULL) {
1747 mtx_unlock(&swhash_mtx);
1748 VM_OBJECT_UNLOCK(object);
1749 VM_WAIT;
1750 VM_OBJECT_LOCK(object);
1751 goto retry;
1752 }
1753
1754 swap->swb_hnext = NULL;
1755 swap->swb_object = object;
1756 swap->swb_index = pindex & ~(vm_pindex_t)SWAP_META_MASK;
1757 swap->swb_count = 0;
1758
1759 ++object->un_pager.swp.swp_bcount;
1760
1761 for (i = 0; i < SWAP_META_PAGES; ++i)
1762 swap->swb_pages[i] = SWAPBLK_NONE;
1763 }
1764
1765 /*
1766 * Delete prior contents of metadata
1767 */
1768 idx = pindex & SWAP_META_MASK;
1769
1770 if (swap->swb_pages[idx] != SWAPBLK_NONE) {
1771 swp_pager_freeswapspace(swap->swb_pages[idx], 1);
1772 --swap->swb_count;
1773 }
1774
1775 /*
1776 * Enter block into metadata
1777 */
1778 swap->swb_pages[idx] = swapblk;
1779 if (swapblk != SWAPBLK_NONE)
1780 ++swap->swb_count;
1781done:
1782 mtx_unlock(&swhash_mtx);
1783}
1784
1785/*
1786 * SWP_PAGER_META_FREE() - free a range of blocks in the object's swap metadata
1787 *
1788 * The requested range of blocks is freed, with any associated swap
1789 * returned to the swap bitmap.
1790 *
1791 * This routine will free swap metadata structures as they are cleaned
1792 * out. This routine does *NOT* operate on swap metadata associated
1793 * with resident pages.
1794 *
1795 * This routine must be called at splvm()
1796 */
1797static void
1798swp_pager_meta_free(vm_object_t object, vm_pindex_t index, daddr_t count)
1799{
1800
1801 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1802 if (object->type != OBJT_SWAP)
1803 return;
1804
1805 while (count > 0) {
1806 struct swblock **pswap;
1807 struct swblock *swap;
1808
1809 mtx_lock(&swhash_mtx);
1810 pswap = swp_pager_hash(object, index);
1811
1812 if ((swap = *pswap) != NULL) {
1813 daddr_t v = swap->swb_pages[index & SWAP_META_MASK];
1814
1815 if (v != SWAPBLK_NONE) {
1816 swp_pager_freeswapspace(v, 1);
1817 swap->swb_pages[index & SWAP_META_MASK] =
1818 SWAPBLK_NONE;
1819 if (--swap->swb_count == 0) {
1820 *pswap = swap->swb_hnext;
1821 uma_zfree(swap_zone, swap);
1822 --object->un_pager.swp.swp_bcount;
1823 }
1824 }
1825 --count;
1826 ++index;
1827 } else {
1828 int n = SWAP_META_PAGES - (index & SWAP_META_MASK);
1829 count -= n;
1830 index += n;
1831 }
1832 mtx_unlock(&swhash_mtx);
1833 }
1834}
1835
1836/*
1837 * SWP_PAGER_META_FREE_ALL() - destroy all swap metadata associated with object
1838 *
1839 * This routine locates and destroys all swap metadata associated with
1840 * an object.
1841 *
1842 * This routine must be called at splvm()
1843 */
1844static void
1845swp_pager_meta_free_all(vm_object_t object)
1846{
1847 daddr_t index = 0;
1848
1849 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1850 if (object->type != OBJT_SWAP)
1851 return;
1852
1853 while (object->un_pager.swp.swp_bcount) {
1854 struct swblock **pswap;
1855 struct swblock *swap;
1856
1857 mtx_lock(&swhash_mtx);
1858 pswap = swp_pager_hash(object, index);
1859 if ((swap = *pswap) != NULL) {
1860 int i;
1861
1862 for (i = 0; i < SWAP_META_PAGES; ++i) {
1863 daddr_t v = swap->swb_pages[i];
1864 if (v != SWAPBLK_NONE) {
1865 --swap->swb_count;
1866 swp_pager_freeswapspace(v, 1);
1867 }
1868 }
1869 if (swap->swb_count != 0)
1870 panic("swap_pager_meta_free_all: swb_count != 0");
1871 *pswap = swap->swb_hnext;
1872 uma_zfree(swap_zone, swap);
1873 --object->un_pager.swp.swp_bcount;
1874 }
1875 mtx_unlock(&swhash_mtx);
1876 index += SWAP_META_PAGES;
1877 if (index > 0x20000000)
1878 panic("swp_pager_meta_free_all: failed to locate all swap meta blocks");
1879 }
1880}
1881
1882/*
1883 * SWP_PAGER_METACTL() - misc control of swap and vm_page_t meta data.
1884 *
1885 * This routine is capable of looking up, popping, or freeing
1886 * swapblk assignments in the swap meta data or in the vm_page_t.
1887 * The routine typically returns the swapblk being looked-up, or popped,
1888 * or SWAPBLK_NONE if the block was freed, or SWAPBLK_NONE if the block
1889 * was invalid. This routine will automatically free any invalid
1890 * meta-data swapblks.
1891 *
1892 * It is not possible to store invalid swapblks in the swap meta data
1893 * (other then a literal 'SWAPBLK_NONE'), so we don't bother checking.
1894 *
1895 * When acting on a busy resident page and paging is in progress, we
1896 * have to wait until paging is complete but otherwise can act on the
1897 * busy page.
1898 *
1899 * This routine must be called at splvm().
1900 *
1901 * SWM_FREE remove and free swap block from metadata
1902 * SWM_POP remove from meta data but do not free.. pop it out
1903 */
1904static daddr_t
1905swp_pager_meta_ctl(vm_object_t object, vm_pindex_t pindex, int flags)
1906{
1907 struct swblock **pswap;
1908 struct swblock *swap;
1909 daddr_t r1;
1910 int idx;
1911
1912 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1913 /*
1914 * The meta data only exists of the object is OBJT_SWAP
1915 * and even then might not be allocated yet.
1916 */
1917 if (object->type != OBJT_SWAP)
1918 return (SWAPBLK_NONE);
1919
1920 r1 = SWAPBLK_NONE;
1921 mtx_lock(&swhash_mtx);
1922 pswap = swp_pager_hash(object, pindex);
1923
1924 if ((swap = *pswap) != NULL) {
1925 idx = pindex & SWAP_META_MASK;
1926 r1 = swap->swb_pages[idx];
1927
1928 if (r1 != SWAPBLK_NONE) {
1929 if (flags & SWM_FREE) {
1930 swp_pager_freeswapspace(r1, 1);
1931 r1 = SWAPBLK_NONE;
1932 }
1933 if (flags & (SWM_FREE|SWM_POP)) {
1934 swap->swb_pages[idx] = SWAPBLK_NONE;
1935 if (--swap->swb_count == 0) {
1936 *pswap = swap->swb_hnext;
1937 uma_zfree(swap_zone, swap);
1938 --object->un_pager.swp.swp_bcount;
1939 }
1940 }
1941 }
1942 }
1943 mtx_unlock(&swhash_mtx);
1944 return (r1);
1945}
1946
1947/*
1948 * System call swapon(name) enables swapping on device name,
1949 * which must be in the swdevsw. Return EBUSY
1950 * if already swapping on this device.
1951 */
1952#ifndef _SYS_SYSPROTO_H_
1953struct swapon_args {
1954 char *name;
1955};
1956#endif
1957
1958/*
1959 * MPSAFE
1960 */
1961/* ARGSUSED */
1962int
1963swapon(struct thread *td, struct swapon_args *uap)
1964{
1965 struct vattr attr;
1966 struct vnode *vp;
1967 struct nameidata nd;
1968 int error;
1969
1970 error = priv_check(td, PRIV_SWAPON);
1971 if (error)
1972 return (error);
1973
1974 mtx_lock(&Giant);
1975 while (swdev_syscall_active)
1976 tsleep(&swdev_syscall_active, PUSER - 1, "swpon", 0);
1977 swdev_syscall_active = 1;
1978
1979 /*
1980 * Swap metadata may not fit in the KVM if we have physical
1981 * memory of >1GB.
1982 */
1983 if (swap_zone == NULL) {
1984 error = ENOMEM;
1985 goto done;
1986 }
1987
1988 NDINIT(&nd, LOOKUP, ISOPEN | FOLLOW, UIO_USERSPACE, uap->name, td);
1989 error = namei(&nd);
1990 if (error)
1991 goto done;
1992
1993 NDFREE(&nd, NDF_ONLY_PNBUF);
1994 vp = nd.ni_vp;
1995
1996 if (vn_isdisk(vp, &error)) {
1997 error = swapongeom(td, vp);
1998 } else if (vp->v_type == VREG &&
1999 (vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
2000 (error = VOP_GETATTR(vp, &attr, td->td_ucred, td)) == 0) {
2001 /*
2002 * Allow direct swapping to NFS regular files in the same
2003 * way that nfs_mountroot() sets up diskless swapping.
2004 */
2005 error = swaponvp(td, vp, attr.va_size / DEV_BSIZE);
2006 }
2007
2008 if (error)
2009 vrele(vp);
2010done:
2011 swdev_syscall_active = 0;
2012 wakeup_one(&swdev_syscall_active);
2013 mtx_unlock(&Giant);
2014 return (error);
2015}
2016
2017static void
2018swaponsomething(struct vnode *vp, void *id, u_long nblks, sw_strategy_t *strategy, sw_close_t *close, dev_t dev)
2019{
2020 struct swdevt *sp, *tsp;
2021 swblk_t dvbase;
2022 u_long mblocks;
2023
2024 /*
2025 * If we go beyond this, we get overflows in the radix
2026 * tree bitmap code.
2027 */
2028 mblocks = 0x40000000 / BLIST_META_RADIX;
2029 if (nblks > mblocks) {
2030 printf("WARNING: reducing size to maximum of %lu blocks per swap unit\n",
2031 mblocks);
2032 nblks = mblocks;
2033 }
2034 /*
2035 * nblks is in DEV_BSIZE'd chunks, convert to PAGE_SIZE'd chunks.
2036 * First chop nblks off to page-align it, then convert.
2037 *
2038 * sw->sw_nblks is in page-sized chunks now too.
2039 */
2040 nblks &= ~(ctodb(1) - 1);
2041 nblks = dbtoc(nblks);
2042
2043 sp = malloc(sizeof *sp, M_VMPGDATA, M_WAITOK | M_ZERO);
2044 sp->sw_vp = vp;
2045 sp->sw_id = id;
2046 sp->sw_dev = dev;
2047 sp->sw_flags = 0;
2048 sp->sw_nblks = nblks;
2049 sp->sw_used = 0;
2050 sp->sw_strategy = strategy;
2051 sp->sw_close = close;
2052
2053 sp->sw_blist = blist_create(nblks);
2054 /*
2055 * Do not free the first two block in order to avoid overwriting
2056 * any bsd label at the front of the partition
2057 */
2058 blist_free(sp->sw_blist, 2, nblks - 2);
2059
2060 dvbase = 0;
2061 mtx_lock(&sw_dev_mtx);
2062 TAILQ_FOREACH(tsp, &swtailq, sw_list) {
2063 if (tsp->sw_end >= dvbase) {
2064 /*
2065 * We put one uncovered page between the devices
2066 * in order to definitively prevent any cross-device
2067 * I/O requests
2068 */
2069 dvbase = tsp->sw_end + 1;
2070 }
2071 }
2072 sp->sw_first = dvbase;
2073 sp->sw_end = dvbase + nblks;
2074 TAILQ_INSERT_TAIL(&swtailq, sp, sw_list);
2075 nswapdev++;
2076 swap_pager_avail += nblks;
2077 swp_sizecheck();
2078 mtx_unlock(&sw_dev_mtx);
2079}
2080
2081/*
2082 * SYSCALL: swapoff(devname)
2083 *
2084 * Disable swapping on the given device.
2085 *
2086 * XXX: Badly designed system call: it should use a device index
2087 * rather than filename as specification. We keep sw_vp around
2088 * only to make this work.
2089 */
2090#ifndef _SYS_SYSPROTO_H_
2091struct swapoff_args {
2092 char *name;
2093};
2094#endif
2095
2096/*
2097 * MPSAFE
2098 */
2099/* ARGSUSED */
2100int
2101swapoff(struct thread *td, struct swapoff_args *uap)
2102{
2103 struct vnode *vp;
2104 struct nameidata nd;
2105 struct swdevt *sp;
2106 int error;
2107
2108 error = priv_check(td, PRIV_SWAPOFF);
2109 if (error)
2110 return (error);
2111
2112 mtx_lock(&Giant);
2113 while (swdev_syscall_active)
2114 tsleep(&swdev_syscall_active, PUSER - 1, "swpoff", 0);
2115 swdev_syscall_active = 1;
2116
2117 NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, uap->name, td);
2118 error = namei(&nd);
2119 if (error)
2120 goto done;
2121 NDFREE(&nd, NDF_ONLY_PNBUF);
2122 vp = nd.ni_vp;
2123
2124 mtx_lock(&sw_dev_mtx);
2125 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2126 if (sp->sw_vp == vp)
2127 break;
2128 }
2129 mtx_unlock(&sw_dev_mtx);
2130 if (sp == NULL) {
2131 error = EINVAL;
2132 goto done;
2133 }
2134 error = swapoff_one(sp, td);
2135done:
2136 swdev_syscall_active = 0;
2137 wakeup_one(&swdev_syscall_active);
2138 mtx_unlock(&Giant);
2139 return (error);
2140}
2141
2142static int
2143swapoff_one(struct swdevt *sp, struct thread *td)
2144{
2145 u_long nblks, dvbase;
2146#ifdef MAC
2147 int error;
2148#endif
2149
2150 mtx_assert(&Giant, MA_OWNED);
2151#ifdef MAC
2152 (void) vn_lock(sp->sw_vp, LK_EXCLUSIVE | LK_RETRY, td);
2153 error = mac_check_system_swapoff(td->td_ucred, sp->sw_vp);
2154 (void) VOP_UNLOCK(sp->sw_vp, 0, td);
2155 if (error != 0)
2156 return (error);
2157#endif
2158 nblks = sp->sw_nblks;
2159
2160 /*
2161 * We can turn off this swap device safely only if the
2162 * available virtual memory in the system will fit the amount
2163 * of data we will have to page back in, plus an epsilon so
2164 * the system doesn't become critically low on swap space.
2165 */
2166 if (cnt.v_free_count + cnt.v_cache_count + swap_pager_avail <
2167 nblks + nswap_lowat) {
2168 return (ENOMEM);
2169 }
2170
2171 /*
2172 * Prevent further allocations on this device.
2173 */
2174 mtx_lock(&sw_dev_mtx);
2175 sp->sw_flags |= SW_CLOSING;
2176 for (dvbase = 0; dvbase < sp->sw_end; dvbase += dmmax) {
2177 swap_pager_avail -= blist_fill(sp->sw_blist,
2178 dvbase, dmmax);
2179 }
2180 mtx_unlock(&sw_dev_mtx);
2181
2182 /*
2183 * Page in the contents of the device and close it.
2184 */
2185 swap_pager_swapoff(sp);
2186
2187 sp->sw_close(td, sp);
2188 sp->sw_id = NULL;
2189 mtx_lock(&sw_dev_mtx);
2190 TAILQ_REMOVE(&swtailq, sp, sw_list);
2191 nswapdev--;
2192 if (nswapdev == 0) {
2193 swap_pager_full = 2;
2194 swap_pager_almost_full = 1;
2195 }
2196 if (swdevhd == sp)
2197 swdevhd = NULL;
2198 mtx_unlock(&sw_dev_mtx);
2199 blist_destroy(sp->sw_blist);
2200 free(sp, M_VMPGDATA);
2201 return (0);
2202}
2203
2204void
2205swapoff_all(void)
2206{
2207 struct swdevt *sp, *spt;
2208 const char *devname;
2209 int error;
2210
2211 mtx_lock(&Giant);
2212 while (swdev_syscall_active)
2213 tsleep(&swdev_syscall_active, PUSER - 1, "swpoff", 0);
2214 swdev_syscall_active = 1;
2215
2216 mtx_lock(&sw_dev_mtx);
2217 TAILQ_FOREACH_SAFE(sp, &swtailq, sw_list, spt) {
2218 mtx_unlock(&sw_dev_mtx);
2219 if (vn_isdisk(sp->sw_vp, NULL))
2220 devname = sp->sw_vp->v_rdev->si_name;
2221 else
2222 devname = "[file]";
2223 error = swapoff_one(sp, &thread0);
2224 if (error != 0) {
2225 printf("Cannot remove swap device %s (error=%d), "
2226 "skipping.\n", devname, error);
2227 } else if (bootverbose) {
2228 printf("Swap device %s removed.\n", devname);
2229 }
2230 mtx_lock(&sw_dev_mtx);
2231 }
2232 mtx_unlock(&sw_dev_mtx);
2233
2234 swdev_syscall_active = 0;
2235 wakeup_one(&swdev_syscall_active);
2236 mtx_unlock(&Giant);
2237}
2238
2239void
2240swap_pager_status(int *total, int *used)
2241{
2242 struct swdevt *sp;
2243
2244 *total = 0;
2245 *used = 0;
2246 mtx_lock(&sw_dev_mtx);
2247 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2248 *total += sp->sw_nblks;
2249 *used += sp->sw_used;
2250 }
2251 mtx_unlock(&sw_dev_mtx);
2252}
2253
2254static int
2255sysctl_vm_swap_info(SYSCTL_HANDLER_ARGS)
2256{
2257 int *name = (int *)arg1;
2258 int error, n;
2259 struct xswdev xs;
2260 struct swdevt *sp;
2261
2262 if (arg2 != 1) /* name length */
2263 return (EINVAL);
2264
2265 n = 0;
2266 mtx_lock(&sw_dev_mtx);
2267 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2268 if (n == *name) {
2269 mtx_unlock(&sw_dev_mtx);
2270 xs.xsw_version = XSWDEV_VERSION;
2271 xs.xsw_dev = sp->sw_dev;
2272 xs.xsw_flags = sp->sw_flags;
2273 xs.xsw_nblks = sp->sw_nblks;
2274 xs.xsw_used = sp->sw_used;
2275
2276 error = SYSCTL_OUT(req, &xs, sizeof(xs));
2277 return (error);
2278 }
2279 n++;
2280 }
2281 mtx_unlock(&sw_dev_mtx);
2282 return (ENOENT);
2283}
2284
2285SYSCTL_INT(_vm, OID_AUTO, nswapdev, CTLFLAG_RD, &nswapdev, 0,
2286 "Number of swap devices");
2287SYSCTL_NODE(_vm, OID_AUTO, swap_info, CTLFLAG_RD, sysctl_vm_swap_info,
2288 "Swap statistics by device");
2289
2290/*
2291 * vmspace_swap_count() - count the approximate swap useage in pages for a
2292 * vmspace.
2293 *
2294 * The map must be locked.
2295 *
2296 * Swap useage is determined by taking the proportional swap used by
2297 * VM objects backing the VM map. To make up for fractional losses,
2298 * if the VM object has any swap use at all the associated map entries
2299 * count for at least 1 swap page.
2300 */
2301int
2302vmspace_swap_count(struct vmspace *vmspace)
2303{
2304 vm_map_t map = &vmspace->vm_map;
2305 vm_map_entry_t cur;
2306 int count = 0;
2307
2308 for (cur = map->header.next; cur != &map->header; cur = cur->next) {
2309 vm_object_t object;
2310
2311 if ((cur->eflags & MAP_ENTRY_IS_SUB_MAP) == 0 &&
2312 (object = cur->object.vm_object) != NULL) {
2313 VM_OBJECT_LOCK(object);
2314 if (object->type == OBJT_SWAP &&
2315 object->un_pager.swp.swp_bcount != 0) {
2316 int n = (cur->end - cur->start) / PAGE_SIZE;
2317
2318 count += object->un_pager.swp.swp_bcount *
2319 SWAP_META_PAGES * n / object->size + 1;
2320 }
2321 VM_OBJECT_UNLOCK(object);
2322 }
2323 }
2324 return (count);
2325}
2326
2327/*
2328 * GEOM backend
2329 *
2330 * Swapping onto disk devices.
2331 *
2332 */
2333
2334static g_orphan_t swapgeom_orphan;
2335
2336static struct g_class g_swap_class = {
2337 .name = "SWAP",
2338 .version = G_VERSION,
2339 .orphan = swapgeom_orphan,
2340};
2341
2342DECLARE_GEOM_CLASS(g_swap_class, g_class);
2343
2344
2345static void
2346swapgeom_done(struct bio *bp2)
2347{
2348 struct buf *bp;
2349
2350 bp = bp2->bio_caller2;
2351 bp->b_ioflags = bp2->bio_flags;
2352 if (bp2->bio_error)
2353 bp->b_ioflags |= BIO_ERROR;
2354 bp->b_resid = bp->b_bcount - bp2->bio_completed;
2355 bp->b_error = bp2->bio_error;
2356 bufdone(bp);
2357 g_destroy_bio(bp2);
2358}
2359
2360static void
2361swapgeom_strategy(struct buf *bp, struct swdevt *sp)
2362{
2363 struct bio *bio;
2364 struct g_consumer *cp;
2365
2366 cp = sp->sw_id;
2367 if (cp == NULL) {
2368 bp->b_error = ENXIO;
2369 bp->b_ioflags |= BIO_ERROR;
2370 bufdone(bp);
2371 return;
2372 }
2373 bio = g_alloc_bio();
2374#if 0
2375 /*
2376 * XXX: We shouldn't really sleep here when we run out of buffers
2377 * XXX: but the alternative is worse right now.
2378 */
2379 if (bio == NULL) {
2380 bp->b_error = ENOMEM;
2381 bp->b_ioflags |= BIO_ERROR;
2382 bufdone(bp);
2383 return;
2384 }
2385#endif
2386 bio->bio_caller2 = bp;
2387 bio->bio_cmd = bp->b_iocmd;
2388 bio->bio_data = bp->b_data;
2389 bio->bio_offset = (bp->b_blkno - sp->sw_first) * PAGE_SIZE;
2390 bio->bio_length = bp->b_bcount;
2391 bio->bio_done = swapgeom_done;
2392 g_io_request(bio, cp);
2393 return;
2394}
2395
2396static void
2397swapgeom_orphan(struct g_consumer *cp)
2398{
2399 struct swdevt *sp;
2400
2401 mtx_lock(&sw_dev_mtx);
2402 TAILQ_FOREACH(sp, &swtailq, sw_list)
2403 if (sp->sw_id == cp)
2404 sp->sw_id = NULL;
2405 mtx_unlock(&sw_dev_mtx);
2406}
2407
2408static void
2409swapgeom_close_ev(void *arg, int flags)
2410{
2411 struct g_consumer *cp;
2412
2413 cp = arg;
2414 g_access(cp, -1, -1, 0);
2415 g_detach(cp);
2416 g_destroy_consumer(cp);
2417}
2418
2419static void
2420swapgeom_close(struct thread *td, struct swdevt *sw)
2421{
2422
2423 /* XXX: direct call when Giant untangled */
2424 g_waitfor_event(swapgeom_close_ev, sw->sw_id, M_WAITOK, NULL);
2425}
2426
2427
2428struct swh0h0 {
2429 struct cdev *dev;
2430 struct vnode *vp;
2431 int error;
2432};
2433
2434static void
2435swapongeom_ev(void *arg, int flags)
2436{
2437 struct swh0h0 *swh;
2438 struct g_provider *pp;
2439 struct g_consumer *cp;
2440 static struct g_geom *gp;
2441 struct swdevt *sp;
2442 u_long nblks;
2443 int error;
2444
2445 swh = arg;
2446 swh->error = 0;
2447 pp = g_dev_getprovider(swh->dev);
2448 if (pp == NULL) {
2449 swh->error = ENODEV;
2450 return;
2451 }
2452 mtx_lock(&sw_dev_mtx);
2453 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2454 cp = sp->sw_id;
2455 if (cp != NULL && cp->provider == pp) {
2456 mtx_unlock(&sw_dev_mtx);
2457 swh->error = EBUSY;
2458 return;
2459 }
2460 }
2461 mtx_unlock(&sw_dev_mtx);
2462 if (gp == NULL)
2463 gp = g_new_geomf(&g_swap_class, "swap", NULL);
2464 cp = g_new_consumer(gp);
2465 g_attach(cp, pp);
2466 /*
2467 * XXX: Everytime you think you can improve the margin for
2468 * footshooting, somebody depends on the ability to do so:
2469 * savecore(8) wants to write to our swapdev so we cannot
2470 * set an exclusive count :-(
2471 */
2472 error = g_access(cp, 1, 1, 0);
2473 if (error) {
2474 g_detach(cp);
2475 g_destroy_consumer(cp);
2476 swh->error = error;
2477 return;
2478 }
2479 nblks = pp->mediasize / DEV_BSIZE;
2480 swaponsomething(swh->vp, cp, nblks, swapgeom_strategy,
2481 swapgeom_close, dev2udev(swh->dev));
2482 swh->error = 0;
2483 return;
2484}
2485
2486static int
2487swapongeom(struct thread *td, struct vnode *vp)
2488{
2489 int error;
2490 struct swh0h0 swh;
2491
2492 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
2493
2494 swh.dev = vp->v_rdev;
2495 swh.vp = vp;
2496 swh.error = 0;
2497 /* XXX: direct call when Giant untangled */
2498 error = g_waitfor_event(swapongeom_ev, &swh, M_WAITOK, NULL);
2499 if (!error)
2500 error = swh.error;
2501 VOP_UNLOCK(vp, 0, td);
2502 return (error);
2503}
2504
2505/*
2506 * VNODE backend
2507 *
2508 * This is used mainly for network filesystem (read: probably only tested
2509 * with NFS) swapfiles.
2510 *
2511 */
2512
2513static void
2514swapdev_strategy(struct buf *bp, struct swdevt *sp)
2515{
2516 struct vnode *vp2;
2517
2518 bp->b_blkno = ctodb(bp->b_blkno - sp->sw_first);
2519
2520 vp2 = sp->sw_id;
2521 vhold(vp2);
2522 if (bp->b_iocmd == BIO_WRITE) {
2523 if (bp->b_bufobj)
2524 bufobj_wdrop(bp->b_bufobj);
2525 bufobj_wref(&vp2->v_bufobj);
2526 }
2527 if (bp->b_bufobj != &vp2->v_bufobj)
2528 bp->b_bufobj = &vp2->v_bufobj;
2529 bp->b_vp = vp2;
2530 bp->b_iooffset = dbtob(bp->b_blkno);
2531 bstrategy(bp);
2532 return;
2533}
2534
2535static void
2536swapdev_close(struct thread *td, struct swdevt *sp)
2537{
2538
2539 VOP_CLOSE(sp->sw_vp, FREAD | FWRITE, td->td_ucred, td);
2540 vrele(sp->sw_vp);
2541}
2542
2543
2544static int
2545swaponvp(struct thread *td, struct vnode *vp, u_long nblks)
2546{
2547 struct swdevt *sp;
2548 int error;
2549
2550 if (nblks == 0)
2551 return (ENXIO);
2552 mtx_lock(&sw_dev_mtx);
2553 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2554 if (sp->sw_id == vp) {
2555 mtx_unlock(&sw_dev_mtx);
2556 return (EBUSY);
2557 }
2558 }
2559 mtx_unlock(&sw_dev_mtx);
2560
2561 (void) vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
2562#ifdef MAC
2563 error = mac_check_system_swapon(td->td_ucred, vp);
2564 if (error == 0)
2565#endif
2566 error = VOP_OPEN(vp, FREAD | FWRITE, td->td_ucred, td, -1);
2567 (void) VOP_UNLOCK(vp, 0, td);
2568 if (error)
2569 return (error);
2570
2571 swaponsomething(vp, vp, nblks, swapdev_strategy, swapdev_close,
2572 NODEV);
2573 return (0);
2574}
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.
7 *
8 * This code is derived from software contributed to Berkeley by
9 * the Systems Programming Group of the University of Utah Computer
10 * Science Department.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
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.
27 *
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
38 * SUCH DAMAGE.
39 *
40 * New Swap System
41 * Matthew Dillon
42 *
43 * Radix Bitmap 'blists'.
44 *
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.
48 *
49 * Features:
50 *
51 * - on the fly reallocation of swap during putpages. The new system
52 * does not try to keep previously allocated swap blocks for dirty
53 * pages.
54 *
55 * - on the fly deallocation of swap
56 *
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
61 * or renamed.
62 *
63 * from: Utah $Hdr: swap_pager.c 1.4 91/04/30$
64 *
65 * @(#)swap_pager.c 8.9 (Berkeley) 3/21/94
66 * @(#)vm_swap.c 8.5 (Berkeley) 2/17/94
67 */
68
69#include <sys/cdefs.h>
70__FBSDID("$FreeBSD: head/sys/vm/swap_pager.c 164033 2006-11-06 13:42:10Z rwatson $");
71
72#include "opt_mac.h"
73#include "opt_swap.h"
74#include "opt_vm.h"
75
76#include <sys/param.h>
77#include <sys/systm.h>
78#include <sys/conf.h>
79#include <sys/kernel.h>
80#include <sys/priv.h>
81#include <sys/proc.h>
82#include <sys/bio.h>
83#include <sys/buf.h>
84#include <sys/disk.h>
85#include <sys/fcntl.h>
86#include <sys/mount.h>
87#include <sys/namei.h>
88#include <sys/vnode.h>
89#include <sys/malloc.h>
90#include <sys/sysctl.h>
91#include <sys/sysproto.h>
92#include <sys/blist.h>
93#include <sys/lock.h>
94#include <sys/sx.h>
95#include <sys/vmmeter.h>
96
97#include <security/mac/mac_framework.h>
98
99#include <vm/vm.h>
100#include <vm/pmap.h>
101#include <vm/vm_map.h>
102#include <vm/vm_kern.h>
103#include <vm/vm_object.h>
104#include <vm/vm_page.h>
105#include <vm/vm_pager.h>
106#include <vm/vm_pageout.h>
107#include <vm/vm_param.h>
108#include <vm/swap_pager.h>
109#include <vm/vm_extern.h>
110#include <vm/uma.h>
111
112#include <geom/geom.h>
113
114/*
115 * SWB_NPAGES must be a power of 2. It may be set to 1, 2, 4, 8, or 16
116 * pages per allocation. We recommend you stick with the default of 8.
117 * The 16-page limit is due to the radix code (kern/subr_blist.c).
118 */
119#ifndef MAX_PAGEOUT_CLUSTER
120#define MAX_PAGEOUT_CLUSTER 16
121#endif
122
123#if !defined(SWB_NPAGES)
124#define SWB_NPAGES MAX_PAGEOUT_CLUSTER
125#endif
126
127/*
128 * Piecemeal swap metadata structure. Swap is stored in a radix tree.
129 *
130 * If SWB_NPAGES is 8 and sizeof(char *) == sizeof(daddr_t), our radix
131 * is basically 8. Assuming PAGE_SIZE == 4096, one tree level represents
132 * 32K worth of data, two levels represent 256K, three levels represent
133 * 2 MBytes. This is acceptable.
134 *
135 * Overall memory utilization is about the same as the old swap structure.
136 */
137#define SWCORRECT(n) (sizeof(void *) * (n) / sizeof(daddr_t))
138#define SWAP_META_PAGES (SWB_NPAGES * 2)
139#define SWAP_META_MASK (SWAP_META_PAGES - 1)
140
141typedef int32_t swblk_t; /*
142 * swap offset. This is the type used to
143 * address the "virtual swap device" and
144 * therefore the maximum swap space is
145 * 2^32 pages.
146 */
147
148struct swdevt;
149typedef void sw_strategy_t(struct buf *bp, struct swdevt *sw);
150typedef void sw_close_t(struct thread *td, struct swdevt *sw);
151
152/*
153 * Swap device table
154 */
155struct swdevt {
156 int sw_flags;
157 int sw_nblks;
158 int sw_used;
159 dev_t sw_dev;
160 struct vnode *sw_vp;
161 void *sw_id;
162 swblk_t sw_first;
163 swblk_t sw_end;
164 struct blist *sw_blist;
165 TAILQ_ENTRY(swdevt) sw_list;
166 sw_strategy_t *sw_strategy;
167 sw_close_t *sw_close;
168};
169
170#define SW_CLOSING 0x04
171
172struct swblock {
173 struct swblock *swb_hnext;
174 vm_object_t swb_object;
175 vm_pindex_t swb_index;
176 int swb_count;
177 daddr_t swb_pages[SWAP_META_PAGES];
178};
179
180static struct mtx sw_dev_mtx;
181static TAILQ_HEAD(, swdevt) swtailq = TAILQ_HEAD_INITIALIZER(swtailq);
182static struct swdevt *swdevhd; /* Allocate from here next */
183static int nswapdev; /* Number of swap devices */
184int swap_pager_avail;
185static int swdev_syscall_active = 0; /* serialize swap(on|off) */
186
187static void swapdev_strategy(struct buf *, struct swdevt *sw);
188
189#define SWM_FREE 0x02 /* free, period */
190#define SWM_POP 0x04 /* pop out */
191
192int swap_pager_full = 2; /* swap space exhaustion (task killing) */
193static int swap_pager_almost_full = 1; /* swap space exhaustion (w/hysteresis)*/
194static int nsw_rcount; /* free read buffers */
195static int nsw_wcount_sync; /* limit write buffers / synchronous */
196static int nsw_wcount_async; /* limit write buffers / asynchronous */
197static int nsw_wcount_async_max;/* assigned maximum */
198static int nsw_cluster_max; /* maximum VOP I/O allowed */
199
200static struct swblock **swhash;
201static int swhash_mask;
202static struct mtx swhash_mtx;
203
204static int swap_async_max = 4; /* maximum in-progress async I/O's */
205static struct sx sw_alloc_sx;
206
207
208SYSCTL_INT(_vm, OID_AUTO, swap_async_max,
209 CTLFLAG_RW, &swap_async_max, 0, "Maximum running async swap ops");
210
211/*
212 * "named" and "unnamed" anon region objects. Try to reduce the overhead
213 * of searching a named list by hashing it just a little.
214 */
215
216#define NOBJLISTS 8
217
218#define NOBJLIST(handle) \
219 (&swap_pager_object_list[((int)(intptr_t)handle >> 4) & (NOBJLISTS-1)])
220
221static struct mtx sw_alloc_mtx; /* protect list manipulation */
222static struct pagerlst swap_pager_object_list[NOBJLISTS];
223static uma_zone_t swap_zone;
224static struct vm_object swap_zone_obj;
225
226/*
227 * pagerops for OBJT_SWAP - "swap pager". Some ops are also global procedure
228 * calls hooked from other parts of the VM system and do not appear here.
229 * (see vm/swap_pager.h).
230 */
231static vm_object_t
232 swap_pager_alloc(void *handle, vm_ooffset_t size,
233 vm_prot_t prot, vm_ooffset_t offset);
234static void swap_pager_dealloc(vm_object_t object);
235static int swap_pager_getpages(vm_object_t, vm_page_t *, int, int);
236static void swap_pager_putpages(vm_object_t, vm_page_t *, int, boolean_t, int *);
237static boolean_t
238 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before, int *after);
239static void swap_pager_init(void);
240static void swap_pager_unswapped(vm_page_t);
241static void swap_pager_swapoff(struct swdevt *sp);
242
243struct pagerops swappagerops = {
244 .pgo_init = swap_pager_init, /* early system initialization of pager */
245 .pgo_alloc = swap_pager_alloc, /* allocate an OBJT_SWAP object */
246 .pgo_dealloc = swap_pager_dealloc, /* deallocate an OBJT_SWAP object */
247 .pgo_getpages = swap_pager_getpages, /* pagein */
248 .pgo_putpages = swap_pager_putpages, /* pageout */
249 .pgo_haspage = swap_pager_haspage, /* get backing store status for page */
250 .pgo_pageunswapped = swap_pager_unswapped, /* remove swap related to page */
251};
252
253/*
254 * dmmax is in page-sized chunks with the new swap system. It was
255 * dev-bsized chunks in the old. dmmax is always a power of 2.
256 *
257 * swap_*() routines are externally accessible. swp_*() routines are
258 * internal.
259 */
260static int dmmax;
261static int nswap_lowat = 128; /* in pages, swap_pager_almost_full warn */
262static int nswap_hiwat = 512; /* in pages, swap_pager_almost_full warn */
263
264SYSCTL_INT(_vm, OID_AUTO, dmmax,
265 CTLFLAG_RD, &dmmax, 0, "Maximum size of a swap block");
266
267static void swp_sizecheck(void);
268static void swp_pager_async_iodone(struct buf *bp);
269static int swapongeom(struct thread *, struct vnode *);
270static int swaponvp(struct thread *, struct vnode *, u_long);
271static int swapoff_one(struct swdevt *sp, struct thread *td);
272
273/*
274 * Swap bitmap functions
275 */
276static void swp_pager_freeswapspace(daddr_t blk, int npages);
277static daddr_t swp_pager_getswapspace(int npages);
278
279/*
280 * Metadata functions
281 */
282static struct swblock **swp_pager_hash(vm_object_t object, vm_pindex_t index);
283static void swp_pager_meta_build(vm_object_t, vm_pindex_t, daddr_t);
284static void swp_pager_meta_free(vm_object_t, vm_pindex_t, daddr_t);
285static void swp_pager_meta_free_all(vm_object_t);
286static daddr_t swp_pager_meta_ctl(vm_object_t, vm_pindex_t, int);
287
288/*
289 * SWP_SIZECHECK() - update swap_pager_full indication
290 *
291 * update the swap_pager_almost_full indication and warn when we are
292 * about to run out of swap space, using lowat/hiwat hysteresis.
293 *
294 * Clear swap_pager_full ( task killing ) indication when lowat is met.
295 *
296 * No restrictions on call
297 * This routine may not block.
298 * This routine must be called at splvm()
299 */
300static void
301swp_sizecheck(void)
302{
303
304 if (swap_pager_avail < nswap_lowat) {
305 if (swap_pager_almost_full == 0) {
306 printf("swap_pager: out of swap space\n");
307 swap_pager_almost_full = 1;
308 }
309 } else {
310 swap_pager_full = 0;
311 if (swap_pager_avail > nswap_hiwat)
312 swap_pager_almost_full = 0;
313 }
314}
315
316/*
317 * SWP_PAGER_HASH() - hash swap meta data
318 *
319 * This is an helper function which hashes the swapblk given
320 * the object and page index. It returns a pointer to a pointer
321 * to the object, or a pointer to a NULL pointer if it could not
322 * find a swapblk.
323 *
324 * This routine must be called at splvm().
325 */
326static struct swblock **
327swp_pager_hash(vm_object_t object, vm_pindex_t index)
328{
329 struct swblock **pswap;
330 struct swblock *swap;
331
332 index &= ~(vm_pindex_t)SWAP_META_MASK;
333 pswap = &swhash[(index ^ (int)(intptr_t)object) & swhash_mask];
334 while ((swap = *pswap) != NULL) {
335 if (swap->swb_object == object &&
336 swap->swb_index == index
337 ) {
338 break;
339 }
340 pswap = &swap->swb_hnext;
341 }
342 return (pswap);
343}
344
345/*
346 * SWAP_PAGER_INIT() - initialize the swap pager!
347 *
348 * Expected to be started from system init. NOTE: This code is run
349 * before much else so be careful what you depend on. Most of the VM
350 * system has yet to be initialized at this point.
351 */
352static void
353swap_pager_init(void)
354{
355 /*
356 * Initialize object lists
357 */
358 int i;
359
360 for (i = 0; i < NOBJLISTS; ++i)
361 TAILQ_INIT(&swap_pager_object_list[i]);
362 mtx_init(&sw_alloc_mtx, "swap_pager list", NULL, MTX_DEF);
363 mtx_init(&sw_dev_mtx, "swapdev", NULL, MTX_DEF);
364
365 /*
366 * Device Stripe, in PAGE_SIZE'd blocks
367 */
368 dmmax = SWB_NPAGES * 2;
369}
370
371/*
372 * SWAP_PAGER_SWAP_INIT() - swap pager initialization from pageout process
373 *
374 * Expected to be started from pageout process once, prior to entering
375 * its main loop.
376 */
377void
378swap_pager_swap_init(void)
379{
380 int n, n2;
381
382 /*
383 * Number of in-transit swap bp operations. Don't
384 * exhaust the pbufs completely. Make sure we
385 * initialize workable values (0 will work for hysteresis
386 * but it isn't very efficient).
387 *
388 * The nsw_cluster_max is constrained by the bp->b_pages[]
389 * array (MAXPHYS/PAGE_SIZE) and our locally defined
390 * MAX_PAGEOUT_CLUSTER. Also be aware that swap ops are
391 * constrained by the swap device interleave stripe size.
392 *
393 * Currently we hardwire nsw_wcount_async to 4. This limit is
394 * designed to prevent other I/O from having high latencies due to
395 * our pageout I/O. The value 4 works well for one or two active swap
396 * devices but is probably a little low if you have more. Even so,
397 * a higher value would probably generate only a limited improvement
398 * with three or four active swap devices since the system does not
399 * typically have to pageout at extreme bandwidths. We will want
400 * at least 2 per swap devices, and 4 is a pretty good value if you
401 * have one NFS swap device due to the command/ack latency over NFS.
402 * So it all works out pretty well.
403 */
404 nsw_cluster_max = min((MAXPHYS/PAGE_SIZE), MAX_PAGEOUT_CLUSTER);
405
406 mtx_lock(&pbuf_mtx);
407 nsw_rcount = (nswbuf + 1) / 2;
408 nsw_wcount_sync = (nswbuf + 3) / 4;
409 nsw_wcount_async = 4;
410 nsw_wcount_async_max = nsw_wcount_async;
411 mtx_unlock(&pbuf_mtx);
412
413 /*
414 * Initialize our zone. Right now I'm just guessing on the number
415 * we need based on the number of pages in the system. Each swblock
416 * can hold 16 pages, so this is probably overkill. This reservation
417 * is typically limited to around 32MB by default.
418 */
419 n = cnt.v_page_count / 2;
420 if (maxswzone && n > maxswzone / sizeof(struct swblock))
421 n = maxswzone / sizeof(struct swblock);
422 n2 = n;
423 swap_zone = uma_zcreate("SWAPMETA", sizeof(struct swblock), NULL, NULL,
424 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
425 if (swap_zone == NULL)
426 panic("failed to create swap_zone.");
427 do {
428 if (uma_zone_set_obj(swap_zone, &swap_zone_obj, n))
429 break;
430 /*
431 * if the allocation failed, try a zone two thirds the
432 * size of the previous attempt.
433 */
434 n -= ((n + 2) / 3);
435 } while (n > 0);
436 if (n2 != n)
437 printf("Swap zone entries reduced from %d to %d.\n", n2, n);
438 n2 = n;
439
440 /*
441 * Initialize our meta-data hash table. The swapper does not need to
442 * be quite as efficient as the VM system, so we do not use an
443 * oversized hash table.
444 *
445 * n: size of hash table, must be power of 2
446 * swhash_mask: hash table index mask
447 */
448 for (n = 1; n < n2 / 8; n *= 2)
449 ;
450 swhash = malloc(sizeof(struct swblock *) * n, M_VMPGDATA, M_WAITOK | M_ZERO);
451 swhash_mask = n - 1;
452 mtx_init(&swhash_mtx, "swap_pager swhash", NULL, MTX_DEF);
453}
454
455/*
456 * SWAP_PAGER_ALLOC() - allocate a new OBJT_SWAP VM object and instantiate
457 * its metadata structures.
458 *
459 * This routine is called from the mmap and fork code to create a new
460 * OBJT_SWAP object. We do this by creating an OBJT_DEFAULT object
461 * and then converting it with swp_pager_meta_build().
462 *
463 * This routine may block in vm_object_allocate() and create a named
464 * object lookup race, so we must interlock. We must also run at
465 * splvm() for the object lookup to handle races with interrupts, but
466 * we do not have to maintain splvm() in between the lookup and the
467 * add because (I believe) it is not possible to attempt to create
468 * a new swap object w/handle when a default object with that handle
469 * already exists.
470 *
471 * MPSAFE
472 */
473static vm_object_t
474swap_pager_alloc(void *handle, vm_ooffset_t size, vm_prot_t prot,
475 vm_ooffset_t offset)
476{
477 vm_object_t object;
478 vm_pindex_t pindex;
479
480 pindex = OFF_TO_IDX(offset + PAGE_MASK + size);
481
482 if (handle) {
483 mtx_lock(&Giant);
484 /*
485 * Reference existing named region or allocate new one. There
486 * should not be a race here against swp_pager_meta_build()
487 * as called from vm_page_remove() in regards to the lookup
488 * of the handle.
489 */
490 sx_xlock(&sw_alloc_sx);
491 object = vm_pager_object_lookup(NOBJLIST(handle), handle);
492
493 if (object != NULL) {
494 vm_object_reference(object);
495 } else {
496 object = vm_object_allocate(OBJT_DEFAULT, pindex);
497 object->handle = handle;
498
499 VM_OBJECT_LOCK(object);
500 swp_pager_meta_build(object, 0, SWAPBLK_NONE);
501 VM_OBJECT_UNLOCK(object);
502 }
503 sx_xunlock(&sw_alloc_sx);
504 mtx_unlock(&Giant);
505 } else {
506 object = vm_object_allocate(OBJT_DEFAULT, pindex);
507
508 VM_OBJECT_LOCK(object);
509 swp_pager_meta_build(object, 0, SWAPBLK_NONE);
510 VM_OBJECT_UNLOCK(object);
511 }
512 return (object);
513}
514
515/*
516 * SWAP_PAGER_DEALLOC() - remove swap metadata from object
517 *
518 * The swap backing for the object is destroyed. The code is
519 * designed such that we can reinstantiate it later, but this
520 * routine is typically called only when the entire object is
521 * about to be destroyed.
522 *
523 * This routine may block, but no longer does.
524 *
525 * The object must be locked or unreferenceable.
526 */
527static void
528swap_pager_dealloc(vm_object_t object)
529{
530
531 /*
532 * Remove from list right away so lookups will fail if we block for
533 * pageout completion.
534 */
535 if (object->handle != NULL) {
536 mtx_lock(&sw_alloc_mtx);
537 TAILQ_REMOVE(NOBJLIST(object->handle), object, pager_object_list);
538 mtx_unlock(&sw_alloc_mtx);
539 }
540
541 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
542 vm_object_pip_wait(object, "swpdea");
543
544 /*
545 * Free all remaining metadata. We only bother to free it from
546 * the swap meta data. We do not attempt to free swapblk's still
547 * associated with vm_page_t's for this object. We do not care
548 * if paging is still in progress on some objects.
549 */
550 swp_pager_meta_free_all(object);
551}
552
553/************************************************************************
554 * SWAP PAGER BITMAP ROUTINES *
555 ************************************************************************/
556
557/*
558 * SWP_PAGER_GETSWAPSPACE() - allocate raw swap space
559 *
560 * Allocate swap for the requested number of pages. The starting
561 * swap block number (a page index) is returned or SWAPBLK_NONE
562 * if the allocation failed.
563 *
564 * Also has the side effect of advising that somebody made a mistake
565 * when they configured swap and didn't configure enough.
566 *
567 * Must be called at splvm() to avoid races with bitmap frees from
568 * vm_page_remove() aka swap_pager_page_removed().
569 *
570 * This routine may not block
571 * This routine must be called at splvm().
572 *
573 * We allocate in round-robin fashion from the configured devices.
574 */
575static daddr_t
576swp_pager_getswapspace(int npages)
577{
578 daddr_t blk;
579 struct swdevt *sp;
580 int i;
581
582 blk = SWAPBLK_NONE;
583 mtx_lock(&sw_dev_mtx);
584 sp = swdevhd;
585 for (i = 0; i < nswapdev; i++) {
586 if (sp == NULL)
587 sp = TAILQ_FIRST(&swtailq);
588 if (!(sp->sw_flags & SW_CLOSING)) {
589 blk = blist_alloc(sp->sw_blist, npages);
590 if (blk != SWAPBLK_NONE) {
591 blk += sp->sw_first;
592 sp->sw_used += npages;
593 swap_pager_avail -= npages;
594 swp_sizecheck();
595 swdevhd = TAILQ_NEXT(sp, sw_list);
596 goto done;
597 }
598 }
599 sp = TAILQ_NEXT(sp, sw_list);
600 }
601 if (swap_pager_full != 2) {
602 printf("swap_pager_getswapspace(%d): failed\n", npages);
603 swap_pager_full = 2;
604 swap_pager_almost_full = 1;
605 }
606 swdevhd = NULL;
607done:
608 mtx_unlock(&sw_dev_mtx);
609 return (blk);
610}
611
612static int
613swp_pager_isondev(daddr_t blk, struct swdevt *sp)
614{
615
616 return (blk >= sp->sw_first && blk < sp->sw_end);
617}
618
619static void
620swp_pager_strategy(struct buf *bp)
621{
622 struct swdevt *sp;
623
624 mtx_lock(&sw_dev_mtx);
625 TAILQ_FOREACH(sp, &swtailq, sw_list) {
626 if (bp->b_blkno >= sp->sw_first && bp->b_blkno < sp->sw_end) {
627 mtx_unlock(&sw_dev_mtx);
628 sp->sw_strategy(bp, sp);
629 return;
630 }
631 }
632 panic("Swapdev not found");
633}
634
635
636/*
637 * SWP_PAGER_FREESWAPSPACE() - free raw swap space
638 *
639 * This routine returns the specified swap blocks back to the bitmap.
640 *
641 * Note: This routine may not block (it could in the old swap code),
642 * and through the use of the new blist routines it does not block.
643 *
644 * We must be called at splvm() to avoid races with bitmap frees from
645 * vm_page_remove() aka swap_pager_page_removed().
646 *
647 * This routine may not block
648 * This routine must be called at splvm().
649 */
650static void
651swp_pager_freeswapspace(daddr_t blk, int npages)
652{
653 struct swdevt *sp;
654
655 mtx_lock(&sw_dev_mtx);
656 TAILQ_FOREACH(sp, &swtailq, sw_list) {
657 if (blk >= sp->sw_first && blk < sp->sw_end) {
658 sp->sw_used -= npages;
659 /*
660 * If we are attempting to stop swapping on
661 * this device, we don't want to mark any
662 * blocks free lest they be reused.
663 */
664 if ((sp->sw_flags & SW_CLOSING) == 0) {
665 blist_free(sp->sw_blist, blk - sp->sw_first,
666 npages);
667 swap_pager_avail += npages;
668 swp_sizecheck();
669 }
670 mtx_unlock(&sw_dev_mtx);
671 return;
672 }
673 }
674 panic("Swapdev not found");
675}
676
677/*
678 * SWAP_PAGER_FREESPACE() - frees swap blocks associated with a page
679 * range within an object.
680 *
681 * This is a globally accessible routine.
682 *
683 * This routine removes swapblk assignments from swap metadata.
684 *
685 * The external callers of this routine typically have already destroyed
686 * or renamed vm_page_t's associated with this range in the object so
687 * we should be ok.
688 *
689 * This routine may be called at any spl. We up our spl to splvm temporarily
690 * in order to perform the metadata removal.
691 */
692void
693swap_pager_freespace(vm_object_t object, vm_pindex_t start, vm_size_t size)
694{
695
696 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
697 swp_pager_meta_free(object, start, size);
698}
699
700/*
701 * SWAP_PAGER_RESERVE() - reserve swap blocks in object
702 *
703 * Assigns swap blocks to the specified range within the object. The
704 * swap blocks are not zerod. Any previous swap assignment is destroyed.
705 *
706 * Returns 0 on success, -1 on failure.
707 */
708int
709swap_pager_reserve(vm_object_t object, vm_pindex_t start, vm_size_t size)
710{
711 int n = 0;
712 daddr_t blk = SWAPBLK_NONE;
713 vm_pindex_t beg = start; /* save start index */
714
715 VM_OBJECT_LOCK(object);
716 while (size) {
717 if (n == 0) {
718 n = BLIST_MAX_ALLOC;
719 while ((blk = swp_pager_getswapspace(n)) == SWAPBLK_NONE) {
720 n >>= 1;
721 if (n == 0) {
722 swp_pager_meta_free(object, beg, start - beg);
723 VM_OBJECT_UNLOCK(object);
724 return (-1);
725 }
726 }
727 }
728 swp_pager_meta_build(object, start, blk);
729 --size;
730 ++start;
731 ++blk;
732 --n;
733 }
734 swp_pager_meta_free(object, start, n);
735 VM_OBJECT_UNLOCK(object);
736 return (0);
737}
738
739/*
740 * SWAP_PAGER_COPY() - copy blocks from source pager to destination pager
741 * and destroy the source.
742 *
743 * Copy any valid swapblks from the source to the destination. In
744 * cases where both the source and destination have a valid swapblk,
745 * we keep the destination's.
746 *
747 * This routine is allowed to block. It may block allocating metadata
748 * indirectly through swp_pager_meta_build() or if paging is still in
749 * progress on the source.
750 *
751 * This routine can be called at any spl
752 *
753 * XXX vm_page_collapse() kinda expects us not to block because we
754 * supposedly do not need to allocate memory, but for the moment we
755 * *may* have to get a little memory from the zone allocator, but
756 * it is taken from the interrupt memory. We should be ok.
757 *
758 * The source object contains no vm_page_t's (which is just as well)
759 *
760 * The source object is of type OBJT_SWAP.
761 *
762 * The source and destination objects must be locked or
763 * inaccessible (XXX are they ?)
764 */
765void
766swap_pager_copy(vm_object_t srcobject, vm_object_t dstobject,
767 vm_pindex_t offset, int destroysource)
768{
769 vm_pindex_t i;
770
771 VM_OBJECT_LOCK_ASSERT(srcobject, MA_OWNED);
772 VM_OBJECT_LOCK_ASSERT(dstobject, MA_OWNED);
773
774 /*
775 * If destroysource is set, we remove the source object from the
776 * swap_pager internal queue now.
777 */
778 if (destroysource) {
779 if (srcobject->handle != NULL) {
780 mtx_lock(&sw_alloc_mtx);
781 TAILQ_REMOVE(
782 NOBJLIST(srcobject->handle),
783 srcobject,
784 pager_object_list
785 );
786 mtx_unlock(&sw_alloc_mtx);
787 }
788 }
789
790 /*
791 * transfer source to destination.
792 */
793 for (i = 0; i < dstobject->size; ++i) {
794 daddr_t dstaddr;
795
796 /*
797 * Locate (without changing) the swapblk on the destination,
798 * unless it is invalid in which case free it silently, or
799 * if the destination is a resident page, in which case the
800 * source is thrown away.
801 */
802 dstaddr = swp_pager_meta_ctl(dstobject, i, 0);
803
804 if (dstaddr == SWAPBLK_NONE) {
805 /*
806 * Destination has no swapblk and is not resident,
807 * copy source.
808 */
809 daddr_t srcaddr;
810
811 srcaddr = swp_pager_meta_ctl(
812 srcobject,
813 i + offset,
814 SWM_POP
815 );
816
817 if (srcaddr != SWAPBLK_NONE) {
818 /*
819 * swp_pager_meta_build() can sleep.
820 */
821 vm_object_pip_add(srcobject, 1);
822 VM_OBJECT_UNLOCK(srcobject);
823 vm_object_pip_add(dstobject, 1);
824 swp_pager_meta_build(dstobject, i, srcaddr);
825 vm_object_pip_wakeup(dstobject);
826 VM_OBJECT_LOCK(srcobject);
827 vm_object_pip_wakeup(srcobject);
828 }
829 } else {
830 /*
831 * Destination has valid swapblk or it is represented
832 * by a resident page. We destroy the sourceblock.
833 */
834
835 swp_pager_meta_ctl(srcobject, i + offset, SWM_FREE);
836 }
837 }
838
839 /*
840 * Free left over swap blocks in source.
841 *
842 * We have to revert the type to OBJT_DEFAULT so we do not accidently
843 * double-remove the object from the swap queues.
844 */
845 if (destroysource) {
846 swp_pager_meta_free_all(srcobject);
847 /*
848 * Reverting the type is not necessary, the caller is going
849 * to destroy srcobject directly, but I'm doing it here
850 * for consistency since we've removed the object from its
851 * queues.
852 */
853 srcobject->type = OBJT_DEFAULT;
854 }
855}
856
857/*
858 * SWAP_PAGER_HASPAGE() - determine if we have good backing store for
859 * the requested page.
860 *
861 * We determine whether good backing store exists for the requested
862 * page and return TRUE if it does, FALSE if it doesn't.
863 *
864 * If TRUE, we also try to determine how much valid, contiguous backing
865 * store exists before and after the requested page within a reasonable
866 * distance. We do not try to restrict it to the swap device stripe
867 * (that is handled in getpages/putpages). It probably isn't worth
868 * doing here.
869 */
870static boolean_t
871swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before, int *after)
872{
873 daddr_t blk0;
874
875 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
876 /*
877 * do we have good backing store at the requested index ?
878 */
879 blk0 = swp_pager_meta_ctl(object, pindex, 0);
880
881 if (blk0 == SWAPBLK_NONE) {
882 if (before)
883 *before = 0;
884 if (after)
885 *after = 0;
886 return (FALSE);
887 }
888
889 /*
890 * find backwards-looking contiguous good backing store
891 */
892 if (before != NULL) {
893 int i;
894
895 for (i = 1; i < (SWB_NPAGES/2); ++i) {
896 daddr_t blk;
897
898 if (i > pindex)
899 break;
900 blk = swp_pager_meta_ctl(object, pindex - i, 0);
901 if (blk != blk0 - i)
902 break;
903 }
904 *before = (i - 1);
905 }
906
907 /*
908 * find forward-looking contiguous good backing store
909 */
910 if (after != NULL) {
911 int i;
912
913 for (i = 1; i < (SWB_NPAGES/2); ++i) {
914 daddr_t blk;
915
916 blk = swp_pager_meta_ctl(object, pindex + i, 0);
917 if (blk != blk0 + i)
918 break;
919 }
920 *after = (i - 1);
921 }
922 return (TRUE);
923}
924
925/*
926 * SWAP_PAGER_PAGE_UNSWAPPED() - remove swap backing store related to page
927 *
928 * This removes any associated swap backing store, whether valid or
929 * not, from the page.
930 *
931 * This routine is typically called when a page is made dirty, at
932 * which point any associated swap can be freed. MADV_FREE also
933 * calls us in a special-case situation
934 *
935 * NOTE!!! If the page is clean and the swap was valid, the caller
936 * should make the page dirty before calling this routine. This routine
937 * does NOT change the m->dirty status of the page. Also: MADV_FREE
938 * depends on it.
939 *
940 * This routine may not block
941 * This routine must be called at splvm()
942 */
943static void
944swap_pager_unswapped(vm_page_t m)
945{
946
947 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
948 swp_pager_meta_ctl(m->object, m->pindex, SWM_FREE);
949}
950
951/*
952 * SWAP_PAGER_GETPAGES() - bring pages in from swap
953 *
954 * Attempt to retrieve (m, count) pages from backing store, but make
955 * sure we retrieve at least m[reqpage]. We try to load in as large
956 * a chunk surrounding m[reqpage] as is contiguous in swap and which
957 * belongs to the same object.
958 *
959 * The code is designed for asynchronous operation and
960 * immediate-notification of 'reqpage' but tends not to be
961 * used that way. Please do not optimize-out this algorithmic
962 * feature, I intend to improve on it in the future.
963 *
964 * The parent has a single vm_object_pip_add() reference prior to
965 * calling us and we should return with the same.
966 *
967 * The parent has BUSY'd the pages. We should return with 'm'
968 * left busy, but the others adjusted.
969 */
970static int
971swap_pager_getpages(vm_object_t object, vm_page_t *m, int count, int reqpage)
972{
973 struct buf *bp;
974 vm_page_t mreq;
975 int i;
976 int j;
977 daddr_t blk;
978
979 mreq = m[reqpage];
980
981 KASSERT(mreq->object == object,
982 ("swap_pager_getpages: object mismatch %p/%p",
983 object, mreq->object));
984
985 /*
986 * Calculate range to retrieve. The pages have already been assigned
987 * their swapblks. We require a *contiguous* range but we know it to
988 * not span devices. If we do not supply it, bad things
989 * happen. Note that blk, iblk & jblk can be SWAPBLK_NONE, but the
990 * loops are set up such that the case(s) are handled implicitly.
991 *
992 * The swp_*() calls must be made at splvm(). vm_page_free() does
993 * not need to be, but it will go a little faster if it is.
994 */
995 blk = swp_pager_meta_ctl(mreq->object, mreq->pindex, 0);
996
997 for (i = reqpage - 1; i >= 0; --i) {
998 daddr_t iblk;
999
1000 iblk = swp_pager_meta_ctl(m[i]->object, m[i]->pindex, 0);
1001 if (blk != iblk + (reqpage - i))
1002 break;
1003 }
1004 ++i;
1005
1006 for (j = reqpage + 1; j < count; ++j) {
1007 daddr_t jblk;
1008
1009 jblk = swp_pager_meta_ctl(m[j]->object, m[j]->pindex, 0);
1010 if (blk != jblk - (j - reqpage))
1011 break;
1012 }
1013
1014 /*
1015 * free pages outside our collection range. Note: we never free
1016 * mreq, it must remain busy throughout.
1017 */
1018 if (0 < i || j < count) {
1019 int k;
1020
1021 vm_page_lock_queues();
1022 for (k = 0; k < i; ++k)
1023 vm_page_free(m[k]);
1024 for (k = j; k < count; ++k)
1025 vm_page_free(m[k]);
1026 vm_page_unlock_queues();
1027 }
1028
1029 /*
1030 * Return VM_PAGER_FAIL if we have nothing to do. Return mreq
1031 * still busy, but the others unbusied.
1032 */
1033 if (blk == SWAPBLK_NONE)
1034 return (VM_PAGER_FAIL);
1035
1036 /*
1037 * Getpbuf() can sleep.
1038 */
1039 VM_OBJECT_UNLOCK(object);
1040 /*
1041 * Get a swap buffer header to perform the IO
1042 */
1043 bp = getpbuf(&nsw_rcount);
1044 bp->b_flags |= B_PAGING;
1045
1046 /*
1047 * map our page(s) into kva for input
1048 */
1049 pmap_qenter((vm_offset_t)bp->b_data, m + i, j - i);
1050
1051 bp->b_iocmd = BIO_READ;
1052 bp->b_iodone = swp_pager_async_iodone;
1053 bp->b_rcred = crhold(thread0.td_ucred);
1054 bp->b_wcred = crhold(thread0.td_ucred);
1055 bp->b_blkno = blk - (reqpage - i);
1056 bp->b_bcount = PAGE_SIZE * (j - i);
1057 bp->b_bufsize = PAGE_SIZE * (j - i);
1058 bp->b_pager.pg_reqpage = reqpage - i;
1059
1060 VM_OBJECT_LOCK(object);
1061 {
1062 int k;
1063
1064 for (k = i; k < j; ++k) {
1065 bp->b_pages[k - i] = m[k];
1066 m[k]->oflags |= VPO_SWAPINPROG;
1067 }
1068 }
1069 bp->b_npages = j - i;
1070
1071 cnt.v_swapin++;
1072 cnt.v_swappgsin += bp->b_npages;
1073
1074 /*
1075 * We still hold the lock on mreq, and our automatic completion routine
1076 * does not remove it.
1077 */
1078 vm_object_pip_add(object, bp->b_npages);
1079 VM_OBJECT_UNLOCK(object);
1080
1081 /*
1082 * perform the I/O. NOTE!!! bp cannot be considered valid after
1083 * this point because we automatically release it on completion.
1084 * Instead, we look at the one page we are interested in which we
1085 * still hold a lock on even through the I/O completion.
1086 *
1087 * The other pages in our m[] array are also released on completion,
1088 * so we cannot assume they are valid anymore either.
1089 *
1090 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1091 */
1092 BUF_KERNPROC(bp);
1093 swp_pager_strategy(bp);
1094
1095 /*
1096 * wait for the page we want to complete. VPO_SWAPINPROG is always
1097 * cleared on completion. If an I/O error occurs, SWAPBLK_NONE
1098 * is set in the meta-data.
1099 */
1100 VM_OBJECT_LOCK(object);
1101 while ((mreq->oflags & VPO_SWAPINPROG) != 0) {
1102 mreq->oflags |= VPO_WANTED;
1103 vm_page_lock_queues();
1104 vm_page_flag_set(mreq, PG_REFERENCED);
1105 vm_page_unlock_queues();
1106 cnt.v_intrans++;
1107 if (msleep(mreq, VM_OBJECT_MTX(object), PSWP, "swread", hz*20)) {
1108 printf(
1109"swap_pager: indefinite wait buffer: bufobj: %p, blkno: %jd, size: %ld\n",
1110 bp->b_bufobj, (intmax_t)bp->b_blkno, bp->b_bcount);
1111 }
1112 }
1113
1114 /*
1115 * mreq is left busied after completion, but all the other pages
1116 * are freed. If we had an unrecoverable read error the page will
1117 * not be valid.
1118 */
1119 if (mreq->valid != VM_PAGE_BITS_ALL) {
1120 return (VM_PAGER_ERROR);
1121 } else {
1122 return (VM_PAGER_OK);
1123 }
1124
1125 /*
1126 * A final note: in a low swap situation, we cannot deallocate swap
1127 * and mark a page dirty here because the caller is likely to mark
1128 * the page clean when we return, causing the page to possibly revert
1129 * to all-zero's later.
1130 */
1131}
1132
1133/*
1134 * swap_pager_putpages:
1135 *
1136 * Assign swap (if necessary) and initiate I/O on the specified pages.
1137 *
1138 * We support both OBJT_DEFAULT and OBJT_SWAP objects. DEFAULT objects
1139 * are automatically converted to SWAP objects.
1140 *
1141 * In a low memory situation we may block in VOP_STRATEGY(), but the new
1142 * vm_page reservation system coupled with properly written VFS devices
1143 * should ensure that no low-memory deadlock occurs. This is an area
1144 * which needs work.
1145 *
1146 * The parent has N vm_object_pip_add() references prior to
1147 * calling us and will remove references for rtvals[] that are
1148 * not set to VM_PAGER_PEND. We need to remove the rest on I/O
1149 * completion.
1150 *
1151 * The parent has soft-busy'd the pages it passes us and will unbusy
1152 * those whos rtvals[] entry is not set to VM_PAGER_PEND on return.
1153 * We need to unbusy the rest on I/O completion.
1154 */
1155void
1156swap_pager_putpages(vm_object_t object, vm_page_t *m, int count,
1157 boolean_t sync, int *rtvals)
1158{
1159 int i;
1160 int n = 0;
1161
1162 GIANT_REQUIRED;
1163 if (count && m[0]->object != object) {
1164 panic("swap_pager_getpages: object mismatch %p/%p",
1165 object,
1166 m[0]->object
1167 );
1168 }
1169
1170 /*
1171 * Step 1
1172 *
1173 * Turn object into OBJT_SWAP
1174 * check for bogus sysops
1175 * force sync if not pageout process
1176 */
1177 if (object->type != OBJT_SWAP)
1178 swp_pager_meta_build(object, 0, SWAPBLK_NONE);
1179 VM_OBJECT_UNLOCK(object);
1180
1181 if (curproc != pageproc)
1182 sync = TRUE;
1183
1184 /*
1185 * Step 2
1186 *
1187 * Update nsw parameters from swap_async_max sysctl values.
1188 * Do not let the sysop crash the machine with bogus numbers.
1189 */
1190 mtx_lock(&pbuf_mtx);
1191 if (swap_async_max != nsw_wcount_async_max) {
1192 int n;
1193
1194 /*
1195 * limit range
1196 */
1197 if ((n = swap_async_max) > nswbuf / 2)
1198 n = nswbuf / 2;
1199 if (n < 1)
1200 n = 1;
1201 swap_async_max = n;
1202
1203 /*
1204 * Adjust difference ( if possible ). If the current async
1205 * count is too low, we may not be able to make the adjustment
1206 * at this time.
1207 */
1208 n -= nsw_wcount_async_max;
1209 if (nsw_wcount_async + n >= 0) {
1210 nsw_wcount_async += n;
1211 nsw_wcount_async_max += n;
1212 wakeup(&nsw_wcount_async);
1213 }
1214 }
1215 mtx_unlock(&pbuf_mtx);
1216
1217 /*
1218 * Step 3
1219 *
1220 * Assign swap blocks and issue I/O. We reallocate swap on the fly.
1221 * The page is left dirty until the pageout operation completes
1222 * successfully.
1223 */
1224 for (i = 0; i < count; i += n) {
1225 int j;
1226 struct buf *bp;
1227 daddr_t blk;
1228
1229 /*
1230 * Maximum I/O size is limited by a number of factors.
1231 */
1232 n = min(BLIST_MAX_ALLOC, count - i);
1233 n = min(n, nsw_cluster_max);
1234
1235 /*
1236 * Get biggest block of swap we can. If we fail, fall
1237 * back and try to allocate a smaller block. Don't go
1238 * overboard trying to allocate space if it would overly
1239 * fragment swap.
1240 */
1241 while (
1242 (blk = swp_pager_getswapspace(n)) == SWAPBLK_NONE &&
1243 n > 4
1244 ) {
1245 n >>= 1;
1246 }
1247 if (blk == SWAPBLK_NONE) {
1248 for (j = 0; j < n; ++j)
1249 rtvals[i+j] = VM_PAGER_FAIL;
1250 continue;
1251 }
1252
1253 /*
1254 * All I/O parameters have been satisfied, build the I/O
1255 * request and assign the swap space.
1256 */
1257 if (sync == TRUE) {
1258 bp = getpbuf(&nsw_wcount_sync);
1259 } else {
1260 bp = getpbuf(&nsw_wcount_async);
1261 bp->b_flags = B_ASYNC;
1262 }
1263 bp->b_flags |= B_PAGING;
1264 bp->b_iocmd = BIO_WRITE;
1265
1266 pmap_qenter((vm_offset_t)bp->b_data, &m[i], n);
1267
1268 bp->b_rcred = crhold(thread0.td_ucred);
1269 bp->b_wcred = crhold(thread0.td_ucred);
1270 bp->b_bcount = PAGE_SIZE * n;
1271 bp->b_bufsize = PAGE_SIZE * n;
1272 bp->b_blkno = blk;
1273
1274 VM_OBJECT_LOCK(object);
1275 for (j = 0; j < n; ++j) {
1276 vm_page_t mreq = m[i+j];
1277
1278 swp_pager_meta_build(
1279 mreq->object,
1280 mreq->pindex,
1281 blk + j
1282 );
1283 vm_page_dirty(mreq);
1284 rtvals[i+j] = VM_PAGER_OK;
1285
1286 mreq->oflags |= VPO_SWAPINPROG;
1287 bp->b_pages[j] = mreq;
1288 }
1289 VM_OBJECT_UNLOCK(object);
1290 bp->b_npages = n;
1291 /*
1292 * Must set dirty range for NFS to work.
1293 */
1294 bp->b_dirtyoff = 0;
1295 bp->b_dirtyend = bp->b_bcount;
1296
1297 cnt.v_swapout++;
1298 cnt.v_swappgsout += bp->b_npages;
1299
1300 /*
1301 * asynchronous
1302 *
1303 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1304 */
1305 if (sync == FALSE) {
1306 bp->b_iodone = swp_pager_async_iodone;
1307 BUF_KERNPROC(bp);
1308 swp_pager_strategy(bp);
1309
1310 for (j = 0; j < n; ++j)
1311 rtvals[i+j] = VM_PAGER_PEND;
1312 /* restart outter loop */
1313 continue;
1314 }
1315
1316 /*
1317 * synchronous
1318 *
1319 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1320 */
1321 bp->b_iodone = bdone;
1322 swp_pager_strategy(bp);
1323
1324 /*
1325 * Wait for the sync I/O to complete, then update rtvals.
1326 * We just set the rtvals[] to VM_PAGER_PEND so we can call
1327 * our async completion routine at the end, thus avoiding a
1328 * double-free.
1329 */
1330 bwait(bp, PVM, "swwrt");
1331 for (j = 0; j < n; ++j)
1332 rtvals[i+j] = VM_PAGER_PEND;
1333 /*
1334 * Now that we are through with the bp, we can call the
1335 * normal async completion, which frees everything up.
1336 */
1337 swp_pager_async_iodone(bp);
1338 }
1339 VM_OBJECT_LOCK(object);
1340}
1341
1342/*
1343 * swp_pager_async_iodone:
1344 *
1345 * Completion routine for asynchronous reads and writes from/to swap.
1346 * Also called manually by synchronous code to finish up a bp.
1347 *
1348 * For READ operations, the pages are PG_BUSY'd. For WRITE operations,
1349 * the pages are vm_page_t->busy'd. For READ operations, we PG_BUSY
1350 * unbusy all pages except the 'main' request page. For WRITE
1351 * operations, we vm_page_t->busy'd unbusy all pages ( we can do this
1352 * because we marked them all VM_PAGER_PEND on return from putpages ).
1353 *
1354 * This routine may not block.
1355 * This routine is called at splbio() or better
1356 *
1357 * We up ourselves to splvm() as required for various vm_page related
1358 * calls.
1359 */
1360static void
1361swp_pager_async_iodone(struct buf *bp)
1362{
1363 int i;
1364 vm_object_t object = NULL;
1365
1366 /*
1367 * report error
1368 */
1369 if (bp->b_ioflags & BIO_ERROR) {
1370 printf(
1371 "swap_pager: I/O error - %s failed; blkno %ld,"
1372 "size %ld, error %d\n",
1373 ((bp->b_iocmd == BIO_READ) ? "pagein" : "pageout"),
1374 (long)bp->b_blkno,
1375 (long)bp->b_bcount,
1376 bp->b_error
1377 );
1378 }
1379
1380 /*
1381 * remove the mapping for kernel virtual
1382 */
1383 pmap_qremove((vm_offset_t)bp->b_data, bp->b_npages);
1384
1385 if (bp->b_npages) {
1386 object = bp->b_pages[0]->object;
1387 VM_OBJECT_LOCK(object);
1388 }
1389 vm_page_lock_queues();
1390 /*
1391 * cleanup pages. If an error occurs writing to swap, we are in
1392 * very serious trouble. If it happens to be a disk error, though,
1393 * we may be able to recover by reassigning the swap later on. So
1394 * in this case we remove the m->swapblk assignment for the page
1395 * but do not free it in the rlist. The errornous block(s) are thus
1396 * never reallocated as swap. Redirty the page and continue.
1397 */
1398 for (i = 0; i < bp->b_npages; ++i) {
1399 vm_page_t m = bp->b_pages[i];
1400
1401 m->oflags &= ~VPO_SWAPINPROG;
1402
1403 if (bp->b_ioflags & BIO_ERROR) {
1404 /*
1405 * If an error occurs I'd love to throw the swapblk
1406 * away without freeing it back to swapspace, so it
1407 * can never be used again. But I can't from an
1408 * interrupt.
1409 */
1410 if (bp->b_iocmd == BIO_READ) {
1411 /*
1412 * When reading, reqpage needs to stay
1413 * locked for the parent, but all other
1414 * pages can be freed. We still want to
1415 * wakeup the parent waiting on the page,
1416 * though. ( also: pg_reqpage can be -1 and
1417 * not match anything ).
1418 *
1419 * We have to wake specifically requested pages
1420 * up too because we cleared VPO_SWAPINPROG and
1421 * someone may be waiting for that.
1422 *
1423 * NOTE: for reads, m->dirty will probably
1424 * be overridden by the original caller of
1425 * getpages so don't play cute tricks here.
1426 */
1427 m->valid = 0;
1428 if (i != bp->b_pager.pg_reqpage)
1429 vm_page_free(m);
1430 else
1431 vm_page_flash(m);
1432 /*
1433 * If i == bp->b_pager.pg_reqpage, do not wake
1434 * the page up. The caller needs to.
1435 */
1436 } else {
1437 /*
1438 * If a write error occurs, reactivate page
1439 * so it doesn't clog the inactive list,
1440 * then finish the I/O.
1441 */
1442 vm_page_dirty(m);
1443 vm_page_activate(m);
1444 vm_page_io_finish(m);
1445 }
1446 } else if (bp->b_iocmd == BIO_READ) {
1447 /*
1448 * For read success, clear dirty bits. Nobody should
1449 * have this page mapped but don't take any chances,
1450 * make sure the pmap modify bits are also cleared.
1451 *
1452 * NOTE: for reads, m->dirty will probably be
1453 * overridden by the original caller of getpages so
1454 * we cannot set them in order to free the underlying
1455 * swap in a low-swap situation. I don't think we'd
1456 * want to do that anyway, but it was an optimization
1457 * that existed in the old swapper for a time before
1458 * it got ripped out due to precisely this problem.
1459 *
1460 * If not the requested page then deactivate it.
1461 *
1462 * Note that the requested page, reqpage, is left
1463 * busied, but we still have to wake it up. The
1464 * other pages are released (unbusied) by
1465 * vm_page_wakeup(). We do not set reqpage's
1466 * valid bits here, it is up to the caller.
1467 */
1468 pmap_clear_modify(m);
1469 m->valid = VM_PAGE_BITS_ALL;
1470 vm_page_undirty(m);
1471
1472 /*
1473 * We have to wake specifically requested pages
1474 * up too because we cleared VPO_SWAPINPROG and
1475 * could be waiting for it in getpages. However,
1476 * be sure to not unbusy getpages specifically
1477 * requested page - getpages expects it to be
1478 * left busy.
1479 */
1480 if (i != bp->b_pager.pg_reqpage) {
1481 vm_page_deactivate(m);
1482 vm_page_wakeup(m);
1483 } else {
1484 vm_page_flash(m);
1485 }
1486 } else {
1487 /*
1488 * For write success, clear the modify and dirty
1489 * status, then finish the I/O ( which decrements the
1490 * busy count and possibly wakes waiter's up ).
1491 */
1492 pmap_clear_modify(m);
1493 vm_page_undirty(m);
1494 vm_page_io_finish(m);
1495 if (vm_page_count_severe())
1496 vm_page_try_to_cache(m);
1497 }
1498 }
1499 vm_page_unlock_queues();
1500
1501 /*
1502 * adjust pip. NOTE: the original parent may still have its own
1503 * pip refs on the object.
1504 */
1505 if (object != NULL) {
1506 vm_object_pip_wakeupn(object, bp->b_npages);
1507 VM_OBJECT_UNLOCK(object);
1508 }
1509
1510 /*
1511 * swapdev_strategy() manually sets b_vp and b_bufobj before calling
1512 * bstrategy(). Set them back to NULL now we're done with it, or we'll
1513 * trigger a KASSERT in relpbuf().
1514 */
1515 if (bp->b_vp) {
1516 bp->b_vp = NULL;
1517 bp->b_bufobj = NULL;
1518 }
1519 /*
1520 * release the physical I/O buffer
1521 */
1522 relpbuf(
1523 bp,
1524 ((bp->b_iocmd == BIO_READ) ? &nsw_rcount :
1525 ((bp->b_flags & B_ASYNC) ?
1526 &nsw_wcount_async :
1527 &nsw_wcount_sync
1528 )
1529 )
1530 );
1531}
1532
1533/*
1534 * swap_pager_isswapped:
1535 *
1536 * Return 1 if at least one page in the given object is paged
1537 * out to the given swap device.
1538 *
1539 * This routine may not block.
1540 */
1541int
1542swap_pager_isswapped(vm_object_t object, struct swdevt *sp)
1543{
1544 daddr_t index = 0;
1545 int bcount;
1546 int i;
1547
1548 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1549 if (object->type != OBJT_SWAP)
1550 return (0);
1551
1552 mtx_lock(&swhash_mtx);
1553 for (bcount = 0; bcount < object->un_pager.swp.swp_bcount; bcount++) {
1554 struct swblock *swap;
1555
1556 if ((swap = *swp_pager_hash(object, index)) != NULL) {
1557 for (i = 0; i < SWAP_META_PAGES; ++i) {
1558 if (swp_pager_isondev(swap->swb_pages[i], sp)) {
1559 mtx_unlock(&swhash_mtx);
1560 return (1);
1561 }
1562 }
1563 }
1564 index += SWAP_META_PAGES;
1565 if (index > 0x20000000)
1566 panic("swap_pager_isswapped: failed to locate all swap meta blocks");
1567 }
1568 mtx_unlock(&swhash_mtx);
1569 return (0);
1570}
1571
1572/*
1573 * SWP_PAGER_FORCE_PAGEIN() - force a swap block to be paged in
1574 *
1575 * This routine dissociates the page at the given index within a
1576 * swap block from its backing store, paging it in if necessary.
1577 * If the page is paged in, it is placed in the inactive queue,
1578 * since it had its backing store ripped out from under it.
1579 * We also attempt to swap in all other pages in the swap block,
1580 * we only guarantee that the one at the specified index is
1581 * paged in.
1582 *
1583 * XXX - The code to page the whole block in doesn't work, so we
1584 * revert to the one-by-one behavior for now. Sigh.
1585 */
1586static inline void
1587swp_pager_force_pagein(vm_object_t object, vm_pindex_t pindex)
1588{
1589 vm_page_t m;
1590
1591 vm_object_pip_add(object, 1);
1592 m = vm_page_grab(object, pindex, VM_ALLOC_NORMAL|VM_ALLOC_RETRY);
1593 if (m->valid == VM_PAGE_BITS_ALL) {
1594 vm_object_pip_subtract(object, 1);
1595 vm_page_lock_queues();
1596 vm_page_activate(m);
1597 vm_page_dirty(m);
1598 vm_page_unlock_queues();
1599 vm_page_wakeup(m);
1600 vm_pager_page_unswapped(m);
1601 return;
1602 }
1603
1604 if (swap_pager_getpages(object, &m, 1, 0) != VM_PAGER_OK)
1605 panic("swap_pager_force_pagein: read from swap failed");/*XXX*/
1606 vm_object_pip_subtract(object, 1);
1607 vm_page_lock_queues();
1608 vm_page_dirty(m);
1609 vm_page_dontneed(m);
1610 vm_page_unlock_queues();
1611 vm_page_wakeup(m);
1612 vm_pager_page_unswapped(m);
1613}
1614
1615/*
1616 * swap_pager_swapoff:
1617 *
1618 * Page in all of the pages that have been paged out to the
1619 * given device. The corresponding blocks in the bitmap must be
1620 * marked as allocated and the device must be flagged SW_CLOSING.
1621 * There may be no processes swapped out to the device.
1622 *
1623 * This routine may block.
1624 */
1625static void
1626swap_pager_swapoff(struct swdevt *sp)
1627{
1628 struct swblock *swap;
1629 int i, j, retries;
1630
1631 GIANT_REQUIRED;
1632
1633 retries = 0;
1634full_rescan:
1635 mtx_lock(&swhash_mtx);
1636 for (i = 0; i <= swhash_mask; i++) { /* '<=' is correct here */
1637restart:
1638 for (swap = swhash[i]; swap != NULL; swap = swap->swb_hnext) {
1639 vm_object_t object = swap->swb_object;
1640 vm_pindex_t pindex = swap->swb_index;
1641 for (j = 0; j < SWAP_META_PAGES; ++j) {
1642 if (swp_pager_isondev(swap->swb_pages[j], sp)) {
1643 /* avoid deadlock */
1644 if (!VM_OBJECT_TRYLOCK(object)) {
1645 break;
1646 } else {
1647 mtx_unlock(&swhash_mtx);
1648 swp_pager_force_pagein(object,
1649 pindex + j);
1650 VM_OBJECT_UNLOCK(object);
1651 mtx_lock(&swhash_mtx);
1652 goto restart;
1653 }
1654 }
1655 }
1656 }
1657 }
1658 mtx_unlock(&swhash_mtx);
1659 if (sp->sw_used) {
1660 int dummy;
1661 /*
1662 * Objects may be locked or paging to the device being
1663 * removed, so we will miss their pages and need to
1664 * make another pass. We have marked this device as
1665 * SW_CLOSING, so the activity should finish soon.
1666 */
1667 retries++;
1668 if (retries > 100) {
1669 panic("swapoff: failed to locate %d swap blocks",
1670 sp->sw_used);
1671 }
1672 tsleep(&dummy, PVM, "swpoff", hz / 20);
1673 goto full_rescan;
1674 }
1675}
1676
1677/************************************************************************
1678 * SWAP META DATA *
1679 ************************************************************************
1680 *
1681 * These routines manipulate the swap metadata stored in the
1682 * OBJT_SWAP object. All swp_*() routines must be called at
1683 * splvm() because swap can be freed up by the low level vm_page
1684 * code which might be called from interrupts beyond what splbio() covers.
1685 *
1686 * Swap metadata is implemented with a global hash and not directly
1687 * linked into the object. Instead the object simply contains
1688 * appropriate tracking counters.
1689 */
1690
1691/*
1692 * SWP_PAGER_META_BUILD() - add swap block to swap meta data for object
1693 *
1694 * We first convert the object to a swap object if it is a default
1695 * object.
1696 *
1697 * The specified swapblk is added to the object's swap metadata. If
1698 * the swapblk is not valid, it is freed instead. Any previously
1699 * assigned swapblk is freed.
1700 *
1701 * This routine must be called at splvm(), except when used to convert
1702 * an OBJT_DEFAULT object into an OBJT_SWAP object.
1703 */
1704static void
1705swp_pager_meta_build(vm_object_t object, vm_pindex_t pindex, daddr_t swapblk)
1706{
1707 struct swblock *swap;
1708 struct swblock **pswap;
1709 int idx;
1710
1711 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1712 /*
1713 * Convert default object to swap object if necessary
1714 */
1715 if (object->type != OBJT_SWAP) {
1716 object->type = OBJT_SWAP;
1717 object->un_pager.swp.swp_bcount = 0;
1718
1719 if (object->handle != NULL) {
1720 mtx_lock(&sw_alloc_mtx);
1721 TAILQ_INSERT_TAIL(
1722 NOBJLIST(object->handle),
1723 object,
1724 pager_object_list
1725 );
1726 mtx_unlock(&sw_alloc_mtx);
1727 }
1728 }
1729
1730 /*
1731 * Locate hash entry. If not found create, but if we aren't adding
1732 * anything just return. If we run out of space in the map we wait
1733 * and, since the hash table may have changed, retry.
1734 */
1735retry:
1736 mtx_lock(&swhash_mtx);
1737 pswap = swp_pager_hash(object, pindex);
1738
1739 if ((swap = *pswap) == NULL) {
1740 int i;
1741
1742 if (swapblk == SWAPBLK_NONE)
1743 goto done;
1744
1745 swap = *pswap = uma_zalloc(swap_zone, M_NOWAIT);
1746 if (swap == NULL) {
1747 mtx_unlock(&swhash_mtx);
1748 VM_OBJECT_UNLOCK(object);
1749 VM_WAIT;
1750 VM_OBJECT_LOCK(object);
1751 goto retry;
1752 }
1753
1754 swap->swb_hnext = NULL;
1755 swap->swb_object = object;
1756 swap->swb_index = pindex & ~(vm_pindex_t)SWAP_META_MASK;
1757 swap->swb_count = 0;
1758
1759 ++object->un_pager.swp.swp_bcount;
1760
1761 for (i = 0; i < SWAP_META_PAGES; ++i)
1762 swap->swb_pages[i] = SWAPBLK_NONE;
1763 }
1764
1765 /*
1766 * Delete prior contents of metadata
1767 */
1768 idx = pindex & SWAP_META_MASK;
1769
1770 if (swap->swb_pages[idx] != SWAPBLK_NONE) {
1771 swp_pager_freeswapspace(swap->swb_pages[idx], 1);
1772 --swap->swb_count;
1773 }
1774
1775 /*
1776 * Enter block into metadata
1777 */
1778 swap->swb_pages[idx] = swapblk;
1779 if (swapblk != SWAPBLK_NONE)
1780 ++swap->swb_count;
1781done:
1782 mtx_unlock(&swhash_mtx);
1783}
1784
1785/*
1786 * SWP_PAGER_META_FREE() - free a range of blocks in the object's swap metadata
1787 *
1788 * The requested range of blocks is freed, with any associated swap
1789 * returned to the swap bitmap.
1790 *
1791 * This routine will free swap metadata structures as they are cleaned
1792 * out. This routine does *NOT* operate on swap metadata associated
1793 * with resident pages.
1794 *
1795 * This routine must be called at splvm()
1796 */
1797static void
1798swp_pager_meta_free(vm_object_t object, vm_pindex_t index, daddr_t count)
1799{
1800
1801 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1802 if (object->type != OBJT_SWAP)
1803 return;
1804
1805 while (count > 0) {
1806 struct swblock **pswap;
1807 struct swblock *swap;
1808
1809 mtx_lock(&swhash_mtx);
1810 pswap = swp_pager_hash(object, index);
1811
1812 if ((swap = *pswap) != NULL) {
1813 daddr_t v = swap->swb_pages[index & SWAP_META_MASK];
1814
1815 if (v != SWAPBLK_NONE) {
1816 swp_pager_freeswapspace(v, 1);
1817 swap->swb_pages[index & SWAP_META_MASK] =
1818 SWAPBLK_NONE;
1819 if (--swap->swb_count == 0) {
1820 *pswap = swap->swb_hnext;
1821 uma_zfree(swap_zone, swap);
1822 --object->un_pager.swp.swp_bcount;
1823 }
1824 }
1825 --count;
1826 ++index;
1827 } else {
1828 int n = SWAP_META_PAGES - (index & SWAP_META_MASK);
1829 count -= n;
1830 index += n;
1831 }
1832 mtx_unlock(&swhash_mtx);
1833 }
1834}
1835
1836/*
1837 * SWP_PAGER_META_FREE_ALL() - destroy all swap metadata associated with object
1838 *
1839 * This routine locates and destroys all swap metadata associated with
1840 * an object.
1841 *
1842 * This routine must be called at splvm()
1843 */
1844static void
1845swp_pager_meta_free_all(vm_object_t object)
1846{
1847 daddr_t index = 0;
1848
1849 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1850 if (object->type != OBJT_SWAP)
1851 return;
1852
1853 while (object->un_pager.swp.swp_bcount) {
1854 struct swblock **pswap;
1855 struct swblock *swap;
1856
1857 mtx_lock(&swhash_mtx);
1858 pswap = swp_pager_hash(object, index);
1859 if ((swap = *pswap) != NULL) {
1860 int i;
1861
1862 for (i = 0; i < SWAP_META_PAGES; ++i) {
1863 daddr_t v = swap->swb_pages[i];
1864 if (v != SWAPBLK_NONE) {
1865 --swap->swb_count;
1866 swp_pager_freeswapspace(v, 1);
1867 }
1868 }
1869 if (swap->swb_count != 0)
1870 panic("swap_pager_meta_free_all: swb_count != 0");
1871 *pswap = swap->swb_hnext;
1872 uma_zfree(swap_zone, swap);
1873 --object->un_pager.swp.swp_bcount;
1874 }
1875 mtx_unlock(&swhash_mtx);
1876 index += SWAP_META_PAGES;
1877 if (index > 0x20000000)
1878 panic("swp_pager_meta_free_all: failed to locate all swap meta blocks");
1879 }
1880}
1881
1882/*
1883 * SWP_PAGER_METACTL() - misc control of swap and vm_page_t meta data.
1884 *
1885 * This routine is capable of looking up, popping, or freeing
1886 * swapblk assignments in the swap meta data or in the vm_page_t.
1887 * The routine typically returns the swapblk being looked-up, or popped,
1888 * or SWAPBLK_NONE if the block was freed, or SWAPBLK_NONE if the block
1889 * was invalid. This routine will automatically free any invalid
1890 * meta-data swapblks.
1891 *
1892 * It is not possible to store invalid swapblks in the swap meta data
1893 * (other then a literal 'SWAPBLK_NONE'), so we don't bother checking.
1894 *
1895 * When acting on a busy resident page and paging is in progress, we
1896 * have to wait until paging is complete but otherwise can act on the
1897 * busy page.
1898 *
1899 * This routine must be called at splvm().
1900 *
1901 * SWM_FREE remove and free swap block from metadata
1902 * SWM_POP remove from meta data but do not free.. pop it out
1903 */
1904static daddr_t
1905swp_pager_meta_ctl(vm_object_t object, vm_pindex_t pindex, int flags)
1906{
1907 struct swblock **pswap;
1908 struct swblock *swap;
1909 daddr_t r1;
1910 int idx;
1911
1912 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1913 /*
1914 * The meta data only exists of the object is OBJT_SWAP
1915 * and even then might not be allocated yet.
1916 */
1917 if (object->type != OBJT_SWAP)
1918 return (SWAPBLK_NONE);
1919
1920 r1 = SWAPBLK_NONE;
1921 mtx_lock(&swhash_mtx);
1922 pswap = swp_pager_hash(object, pindex);
1923
1924 if ((swap = *pswap) != NULL) {
1925 idx = pindex & SWAP_META_MASK;
1926 r1 = swap->swb_pages[idx];
1927
1928 if (r1 != SWAPBLK_NONE) {
1929 if (flags & SWM_FREE) {
1930 swp_pager_freeswapspace(r1, 1);
1931 r1 = SWAPBLK_NONE;
1932 }
1933 if (flags & (SWM_FREE|SWM_POP)) {
1934 swap->swb_pages[idx] = SWAPBLK_NONE;
1935 if (--swap->swb_count == 0) {
1936 *pswap = swap->swb_hnext;
1937 uma_zfree(swap_zone, swap);
1938 --object->un_pager.swp.swp_bcount;
1939 }
1940 }
1941 }
1942 }
1943 mtx_unlock(&swhash_mtx);
1944 return (r1);
1945}
1946
1947/*
1948 * System call swapon(name) enables swapping on device name,
1949 * which must be in the swdevsw. Return EBUSY
1950 * if already swapping on this device.
1951 */
1952#ifndef _SYS_SYSPROTO_H_
1953struct swapon_args {
1954 char *name;
1955};
1956#endif
1957
1958/*
1959 * MPSAFE
1960 */
1961/* ARGSUSED */
1962int
1963swapon(struct thread *td, struct swapon_args *uap)
1964{
1965 struct vattr attr;
1966 struct vnode *vp;
1967 struct nameidata nd;
1968 int error;
1969
1970 error = priv_check(td, PRIV_SWAPON);
1971 if (error)
1972 return (error);
1973
1974 mtx_lock(&Giant);
1975 while (swdev_syscall_active)
1976 tsleep(&swdev_syscall_active, PUSER - 1, "swpon", 0);
1977 swdev_syscall_active = 1;
1978
1979 /*
1980 * Swap metadata may not fit in the KVM if we have physical
1981 * memory of >1GB.
1982 */
1983 if (swap_zone == NULL) {
1984 error = ENOMEM;
1985 goto done;
1986 }
1987
1988 NDINIT(&nd, LOOKUP, ISOPEN | FOLLOW, UIO_USERSPACE, uap->name, td);
1989 error = namei(&nd);
1990 if (error)
1991 goto done;
1992
1993 NDFREE(&nd, NDF_ONLY_PNBUF);
1994 vp = nd.ni_vp;
1995
1996 if (vn_isdisk(vp, &error)) {
1997 error = swapongeom(td, vp);
1998 } else if (vp->v_type == VREG &&
1999 (vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
2000 (error = VOP_GETATTR(vp, &attr, td->td_ucred, td)) == 0) {
2001 /*
2002 * Allow direct swapping to NFS regular files in the same
2003 * way that nfs_mountroot() sets up diskless swapping.
2004 */
2005 error = swaponvp(td, vp, attr.va_size / DEV_BSIZE);
2006 }
2007
2008 if (error)
2009 vrele(vp);
2010done:
2011 swdev_syscall_active = 0;
2012 wakeup_one(&swdev_syscall_active);
2013 mtx_unlock(&Giant);
2014 return (error);
2015}
2016
2017static void
2018swaponsomething(struct vnode *vp, void *id, u_long nblks, sw_strategy_t *strategy, sw_close_t *close, dev_t dev)
2019{
2020 struct swdevt *sp, *tsp;
2021 swblk_t dvbase;
2022 u_long mblocks;
2023
2024 /*
2025 * If we go beyond this, we get overflows in the radix
2026 * tree bitmap code.
2027 */
2028 mblocks = 0x40000000 / BLIST_META_RADIX;
2029 if (nblks > mblocks) {
2030 printf("WARNING: reducing size to maximum of %lu blocks per swap unit\n",
2031 mblocks);
2032 nblks = mblocks;
2033 }
2034 /*
2035 * nblks is in DEV_BSIZE'd chunks, convert to PAGE_SIZE'd chunks.
2036 * First chop nblks off to page-align it, then convert.
2037 *
2038 * sw->sw_nblks is in page-sized chunks now too.
2039 */
2040 nblks &= ~(ctodb(1) - 1);
2041 nblks = dbtoc(nblks);
2042
2043 sp = malloc(sizeof *sp, M_VMPGDATA, M_WAITOK | M_ZERO);
2044 sp->sw_vp = vp;
2045 sp->sw_id = id;
2046 sp->sw_dev = dev;
2047 sp->sw_flags = 0;
2048 sp->sw_nblks = nblks;
2049 sp->sw_used = 0;
2050 sp->sw_strategy = strategy;
2051 sp->sw_close = close;
2052
2053 sp->sw_blist = blist_create(nblks);
2054 /*
2055 * Do not free the first two block in order to avoid overwriting
2056 * any bsd label at the front of the partition
2057 */
2058 blist_free(sp->sw_blist, 2, nblks - 2);
2059
2060 dvbase = 0;
2061 mtx_lock(&sw_dev_mtx);
2062 TAILQ_FOREACH(tsp, &swtailq, sw_list) {
2063 if (tsp->sw_end >= dvbase) {
2064 /*
2065 * We put one uncovered page between the devices
2066 * in order to definitively prevent any cross-device
2067 * I/O requests
2068 */
2069 dvbase = tsp->sw_end + 1;
2070 }
2071 }
2072 sp->sw_first = dvbase;
2073 sp->sw_end = dvbase + nblks;
2074 TAILQ_INSERT_TAIL(&swtailq, sp, sw_list);
2075 nswapdev++;
2076 swap_pager_avail += nblks;
2077 swp_sizecheck();
2078 mtx_unlock(&sw_dev_mtx);
2079}
2080
2081/*
2082 * SYSCALL: swapoff(devname)
2083 *
2084 * Disable swapping on the given device.
2085 *
2086 * XXX: Badly designed system call: it should use a device index
2087 * rather than filename as specification. We keep sw_vp around
2088 * only to make this work.
2089 */
2090#ifndef _SYS_SYSPROTO_H_
2091struct swapoff_args {
2092 char *name;
2093};
2094#endif
2095
2096/*
2097 * MPSAFE
2098 */
2099/* ARGSUSED */
2100int
2101swapoff(struct thread *td, struct swapoff_args *uap)
2102{
2103 struct vnode *vp;
2104 struct nameidata nd;
2105 struct swdevt *sp;
2106 int error;
2107
2108 error = priv_check(td, PRIV_SWAPOFF);
2109 if (error)
2110 return (error);
2111
2112 mtx_lock(&Giant);
2113 while (swdev_syscall_active)
2114 tsleep(&swdev_syscall_active, PUSER - 1, "swpoff", 0);
2115 swdev_syscall_active = 1;
2116
2117 NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, uap->name, td);
2118 error = namei(&nd);
2119 if (error)
2120 goto done;
2121 NDFREE(&nd, NDF_ONLY_PNBUF);
2122 vp = nd.ni_vp;
2123
2124 mtx_lock(&sw_dev_mtx);
2125 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2126 if (sp->sw_vp == vp)
2127 break;
2128 }
2129 mtx_unlock(&sw_dev_mtx);
2130 if (sp == NULL) {
2131 error = EINVAL;
2132 goto done;
2133 }
2134 error = swapoff_one(sp, td);
2135done:
2136 swdev_syscall_active = 0;
2137 wakeup_one(&swdev_syscall_active);
2138 mtx_unlock(&Giant);
2139 return (error);
2140}
2141
2142static int
2143swapoff_one(struct swdevt *sp, struct thread *td)
2144{
2145 u_long nblks, dvbase;
2146#ifdef MAC
2147 int error;
2148#endif
2149
2150 mtx_assert(&Giant, MA_OWNED);
2151#ifdef MAC
2152 (void) vn_lock(sp->sw_vp, LK_EXCLUSIVE | LK_RETRY, td);
2153 error = mac_check_system_swapoff(td->td_ucred, sp->sw_vp);
2154 (void) VOP_UNLOCK(sp->sw_vp, 0, td);
2155 if (error != 0)
2156 return (error);
2157#endif
2158 nblks = sp->sw_nblks;
2159
2160 /*
2161 * We can turn off this swap device safely only if the
2162 * available virtual memory in the system will fit the amount
2163 * of data we will have to page back in, plus an epsilon so
2164 * the system doesn't become critically low on swap space.
2165 */
2166 if (cnt.v_free_count + cnt.v_cache_count + swap_pager_avail <
2167 nblks + nswap_lowat) {
2168 return (ENOMEM);
2169 }
2170
2171 /*
2172 * Prevent further allocations on this device.
2173 */
2174 mtx_lock(&sw_dev_mtx);
2175 sp->sw_flags |= SW_CLOSING;
2176 for (dvbase = 0; dvbase < sp->sw_end; dvbase += dmmax) {
2177 swap_pager_avail -= blist_fill(sp->sw_blist,
2178 dvbase, dmmax);
2179 }
2180 mtx_unlock(&sw_dev_mtx);
2181
2182 /*
2183 * Page in the contents of the device and close it.
2184 */
2185 swap_pager_swapoff(sp);
2186
2187 sp->sw_close(td, sp);
2188 sp->sw_id = NULL;
2189 mtx_lock(&sw_dev_mtx);
2190 TAILQ_REMOVE(&swtailq, sp, sw_list);
2191 nswapdev--;
2192 if (nswapdev == 0) {
2193 swap_pager_full = 2;
2194 swap_pager_almost_full = 1;
2195 }
2196 if (swdevhd == sp)
2197 swdevhd = NULL;
2198 mtx_unlock(&sw_dev_mtx);
2199 blist_destroy(sp->sw_blist);
2200 free(sp, M_VMPGDATA);
2201 return (0);
2202}
2203
2204void
2205swapoff_all(void)
2206{
2207 struct swdevt *sp, *spt;
2208 const char *devname;
2209 int error;
2210
2211 mtx_lock(&Giant);
2212 while (swdev_syscall_active)
2213 tsleep(&swdev_syscall_active, PUSER - 1, "swpoff", 0);
2214 swdev_syscall_active = 1;
2215
2216 mtx_lock(&sw_dev_mtx);
2217 TAILQ_FOREACH_SAFE(sp, &swtailq, sw_list, spt) {
2218 mtx_unlock(&sw_dev_mtx);
2219 if (vn_isdisk(sp->sw_vp, NULL))
2220 devname = sp->sw_vp->v_rdev->si_name;
2221 else
2222 devname = "[file]";
2223 error = swapoff_one(sp, &thread0);
2224 if (error != 0) {
2225 printf("Cannot remove swap device %s (error=%d), "
2226 "skipping.\n", devname, error);
2227 } else if (bootverbose) {
2228 printf("Swap device %s removed.\n", devname);
2229 }
2230 mtx_lock(&sw_dev_mtx);
2231 }
2232 mtx_unlock(&sw_dev_mtx);
2233
2234 swdev_syscall_active = 0;
2235 wakeup_one(&swdev_syscall_active);
2236 mtx_unlock(&Giant);
2237}
2238
2239void
2240swap_pager_status(int *total, int *used)
2241{
2242 struct swdevt *sp;
2243
2244 *total = 0;
2245 *used = 0;
2246 mtx_lock(&sw_dev_mtx);
2247 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2248 *total += sp->sw_nblks;
2249 *used += sp->sw_used;
2250 }
2251 mtx_unlock(&sw_dev_mtx);
2252}
2253
2254static int
2255sysctl_vm_swap_info(SYSCTL_HANDLER_ARGS)
2256{
2257 int *name = (int *)arg1;
2258 int error, n;
2259 struct xswdev xs;
2260 struct swdevt *sp;
2261
2262 if (arg2 != 1) /* name length */
2263 return (EINVAL);
2264
2265 n = 0;
2266 mtx_lock(&sw_dev_mtx);
2267 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2268 if (n == *name) {
2269 mtx_unlock(&sw_dev_mtx);
2270 xs.xsw_version = XSWDEV_VERSION;
2271 xs.xsw_dev = sp->sw_dev;
2272 xs.xsw_flags = sp->sw_flags;
2273 xs.xsw_nblks = sp->sw_nblks;
2274 xs.xsw_used = sp->sw_used;
2275
2276 error = SYSCTL_OUT(req, &xs, sizeof(xs));
2277 return (error);
2278 }
2279 n++;
2280 }
2281 mtx_unlock(&sw_dev_mtx);
2282 return (ENOENT);
2283}
2284
2285SYSCTL_INT(_vm, OID_AUTO, nswapdev, CTLFLAG_RD, &nswapdev, 0,
2286 "Number of swap devices");
2287SYSCTL_NODE(_vm, OID_AUTO, swap_info, CTLFLAG_RD, sysctl_vm_swap_info,
2288 "Swap statistics by device");
2289
2290/*
2291 * vmspace_swap_count() - count the approximate swap useage in pages for a
2292 * vmspace.
2293 *
2294 * The map must be locked.
2295 *
2296 * Swap useage is determined by taking the proportional swap used by
2297 * VM objects backing the VM map. To make up for fractional losses,
2298 * if the VM object has any swap use at all the associated map entries
2299 * count for at least 1 swap page.
2300 */
2301int
2302vmspace_swap_count(struct vmspace *vmspace)
2303{
2304 vm_map_t map = &vmspace->vm_map;
2305 vm_map_entry_t cur;
2306 int count = 0;
2307
2308 for (cur = map->header.next; cur != &map->header; cur = cur->next) {
2309 vm_object_t object;
2310
2311 if ((cur->eflags & MAP_ENTRY_IS_SUB_MAP) == 0 &&
2312 (object = cur->object.vm_object) != NULL) {
2313 VM_OBJECT_LOCK(object);
2314 if (object->type == OBJT_SWAP &&
2315 object->un_pager.swp.swp_bcount != 0) {
2316 int n = (cur->end - cur->start) / PAGE_SIZE;
2317
2318 count += object->un_pager.swp.swp_bcount *
2319 SWAP_META_PAGES * n / object->size + 1;
2320 }
2321 VM_OBJECT_UNLOCK(object);
2322 }
2323 }
2324 return (count);
2325}
2326
2327/*
2328 * GEOM backend
2329 *
2330 * Swapping onto disk devices.
2331 *
2332 */
2333
2334static g_orphan_t swapgeom_orphan;
2335
2336static struct g_class g_swap_class = {
2337 .name = "SWAP",
2338 .version = G_VERSION,
2339 .orphan = swapgeom_orphan,
2340};
2341
2342DECLARE_GEOM_CLASS(g_swap_class, g_class);
2343
2344
2345static void
2346swapgeom_done(struct bio *bp2)
2347{
2348 struct buf *bp;
2349
2350 bp = bp2->bio_caller2;
2351 bp->b_ioflags = bp2->bio_flags;
2352 if (bp2->bio_error)
2353 bp->b_ioflags |= BIO_ERROR;
2354 bp->b_resid = bp->b_bcount - bp2->bio_completed;
2355 bp->b_error = bp2->bio_error;
2356 bufdone(bp);
2357 g_destroy_bio(bp2);
2358}
2359
2360static void
2361swapgeom_strategy(struct buf *bp, struct swdevt *sp)
2362{
2363 struct bio *bio;
2364 struct g_consumer *cp;
2365
2366 cp = sp->sw_id;
2367 if (cp == NULL) {
2368 bp->b_error = ENXIO;
2369 bp->b_ioflags |= BIO_ERROR;
2370 bufdone(bp);
2371 return;
2372 }
2373 bio = g_alloc_bio();
2374#if 0
2375 /*
2376 * XXX: We shouldn't really sleep here when we run out of buffers
2377 * XXX: but the alternative is worse right now.
2378 */
2379 if (bio == NULL) {
2380 bp->b_error = ENOMEM;
2381 bp->b_ioflags |= BIO_ERROR;
2382 bufdone(bp);
2383 return;
2384 }
2385#endif
2386 bio->bio_caller2 = bp;
2387 bio->bio_cmd = bp->b_iocmd;
2388 bio->bio_data = bp->b_data;
2389 bio->bio_offset = (bp->b_blkno - sp->sw_first) * PAGE_SIZE;
2390 bio->bio_length = bp->b_bcount;
2391 bio->bio_done = swapgeom_done;
2392 g_io_request(bio, cp);
2393 return;
2394}
2395
2396static void
2397swapgeom_orphan(struct g_consumer *cp)
2398{
2399 struct swdevt *sp;
2400
2401 mtx_lock(&sw_dev_mtx);
2402 TAILQ_FOREACH(sp, &swtailq, sw_list)
2403 if (sp->sw_id == cp)
2404 sp->sw_id = NULL;
2405 mtx_unlock(&sw_dev_mtx);
2406}
2407
2408static void
2409swapgeom_close_ev(void *arg, int flags)
2410{
2411 struct g_consumer *cp;
2412
2413 cp = arg;
2414 g_access(cp, -1, -1, 0);
2415 g_detach(cp);
2416 g_destroy_consumer(cp);
2417}
2418
2419static void
2420swapgeom_close(struct thread *td, struct swdevt *sw)
2421{
2422
2423 /* XXX: direct call when Giant untangled */
2424 g_waitfor_event(swapgeom_close_ev, sw->sw_id, M_WAITOK, NULL);
2425}
2426
2427
2428struct swh0h0 {
2429 struct cdev *dev;
2430 struct vnode *vp;
2431 int error;
2432};
2433
2434static void
2435swapongeom_ev(void *arg, int flags)
2436{
2437 struct swh0h0 *swh;
2438 struct g_provider *pp;
2439 struct g_consumer *cp;
2440 static struct g_geom *gp;
2441 struct swdevt *sp;
2442 u_long nblks;
2443 int error;
2444
2445 swh = arg;
2446 swh->error = 0;
2447 pp = g_dev_getprovider(swh->dev);
2448 if (pp == NULL) {
2449 swh->error = ENODEV;
2450 return;
2451 }
2452 mtx_lock(&sw_dev_mtx);
2453 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2454 cp = sp->sw_id;
2455 if (cp != NULL && cp->provider == pp) {
2456 mtx_unlock(&sw_dev_mtx);
2457 swh->error = EBUSY;
2458 return;
2459 }
2460 }
2461 mtx_unlock(&sw_dev_mtx);
2462 if (gp == NULL)
2463 gp = g_new_geomf(&g_swap_class, "swap", NULL);
2464 cp = g_new_consumer(gp);
2465 g_attach(cp, pp);
2466 /*
2467 * XXX: Everytime you think you can improve the margin for
2468 * footshooting, somebody depends on the ability to do so:
2469 * savecore(8) wants to write to our swapdev so we cannot
2470 * set an exclusive count :-(
2471 */
2472 error = g_access(cp, 1, 1, 0);
2473 if (error) {
2474 g_detach(cp);
2475 g_destroy_consumer(cp);
2476 swh->error = error;
2477 return;
2478 }
2479 nblks = pp->mediasize / DEV_BSIZE;
2480 swaponsomething(swh->vp, cp, nblks, swapgeom_strategy,
2481 swapgeom_close, dev2udev(swh->dev));
2482 swh->error = 0;
2483 return;
2484}
2485
2486static int
2487swapongeom(struct thread *td, struct vnode *vp)
2488{
2489 int error;
2490 struct swh0h0 swh;
2491
2492 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
2493
2494 swh.dev = vp->v_rdev;
2495 swh.vp = vp;
2496 swh.error = 0;
2497 /* XXX: direct call when Giant untangled */
2498 error = g_waitfor_event(swapongeom_ev, &swh, M_WAITOK, NULL);
2499 if (!error)
2500 error = swh.error;
2501 VOP_UNLOCK(vp, 0, td);
2502 return (error);
2503}
2504
2505/*
2506 * VNODE backend
2507 *
2508 * This is used mainly for network filesystem (read: probably only tested
2509 * with NFS) swapfiles.
2510 *
2511 */
2512
2513static void
2514swapdev_strategy(struct buf *bp, struct swdevt *sp)
2515{
2516 struct vnode *vp2;
2517
2518 bp->b_blkno = ctodb(bp->b_blkno - sp->sw_first);
2519
2520 vp2 = sp->sw_id;
2521 vhold(vp2);
2522 if (bp->b_iocmd == BIO_WRITE) {
2523 if (bp->b_bufobj)
2524 bufobj_wdrop(bp->b_bufobj);
2525 bufobj_wref(&vp2->v_bufobj);
2526 }
2527 if (bp->b_bufobj != &vp2->v_bufobj)
2528 bp->b_bufobj = &vp2->v_bufobj;
2529 bp->b_vp = vp2;
2530 bp->b_iooffset = dbtob(bp->b_blkno);
2531 bstrategy(bp);
2532 return;
2533}
2534
2535static void
2536swapdev_close(struct thread *td, struct swdevt *sp)
2537{
2538
2539 VOP_CLOSE(sp->sw_vp, FREAD | FWRITE, td->td_ucred, td);
2540 vrele(sp->sw_vp);
2541}
2542
2543
2544static int
2545swaponvp(struct thread *td, struct vnode *vp, u_long nblks)
2546{
2547 struct swdevt *sp;
2548 int error;
2549
2550 if (nblks == 0)
2551 return (ENXIO);
2552 mtx_lock(&sw_dev_mtx);
2553 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2554 if (sp->sw_id == vp) {
2555 mtx_unlock(&sw_dev_mtx);
2556 return (EBUSY);
2557 }
2558 }
2559 mtx_unlock(&sw_dev_mtx);
2560
2561 (void) vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
2562#ifdef MAC
2563 error = mac_check_system_swapon(td->td_ucred, vp);
2564 if (error == 0)
2565#endif
2566 error = VOP_OPEN(vp, FREAD | FWRITE, td->td_ucred, td, -1);
2567 (void) VOP_UNLOCK(vp, 0, td);
2568 if (error)
2569 return (error);
2570
2571 swaponsomething(vp, vp, nblks, swapdev_strategy, swapdev_close,
2572 NODEV);
2573 return (0);
2574}