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