The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/vm/swap_pager.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

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

Cache object: 92c7059705f1e4b32fdb2b045ba00e56


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.