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