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