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