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