]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/vm/swap_pager.c
swap pager: lock vnode around VOP_CLOSE()
[FreeBSD/FreeBSD.git] / sys / vm / swap_pager.c
1 /*-
2  * SPDX-License-Identifier: BSD-4-Clause
3  *
4  * Copyright (c) 1998 Matthew Dillon,
5  * Copyright (c) 1994 John S. Dyson
6  * Copyright (c) 1990 University of Utah.
7  * Copyright (c) 1982, 1986, 1989, 1993
8  *      The Regents of the University of California.  All rights reserved.
9  *
10  * This code is derived from software contributed to Berkeley by
11  * the Systems Programming Group of the University of Utah Computer
12  * Science Department.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  * 3. All advertising materials mentioning features or use of this software
23  *    must display the following acknowledgement:
24  *      This product includes software developed by the University of
25  *      California, Berkeley and its contributors.
26  * 4. Neither the name of the University nor the names of its contributors
27  *    may be used to endorse or promote products derived from this software
28  *    without specific prior written permission.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
31  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
34  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40  * SUCH DAMAGE.
41  *
42  *                              New Swap System
43  *                              Matthew Dillon
44  *
45  * Radix Bitmap 'blists'.
46  *
47  *      - The new swapper uses the new radix bitmap code.  This should scale
48  *        to arbitrarily small or arbitrarily large swap spaces and an almost
49  *        arbitrary degree of fragmentation.
50  *
51  * Features:
52  *
53  *      - on the fly reallocation of swap during putpages.  The new system
54  *        does not try to keep previously allocated swap blocks for dirty
55  *        pages.
56  *
57  *      - on the fly deallocation of swap
58  *
59  *      - No more garbage collection required.  Unnecessarily allocated swap
60  *        blocks only exist for dirty vm_page_t's now and these are already
61  *        cycled (in a high-load system) by the pager.  We also do on-the-fly
62  *        removal of invalidated swap blocks when a page is destroyed
63  *        or renamed.
64  *
65  * from: Utah $Hdr: swap_pager.c 1.4 91/04/30$
66  *
67  *      @(#)swap_pager.c        8.9 (Berkeley) 3/21/94
68  *      @(#)vm_swap.c   8.5 (Berkeley) 2/17/94
69  */
70
71 #include <sys/cdefs.h>
72 __FBSDID("$FreeBSD$");
73
74 #include "opt_vm.h"
75
76 #include <sys/param.h>
77 #include <sys/bio.h>
78 #include <sys/blist.h>
79 #include <sys/buf.h>
80 #include <sys/conf.h>
81 #include <sys/disk.h>
82 #include <sys/disklabel.h>
83 #include <sys/eventhandler.h>
84 #include <sys/fcntl.h>
85 #include <sys/limits.h>
86 #include <sys/lock.h>
87 #include <sys/kernel.h>
88 #include <sys/mount.h>
89 #include <sys/namei.h>
90 #include <sys/malloc.h>
91 #include <sys/pctrie.h>
92 #include <sys/priv.h>
93 #include <sys/proc.h>
94 #include <sys/racct.h>
95 #include <sys/resource.h>
96 #include <sys/resourcevar.h>
97 #include <sys/rwlock.h>
98 #include <sys/sbuf.h>
99 #include <sys/sysctl.h>
100 #include <sys/sysproto.h>
101 #include <sys/systm.h>
102 #include <sys/sx.h>
103 #include <sys/user.h>
104 #include <sys/vmmeter.h>
105 #include <sys/vnode.h>
106
107 #include <security/mac/mac_framework.h>
108
109 #include <vm/vm.h>
110 #include <vm/pmap.h>
111 #include <vm/vm_map.h>
112 #include <vm/vm_kern.h>
113 #include <vm/vm_object.h>
114 #include <vm/vm_page.h>
115 #include <vm/vm_pager.h>
116 #include <vm/vm_pageout.h>
117 #include <vm/vm_param.h>
118 #include <vm/swap_pager.h>
119 #include <vm/vm_extern.h>
120 #include <vm/uma.h>
121
122 #include <geom/geom.h>
123
124 /*
125  * MAX_PAGEOUT_CLUSTER must be a power of 2 between 1 and 64.
126  * The 64-page limit is due to the radix code (kern/subr_blist.c).
127  */
128 #ifndef MAX_PAGEOUT_CLUSTER
129 #define MAX_PAGEOUT_CLUSTER     32
130 #endif
131
132 #if !defined(SWB_NPAGES)
133 #define SWB_NPAGES      MAX_PAGEOUT_CLUSTER
134 #endif
135
136 #define SWAP_META_PAGES         PCTRIE_COUNT
137
138 /*
139  * A swblk structure maps each page index within a
140  * SWAP_META_PAGES-aligned and sized range to the address of an
141  * on-disk swap block (or SWAPBLK_NONE). The collection of these
142  * mappings for an entire vm object is implemented as a pc-trie.
143  */
144 struct swblk {
145         vm_pindex_t     p;
146         daddr_t         d[SWAP_META_PAGES];
147 };
148
149 static MALLOC_DEFINE(M_VMPGDATA, "vm_pgdata", "swap pager private data");
150 static struct mtx sw_dev_mtx;
151 static TAILQ_HEAD(, swdevt) swtailq = TAILQ_HEAD_INITIALIZER(swtailq);
152 static struct swdevt *swdevhd;  /* Allocate from here next */
153 static int nswapdev;            /* Number of swap devices */
154 int swap_pager_avail;
155 static struct sx swdev_syscall_lock;    /* serialize swap(on|off) */
156
157 static __exclusive_cache_line u_long swap_reserved;
158 static u_long swap_total;
159 static int sysctl_page_shift(SYSCTL_HANDLER_ARGS);
160
161 static SYSCTL_NODE(_vm_stats, OID_AUTO, swap, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
162     "VM swap stats");
163
164 SYSCTL_PROC(_vm, OID_AUTO, swap_reserved, CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE,
165     &swap_reserved, 0, sysctl_page_shift, "A", 
166     "Amount of swap storage needed to back all allocated anonymous memory.");
167 SYSCTL_PROC(_vm, OID_AUTO, swap_total, CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE,
168     &swap_total, 0, sysctl_page_shift, "A", 
169     "Total amount of available swap storage.");
170
171 static int overcommit = 0;
172 SYSCTL_INT(_vm, VM_OVERCOMMIT, overcommit, CTLFLAG_RW, &overcommit, 0,
173     "Configure virtual memory overcommit behavior. See tuning(7) "
174     "for details.");
175 static unsigned long swzone;
176 SYSCTL_ULONG(_vm, OID_AUTO, swzone, CTLFLAG_RD, &swzone, 0,
177     "Actual size of swap metadata zone");
178 static unsigned long swap_maxpages;
179 SYSCTL_ULONG(_vm, OID_AUTO, swap_maxpages, CTLFLAG_RD, &swap_maxpages, 0,
180     "Maximum amount of swap supported");
181
182 static COUNTER_U64_DEFINE_EARLY(swap_free_deferred);
183 SYSCTL_COUNTER_U64(_vm_stats_swap, OID_AUTO, free_deferred,
184     CTLFLAG_RD, &swap_free_deferred,
185     "Number of pages that deferred freeing swap space");
186
187 static COUNTER_U64_DEFINE_EARLY(swap_free_completed);
188 SYSCTL_COUNTER_U64(_vm_stats_swap, OID_AUTO, free_completed,
189     CTLFLAG_RD, &swap_free_completed,
190     "Number of deferred frees completed");
191
192 /* bits from overcommit */
193 #define SWAP_RESERVE_FORCE_ON           (1 << 0)
194 #define SWAP_RESERVE_RLIMIT_ON          (1 << 1)
195 #define SWAP_RESERVE_ALLOW_NONWIRED     (1 << 2)
196
197 static int
198 sysctl_page_shift(SYSCTL_HANDLER_ARGS)
199 {
200         uint64_t newval;
201         u_long value = *(u_long *)arg1;
202
203         newval = ((uint64_t)value) << PAGE_SHIFT;
204         return (sysctl_handle_64(oidp, &newval, 0, req));
205 }
206
207 static bool
208 swap_reserve_by_cred_rlimit(u_long pincr, struct ucred *cred, int oc)
209 {
210         struct uidinfo *uip;
211         u_long prev;
212
213         uip = cred->cr_ruidinfo;
214
215         prev = atomic_fetchadd_long(&uip->ui_vmsize, pincr);
216         if ((oc & SWAP_RESERVE_RLIMIT_ON) != 0 &&
217             prev + pincr > lim_cur(curthread, RLIMIT_SWAP) &&
218             priv_check(curthread, PRIV_VM_SWAP_NORLIMIT) != 0) {
219                 prev = atomic_fetchadd_long(&uip->ui_vmsize, -pincr);
220                 KASSERT(prev >= pincr, ("negative vmsize for uid = %d\n", uip->ui_uid));
221                 return (false);
222         }
223         return (true);
224 }
225
226 static void
227 swap_release_by_cred_rlimit(u_long pdecr, struct ucred *cred)
228 {
229         struct uidinfo *uip;
230 #ifdef INVARIANTS
231         u_long prev;
232 #endif
233
234         uip = cred->cr_ruidinfo;
235
236 #ifdef INVARIANTS
237         prev = atomic_fetchadd_long(&uip->ui_vmsize, -pdecr);
238         KASSERT(prev >= pdecr, ("negative vmsize for uid = %d\n", uip->ui_uid));
239 #else
240         atomic_subtract_long(&uip->ui_vmsize, pdecr);
241 #endif
242 }
243
244 static void
245 swap_reserve_force_rlimit(u_long pincr, struct ucred *cred)
246 {
247         struct uidinfo *uip;
248
249         uip = cred->cr_ruidinfo;
250         atomic_add_long(&uip->ui_vmsize, pincr);
251 }
252
253 bool
254 swap_reserve(vm_ooffset_t incr)
255 {
256
257         return (swap_reserve_by_cred(incr, curthread->td_ucred));
258 }
259
260 bool
261 swap_reserve_by_cred(vm_ooffset_t incr, struct ucred *cred)
262 {
263         u_long r, s, prev, pincr;
264 #ifdef RACCT
265         int error;
266 #endif
267         int oc;
268         static int curfail;
269         static struct timeval lastfail;
270
271         KASSERT((incr & PAGE_MASK) == 0, ("%s: incr: %ju & PAGE_MASK", __func__,
272             (uintmax_t)incr));
273
274 #ifdef RACCT
275         if (RACCT_ENABLED()) {
276                 PROC_LOCK(curproc);
277                 error = racct_add(curproc, RACCT_SWAP, incr);
278                 PROC_UNLOCK(curproc);
279                 if (error != 0)
280                         return (false);
281         }
282 #endif
283
284         pincr = atop(incr);
285         prev = atomic_fetchadd_long(&swap_reserved, pincr);
286         r = prev + pincr;
287         s = swap_total;
288         oc = atomic_load_int(&overcommit);
289         if (r > s && (oc & SWAP_RESERVE_ALLOW_NONWIRED) != 0) {
290                 s += vm_cnt.v_page_count - vm_cnt.v_free_reserved -
291                     vm_wire_count();
292         }
293         if ((oc & SWAP_RESERVE_FORCE_ON) != 0 && r > s &&
294             priv_check(curthread, PRIV_VM_SWAP_NOQUOTA) != 0) {
295                 prev = atomic_fetchadd_long(&swap_reserved, -pincr);
296                 KASSERT(prev >= pincr, ("swap_reserved < incr on overcommit fail"));
297                 goto out_error;
298         }
299
300         if (!swap_reserve_by_cred_rlimit(pincr, cred, oc)) {
301                 prev = atomic_fetchadd_long(&swap_reserved, -pincr);
302                 KASSERT(prev >= pincr, ("swap_reserved < incr on overcommit fail"));
303                 goto out_error;
304         }
305
306         return (true);
307
308 out_error:
309         if (ppsratecheck(&lastfail, &curfail, 1)) {
310                 printf("uid %d, pid %d: swap reservation for %jd bytes failed\n",
311                     cred->cr_ruidinfo->ui_uid, curproc->p_pid, incr);
312         }
313 #ifdef RACCT
314         if (RACCT_ENABLED()) {
315                 PROC_LOCK(curproc);
316                 racct_sub(curproc, RACCT_SWAP, incr);
317                 PROC_UNLOCK(curproc);
318         }
319 #endif
320
321         return (false);
322 }
323
324 void
325 swap_reserve_force(vm_ooffset_t incr)
326 {
327         u_long pincr;
328
329         KASSERT((incr & PAGE_MASK) == 0, ("%s: incr: %ju & PAGE_MASK", __func__,
330             (uintmax_t)incr));
331
332 #ifdef RACCT
333         if (RACCT_ENABLED()) {
334                 PROC_LOCK(curproc);
335                 racct_add_force(curproc, RACCT_SWAP, incr);
336                 PROC_UNLOCK(curproc);
337         }
338 #endif
339         pincr = atop(incr);
340         atomic_add_long(&swap_reserved, pincr);
341         swap_reserve_force_rlimit(pincr, curthread->td_ucred);
342 }
343
344 void
345 swap_release(vm_ooffset_t decr)
346 {
347         struct ucred *cred;
348
349         PROC_LOCK(curproc);
350         cred = curproc->p_ucred;
351         swap_release_by_cred(decr, cred);
352         PROC_UNLOCK(curproc);
353 }
354
355 void
356 swap_release_by_cred(vm_ooffset_t decr, struct ucred *cred)
357 {
358         u_long pdecr;
359 #ifdef INVARIANTS
360         u_long prev;
361 #endif
362
363         KASSERT((decr & PAGE_MASK) == 0, ("%s: decr: %ju & PAGE_MASK", __func__,
364             (uintmax_t)decr));
365
366         pdecr = atop(decr);
367 #ifdef INVARIANTS
368         prev = atomic_fetchadd_long(&swap_reserved, -pdecr);
369         KASSERT(prev >= pdecr, ("swap_reserved < decr"));
370 #else
371         atomic_subtract_long(&swap_reserved, pdecr);
372 #endif
373
374         swap_release_by_cred_rlimit(pdecr, cred);
375 #ifdef RACCT
376         if (racct_enable)
377                 racct_sub_cred(cred, RACCT_SWAP, decr);
378 #endif
379 }
380
381 static int swap_pager_full = 2; /* swap space exhaustion (task killing) */
382 static int swap_pager_almost_full = 1; /* swap space exhaustion (w/hysteresis)*/
383 static struct mtx swbuf_mtx;    /* to sync nsw_wcount_async */
384 static int nsw_wcount_async;    /* limit async write buffers */
385 static int nsw_wcount_async_max;/* assigned maximum                     */
386 static int nsw_cluster_max;     /* maximum VOP I/O allowed              */
387
388 static int sysctl_swap_async_max(SYSCTL_HANDLER_ARGS);
389 SYSCTL_PROC(_vm, OID_AUTO, swap_async_max, CTLTYPE_INT | CTLFLAG_RW |
390     CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_async_max, "I",
391     "Maximum running async swap ops");
392 static int sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS);
393 SYSCTL_PROC(_vm, OID_AUTO, swap_fragmentation, CTLTYPE_STRING | CTLFLAG_RD |
394     CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_fragmentation, "A",
395     "Swap Fragmentation Info");
396
397 static struct sx sw_alloc_sx;
398
399 /*
400  * "named" and "unnamed" anon region objects.  Try to reduce the overhead
401  * of searching a named list by hashing it just a little.
402  */
403
404 #define NOBJLISTS               8
405
406 #define NOBJLIST(handle)        \
407         (&swap_pager_object_list[((int)(intptr_t)handle >> 4) & (NOBJLISTS-1)])
408
409 static struct pagerlst  swap_pager_object_list[NOBJLISTS];
410 static uma_zone_t swwbuf_zone;
411 static uma_zone_t swrbuf_zone;
412 static uma_zone_t swblk_zone;
413 static uma_zone_t swpctrie_zone;
414
415 /*
416  * pagerops for OBJT_SWAP - "swap pager".  Some ops are also global procedure
417  * calls hooked from other parts of the VM system and do not appear here.
418  * (see vm/swap_pager.h).
419  */
420 static vm_object_t
421                 swap_pager_alloc(void *handle, vm_ooffset_t size,
422                     vm_prot_t prot, vm_ooffset_t offset, struct ucred *);
423 static void     swap_pager_dealloc(vm_object_t object);
424 static int      swap_pager_getpages(vm_object_t, vm_page_t *, int, int *,
425     int *);
426 static int      swap_pager_getpages_async(vm_object_t, vm_page_t *, int, int *,
427     int *, pgo_getpages_iodone_t, void *);
428 static void     swap_pager_putpages(vm_object_t, vm_page_t *, int, boolean_t, int *);
429 static boolean_t
430                 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before, int *after);
431 static void     swap_pager_init(void);
432 static void     swap_pager_unswapped(vm_page_t);
433 static void     swap_pager_swapoff(struct swdevt *sp);
434 static void     swap_pager_update_writecount(vm_object_t object,
435     vm_offset_t start, vm_offset_t end);
436 static void     swap_pager_release_writecount(vm_object_t object,
437     vm_offset_t start, vm_offset_t end);
438 static void     swap_pager_freespace(vm_object_t object, vm_pindex_t start,
439     vm_size_t size);
440
441 const struct pagerops swappagerops = {
442         .pgo_kvme_type = KVME_TYPE_SWAP,
443         .pgo_init =     swap_pager_init,        /* early system initialization of pager */
444         .pgo_alloc =    swap_pager_alloc,       /* allocate an OBJT_SWAP object */
445         .pgo_dealloc =  swap_pager_dealloc,     /* deallocate an OBJT_SWAP object */
446         .pgo_getpages = swap_pager_getpages,    /* pagein */
447         .pgo_getpages_async = swap_pager_getpages_async, /* pagein (async) */
448         .pgo_putpages = swap_pager_putpages,    /* pageout */
449         .pgo_haspage =  swap_pager_haspage,     /* get backing store status for page */
450         .pgo_pageunswapped = swap_pager_unswapped, /* remove swap related to page */
451         .pgo_update_writecount = swap_pager_update_writecount,
452         .pgo_release_writecount = swap_pager_release_writecount,
453         .pgo_freespace = swap_pager_freespace,
454 };
455
456 /*
457  * swap_*() routines are externally accessible.  swp_*() routines are
458  * internal.
459  */
460 static int nswap_lowat = 128;   /* in pages, swap_pager_almost_full warn */
461 static int nswap_hiwat = 512;   /* in pages, swap_pager_almost_full warn */
462
463 SYSCTL_INT(_vm, OID_AUTO, dmmax, CTLFLAG_RD, &nsw_cluster_max, 0,
464     "Maximum size of a swap block in pages");
465
466 static void     swp_sizecheck(void);
467 static void     swp_pager_async_iodone(struct buf *bp);
468 static bool     swp_pager_swblk_empty(struct swblk *sb, int start, int limit);
469 static void     swp_pager_free_empty_swblk(vm_object_t, struct swblk *sb);
470 static int      swapongeom(struct vnode *);
471 static int      swaponvp(struct thread *, struct vnode *, u_long);
472 static int      swapoff_one(struct swdevt *sp, struct ucred *cred);
473
474 /*
475  * Swap bitmap functions
476  */
477 static void     swp_pager_freeswapspace(daddr_t blk, daddr_t npages);
478 static daddr_t  swp_pager_getswapspace(int *npages);
479
480 /*
481  * Metadata functions
482  */
483 static daddr_t swp_pager_meta_build(vm_object_t, vm_pindex_t, daddr_t);
484 static void swp_pager_meta_free(vm_object_t, vm_pindex_t, vm_pindex_t);
485 static void swp_pager_meta_transfer(vm_object_t src, vm_object_t dst,
486     vm_pindex_t pindex, vm_pindex_t count);
487 static void swp_pager_meta_free_all(vm_object_t);
488 static daddr_t swp_pager_meta_lookup(vm_object_t, vm_pindex_t);
489
490 static void
491 swp_pager_init_freerange(daddr_t *start, daddr_t *num)
492 {
493
494         *start = SWAPBLK_NONE;
495         *num = 0;
496 }
497
498 static void
499 swp_pager_update_freerange(daddr_t *start, daddr_t *num, daddr_t addr)
500 {
501
502         if (*start + *num == addr) {
503                 (*num)++;
504         } else {
505                 swp_pager_freeswapspace(*start, *num);
506                 *start = addr;
507                 *num = 1;
508         }
509 }
510
511 static void *
512 swblk_trie_alloc(struct pctrie *ptree)
513 {
514
515         return (uma_zalloc(swpctrie_zone, M_NOWAIT | (curproc == pageproc ?
516             M_USE_RESERVE : 0)));
517 }
518
519 static void
520 swblk_trie_free(struct pctrie *ptree, void *node)
521 {
522
523         uma_zfree(swpctrie_zone, node);
524 }
525
526 PCTRIE_DEFINE(SWAP, swblk, p, swblk_trie_alloc, swblk_trie_free);
527
528 /*
529  * SWP_SIZECHECK() -    update swap_pager_full indication
530  *
531  *      update the swap_pager_almost_full indication and warn when we are
532  *      about to run out of swap space, using lowat/hiwat hysteresis.
533  *
534  *      Clear swap_pager_full ( task killing ) indication when lowat is met.
535  *
536  *      No restrictions on call
537  *      This routine may not block.
538  */
539 static void
540 swp_sizecheck(void)
541 {
542
543         if (swap_pager_avail < nswap_lowat) {
544                 if (swap_pager_almost_full == 0) {
545                         printf("swap_pager: out of swap space\n");
546                         swap_pager_almost_full = 1;
547                 }
548         } else {
549                 swap_pager_full = 0;
550                 if (swap_pager_avail > nswap_hiwat)
551                         swap_pager_almost_full = 0;
552         }
553 }
554
555 /*
556  * SWAP_PAGER_INIT() -  initialize the swap pager!
557  *
558  *      Expected to be started from system init.  NOTE:  This code is run
559  *      before much else so be careful what you depend on.  Most of the VM
560  *      system has yet to be initialized at this point.
561  */
562 static void
563 swap_pager_init(void)
564 {
565         /*
566          * Initialize object lists
567          */
568         int i;
569
570         for (i = 0; i < NOBJLISTS; ++i)
571                 TAILQ_INIT(&swap_pager_object_list[i]);
572         mtx_init(&sw_dev_mtx, "swapdev", NULL, MTX_DEF);
573         sx_init(&sw_alloc_sx, "swspsx");
574         sx_init(&swdev_syscall_lock, "swsysc");
575 }
576
577 /*
578  * SWAP_PAGER_SWAP_INIT() - swap pager initialization from pageout process
579  *
580  *      Expected to be started from pageout process once, prior to entering
581  *      its main loop.
582  */
583 void
584 swap_pager_swap_init(void)
585 {
586         unsigned long n, n2;
587
588         /*
589          * Number of in-transit swap bp operations.  Don't
590          * exhaust the pbufs completely.  Make sure we
591          * initialize workable values (0 will work for hysteresis
592          * but it isn't very efficient).
593          *
594          * The nsw_cluster_max is constrained by the bp->b_pages[]
595          * array, which has maxphys / PAGE_SIZE entries, and our locally
596          * defined MAX_PAGEOUT_CLUSTER.   Also be aware that swap ops are
597          * constrained by the swap device interleave stripe size.
598          *
599          * Currently we hardwire nsw_wcount_async to 4.  This limit is
600          * designed to prevent other I/O from having high latencies due to
601          * our pageout I/O.  The value 4 works well for one or two active swap
602          * devices but is probably a little low if you have more.  Even so,
603          * a higher value would probably generate only a limited improvement
604          * with three or four active swap devices since the system does not
605          * typically have to pageout at extreme bandwidths.   We will want
606          * at least 2 per swap devices, and 4 is a pretty good value if you
607          * have one NFS swap device due to the command/ack latency over NFS.
608          * So it all works out pretty well.
609          */
610         nsw_cluster_max = min(maxphys / PAGE_SIZE, MAX_PAGEOUT_CLUSTER);
611
612         nsw_wcount_async = 4;
613         nsw_wcount_async_max = nsw_wcount_async;
614         mtx_init(&swbuf_mtx, "async swbuf mutex", NULL, MTX_DEF);
615
616         swwbuf_zone = pbuf_zsecond_create("swwbuf", nswbuf / 4);
617         swrbuf_zone = pbuf_zsecond_create("swrbuf", nswbuf / 2);
618
619         /*
620          * Initialize our zone, taking the user's requested size or
621          * estimating the number we need based on the number of pages
622          * in the system.
623          */
624         n = maxswzone != 0 ? maxswzone / sizeof(struct swblk) :
625             vm_cnt.v_page_count / 2;
626         swpctrie_zone = uma_zcreate("swpctrie", pctrie_node_size(), NULL, NULL,
627             pctrie_zone_init, NULL, UMA_ALIGN_PTR, 0);
628         if (swpctrie_zone == NULL)
629                 panic("failed to create swap pctrie zone.");
630         swblk_zone = uma_zcreate("swblk", sizeof(struct swblk), NULL, NULL,
631             NULL, NULL, _Alignof(struct swblk) - 1, 0);
632         if (swblk_zone == NULL)
633                 panic("failed to create swap blk zone.");
634         n2 = n;
635         do {
636                 if (uma_zone_reserve_kva(swblk_zone, n))
637                         break;
638                 /*
639                  * if the allocation failed, try a zone two thirds the
640                  * size of the previous attempt.
641                  */
642                 n -= ((n + 2) / 3);
643         } while (n > 0);
644
645         /*
646          * Often uma_zone_reserve_kva() cannot reserve exactly the
647          * requested size.  Account for the difference when
648          * calculating swap_maxpages.
649          */
650         n = uma_zone_get_max(swblk_zone);
651
652         if (n < n2)
653                 printf("Swap blk zone entries changed from %lu to %lu.\n",
654                     n2, n);
655         /* absolute maximum we can handle assuming 100% efficiency */
656         swap_maxpages = n * SWAP_META_PAGES;
657         swzone = n * sizeof(struct swblk);
658         if (!uma_zone_reserve_kva(swpctrie_zone, n))
659                 printf("Cannot reserve swap pctrie zone, "
660                     "reduce kern.maxswzone.\n");
661 }
662
663 bool
664 swap_pager_init_object(vm_object_t object, void *handle, struct ucred *cred,
665     vm_ooffset_t size, vm_ooffset_t offset)
666 {
667         if (cred != NULL) {
668                 if (!swap_reserve_by_cred(size, cred))
669                         return (false);
670                 crhold(cred);
671         }
672
673         object->un_pager.swp.writemappings = 0;
674         object->handle = handle;
675         if (cred != NULL) {
676                 object->cred = cred;
677                 object->charge = size;
678         }
679         return (true);
680 }
681
682 static vm_object_t
683 swap_pager_alloc_init(objtype_t otype, void *handle, struct ucred *cred,
684     vm_ooffset_t size, vm_ooffset_t offset)
685 {
686         vm_object_t object;
687
688         /*
689          * The un_pager.swp.swp_blks trie is initialized by
690          * vm_object_allocate() to ensure the correct order of
691          * visibility to other threads.
692          */
693         object = vm_object_allocate(otype, OFF_TO_IDX(offset +
694             PAGE_MASK + size));
695
696         if (!swap_pager_init_object(object, handle, cred, size, offset)) {
697                 vm_object_deallocate(object);
698                 return (NULL);
699         }
700         return (object);
701 }
702
703 /*
704  * SWAP_PAGER_ALLOC() - allocate a new OBJT_SWAP VM object and instantiate
705  *                      its metadata structures.
706  *
707  *      This routine is called from the mmap and fork code to create a new
708  *      OBJT_SWAP object.
709  *
710  *      This routine must ensure that no live duplicate is created for
711  *      the named object request, which is protected against by
712  *      holding the sw_alloc_sx lock in case handle != NULL.
713  */
714 static vm_object_t
715 swap_pager_alloc(void *handle, vm_ooffset_t size, vm_prot_t prot,
716     vm_ooffset_t offset, struct ucred *cred)
717 {
718         vm_object_t object;
719
720         if (handle != NULL) {
721                 /*
722                  * Reference existing named region or allocate new one.  There
723                  * should not be a race here against swp_pager_meta_build()
724                  * as called from vm_page_remove() in regards to the lookup
725                  * of the handle.
726                  */
727                 sx_xlock(&sw_alloc_sx);
728                 object = vm_pager_object_lookup(NOBJLIST(handle), handle);
729                 if (object == NULL) {
730                         object = swap_pager_alloc_init(OBJT_SWAP, handle, cred,
731                             size, offset);
732                         if (object != NULL) {
733                                 TAILQ_INSERT_TAIL(NOBJLIST(object->handle),
734                                     object, pager_object_list);
735                         }
736                 }
737                 sx_xunlock(&sw_alloc_sx);
738         } else {
739                 object = swap_pager_alloc_init(OBJT_SWAP, handle, cred,
740                     size, offset);
741         }
742         return (object);
743 }
744
745 /*
746  * SWAP_PAGER_DEALLOC() -       remove swap metadata from object
747  *
748  *      The swap backing for the object is destroyed.  The code is
749  *      designed such that we can reinstantiate it later, but this
750  *      routine is typically called only when the entire object is
751  *      about to be destroyed.
752  *
753  *      The object must be locked.
754  */
755 static void
756 swap_pager_dealloc(vm_object_t object)
757 {
758
759         VM_OBJECT_ASSERT_WLOCKED(object);
760         KASSERT((object->flags & OBJ_DEAD) != 0, ("dealloc of reachable obj"));
761
762         /*
763          * Remove from list right away so lookups will fail if we block for
764          * pageout completion.
765          */
766         if ((object->flags & OBJ_ANON) == 0 && object->handle != NULL) {
767                 VM_OBJECT_WUNLOCK(object);
768                 sx_xlock(&sw_alloc_sx);
769                 TAILQ_REMOVE(NOBJLIST(object->handle), object,
770                     pager_object_list);
771                 sx_xunlock(&sw_alloc_sx);
772                 VM_OBJECT_WLOCK(object);
773         }
774
775         vm_object_pip_wait(object, "swpdea");
776
777         /*
778          * Free all remaining metadata.  We only bother to free it from
779          * the swap meta data.  We do not attempt to free swapblk's still
780          * associated with vm_page_t's for this object.  We do not care
781          * if paging is still in progress on some objects.
782          */
783         swp_pager_meta_free_all(object);
784         object->handle = NULL;
785         object->type = OBJT_DEAD;
786         vm_object_clear_flag(object, OBJ_SWAP);
787 }
788
789 /************************************************************************
790  *                      SWAP PAGER BITMAP ROUTINES                      *
791  ************************************************************************/
792
793 /*
794  * SWP_PAGER_GETSWAPSPACE() -   allocate raw swap space
795  *
796  *      Allocate swap for up to the requested number of pages.  The
797  *      starting swap block number (a page index) is returned or
798  *      SWAPBLK_NONE if the allocation failed.
799  *
800  *      Also has the side effect of advising that somebody made a mistake
801  *      when they configured swap and didn't configure enough.
802  *
803  *      This routine may not sleep.
804  *
805  *      We allocate in round-robin fashion from the configured devices.
806  */
807 static daddr_t
808 swp_pager_getswapspace(int *io_npages)
809 {
810         daddr_t blk;
811         struct swdevt *sp;
812         int mpages, npages;
813
814         KASSERT(*io_npages >= 1,
815             ("%s: npages not positive", __func__));
816         blk = SWAPBLK_NONE;
817         mpages = *io_npages;
818         npages = imin(BLIST_MAX_ALLOC, mpages);
819         mtx_lock(&sw_dev_mtx);
820         sp = swdevhd;
821         while (!TAILQ_EMPTY(&swtailq)) {
822                 if (sp == NULL)
823                         sp = TAILQ_FIRST(&swtailq);
824                 if ((sp->sw_flags & SW_CLOSING) == 0)
825                         blk = blist_alloc(sp->sw_blist, &npages, mpages);
826                 if (blk != SWAPBLK_NONE)
827                         break;
828                 sp = TAILQ_NEXT(sp, sw_list);
829                 if (swdevhd == sp) {
830                         if (npages == 1)
831                                 break;
832                         mpages = npages - 1;
833                         npages >>= 1;
834                 }
835         }
836         if (blk != SWAPBLK_NONE) {
837                 *io_npages = npages;
838                 blk += sp->sw_first;
839                 sp->sw_used += npages;
840                 swap_pager_avail -= npages;
841                 swp_sizecheck();
842                 swdevhd = TAILQ_NEXT(sp, sw_list);
843         } else {
844                 if (swap_pager_full != 2) {
845                         printf("swp_pager_getswapspace(%d): failed\n",
846                             *io_npages);
847                         swap_pager_full = 2;
848                         swap_pager_almost_full = 1;
849                 }
850                 swdevhd = NULL;
851         }
852         mtx_unlock(&sw_dev_mtx);
853         return (blk);
854 }
855
856 static bool
857 swp_pager_isondev(daddr_t blk, struct swdevt *sp)
858 {
859
860         return (blk >= sp->sw_first && blk < sp->sw_end);
861 }
862
863 static void
864 swp_pager_strategy(struct buf *bp)
865 {
866         struct swdevt *sp;
867
868         mtx_lock(&sw_dev_mtx);
869         TAILQ_FOREACH(sp, &swtailq, sw_list) {
870                 if (swp_pager_isondev(bp->b_blkno, sp)) {
871                         mtx_unlock(&sw_dev_mtx);
872                         if ((sp->sw_flags & SW_UNMAPPED) != 0 &&
873                             unmapped_buf_allowed) {
874                                 bp->b_data = unmapped_buf;
875                                 bp->b_offset = 0;
876                         } else {
877                                 pmap_qenter((vm_offset_t)bp->b_data,
878                                     &bp->b_pages[0], bp->b_bcount / PAGE_SIZE);
879                         }
880                         sp->sw_strategy(bp, sp);
881                         return;
882                 }
883         }
884         panic("Swapdev not found");
885 }
886
887 /*
888  * SWP_PAGER_FREESWAPSPACE() -  free raw swap space
889  *
890  *      This routine returns the specified swap blocks back to the bitmap.
891  *
892  *      This routine may not sleep.
893  */
894 static void
895 swp_pager_freeswapspace(daddr_t blk, daddr_t npages)
896 {
897         struct swdevt *sp;
898
899         if (npages == 0)
900                 return;
901         mtx_lock(&sw_dev_mtx);
902         TAILQ_FOREACH(sp, &swtailq, sw_list) {
903                 if (swp_pager_isondev(blk, sp)) {
904                         sp->sw_used -= npages;
905                         /*
906                          * If we are attempting to stop swapping on
907                          * this device, we don't want to mark any
908                          * blocks free lest they be reused.
909                          */
910                         if ((sp->sw_flags & SW_CLOSING) == 0) {
911                                 blist_free(sp->sw_blist, blk - sp->sw_first,
912                                     npages);
913                                 swap_pager_avail += npages;
914                                 swp_sizecheck();
915                         }
916                         mtx_unlock(&sw_dev_mtx);
917                         return;
918                 }
919         }
920         panic("Swapdev not found");
921 }
922
923 /*
924  * SYSCTL_SWAP_FRAGMENTATION() -        produce raw swap space stats
925  */
926 static int
927 sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS)
928 {
929         struct sbuf sbuf;
930         struct swdevt *sp;
931         const char *devname;
932         int error;
933
934         error = sysctl_wire_old_buffer(req, 0);
935         if (error != 0)
936                 return (error);
937         sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
938         mtx_lock(&sw_dev_mtx);
939         TAILQ_FOREACH(sp, &swtailq, sw_list) {
940                 if (vn_isdisk(sp->sw_vp))
941                         devname = devtoname(sp->sw_vp->v_rdev);
942                 else
943                         devname = "[file]";
944                 sbuf_printf(&sbuf, "\nFree space on device %s:\n", devname);
945                 blist_stats(sp->sw_blist, &sbuf);
946         }
947         mtx_unlock(&sw_dev_mtx);
948         error = sbuf_finish(&sbuf);
949         sbuf_delete(&sbuf);
950         return (error);
951 }
952
953 /*
954  * SWAP_PAGER_FREESPACE() -     frees swap blocks associated with a page
955  *                              range within an object.
956  *
957  *      This routine removes swapblk assignments from swap metadata.
958  *
959  *      The external callers of this routine typically have already destroyed
960  *      or renamed vm_page_t's associated with this range in the object so
961  *      we should be ok.
962  *
963  *      The object must be locked.
964  */
965 static void
966 swap_pager_freespace(vm_object_t object, vm_pindex_t start, vm_size_t size)
967 {
968
969         swp_pager_meta_free(object, start, size);
970 }
971
972 /*
973  * SWAP_PAGER_RESERVE() - reserve swap blocks in object
974  *
975  *      Assigns swap blocks to the specified range within the object.  The
976  *      swap blocks are not zeroed.  Any previous swap assignment is destroyed.
977  *
978  *      Returns 0 on success, -1 on failure.
979  */
980 int
981 swap_pager_reserve(vm_object_t object, vm_pindex_t start, vm_pindex_t size)
982 {
983         daddr_t addr, blk, n_free, s_free;
984         vm_pindex_t i, j;
985         int n;
986
987         swp_pager_init_freerange(&s_free, &n_free);
988         VM_OBJECT_WLOCK(object);
989         for (i = 0; i < size; i += n) {
990                 n = MIN(size - i, INT_MAX);
991                 blk = swp_pager_getswapspace(&n);
992                 if (blk == SWAPBLK_NONE) {
993                         swp_pager_meta_free(object, start, i);
994                         VM_OBJECT_WUNLOCK(object);
995                         return (-1);
996                 }
997                 for (j = 0; j < n; ++j) {
998                         addr = swp_pager_meta_build(object,
999                             start + i + j, blk + j);
1000                         if (addr != SWAPBLK_NONE)
1001                                 swp_pager_update_freerange(&s_free, &n_free,
1002                                     addr);
1003                 }
1004         }
1005         swp_pager_freeswapspace(s_free, n_free);
1006         VM_OBJECT_WUNLOCK(object);
1007         return (0);
1008 }
1009
1010 static bool
1011 swp_pager_xfer_source(vm_object_t srcobject, vm_object_t dstobject,
1012     vm_pindex_t pindex, daddr_t addr)
1013 {
1014         daddr_t dstaddr;
1015
1016         KASSERT((srcobject->flags & OBJ_SWAP) != 0,
1017             ("%s: Srcobject not swappable", __func__));
1018         if ((dstobject->flags & OBJ_SWAP) != 0 &&
1019             swp_pager_meta_lookup(dstobject, pindex) != SWAPBLK_NONE) {
1020                 /* Caller should destroy the source block. */
1021                 return (false);
1022         }
1023
1024         /*
1025          * Destination has no swapblk and is not resident, transfer source.
1026          * swp_pager_meta_build() can sleep.
1027          */
1028         VM_OBJECT_WUNLOCK(srcobject);
1029         dstaddr = swp_pager_meta_build(dstobject, pindex, addr);
1030         KASSERT(dstaddr == SWAPBLK_NONE,
1031             ("Unexpected destination swapblk"));
1032         VM_OBJECT_WLOCK(srcobject);
1033
1034         return (true);
1035 }
1036
1037 /*
1038  * SWAP_PAGER_COPY() -  copy blocks from source pager to destination pager
1039  *                      and destroy the source.
1040  *
1041  *      Copy any valid swapblks from the source to the destination.  In
1042  *      cases where both the source and destination have a valid swapblk,
1043  *      we keep the destination's.
1044  *
1045  *      This routine is allowed to sleep.  It may sleep allocating metadata
1046  *      indirectly through swp_pager_meta_build().
1047  *
1048  *      The source object contains no vm_page_t's (which is just as well)
1049  *
1050  *      The source object is of type OBJT_SWAP.
1051  *
1052  *      The source and destination objects must be locked.
1053  *      Both object locks may temporarily be released.
1054  */
1055 void
1056 swap_pager_copy(vm_object_t srcobject, vm_object_t dstobject,
1057     vm_pindex_t offset, int destroysource)
1058 {
1059
1060         VM_OBJECT_ASSERT_WLOCKED(srcobject);
1061         VM_OBJECT_ASSERT_WLOCKED(dstobject);
1062
1063         /*
1064          * If destroysource is set, we remove the source object from the
1065          * swap_pager internal queue now.
1066          */
1067         if (destroysource && (srcobject->flags & OBJ_ANON) == 0 &&
1068             srcobject->handle != NULL) {
1069                 VM_OBJECT_WUNLOCK(srcobject);
1070                 VM_OBJECT_WUNLOCK(dstobject);
1071                 sx_xlock(&sw_alloc_sx);
1072                 TAILQ_REMOVE(NOBJLIST(srcobject->handle), srcobject,
1073                     pager_object_list);
1074                 sx_xunlock(&sw_alloc_sx);
1075                 VM_OBJECT_WLOCK(dstobject);
1076                 VM_OBJECT_WLOCK(srcobject);
1077         }
1078
1079         /*
1080          * Transfer source to destination.
1081          */
1082         swp_pager_meta_transfer(srcobject, dstobject, offset, dstobject->size);
1083
1084         /*
1085          * Free left over swap blocks in source.
1086          *
1087          * We have to revert the type to OBJT_DEFAULT so we do not accidentally
1088          * double-remove the object from the swap queues.
1089          */
1090         if (destroysource) {
1091                 swp_pager_meta_free_all(srcobject);
1092                 /*
1093                  * Reverting the type is not necessary, the caller is going
1094                  * to destroy srcobject directly, but I'm doing it here
1095                  * for consistency since we've removed the object from its
1096                  * queues.
1097                  */
1098                 srcobject->type = OBJT_DEFAULT;
1099                 vm_object_clear_flag(srcobject, OBJ_SWAP);
1100         }
1101 }
1102
1103 /*
1104  * SWAP_PAGER_HASPAGE() -       determine if we have good backing store for
1105  *                              the requested page.
1106  *
1107  *      We determine whether good backing store exists for the requested
1108  *      page and return TRUE if it does, FALSE if it doesn't.
1109  *
1110  *      If TRUE, we also try to determine how much valid, contiguous backing
1111  *      store exists before and after the requested page.
1112  */
1113 static boolean_t
1114 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before,
1115     int *after)
1116 {
1117         daddr_t blk, blk0;
1118         int i;
1119
1120         VM_OBJECT_ASSERT_LOCKED(object);
1121         KASSERT((object->flags & OBJ_SWAP) != 0,
1122             ("%s: object not swappable", __func__));
1123
1124         /*
1125          * do we have good backing store at the requested index ?
1126          */
1127         blk0 = swp_pager_meta_lookup(object, pindex);
1128         if (blk0 == SWAPBLK_NONE) {
1129                 if (before)
1130                         *before = 0;
1131                 if (after)
1132                         *after = 0;
1133                 return (FALSE);
1134         }
1135
1136         /*
1137          * find backwards-looking contiguous good backing store
1138          */
1139         if (before != NULL) {
1140                 for (i = 1; i < SWB_NPAGES; i++) {
1141                         if (i > pindex)
1142                                 break;
1143                         blk = swp_pager_meta_lookup(object, pindex - i);
1144                         if (blk != blk0 - i)
1145                                 break;
1146                 }
1147                 *before = i - 1;
1148         }
1149
1150         /*
1151          * find forward-looking contiguous good backing store
1152          */
1153         if (after != NULL) {
1154                 for (i = 1; i < SWB_NPAGES; i++) {
1155                         blk = swp_pager_meta_lookup(object, pindex + i);
1156                         if (blk != blk0 + i)
1157                                 break;
1158                 }
1159                 *after = i - 1;
1160         }
1161         return (TRUE);
1162 }
1163
1164 /*
1165  * SWAP_PAGER_PAGE_UNSWAPPED() - remove swap backing store related to page
1166  *
1167  *      This removes any associated swap backing store, whether valid or
1168  *      not, from the page.
1169  *
1170  *      This routine is typically called when a page is made dirty, at
1171  *      which point any associated swap can be freed.  MADV_FREE also
1172  *      calls us in a special-case situation
1173  *
1174  *      NOTE!!!  If the page is clean and the swap was valid, the caller
1175  *      should make the page dirty before calling this routine.  This routine
1176  *      does NOT change the m->dirty status of the page.  Also: MADV_FREE
1177  *      depends on it.
1178  *
1179  *      This routine may not sleep.
1180  *
1181  *      The object containing the page may be locked.
1182  */
1183 static void
1184 swap_pager_unswapped(vm_page_t m)
1185 {
1186         struct swblk *sb;
1187         vm_object_t obj;
1188
1189         /*
1190          * Handle enqueing deferred frees first.  If we do not have the
1191          * object lock we wait for the page daemon to clear the space.
1192          */
1193         obj = m->object;
1194         if (!VM_OBJECT_WOWNED(obj)) {
1195                 VM_PAGE_OBJECT_BUSY_ASSERT(m);
1196                 /*
1197                  * The caller is responsible for synchronization but we
1198                  * will harmlessly handle races.  This is typically provided
1199                  * by only calling unswapped() when a page transitions from
1200                  * clean to dirty.
1201                  */
1202                 if ((m->a.flags & (PGA_SWAP_SPACE | PGA_SWAP_FREE)) ==
1203                     PGA_SWAP_SPACE) {
1204                         vm_page_aflag_set(m, PGA_SWAP_FREE);
1205                         counter_u64_add(swap_free_deferred, 1);
1206                 }
1207                 return;
1208         }
1209         if ((m->a.flags & PGA_SWAP_FREE) != 0)
1210                 counter_u64_add(swap_free_completed, 1);
1211         vm_page_aflag_clear(m, PGA_SWAP_FREE | PGA_SWAP_SPACE);
1212
1213         /*
1214          * The meta data only exists if the object is OBJT_SWAP
1215          * and even then might not be allocated yet.
1216          */
1217         KASSERT((m->object->flags & OBJ_SWAP) != 0,
1218             ("Free object not swappable"));
1219
1220         sb = SWAP_PCTRIE_LOOKUP(&m->object->un_pager.swp.swp_blks,
1221             rounddown(m->pindex, SWAP_META_PAGES));
1222         if (sb == NULL)
1223                 return;
1224         if (sb->d[m->pindex % SWAP_META_PAGES] == SWAPBLK_NONE)
1225                 return;
1226         swp_pager_freeswapspace(sb->d[m->pindex % SWAP_META_PAGES], 1);
1227         sb->d[m->pindex % SWAP_META_PAGES] = SWAPBLK_NONE;
1228         swp_pager_free_empty_swblk(m->object, sb);
1229 }
1230
1231 /*
1232  * swap_pager_getpages() - bring pages in from swap
1233  *
1234  *      Attempt to page in the pages in array "ma" of length "count".  The
1235  *      caller may optionally specify that additional pages preceding and
1236  *      succeeding the specified range be paged in.  The number of such pages
1237  *      is returned in the "rbehind" and "rahead" parameters, and they will
1238  *      be in the inactive queue upon return.
1239  *
1240  *      The pages in "ma" must be busied and will remain busied upon return.
1241  */
1242 static int
1243 swap_pager_getpages_locked(vm_object_t object, vm_page_t *ma, int count,
1244     int *rbehind, int *rahead)
1245 {
1246         struct buf *bp;
1247         vm_page_t bm, mpred, msucc, p;
1248         vm_pindex_t pindex;
1249         daddr_t blk;
1250         int i, maxahead, maxbehind, reqcount;
1251
1252         VM_OBJECT_ASSERT_WLOCKED(object);
1253         reqcount = count;
1254
1255         KASSERT((object->flags & OBJ_SWAP) != 0,
1256             ("%s: object not swappable", __func__));
1257         if (!swap_pager_haspage(object, ma[0]->pindex, &maxbehind, &maxahead)) {
1258                 VM_OBJECT_WUNLOCK(object);
1259                 return (VM_PAGER_FAIL);
1260         }
1261
1262         KASSERT(reqcount - 1 <= maxahead,
1263             ("page count %d extends beyond swap block", reqcount));
1264
1265         /*
1266          * Do not transfer any pages other than those that are xbusied
1267          * when running during a split or collapse operation.  This
1268          * prevents clustering from re-creating pages which are being
1269          * moved into another object.
1270          */
1271         if ((object->flags & (OBJ_SPLIT | OBJ_DEAD)) != 0) {
1272                 maxahead = reqcount - 1;
1273                 maxbehind = 0;
1274         }
1275
1276         /*
1277          * Clip the readahead and readbehind ranges to exclude resident pages.
1278          */
1279         if (rahead != NULL) {
1280                 *rahead = imin(*rahead, maxahead - (reqcount - 1));
1281                 pindex = ma[reqcount - 1]->pindex;
1282                 msucc = TAILQ_NEXT(ma[reqcount - 1], listq);
1283                 if (msucc != NULL && msucc->pindex - pindex - 1 < *rahead)
1284                         *rahead = msucc->pindex - pindex - 1;
1285         }
1286         if (rbehind != NULL) {
1287                 *rbehind = imin(*rbehind, maxbehind);
1288                 pindex = ma[0]->pindex;
1289                 mpred = TAILQ_PREV(ma[0], pglist, listq);
1290                 if (mpred != NULL && pindex - mpred->pindex - 1 < *rbehind)
1291                         *rbehind = pindex - mpred->pindex - 1;
1292         }
1293
1294         bm = ma[0];
1295         for (i = 0; i < count; i++)
1296                 ma[i]->oflags |= VPO_SWAPINPROG;
1297
1298         /*
1299          * Allocate readahead and readbehind pages.
1300          */
1301         if (rbehind != NULL) {
1302                 for (i = 1; i <= *rbehind; i++) {
1303                         p = vm_page_alloc(object, ma[0]->pindex - i,
1304                             VM_ALLOC_NORMAL);
1305                         if (p == NULL)
1306                                 break;
1307                         p->oflags |= VPO_SWAPINPROG;
1308                         bm = p;
1309                 }
1310                 *rbehind = i - 1;
1311         }
1312         if (rahead != NULL) {
1313                 for (i = 0; i < *rahead; i++) {
1314                         p = vm_page_alloc(object,
1315                             ma[reqcount - 1]->pindex + i + 1, VM_ALLOC_NORMAL);
1316                         if (p == NULL)
1317                                 break;
1318                         p->oflags |= VPO_SWAPINPROG;
1319                 }
1320                 *rahead = i;
1321         }
1322         if (rbehind != NULL)
1323                 count += *rbehind;
1324         if (rahead != NULL)
1325                 count += *rahead;
1326
1327         vm_object_pip_add(object, count);
1328
1329         pindex = bm->pindex;
1330         blk = swp_pager_meta_lookup(object, pindex);
1331         KASSERT(blk != SWAPBLK_NONE,
1332             ("no swap blocking containing %p(%jx)", object, (uintmax_t)pindex));
1333
1334         VM_OBJECT_WUNLOCK(object);
1335         bp = uma_zalloc(swrbuf_zone, M_WAITOK);
1336         MPASS((bp->b_flags & B_MAXPHYS) != 0);
1337         /* Pages cannot leave the object while busy. */
1338         for (i = 0, p = bm; i < count; i++, p = TAILQ_NEXT(p, listq)) {
1339                 MPASS(p->pindex == bm->pindex + i);
1340                 bp->b_pages[i] = p;
1341         }
1342
1343         bp->b_flags |= B_PAGING;
1344         bp->b_iocmd = BIO_READ;
1345         bp->b_iodone = swp_pager_async_iodone;
1346         bp->b_rcred = crhold(thread0.td_ucred);
1347         bp->b_wcred = crhold(thread0.td_ucred);
1348         bp->b_blkno = blk;
1349         bp->b_bcount = PAGE_SIZE * count;
1350         bp->b_bufsize = PAGE_SIZE * count;
1351         bp->b_npages = count;
1352         bp->b_pgbefore = rbehind != NULL ? *rbehind : 0;
1353         bp->b_pgafter = rahead != NULL ? *rahead : 0;
1354
1355         VM_CNT_INC(v_swapin);
1356         VM_CNT_ADD(v_swappgsin, count);
1357
1358         /*
1359          * perform the I/O.  NOTE!!!  bp cannot be considered valid after
1360          * this point because we automatically release it on completion.
1361          * Instead, we look at the one page we are interested in which we
1362          * still hold a lock on even through the I/O completion.
1363          *
1364          * The other pages in our ma[] array are also released on completion,
1365          * so we cannot assume they are valid anymore either.
1366          *
1367          * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1368          */
1369         BUF_KERNPROC(bp);
1370         swp_pager_strategy(bp);
1371
1372         /*
1373          * Wait for the pages we want to complete.  VPO_SWAPINPROG is always
1374          * cleared on completion.  If an I/O error occurs, SWAPBLK_NONE
1375          * is set in the metadata for each page in the request.
1376          */
1377         VM_OBJECT_WLOCK(object);
1378         /* This could be implemented more efficiently with aflags */
1379         while ((ma[0]->oflags & VPO_SWAPINPROG) != 0) {
1380                 ma[0]->oflags |= VPO_SWAPSLEEP;
1381                 VM_CNT_INC(v_intrans);
1382                 if (VM_OBJECT_SLEEP(object, &object->handle, PSWP,
1383                     "swread", hz * 20)) {
1384                         printf(
1385 "swap_pager: indefinite wait buffer: bufobj: %p, blkno: %jd, size: %ld\n",
1386                             bp->b_bufobj, (intmax_t)bp->b_blkno, bp->b_bcount);
1387                 }
1388         }
1389         VM_OBJECT_WUNLOCK(object);
1390
1391         /*
1392          * If we had an unrecoverable read error pages will not be valid.
1393          */
1394         for (i = 0; i < reqcount; i++)
1395                 if (ma[i]->valid != VM_PAGE_BITS_ALL)
1396                         return (VM_PAGER_ERROR);
1397
1398         return (VM_PAGER_OK);
1399
1400         /*
1401          * A final note: in a low swap situation, we cannot deallocate swap
1402          * and mark a page dirty here because the caller is likely to mark
1403          * the page clean when we return, causing the page to possibly revert
1404          * to all-zero's later.
1405          */
1406 }
1407
1408 static int
1409 swap_pager_getpages(vm_object_t object, vm_page_t *ma, int count,
1410     int *rbehind, int *rahead)
1411 {
1412
1413         VM_OBJECT_WLOCK(object);
1414         return (swap_pager_getpages_locked(object, ma, count, rbehind, rahead));
1415 }
1416
1417 /*
1418  *      swap_pager_getpages_async():
1419  *
1420  *      Right now this is emulation of asynchronous operation on top of
1421  *      swap_pager_getpages().
1422  */
1423 static int
1424 swap_pager_getpages_async(vm_object_t object, vm_page_t *ma, int count,
1425     int *rbehind, int *rahead, pgo_getpages_iodone_t iodone, void *arg)
1426 {
1427         int r, error;
1428
1429         r = swap_pager_getpages(object, ma, count, rbehind, rahead);
1430         switch (r) {
1431         case VM_PAGER_OK:
1432                 error = 0;
1433                 break;
1434         case VM_PAGER_ERROR:
1435                 error = EIO;
1436                 break;
1437         case VM_PAGER_FAIL:
1438                 error = EINVAL;
1439                 break;
1440         default:
1441                 panic("unhandled swap_pager_getpages() error %d", r);
1442         }
1443         (iodone)(arg, ma, count, error);
1444
1445         return (r);
1446 }
1447
1448 /*
1449  *      swap_pager_putpages:
1450  *
1451  *      Assign swap (if necessary) and initiate I/O on the specified pages.
1452  *
1453  *      We support both OBJT_DEFAULT and OBJT_SWAP objects.  DEFAULT objects
1454  *      are automatically converted to SWAP objects.
1455  *
1456  *      In a low memory situation we may block in VOP_STRATEGY(), but the new
1457  *      vm_page reservation system coupled with properly written VFS devices
1458  *      should ensure that no low-memory deadlock occurs.  This is an area
1459  *      which needs work.
1460  *
1461  *      The parent has N vm_object_pip_add() references prior to
1462  *      calling us and will remove references for rtvals[] that are
1463  *      not set to VM_PAGER_PEND.  We need to remove the rest on I/O
1464  *      completion.
1465  *
1466  *      The parent has soft-busy'd the pages it passes us and will unbusy
1467  *      those whose rtvals[] entry is not set to VM_PAGER_PEND on return.
1468  *      We need to unbusy the rest on I/O completion.
1469  */
1470 static void
1471 swap_pager_putpages(vm_object_t object, vm_page_t *ma, int count,
1472     int flags, int *rtvals)
1473 {
1474         struct buf *bp;
1475         daddr_t addr, blk, n_free, s_free;
1476         vm_page_t mreq;
1477         int i, j, n;
1478         bool async;
1479
1480         KASSERT(count == 0 || ma[0]->object == object,
1481             ("%s: object mismatch %p/%p",
1482             __func__, object, ma[0]->object));
1483
1484         /*
1485          * Step 1
1486          *
1487          * Turn object into OBJT_SWAP.  Force sync if not a pageout process.
1488          */
1489         if ((object->flags & OBJ_SWAP) == 0) {
1490                 addr = swp_pager_meta_build(object, 0, SWAPBLK_NONE);
1491                 KASSERT(addr == SWAPBLK_NONE,
1492                     ("unexpected object swap block"));
1493         }
1494         VM_OBJECT_WUNLOCK(object);
1495         async = curproc == pageproc && (flags & VM_PAGER_PUT_SYNC) == 0;
1496         swp_pager_init_freerange(&s_free, &n_free);
1497
1498         /*
1499          * Step 2
1500          *
1501          * Assign swap blocks and issue I/O.  We reallocate swap on the fly.
1502          * The page is left dirty until the pageout operation completes
1503          * successfully.
1504          */
1505         for (i = 0; i < count; i += n) {
1506                 /* Maximum I/O size is limited by maximum swap block size. */
1507                 n = min(count - i, nsw_cluster_max);
1508
1509                 if (async) {
1510                         mtx_lock(&swbuf_mtx);
1511                         while (nsw_wcount_async == 0)
1512                                 msleep(&nsw_wcount_async, &swbuf_mtx, PVM,
1513                                     "swbufa", 0);
1514                         nsw_wcount_async--;
1515                         mtx_unlock(&swbuf_mtx);
1516                 }
1517
1518                 /* Get a block of swap of size up to size n. */
1519                 VM_OBJECT_WLOCK(object);
1520                 blk = swp_pager_getswapspace(&n);
1521                 if (blk == SWAPBLK_NONE) {
1522                         VM_OBJECT_WUNLOCK(object);
1523                         mtx_lock(&swbuf_mtx);
1524                         if (++nsw_wcount_async == 1)
1525                                 wakeup(&nsw_wcount_async);
1526                         mtx_unlock(&swbuf_mtx);
1527                         for (j = 0; j < n; ++j)
1528                                 rtvals[i + j] = VM_PAGER_FAIL;
1529                         continue;
1530                 }
1531                 for (j = 0; j < n; ++j) {
1532                         mreq = ma[i + j];
1533                         vm_page_aflag_clear(mreq, PGA_SWAP_FREE);
1534                         addr = swp_pager_meta_build(mreq->object, mreq->pindex,
1535                             blk + j);
1536                         if (addr != SWAPBLK_NONE)
1537                                 swp_pager_update_freerange(&s_free, &n_free,
1538                                     addr);
1539                         MPASS(mreq->dirty == VM_PAGE_BITS_ALL);
1540                         mreq->oflags |= VPO_SWAPINPROG;
1541                 }
1542                 VM_OBJECT_WUNLOCK(object);
1543
1544                 bp = uma_zalloc(swwbuf_zone, M_WAITOK);
1545                 MPASS((bp->b_flags & B_MAXPHYS) != 0);
1546                 if (async)
1547                         bp->b_flags |= B_ASYNC;
1548                 bp->b_flags |= B_PAGING;
1549                 bp->b_iocmd = BIO_WRITE;
1550
1551                 bp->b_rcred = crhold(thread0.td_ucred);
1552                 bp->b_wcred = crhold(thread0.td_ucred);
1553                 bp->b_bcount = PAGE_SIZE * n;
1554                 bp->b_bufsize = PAGE_SIZE * n;
1555                 bp->b_blkno = blk;
1556                 for (j = 0; j < n; j++)
1557                         bp->b_pages[j] = ma[i + j];
1558                 bp->b_npages = n;
1559
1560                 /*
1561                  * Must set dirty range for NFS to work.
1562                  */
1563                 bp->b_dirtyoff = 0;
1564                 bp->b_dirtyend = bp->b_bcount;
1565
1566                 VM_CNT_INC(v_swapout);
1567                 VM_CNT_ADD(v_swappgsout, bp->b_npages);
1568
1569                 /*
1570                  * We unconditionally set rtvals[] to VM_PAGER_PEND so that we
1571                  * can call the async completion routine at the end of a
1572                  * synchronous I/O operation.  Otherwise, our caller would
1573                  * perform duplicate unbusy and wakeup operations on the page
1574                  * and object, respectively.
1575                  */
1576                 for (j = 0; j < n; j++)
1577                         rtvals[i + j] = VM_PAGER_PEND;
1578
1579                 /*
1580                  * asynchronous
1581                  *
1582                  * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
1583                  */
1584                 if (async) {
1585                         bp->b_iodone = swp_pager_async_iodone;
1586                         BUF_KERNPROC(bp);
1587                         swp_pager_strategy(bp);
1588                         continue;
1589                 }
1590
1591                 /*
1592                  * synchronous
1593                  *
1594                  * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
1595                  */
1596                 bp->b_iodone = bdone;
1597                 swp_pager_strategy(bp);
1598
1599                 /*
1600                  * Wait for the sync I/O to complete.
1601                  */
1602                 bwait(bp, PVM, "swwrt");
1603
1604                 /*
1605                  * Now that we are through with the bp, we can call the
1606                  * normal async completion, which frees everything up.
1607                  */
1608                 swp_pager_async_iodone(bp);
1609         }
1610         swp_pager_freeswapspace(s_free, n_free);
1611         VM_OBJECT_WLOCK(object);
1612 }
1613
1614 /*
1615  *      swp_pager_async_iodone:
1616  *
1617  *      Completion routine for asynchronous reads and writes from/to swap.
1618  *      Also called manually by synchronous code to finish up a bp.
1619  *
1620  *      This routine may not sleep.
1621  */
1622 static void
1623 swp_pager_async_iodone(struct buf *bp)
1624 {
1625         int i;
1626         vm_object_t object = NULL;
1627
1628         /*
1629          * Report error - unless we ran out of memory, in which case
1630          * we've already logged it in swapgeom_strategy().
1631          */
1632         if (bp->b_ioflags & BIO_ERROR && bp->b_error != ENOMEM) {
1633                 printf(
1634                     "swap_pager: I/O error - %s failed; blkno %ld,"
1635                         "size %ld, error %d\n",
1636                     ((bp->b_iocmd == BIO_READ) ? "pagein" : "pageout"),
1637                     (long)bp->b_blkno,
1638                     (long)bp->b_bcount,
1639                     bp->b_error
1640                 );
1641         }
1642
1643         /*
1644          * remove the mapping for kernel virtual
1645          */
1646         if (buf_mapped(bp))
1647                 pmap_qremove((vm_offset_t)bp->b_data, bp->b_npages);
1648         else
1649                 bp->b_data = bp->b_kvabase;
1650
1651         if (bp->b_npages) {
1652                 object = bp->b_pages[0]->object;
1653                 VM_OBJECT_WLOCK(object);
1654         }
1655
1656         /*
1657          * cleanup pages.  If an error occurs writing to swap, we are in
1658          * very serious trouble.  If it happens to be a disk error, though,
1659          * we may be able to recover by reassigning the swap later on.  So
1660          * in this case we remove the m->swapblk assignment for the page
1661          * but do not free it in the rlist.  The errornous block(s) are thus
1662          * never reallocated as swap.  Redirty the page and continue.
1663          */
1664         for (i = 0; i < bp->b_npages; ++i) {
1665                 vm_page_t m = bp->b_pages[i];
1666
1667                 m->oflags &= ~VPO_SWAPINPROG;
1668                 if (m->oflags & VPO_SWAPSLEEP) {
1669                         m->oflags &= ~VPO_SWAPSLEEP;
1670                         wakeup(&object->handle);
1671                 }
1672
1673                 /* We always have space after I/O, successful or not. */
1674                 vm_page_aflag_set(m, PGA_SWAP_SPACE);
1675
1676                 if (bp->b_ioflags & BIO_ERROR) {
1677                         /*
1678                          * If an error occurs I'd love to throw the swapblk
1679                          * away without freeing it back to swapspace, so it
1680                          * can never be used again.  But I can't from an
1681                          * interrupt.
1682                          */
1683                         if (bp->b_iocmd == BIO_READ) {
1684                                 /*
1685                                  * NOTE: for reads, m->dirty will probably
1686                                  * be overridden by the original caller of
1687                                  * getpages so don't play cute tricks here.
1688                                  */
1689                                 vm_page_invalid(m);
1690                         } else {
1691                                 /*
1692                                  * If a write error occurs, reactivate page
1693                                  * so it doesn't clog the inactive list,
1694                                  * then finish the I/O.
1695                                  */
1696                                 MPASS(m->dirty == VM_PAGE_BITS_ALL);
1697
1698                                 /* PQ_UNSWAPPABLE? */
1699                                 vm_page_activate(m);
1700                                 vm_page_sunbusy(m);
1701                         }
1702                 } else if (bp->b_iocmd == BIO_READ) {
1703                         /*
1704                          * NOTE: for reads, m->dirty will probably be
1705                          * overridden by the original caller of getpages so
1706                          * we cannot set them in order to free the underlying
1707                          * swap in a low-swap situation.  I don't think we'd
1708                          * want to do that anyway, but it was an optimization
1709                          * that existed in the old swapper for a time before
1710                          * it got ripped out due to precisely this problem.
1711                          */
1712                         KASSERT(!pmap_page_is_mapped(m),
1713                             ("swp_pager_async_iodone: page %p is mapped", m));
1714                         KASSERT(m->dirty == 0,
1715                             ("swp_pager_async_iodone: page %p is dirty", m));
1716
1717                         vm_page_valid(m);
1718                         if (i < bp->b_pgbefore ||
1719                             i >= bp->b_npages - bp->b_pgafter)
1720                                 vm_page_readahead_finish(m);
1721                 } else {
1722                         /*
1723                          * For write success, clear the dirty
1724                          * status, then finish the I/O ( which decrements the
1725                          * busy count and possibly wakes waiter's up ).
1726                          * A page is only written to swap after a period of
1727                          * inactivity.  Therefore, we do not expect it to be
1728                          * reused.
1729                          */
1730                         KASSERT(!pmap_page_is_write_mapped(m),
1731                             ("swp_pager_async_iodone: page %p is not write"
1732                             " protected", m));
1733                         vm_page_undirty(m);
1734                         vm_page_deactivate_noreuse(m);
1735                         vm_page_sunbusy(m);
1736                 }
1737         }
1738
1739         /*
1740          * adjust pip.  NOTE: the original parent may still have its own
1741          * pip refs on the object.
1742          */
1743         if (object != NULL) {
1744                 vm_object_pip_wakeupn(object, bp->b_npages);
1745                 VM_OBJECT_WUNLOCK(object);
1746         }
1747
1748         /*
1749          * swapdev_strategy() manually sets b_vp and b_bufobj before calling
1750          * bstrategy(). Set them back to NULL now we're done with it, or we'll
1751          * trigger a KASSERT in relpbuf().
1752          */
1753         if (bp->b_vp) {
1754                     bp->b_vp = NULL;
1755                     bp->b_bufobj = NULL;
1756         }
1757         /*
1758          * release the physical I/O buffer
1759          */
1760         if (bp->b_flags & B_ASYNC) {
1761                 mtx_lock(&swbuf_mtx);
1762                 if (++nsw_wcount_async == 1)
1763                         wakeup(&nsw_wcount_async);
1764                 mtx_unlock(&swbuf_mtx);
1765         }
1766         uma_zfree((bp->b_iocmd == BIO_READ) ? swrbuf_zone : swwbuf_zone, bp);
1767 }
1768
1769 int
1770 swap_pager_nswapdev(void)
1771 {
1772
1773         return (nswapdev);
1774 }
1775
1776 static void
1777 swp_pager_force_dirty(vm_page_t m)
1778 {
1779
1780         vm_page_dirty(m);
1781         swap_pager_unswapped(m);
1782         vm_page_launder(m);
1783 }
1784
1785 u_long
1786 swap_pager_swapped_pages(vm_object_t object)
1787 {
1788         struct swblk *sb;
1789         vm_pindex_t pi;
1790         u_long res;
1791         int i;
1792
1793         VM_OBJECT_ASSERT_LOCKED(object);
1794         if ((object->flags & OBJ_SWAP) == 0)
1795                 return (0);
1796
1797         for (res = 0, pi = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
1798             &object->un_pager.swp.swp_blks, pi)) != NULL;
1799             pi = sb->p + SWAP_META_PAGES) {
1800                 for (i = 0; i < SWAP_META_PAGES; i++) {
1801                         if (sb->d[i] != SWAPBLK_NONE)
1802                                 res++;
1803                 }
1804         }
1805         return (res);
1806 }
1807
1808 /*
1809  *      swap_pager_swapoff_object:
1810  *
1811  *      Page in all of the pages that have been paged out for an object
1812  *      to a swap device.
1813  */
1814 static void
1815 swap_pager_swapoff_object(struct swdevt *sp, vm_object_t object)
1816 {
1817         struct swblk *sb;
1818         vm_page_t m;
1819         vm_pindex_t pi;
1820         daddr_t blk;
1821         int i, nv, rahead, rv;
1822
1823         KASSERT((object->flags & OBJ_SWAP) != 0,
1824             ("%s: Object not swappable", __func__));
1825
1826         for (pi = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
1827             &object->un_pager.swp.swp_blks, pi)) != NULL; ) {
1828                 if ((object->flags & OBJ_DEAD) != 0) {
1829                         /*
1830                          * Make sure that pending writes finish before
1831                          * returning.
1832                          */
1833                         vm_object_pip_wait(object, "swpoff");
1834                         swp_pager_meta_free_all(object);
1835                         break;
1836                 }
1837                 for (i = 0; i < SWAP_META_PAGES; i++) {
1838                         /*
1839                          * Count the number of contiguous valid blocks.
1840                          */
1841                         for (nv = 0; nv < SWAP_META_PAGES - i; nv++) {
1842                                 blk = sb->d[i + nv];
1843                                 if (!swp_pager_isondev(blk, sp) ||
1844                                     blk == SWAPBLK_NONE)
1845                                         break;
1846                         }
1847                         if (nv == 0)
1848                                 continue;
1849
1850                         /*
1851                          * Look for a page corresponding to the first
1852                          * valid block and ensure that any pending paging
1853                          * operations on it are complete.  If the page is valid,
1854                          * mark it dirty and free the swap block.  Try to batch
1855                          * this operation since it may cause sp to be freed,
1856                          * meaning that we must restart the scan.  Avoid busying
1857                          * valid pages since we may block forever on kernel
1858                          * stack pages.
1859                          */
1860                         m = vm_page_lookup(object, sb->p + i);
1861                         if (m == NULL) {
1862                                 m = vm_page_alloc(object, sb->p + i,
1863                                     VM_ALLOC_NORMAL | VM_ALLOC_WAITFAIL);
1864                                 if (m == NULL)
1865                                         break;
1866                         } else {
1867                                 if ((m->oflags & VPO_SWAPINPROG) != 0) {
1868                                         m->oflags |= VPO_SWAPSLEEP;
1869                                         VM_OBJECT_SLEEP(object, &object->handle,
1870                                             PSWP, "swpoff", 0);
1871                                         break;
1872                                 }
1873                                 if (vm_page_all_valid(m)) {
1874                                         do {
1875                                                 swp_pager_force_dirty(m);
1876                                         } while (--nv > 0 &&
1877                                             (m = vm_page_next(m)) != NULL &&
1878                                             vm_page_all_valid(m) &&
1879                                             (m->oflags & VPO_SWAPINPROG) == 0);
1880                                         break;
1881                                 }
1882                                 if (!vm_page_busy_acquire(m, VM_ALLOC_WAITFAIL))
1883                                         break;
1884                         }
1885
1886                         vm_object_pip_add(object, 1);
1887                         rahead = SWAP_META_PAGES;
1888                         rv = swap_pager_getpages_locked(object, &m, 1, NULL,
1889                             &rahead);
1890                         if (rv != VM_PAGER_OK)
1891                                 panic("%s: read from swap failed: %d",
1892                                     __func__, rv);
1893                         vm_object_pip_wakeupn(object, 1);
1894                         VM_OBJECT_WLOCK(object);
1895                         vm_page_xunbusy(m);
1896
1897                         /*
1898                          * The object lock was dropped so we must restart the
1899                          * scan of this swap block.  Pages paged in during this
1900                          * iteration will be marked dirty in a future iteration.
1901                          */
1902                         break;
1903                 }
1904                 if (i == SWAP_META_PAGES)
1905                         pi = sb->p + SWAP_META_PAGES;
1906         }
1907 }
1908
1909 /*
1910  *      swap_pager_swapoff:
1911  *
1912  *      Page in all of the pages that have been paged out to the
1913  *      given device.  The corresponding blocks in the bitmap must be
1914  *      marked as allocated and the device must be flagged SW_CLOSING.
1915  *      There may be no processes swapped out to the device.
1916  *
1917  *      This routine may block.
1918  */
1919 static void
1920 swap_pager_swapoff(struct swdevt *sp)
1921 {
1922         vm_object_t object;
1923         int retries;
1924
1925         sx_assert(&swdev_syscall_lock, SA_XLOCKED);
1926
1927         retries = 0;
1928 full_rescan:
1929         mtx_lock(&vm_object_list_mtx);
1930         TAILQ_FOREACH(object, &vm_object_list, object_list) {
1931                 if ((object->flags & OBJ_SWAP) == 0)
1932                         continue;
1933                 mtx_unlock(&vm_object_list_mtx);
1934                 /* Depends on type-stability. */
1935                 VM_OBJECT_WLOCK(object);
1936
1937                 /*
1938                  * Dead objects are eventually terminated on their own.
1939                  */
1940                 if ((object->flags & OBJ_DEAD) != 0)
1941                         goto next_obj;
1942
1943                 /*
1944                  * Sync with fences placed after pctrie
1945                  * initialization.  We must not access pctrie below
1946                  * unless we checked that our object is swap and not
1947                  * dead.
1948                  */
1949                 atomic_thread_fence_acq();
1950                 if ((object->flags & OBJ_SWAP) == 0)
1951                         goto next_obj;
1952
1953                 swap_pager_swapoff_object(sp, object);
1954 next_obj:
1955                 VM_OBJECT_WUNLOCK(object);
1956                 mtx_lock(&vm_object_list_mtx);
1957         }
1958         mtx_unlock(&vm_object_list_mtx);
1959
1960         if (sp->sw_used) {
1961                 /*
1962                  * Objects may be locked or paging to the device being
1963                  * removed, so we will miss their pages and need to
1964                  * make another pass.  We have marked this device as
1965                  * SW_CLOSING, so the activity should finish soon.
1966                  */
1967                 retries++;
1968                 if (retries > 100) {
1969                         panic("swapoff: failed to locate %d swap blocks",
1970                             sp->sw_used);
1971                 }
1972                 pause("swpoff", hz / 20);
1973                 goto full_rescan;
1974         }
1975         EVENTHANDLER_INVOKE(swapoff, sp);
1976 }
1977
1978 /************************************************************************
1979  *                              SWAP META DATA                          *
1980  ************************************************************************
1981  *
1982  *      These routines manipulate the swap metadata stored in the
1983  *      OBJT_SWAP object.
1984  *
1985  *      Swap metadata is implemented with a global hash and not directly
1986  *      linked into the object.  Instead the object simply contains
1987  *      appropriate tracking counters.
1988  */
1989
1990 /*
1991  * SWP_PAGER_SWBLK_EMPTY() - is a range of blocks free?
1992  */
1993 static bool
1994 swp_pager_swblk_empty(struct swblk *sb, int start, int limit)
1995 {
1996         int i;
1997
1998         MPASS(0 <= start && start <= limit && limit <= SWAP_META_PAGES);
1999         for (i = start; i < limit; i++) {
2000                 if (sb->d[i] != SWAPBLK_NONE)
2001                         return (false);
2002         }
2003         return (true);
2004 }
2005
2006 /*
2007  * SWP_PAGER_FREE_EMPTY_SWBLK() - frees if a block is free
2008  *
2009  *  Nothing is done if the block is still in use.
2010  */
2011 static void
2012 swp_pager_free_empty_swblk(vm_object_t object, struct swblk *sb)
2013 {
2014
2015         if (swp_pager_swblk_empty(sb, 0, SWAP_META_PAGES)) {
2016                 SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
2017                 uma_zfree(swblk_zone, sb);
2018         }
2019 }
2020    
2021 /*
2022  * SWP_PAGER_META_BUILD() -     add swap block to swap meta data for object
2023  *
2024  *      We first convert the object to a swap object if it is a default
2025  *      object.
2026  *
2027  *      The specified swapblk is added to the object's swap metadata.  If
2028  *      the swapblk is not valid, it is freed instead.  Any previously
2029  *      assigned swapblk is returned.
2030  */
2031 static daddr_t
2032 swp_pager_meta_build(vm_object_t object, vm_pindex_t pindex, daddr_t swapblk)
2033 {
2034         static volatile int swblk_zone_exhausted, swpctrie_zone_exhausted;
2035         struct swblk *sb, *sb1;
2036         vm_pindex_t modpi, rdpi;
2037         daddr_t prev_swapblk;
2038         int error, i;
2039
2040         VM_OBJECT_ASSERT_WLOCKED(object);
2041
2042         /*
2043          * Convert default object to swap object if necessary
2044          */
2045         if ((object->flags & OBJ_SWAP) == 0) {
2046                 pctrie_init(&object->un_pager.swp.swp_blks);
2047
2048                 /*
2049                  * Ensure that swap_pager_swapoff()'s iteration over
2050                  * object_list does not see a garbage pctrie.
2051                  */
2052                 atomic_thread_fence_rel();
2053
2054                 object->type = OBJT_SWAP;
2055                 vm_object_set_flag(object, OBJ_SWAP);
2056                 object->un_pager.swp.writemappings = 0;
2057                 KASSERT((object->flags & OBJ_ANON) != 0 ||
2058                     object->handle == NULL,
2059                     ("default pager %p with handle %p",
2060                     object, object->handle));
2061         }
2062
2063         rdpi = rounddown(pindex, SWAP_META_PAGES);
2064         sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks, rdpi);
2065         if (sb == NULL) {
2066                 if (swapblk == SWAPBLK_NONE)
2067                         return (SWAPBLK_NONE);
2068                 for (;;) {
2069                         sb = uma_zalloc(swblk_zone, M_NOWAIT | (curproc ==
2070                             pageproc ? M_USE_RESERVE : 0));
2071                         if (sb != NULL) {
2072                                 sb->p = rdpi;
2073                                 for (i = 0; i < SWAP_META_PAGES; i++)
2074                                         sb->d[i] = SWAPBLK_NONE;
2075                                 if (atomic_cmpset_int(&swblk_zone_exhausted,
2076                                     1, 0))
2077                                         printf("swblk zone ok\n");
2078                                 break;
2079                         }
2080                         VM_OBJECT_WUNLOCK(object);
2081                         if (uma_zone_exhausted(swblk_zone)) {
2082                                 if (atomic_cmpset_int(&swblk_zone_exhausted,
2083                                     0, 1))
2084                                         printf("swap blk zone exhausted, "
2085                                             "increase kern.maxswzone\n");
2086                                 vm_pageout_oom(VM_OOM_SWAPZ);
2087                                 pause("swzonxb", 10);
2088                         } else
2089                                 uma_zwait(swblk_zone);
2090                         VM_OBJECT_WLOCK(object);
2091                         sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2092                             rdpi);
2093                         if (sb != NULL)
2094                                 /*
2095                                  * Somebody swapped out a nearby page,
2096                                  * allocating swblk at the rdpi index,
2097                                  * while we dropped the object lock.
2098                                  */
2099                                 goto allocated;
2100                 }
2101                 for (;;) {
2102                         error = SWAP_PCTRIE_INSERT(
2103                             &object->un_pager.swp.swp_blks, sb);
2104                         if (error == 0) {
2105                                 if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2106                                     1, 0))
2107                                         printf("swpctrie zone ok\n");
2108                                 break;
2109                         }
2110                         VM_OBJECT_WUNLOCK(object);
2111                         if (uma_zone_exhausted(swpctrie_zone)) {
2112                                 if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2113                                     0, 1))
2114                                         printf("swap pctrie zone exhausted, "
2115                                             "increase kern.maxswzone\n");
2116                                 vm_pageout_oom(VM_OOM_SWAPZ);
2117                                 pause("swzonxp", 10);
2118                         } else
2119                                 uma_zwait(swpctrie_zone);
2120                         VM_OBJECT_WLOCK(object);
2121                         sb1 = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2122                             rdpi);
2123                         if (sb1 != NULL) {
2124                                 uma_zfree(swblk_zone, sb);
2125                                 sb = sb1;
2126                                 goto allocated;
2127                         }
2128                 }
2129         }
2130 allocated:
2131         MPASS(sb->p == rdpi);
2132
2133         modpi = pindex % SWAP_META_PAGES;
2134         /* Return prior contents of metadata. */
2135         prev_swapblk = sb->d[modpi];
2136         /* Enter block into metadata. */
2137         sb->d[modpi] = swapblk;
2138
2139         /*
2140          * Free the swblk if we end up with the empty page run.
2141          */
2142         if (swapblk == SWAPBLK_NONE)
2143                 swp_pager_free_empty_swblk(object, sb);
2144         return (prev_swapblk);
2145 }
2146
2147 /*
2148  * SWP_PAGER_META_TRANSFER() - free a range of blocks in the srcobject's swap
2149  * metadata, or transfer it into dstobject.
2150  *
2151  *      This routine will free swap metadata structures as they are cleaned
2152  *      out.
2153  */
2154 static void
2155 swp_pager_meta_transfer(vm_object_t srcobject, vm_object_t dstobject,
2156     vm_pindex_t pindex, vm_pindex_t count)
2157 {
2158         struct swblk *sb;
2159         daddr_t n_free, s_free;
2160         vm_pindex_t offset, last;
2161         int i, limit, start;
2162
2163         VM_OBJECT_ASSERT_WLOCKED(srcobject);
2164         if ((srcobject->flags & OBJ_SWAP) == 0 || count == 0)
2165                 return;
2166
2167         swp_pager_init_freerange(&s_free, &n_free);
2168         offset = pindex;
2169         last = pindex + count;
2170         for (;;) {
2171                 sb = SWAP_PCTRIE_LOOKUP_GE(&srcobject->un_pager.swp.swp_blks,
2172                     rounddown(pindex, SWAP_META_PAGES));
2173                 if (sb == NULL || sb->p >= last)
2174                         break;
2175                 start = pindex > sb->p ? pindex - sb->p : 0;
2176                 limit = last - sb->p < SWAP_META_PAGES ? last - sb->p :
2177                     SWAP_META_PAGES;
2178                 for (i = start; i < limit; i++) {
2179                         if (sb->d[i] == SWAPBLK_NONE)
2180                                 continue;
2181                         if (dstobject == NULL ||
2182                             !swp_pager_xfer_source(srcobject, dstobject, 
2183                             sb->p + i - offset, sb->d[i])) {
2184                                 swp_pager_update_freerange(&s_free, &n_free,
2185                                     sb->d[i]);
2186                         }
2187                         sb->d[i] = SWAPBLK_NONE;
2188                 }
2189                 pindex = sb->p + SWAP_META_PAGES;
2190                 if (swp_pager_swblk_empty(sb, 0, start) &&
2191                     swp_pager_swblk_empty(sb, limit, SWAP_META_PAGES)) {
2192                         SWAP_PCTRIE_REMOVE(&srcobject->un_pager.swp.swp_blks,
2193                             sb->p);
2194                         uma_zfree(swblk_zone, sb);
2195                 }
2196         }
2197         swp_pager_freeswapspace(s_free, n_free);
2198 }
2199
2200 /*
2201  * SWP_PAGER_META_FREE() - free a range of blocks in the object's swap metadata
2202  *
2203  *      The requested range of blocks is freed, with any associated swap
2204  *      returned to the swap bitmap.
2205  *
2206  *      This routine will free swap metadata structures as they are cleaned
2207  *      out.  This routine does *NOT* operate on swap metadata associated
2208  *      with resident pages.
2209  */
2210 static void
2211 swp_pager_meta_free(vm_object_t object, vm_pindex_t pindex, vm_pindex_t count)
2212 {
2213         swp_pager_meta_transfer(object, NULL, pindex, count);
2214 }
2215
2216 /*
2217  * SWP_PAGER_META_FREE_ALL() - destroy all swap metadata associated with object
2218  *
2219  *      This routine locates and destroys all swap metadata associated with
2220  *      an object.
2221  */
2222 static void
2223 swp_pager_meta_free_all(vm_object_t object)
2224 {
2225         struct swblk *sb;
2226         daddr_t n_free, s_free;
2227         vm_pindex_t pindex;
2228         int i;
2229
2230         VM_OBJECT_ASSERT_WLOCKED(object);
2231         if ((object->flags & OBJ_SWAP) == 0)
2232                 return;
2233
2234         swp_pager_init_freerange(&s_free, &n_free);
2235         for (pindex = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
2236             &object->un_pager.swp.swp_blks, pindex)) != NULL;) {
2237                 pindex = sb->p + SWAP_META_PAGES;
2238                 for (i = 0; i < SWAP_META_PAGES; i++) {
2239                         if (sb->d[i] == SWAPBLK_NONE)
2240                                 continue;
2241                         swp_pager_update_freerange(&s_free, &n_free, sb->d[i]);
2242                 }
2243                 SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
2244                 uma_zfree(swblk_zone, sb);
2245         }
2246         swp_pager_freeswapspace(s_free, n_free);
2247 }
2248
2249 /*
2250  * SWP_PAGER_METACTL() -  misc control of swap meta data.
2251  *
2252  *      This routine is capable of looking up, or removing swapblk
2253  *      assignments in the swap meta data.  It returns the swapblk being
2254  *      looked-up, popped, or SWAPBLK_NONE if the block was invalid.
2255  *
2256  *      When acting on a busy resident page and paging is in progress, we
2257  *      have to wait until paging is complete but otherwise can act on the
2258  *      busy page.
2259  */
2260 static daddr_t
2261 swp_pager_meta_lookup(vm_object_t object, vm_pindex_t pindex)
2262 {
2263         struct swblk *sb;
2264
2265         VM_OBJECT_ASSERT_LOCKED(object);
2266
2267         /*
2268          * The meta data only exists if the object is OBJT_SWAP
2269          * and even then might not be allocated yet.
2270          */
2271         KASSERT((object->flags & OBJ_SWAP) != 0,
2272             ("Lookup object not swappable"));
2273
2274         sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2275             rounddown(pindex, SWAP_META_PAGES));
2276         if (sb == NULL)
2277                 return (SWAPBLK_NONE);
2278         return (sb->d[pindex % SWAP_META_PAGES]);
2279 }
2280
2281 /*
2282  * Returns the least page index which is greater than or equal to the
2283  * parameter pindex and for which there is a swap block allocated.
2284  * Returns object's size if the object's type is not swap or if there
2285  * are no allocated swap blocks for the object after the requested
2286  * pindex.
2287  */
2288 vm_pindex_t
2289 swap_pager_find_least(vm_object_t object, vm_pindex_t pindex)
2290 {
2291         struct swblk *sb;
2292         int i;
2293
2294         VM_OBJECT_ASSERT_LOCKED(object);
2295         if ((object->flags & OBJ_SWAP) == 0)
2296                 return (object->size);
2297
2298         sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2299             rounddown(pindex, SWAP_META_PAGES));
2300         if (sb == NULL)
2301                 return (object->size);
2302         if (sb->p < pindex) {
2303                 for (i = pindex % SWAP_META_PAGES; i < SWAP_META_PAGES; i++) {
2304                         if (sb->d[i] != SWAPBLK_NONE)
2305                                 return (sb->p + i);
2306                 }
2307                 sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2308                     roundup(pindex, SWAP_META_PAGES));
2309                 if (sb == NULL)
2310                         return (object->size);
2311         }
2312         for (i = 0; i < SWAP_META_PAGES; i++) {
2313                 if (sb->d[i] != SWAPBLK_NONE)
2314                         return (sb->p + i);
2315         }
2316
2317         /*
2318          * We get here if a swblk is present in the trie but it
2319          * doesn't map any blocks.
2320          */
2321         MPASS(0);
2322         return (object->size);
2323 }
2324
2325 /*
2326  * System call swapon(name) enables swapping on device name,
2327  * which must be in the swdevsw.  Return EBUSY
2328  * if already swapping on this device.
2329  */
2330 #ifndef _SYS_SYSPROTO_H_
2331 struct swapon_args {
2332         char *name;
2333 };
2334 #endif
2335
2336 /*
2337  * MPSAFE
2338  */
2339 /* ARGSUSED */
2340 int
2341 sys_swapon(struct thread *td, struct swapon_args *uap)
2342 {
2343         struct vattr attr;
2344         struct vnode *vp;
2345         struct nameidata nd;
2346         int error;
2347
2348         error = priv_check(td, PRIV_SWAPON);
2349         if (error)
2350                 return (error);
2351
2352         sx_xlock(&swdev_syscall_lock);
2353
2354         /*
2355          * Swap metadata may not fit in the KVM if we have physical
2356          * memory of >1GB.
2357          */
2358         if (swblk_zone == NULL) {
2359                 error = ENOMEM;
2360                 goto done;
2361         }
2362
2363         NDINIT(&nd, LOOKUP, ISOPEN | FOLLOW | AUDITVNODE1, UIO_USERSPACE,
2364             uap->name, td);
2365         error = namei(&nd);
2366         if (error)
2367                 goto done;
2368
2369         NDFREE(&nd, NDF_ONLY_PNBUF);
2370         vp = nd.ni_vp;
2371
2372         if (vn_isdisk_error(vp, &error)) {
2373                 error = swapongeom(vp);
2374         } else if (vp->v_type == VREG &&
2375             (vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
2376             (error = VOP_GETATTR(vp, &attr, td->td_ucred)) == 0) {
2377                 /*
2378                  * Allow direct swapping to NFS regular files in the same
2379                  * way that nfs_mountroot() sets up diskless swapping.
2380                  */
2381                 error = swaponvp(td, vp, attr.va_size / DEV_BSIZE);
2382         }
2383
2384         if (error)
2385                 vrele(vp);
2386 done:
2387         sx_xunlock(&swdev_syscall_lock);
2388         return (error);
2389 }
2390
2391 /*
2392  * Check that the total amount of swap currently configured does not
2393  * exceed half the theoretical maximum.  If it does, print a warning
2394  * message.
2395  */
2396 static void
2397 swapon_check_swzone(void)
2398 {
2399
2400         /* recommend using no more than half that amount */
2401         if (swap_total > swap_maxpages / 2) {
2402                 printf("warning: total configured swap (%lu pages) "
2403                     "exceeds maximum recommended amount (%lu pages).\n",
2404                     swap_total, swap_maxpages / 2);
2405                 printf("warning: increase kern.maxswzone "
2406                     "or reduce amount of swap.\n");
2407         }
2408 }
2409
2410 static void
2411 swaponsomething(struct vnode *vp, void *id, u_long nblks,
2412     sw_strategy_t *strategy, sw_close_t *close, dev_t dev, int flags)
2413 {
2414         struct swdevt *sp, *tsp;
2415         daddr_t dvbase;
2416
2417         /*
2418          * nblks is in DEV_BSIZE'd chunks, convert to PAGE_SIZE'd chunks.
2419          * First chop nblks off to page-align it, then convert.
2420          *
2421          * sw->sw_nblks is in page-sized chunks now too.
2422          */
2423         nblks &= ~(ctodb(1) - 1);
2424         nblks = dbtoc(nblks);
2425
2426         sp = malloc(sizeof *sp, M_VMPGDATA, M_WAITOK | M_ZERO);
2427         sp->sw_blist = blist_create(nblks, M_WAITOK);
2428         sp->sw_vp = vp;
2429         sp->sw_id = id;
2430         sp->sw_dev = dev;
2431         sp->sw_nblks = nblks;
2432         sp->sw_used = 0;
2433         sp->sw_strategy = strategy;
2434         sp->sw_close = close;
2435         sp->sw_flags = flags;
2436
2437         /*
2438          * Do not free the first blocks in order to avoid overwriting
2439          * any bsd label at the front of the partition
2440          */
2441         blist_free(sp->sw_blist, howmany(BBSIZE, PAGE_SIZE),
2442             nblks - howmany(BBSIZE, PAGE_SIZE));
2443
2444         dvbase = 0;
2445         mtx_lock(&sw_dev_mtx);
2446         TAILQ_FOREACH(tsp, &swtailq, sw_list) {
2447                 if (tsp->sw_end >= dvbase) {
2448                         /*
2449                          * We put one uncovered page between the devices
2450                          * in order to definitively prevent any cross-device
2451                          * I/O requests
2452                          */
2453                         dvbase = tsp->sw_end + 1;
2454                 }
2455         }
2456         sp->sw_first = dvbase;
2457         sp->sw_end = dvbase + nblks;
2458         TAILQ_INSERT_TAIL(&swtailq, sp, sw_list);
2459         nswapdev++;
2460         swap_pager_avail += nblks - howmany(BBSIZE, PAGE_SIZE);
2461         swap_total += nblks;
2462         swapon_check_swzone();
2463         swp_sizecheck();
2464         mtx_unlock(&sw_dev_mtx);
2465         EVENTHANDLER_INVOKE(swapon, sp);
2466 }
2467
2468 /*
2469  * SYSCALL: swapoff(devname)
2470  *
2471  * Disable swapping on the given device.
2472  *
2473  * XXX: Badly designed system call: it should use a device index
2474  * rather than filename as specification.  We keep sw_vp around
2475  * only to make this work.
2476  */
2477 #ifndef _SYS_SYSPROTO_H_
2478 struct swapoff_args {
2479         char *name;
2480 };
2481 #endif
2482
2483 /*
2484  * MPSAFE
2485  */
2486 /* ARGSUSED */
2487 int
2488 sys_swapoff(struct thread *td, struct swapoff_args *uap)
2489 {
2490         struct vnode *vp;
2491         struct nameidata nd;
2492         struct swdevt *sp;
2493         int error;
2494
2495         error = priv_check(td, PRIV_SWAPOFF);
2496         if (error)
2497                 return (error);
2498
2499         sx_xlock(&swdev_syscall_lock);
2500
2501         NDINIT(&nd, LOOKUP, FOLLOW | AUDITVNODE1, UIO_USERSPACE, uap->name,
2502             td);
2503         error = namei(&nd);
2504         if (error)
2505                 goto done;
2506         NDFREE(&nd, NDF_ONLY_PNBUF);
2507         vp = nd.ni_vp;
2508
2509         mtx_lock(&sw_dev_mtx);
2510         TAILQ_FOREACH(sp, &swtailq, sw_list) {
2511                 if (sp->sw_vp == vp)
2512                         break;
2513         }
2514         mtx_unlock(&sw_dev_mtx);
2515         if (sp == NULL) {
2516                 error = EINVAL;
2517                 goto done;
2518         }
2519         error = swapoff_one(sp, td->td_ucred);
2520 done:
2521         sx_xunlock(&swdev_syscall_lock);
2522         return (error);
2523 }
2524
2525 static int
2526 swapoff_one(struct swdevt *sp, struct ucred *cred)
2527 {
2528         u_long nblks;
2529 #ifdef MAC
2530         int error;
2531 #endif
2532
2533         sx_assert(&swdev_syscall_lock, SA_XLOCKED);
2534 #ifdef MAC
2535         (void) vn_lock(sp->sw_vp, LK_EXCLUSIVE | LK_RETRY);
2536         error = mac_system_check_swapoff(cred, sp->sw_vp);
2537         (void) VOP_UNLOCK(sp->sw_vp);
2538         if (error != 0)
2539                 return (error);
2540 #endif
2541         nblks = sp->sw_nblks;
2542
2543         /*
2544          * We can turn off this swap device safely only if the
2545          * available virtual memory in the system will fit the amount
2546          * of data we will have to page back in, plus an epsilon so
2547          * the system doesn't become critically low on swap space.
2548          */
2549         if (vm_free_count() + swap_pager_avail < nblks + nswap_lowat)
2550                 return (ENOMEM);
2551
2552         /*
2553          * Prevent further allocations on this device.
2554          */
2555         mtx_lock(&sw_dev_mtx);
2556         sp->sw_flags |= SW_CLOSING;
2557         swap_pager_avail -= blist_fill(sp->sw_blist, 0, nblks);
2558         swap_total -= nblks;
2559         mtx_unlock(&sw_dev_mtx);
2560
2561         /*
2562          * Page in the contents of the device and close it.
2563          */
2564         swap_pager_swapoff(sp);
2565
2566         sp->sw_close(curthread, sp);
2567         mtx_lock(&sw_dev_mtx);
2568         sp->sw_id = NULL;
2569         TAILQ_REMOVE(&swtailq, sp, sw_list);
2570         nswapdev--;
2571         if (nswapdev == 0) {
2572                 swap_pager_full = 2;
2573                 swap_pager_almost_full = 1;
2574         }
2575         if (swdevhd == sp)
2576                 swdevhd = NULL;
2577         mtx_unlock(&sw_dev_mtx);
2578         blist_destroy(sp->sw_blist);
2579         free(sp, M_VMPGDATA);
2580         return (0);
2581 }
2582
2583 void
2584 swapoff_all(void)
2585 {
2586         struct swdevt *sp, *spt;
2587         const char *devname;
2588         int error;
2589
2590         sx_xlock(&swdev_syscall_lock);
2591
2592         mtx_lock(&sw_dev_mtx);
2593         TAILQ_FOREACH_SAFE(sp, &swtailq, sw_list, spt) {
2594                 mtx_unlock(&sw_dev_mtx);
2595                 if (vn_isdisk(sp->sw_vp))
2596                         devname = devtoname(sp->sw_vp->v_rdev);
2597                 else
2598                         devname = "[file]";
2599                 error = swapoff_one(sp, thread0.td_ucred);
2600                 if (error != 0) {
2601                         printf("Cannot remove swap device %s (error=%d), "
2602                             "skipping.\n", devname, error);
2603                 } else if (bootverbose) {
2604                         printf("Swap device %s removed.\n", devname);
2605                 }
2606                 mtx_lock(&sw_dev_mtx);
2607         }
2608         mtx_unlock(&sw_dev_mtx);
2609
2610         sx_xunlock(&swdev_syscall_lock);
2611 }
2612
2613 void
2614 swap_pager_status(int *total, int *used)
2615 {
2616
2617         *total = swap_total;
2618         *used = swap_total - swap_pager_avail -
2619             nswapdev * howmany(BBSIZE, PAGE_SIZE);
2620 }
2621
2622 int
2623 swap_dev_info(int name, struct xswdev *xs, char *devname, size_t len)
2624 {
2625         struct swdevt *sp;
2626         const char *tmp_devname;
2627         int error, n;
2628
2629         n = 0;
2630         error = ENOENT;
2631         mtx_lock(&sw_dev_mtx);
2632         TAILQ_FOREACH(sp, &swtailq, sw_list) {
2633                 if (n != name) {
2634                         n++;
2635                         continue;
2636                 }
2637                 xs->xsw_version = XSWDEV_VERSION;
2638                 xs->xsw_dev = sp->sw_dev;
2639                 xs->xsw_flags = sp->sw_flags;
2640                 xs->xsw_nblks = sp->sw_nblks;
2641                 xs->xsw_used = sp->sw_used;
2642                 if (devname != NULL) {
2643                         if (vn_isdisk(sp->sw_vp))
2644                                 tmp_devname = devtoname(sp->sw_vp->v_rdev);
2645                         else
2646                                 tmp_devname = "[file]";
2647                         strncpy(devname, tmp_devname, len);
2648                 }
2649                 error = 0;
2650                 break;
2651         }
2652         mtx_unlock(&sw_dev_mtx);
2653         return (error);
2654 }
2655
2656 #if defined(COMPAT_FREEBSD11)
2657 #define XSWDEV_VERSION_11       1
2658 struct xswdev11 {
2659         u_int   xsw_version;
2660         uint32_t xsw_dev;
2661         int     xsw_flags;
2662         int     xsw_nblks;
2663         int     xsw_used;
2664 };
2665 #endif
2666
2667 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2668 struct xswdev32 {
2669         u_int   xsw_version;
2670         u_int   xsw_dev1, xsw_dev2;
2671         int     xsw_flags;
2672         int     xsw_nblks;
2673         int     xsw_used;
2674 };
2675 #endif
2676
2677 static int
2678 sysctl_vm_swap_info(SYSCTL_HANDLER_ARGS)
2679 {
2680         struct xswdev xs;
2681 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2682         struct xswdev32 xs32;
2683 #endif
2684 #if defined(COMPAT_FREEBSD11)
2685         struct xswdev11 xs11;
2686 #endif
2687         int error;
2688
2689         if (arg2 != 1)                  /* name length */
2690                 return (EINVAL);
2691
2692         memset(&xs, 0, sizeof(xs));
2693         error = swap_dev_info(*(int *)arg1, &xs, NULL, 0);
2694         if (error != 0)
2695                 return (error);
2696 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2697         if (req->oldlen == sizeof(xs32)) {
2698                 memset(&xs32, 0, sizeof(xs32));
2699                 xs32.xsw_version = XSWDEV_VERSION;
2700                 xs32.xsw_dev1 = xs.xsw_dev;
2701                 xs32.xsw_dev2 = xs.xsw_dev >> 32;
2702                 xs32.xsw_flags = xs.xsw_flags;
2703                 xs32.xsw_nblks = xs.xsw_nblks;
2704                 xs32.xsw_used = xs.xsw_used;
2705                 error = SYSCTL_OUT(req, &xs32, sizeof(xs32));
2706                 return (error);
2707         }
2708 #endif
2709 #if defined(COMPAT_FREEBSD11)
2710         if (req->oldlen == sizeof(xs11)) {
2711                 memset(&xs11, 0, sizeof(xs11));
2712                 xs11.xsw_version = XSWDEV_VERSION_11;
2713                 xs11.xsw_dev = xs.xsw_dev; /* truncation */
2714                 xs11.xsw_flags = xs.xsw_flags;
2715                 xs11.xsw_nblks = xs.xsw_nblks;
2716                 xs11.xsw_used = xs.xsw_used;
2717                 error = SYSCTL_OUT(req, &xs11, sizeof(xs11));
2718                 return (error);
2719         }
2720 #endif
2721         error = SYSCTL_OUT(req, &xs, sizeof(xs));
2722         return (error);
2723 }
2724
2725 SYSCTL_INT(_vm, OID_AUTO, nswapdev, CTLFLAG_RD, &nswapdev, 0,
2726     "Number of swap devices");
2727 SYSCTL_NODE(_vm, OID_AUTO, swap_info, CTLFLAG_RD | CTLFLAG_MPSAFE,
2728     sysctl_vm_swap_info,
2729     "Swap statistics by device");
2730
2731 /*
2732  * Count the approximate swap usage in pages for a vmspace.  The
2733  * shadowed or not yet copied on write swap blocks are not accounted.
2734  * The map must be locked.
2735  */
2736 long
2737 vmspace_swap_count(struct vmspace *vmspace)
2738 {
2739         vm_map_t map;
2740         vm_map_entry_t cur;
2741         vm_object_t object;
2742         struct swblk *sb;
2743         vm_pindex_t e, pi;
2744         long count;
2745         int i;
2746
2747         map = &vmspace->vm_map;
2748         count = 0;
2749
2750         VM_MAP_ENTRY_FOREACH(cur, map) {
2751                 if ((cur->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
2752                         continue;
2753                 object = cur->object.vm_object;
2754                 if (object == NULL || (object->flags & OBJ_SWAP) == 0)
2755                         continue;
2756                 VM_OBJECT_RLOCK(object);
2757                 if ((object->flags & OBJ_SWAP) == 0)
2758                         goto unlock;
2759                 pi = OFF_TO_IDX(cur->offset);
2760                 e = pi + OFF_TO_IDX(cur->end - cur->start);
2761                 for (;; pi = sb->p + SWAP_META_PAGES) {
2762                         sb = SWAP_PCTRIE_LOOKUP_GE(
2763                             &object->un_pager.swp.swp_blks, pi);
2764                         if (sb == NULL || sb->p >= e)
2765                                 break;
2766                         for (i = 0; i < SWAP_META_PAGES; i++) {
2767                                 if (sb->p + i < e &&
2768                                     sb->d[i] != SWAPBLK_NONE)
2769                                         count++;
2770                         }
2771                 }
2772 unlock:
2773                 VM_OBJECT_RUNLOCK(object);
2774         }
2775         return (count);
2776 }
2777
2778 /*
2779  * GEOM backend
2780  *
2781  * Swapping onto disk devices.
2782  *
2783  */
2784
2785 static g_orphan_t swapgeom_orphan;
2786
2787 static struct g_class g_swap_class = {
2788         .name = "SWAP",
2789         .version = G_VERSION,
2790         .orphan = swapgeom_orphan,
2791 };
2792
2793 DECLARE_GEOM_CLASS(g_swap_class, g_class);
2794
2795 static void
2796 swapgeom_close_ev(void *arg, int flags)
2797 {
2798         struct g_consumer *cp;
2799
2800         cp = arg;
2801         g_access(cp, -1, -1, 0);
2802         g_detach(cp);
2803         g_destroy_consumer(cp);
2804 }
2805
2806 /*
2807  * Add a reference to the g_consumer for an inflight transaction.
2808  */
2809 static void
2810 swapgeom_acquire(struct g_consumer *cp)
2811 {
2812
2813         mtx_assert(&sw_dev_mtx, MA_OWNED);
2814         cp->index++;
2815 }
2816
2817 /*
2818  * Remove a reference from the g_consumer.  Post a close event if all
2819  * references go away, since the function might be called from the
2820  * biodone context.
2821  */
2822 static void
2823 swapgeom_release(struct g_consumer *cp, struct swdevt *sp)
2824 {
2825
2826         mtx_assert(&sw_dev_mtx, MA_OWNED);
2827         cp->index--;
2828         if (cp->index == 0) {
2829                 if (g_post_event(swapgeom_close_ev, cp, M_NOWAIT, NULL) == 0)
2830                         sp->sw_id = NULL;
2831         }
2832 }
2833
2834 static void
2835 swapgeom_done(struct bio *bp2)
2836 {
2837         struct swdevt *sp;
2838         struct buf *bp;
2839         struct g_consumer *cp;
2840
2841         bp = bp2->bio_caller2;
2842         cp = bp2->bio_from;
2843         bp->b_ioflags = bp2->bio_flags;
2844         if (bp2->bio_error)
2845                 bp->b_ioflags |= BIO_ERROR;
2846         bp->b_resid = bp->b_bcount - bp2->bio_completed;
2847         bp->b_error = bp2->bio_error;
2848         bp->b_caller1 = NULL;
2849         bufdone(bp);
2850         sp = bp2->bio_caller1;
2851         mtx_lock(&sw_dev_mtx);
2852         swapgeom_release(cp, sp);
2853         mtx_unlock(&sw_dev_mtx);
2854         g_destroy_bio(bp2);
2855 }
2856
2857 static void
2858 swapgeom_strategy(struct buf *bp, struct swdevt *sp)
2859 {
2860         struct bio *bio;
2861         struct g_consumer *cp;
2862
2863         mtx_lock(&sw_dev_mtx);
2864         cp = sp->sw_id;
2865         if (cp == NULL) {
2866                 mtx_unlock(&sw_dev_mtx);
2867                 bp->b_error = ENXIO;
2868                 bp->b_ioflags |= BIO_ERROR;
2869                 bufdone(bp);
2870                 return;
2871         }
2872         swapgeom_acquire(cp);
2873         mtx_unlock(&sw_dev_mtx);
2874         if (bp->b_iocmd == BIO_WRITE)
2875                 bio = g_new_bio();
2876         else
2877                 bio = g_alloc_bio();
2878         if (bio == NULL) {
2879                 mtx_lock(&sw_dev_mtx);
2880                 swapgeom_release(cp, sp);
2881                 mtx_unlock(&sw_dev_mtx);
2882                 bp->b_error = ENOMEM;
2883                 bp->b_ioflags |= BIO_ERROR;
2884                 printf("swap_pager: cannot allocate bio\n");
2885                 bufdone(bp);
2886                 return;
2887         }
2888
2889         bp->b_caller1 = bio;
2890         bio->bio_caller1 = sp;
2891         bio->bio_caller2 = bp;
2892         bio->bio_cmd = bp->b_iocmd;
2893         bio->bio_offset = (bp->b_blkno - sp->sw_first) * PAGE_SIZE;
2894         bio->bio_length = bp->b_bcount;
2895         bio->bio_done = swapgeom_done;
2896         if (!buf_mapped(bp)) {
2897                 bio->bio_ma = bp->b_pages;
2898                 bio->bio_data = unmapped_buf;
2899                 bio->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
2900                 bio->bio_ma_n = bp->b_npages;
2901                 bio->bio_flags |= BIO_UNMAPPED;
2902         } else {
2903                 bio->bio_data = bp->b_data;
2904                 bio->bio_ma = NULL;
2905         }
2906         g_io_request(bio, cp);
2907         return;
2908 }
2909
2910 static void
2911 swapgeom_orphan(struct g_consumer *cp)
2912 {
2913         struct swdevt *sp;
2914         int destroy;
2915
2916         mtx_lock(&sw_dev_mtx);
2917         TAILQ_FOREACH(sp, &swtailq, sw_list) {
2918                 if (sp->sw_id == cp) {
2919                         sp->sw_flags |= SW_CLOSING;
2920                         break;
2921                 }
2922         }
2923         /*
2924          * Drop reference we were created with. Do directly since we're in a
2925          * special context where we don't have to queue the call to
2926          * swapgeom_close_ev().
2927          */
2928         cp->index--;
2929         destroy = ((sp != NULL) && (cp->index == 0));
2930         if (destroy)
2931                 sp->sw_id = NULL;
2932         mtx_unlock(&sw_dev_mtx);
2933         if (destroy)
2934                 swapgeom_close_ev(cp, 0);
2935 }
2936
2937 static void
2938 swapgeom_close(struct thread *td, struct swdevt *sw)
2939 {
2940         struct g_consumer *cp;
2941
2942         mtx_lock(&sw_dev_mtx);
2943         cp = sw->sw_id;
2944         sw->sw_id = NULL;
2945         mtx_unlock(&sw_dev_mtx);
2946
2947         /*
2948          * swapgeom_close() may be called from the biodone context,
2949          * where we cannot perform topology changes.  Delegate the
2950          * work to the events thread.
2951          */
2952         if (cp != NULL)
2953                 g_waitfor_event(swapgeom_close_ev, cp, M_WAITOK, NULL);
2954 }
2955
2956 static int
2957 swapongeom_locked(struct cdev *dev, struct vnode *vp)
2958 {
2959         struct g_provider *pp;
2960         struct g_consumer *cp;
2961         static struct g_geom *gp;
2962         struct swdevt *sp;
2963         u_long nblks;
2964         int error;
2965
2966         pp = g_dev_getprovider(dev);
2967         if (pp == NULL)
2968                 return (ENODEV);
2969         mtx_lock(&sw_dev_mtx);
2970         TAILQ_FOREACH(sp, &swtailq, sw_list) {
2971                 cp = sp->sw_id;
2972                 if (cp != NULL && cp->provider == pp) {
2973                         mtx_unlock(&sw_dev_mtx);
2974                         return (EBUSY);
2975                 }
2976         }
2977         mtx_unlock(&sw_dev_mtx);
2978         if (gp == NULL)
2979                 gp = g_new_geomf(&g_swap_class, "swap");
2980         cp = g_new_consumer(gp);
2981         cp->index = 1;  /* Number of active I/Os, plus one for being active. */
2982         cp->flags |=  G_CF_DIRECT_SEND | G_CF_DIRECT_RECEIVE;
2983         g_attach(cp, pp);
2984         /*
2985          * XXX: Every time you think you can improve the margin for
2986          * footshooting, somebody depends on the ability to do so:
2987          * savecore(8) wants to write to our swapdev so we cannot
2988          * set an exclusive count :-(
2989          */
2990         error = g_access(cp, 1, 1, 0);
2991         if (error != 0) {
2992                 g_detach(cp);
2993                 g_destroy_consumer(cp);
2994                 return (error);
2995         }
2996         nblks = pp->mediasize / DEV_BSIZE;
2997         swaponsomething(vp, cp, nblks, swapgeom_strategy,
2998             swapgeom_close, dev2udev(dev),
2999             (pp->flags & G_PF_ACCEPT_UNMAPPED) != 0 ? SW_UNMAPPED : 0);
3000         return (0);
3001 }
3002
3003 static int
3004 swapongeom(struct vnode *vp)
3005 {
3006         int error;
3007
3008         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3009         if (vp->v_type != VCHR || VN_IS_DOOMED(vp)) {
3010                 error = ENOENT;
3011         } else {
3012                 g_topology_lock();
3013                 error = swapongeom_locked(vp->v_rdev, vp);
3014                 g_topology_unlock();
3015         }
3016         VOP_UNLOCK(vp);
3017         return (error);
3018 }
3019
3020 /*
3021  * VNODE backend
3022  *
3023  * This is used mainly for network filesystem (read: probably only tested
3024  * with NFS) swapfiles.
3025  *
3026  */
3027
3028 static void
3029 swapdev_strategy(struct buf *bp, struct swdevt *sp)
3030 {
3031         struct vnode *vp2;
3032
3033         bp->b_blkno = ctodb(bp->b_blkno - sp->sw_first);
3034
3035         vp2 = sp->sw_id;
3036         vhold(vp2);
3037         if (bp->b_iocmd == BIO_WRITE) {
3038                 if (bp->b_bufobj)
3039                         bufobj_wdrop(bp->b_bufobj);
3040                 bufobj_wref(&vp2->v_bufobj);
3041         }
3042         if (bp->b_bufobj != &vp2->v_bufobj)
3043                 bp->b_bufobj = &vp2->v_bufobj;
3044         bp->b_vp = vp2;
3045         bp->b_iooffset = dbtob(bp->b_blkno);
3046         bstrategy(bp);
3047         return;
3048 }
3049
3050 static void
3051 swapdev_close(struct thread *td, struct swdevt *sp)
3052 {
3053         struct vnode *vp;
3054
3055         vp = sp->sw_vp;
3056         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3057         VOP_CLOSE(vp, FREAD | FWRITE, td->td_ucred, td);
3058         vput(vp);
3059 }
3060
3061 static int
3062 swaponvp(struct thread *td, struct vnode *vp, u_long nblks)
3063 {
3064         struct swdevt *sp;
3065         int error;
3066
3067         if (nblks == 0)
3068                 return (ENXIO);
3069         mtx_lock(&sw_dev_mtx);
3070         TAILQ_FOREACH(sp, &swtailq, sw_list) {
3071                 if (sp->sw_id == vp) {
3072                         mtx_unlock(&sw_dev_mtx);
3073                         return (EBUSY);
3074                 }
3075         }
3076         mtx_unlock(&sw_dev_mtx);
3077
3078         (void) vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3079 #ifdef MAC
3080         error = mac_system_check_swapon(td->td_ucred, vp);
3081         if (error == 0)
3082 #endif
3083                 error = VOP_OPEN(vp, FREAD | FWRITE, td->td_ucred, td, NULL);
3084         (void) VOP_UNLOCK(vp);
3085         if (error)
3086                 return (error);
3087
3088         swaponsomething(vp, vp, nblks, swapdev_strategy, swapdev_close,
3089             NODEV, 0);
3090         return (0);
3091 }
3092
3093 static int
3094 sysctl_swap_async_max(SYSCTL_HANDLER_ARGS)
3095 {
3096         int error, new, n;
3097
3098         new = nsw_wcount_async_max;
3099         error = sysctl_handle_int(oidp, &new, 0, req);
3100         if (error != 0 || req->newptr == NULL)
3101                 return (error);
3102
3103         if (new > nswbuf / 2 || new < 1)
3104                 return (EINVAL);
3105
3106         mtx_lock(&swbuf_mtx);
3107         while (nsw_wcount_async_max != new) {
3108                 /*
3109                  * Adjust difference.  If the current async count is too low,
3110                  * we will need to sqeeze our update slowly in.  Sleep with a
3111                  * higher priority than getpbuf() to finish faster.
3112                  */
3113                 n = new - nsw_wcount_async_max;
3114                 if (nsw_wcount_async + n >= 0) {
3115                         nsw_wcount_async += n;
3116                         nsw_wcount_async_max += n;
3117                         wakeup(&nsw_wcount_async);
3118                 } else {
3119                         nsw_wcount_async_max -= nsw_wcount_async;
3120                         nsw_wcount_async = 0;
3121                         msleep(&nsw_wcount_async, &swbuf_mtx, PSWP,
3122                             "swpsysctl", 0);
3123                 }
3124         }
3125         mtx_unlock(&swbuf_mtx);
3126
3127         return (0);
3128 }
3129
3130 static void
3131 swap_pager_update_writecount(vm_object_t object, vm_offset_t start,
3132     vm_offset_t end)
3133 {
3134
3135         VM_OBJECT_WLOCK(object);
3136         KASSERT((object->flags & OBJ_ANON) == 0,
3137             ("Splittable object with writecount"));
3138         object->un_pager.swp.writemappings += (vm_ooffset_t)end - start;
3139         VM_OBJECT_WUNLOCK(object);
3140 }
3141
3142 static void
3143 swap_pager_release_writecount(vm_object_t object, vm_offset_t start,
3144     vm_offset_t end)
3145 {
3146
3147         VM_OBJECT_WLOCK(object);
3148         KASSERT((object->flags & OBJ_ANON) == 0,
3149             ("Splittable object with writecount"));
3150         object->un_pager.swp.writemappings -= (vm_ooffset_t)end - start;
3151         VM_OBJECT_WUNLOCK(object);
3152 }