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