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