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