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