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