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