xref: /freebsd/sys/vm/vm_swapout.c (revision 26743408e9ff53ac0e041407c359ed3c17c15596)
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 #include "opt_kstack_pages.h"
72 #include "opt_kstack_max_pages.h"
73 #include "opt_vm.h"
74 
75 #include <sys/param.h>
76 #include <sys/systm.h>
77 #include <sys/limits.h>
78 #include <sys/kernel.h>
79 #include <sys/eventhandler.h>
80 #include <sys/lock.h>
81 #include <sys/mutex.h>
82 #include <sys/proc.h>
83 #include <sys/kthread.h>
84 #include <sys/ktr.h>
85 #include <sys/mount.h>
86 #include <sys/racct.h>
87 #include <sys/resourcevar.h>
88 #include <sys/refcount.h>
89 #include <sys/sched.h>
90 #include <sys/sdt.h>
91 #include <sys/signalvar.h>
92 #include <sys/smp.h>
93 #include <sys/time.h>
94 #include <sys/vnode.h>
95 #include <sys/vmmeter.h>
96 #include <sys/rwlock.h>
97 #include <sys/sx.h>
98 #include <sys/sysctl.h>
99 
100 #include <vm/vm.h>
101 #include <vm/vm_param.h>
102 #include <vm/vm_kern.h>
103 #include <vm/vm_object.h>
104 #include <vm/vm_page.h>
105 #include <vm/vm_map.h>
106 #include <vm/vm_pageout.h>
107 #include <vm/vm_pager.h>
108 #include <vm/vm_phys.h>
109 #include <vm/swap_pager.h>
110 #include <vm/vm_extern.h>
111 #include <vm/uma.h>
112 
113 /* the kernel process "vm_daemon" */
114 static void vm_daemon(void);
115 static struct proc *vmproc;
116 
117 static struct kproc_desc vm_kp = {
118 	"vmdaemon",
119 	vm_daemon,
120 	&vmproc
121 };
122 SYSINIT(vmdaemon, SI_SUB_KTHREAD_VM, SI_ORDER_FIRST, kproc_start, &vm_kp);
123 
124 static int vm_daemon_timeout = 0;
125 SYSCTL_INT(_vm, OID_AUTO, vmdaemon_timeout, CTLFLAG_RW,
126     &vm_daemon_timeout, 0,
127     "Time between vmdaemon runs");
128 
129 static int vm_daemon_needed;
130 static struct mtx vm_daemon_mtx;
131 /* Allow for use by vm_pageout before vm_daemon is initialized. */
132 MTX_SYSINIT(vm_daemon, &vm_daemon_mtx, "vm daemon", MTX_DEF);
133 
134 static void vm_swapout_map_deactivate_pages(vm_map_t, long);
135 static void vm_swapout_object_deactivate(pmap_t, vm_object_t, long);
136 
137 static void
138 vm_swapout_object_deactivate_page(pmap_t pmap, vm_page_t m, bool unmap)
139 {
140 
141 	/*
142 	 * Ignore unreclaimable wired pages.  Repeat the check after busying
143 	 * since a busy holder may wire the page.
144 	 */
145 	if (vm_page_wired(m) || !vm_page_tryxbusy(m))
146 		return;
147 
148 	if (vm_page_wired(m) || !pmap_page_exists_quick(pmap, m)) {
149 		vm_page_xunbusy(m);
150 		return;
151 	}
152 	if (!pmap_is_referenced(m)) {
153 		if (!vm_page_active(m))
154 			(void)vm_page_try_remove_all(m);
155 		else if (unmap && vm_page_try_remove_all(m))
156 			vm_page_deactivate(m);
157 	}
158 	vm_page_xunbusy(m);
159 }
160 
161 /*
162  *	vm_swapout_object_deactivate
163  *
164  *	Deactivate enough pages to satisfy the inactive target
165  *	requirements.
166  *
167  *	The object and map must be locked.
168  */
169 static void
170 vm_swapout_object_deactivate(pmap_t pmap, vm_object_t first_object,
171     long desired)
172 {
173 	vm_object_t backing_object, object;
174 	vm_page_t m;
175 	bool unmap;
176 
177 	VM_OBJECT_ASSERT_LOCKED(first_object);
178 	if ((first_object->flags & OBJ_FICTITIOUS) != 0)
179 		return;
180 	for (object = first_object;; object = backing_object) {
181 		if (pmap_resident_count(pmap) <= desired)
182 			goto unlock_return;
183 		VM_OBJECT_ASSERT_LOCKED(object);
184 		if ((object->flags & OBJ_UNMANAGED) != 0 ||
185 		    blockcount_read(&object->paging_in_progress) > 0)
186 			goto unlock_return;
187 
188 		unmap = true;
189 		if (object->shadow_count > 1)
190 			unmap = false;
191 
192 		/*
193 		 * Scan the object's entire memory queue.
194 		 */
195 		TAILQ_FOREACH(m, &object->memq, listq) {
196 			if (pmap_resident_count(pmap) <= desired)
197 				goto unlock_return;
198 			if (should_yield())
199 				goto unlock_return;
200 			vm_swapout_object_deactivate_page(pmap, m, unmap);
201 		}
202 		if ((backing_object = object->backing_object) == NULL)
203 			goto unlock_return;
204 		VM_OBJECT_RLOCK(backing_object);
205 		if (object != first_object)
206 			VM_OBJECT_RUNLOCK(object);
207 	}
208 unlock_return:
209 	if (object != first_object)
210 		VM_OBJECT_RUNLOCK(object);
211 }
212 
213 /*
214  * deactivate some number of pages in a map, try to do it fairly, but
215  * that is really hard to do.
216  */
217 static void
218 vm_swapout_map_deactivate_pages(vm_map_t map, long desired)
219 {
220 	vm_map_entry_t tmpe;
221 	vm_object_t obj, bigobj;
222 	int nothingwired;
223 
224 	if (!vm_map_trylock_read(map))
225 		return;
226 
227 	bigobj = NULL;
228 	nothingwired = TRUE;
229 
230 	/*
231 	 * first, search out the biggest object, and try to free pages from
232 	 * that.
233 	 */
234 	VM_MAP_ENTRY_FOREACH(tmpe, map) {
235 		if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
236 			obj = tmpe->object.vm_object;
237 			if (obj != NULL && VM_OBJECT_TRYRLOCK(obj)) {
238 				if (obj->shadow_count <= 1 &&
239 				    (bigobj == NULL ||
240 				     bigobj->resident_page_count <
241 				     obj->resident_page_count)) {
242 					if (bigobj != NULL)
243 						VM_OBJECT_RUNLOCK(bigobj);
244 					bigobj = obj;
245 				} else
246 					VM_OBJECT_RUNLOCK(obj);
247 			}
248 		}
249 		if (tmpe->wired_count > 0)
250 			nothingwired = FALSE;
251 	}
252 
253 	if (bigobj != NULL) {
254 		vm_swapout_object_deactivate(map->pmap, bigobj, desired);
255 		VM_OBJECT_RUNLOCK(bigobj);
256 	}
257 	/*
258 	 * Next, hunt around for other pages to deactivate.  We actually
259 	 * do this search sort of wrong -- .text first is not the best idea.
260 	 */
261 	VM_MAP_ENTRY_FOREACH(tmpe, map) {
262 		if (pmap_resident_count(vm_map_pmap(map)) <= desired)
263 			break;
264 		if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
265 			obj = tmpe->object.vm_object;
266 			if (obj != NULL) {
267 				VM_OBJECT_RLOCK(obj);
268 				vm_swapout_object_deactivate(map->pmap, obj,
269 				    desired);
270 				VM_OBJECT_RUNLOCK(obj);
271 			}
272 		}
273 	}
274 
275 	/*
276 	 * Remove all mappings if a process is swapped out, this will free page
277 	 * table pages.
278 	 */
279 	if (desired == 0 && nothingwired) {
280 		pmap_remove(vm_map_pmap(map), vm_map_min(map),
281 		    vm_map_max(map));
282 	}
283 
284 	vm_map_unlock_read(map);
285 }
286 
287 static void
288 vm_daemon(void)
289 {
290 	struct rlimit rsslim;
291 	struct proc *p;
292 	struct thread *td;
293 	struct vmspace *vm;
294 	int breakout, tryagain, attempts;
295 	uint64_t rsize, ravailable;
296 
297 	if (racct_enable && vm_daemon_timeout == 0)
298 		vm_daemon_timeout = hz;
299 
300 	while (TRUE) {
301 		mtx_lock(&vm_daemon_mtx);
302 		msleep(&vm_daemon_needed, &vm_daemon_mtx, PPAUSE, "psleep",
303 		    vm_daemon_timeout);
304 		mtx_unlock(&vm_daemon_mtx);
305 
306 		/*
307 		 * scan the processes for exceeding their rlimits or if
308 		 * process is swapped out -- deactivate pages
309 		 */
310 		tryagain = 0;
311 		attempts = 0;
312 again:
313 		attempts++;
314 		sx_slock(&allproc_lock);
315 		FOREACH_PROC_IN_SYSTEM(p) {
316 			vm_pindex_t limit, size;
317 
318 			/*
319 			 * if this is a system process or if we have already
320 			 * looked at this process, skip it.
321 			 */
322 			PROC_LOCK(p);
323 			if (p->p_state != PRS_NORMAL ||
324 			    p->p_flag & (P_INEXEC | P_SYSTEM | P_WEXIT)) {
325 				PROC_UNLOCK(p);
326 				continue;
327 			}
328 			/*
329 			 * if the process is in a non-running type state,
330 			 * don't touch it.
331 			 */
332 			breakout = 0;
333 			FOREACH_THREAD_IN_PROC(p, td) {
334 				thread_lock(td);
335 				if (!TD_ON_RUNQ(td) &&
336 				    !TD_IS_RUNNING(td) &&
337 				    !TD_IS_SLEEPING(td) &&
338 				    !TD_IS_SUSPENDED(td)) {
339 					thread_unlock(td);
340 					breakout = 1;
341 					break;
342 				}
343 				thread_unlock(td);
344 			}
345 			if (breakout) {
346 				PROC_UNLOCK(p);
347 				continue;
348 			}
349 			/*
350 			 * get a limit
351 			 */
352 			lim_rlimit_proc(p, RLIMIT_RSS, &rsslim);
353 			limit = OFF_TO_IDX(
354 			    qmin(rsslim.rlim_cur, rsslim.rlim_max));
355 
356 			vm = vmspace_acquire_ref(p);
357 			_PHOLD(p);
358 			PROC_UNLOCK(p);
359 			if (vm == NULL) {
360 				PRELE(p);
361 				continue;
362 			}
363 			sx_sunlock(&allproc_lock);
364 
365 			size = vmspace_resident_count(vm);
366 			if (size >= limit) {
367 				vm_swapout_map_deactivate_pages(
368 				    &vm->vm_map, limit);
369 				size = vmspace_resident_count(vm);
370 			}
371 			if (racct_enable) {
372 				rsize = IDX_TO_OFF(size);
373 				PROC_LOCK(p);
374 				if (p->p_state == PRS_NORMAL)
375 					racct_set(p, RACCT_RSS, rsize);
376 				ravailable = racct_get_available(p, RACCT_RSS);
377 				PROC_UNLOCK(p);
378 				if (rsize > ravailable) {
379 					/*
380 					 * Don't be overly aggressive; this
381 					 * might be an innocent process,
382 					 * and the limit could've been exceeded
383 					 * by some memory hog.  Don't try
384 					 * to deactivate more than 1/4th
385 					 * of process' resident set size.
386 					 */
387 					if (attempts <= 8) {
388 						if (ravailable < rsize -
389 						    (rsize / 4)) {
390 							ravailable = rsize -
391 							    (rsize / 4);
392 						}
393 					}
394 					vm_swapout_map_deactivate_pages(
395 					    &vm->vm_map,
396 					    OFF_TO_IDX(ravailable));
397 					/* Update RSS usage after paging out. */
398 					size = vmspace_resident_count(vm);
399 					rsize = IDX_TO_OFF(size);
400 					PROC_LOCK(p);
401 					if (p->p_state == PRS_NORMAL)
402 						racct_set(p, RACCT_RSS, rsize);
403 					PROC_UNLOCK(p);
404 					if (rsize > ravailable)
405 						tryagain = 1;
406 				}
407 			}
408 			vmspace_free(vm);
409 			sx_slock(&allproc_lock);
410 			PRELE(p);
411 		}
412 		sx_sunlock(&allproc_lock);
413 		if (tryagain != 0 && attempts <= 10) {
414 			maybe_yield();
415 			goto again;
416 		}
417 	}
418 }
419