xref: /freebsd/sys/vm/vm_pageout.c (revision b077aed33b7b6aefca7b17ddb250cf521f938613)
1 /*-
2  * SPDX-License-Identifier: (BSD-4-Clause AND MIT-CMU)
3  *
4  * Copyright (c) 1991 Regents of the University of California.
5  * All rights reserved.
6  * Copyright (c) 1994 John S. Dyson
7  * All rights reserved.
8  * Copyright (c) 1994 David Greenman
9  * All rights reserved.
10  * Copyright (c) 2005 Yahoo! Technologies Norway AS
11  * All rights reserved.
12  *
13  * This code is derived from software contributed to Berkeley by
14  * The Mach Operating System project at Carnegie-Mellon University.
15  *
16  * Redistribution and use in source and binary forms, with or without
17  * modification, are permitted provided that the following conditions
18  * are met:
19  * 1. Redistributions of source code must retain the above copyright
20  *    notice, this list of conditions and the following disclaimer.
21  * 2. Redistributions in binary form must reproduce the above copyright
22  *    notice, this list of conditions and the following disclaimer in the
23  *    documentation and/or other materials provided with the distribution.
24  * 3. All advertising materials mentioning features or use of this software
25  *    must display the following acknowledgement:
26  *	This product includes software developed by the University of
27  *	California, Berkeley and its contributors.
28  * 4. Neither the name of the University nor the names of its contributors
29  *    may be used to endorse or promote products derived from this software
30  *    without specific prior written permission.
31  *
32  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
33  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
34  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
35  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
36  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
37  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
38  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
39  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
40  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
41  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
42  * SUCH DAMAGE.
43  *
44  *	from: @(#)vm_pageout.c	7.4 (Berkeley) 5/7/91
45  *
46  *
47  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
48  * All rights reserved.
49  *
50  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
51  *
52  * Permission to use, copy, modify and distribute this software and
53  * its documentation is hereby granted, provided that both the copyright
54  * notice and this permission notice appear in all copies of the
55  * software, derivative works or modified versions, and any portions
56  * thereof, and that both notices appear in supporting documentation.
57  *
58  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
59  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
60  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
61  *
62  * Carnegie Mellon requests users of this software to return to
63  *
64  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
65  *  School of Computer Science
66  *  Carnegie Mellon University
67  *  Pittsburgh PA 15213-3890
68  *
69  * any improvements or extensions that they make and grant Carnegie the
70  * rights to redistribute these changes.
71  */
72 
73 /*
74  *	The proverbial page-out daemon.
75  */
76 
77 #include <sys/cdefs.h>
78 __FBSDID("$FreeBSD$");
79 
80 #include "opt_vm.h"
81 
82 #include <sys/param.h>
83 #include <sys/systm.h>
84 #include <sys/kernel.h>
85 #include <sys/blockcount.h>
86 #include <sys/eventhandler.h>
87 #include <sys/lock.h>
88 #include <sys/mutex.h>
89 #include <sys/proc.h>
90 #include <sys/kthread.h>
91 #include <sys/ktr.h>
92 #include <sys/mount.h>
93 #include <sys/racct.h>
94 #include <sys/resourcevar.h>
95 #include <sys/sched.h>
96 #include <sys/sdt.h>
97 #include <sys/signalvar.h>
98 #include <sys/smp.h>
99 #include <sys/time.h>
100 #include <sys/vnode.h>
101 #include <sys/vmmeter.h>
102 #include <sys/rwlock.h>
103 #include <sys/sx.h>
104 #include <sys/sysctl.h>
105 
106 #include <vm/vm.h>
107 #include <vm/vm_param.h>
108 #include <vm/vm_object.h>
109 #include <vm/vm_page.h>
110 #include <vm/vm_map.h>
111 #include <vm/vm_pageout.h>
112 #include <vm/vm_pager.h>
113 #include <vm/vm_phys.h>
114 #include <vm/vm_pagequeue.h>
115 #include <vm/swap_pager.h>
116 #include <vm/vm_extern.h>
117 #include <vm/uma.h>
118 
119 /*
120  * System initialization
121  */
122 
123 /* the kernel process "vm_pageout"*/
124 static void vm_pageout(void);
125 static void vm_pageout_init(void);
126 static int vm_pageout_clean(vm_page_t m, int *numpagedout);
127 static int vm_pageout_cluster(vm_page_t m);
128 static void vm_pageout_mightbe_oom(struct vm_domain *vmd, int page_shortage,
129     int starting_page_shortage);
130 
131 SYSINIT(pagedaemon_init, SI_SUB_KTHREAD_PAGE, SI_ORDER_FIRST, vm_pageout_init,
132     NULL);
133 
134 struct proc *pageproc;
135 
136 static struct kproc_desc page_kp = {
137 	"pagedaemon",
138 	vm_pageout,
139 	&pageproc
140 };
141 SYSINIT(pagedaemon, SI_SUB_KTHREAD_PAGE, SI_ORDER_SECOND, kproc_start,
142     &page_kp);
143 
144 SDT_PROVIDER_DEFINE(vm);
145 SDT_PROBE_DEFINE(vm, , , vm__lowmem_scan);
146 
147 /* Pagedaemon activity rates, in subdivisions of one second. */
148 #define	VM_LAUNDER_RATE		10
149 #define	VM_INACT_SCAN_RATE	10
150 
151 static int swapdev_enabled;
152 int vm_pageout_page_count = 32;
153 
154 static int vm_panic_on_oom = 0;
155 SYSCTL_INT(_vm, OID_AUTO, panic_on_oom,
156     CTLFLAG_RWTUN, &vm_panic_on_oom, 0,
157     "Panic on the given number of out-of-memory errors instead of "
158     "killing the largest process");
159 
160 static int vm_pageout_update_period;
161 SYSCTL_INT(_vm, OID_AUTO, pageout_update_period,
162     CTLFLAG_RWTUN, &vm_pageout_update_period, 0,
163     "Maximum active LRU update period");
164 
165 static int pageout_cpus_per_thread = 16;
166 SYSCTL_INT(_vm, OID_AUTO, pageout_cpus_per_thread, CTLFLAG_RDTUN,
167     &pageout_cpus_per_thread, 0,
168     "Number of CPUs per pagedaemon worker thread");
169 
170 static int lowmem_period = 10;
171 SYSCTL_INT(_vm, OID_AUTO, lowmem_period, CTLFLAG_RWTUN, &lowmem_period, 0,
172     "Low memory callback period");
173 
174 static int disable_swap_pageouts;
175 SYSCTL_INT(_vm, OID_AUTO, disable_swapspace_pageouts,
176     CTLFLAG_RWTUN, &disable_swap_pageouts, 0,
177     "Disallow swapout of dirty pages");
178 
179 static int pageout_lock_miss;
180 SYSCTL_INT(_vm, OID_AUTO, pageout_lock_miss,
181     CTLFLAG_RD, &pageout_lock_miss, 0,
182     "vget() lock misses during pageout");
183 
184 static int vm_pageout_oom_seq = 12;
185 SYSCTL_INT(_vm, OID_AUTO, pageout_oom_seq,
186     CTLFLAG_RWTUN, &vm_pageout_oom_seq, 0,
187     "back-to-back calls to oom detector to start OOM");
188 
189 static int act_scan_laundry_weight = 3;
190 SYSCTL_INT(_vm, OID_AUTO, act_scan_laundry_weight, CTLFLAG_RWTUN,
191     &act_scan_laundry_weight, 0,
192     "weight given to clean vs. dirty pages in active queue scans");
193 
194 static u_int vm_background_launder_rate = 4096;
195 SYSCTL_UINT(_vm, OID_AUTO, background_launder_rate, CTLFLAG_RWTUN,
196     &vm_background_launder_rate, 0,
197     "background laundering rate, in kilobytes per second");
198 
199 static u_int vm_background_launder_max = 20 * 1024;
200 SYSCTL_UINT(_vm, OID_AUTO, background_launder_max, CTLFLAG_RWTUN,
201     &vm_background_launder_max, 0,
202     "background laundering cap, in kilobytes");
203 
204 u_long vm_page_max_user_wired;
205 SYSCTL_ULONG(_vm, OID_AUTO, max_user_wired, CTLFLAG_RW,
206     &vm_page_max_user_wired, 0,
207     "system-wide limit to user-wired page count");
208 
209 static u_int isqrt(u_int num);
210 static int vm_pageout_launder(struct vm_domain *vmd, int launder,
211     bool in_shortfall);
212 static void vm_pageout_laundry_worker(void *arg);
213 
214 struct scan_state {
215 	struct vm_batchqueue bq;
216 	struct vm_pagequeue *pq;
217 	vm_page_t	marker;
218 	int		maxscan;
219 	int		scanned;
220 };
221 
222 static void
223 vm_pageout_init_scan(struct scan_state *ss, struct vm_pagequeue *pq,
224     vm_page_t marker, vm_page_t after, int maxscan)
225 {
226 
227 	vm_pagequeue_assert_locked(pq);
228 	KASSERT((marker->a.flags & PGA_ENQUEUED) == 0,
229 	    ("marker %p already enqueued", marker));
230 
231 	if (after == NULL)
232 		TAILQ_INSERT_HEAD(&pq->pq_pl, marker, plinks.q);
233 	else
234 		TAILQ_INSERT_AFTER(&pq->pq_pl, after, marker, plinks.q);
235 	vm_page_aflag_set(marker, PGA_ENQUEUED);
236 
237 	vm_batchqueue_init(&ss->bq);
238 	ss->pq = pq;
239 	ss->marker = marker;
240 	ss->maxscan = maxscan;
241 	ss->scanned = 0;
242 	vm_pagequeue_unlock(pq);
243 }
244 
245 static void
246 vm_pageout_end_scan(struct scan_state *ss)
247 {
248 	struct vm_pagequeue *pq;
249 
250 	pq = ss->pq;
251 	vm_pagequeue_assert_locked(pq);
252 	KASSERT((ss->marker->a.flags & PGA_ENQUEUED) != 0,
253 	    ("marker %p not enqueued", ss->marker));
254 
255 	TAILQ_REMOVE(&pq->pq_pl, ss->marker, plinks.q);
256 	vm_page_aflag_clear(ss->marker, PGA_ENQUEUED);
257 	pq->pq_pdpages += ss->scanned;
258 }
259 
260 /*
261  * Add a small number of queued pages to a batch queue for later processing
262  * without the corresponding queue lock held.  The caller must have enqueued a
263  * marker page at the desired start point for the scan.  Pages will be
264  * physically dequeued if the caller so requests.  Otherwise, the returned
265  * batch may contain marker pages, and it is up to the caller to handle them.
266  *
267  * When processing the batch queue, vm_pageout_defer() must be used to
268  * determine whether the page has been logically dequeued since the batch was
269  * collected.
270  */
271 static __always_inline void
272 vm_pageout_collect_batch(struct scan_state *ss, const bool dequeue)
273 {
274 	struct vm_pagequeue *pq;
275 	vm_page_t m, marker, n;
276 
277 	marker = ss->marker;
278 	pq = ss->pq;
279 
280 	KASSERT((marker->a.flags & PGA_ENQUEUED) != 0,
281 	    ("marker %p not enqueued", ss->marker));
282 
283 	vm_pagequeue_lock(pq);
284 	for (m = TAILQ_NEXT(marker, plinks.q); m != NULL &&
285 	    ss->scanned < ss->maxscan && ss->bq.bq_cnt < VM_BATCHQUEUE_SIZE;
286 	    m = n, ss->scanned++) {
287 		n = TAILQ_NEXT(m, plinks.q);
288 		if ((m->flags & PG_MARKER) == 0) {
289 			KASSERT((m->a.flags & PGA_ENQUEUED) != 0,
290 			    ("page %p not enqueued", m));
291 			KASSERT((m->flags & PG_FICTITIOUS) == 0,
292 			    ("Fictitious page %p cannot be in page queue", m));
293 			KASSERT((m->oflags & VPO_UNMANAGED) == 0,
294 			    ("Unmanaged page %p cannot be in page queue", m));
295 		} else if (dequeue)
296 			continue;
297 
298 		(void)vm_batchqueue_insert(&ss->bq, m);
299 		if (dequeue) {
300 			TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
301 			vm_page_aflag_clear(m, PGA_ENQUEUED);
302 		}
303 	}
304 	TAILQ_REMOVE(&pq->pq_pl, marker, plinks.q);
305 	if (__predict_true(m != NULL))
306 		TAILQ_INSERT_BEFORE(m, marker, plinks.q);
307 	else
308 		TAILQ_INSERT_TAIL(&pq->pq_pl, marker, plinks.q);
309 	if (dequeue)
310 		vm_pagequeue_cnt_add(pq, -ss->bq.bq_cnt);
311 	vm_pagequeue_unlock(pq);
312 }
313 
314 /*
315  * Return the next page to be scanned, or NULL if the scan is complete.
316  */
317 static __always_inline vm_page_t
318 vm_pageout_next(struct scan_state *ss, const bool dequeue)
319 {
320 
321 	if (ss->bq.bq_cnt == 0)
322 		vm_pageout_collect_batch(ss, dequeue);
323 	return (vm_batchqueue_pop(&ss->bq));
324 }
325 
326 /*
327  * Determine whether processing of a page should be deferred and ensure that any
328  * outstanding queue operations are processed.
329  */
330 static __always_inline bool
331 vm_pageout_defer(vm_page_t m, const uint8_t queue, const bool enqueued)
332 {
333 	vm_page_astate_t as;
334 
335 	as = vm_page_astate_load(m);
336 	if (__predict_false(as.queue != queue ||
337 	    ((as.flags & PGA_ENQUEUED) != 0) != enqueued))
338 		return (true);
339 	if ((as.flags & PGA_QUEUE_OP_MASK) != 0) {
340 		vm_page_pqbatch_submit(m, queue);
341 		return (true);
342 	}
343 	return (false);
344 }
345 
346 /*
347  * Scan for pages at adjacent offsets within the given page's object that are
348  * eligible for laundering, form a cluster of these pages and the given page,
349  * and launder that cluster.
350  */
351 static int
352 vm_pageout_cluster(vm_page_t m)
353 {
354 	vm_object_t object;
355 	vm_page_t mc[2 * vm_pageout_page_count], p, pb, ps;
356 	vm_pindex_t pindex;
357 	int ib, is, page_base, pageout_count;
358 
359 	object = m->object;
360 	VM_OBJECT_ASSERT_WLOCKED(object);
361 	pindex = m->pindex;
362 
363 	vm_page_assert_xbusied(m);
364 
365 	mc[vm_pageout_page_count] = pb = ps = m;
366 	pageout_count = 1;
367 	page_base = vm_pageout_page_count;
368 	ib = 1;
369 	is = 1;
370 
371 	/*
372 	 * We can cluster only if the page is not clean, busy, or held, and
373 	 * the page is in the laundry queue.
374 	 *
375 	 * During heavy mmap/modification loads the pageout
376 	 * daemon can really fragment the underlying file
377 	 * due to flushing pages out of order and not trying to
378 	 * align the clusters (which leaves sporadic out-of-order
379 	 * holes).  To solve this problem we do the reverse scan
380 	 * first and attempt to align our cluster, then do a
381 	 * forward scan if room remains.
382 	 */
383 more:
384 	while (ib != 0 && pageout_count < vm_pageout_page_count) {
385 		if (ib > pindex) {
386 			ib = 0;
387 			break;
388 		}
389 		if ((p = vm_page_prev(pb)) == NULL ||
390 		    vm_page_tryxbusy(p) == 0) {
391 			ib = 0;
392 			break;
393 		}
394 		if (vm_page_wired(p)) {
395 			ib = 0;
396 			vm_page_xunbusy(p);
397 			break;
398 		}
399 		vm_page_test_dirty(p);
400 		if (p->dirty == 0) {
401 			ib = 0;
402 			vm_page_xunbusy(p);
403 			break;
404 		}
405 		if (!vm_page_in_laundry(p) || !vm_page_try_remove_write(p)) {
406 			vm_page_xunbusy(p);
407 			ib = 0;
408 			break;
409 		}
410 		mc[--page_base] = pb = p;
411 		++pageout_count;
412 		++ib;
413 
414 		/*
415 		 * We are at an alignment boundary.  Stop here, and switch
416 		 * directions.  Do not clear ib.
417 		 */
418 		if ((pindex - (ib - 1)) % vm_pageout_page_count == 0)
419 			break;
420 	}
421 	while (pageout_count < vm_pageout_page_count &&
422 	    pindex + is < object->size) {
423 		if ((p = vm_page_next(ps)) == NULL ||
424 		    vm_page_tryxbusy(p) == 0)
425 			break;
426 		if (vm_page_wired(p)) {
427 			vm_page_xunbusy(p);
428 			break;
429 		}
430 		vm_page_test_dirty(p);
431 		if (p->dirty == 0) {
432 			vm_page_xunbusy(p);
433 			break;
434 		}
435 		if (!vm_page_in_laundry(p) || !vm_page_try_remove_write(p)) {
436 			vm_page_xunbusy(p);
437 			break;
438 		}
439 		mc[page_base + pageout_count] = ps = p;
440 		++pageout_count;
441 		++is;
442 	}
443 
444 	/*
445 	 * If we exhausted our forward scan, continue with the reverse scan
446 	 * when possible, even past an alignment boundary.  This catches
447 	 * boundary conditions.
448 	 */
449 	if (ib != 0 && pageout_count < vm_pageout_page_count)
450 		goto more;
451 
452 	return (vm_pageout_flush(&mc[page_base], pageout_count,
453 	    VM_PAGER_PUT_NOREUSE, 0, NULL, NULL));
454 }
455 
456 /*
457  * vm_pageout_flush() - launder the given pages
458  *
459  *	The given pages are laundered.  Note that we setup for the start of
460  *	I/O ( i.e. busy the page ), mark it read-only, and bump the object
461  *	reference count all in here rather then in the parent.  If we want
462  *	the parent to do more sophisticated things we may have to change
463  *	the ordering.
464  *
465  *	Returned runlen is the count of pages between mreq and first
466  *	page after mreq with status VM_PAGER_AGAIN.
467  *	*eio is set to TRUE if pager returned VM_PAGER_ERROR or VM_PAGER_FAIL
468  *	for any page in runlen set.
469  */
470 int
471 vm_pageout_flush(vm_page_t *mc, int count, int flags, int mreq, int *prunlen,
472     boolean_t *eio)
473 {
474 	vm_object_t object = mc[0]->object;
475 	int pageout_status[count];
476 	int numpagedout = 0;
477 	int i, runlen;
478 
479 	VM_OBJECT_ASSERT_WLOCKED(object);
480 
481 	/*
482 	 * Initiate I/O.  Mark the pages shared busy and verify that they're
483 	 * valid and read-only.
484 	 *
485 	 * We do not have to fixup the clean/dirty bits here... we can
486 	 * allow the pager to do it after the I/O completes.
487 	 *
488 	 * NOTE! mc[i]->dirty may be partial or fragmented due to an
489 	 * edge case with file fragments.
490 	 */
491 	for (i = 0; i < count; i++) {
492 		KASSERT(vm_page_all_valid(mc[i]),
493 		    ("vm_pageout_flush: partially invalid page %p index %d/%d",
494 			mc[i], i, count));
495 		KASSERT((mc[i]->a.flags & PGA_WRITEABLE) == 0,
496 		    ("vm_pageout_flush: writeable page %p", mc[i]));
497 		vm_page_busy_downgrade(mc[i]);
498 	}
499 	vm_object_pip_add(object, count);
500 
501 	vm_pager_put_pages(object, mc, count, flags, pageout_status);
502 
503 	runlen = count - mreq;
504 	if (eio != NULL)
505 		*eio = FALSE;
506 	for (i = 0; i < count; i++) {
507 		vm_page_t mt = mc[i];
508 
509 		KASSERT(pageout_status[i] == VM_PAGER_PEND ||
510 		    !pmap_page_is_write_mapped(mt),
511 		    ("vm_pageout_flush: page %p is not write protected", mt));
512 		switch (pageout_status[i]) {
513 		case VM_PAGER_OK:
514 			/*
515 			 * The page may have moved since laundering started, in
516 			 * which case it should be left alone.
517 			 */
518 			if (vm_page_in_laundry(mt))
519 				vm_page_deactivate_noreuse(mt);
520 			/* FALLTHROUGH */
521 		case VM_PAGER_PEND:
522 			numpagedout++;
523 			break;
524 		case VM_PAGER_BAD:
525 			/*
526 			 * The page is outside the object's range.  We pretend
527 			 * that the page out worked and clean the page, so the
528 			 * changes will be lost if the page is reclaimed by
529 			 * the page daemon.
530 			 */
531 			vm_page_undirty(mt);
532 			if (vm_page_in_laundry(mt))
533 				vm_page_deactivate_noreuse(mt);
534 			break;
535 		case VM_PAGER_ERROR:
536 		case VM_PAGER_FAIL:
537 			/*
538 			 * If the page couldn't be paged out to swap because the
539 			 * pager wasn't able to find space, place the page in
540 			 * the PQ_UNSWAPPABLE holding queue.  This is an
541 			 * optimization that prevents the page daemon from
542 			 * wasting CPU cycles on pages that cannot be reclaimed
543 			 * because no swap device is configured.
544 			 *
545 			 * Otherwise, reactivate the page so that it doesn't
546 			 * clog the laundry and inactive queues.  (We will try
547 			 * paging it out again later.)
548 			 */
549 			if ((object->flags & OBJ_SWAP) != 0 &&
550 			    pageout_status[i] == VM_PAGER_FAIL) {
551 				vm_page_unswappable(mt);
552 				numpagedout++;
553 			} else
554 				vm_page_activate(mt);
555 			if (eio != NULL && i >= mreq && i - mreq < runlen)
556 				*eio = TRUE;
557 			break;
558 		case VM_PAGER_AGAIN:
559 			if (i >= mreq && i - mreq < runlen)
560 				runlen = i - mreq;
561 			break;
562 		}
563 
564 		/*
565 		 * If the operation is still going, leave the page busy to
566 		 * block all other accesses. Also, leave the paging in
567 		 * progress indicator set so that we don't attempt an object
568 		 * collapse.
569 		 */
570 		if (pageout_status[i] != VM_PAGER_PEND) {
571 			vm_object_pip_wakeup(object);
572 			vm_page_sunbusy(mt);
573 		}
574 	}
575 	if (prunlen != NULL)
576 		*prunlen = runlen;
577 	return (numpagedout);
578 }
579 
580 static void
581 vm_pageout_swapon(void *arg __unused, struct swdevt *sp __unused)
582 {
583 
584 	atomic_store_rel_int(&swapdev_enabled, 1);
585 }
586 
587 static void
588 vm_pageout_swapoff(void *arg __unused, struct swdevt *sp __unused)
589 {
590 
591 	if (swap_pager_nswapdev() == 1)
592 		atomic_store_rel_int(&swapdev_enabled, 0);
593 }
594 
595 /*
596  * Attempt to acquire all of the necessary locks to launder a page and
597  * then call through the clustering layer to PUTPAGES.  Wait a short
598  * time for a vnode lock.
599  *
600  * Requires the page and object lock on entry, releases both before return.
601  * Returns 0 on success and an errno otherwise.
602  */
603 static int
604 vm_pageout_clean(vm_page_t m, int *numpagedout)
605 {
606 	struct vnode *vp;
607 	struct mount *mp;
608 	vm_object_t object;
609 	vm_pindex_t pindex;
610 	int error;
611 
612 	object = m->object;
613 	VM_OBJECT_ASSERT_WLOCKED(object);
614 	error = 0;
615 	vp = NULL;
616 	mp = NULL;
617 
618 	/*
619 	 * The object is already known NOT to be dead.   It
620 	 * is possible for the vget() to block the whole
621 	 * pageout daemon, but the new low-memory handling
622 	 * code should prevent it.
623 	 *
624 	 * We can't wait forever for the vnode lock, we might
625 	 * deadlock due to a vn_read() getting stuck in
626 	 * vm_wait while holding this vnode.  We skip the
627 	 * vnode if we can't get it in a reasonable amount
628 	 * of time.
629 	 */
630 	if (object->type == OBJT_VNODE) {
631 		vm_page_xunbusy(m);
632 		vp = object->handle;
633 		if (vp->v_type == VREG &&
634 		    vn_start_write(vp, &mp, V_NOWAIT) != 0) {
635 			mp = NULL;
636 			error = EDEADLK;
637 			goto unlock_all;
638 		}
639 		KASSERT(mp != NULL,
640 		    ("vp %p with NULL v_mount", vp));
641 		vm_object_reference_locked(object);
642 		pindex = m->pindex;
643 		VM_OBJECT_WUNLOCK(object);
644 		if (vget(vp, vn_lktype_write(NULL, vp) | LK_TIMELOCK) != 0) {
645 			vp = NULL;
646 			error = EDEADLK;
647 			goto unlock_mp;
648 		}
649 		VM_OBJECT_WLOCK(object);
650 
651 		/*
652 		 * Ensure that the object and vnode were not disassociated
653 		 * while locks were dropped.
654 		 */
655 		if (vp->v_object != object) {
656 			error = ENOENT;
657 			goto unlock_all;
658 		}
659 
660 		/*
661 		 * While the object was unlocked, the page may have been:
662 		 * (1) moved to a different queue,
663 		 * (2) reallocated to a different object,
664 		 * (3) reallocated to a different offset, or
665 		 * (4) cleaned.
666 		 */
667 		if (!vm_page_in_laundry(m) || m->object != object ||
668 		    m->pindex != pindex || m->dirty == 0) {
669 			error = ENXIO;
670 			goto unlock_all;
671 		}
672 
673 		/*
674 		 * The page may have been busied while the object lock was
675 		 * released.
676 		 */
677 		if (vm_page_tryxbusy(m) == 0) {
678 			error = EBUSY;
679 			goto unlock_all;
680 		}
681 	}
682 
683 	/*
684 	 * Remove all writeable mappings, failing if the page is wired.
685 	 */
686 	if (!vm_page_try_remove_write(m)) {
687 		vm_page_xunbusy(m);
688 		error = EBUSY;
689 		goto unlock_all;
690 	}
691 
692 	/*
693 	 * If a page is dirty, then it is either being washed
694 	 * (but not yet cleaned) or it is still in the
695 	 * laundry.  If it is still in the laundry, then we
696 	 * start the cleaning operation.
697 	 */
698 	if ((*numpagedout = vm_pageout_cluster(m)) == 0)
699 		error = EIO;
700 
701 unlock_all:
702 	VM_OBJECT_WUNLOCK(object);
703 
704 unlock_mp:
705 	if (mp != NULL) {
706 		if (vp != NULL)
707 			vput(vp);
708 		vm_object_deallocate(object);
709 		vn_finished_write(mp);
710 	}
711 
712 	return (error);
713 }
714 
715 /*
716  * Attempt to launder the specified number of pages.
717  *
718  * Returns the number of pages successfully laundered.
719  */
720 static int
721 vm_pageout_launder(struct vm_domain *vmd, int launder, bool in_shortfall)
722 {
723 	struct scan_state ss;
724 	struct vm_pagequeue *pq;
725 	vm_object_t object;
726 	vm_page_t m, marker;
727 	vm_page_astate_t new, old;
728 	int act_delta, error, numpagedout, queue, refs, starting_target;
729 	int vnodes_skipped;
730 	bool pageout_ok;
731 
732 	object = NULL;
733 	starting_target = launder;
734 	vnodes_skipped = 0;
735 
736 	/*
737 	 * Scan the laundry queues for pages eligible to be laundered.  We stop
738 	 * once the target number of dirty pages have been laundered, or once
739 	 * we've reached the end of the queue.  A single iteration of this loop
740 	 * may cause more than one page to be laundered because of clustering.
741 	 *
742 	 * As an optimization, we avoid laundering from PQ_UNSWAPPABLE when no
743 	 * swap devices are configured.
744 	 */
745 	if (atomic_load_acq_int(&swapdev_enabled))
746 		queue = PQ_UNSWAPPABLE;
747 	else
748 		queue = PQ_LAUNDRY;
749 
750 scan:
751 	marker = &vmd->vmd_markers[queue];
752 	pq = &vmd->vmd_pagequeues[queue];
753 	vm_pagequeue_lock(pq);
754 	vm_pageout_init_scan(&ss, pq, marker, NULL, pq->pq_cnt);
755 	while (launder > 0 && (m = vm_pageout_next(&ss, false)) != NULL) {
756 		if (__predict_false((m->flags & PG_MARKER) != 0))
757 			continue;
758 
759 		/*
760 		 * Don't touch a page that was removed from the queue after the
761 		 * page queue lock was released.  Otherwise, ensure that any
762 		 * pending queue operations, such as dequeues for wired pages,
763 		 * are handled.
764 		 */
765 		if (vm_pageout_defer(m, queue, true))
766 			continue;
767 
768 		/*
769 		 * Lock the page's object.
770 		 */
771 		if (object == NULL || object != m->object) {
772 			if (object != NULL)
773 				VM_OBJECT_WUNLOCK(object);
774 			object = atomic_load_ptr(&m->object);
775 			if (__predict_false(object == NULL))
776 				/* The page is being freed by another thread. */
777 				continue;
778 
779 			/* Depends on type-stability. */
780 			VM_OBJECT_WLOCK(object);
781 			if (__predict_false(m->object != object)) {
782 				VM_OBJECT_WUNLOCK(object);
783 				object = NULL;
784 				continue;
785 			}
786 		}
787 
788 		if (vm_page_tryxbusy(m) == 0)
789 			continue;
790 
791 		/*
792 		 * Check for wirings now that we hold the object lock and have
793 		 * exclusively busied the page.  If the page is mapped, it may
794 		 * still be wired by pmap lookups.  The call to
795 		 * vm_page_try_remove_all() below atomically checks for such
796 		 * wirings and removes mappings.  If the page is unmapped, the
797 		 * wire count is guaranteed not to increase after this check.
798 		 */
799 		if (__predict_false(vm_page_wired(m)))
800 			goto skip_page;
801 
802 		/*
803 		 * Invalid pages can be easily freed.  They cannot be
804 		 * mapped; vm_page_free() asserts this.
805 		 */
806 		if (vm_page_none_valid(m))
807 			goto free_page;
808 
809 		refs = object->ref_count != 0 ? pmap_ts_referenced(m) : 0;
810 
811 		for (old = vm_page_astate_load(m);;) {
812 			/*
813 			 * Check to see if the page has been removed from the
814 			 * queue since the first such check.  Leave it alone if
815 			 * so, discarding any references collected by
816 			 * pmap_ts_referenced().
817 			 */
818 			if (__predict_false(_vm_page_queue(old) == PQ_NONE))
819 				goto skip_page;
820 
821 			new = old;
822 			act_delta = refs;
823 			if ((old.flags & PGA_REFERENCED) != 0) {
824 				new.flags &= ~PGA_REFERENCED;
825 				act_delta++;
826 			}
827 			if (act_delta == 0) {
828 				;
829 			} else if (object->ref_count != 0) {
830 				/*
831 				 * Increase the activation count if the page was
832 				 * referenced while in the laundry queue.  This
833 				 * makes it less likely that the page will be
834 				 * returned prematurely to the laundry queue.
835 				 */
836 				new.act_count += ACT_ADVANCE +
837 				    act_delta;
838 				if (new.act_count > ACT_MAX)
839 					new.act_count = ACT_MAX;
840 
841 				new.flags &= ~PGA_QUEUE_OP_MASK;
842 				new.flags |= PGA_REQUEUE;
843 				new.queue = PQ_ACTIVE;
844 				if (!vm_page_pqstate_commit(m, &old, new))
845 					continue;
846 
847 				/*
848 				 * If this was a background laundering, count
849 				 * activated pages towards our target.  The
850 				 * purpose of background laundering is to ensure
851 				 * that pages are eventually cycled through the
852 				 * laundry queue, and an activation is a valid
853 				 * way out.
854 				 */
855 				if (!in_shortfall)
856 					launder--;
857 				VM_CNT_INC(v_reactivated);
858 				goto skip_page;
859 			} else if ((object->flags & OBJ_DEAD) == 0) {
860 				new.flags |= PGA_REQUEUE;
861 				if (!vm_page_pqstate_commit(m, &old, new))
862 					continue;
863 				goto skip_page;
864 			}
865 			break;
866 		}
867 
868 		/*
869 		 * If the page appears to be clean at the machine-independent
870 		 * layer, then remove all of its mappings from the pmap in
871 		 * anticipation of freeing it.  If, however, any of the page's
872 		 * mappings allow write access, then the page may still be
873 		 * modified until the last of those mappings are removed.
874 		 */
875 		if (object->ref_count != 0) {
876 			vm_page_test_dirty(m);
877 			if (m->dirty == 0 && !vm_page_try_remove_all(m))
878 				goto skip_page;
879 		}
880 
881 		/*
882 		 * Clean pages are freed, and dirty pages are paged out unless
883 		 * they belong to a dead object.  Requeueing dirty pages from
884 		 * dead objects is pointless, as they are being paged out and
885 		 * freed by the thread that destroyed the object.
886 		 */
887 		if (m->dirty == 0) {
888 free_page:
889 			/*
890 			 * Now we are guaranteed that no other threads are
891 			 * manipulating the page, check for a last-second
892 			 * reference.
893 			 */
894 			if (vm_pageout_defer(m, queue, true))
895 				goto skip_page;
896 			vm_page_free(m);
897 			VM_CNT_INC(v_dfree);
898 		} else if ((object->flags & OBJ_DEAD) == 0) {
899 			if ((object->flags & OBJ_SWAP) != 0)
900 				pageout_ok = disable_swap_pageouts == 0;
901 			else
902 				pageout_ok = true;
903 			if (!pageout_ok) {
904 				vm_page_launder(m);
905 				goto skip_page;
906 			}
907 
908 			/*
909 			 * Form a cluster with adjacent, dirty pages from the
910 			 * same object, and page out that entire cluster.
911 			 *
912 			 * The adjacent, dirty pages must also be in the
913 			 * laundry.  However, their mappings are not checked
914 			 * for new references.  Consequently, a recently
915 			 * referenced page may be paged out.  However, that
916 			 * page will not be prematurely reclaimed.  After page
917 			 * out, the page will be placed in the inactive queue,
918 			 * where any new references will be detected and the
919 			 * page reactivated.
920 			 */
921 			error = vm_pageout_clean(m, &numpagedout);
922 			if (error == 0) {
923 				launder -= numpagedout;
924 				ss.scanned += numpagedout;
925 			} else if (error == EDEADLK) {
926 				pageout_lock_miss++;
927 				vnodes_skipped++;
928 			}
929 			object = NULL;
930 		} else {
931 skip_page:
932 			vm_page_xunbusy(m);
933 		}
934 	}
935 	if (object != NULL) {
936 		VM_OBJECT_WUNLOCK(object);
937 		object = NULL;
938 	}
939 	vm_pagequeue_lock(pq);
940 	vm_pageout_end_scan(&ss);
941 	vm_pagequeue_unlock(pq);
942 
943 	if (launder > 0 && queue == PQ_UNSWAPPABLE) {
944 		queue = PQ_LAUNDRY;
945 		goto scan;
946 	}
947 
948 	/*
949 	 * Wakeup the sync daemon if we skipped a vnode in a writeable object
950 	 * and we didn't launder enough pages.
951 	 */
952 	if (vnodes_skipped > 0 && launder > 0)
953 		(void)speedup_syncer();
954 
955 	return (starting_target - launder);
956 }
957 
958 /*
959  * Compute the integer square root.
960  */
961 static u_int
962 isqrt(u_int num)
963 {
964 	u_int bit, root, tmp;
965 
966 	bit = num != 0 ? (1u << ((fls(num) - 1) & ~1)) : 0;
967 	root = 0;
968 	while (bit != 0) {
969 		tmp = root + bit;
970 		root >>= 1;
971 		if (num >= tmp) {
972 			num -= tmp;
973 			root += bit;
974 		}
975 		bit >>= 2;
976 	}
977 	return (root);
978 }
979 
980 /*
981  * Perform the work of the laundry thread: periodically wake up and determine
982  * whether any pages need to be laundered.  If so, determine the number of pages
983  * that need to be laundered, and launder them.
984  */
985 static void
986 vm_pageout_laundry_worker(void *arg)
987 {
988 	struct vm_domain *vmd;
989 	struct vm_pagequeue *pq;
990 	uint64_t nclean, ndirty, nfreed;
991 	int domain, last_target, launder, shortfall, shortfall_cycle, target;
992 	bool in_shortfall;
993 
994 	domain = (uintptr_t)arg;
995 	vmd = VM_DOMAIN(domain);
996 	pq = &vmd->vmd_pagequeues[PQ_LAUNDRY];
997 	KASSERT(vmd->vmd_segs != 0, ("domain without segments"));
998 
999 	shortfall = 0;
1000 	in_shortfall = false;
1001 	shortfall_cycle = 0;
1002 	last_target = target = 0;
1003 	nfreed = 0;
1004 
1005 	/*
1006 	 * Calls to these handlers are serialized by the swap syscall lock.
1007 	 */
1008 	(void)EVENTHANDLER_REGISTER(swapon, vm_pageout_swapon, vmd,
1009 	    EVENTHANDLER_PRI_ANY);
1010 	(void)EVENTHANDLER_REGISTER(swapoff, vm_pageout_swapoff, vmd,
1011 	    EVENTHANDLER_PRI_ANY);
1012 
1013 	/*
1014 	 * The pageout laundry worker is never done, so loop forever.
1015 	 */
1016 	for (;;) {
1017 		KASSERT(target >= 0, ("negative target %d", target));
1018 		KASSERT(shortfall_cycle >= 0,
1019 		    ("negative cycle %d", shortfall_cycle));
1020 		launder = 0;
1021 
1022 		/*
1023 		 * First determine whether we need to launder pages to meet a
1024 		 * shortage of free pages.
1025 		 */
1026 		if (shortfall > 0) {
1027 			in_shortfall = true;
1028 			shortfall_cycle = VM_LAUNDER_RATE / VM_INACT_SCAN_RATE;
1029 			target = shortfall;
1030 		} else if (!in_shortfall)
1031 			goto trybackground;
1032 		else if (shortfall_cycle == 0 || vm_laundry_target(vmd) <= 0) {
1033 			/*
1034 			 * We recently entered shortfall and began laundering
1035 			 * pages.  If we have completed that laundering run
1036 			 * (and we are no longer in shortfall) or we have met
1037 			 * our laundry target through other activity, then we
1038 			 * can stop laundering pages.
1039 			 */
1040 			in_shortfall = false;
1041 			target = 0;
1042 			goto trybackground;
1043 		}
1044 		launder = target / shortfall_cycle--;
1045 		goto dolaundry;
1046 
1047 		/*
1048 		 * There's no immediate need to launder any pages; see if we
1049 		 * meet the conditions to perform background laundering:
1050 		 *
1051 		 * 1. The ratio of dirty to clean inactive pages exceeds the
1052 		 *    background laundering threshold, or
1053 		 * 2. we haven't yet reached the target of the current
1054 		 *    background laundering run.
1055 		 *
1056 		 * The background laundering threshold is not a constant.
1057 		 * Instead, it is a slowly growing function of the number of
1058 		 * clean pages freed by the page daemon since the last
1059 		 * background laundering.  Thus, as the ratio of dirty to
1060 		 * clean inactive pages grows, the amount of memory pressure
1061 		 * required to trigger laundering decreases.  We ensure
1062 		 * that the threshold is non-zero after an inactive queue
1063 		 * scan, even if that scan failed to free a single clean page.
1064 		 */
1065 trybackground:
1066 		nclean = vmd->vmd_free_count +
1067 		    vmd->vmd_pagequeues[PQ_INACTIVE].pq_cnt;
1068 		ndirty = vmd->vmd_pagequeues[PQ_LAUNDRY].pq_cnt;
1069 		if (target == 0 && ndirty * isqrt(howmany(nfreed + 1,
1070 		    vmd->vmd_free_target - vmd->vmd_free_min)) >= nclean) {
1071 			target = vmd->vmd_background_launder_target;
1072 		}
1073 
1074 		/*
1075 		 * We have a non-zero background laundering target.  If we've
1076 		 * laundered up to our maximum without observing a page daemon
1077 		 * request, just stop.  This is a safety belt that ensures we
1078 		 * don't launder an excessive amount if memory pressure is low
1079 		 * and the ratio of dirty to clean pages is large.  Otherwise,
1080 		 * proceed at the background laundering rate.
1081 		 */
1082 		if (target > 0) {
1083 			if (nfreed > 0) {
1084 				nfreed = 0;
1085 				last_target = target;
1086 			} else if (last_target - target >=
1087 			    vm_background_launder_max * PAGE_SIZE / 1024) {
1088 				target = 0;
1089 			}
1090 			launder = vm_background_launder_rate * PAGE_SIZE / 1024;
1091 			launder /= VM_LAUNDER_RATE;
1092 			if (launder > target)
1093 				launder = target;
1094 		}
1095 
1096 dolaundry:
1097 		if (launder > 0) {
1098 			/*
1099 			 * Because of I/O clustering, the number of laundered
1100 			 * pages could exceed "target" by the maximum size of
1101 			 * a cluster minus one.
1102 			 */
1103 			target -= min(vm_pageout_launder(vmd, launder,
1104 			    in_shortfall), target);
1105 			pause("laundp", hz / VM_LAUNDER_RATE);
1106 		}
1107 
1108 		/*
1109 		 * If we're not currently laundering pages and the page daemon
1110 		 * hasn't posted a new request, sleep until the page daemon
1111 		 * kicks us.
1112 		 */
1113 		vm_pagequeue_lock(pq);
1114 		if (target == 0 && vmd->vmd_laundry_request == VM_LAUNDRY_IDLE)
1115 			(void)mtx_sleep(&vmd->vmd_laundry_request,
1116 			    vm_pagequeue_lockptr(pq), PVM, "launds", 0);
1117 
1118 		/*
1119 		 * If the pagedaemon has indicated that it's in shortfall, start
1120 		 * a shortfall laundering unless we're already in the middle of
1121 		 * one.  This may preempt a background laundering.
1122 		 */
1123 		if (vmd->vmd_laundry_request == VM_LAUNDRY_SHORTFALL &&
1124 		    (!in_shortfall || shortfall_cycle == 0)) {
1125 			shortfall = vm_laundry_target(vmd) +
1126 			    vmd->vmd_pageout_deficit;
1127 			target = 0;
1128 		} else
1129 			shortfall = 0;
1130 
1131 		if (target == 0)
1132 			vmd->vmd_laundry_request = VM_LAUNDRY_IDLE;
1133 		nfreed += vmd->vmd_clean_pages_freed;
1134 		vmd->vmd_clean_pages_freed = 0;
1135 		vm_pagequeue_unlock(pq);
1136 	}
1137 }
1138 
1139 /*
1140  * Compute the number of pages we want to try to move from the
1141  * active queue to either the inactive or laundry queue.
1142  *
1143  * When scanning active pages during a shortage, we make clean pages
1144  * count more heavily towards the page shortage than dirty pages.
1145  * This is because dirty pages must be laundered before they can be
1146  * reused and thus have less utility when attempting to quickly
1147  * alleviate a free page shortage.  However, this weighting also
1148  * causes the scan to deactivate dirty pages more aggressively,
1149  * improving the effectiveness of clustering.
1150  */
1151 static int
1152 vm_pageout_active_target(struct vm_domain *vmd)
1153 {
1154 	int shortage;
1155 
1156 	shortage = vmd->vmd_inactive_target + vm_paging_target(vmd) -
1157 	    (vmd->vmd_pagequeues[PQ_INACTIVE].pq_cnt +
1158 	    vmd->vmd_pagequeues[PQ_LAUNDRY].pq_cnt / act_scan_laundry_weight);
1159 	shortage *= act_scan_laundry_weight;
1160 	return (shortage);
1161 }
1162 
1163 /*
1164  * Scan the active queue.  If there is no shortage of inactive pages, scan a
1165  * small portion of the queue in order to maintain quasi-LRU.
1166  */
1167 static void
1168 vm_pageout_scan_active(struct vm_domain *vmd, int page_shortage)
1169 {
1170 	struct scan_state ss;
1171 	vm_object_t object;
1172 	vm_page_t m, marker;
1173 	struct vm_pagequeue *pq;
1174 	vm_page_astate_t old, new;
1175 	long min_scan;
1176 	int act_delta, max_scan, ps_delta, refs, scan_tick;
1177 	uint8_t nqueue;
1178 
1179 	marker = &vmd->vmd_markers[PQ_ACTIVE];
1180 	pq = &vmd->vmd_pagequeues[PQ_ACTIVE];
1181 	vm_pagequeue_lock(pq);
1182 
1183 	/*
1184 	 * If we're just idle polling attempt to visit every
1185 	 * active page within 'update_period' seconds.
1186 	 */
1187 	scan_tick = ticks;
1188 	if (vm_pageout_update_period != 0) {
1189 		min_scan = pq->pq_cnt;
1190 		min_scan *= scan_tick - vmd->vmd_last_active_scan;
1191 		min_scan /= hz * vm_pageout_update_period;
1192 	} else
1193 		min_scan = 0;
1194 	if (min_scan > 0 || (page_shortage > 0 && pq->pq_cnt > 0))
1195 		vmd->vmd_last_active_scan = scan_tick;
1196 
1197 	/*
1198 	 * Scan the active queue for pages that can be deactivated.  Update
1199 	 * the per-page activity counter and use it to identify deactivation
1200 	 * candidates.  Held pages may be deactivated.
1201 	 *
1202 	 * To avoid requeuing each page that remains in the active queue, we
1203 	 * implement the CLOCK algorithm.  To keep the implementation of the
1204 	 * enqueue operation consistent for all page queues, we use two hands,
1205 	 * represented by marker pages. Scans begin at the first hand, which
1206 	 * precedes the second hand in the queue.  When the two hands meet,
1207 	 * they are moved back to the head and tail of the queue, respectively,
1208 	 * and scanning resumes.
1209 	 */
1210 	max_scan = page_shortage > 0 ? pq->pq_cnt : min_scan;
1211 act_scan:
1212 	vm_pageout_init_scan(&ss, pq, marker, &vmd->vmd_clock[0], max_scan);
1213 	while ((m = vm_pageout_next(&ss, false)) != NULL) {
1214 		if (__predict_false(m == &vmd->vmd_clock[1])) {
1215 			vm_pagequeue_lock(pq);
1216 			TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_clock[0], plinks.q);
1217 			TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_clock[1], plinks.q);
1218 			TAILQ_INSERT_HEAD(&pq->pq_pl, &vmd->vmd_clock[0],
1219 			    plinks.q);
1220 			TAILQ_INSERT_TAIL(&pq->pq_pl, &vmd->vmd_clock[1],
1221 			    plinks.q);
1222 			max_scan -= ss.scanned;
1223 			vm_pageout_end_scan(&ss);
1224 			goto act_scan;
1225 		}
1226 		if (__predict_false((m->flags & PG_MARKER) != 0))
1227 			continue;
1228 
1229 		/*
1230 		 * Don't touch a page that was removed from the queue after the
1231 		 * page queue lock was released.  Otherwise, ensure that any
1232 		 * pending queue operations, such as dequeues for wired pages,
1233 		 * are handled.
1234 		 */
1235 		if (vm_pageout_defer(m, PQ_ACTIVE, true))
1236 			continue;
1237 
1238 		/*
1239 		 * A page's object pointer may be set to NULL before
1240 		 * the object lock is acquired.
1241 		 */
1242 		object = atomic_load_ptr(&m->object);
1243 		if (__predict_false(object == NULL))
1244 			/*
1245 			 * The page has been removed from its object.
1246 			 */
1247 			continue;
1248 
1249 		/* Deferred free of swap space. */
1250 		if ((m->a.flags & PGA_SWAP_FREE) != 0 &&
1251 		    VM_OBJECT_TRYWLOCK(object)) {
1252 			if (m->object == object)
1253 				vm_pager_page_unswapped(m);
1254 			VM_OBJECT_WUNLOCK(object);
1255 		}
1256 
1257 		/*
1258 		 * Check to see "how much" the page has been used.
1259 		 *
1260 		 * Test PGA_REFERENCED after calling pmap_ts_referenced() so
1261 		 * that a reference from a concurrently destroyed mapping is
1262 		 * observed here and now.
1263 		 *
1264 		 * Perform an unsynchronized object ref count check.  While
1265 		 * the page lock ensures that the page is not reallocated to
1266 		 * another object, in particular, one with unmanaged mappings
1267 		 * that cannot support pmap_ts_referenced(), two races are,
1268 		 * nonetheless, possible:
1269 		 * 1) The count was transitioning to zero, but we saw a non-
1270 		 *    zero value.  pmap_ts_referenced() will return zero
1271 		 *    because the page is not mapped.
1272 		 * 2) The count was transitioning to one, but we saw zero.
1273 		 *    This race delays the detection of a new reference.  At
1274 		 *    worst, we will deactivate and reactivate the page.
1275 		 */
1276 		refs = object->ref_count != 0 ? pmap_ts_referenced(m) : 0;
1277 
1278 		old = vm_page_astate_load(m);
1279 		do {
1280 			/*
1281 			 * Check to see if the page has been removed from the
1282 			 * queue since the first such check.  Leave it alone if
1283 			 * so, discarding any references collected by
1284 			 * pmap_ts_referenced().
1285 			 */
1286 			if (__predict_false(_vm_page_queue(old) == PQ_NONE)) {
1287 				ps_delta = 0;
1288 				break;
1289 			}
1290 
1291 			/*
1292 			 * Advance or decay the act_count based on recent usage.
1293 			 */
1294 			new = old;
1295 			act_delta = refs;
1296 			if ((old.flags & PGA_REFERENCED) != 0) {
1297 				new.flags &= ~PGA_REFERENCED;
1298 				act_delta++;
1299 			}
1300 			if (act_delta != 0) {
1301 				new.act_count += ACT_ADVANCE + act_delta;
1302 				if (new.act_count > ACT_MAX)
1303 					new.act_count = ACT_MAX;
1304 			} else {
1305 				new.act_count -= min(new.act_count,
1306 				    ACT_DECLINE);
1307 			}
1308 
1309 			if (new.act_count > 0) {
1310 				/*
1311 				 * Adjust the activation count and keep the page
1312 				 * in the active queue.  The count might be left
1313 				 * unchanged if it is saturated.  The page may
1314 				 * have been moved to a different queue since we
1315 				 * started the scan, in which case we move it
1316 				 * back.
1317 				 */
1318 				ps_delta = 0;
1319 				if (old.queue != PQ_ACTIVE) {
1320 					new.flags &= ~PGA_QUEUE_OP_MASK;
1321 					new.flags |= PGA_REQUEUE;
1322 					new.queue = PQ_ACTIVE;
1323 				}
1324 			} else {
1325 				/*
1326 				 * When not short for inactive pages, let dirty
1327 				 * pages go through the inactive queue before
1328 				 * moving to the laundry queue.  This gives them
1329 				 * some extra time to be reactivated,
1330 				 * potentially avoiding an expensive pageout.
1331 				 * However, during a page shortage, the inactive
1332 				 * queue is necessarily small, and so dirty
1333 				 * pages would only spend a trivial amount of
1334 				 * time in the inactive queue.  Therefore, we
1335 				 * might as well place them directly in the
1336 				 * laundry queue to reduce queuing overhead.
1337 				 *
1338 				 * Calling vm_page_test_dirty() here would
1339 				 * require acquisition of the object's write
1340 				 * lock.  However, during a page shortage,
1341 				 * directing dirty pages into the laundry queue
1342 				 * is only an optimization and not a
1343 				 * requirement.  Therefore, we simply rely on
1344 				 * the opportunistic updates to the page's dirty
1345 				 * field by the pmap.
1346 				 */
1347 				if (page_shortage <= 0) {
1348 					nqueue = PQ_INACTIVE;
1349 					ps_delta = 0;
1350 				} else if (m->dirty == 0) {
1351 					nqueue = PQ_INACTIVE;
1352 					ps_delta = act_scan_laundry_weight;
1353 				} else {
1354 					nqueue = PQ_LAUNDRY;
1355 					ps_delta = 1;
1356 				}
1357 
1358 				new.flags &= ~PGA_QUEUE_OP_MASK;
1359 				new.flags |= PGA_REQUEUE;
1360 				new.queue = nqueue;
1361 			}
1362 		} while (!vm_page_pqstate_commit(m, &old, new));
1363 
1364 		page_shortage -= ps_delta;
1365 	}
1366 	vm_pagequeue_lock(pq);
1367 	TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_clock[0], plinks.q);
1368 	TAILQ_INSERT_AFTER(&pq->pq_pl, marker, &vmd->vmd_clock[0], plinks.q);
1369 	vm_pageout_end_scan(&ss);
1370 	vm_pagequeue_unlock(pq);
1371 }
1372 
1373 static int
1374 vm_pageout_reinsert_inactive_page(struct vm_pagequeue *pq, vm_page_t marker,
1375     vm_page_t m)
1376 {
1377 	vm_page_astate_t as;
1378 
1379 	vm_pagequeue_assert_locked(pq);
1380 
1381 	as = vm_page_astate_load(m);
1382 	if (as.queue != PQ_INACTIVE || (as.flags & PGA_ENQUEUED) != 0)
1383 		return (0);
1384 	vm_page_aflag_set(m, PGA_ENQUEUED);
1385 	TAILQ_INSERT_BEFORE(marker, m, plinks.q);
1386 	return (1);
1387 }
1388 
1389 /*
1390  * Re-add stuck pages to the inactive queue.  We will examine them again
1391  * during the next scan.  If the queue state of a page has changed since
1392  * it was physically removed from the page queue in
1393  * vm_pageout_collect_batch(), don't do anything with that page.
1394  */
1395 static void
1396 vm_pageout_reinsert_inactive(struct scan_state *ss, struct vm_batchqueue *bq,
1397     vm_page_t m)
1398 {
1399 	struct vm_pagequeue *pq;
1400 	vm_page_t marker;
1401 	int delta;
1402 
1403 	delta = 0;
1404 	marker = ss->marker;
1405 	pq = ss->pq;
1406 
1407 	if (m != NULL) {
1408 		if (vm_batchqueue_insert(bq, m) != 0)
1409 			return;
1410 		vm_pagequeue_lock(pq);
1411 		delta += vm_pageout_reinsert_inactive_page(pq, marker, m);
1412 	} else
1413 		vm_pagequeue_lock(pq);
1414 	while ((m = vm_batchqueue_pop(bq)) != NULL)
1415 		delta += vm_pageout_reinsert_inactive_page(pq, marker, m);
1416 	vm_pagequeue_cnt_add(pq, delta);
1417 	vm_pagequeue_unlock(pq);
1418 	vm_batchqueue_init(bq);
1419 }
1420 
1421 static void
1422 vm_pageout_scan_inactive(struct vm_domain *vmd, int page_shortage)
1423 {
1424 	struct timeval start, end;
1425 	struct scan_state ss;
1426 	struct vm_batchqueue rq;
1427 	struct vm_page marker_page;
1428 	vm_page_t m, marker;
1429 	struct vm_pagequeue *pq;
1430 	vm_object_t object;
1431 	vm_page_astate_t old, new;
1432 	int act_delta, addl_page_shortage, starting_page_shortage, refs;
1433 
1434 	object = NULL;
1435 	vm_batchqueue_init(&rq);
1436 	getmicrouptime(&start);
1437 
1438 	/*
1439 	 * The addl_page_shortage is an estimate of the number of temporarily
1440 	 * stuck pages in the inactive queue.  In other words, the
1441 	 * number of pages from the inactive count that should be
1442 	 * discounted in setting the target for the active queue scan.
1443 	 */
1444 	addl_page_shortage = 0;
1445 
1446 	/*
1447 	 * Start scanning the inactive queue for pages that we can free.  The
1448 	 * scan will stop when we reach the target or we have scanned the
1449 	 * entire queue.  (Note that m->a.act_count is not used to make
1450 	 * decisions for the inactive queue, only for the active queue.)
1451 	 */
1452 	starting_page_shortage = page_shortage;
1453 	marker = &marker_page;
1454 	vm_page_init_marker(marker, PQ_INACTIVE, 0);
1455 	pq = &vmd->vmd_pagequeues[PQ_INACTIVE];
1456 	vm_pagequeue_lock(pq);
1457 	vm_pageout_init_scan(&ss, pq, marker, NULL, pq->pq_cnt);
1458 	while (page_shortage > 0 && (m = vm_pageout_next(&ss, true)) != NULL) {
1459 		KASSERT((m->flags & PG_MARKER) == 0,
1460 		    ("marker page %p was dequeued", m));
1461 
1462 		/*
1463 		 * Don't touch a page that was removed from the queue after the
1464 		 * page queue lock was released.  Otherwise, ensure that any
1465 		 * pending queue operations, such as dequeues for wired pages,
1466 		 * are handled.
1467 		 */
1468 		if (vm_pageout_defer(m, PQ_INACTIVE, false))
1469 			continue;
1470 
1471 		/*
1472 		 * Lock the page's object.
1473 		 */
1474 		if (object == NULL || object != m->object) {
1475 			if (object != NULL)
1476 				VM_OBJECT_WUNLOCK(object);
1477 			object = atomic_load_ptr(&m->object);
1478 			if (__predict_false(object == NULL))
1479 				/* The page is being freed by another thread. */
1480 				continue;
1481 
1482 			/* Depends on type-stability. */
1483 			VM_OBJECT_WLOCK(object);
1484 			if (__predict_false(m->object != object)) {
1485 				VM_OBJECT_WUNLOCK(object);
1486 				object = NULL;
1487 				goto reinsert;
1488 			}
1489 		}
1490 
1491 		if (vm_page_tryxbusy(m) == 0) {
1492 			/*
1493 			 * Don't mess with busy pages.  Leave them at
1494 			 * the front of the queue.  Most likely, they
1495 			 * are being paged out and will leave the
1496 			 * queue shortly after the scan finishes.  So,
1497 			 * they ought to be discounted from the
1498 			 * inactive count.
1499 			 */
1500 			addl_page_shortage++;
1501 			goto reinsert;
1502 		}
1503 
1504 		/* Deferred free of swap space. */
1505 		if ((m->a.flags & PGA_SWAP_FREE) != 0)
1506 			vm_pager_page_unswapped(m);
1507 
1508 		/*
1509 		 * Check for wirings now that we hold the object lock and have
1510 		 * exclusively busied the page.  If the page is mapped, it may
1511 		 * still be wired by pmap lookups.  The call to
1512 		 * vm_page_try_remove_all() below atomically checks for such
1513 		 * wirings and removes mappings.  If the page is unmapped, the
1514 		 * wire count is guaranteed not to increase after this check.
1515 		 */
1516 		if (__predict_false(vm_page_wired(m)))
1517 			goto skip_page;
1518 
1519 		/*
1520 		 * Invalid pages can be easily freed. They cannot be
1521 		 * mapped, vm_page_free() asserts this.
1522 		 */
1523 		if (vm_page_none_valid(m))
1524 			goto free_page;
1525 
1526 		refs = object->ref_count != 0 ? pmap_ts_referenced(m) : 0;
1527 
1528 		for (old = vm_page_astate_load(m);;) {
1529 			/*
1530 			 * Check to see if the page has been removed from the
1531 			 * queue since the first such check.  Leave it alone if
1532 			 * so, discarding any references collected by
1533 			 * pmap_ts_referenced().
1534 			 */
1535 			if (__predict_false(_vm_page_queue(old) == PQ_NONE))
1536 				goto skip_page;
1537 
1538 			new = old;
1539 			act_delta = refs;
1540 			if ((old.flags & PGA_REFERENCED) != 0) {
1541 				new.flags &= ~PGA_REFERENCED;
1542 				act_delta++;
1543 			}
1544 			if (act_delta == 0) {
1545 				;
1546 			} else if (object->ref_count != 0) {
1547 				/*
1548 				 * Increase the activation count if the
1549 				 * page was referenced while in the
1550 				 * inactive queue.  This makes it less
1551 				 * likely that the page will be returned
1552 				 * prematurely to the inactive queue.
1553 				 */
1554 				new.act_count += ACT_ADVANCE +
1555 				    act_delta;
1556 				if (new.act_count > ACT_MAX)
1557 					new.act_count = ACT_MAX;
1558 
1559 				new.flags &= ~PGA_QUEUE_OP_MASK;
1560 				new.flags |= PGA_REQUEUE;
1561 				new.queue = PQ_ACTIVE;
1562 				if (!vm_page_pqstate_commit(m, &old, new))
1563 					continue;
1564 
1565 				VM_CNT_INC(v_reactivated);
1566 				goto skip_page;
1567 			} else if ((object->flags & OBJ_DEAD) == 0) {
1568 				new.queue = PQ_INACTIVE;
1569 				new.flags |= PGA_REQUEUE;
1570 				if (!vm_page_pqstate_commit(m, &old, new))
1571 					continue;
1572 				goto skip_page;
1573 			}
1574 			break;
1575 		}
1576 
1577 		/*
1578 		 * If the page appears to be clean at the machine-independent
1579 		 * layer, then remove all of its mappings from the pmap in
1580 		 * anticipation of freeing it.  If, however, any of the page's
1581 		 * mappings allow write access, then the page may still be
1582 		 * modified until the last of those mappings are removed.
1583 		 */
1584 		if (object->ref_count != 0) {
1585 			vm_page_test_dirty(m);
1586 			if (m->dirty == 0 && !vm_page_try_remove_all(m))
1587 				goto skip_page;
1588 		}
1589 
1590 		/*
1591 		 * Clean pages can be freed, but dirty pages must be sent back
1592 		 * to the laundry, unless they belong to a dead object.
1593 		 * Requeueing dirty pages from dead objects is pointless, as
1594 		 * they are being paged out and freed by the thread that
1595 		 * destroyed the object.
1596 		 */
1597 		if (m->dirty == 0) {
1598 free_page:
1599 			/*
1600 			 * Now we are guaranteed that no other threads are
1601 			 * manipulating the page, check for a last-second
1602 			 * reference that would save it from doom.
1603 			 */
1604 			if (vm_pageout_defer(m, PQ_INACTIVE, false))
1605 				goto skip_page;
1606 
1607 			/*
1608 			 * Because we dequeued the page and have already checked
1609 			 * for pending dequeue and enqueue requests, we can
1610 			 * safely disassociate the page from the inactive queue
1611 			 * without holding the queue lock.
1612 			 */
1613 			m->a.queue = PQ_NONE;
1614 			vm_page_free(m);
1615 			page_shortage--;
1616 			continue;
1617 		}
1618 		if ((object->flags & OBJ_DEAD) == 0)
1619 			vm_page_launder(m);
1620 skip_page:
1621 		vm_page_xunbusy(m);
1622 		continue;
1623 reinsert:
1624 		vm_pageout_reinsert_inactive(&ss, &rq, m);
1625 	}
1626 	if (object != NULL)
1627 		VM_OBJECT_WUNLOCK(object);
1628 	vm_pageout_reinsert_inactive(&ss, &rq, NULL);
1629 	vm_pageout_reinsert_inactive(&ss, &ss.bq, NULL);
1630 	vm_pagequeue_lock(pq);
1631 	vm_pageout_end_scan(&ss);
1632 	vm_pagequeue_unlock(pq);
1633 
1634 	/*
1635 	 * Record the remaining shortage and the progress and rate it was made.
1636 	 */
1637 	atomic_add_int(&vmd->vmd_addl_shortage, addl_page_shortage);
1638 	getmicrouptime(&end);
1639 	timevalsub(&end, &start);
1640 	atomic_add_int(&vmd->vmd_inactive_us,
1641 	    end.tv_sec * 1000000 + end.tv_usec);
1642 	atomic_add_int(&vmd->vmd_inactive_freed,
1643 	    starting_page_shortage - page_shortage);
1644 }
1645 
1646 /*
1647  * Dispatch a number of inactive threads according to load and collect the
1648  * results to present a coherent view of paging activity on this domain.
1649  */
1650 static int
1651 vm_pageout_inactive_dispatch(struct vm_domain *vmd, int shortage)
1652 {
1653 	u_int freed, pps, slop, threads, us;
1654 
1655 	vmd->vmd_inactive_shortage = shortage;
1656 	slop = 0;
1657 
1658 	/*
1659 	 * If we have more work than we can do in a quarter of our interval, we
1660 	 * fire off multiple threads to process it.
1661 	 */
1662 	threads = vmd->vmd_inactive_threads;
1663 	if (threads > 1 && vmd->vmd_inactive_pps != 0 &&
1664 	    shortage > vmd->vmd_inactive_pps / VM_INACT_SCAN_RATE / 4) {
1665 		vmd->vmd_inactive_shortage /= threads;
1666 		slop = shortage % threads;
1667 		vm_domain_pageout_lock(vmd);
1668 		blockcount_acquire(&vmd->vmd_inactive_starting, threads - 1);
1669 		blockcount_acquire(&vmd->vmd_inactive_running, threads - 1);
1670 		wakeup(&vmd->vmd_inactive_shortage);
1671 		vm_domain_pageout_unlock(vmd);
1672 	}
1673 
1674 	/* Run the local thread scan. */
1675 	vm_pageout_scan_inactive(vmd, vmd->vmd_inactive_shortage + slop);
1676 
1677 	/*
1678 	 * Block until helper threads report results and then accumulate
1679 	 * totals.
1680 	 */
1681 	blockcount_wait(&vmd->vmd_inactive_running, NULL, "vmpoid", PVM);
1682 	freed = atomic_readandclear_int(&vmd->vmd_inactive_freed);
1683 	VM_CNT_ADD(v_dfree, freed);
1684 
1685 	/*
1686 	 * Calculate the per-thread paging rate with an exponential decay of
1687 	 * prior results.  Careful to avoid integer rounding errors with large
1688 	 * us values.
1689 	 */
1690 	us = max(atomic_readandclear_int(&vmd->vmd_inactive_us), 1);
1691 	if (us > 1000000)
1692 		/* Keep rounding to tenths */
1693 		pps = (freed * 10) / ((us * 10) / 1000000);
1694 	else
1695 		pps = (1000000 / us) * freed;
1696 	vmd->vmd_inactive_pps = (vmd->vmd_inactive_pps / 2) + (pps / 2);
1697 
1698 	return (shortage - freed);
1699 }
1700 
1701 /*
1702  * Attempt to reclaim the requested number of pages from the inactive queue.
1703  * Returns true if the shortage was addressed.
1704  */
1705 static int
1706 vm_pageout_inactive(struct vm_domain *vmd, int shortage, int *addl_shortage)
1707 {
1708 	struct vm_pagequeue *pq;
1709 	u_int addl_page_shortage, deficit, page_shortage;
1710 	u_int starting_page_shortage;
1711 
1712 	/*
1713 	 * vmd_pageout_deficit counts the number of pages requested in
1714 	 * allocations that failed because of a free page shortage.  We assume
1715 	 * that the allocations will be reattempted and thus include the deficit
1716 	 * in our scan target.
1717 	 */
1718 	deficit = atomic_readandclear_int(&vmd->vmd_pageout_deficit);
1719 	starting_page_shortage = shortage + deficit;
1720 
1721 	/*
1722 	 * Run the inactive scan on as many threads as is necessary.
1723 	 */
1724 	page_shortage = vm_pageout_inactive_dispatch(vmd, starting_page_shortage);
1725 	addl_page_shortage = atomic_readandclear_int(&vmd->vmd_addl_shortage);
1726 
1727 	/*
1728 	 * Wake up the laundry thread so that it can perform any needed
1729 	 * laundering.  If we didn't meet our target, we're in shortfall and
1730 	 * need to launder more aggressively.  If PQ_LAUNDRY is empty and no
1731 	 * swap devices are configured, the laundry thread has no work to do, so
1732 	 * don't bother waking it up.
1733 	 *
1734 	 * The laundry thread uses the number of inactive queue scans elapsed
1735 	 * since the last laundering to determine whether to launder again, so
1736 	 * keep count.
1737 	 */
1738 	if (starting_page_shortage > 0) {
1739 		pq = &vmd->vmd_pagequeues[PQ_LAUNDRY];
1740 		vm_pagequeue_lock(pq);
1741 		if (vmd->vmd_laundry_request == VM_LAUNDRY_IDLE &&
1742 		    (pq->pq_cnt > 0 || atomic_load_acq_int(&swapdev_enabled))) {
1743 			if (page_shortage > 0) {
1744 				vmd->vmd_laundry_request = VM_LAUNDRY_SHORTFALL;
1745 				VM_CNT_INC(v_pdshortfalls);
1746 			} else if (vmd->vmd_laundry_request !=
1747 			    VM_LAUNDRY_SHORTFALL)
1748 				vmd->vmd_laundry_request =
1749 				    VM_LAUNDRY_BACKGROUND;
1750 			wakeup(&vmd->vmd_laundry_request);
1751 		}
1752 		vmd->vmd_clean_pages_freed +=
1753 		    starting_page_shortage - page_shortage;
1754 		vm_pagequeue_unlock(pq);
1755 	}
1756 
1757 	/*
1758 	 * Wakeup the swapout daemon if we didn't free the targeted number of
1759 	 * pages.
1760 	 */
1761 	if (page_shortage > 0)
1762 		vm_swapout_run();
1763 
1764 	/*
1765 	 * If the inactive queue scan fails repeatedly to meet its
1766 	 * target, kill the largest process.
1767 	 */
1768 	vm_pageout_mightbe_oom(vmd, page_shortage, starting_page_shortage);
1769 
1770 	/*
1771 	 * Reclaim pages by swapping out idle processes, if configured to do so.
1772 	 */
1773 	vm_swapout_run_idle();
1774 
1775 	/*
1776 	 * See the description of addl_page_shortage above.
1777 	 */
1778 	*addl_shortage = addl_page_shortage + deficit;
1779 
1780 	return (page_shortage <= 0);
1781 }
1782 
1783 static int vm_pageout_oom_vote;
1784 
1785 /*
1786  * The pagedaemon threads randlomly select one to perform the
1787  * OOM.  Trying to kill processes before all pagedaemons
1788  * failed to reach free target is premature.
1789  */
1790 static void
1791 vm_pageout_mightbe_oom(struct vm_domain *vmd, int page_shortage,
1792     int starting_page_shortage)
1793 {
1794 	int old_vote;
1795 
1796 	if (starting_page_shortage <= 0 || starting_page_shortage !=
1797 	    page_shortage)
1798 		vmd->vmd_oom_seq = 0;
1799 	else
1800 		vmd->vmd_oom_seq++;
1801 	if (vmd->vmd_oom_seq < vm_pageout_oom_seq) {
1802 		if (vmd->vmd_oom) {
1803 			vmd->vmd_oom = FALSE;
1804 			atomic_subtract_int(&vm_pageout_oom_vote, 1);
1805 		}
1806 		return;
1807 	}
1808 
1809 	/*
1810 	 * Do not follow the call sequence until OOM condition is
1811 	 * cleared.
1812 	 */
1813 	vmd->vmd_oom_seq = 0;
1814 
1815 	if (vmd->vmd_oom)
1816 		return;
1817 
1818 	vmd->vmd_oom = TRUE;
1819 	old_vote = atomic_fetchadd_int(&vm_pageout_oom_vote, 1);
1820 	if (old_vote != vm_ndomains - 1)
1821 		return;
1822 
1823 	/*
1824 	 * The current pagedaemon thread is the last in the quorum to
1825 	 * start OOM.  Initiate the selection and signaling of the
1826 	 * victim.
1827 	 */
1828 	vm_pageout_oom(VM_OOM_MEM);
1829 
1830 	/*
1831 	 * After one round of OOM terror, recall our vote.  On the
1832 	 * next pass, current pagedaemon would vote again if the low
1833 	 * memory condition is still there, due to vmd_oom being
1834 	 * false.
1835 	 */
1836 	vmd->vmd_oom = FALSE;
1837 	atomic_subtract_int(&vm_pageout_oom_vote, 1);
1838 }
1839 
1840 /*
1841  * The OOM killer is the page daemon's action of last resort when
1842  * memory allocation requests have been stalled for a prolonged period
1843  * of time because it cannot reclaim memory.  This function computes
1844  * the approximate number of physical pages that could be reclaimed if
1845  * the specified address space is destroyed.
1846  *
1847  * Private, anonymous memory owned by the address space is the
1848  * principal resource that we expect to recover after an OOM kill.
1849  * Since the physical pages mapped by the address space's COW entries
1850  * are typically shared pages, they are unlikely to be released and so
1851  * they are not counted.
1852  *
1853  * To get to the point where the page daemon runs the OOM killer, its
1854  * efforts to write-back vnode-backed pages may have stalled.  This
1855  * could be caused by a memory allocation deadlock in the write path
1856  * that might be resolved by an OOM kill.  Therefore, physical pages
1857  * belonging to vnode-backed objects are counted, because they might
1858  * be freed without being written out first if the address space holds
1859  * the last reference to an unlinked vnode.
1860  *
1861  * Similarly, physical pages belonging to OBJT_PHYS objects are
1862  * counted because the address space might hold the last reference to
1863  * the object.
1864  */
1865 static long
1866 vm_pageout_oom_pagecount(struct vmspace *vmspace)
1867 {
1868 	vm_map_t map;
1869 	vm_map_entry_t entry;
1870 	vm_object_t obj;
1871 	long res;
1872 
1873 	map = &vmspace->vm_map;
1874 	KASSERT(!map->system_map, ("system map"));
1875 	sx_assert(&map->lock, SA_LOCKED);
1876 	res = 0;
1877 	VM_MAP_ENTRY_FOREACH(entry, map) {
1878 		if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
1879 			continue;
1880 		obj = entry->object.vm_object;
1881 		if (obj == NULL)
1882 			continue;
1883 		if ((entry->eflags & MAP_ENTRY_NEEDS_COPY) != 0 &&
1884 		    obj->ref_count != 1)
1885 			continue;
1886 		if (obj->type == OBJT_PHYS || obj->type == OBJT_VNODE ||
1887 		    (obj->flags & OBJ_SWAP) != 0)
1888 			res += obj->resident_page_count;
1889 	}
1890 	return (res);
1891 }
1892 
1893 static int vm_oom_ratelim_last;
1894 static int vm_oom_pf_secs = 10;
1895 SYSCTL_INT(_vm, OID_AUTO, oom_pf_secs, CTLFLAG_RWTUN, &vm_oom_pf_secs, 0,
1896     "");
1897 static struct mtx vm_oom_ratelim_mtx;
1898 
1899 void
1900 vm_pageout_oom(int shortage)
1901 {
1902 	const char *reason;
1903 	struct proc *p, *bigproc;
1904 	vm_offset_t size, bigsize;
1905 	struct thread *td;
1906 	struct vmspace *vm;
1907 	int now;
1908 	bool breakout;
1909 
1910 	/*
1911 	 * For OOM requests originating from vm_fault(), there is a high
1912 	 * chance that a single large process faults simultaneously in
1913 	 * several threads.  Also, on an active system running many
1914 	 * processes of middle-size, like buildworld, all of them
1915 	 * could fault almost simultaneously as well.
1916 	 *
1917 	 * To avoid killing too many processes, rate-limit OOMs
1918 	 * initiated by vm_fault() time-outs on the waits for free
1919 	 * pages.
1920 	 */
1921 	mtx_lock(&vm_oom_ratelim_mtx);
1922 	now = ticks;
1923 	if (shortage == VM_OOM_MEM_PF &&
1924 	    (u_int)(now - vm_oom_ratelim_last) < hz * vm_oom_pf_secs) {
1925 		mtx_unlock(&vm_oom_ratelim_mtx);
1926 		return;
1927 	}
1928 	vm_oom_ratelim_last = now;
1929 	mtx_unlock(&vm_oom_ratelim_mtx);
1930 
1931 	/*
1932 	 * We keep the process bigproc locked once we find it to keep anyone
1933 	 * from messing with it; however, there is a possibility of
1934 	 * deadlock if process B is bigproc and one of its child processes
1935 	 * attempts to propagate a signal to B while we are waiting for A's
1936 	 * lock while walking this list.  To avoid this, we don't block on
1937 	 * the process lock but just skip a process if it is already locked.
1938 	 */
1939 	bigproc = NULL;
1940 	bigsize = 0;
1941 	sx_slock(&allproc_lock);
1942 	FOREACH_PROC_IN_SYSTEM(p) {
1943 		PROC_LOCK(p);
1944 
1945 		/*
1946 		 * If this is a system, protected or killed process, skip it.
1947 		 */
1948 		if (p->p_state != PRS_NORMAL || (p->p_flag & (P_INEXEC |
1949 		    P_PROTECTED | P_SYSTEM | P_WEXIT)) != 0 ||
1950 		    p->p_pid == 1 || P_KILLED(p) ||
1951 		    (p->p_pid < 48 && swap_pager_avail != 0)) {
1952 			PROC_UNLOCK(p);
1953 			continue;
1954 		}
1955 		/*
1956 		 * If the process is in a non-running type state,
1957 		 * don't touch it.  Check all the threads individually.
1958 		 */
1959 		breakout = false;
1960 		FOREACH_THREAD_IN_PROC(p, td) {
1961 			thread_lock(td);
1962 			if (!TD_ON_RUNQ(td) &&
1963 			    !TD_IS_RUNNING(td) &&
1964 			    !TD_IS_SLEEPING(td) &&
1965 			    !TD_IS_SUSPENDED(td) &&
1966 			    !TD_IS_SWAPPED(td)) {
1967 				thread_unlock(td);
1968 				breakout = true;
1969 				break;
1970 			}
1971 			thread_unlock(td);
1972 		}
1973 		if (breakout) {
1974 			PROC_UNLOCK(p);
1975 			continue;
1976 		}
1977 		/*
1978 		 * get the process size
1979 		 */
1980 		vm = vmspace_acquire_ref(p);
1981 		if (vm == NULL) {
1982 			PROC_UNLOCK(p);
1983 			continue;
1984 		}
1985 		_PHOLD_LITE(p);
1986 		PROC_UNLOCK(p);
1987 		sx_sunlock(&allproc_lock);
1988 		if (!vm_map_trylock_read(&vm->vm_map)) {
1989 			vmspace_free(vm);
1990 			sx_slock(&allproc_lock);
1991 			PRELE(p);
1992 			continue;
1993 		}
1994 		size = vmspace_swap_count(vm);
1995 		if (shortage == VM_OOM_MEM || shortage == VM_OOM_MEM_PF)
1996 			size += vm_pageout_oom_pagecount(vm);
1997 		vm_map_unlock_read(&vm->vm_map);
1998 		vmspace_free(vm);
1999 		sx_slock(&allproc_lock);
2000 
2001 		/*
2002 		 * If this process is bigger than the biggest one,
2003 		 * remember it.
2004 		 */
2005 		if (size > bigsize) {
2006 			if (bigproc != NULL)
2007 				PRELE(bigproc);
2008 			bigproc = p;
2009 			bigsize = size;
2010 		} else {
2011 			PRELE(p);
2012 		}
2013 	}
2014 	sx_sunlock(&allproc_lock);
2015 
2016 	if (bigproc != NULL) {
2017 		switch (shortage) {
2018 		case VM_OOM_MEM:
2019 			reason = "failed to reclaim memory";
2020 			break;
2021 		case VM_OOM_MEM_PF:
2022 			reason = "a thread waited too long to allocate a page";
2023 			break;
2024 		case VM_OOM_SWAPZ:
2025 			reason = "out of swap space";
2026 			break;
2027 		default:
2028 			panic("unknown OOM reason %d", shortage);
2029 		}
2030 		if (vm_panic_on_oom != 0 && --vm_panic_on_oom == 0)
2031 			panic("%s", reason);
2032 		PROC_LOCK(bigproc);
2033 		killproc(bigproc, reason);
2034 		sched_nice(bigproc, PRIO_MIN);
2035 		_PRELE(bigproc);
2036 		PROC_UNLOCK(bigproc);
2037 	}
2038 }
2039 
2040 /*
2041  * Signal a free page shortage to subsystems that have registered an event
2042  * handler.  Reclaim memory from UMA in the event of a severe shortage.
2043  * Return true if the free page count should be re-evaluated.
2044  */
2045 static bool
2046 vm_pageout_lowmem(void)
2047 {
2048 	static int lowmem_ticks = 0;
2049 	int last;
2050 	bool ret;
2051 
2052 	ret = false;
2053 
2054 	last = atomic_load_int(&lowmem_ticks);
2055 	while ((u_int)(ticks - last) / hz >= lowmem_period) {
2056 		if (atomic_fcmpset_int(&lowmem_ticks, &last, ticks) == 0)
2057 			continue;
2058 
2059 		/*
2060 		 * Decrease registered cache sizes.
2061 		 */
2062 		SDT_PROBE0(vm, , , vm__lowmem_scan);
2063 		EVENTHANDLER_INVOKE(vm_lowmem, VM_LOW_PAGES);
2064 
2065 		/*
2066 		 * We do this explicitly after the caches have been
2067 		 * drained above.
2068 		 */
2069 		uma_reclaim(UMA_RECLAIM_TRIM);
2070 		ret = true;
2071 		break;
2072 	}
2073 
2074 	/*
2075 	 * Kick off an asynchronous reclaim of cached memory if one of the
2076 	 * page daemons is failing to keep up with demand.  Use the "severe"
2077 	 * threshold instead of "min" to ensure that we do not blow away the
2078 	 * caches if a subset of the NUMA domains are depleted by kernel memory
2079 	 * allocations; the domainset iterators automatically skip domains
2080 	 * below the "min" threshold on the first pass.
2081 	 *
2082 	 * UMA reclaim worker has its own rate-limiting mechanism, so don't
2083 	 * worry about kicking it too often.
2084 	 */
2085 	if (vm_page_count_severe())
2086 		uma_reclaim_wakeup();
2087 
2088 	return (ret);
2089 }
2090 
2091 static void
2092 vm_pageout_worker(void *arg)
2093 {
2094 	struct vm_domain *vmd;
2095 	u_int ofree;
2096 	int addl_shortage, domain, shortage;
2097 	bool target_met;
2098 
2099 	domain = (uintptr_t)arg;
2100 	vmd = VM_DOMAIN(domain);
2101 	shortage = 0;
2102 	target_met = true;
2103 
2104 	/*
2105 	 * XXXKIB It could be useful to bind pageout daemon threads to
2106 	 * the cores belonging to the domain, from which vm_page_array
2107 	 * is allocated.
2108 	 */
2109 
2110 	KASSERT(vmd->vmd_segs != 0, ("domain without segments"));
2111 	vmd->vmd_last_active_scan = ticks;
2112 
2113 	/*
2114 	 * The pageout daemon worker is never done, so loop forever.
2115 	 */
2116 	while (TRUE) {
2117 		vm_domain_pageout_lock(vmd);
2118 
2119 		/*
2120 		 * We need to clear wanted before we check the limits.  This
2121 		 * prevents races with wakers who will check wanted after they
2122 		 * reach the limit.
2123 		 */
2124 		atomic_store_int(&vmd->vmd_pageout_wanted, 0);
2125 
2126 		/*
2127 		 * Might the page daemon need to run again?
2128 		 */
2129 		if (vm_paging_needed(vmd, vmd->vmd_free_count)) {
2130 			/*
2131 			 * Yes.  If the scan failed to produce enough free
2132 			 * pages, sleep uninterruptibly for some time in the
2133 			 * hope that the laundry thread will clean some pages.
2134 			 */
2135 			vm_domain_pageout_unlock(vmd);
2136 			if (!target_met)
2137 				pause("pwait", hz / VM_INACT_SCAN_RATE);
2138 		} else {
2139 			/*
2140 			 * No, sleep until the next wakeup or until pages
2141 			 * need to have their reference stats updated.
2142 			 */
2143 			if (mtx_sleep(&vmd->vmd_pageout_wanted,
2144 			    vm_domain_pageout_lockptr(vmd), PDROP | PVM,
2145 			    "psleep", hz / VM_INACT_SCAN_RATE) == 0)
2146 				VM_CNT_INC(v_pdwakeups);
2147 		}
2148 
2149 		/* Prevent spurious wakeups by ensuring that wanted is set. */
2150 		atomic_store_int(&vmd->vmd_pageout_wanted, 1);
2151 
2152 		/*
2153 		 * Use the controller to calculate how many pages to free in
2154 		 * this interval, and scan the inactive queue.  If the lowmem
2155 		 * handlers appear to have freed up some pages, subtract the
2156 		 * difference from the inactive queue scan target.
2157 		 */
2158 		shortage = pidctrl_daemon(&vmd->vmd_pid, vmd->vmd_free_count);
2159 		if (shortage > 0) {
2160 			ofree = vmd->vmd_free_count;
2161 			if (vm_pageout_lowmem() && vmd->vmd_free_count > ofree)
2162 				shortage -= min(vmd->vmd_free_count - ofree,
2163 				    (u_int)shortage);
2164 			target_met = vm_pageout_inactive(vmd, shortage,
2165 			    &addl_shortage);
2166 		} else
2167 			addl_shortage = 0;
2168 
2169 		/*
2170 		 * Scan the active queue.  A positive value for shortage
2171 		 * indicates that we must aggressively deactivate pages to avoid
2172 		 * a shortfall.
2173 		 */
2174 		shortage = vm_pageout_active_target(vmd) + addl_shortage;
2175 		vm_pageout_scan_active(vmd, shortage);
2176 	}
2177 }
2178 
2179 /*
2180  * vm_pageout_helper runs additional pageout daemons in times of high paging
2181  * activity.
2182  */
2183 static void
2184 vm_pageout_helper(void *arg)
2185 {
2186 	struct vm_domain *vmd;
2187 	int domain;
2188 
2189 	domain = (uintptr_t)arg;
2190 	vmd = VM_DOMAIN(domain);
2191 
2192 	vm_domain_pageout_lock(vmd);
2193 	for (;;) {
2194 		msleep(&vmd->vmd_inactive_shortage,
2195 		    vm_domain_pageout_lockptr(vmd), PVM, "psleep", 0);
2196 		blockcount_release(&vmd->vmd_inactive_starting, 1);
2197 
2198 		vm_domain_pageout_unlock(vmd);
2199 		vm_pageout_scan_inactive(vmd, vmd->vmd_inactive_shortage);
2200 		vm_domain_pageout_lock(vmd);
2201 
2202 		/*
2203 		 * Release the running count while the pageout lock is held to
2204 		 * prevent wakeup races.
2205 		 */
2206 		blockcount_release(&vmd->vmd_inactive_running, 1);
2207 	}
2208 }
2209 
2210 static int
2211 get_pageout_threads_per_domain(const struct vm_domain *vmd)
2212 {
2213 	unsigned total_pageout_threads, eligible_cpus, domain_cpus;
2214 
2215 	if (VM_DOMAIN_EMPTY(vmd->vmd_domain))
2216 		return (0);
2217 
2218 	/*
2219 	 * Semi-arbitrarily constrain pagedaemon threads to less than half the
2220 	 * total number of CPUs in the system as an upper limit.
2221 	 */
2222 	if (pageout_cpus_per_thread < 2)
2223 		pageout_cpus_per_thread = 2;
2224 	else if (pageout_cpus_per_thread > mp_ncpus)
2225 		pageout_cpus_per_thread = mp_ncpus;
2226 
2227 	total_pageout_threads = howmany(mp_ncpus, pageout_cpus_per_thread);
2228 	domain_cpus = CPU_COUNT(&cpuset_domain[vmd->vmd_domain]);
2229 
2230 	/* Pagedaemons are not run in empty domains. */
2231 	eligible_cpus = mp_ncpus;
2232 	for (unsigned i = 0; i < vm_ndomains; i++)
2233 		if (VM_DOMAIN_EMPTY(i))
2234 			eligible_cpus -= CPU_COUNT(&cpuset_domain[i]);
2235 
2236 	/*
2237 	 * Assign a portion of the total pageout threads to this domain
2238 	 * corresponding to the fraction of pagedaemon-eligible CPUs in the
2239 	 * domain.  In asymmetric NUMA systems, domains with more CPUs may be
2240 	 * allocated more threads than domains with fewer CPUs.
2241 	 */
2242 	return (howmany(total_pageout_threads * domain_cpus, eligible_cpus));
2243 }
2244 
2245 /*
2246  * Initialize basic pageout daemon settings.  See the comment above the
2247  * definition of vm_domain for some explanation of how these thresholds are
2248  * used.
2249  */
2250 static void
2251 vm_pageout_init_domain(int domain)
2252 {
2253 	struct vm_domain *vmd;
2254 	struct sysctl_oid *oid;
2255 
2256 	vmd = VM_DOMAIN(domain);
2257 	vmd->vmd_interrupt_free_min = 2;
2258 
2259 	/*
2260 	 * v_free_reserved needs to include enough for the largest
2261 	 * swap pager structures plus enough for any pv_entry structs
2262 	 * when paging.
2263 	 */
2264 	vmd->vmd_pageout_free_min = 2 * MAXBSIZE / PAGE_SIZE +
2265 	    vmd->vmd_interrupt_free_min;
2266 	vmd->vmd_free_reserved = vm_pageout_page_count +
2267 	    vmd->vmd_pageout_free_min + vmd->vmd_page_count / 768;
2268 	vmd->vmd_free_min = vmd->vmd_page_count / 200;
2269 	vmd->vmd_free_severe = vmd->vmd_free_min / 2;
2270 	vmd->vmd_free_target = 4 * vmd->vmd_free_min + vmd->vmd_free_reserved;
2271 	vmd->vmd_free_min += vmd->vmd_free_reserved;
2272 	vmd->vmd_free_severe += vmd->vmd_free_reserved;
2273 	vmd->vmd_inactive_target = (3 * vmd->vmd_free_target) / 2;
2274 	if (vmd->vmd_inactive_target > vmd->vmd_free_count / 3)
2275 		vmd->vmd_inactive_target = vmd->vmd_free_count / 3;
2276 
2277 	/*
2278 	 * Set the default wakeup threshold to be 10% below the paging
2279 	 * target.  This keeps the steady state out of shortfall.
2280 	 */
2281 	vmd->vmd_pageout_wakeup_thresh = (vmd->vmd_free_target / 10) * 9;
2282 
2283 	/*
2284 	 * Target amount of memory to move out of the laundry queue during a
2285 	 * background laundering.  This is proportional to the amount of system
2286 	 * memory.
2287 	 */
2288 	vmd->vmd_background_launder_target = (vmd->vmd_free_target -
2289 	    vmd->vmd_free_min) / 10;
2290 
2291 	/* Initialize the pageout daemon pid controller. */
2292 	pidctrl_init(&vmd->vmd_pid, hz / VM_INACT_SCAN_RATE,
2293 	    vmd->vmd_free_target, PIDCTRL_BOUND,
2294 	    PIDCTRL_KPD, PIDCTRL_KID, PIDCTRL_KDD);
2295 	oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(vmd->vmd_oid), OID_AUTO,
2296 	    "pidctrl", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2297 	pidctrl_init_sysctl(&vmd->vmd_pid, SYSCTL_CHILDREN(oid));
2298 
2299 	vmd->vmd_inactive_threads = get_pageout_threads_per_domain(vmd);
2300 }
2301 
2302 static void
2303 vm_pageout_init(void)
2304 {
2305 	u_long freecount;
2306 	int i;
2307 
2308 	/*
2309 	 * Initialize some paging parameters.
2310 	 */
2311 	if (vm_cnt.v_page_count < 2000)
2312 		vm_pageout_page_count = 8;
2313 
2314 	freecount = 0;
2315 	for (i = 0; i < vm_ndomains; i++) {
2316 		struct vm_domain *vmd;
2317 
2318 		vm_pageout_init_domain(i);
2319 		vmd = VM_DOMAIN(i);
2320 		vm_cnt.v_free_reserved += vmd->vmd_free_reserved;
2321 		vm_cnt.v_free_target += vmd->vmd_free_target;
2322 		vm_cnt.v_free_min += vmd->vmd_free_min;
2323 		vm_cnt.v_inactive_target += vmd->vmd_inactive_target;
2324 		vm_cnt.v_pageout_free_min += vmd->vmd_pageout_free_min;
2325 		vm_cnt.v_interrupt_free_min += vmd->vmd_interrupt_free_min;
2326 		vm_cnt.v_free_severe += vmd->vmd_free_severe;
2327 		freecount += vmd->vmd_free_count;
2328 	}
2329 
2330 	/*
2331 	 * Set interval in seconds for active scan.  We want to visit each
2332 	 * page at least once every ten minutes.  This is to prevent worst
2333 	 * case paging behaviors with stale active LRU.
2334 	 */
2335 	if (vm_pageout_update_period == 0)
2336 		vm_pageout_update_period = 600;
2337 
2338 	/*
2339 	 * Set the maximum number of user-wired virtual pages.  Historically the
2340 	 * main source of such pages was mlock(2) and mlockall(2).  Hypervisors
2341 	 * may also request user-wired memory.
2342 	 */
2343 	if (vm_page_max_user_wired == 0)
2344 		vm_page_max_user_wired = 4 * freecount / 5;
2345 }
2346 
2347 /*
2348  *     vm_pageout is the high level pageout daemon.
2349  */
2350 static void
2351 vm_pageout(void)
2352 {
2353 	struct proc *p;
2354 	struct thread *td;
2355 	int error, first, i, j, pageout_threads;
2356 
2357 	p = curproc;
2358 	td = curthread;
2359 
2360 	mtx_init(&vm_oom_ratelim_mtx, "vmoomr", NULL, MTX_DEF);
2361 	swap_pager_swap_init();
2362 	for (first = -1, i = 0; i < vm_ndomains; i++) {
2363 		if (VM_DOMAIN_EMPTY(i)) {
2364 			if (bootverbose)
2365 				printf("domain %d empty; skipping pageout\n",
2366 				    i);
2367 			continue;
2368 		}
2369 		if (first == -1)
2370 			first = i;
2371 		else {
2372 			error = kthread_add(vm_pageout_worker,
2373 			    (void *)(uintptr_t)i, p, NULL, 0, 0, "dom%d", i);
2374 			if (error != 0)
2375 				panic("starting pageout for domain %d: %d\n",
2376 				    i, error);
2377 		}
2378 		pageout_threads = VM_DOMAIN(i)->vmd_inactive_threads;
2379 		for (j = 0; j < pageout_threads - 1; j++) {
2380 			error = kthread_add(vm_pageout_helper,
2381 			    (void *)(uintptr_t)i, p, NULL, 0, 0,
2382 			    "dom%d helper%d", i, j);
2383 			if (error != 0)
2384 				panic("starting pageout helper %d for domain "
2385 				    "%d: %d\n", j, i, error);
2386 		}
2387 		error = kthread_add(vm_pageout_laundry_worker,
2388 		    (void *)(uintptr_t)i, p, NULL, 0, 0, "laundry: dom%d", i);
2389 		if (error != 0)
2390 			panic("starting laundry for domain %d: %d", i, error);
2391 	}
2392 	error = kthread_add(uma_reclaim_worker, NULL, p, NULL, 0, 0, "uma");
2393 	if (error != 0)
2394 		panic("starting uma_reclaim helper, error %d\n", error);
2395 
2396 	snprintf(td->td_name, sizeof(td->td_name), "dom%d", first);
2397 	vm_pageout_worker((void *)(uintptr_t)first);
2398 }
2399 
2400 /*
2401  * Perform an advisory wakeup of the page daemon.
2402  */
2403 void
2404 pagedaemon_wakeup(int domain)
2405 {
2406 	struct vm_domain *vmd;
2407 
2408 	vmd = VM_DOMAIN(domain);
2409 	vm_domain_pageout_assert_unlocked(vmd);
2410 	if (curproc == pageproc)
2411 		return;
2412 
2413 	if (atomic_fetchadd_int(&vmd->vmd_pageout_wanted, 1) == 0) {
2414 		vm_domain_pageout_lock(vmd);
2415 		atomic_store_int(&vmd->vmd_pageout_wanted, 1);
2416 		wakeup(&vmd->vmd_pageout_wanted);
2417 		vm_domain_pageout_unlock(vmd);
2418 	}
2419 }
2420