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