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