· 6 years ago · Jul 21, 2019, 02:24 AM
1/*
2 * linux/mm/vmscan.c
3 *
4 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
5 *
6 * Swap reorganised 29.12.95, Stephen Tweedie.
7 * kswapd added: 7.1.96 sct
8 * Removed kswapd_ctl limits, and swap out as many pages as needed
9 * to bring the system back to freepages.high: 2.4.97, Rik van Riel.
10 * Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
11 * Multiqueue VM started 5.8.00, Rik van Riel.
12 */
13
14#include <linux/mm.h>
15#include <linux/module.h>
16#include <linux/gfp.h>
17#include <linux/kernel_stat.h>
18#include <linux/swap.h>
19#include <linux/pagemap.h>
20#include <linux/init.h>
21#include <linux/highmem.h>
22#include <linux/vmpressure.h>
23#include <linux/vmstat.h>
24#include <linux/file.h>
25#include <linux/writeback.h>
26#include <linux/blkdev.h>
27#include <linux/buffer_head.h> /* for try_to_release_page(),
28 buffer_heads_over_limit */
29#include <linux/mm_inline.h>
30#include <linux/backing-dev.h>
31#include <linux/rmap.h>
32#include <linux/topology.h>
33#include <linux/cpu.h>
34#include <linux/cpuset.h>
35#include <linux/compaction.h>
36#include <linux/notifier.h>
37#include <linux/rwsem.h>
38#include <linux/delay.h>
39#include <linux/kthread.h>
40#include <linux/freezer.h>
41#include <linux/memcontrol.h>
42#include <linux/delayacct.h>
43#include <linux/sysctl.h>
44#include <linux/oom.h>
45#include <linux/prefetch.h>
46#include <linux/dax.h>
47
48#include <asm/tlbflush.h>
49#include <asm/div64.h>
50
51#include <linux/swapops.h>
52#include <linux/balloon_compaction.h>
53
54#include "internal.h"
55
56#define CREATE_TRACE_POINTS
57#include <trace/events/vmscan.h>
58
59//ADDED DURING ASSGINMENT 4
60
61#include <linux/a_4_globals.h>
62
63unsigned long statistic5 = 0;
64unsigned long statistic6 = 0;
65unsigned long active_to_inactive = 0;
66unsigned long evicted_from_inactive = 0;
67
68struct scan_control {
69 /* Incremented by the number of inactive pages that were scanned */
70 unsigned long nr_scanned;
71
72 /* Number of pages freed so far during a call to shrink_zones() */
73 unsigned long nr_reclaimed;
74
75 /* How many pages shrink_list() should reclaim */
76 unsigned long nr_to_reclaim;
77
78 unsigned long hibernation_mode;
79
80 /* This context's GFP mask */
81 gfp_t gfp_mask;
82
83 int may_writepage;
84
85 /* Can mapped pages be reclaimed? */
86 int may_unmap;
87
88 /* Can pages be swapped as part of reclaim? */
89 int may_swap;
90
91 int order;
92
93 /* Scan (total_size >> priority) pages at once */
94 int priority;
95
96 /*
97 * The memory cgroup that hit its limit and as a result is the
98 * primary target of this reclaim invocation.
99 */
100 struct mem_cgroup *target_mem_cgroup;
101
102 /*
103 * Nodemask of nodes allowed by the caller. If NULL, all nodes
104 * are scanned.
105 */
106 nodemask_t *nodemask;
107};
108
109#define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru))
110
111#ifdef ARCH_HAS_PREFETCH
112#define prefetch_prev_lru_page(_page, _base, _field) \
113 do { \
114 if ((_page)->lru.prev != _base) { \
115 struct page *prev; \
116 \
117 prev = lru_to_page(&(_page->lru)); \
118 prefetch(&prev->_field); \
119 } \
120 } while (0)
121#else
122#define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
123#endif
124
125#ifdef ARCH_HAS_PREFETCHW
126#define prefetchw_prev_lru_page(_page, _base, _field) \
127 do { \
128 if ((_page)->lru.prev != _base) { \
129 struct page *prev; \
130 \
131 prev = lru_to_page(&(_page->lru)); \
132 prefetchw(&prev->_field); \
133 } \
134 } while (0)
135#else
136#define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
137#endif
138
139/*
140 * From 0 .. 100. Higher means more swappy.
141 */
142int vm_swappiness = 60;
143unsigned long vm_total_pages; /* The total number of pages which the VM controls */
144
145static LIST_HEAD(shrinker_list);
146static DECLARE_RWSEM(shrinker_rwsem);
147
148#ifdef CONFIG_MEMCG
149static bool global_reclaim(struct scan_control *sc)
150{
151 return !sc->target_mem_cgroup;
152}
153
154/**
155 * sane_reclaim - is the usual dirty throttling mechanism operational?
156 * @sc: scan_control in question
157 *
158 * The normal page dirty throttling mechanism in balance_dirty_pages() is
159 * completely broken with the legacy memcg and direct stalling in
160 * shrink_page_list() is used for throttling instead, which lacks all the
161 * niceties such as fairness, adaptive pausing, bandwidth proportional
162 * allocation and configurability.
163 *
164 * This function tests whether the vmscan currently in progress can assume
165 * that the normal dirty throttling mechanism is operational.
166 */
167static bool sane_reclaim(struct scan_control *sc)
168{
169 struct mem_cgroup *memcg = sc->target_mem_cgroup;
170
171 if (!memcg)
172 return true;
173#ifdef CONFIG_CGROUP_WRITEBACK
174 if (cgroup_on_dfl(mem_cgroup_css(memcg)->cgroup))
175 return true;
176#endif
177 return false;
178}
179#else
180static bool global_reclaim(struct scan_control *sc)
181{
182 return true;
183}
184
185static bool sane_reclaim(struct scan_control *sc)
186{
187 return true;
188}
189#endif
190
191static unsigned long zone_reclaimable_pages(struct zone *zone)
192{
193 int nr;
194
195 nr = zone_page_state(zone, NR_ACTIVE_FILE) +
196 zone_page_state(zone, NR_INACTIVE_FILE);
197
198 if (get_nr_swap_pages() > 0)
199 nr += zone_page_state(zone, NR_ACTIVE_ANON) +
200 zone_page_state(zone, NR_INACTIVE_ANON);
201
202 return nr;
203}
204
205static bool zone_reclaimable(struct zone *zone)
206{
207 return zone->pages_scanned < zone_reclaimable_pages(zone) * 6;
208}
209
210static unsigned long get_lru_size(struct lruvec *lruvec, enum lru_list lru)
211{
212 if (!mem_cgroup_disabled())
213 return mem_cgroup_get_lru_size(lruvec, lru);
214
215 return zone_page_state(lruvec_zone(lruvec), NR_LRU_BASE + lru);
216}
217
218/*
219 * Add a shrinker callback to be called from the vm
220 */
221void register_shrinker(struct shrinker *shrinker)
222{
223 atomic_long_set(&shrinker->nr_in_batch, 0);
224 down_write(&shrinker_rwsem);
225 list_add_tail(&shrinker->list, &shrinker_list);
226 up_write(&shrinker_rwsem);
227}
228EXPORT_SYMBOL(register_shrinker);
229
230/*
231 * Remove one
232 */
233void unregister_shrinker(struct shrinker *shrinker)
234{
235 down_write(&shrinker_rwsem);
236 list_del(&shrinker->list);
237 up_write(&shrinker_rwsem);
238}
239EXPORT_SYMBOL(unregister_shrinker);
240
241//ADDED DURING ASSIGNMENT 4
242/*
243static inline unsigned long get_active_to_inactive( int x )
244{
245 return active_to_inactive;
246}
247
248static inline unsigned long get_evicted_from_inactive( int x )
249{
250 return evicted_from_inactive;
251}
252*/
253
254static inline int do_shrinker_shrink(struct shrinker *shrinker,
255 struct shrink_control *sc,
256 unsigned long nr_to_scan)
257{
258 int objects;
259 sc->nr_to_scan = nr_to_scan;
260 objects = (*shrinker->shrink)(shrinker, sc);
261 /*
262 * A shrinker can legitimately return -1 meaning that it cannot do
263 * much work without a risk of deadlock.
264 * However, in some extreme cases, specially when there is abusive
265 * usage of vm.vfs_cache_pressure, a shrinker might return a negative
266 * value indicating that its integer return value has overflown.
267 * In such cases, we just go ahead and cap the return val to INT_MAX.
268 */
269 if (objects < -1)
270 return INT_MAX;
271
272 return objects;
273}
274
275#define SHRINK_BATCH 128
276/*
277 * Call the shrink functions to age shrinkable caches
278 *
279 * Here we assume it costs one seek to replace a lru page and that it also
280 * takes a seek to recreate a cache object. With this in mind we age equal
281 * percentages of the lru and ageable caches. This should balance the seeks
282 * generated by these structures.
283 *
284 * If the vm encountered mapped pages on the LRU it increase the pressure on
285 * slab to avoid swapping.
286 *
287 * We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits.
288 *
289 * `lru_pages' represents the number of on-LRU pages in all the zones which
290 * are eligible for the caller's allocation attempt. It is used for balancing
291 * slab reclaim versus page reclaim.
292 *
293 * Returns the number of slab objects which we shrunk.
294 */
295unsigned long shrink_slab(struct shrink_control *shrink,
296 unsigned long nr_pages_scanned,
297 unsigned long lru_pages)
298{
299 struct shrinker *shrinker;
300 unsigned long ret = 0;
301
302 if (nr_pages_scanned == 0)
303 nr_pages_scanned = SWAP_CLUSTER_MAX;
304
305 if (!down_read_trylock(&shrinker_rwsem)) {
306 /* Assume we'll be able to shrink next time */
307 ret = 1;
308 goto out;
309 }
310
311 list_for_each_entry(shrinker, &shrinker_list, list) {
312 unsigned long long delta;
313 long total_scan;
314 long max_pass;
315 int shrink_ret = 0;
316 long nr;
317 long new_nr;
318 long batch_size = shrinker->batch ? shrinker->batch
319 : SHRINK_BATCH;
320
321 max_pass = do_shrinker_shrink(shrinker, shrink, 0);
322 if (max_pass <= 0)
323 continue;
324
325 /*
326 * copy the current shrinker scan count into a local variable
327 * and zero it so that other concurrent shrinker invocations
328 * don't also do this scanning work.
329 */
330 nr = atomic_long_xchg(&shrinker->nr_in_batch, 0);
331
332 total_scan = nr;
333 delta = (4 * nr_pages_scanned) / shrinker->seeks;
334 delta *= max_pass;
335 do_div(delta, lru_pages + 1);
336 total_scan += delta;
337 if (total_scan < 0) {
338 printk(KERN_ERR "shrink_slab: %pF negative objects to "
339 "delete nr=%ld\n",
340 shrinker->shrink, total_scan);
341 total_scan = max_pass;
342 }
343
344 /*
345 * We need to avoid excessive windup on filesystem shrinkers
346 * due to large numbers of GFP_NOFS allocations causing the
347 * shrinkers to return -1 all the time. This results in a large
348 * nr being built up so when a shrink that can do some work
349 * comes along it empties the entire cache due to nr >>>
350 * max_pass. This is bad for sustaining a working set in
351 * memory.
352 *
353 * Hence only allow the shrinker to scan the entire cache when
354 * a large delta change is calculated directly.
355 */
356 if (delta < max_pass / 4)
357 total_scan = min(total_scan, max_pass / 2);
358
359 /*
360 * Avoid risking looping forever due to too large nr value:
361 * never try to free more than twice the estimate number of
362 * freeable entries.
363 */
364 if (total_scan > max_pass * 2)
365 total_scan = max_pass * 2;
366
367 trace_mm_shrink_slab_start(shrinker, shrink, nr,
368 nr_pages_scanned, lru_pages,
369 max_pass, delta, total_scan);
370
371 while (total_scan >= batch_size) {
372 int nr_before;
373
374 nr_before = do_shrinker_shrink(shrinker, shrink, 0);
375 shrink_ret = do_shrinker_shrink(shrinker, shrink,
376 batch_size);
377 if (shrink_ret == -1)
378 break;
379 if (shrink_ret < nr_before)
380 ret += nr_before - shrink_ret;
381 count_vm_events(SLABS_SCANNED, batch_size);
382 total_scan -= batch_size;
383
384 cond_resched();
385 }
386
387 /*
388 * move the unused scan count back into the shrinker in a
389 * manner that handles concurrent updates. If we exhausted the
390 * scan, there is no need to do an update.
391 */
392 if (total_scan > 0)
393 new_nr = atomic_long_add_return(total_scan,
394 &shrinker->nr_in_batch);
395 else
396 new_nr = atomic_long_read(&shrinker->nr_in_batch);
397
398 trace_mm_shrink_slab_end(shrinker, shrink_ret, nr, new_nr);
399 }
400 up_read(&shrinker_rwsem);
401out:
402 cond_resched();
403 return ret;
404}
405
406static inline int is_page_cache_freeable(struct page *page)
407{
408 /*
409 * A freeable page cache page is referenced only by the caller
410 * that isolated the page, the page cache radix tree and
411 * optional buffer heads at page->private.
412 */
413 return page_count(page) - page_has_private(page) == 2;
414}
415
416static int may_write_to_queue(struct backing_dev_info *bdi,
417 struct scan_control *sc)
418{
419 if (current->flags & PF_SWAPWRITE)
420 return 1;
421 if (!bdi_write_congested(bdi))
422 return 1;
423 if (bdi == current->backing_dev_info)
424 return 1;
425 return 0;
426}
427
428/*
429 * We detected a synchronous write error writing a page out. Probably
430 * -ENOSPC. We need to propagate that into the address_space for a subsequent
431 * fsync(), msync() or close().
432 *
433 * The tricky part is that after writepage we cannot touch the mapping: nothing
434 * prevents it from being freed up. But we have a ref on the page and once
435 * that page is locked, the mapping is pinned.
436 *
437 * We're allowed to run sleeping lock_page() here because we know the caller has
438 * __GFP_FS.
439 */
440static void handle_write_error(struct address_space *mapping,
441 struct page *page, int error)
442{
443 lock_page(page);
444 if (page_mapping(page) == mapping)
445 mapping_set_error(mapping, error);
446 unlock_page(page);
447}
448
449/* possible outcome of pageout() */
450typedef enum {
451 /* failed to write page out, page is locked */
452 PAGE_KEEP,
453 /* move page to the active list, page is locked */
454 PAGE_ACTIVATE,
455 /* page has been sent to the disk successfully, page is unlocked */
456 PAGE_SUCCESS,
457 /* page is clean and locked */
458 PAGE_CLEAN,
459} pageout_t;
460
461/*
462 * pageout is called by shrink_page_list() for each dirty page.
463 * Calls ->writepage().
464 */
465static pageout_t pageout(struct page *page, struct address_space *mapping,
466 struct scan_control *sc)
467{
468 /*
469 * If the page is dirty, only perform writeback if that write
470 * will be non-blocking. To prevent this allocation from being
471 * stalled by pagecache activity. But note that there may be
472 * stalls if we need to run get_block(). We could test
473 * PagePrivate for that.
474 *
475 * If this process is currently in __generic_file_aio_write() against
476 * this page's queue, we can perform writeback even if that
477 * will block.
478 *
479 * If the page is swapcache, write it back even if that would
480 * block, for some throttling. This happens by accident, because
481 * swap_backing_dev_info is bust: it doesn't reflect the
482 * congestion state of the swapdevs. Easy to fix, if needed.
483 */
484 if (!is_page_cache_freeable(page))
485 return PAGE_KEEP;
486 if (!mapping) {
487 /*
488 * Some data journaling orphaned pages can have
489 * page->mapping == NULL while being dirty with clean buffers.
490 */
491 if (page_has_private(page)) {
492 if (try_to_free_buffers(page)) {
493 ClearPageDirty(page);
494 printk("%s: orphaned page\n", __func__);
495 return PAGE_CLEAN;
496 }
497 }
498 return PAGE_KEEP;
499 }
500 if (mapping->a_ops->writepage == NULL)
501 return PAGE_ACTIVATE;
502 if (!may_write_to_queue(mapping->backing_dev_info, sc))
503 return PAGE_KEEP;
504
505 if (clear_page_dirty_for_io(page)) {
506 int res;
507 struct writeback_control wbc = {
508 .sync_mode = WB_SYNC_NONE,
509 .nr_to_write = SWAP_CLUSTER_MAX,
510 .range_start = 0,
511 .range_end = LLONG_MAX,
512 .for_reclaim = 1,
513 };
514
515 SetPageReclaim(page);
516 res = mapping->a_ops->writepage(page, &wbc);
517 if (res < 0)
518 handle_write_error(mapping, page, res);
519 if (res == AOP_WRITEPAGE_ACTIVATE) {
520 ClearPageReclaim(page);
521 return PAGE_ACTIVATE;
522 }
523
524 if (!PageWriteback(page)) {
525 /* synchronous write or broken a_ops? */
526 ClearPageReclaim(page);
527 }
528 trace_mm_vmscan_writepage(page, trace_reclaim_flags(page));
529 inc_zone_page_state(page, NR_VMSCAN_WRITE);
530 return PAGE_SUCCESS;
531 }
532
533 return PAGE_CLEAN;
534}
535
536/*
537 * Same as remove_mapping, but if the page is removed from the mapping, it
538 * gets returned with a refcount of 0.
539 */
540static int __remove_mapping(struct address_space *mapping, struct page *page,
541 bool reclaimed)
542{
543 BUG_ON(!PageLocked(page));
544 BUG_ON(mapping != page_mapping(page));
545
546 spin_lock_irq(&mapping->tree_lock);
547 /*
548 * The non racy check for a busy page.
549 *
550 * Must be careful with the order of the tests. When someone has
551 * a ref to the page, it may be possible that they dirty it then
552 * drop the reference. So if PageDirty is tested before page_count
553 * here, then the following race may occur:
554 *
555 * get_user_pages(&page);
556 * [user mapping goes away]
557 * write_to(page);
558 * !PageDirty(page) [good]
559 * SetPageDirty(page);
560 * put_page(page);
561 * !page_count(page) [good, discard it]
562 *
563 * [oops, our write_to data is lost]
564 *
565 * Reversing the order of the tests ensures such a situation cannot
566 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
567 * load is not satisfied before that of page->_count.
568 *
569 * Note that if SetPageDirty is always performed via set_page_dirty,
570 * and thus under tree_lock, then this ordering is not required.
571 */
572 if (!page_ref_freeze(page, 2))
573 goto cannot_free;
574 /* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */
575 if (unlikely(PageDirty(page))) {
576 page_ref_unfreeze(page, 2);
577 goto cannot_free;
578 }
579
580 if (PageSwapCache(page)) {
581 swp_entry_t swap = { .val = page_private(page) };
582 __delete_from_swap_cache(page);
583 spin_unlock_irq(&mapping->tree_lock);
584 swapcache_free(swap, page);
585 } else {
586 void (*freepage)(struct page *);
587 void *shadow = NULL;
588
589 freepage = mapping->a_ops->freepage;
590 /*
591 * Remember a shadow entry for reclaimed file cache in
592 * order to detect refaults, thus thrashing, later on.
593 *
594 * But don't store shadows in an address space that is
595 * already exiting. This is not just an optizimation,
596 * inode reclaim needs to empty out the radix tree or
597 * the nodes are lost. Don't plant shadows behind its
598 * back.
599 *
600 * We also don't store shadows for DAX mappings because the
601 * only page cache pages found in these are zero pages
602 * covering holes, and because we don't want to mix DAX
603 * exceptional entries and shadow exceptional entries in the
604 * same page_tree.
605 */
606 if (reclaimed && page_is_file_cache(page) &&
607 !mapping_exiting(mapping) && !dax_mapping(mapping))
608 shadow = workingset_eviction(mapping, page);
609 __delete_from_page_cache(page, shadow);
610 spin_unlock_irq(&mapping->tree_lock);
611 mem_cgroup_uncharge_cache_page(page);
612
613 if (freepage != NULL)
614 freepage(page);
615 }
616
617 return 1;
618
619cannot_free:
620 spin_unlock_irq(&mapping->tree_lock);
621 return 0;
622}
623
624/*
625 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
626 * someone else has a ref on the page, abort and return 0. If it was
627 * successfully detached, return 1. Assumes the caller has a single ref on
628 * this page.
629 */
630int remove_mapping(struct address_space *mapping, struct page *page)
631{
632 if (__remove_mapping(mapping, page, false)) {
633 /*
634 * Unfreezing the refcount with 1 rather than 2 effectively
635 * drops the pagecache ref for us without requiring another
636 * atomic operation.
637 */
638 page_ref_unfreeze(page, 1);
639 return 1;
640 }
641 return 0;
642}
643
644/**
645 * putback_lru_page - put previously isolated page onto appropriate LRU list
646 * @page: page to be put back to appropriate lru list
647 *
648 * Add previously isolated @page to appropriate LRU list.
649 * Page may still be unevictable for other reasons.
650 *
651 * lru_lock must not be held, interrupts must be enabled.
652 */
653void putback_lru_page(struct page *page)
654{
655 int lru;
656 int was_unevictable = PageUnevictable(page);
657
658 VM_BUG_ON_PAGE(PageLRU(page), page);
659
660redo:
661 ClearPageUnevictable(page);
662
663 if (page_evictable(page)) {
664 /*
665 * For evictable pages, we can use the cache.
666 * In event of a race, worst case is we end up with an
667 * unevictable page on [in]active list.
668 * We know how to handle that.
669 */
670 lru = page_lru_base_type(page);
671 lru_cache_add(page);
672 } else {
673 /*
674 * Put unevictable pages directly on zone's unevictable
675 * list.
676 */
677 lru = LRU_UNEVICTABLE;
678 add_page_to_unevictable_list(page);
679 /*
680 * When racing with an mlock or AS_UNEVICTABLE clearing
681 * (page is unlocked) make sure that if the other thread
682 * does not observe our setting of PG_lru and fails
683 * isolation/check_move_unevictable_pages,
684 * we see PG_mlocked/AS_UNEVICTABLE cleared below and move
685 * the page back to the evictable list.
686 *
687 * The other side is TestClearPageMlocked() or shmem_lock().
688 */
689 smp_mb();
690 }
691
692 /*
693 * page's status can change while we move it among lru. If an evictable
694 * page is on unevictable list, it never be freed. To avoid that,
695 * check after we added it to the list, again.
696 */
697 if (lru == LRU_UNEVICTABLE && page_evictable(page)) {
698 if (!isolate_lru_page(page)) {
699 put_page(page);
700 goto redo;
701 }
702 /* This means someone else dropped this page from LRU
703 * So, it will be freed or putback to LRU again. There is
704 * nothing to do here.
705 */
706 }
707
708 if (was_unevictable && lru != LRU_UNEVICTABLE)
709 count_vm_event(UNEVICTABLE_PGRESCUED);
710 else if (!was_unevictable && lru == LRU_UNEVICTABLE)
711 count_vm_event(UNEVICTABLE_PGCULLED);
712
713 put_page(page); /* drop ref from isolate */
714}
715
716enum page_references {
717 PAGEREF_RECLAIM,
718 PAGEREF_RECLAIM_CLEAN,
719 PAGEREF_KEEP,
720 PAGEREF_ACTIVATE,
721};
722
723static enum page_references page_check_references(struct page *page,
724 struct scan_control *sc)
725{
726 int referenced_ptes, referenced_page;
727 unsigned long vm_flags;
728
729 referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
730 &vm_flags);
731 referenced_page = TestClearPageReferenced(page);
732
733 /*
734 * Mlock lost the isolation race with us. Let try_to_unmap()
735 * move the page to the unevictable list.
736 */
737 if (vm_flags & VM_LOCKED)
738 return PAGEREF_RECLAIM;
739
740 if (referenced_ptes) {
741 if (PageSwapBacked(page))
742 return PAGEREF_ACTIVATE;
743 /*
744 * All mapped pages start out with page table
745 * references from the instantiating fault, so we need
746 * to look twice if a mapped file page is used more
747 * than once.
748 *
749 * Mark it and spare it for another trip around the
750 * inactive list. Another page table reference will
751 * lead to its activation.
752 *
753 * Note: the mark is set for activated pages as well
754 * so that recently deactivated but used pages are
755 * quickly recovered.
756 */
757 SetPageReferenced(page);
758
759 if (referenced_page || referenced_ptes > 1)
760 return PAGEREF_ACTIVATE;
761
762 /*
763 * Activate file-backed executable pages after first usage.
764 */
765 if (vm_flags & VM_EXEC)
766 return PAGEREF_ACTIVATE;
767
768 return PAGEREF_KEEP;
769 }
770
771 /* Reclaim if clean, defer dirty pages to writeback */
772 if (referenced_page && !PageSwapBacked(page))
773 return PAGEREF_RECLAIM_CLEAN;
774
775 return PAGEREF_RECLAIM;
776}
777
778/* Check if a page is dirty or under writeback */
779static void page_check_dirty_writeback(struct page *page,
780 bool *dirty, bool *writeback)
781{
782 struct address_space *mapping;
783
784 /*
785 * Anonymous pages are not handled by flushers and must be written
786 * from reclaim context. Do not stall reclaim based on them
787 */
788 if (!page_is_file_cache(page)) {
789 *dirty = false;
790 *writeback = false;
791 return;
792 }
793
794 /* By default assume that the page flags are accurate */
795 *dirty = PageDirty(page);
796 *writeback = PageWriteback(page);
797
798 /* Verify dirty/writeback state if the filesystem supports it */
799 if (!page_has_private(page))
800 return;
801
802 mapping = page_mapping(page);
803 if (mapping && mapping->a_ops->is_dirty_writeback)
804 mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
805}
806
807/*
808 * shrink_page_list() returns the number of reclaimed pages
809 */
810static unsigned long shrink_page_list(struct list_head *page_list,
811 struct zone *zone,
812 struct scan_control *sc,
813 enum ttu_flags ttu_flags,
814 unsigned long *ret_nr_dirty,
815 unsigned long *ret_nr_unqueued_dirty,
816 unsigned long *ret_nr_congested,
817 unsigned long *ret_nr_writeback,
818 unsigned long *ret_nr_immediate,
819 bool force_reclaim)
820{
821 LIST_HEAD(ret_pages);
822 LIST_HEAD(free_pages);
823 int pgactivate = 0;
824 unsigned long nr_unqueued_dirty = 0;
825 unsigned long nr_dirty = 0;
826 unsigned long nr_congested = 0;
827 unsigned long nr_reclaimed = 0;
828 unsigned long nr_writeback = 0;
829 unsigned long nr_immediate = 0;
830
831 cond_resched();
832
833 mem_cgroup_uncharge_start();
834 while (!list_empty(page_list)) {
835 struct address_space *mapping;
836 struct page *page;
837 int may_enter_fs;
838 enum page_references references = PAGEREF_RECLAIM_CLEAN;
839 bool dirty, writeback;
840 bool lazyfree = false;
841 int ret = SWAP_SUCCESS;
842
843 cond_resched();
844
845 page = lru_to_page(page_list);
846 list_del(&page->lru);
847
848 if (!trylock_page(page))
849 goto keep;
850
851 VM_BUG_ON_PAGE(PageActive(page), page);
852 VM_BUG_ON_PAGE(page_zone(page) != zone, page);
853
854 sc->nr_scanned++;
855
856 if (unlikely(!page_evictable(page)))
857 goto cull_mlocked;
858
859 if (!sc->may_unmap && page_mapped(page))
860 goto keep_locked;
861
862 /* Double the slab pressure for mapped and swapcache pages */
863 if (page_mapped(page) || PageSwapCache(page))
864 sc->nr_scanned++;
865
866 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
867 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
868
869 /*
870 * The number of dirty pages determines if a zone is marked
871 * reclaim_congested which affects wait_iff_congested. kswapd
872 * will stall and start writing pages if the tail of the LRU
873 * is all dirty unqueued pages.
874 */
875 page_check_dirty_writeback(page, &dirty, &writeback);
876 if (dirty || writeback)
877 nr_dirty++;
878
879 if (dirty && !writeback)
880 nr_unqueued_dirty++;
881
882 /*
883 * Treat this page as congested if the underlying BDI is or if
884 * pages are cycling through the LRU so quickly that the
885 * pages marked for immediate reclaim are making it to the
886 * end of the LRU a second time.
887 */
888 mapping = page_mapping(page);
889 if ((mapping && bdi_write_congested(mapping->backing_dev_info)) ||
890 (writeback && PageReclaim(page)))
891 nr_congested++;
892
893 /*
894 * If a page at the tail of the LRU is under writeback, there
895 * are three cases to consider.
896 *
897 * 1) If reclaim is encountering an excessive number of pages
898 * under writeback and this page is both under writeback and
899 * PageReclaim then it indicates that pages are being queued
900 * for IO but are being recycled through the LRU before the
901 * IO can complete. Waiting on the page itself risks an
902 * indefinite stall if it is impossible to writeback the
903 * page due to IO error or disconnected storage so instead
904 * note that the LRU is being scanned too quickly and the
905 * caller can stall after page list has been processed.
906 *
907 * 2) Global or new memcg reclaim encounters a page that is
908 * not marked for immediate reclaim, or the caller does not
909 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
910 * not to fs). In this case mark the page for immediate
911 * reclaim and continue scanning.
912 *
913 * Require may_enter_fs because we would wait on fs, which
914 * may not have submitted IO yet. And the loop driver might
915 * enter reclaim, and deadlock if it waits on a page for
916 * which it is needed to do the write (loop masks off
917 * __GFP_IO|__GFP_FS for this reason); but more thought
918 * would probably show more reasons.
919 *
920 * 3) Legacy memcg encounters a page that is not already marked
921 * PageReclaim. memcg does not have any dirty pages
922 * throttling so we could easily OOM just because too many
923 * pages are in writeback and there is nothing else to
924 * reclaim. Wait for the writeback to complete.
925 */
926 if (PageWriteback(page)) {
927 /* Case 1 above */
928 if (current_is_kswapd() &&
929 PageReclaim(page) &&
930 zone_is_reclaim_writeback(zone)) {
931 nr_immediate++;
932 goto keep_locked;
933
934 /* Case 2 above */
935 } else if (sane_reclaim(sc) ||
936 !PageReclaim(page) || !may_enter_fs) {
937 /*
938 * This is slightly racy - end_page_writeback()
939 * might have just cleared PageReclaim, then
940 * setting PageReclaim here end up interpreted
941 * as PageReadahead - but that does not matter
942 * enough to care. What we do want is for this
943 * page to have PageReclaim set next time memcg
944 * reclaim reaches the tests above, so it will
945 * then wait_on_page_writeback() to avoid OOM;
946 * and it's also appropriate in global reclaim.
947 */
948 SetPageReclaim(page);
949 nr_writeback++;
950
951 goto keep_locked;
952
953 /* Case 3 above */
954 } else {
955 wait_on_page_writeback(page);
956 }
957 }
958
959 if (!force_reclaim)
960 references = page_check_references(page, sc);
961
962 switch (references) {
963 case PAGEREF_ACTIVATE:
964 goto activate_locked;
965 case PAGEREF_KEEP:
966 goto keep_locked;
967 case PAGEREF_RECLAIM:
968 case PAGEREF_RECLAIM_CLEAN:
969 ; /* try to reclaim the page below */
970 }
971
972 /*
973 * Anonymous process memory has backing store?
974 * Try to allocate it some swap space here.
975 */
976 if (PageAnon(page) && !PageSwapCache(page)) {
977 if (!(sc->gfp_mask & __GFP_IO))
978 goto keep_locked;
979 if (!add_to_swap(page, page_list))
980 goto activate_locked;
981 lazyfree = true;
982 may_enter_fs = 1;
983
984 /* Adding to swap updated mapping */
985 mapping = page_mapping(page);
986 }
987
988 /*
989 * The page is mapped into the page tables of one or more
990 * processes. Try to unmap it here.
991 */
992 if (page_mapped(page) && mapping) {
993 switch (ret = try_to_unmap(page, lazyfree ?
994 (ttu_flags | TTU_BATCH_FLUSH | TTU_LZFREE) :
995 (ttu_flags | TTU_BATCH_FLUSH))) {
996 case SWAP_FAIL:
997 goto activate_locked;
998 case SWAP_AGAIN:
999 goto keep_locked;
1000 case SWAP_MLOCK:
1001 goto cull_mlocked;
1002 case SWAP_LZFREE:
1003 goto lazyfree;
1004 case SWAP_SUCCESS:
1005 ; /* try to free the page below */
1006 }
1007 }
1008
1009 if (PageDirty(page)) {
1010 /*
1011 * Only kswapd can writeback filesystem pages to
1012 * avoid risk of stack overflow but only writeback
1013 * if many dirty pages have been encountered.
1014 */
1015 if (page_is_file_cache(page) &&
1016 (!current_is_kswapd() ||
1017 !zone_is_reclaim_dirty(zone))) {
1018 /*
1019 * Immediately reclaim when written back.
1020 * Similar in principal to deactivate_page()
1021 * except we already have the page isolated
1022 * and know it's dirty
1023 */
1024 inc_zone_page_state(page, NR_VMSCAN_IMMEDIATE);
1025 SetPageReclaim(page);
1026
1027 goto keep_locked;
1028 }
1029
1030 if (references == PAGEREF_RECLAIM_CLEAN)
1031 goto keep_locked;
1032 if (!may_enter_fs)
1033 goto keep_locked;
1034 if (!sc->may_writepage)
1035 goto keep_locked;
1036
1037 /*
1038 * Page is dirty. Flush the TLB if a writable entry
1039 * potentially exists to avoid CPU writes after IO
1040 * starts and then write it out here.
1041 */
1042 try_to_unmap_flush_dirty();
1043 switch (pageout(page, mapping, sc)) {
1044 case PAGE_KEEP:
1045 goto keep_locked;
1046 case PAGE_ACTIVATE:
1047 goto activate_locked;
1048 case PAGE_SUCCESS:
1049 if (PageWriteback(page))
1050 goto keep;
1051 if (PageDirty(page))
1052 goto keep;
1053
1054 /*
1055 * A synchronous write - probably a ramdisk. Go
1056 * ahead and try to reclaim the page.
1057 */
1058 if (!trylock_page(page))
1059 goto keep;
1060 if (PageDirty(page) || PageWriteback(page))
1061 goto keep_locked;
1062 mapping = page_mapping(page);
1063 case PAGE_CLEAN:
1064 ; /* try to free the page below */
1065 }
1066 }
1067
1068 /*
1069 * If the page has buffers, try to free the buffer mappings
1070 * associated with this page. If we succeed we try to free
1071 * the page as well.
1072 *
1073 * We do this even if the page is PageDirty().
1074 * try_to_release_page() does not perform I/O, but it is
1075 * possible for a page to have PageDirty set, but it is actually
1076 * clean (all its buffers are clean). This happens if the
1077 * buffers were written out directly, with submit_bh(). ext3
1078 * will do this, as well as the blockdev mapping.
1079 * try_to_release_page() will discover that cleanness and will
1080 * drop the buffers and mark the page clean - it can be freed.
1081 *
1082 * Rarely, pages can have buffers and no ->mapping. These are
1083 * the pages which were not successfully invalidated in
1084 * truncate_complete_page(). We try to drop those buffers here
1085 * and if that worked, and the page is no longer mapped into
1086 * process address space (page_count == 1) it can be freed.
1087 * Otherwise, leave the page on the LRU so it is swappable.
1088 */
1089 if (page_has_private(page)) {
1090 if (!try_to_release_page(page, sc->gfp_mask))
1091 goto activate_locked;
1092 if (!mapping && page_count(page) == 1) {
1093 unlock_page(page);
1094 if (put_page_testzero(page))
1095 goto free_it;
1096 else {
1097 /*
1098 * rare race with speculative reference.
1099 * the speculative reference will free
1100 * this page shortly, so we may
1101 * increment nr_reclaimed here (and
1102 * leave it off the LRU).
1103 */
1104 nr_reclaimed++;
1105 continue;
1106 }
1107 }
1108 }
1109
1110lazyfree:
1111 if (!mapping || !__remove_mapping(mapping, page, true))
1112 goto keep_locked;
1113
1114 /*
1115 * At this point, we have no other references and there is
1116 * no way to pick any more up (removed from LRU, removed
1117 * from pagecache). Can use non-atomic bitops now (and
1118 * we obviously don't have to worry about waking up a process
1119 * waiting on the page lock, because there are no references.
1120 */
1121 __clear_page_locked(page);
1122free_it:
1123 if (ret == SWAP_LZFREE)
1124 count_vm_event(PGLAZYFREED);
1125
1126 nr_reclaimed++;
1127
1128 /*
1129 * Is there need to periodically free_page_list? It would
1130 * appear not as the counts should be low
1131 */
1132 list_add(&page->lru, &free_pages);
1133 continue;
1134
1135cull_mlocked:
1136 if (PageSwapCache(page))
1137 try_to_free_swap(page);
1138 unlock_page(page);
1139 putback_lru_page(page);
1140 continue;
1141
1142activate_locked:
1143 /* Not a candidate for swapping, so reclaim swap space. */
1144 if (PageSwapCache(page) && vm_swap_full())
1145 try_to_free_swap(page);
1146 VM_BUG_ON_PAGE(PageActive(page), page);
1147 SetPageActive(page);
1148 pgactivate++;
1149keep_locked:
1150 unlock_page(page);
1151keep:
1152 list_add(&page->lru, &ret_pages);
1153 VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
1154 }
1155
1156 try_to_unmap_flush();
1157 free_hot_cold_page_list(&free_pages, true);
1158
1159 list_splice(&ret_pages, page_list);
1160 count_vm_events(PGACTIVATE, pgactivate);
1161 mem_cgroup_uncharge_end();
1162 *ret_nr_dirty += nr_dirty;
1163 *ret_nr_congested += nr_congested;
1164 *ret_nr_unqueued_dirty += nr_unqueued_dirty;
1165 *ret_nr_writeback += nr_writeback;
1166 *ret_nr_immediate += nr_immediate;
1167 return nr_reclaimed;
1168}
1169
1170unsigned long reclaim_clean_pages_from_list(struct zone *zone,
1171 struct list_head *page_list)
1172{
1173 struct scan_control sc = {
1174 .gfp_mask = GFP_KERNEL,
1175 .priority = DEF_PRIORITY,
1176 .may_unmap = 1,
1177 };
1178 unsigned long ret, dummy1, dummy2, dummy3, dummy4, dummy5;
1179 struct page *page, *next;
1180 LIST_HEAD(clean_pages);
1181
1182 list_for_each_entry_safe(page, next, page_list, lru) {
1183 if (page_is_file_cache(page) && !PageDirty(page) &&
1184 !isolated_balloon_page(page)) {
1185 ClearPageActive(page);
1186 list_move(&page->lru, &clean_pages);
1187 }
1188 }
1189
1190 ret = shrink_page_list(&clean_pages, zone, &sc,
1191 TTU_UNMAP|TTU_IGNORE_ACCESS,
1192 &dummy1, &dummy2, &dummy3, &dummy4, &dummy5, true);
1193 list_splice(&clean_pages, page_list);
1194 __mod_zone_page_state(zone, NR_ISOLATED_FILE, -ret);
1195 return ret;
1196}
1197
1198/*
1199 * Attempt to remove the specified page from its LRU. Only take this page
1200 * if it is of the appropriate PageActive status. Pages which are being
1201 * freed elsewhere are also ignored.
1202 *
1203 * page: page to consider
1204 * mode: one of the LRU isolation modes defined above
1205 *
1206 * returns 0 on success, -ve errno on failure.
1207 */
1208int __isolate_lru_page(struct page *page, isolate_mode_t mode)
1209{
1210 int ret = -EINVAL;
1211
1212 /* Only take pages on the LRU. */
1213 if (!PageLRU(page))
1214 return ret;
1215
1216 /* Compaction should not handle unevictable pages but CMA can do so */
1217 if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1218 return ret;
1219
1220 ret = -EBUSY;
1221
1222 /*
1223 * To minimise LRU disruption, the caller can indicate that it only
1224 * wants to isolate pages it will be able to operate on without
1225 * blocking - clean pages for the most part.
1226 *
1227 * ISOLATE_CLEAN means that only clean pages should be isolated. This
1228 * is used by reclaim when it is cannot write to backing storage
1229 *
1230 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1231 * that it is possible to migrate without blocking
1232 */
1233 if (mode & (ISOLATE_CLEAN|ISOLATE_ASYNC_MIGRATE)) {
1234 /* All the caller can do on PageWriteback is block */
1235 if (PageWriteback(page))
1236 return ret;
1237
1238 if (PageDirty(page)) {
1239 struct address_space *mapping;
1240
1241 /* ISOLATE_CLEAN means only clean pages */
1242 if (mode & ISOLATE_CLEAN)
1243 return ret;
1244
1245 /*
1246 * Only pages without mappings or that have a
1247 * ->migratepage callback are possible to migrate
1248 * without blocking
1249 */
1250 mapping = page_mapping(page);
1251 if (mapping && !mapping->a_ops->migratepage)
1252 return ret;
1253 }
1254 }
1255
1256 if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1257 return ret;
1258
1259 if (likely(get_page_unless_zero(page))) {
1260 /*
1261 * Be careful not to clear PageLRU until after we're
1262 * sure the page is not being freed elsewhere -- the
1263 * page release code relies on it.
1264 */
1265 ClearPageLRU(page);
1266 ret = 0;
1267 }
1268
1269 return ret;
1270}
1271
1272/*
1273 * zone->lru_lock is heavily contended. Some of the functions that
1274 * shrink the lists perform better by taking out a batch of pages
1275 * and working on them outside the LRU lock.
1276 *
1277 * For pagecache intensive workloads, this function is the hottest
1278 * spot in the kernel (apart from copy_*_user functions).
1279 *
1280 * Appropriate locks must be held before calling this function.
1281 *
1282 * @nr_to_scan: The number of pages to look through on the list.
1283 * @lruvec: The LRU vector to pull pages from.
1284 * @dst: The temp list to put pages on to.
1285 * @nr_scanned: The number of pages that were scanned.
1286 * @sc: The scan_control struct for this reclaim session
1287 * @mode: One of the LRU isolation modes
1288 * @lru: LRU list id for isolating
1289 *
1290 * returns how many pages were moved onto *@dst.
1291 */
1292static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
1293 struct lruvec *lruvec, struct list_head *dst,
1294 unsigned long *nr_scanned, struct scan_control *sc,
1295 isolate_mode_t mode, enum lru_list lru)
1296{
1297 struct list_head *src = &lruvec->lists[lru];
1298 unsigned long nr_taken = 0;
1299 unsigned long scan;
1300
1301 for (scan = 0; scan < nr_to_scan && !list_empty(src); scan++) {
1302 struct page *page;
1303 int nr_pages;
1304
1305 page = lru_to_page(src);
1306 prefetchw_prev_lru_page(page, src, flags);
1307
1308 VM_BUG_ON_PAGE(!PageLRU(page), page);
1309
1310 switch (__isolate_lru_page(page, mode)) {
1311 case 0:
1312 nr_pages = hpage_nr_pages(page);
1313 mem_cgroup_update_lru_size(lruvec, lru, -nr_pages);
1314 list_move(&page->lru, dst);
1315 nr_taken += nr_pages;
1316 break;
1317
1318 case -EBUSY:
1319 /* else it is being freed elsewhere */
1320 list_move(&page->lru, src);
1321 continue;
1322
1323 default:
1324 BUG();
1325 }
1326 }
1327
1328 *nr_scanned = scan;
1329 trace_mm_vmscan_lru_isolate(sc->order, nr_to_scan, scan,
1330 nr_taken, mode, is_file_lru(lru));
1331 return nr_taken;
1332}
1333
1334/**
1335 * isolate_lru_page - tries to isolate a page from its LRU list
1336 * @page: page to isolate from its LRU list
1337 *
1338 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
1339 * vmstat statistic corresponding to whatever LRU list the page was on.
1340 *
1341 * Returns 0 if the page was removed from an LRU list.
1342 * Returns -EBUSY if the page was not on an LRU list.
1343 *
1344 * The returned page will have PageLRU() cleared. If it was found on
1345 * the active list, it will have PageActive set. If it was found on
1346 * the unevictable list, it will have the PageUnevictable bit set. That flag
1347 * may need to be cleared by the caller before letting the page go.
1348 *
1349 * The vmstat statistic corresponding to the list on which the page was
1350 * found will be decremented.
1351 *
1352 * Restrictions:
1353 * (1) Must be called with an elevated refcount on the page. This is a
1354 * fundamentnal difference from isolate_lru_pages (which is called
1355 * without a stable reference).
1356 * (2) the lru_lock must not be held.
1357 * (3) interrupts must be enabled.
1358 */
1359int isolate_lru_page(struct page *page)
1360{
1361 int ret = -EBUSY;
1362
1363 VM_BUG_ON_PAGE(!page_count(page), page);
1364
1365 if (PageLRU(page)) {
1366 struct zone *zone = page_zone(page);
1367 struct lruvec *lruvec;
1368
1369 spin_lock_irq(&zone->lru_lock);
1370 lruvec = mem_cgroup_page_lruvec(page, zone);
1371 if (PageLRU(page)) {
1372 int lru = page_lru(page);
1373 get_page(page);
1374 ClearPageLRU(page);
1375 del_page_from_lru_list(page, lruvec, lru);
1376 ret = 0;
1377 }
1378 spin_unlock_irq(&zone->lru_lock);
1379 }
1380 return ret;
1381}
1382
1383/*
1384 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1385 * then get resheduled. When there are massive number of tasks doing page
1386 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1387 * the LRU list will go small and be scanned faster than necessary, leading to
1388 * unnecessary swapping, thrashing and OOM.
1389 */
1390static int too_many_isolated(struct zone *zone, int file,
1391 struct scan_control *sc)
1392{
1393 unsigned long inactive, isolated;
1394
1395 if (current_is_kswapd())
1396 return 0;
1397
1398 if (!sane_reclaim(sc))
1399 return 0;
1400
1401 if (file) {
1402 inactive = zone_page_state(zone, NR_INACTIVE_FILE);
1403 isolated = zone_page_state(zone, NR_ISOLATED_FILE);
1404 } else {
1405 inactive = zone_page_state(zone, NR_INACTIVE_ANON);
1406 isolated = zone_page_state(zone, NR_ISOLATED_ANON);
1407 }
1408
1409 /*
1410 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
1411 * won't get blocked by normal direct-reclaimers, forming a circular
1412 * deadlock.
1413 */
1414 if ((sc->gfp_mask & GFP_IOFS) == GFP_IOFS)
1415 inactive >>= 3;
1416
1417 return isolated > inactive;
1418}
1419
1420static noinline_for_stack void
1421putback_inactive_pages(struct lruvec *lruvec, struct list_head *page_list)
1422{
1423 struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1424 struct zone *zone = lruvec_zone(lruvec);
1425 LIST_HEAD(pages_to_free);
1426
1427 /*
1428 * Put back any unfreeable pages.
1429 */
1430 while (!list_empty(page_list)) {
1431 struct page *page = lru_to_page(page_list);
1432 int lru;
1433
1434 VM_BUG_ON_PAGE(PageLRU(page), page);
1435 list_del(&page->lru);
1436 if (unlikely(!page_evictable(page))) {
1437 spin_unlock_irq(&zone->lru_lock);
1438 putback_lru_page(page);
1439 spin_lock_irq(&zone->lru_lock);
1440 continue;
1441 }
1442
1443 lruvec = mem_cgroup_page_lruvec(page, zone);
1444
1445 SetPageLRU(page);
1446 lru = page_lru(page);
1447 add_page_to_lru_list(page, lruvec, lru);
1448
1449 if (is_active_lru(lru)) {
1450 int file = is_file_lru(lru);
1451 int numpages = hpage_nr_pages(page);
1452 reclaim_stat->recent_rotated[file] += numpages;
1453 }
1454 if (put_page_testzero(page)) {
1455 __ClearPageLRU(page);
1456 __ClearPageActive(page);
1457 del_page_from_lru_list(page, lruvec, lru);
1458
1459 if (unlikely(PageCompound(page))) {
1460 spin_unlock_irq(&zone->lru_lock);
1461 (*get_compound_page_dtor(page))(page);
1462 spin_lock_irq(&zone->lru_lock);
1463 } else
1464 list_add(&page->lru, &pages_to_free);
1465 }
1466 }
1467
1468 /*
1469 * To save our caller's stack, now use input list for pages to free.
1470 */
1471 list_splice(&pages_to_free, page_list);
1472}
1473
1474/*
1475 * shrink_inactive_list() is a helper for shrink_zone(). It returns the number
1476 * of reclaimed pages
1477 */
1478static noinline_for_stack unsigned long
1479shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
1480 struct scan_control *sc, enum lru_list lru)
1481{
1482 LIST_HEAD(page_list);
1483 unsigned long nr_scanned;
1484 unsigned long nr_reclaimed = 0;
1485 unsigned long nr_taken;
1486 unsigned long nr_dirty = 0;
1487 unsigned long nr_congested = 0;
1488 unsigned long nr_unqueued_dirty = 0;
1489 unsigned long nr_writeback = 0;
1490 unsigned long nr_immediate = 0;
1491 isolate_mode_t isolate_mode = 0;
1492 int file = is_file_lru(lru);
1493 struct zone *zone = lruvec_zone(lruvec);
1494 struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1495 bool stalled = false;
1496
1497 while (unlikely(too_many_isolated(zone, file, sc))) {
1498 if (stalled)
1499 return 0;
1500
1501 /* wait a bit for the reclaimer. */
1502 msleep(100);
1503 stalled = true;
1504
1505 /* We are about to die and free our memory. Return now. */
1506 if (fatal_signal_pending(current))
1507 return SWAP_CLUSTER_MAX;
1508 }
1509
1510 lru_add_drain();
1511
1512 if (!sc->may_unmap)
1513 isolate_mode |= ISOLATE_UNMAPPED;
1514 if (!sc->may_writepage)
1515 isolate_mode |= ISOLATE_CLEAN;
1516
1517 spin_lock_irq(&zone->lru_lock);
1518
1519 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
1520 &nr_scanned, sc, isolate_mode, lru);
1521
1522 __mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken);
1523 __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
1524
1525 if (global_reclaim(sc)) {
1526 zone->pages_scanned += nr_scanned;
1527 if (current_is_kswapd())
1528 __count_zone_vm_events(PGSCAN_KSWAPD, zone, nr_scanned);
1529 else
1530 __count_zone_vm_events(PGSCAN_DIRECT, zone, nr_scanned);
1531 }
1532 spin_unlock_irq(&zone->lru_lock);
1533
1534 if (nr_taken == 0)
1535 return 0;
1536
1537 nr_reclaimed = shrink_page_list(&page_list, zone, sc, TTU_UNMAP,
1538 &nr_dirty, &nr_unqueued_dirty, &nr_congested,
1539 &nr_writeback, &nr_immediate,
1540 false);
1541
1542 spin_lock_irq(&zone->lru_lock);
1543
1544 reclaim_stat->recent_scanned[file] += nr_taken;
1545
1546 if (global_reclaim(sc)) {
1547 if (current_is_kswapd())
1548 __count_zone_vm_events(PGSTEAL_KSWAPD, zone,
1549 nr_reclaimed);
1550 else
1551 __count_zone_vm_events(PGSTEAL_DIRECT, zone,
1552 nr_reclaimed);
1553 }
1554
1555 putback_inactive_pages(lruvec, &page_list);
1556
1557 __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
1558
1559 spin_unlock_irq(&zone->lru_lock);
1560
1561 free_hot_cold_page_list(&page_list, true);
1562
1563 /*
1564 * If reclaim is isolating dirty pages under writeback, it implies
1565 * that the long-lived page allocation rate is exceeding the page
1566 * laundering rate. Either the global limits are not being effective
1567 * at throttling processes due to the page distribution throughout
1568 * zones or there is heavy usage of a slow backing device. The
1569 * only option is to throttle from reclaim context which is not ideal
1570 * as there is no guarantee the dirtying process is throttled in the
1571 * same way balance_dirty_pages() manages.
1572 *
1573 * Once a zone is flagged ZONE_WRITEBACK, kswapd will count the number
1574 * of pages under pages flagged for immediate reclaim and stall if any
1575 * are encountered in the nr_immediate check below.
1576 */
1577 if (nr_writeback && nr_writeback == nr_taken)
1578 zone_set_flag(zone, ZONE_WRITEBACK);
1579
1580 /*
1581 * Legacy memcg will stall in page writeback so avoid forcibly
1582 * stalling here.
1583 */
1584 if (sane_reclaim(sc)) {
1585 /*
1586 * Tag a zone as congested if all the dirty pages scanned were
1587 * backed by a congested BDI and wait_iff_congested will stall.
1588 */
1589 if (nr_dirty && nr_dirty == nr_congested)
1590 zone_set_flag(zone, ZONE_CONGESTED);
1591
1592 /*
1593 * If dirty pages are scanned that are not queued for IO, it
1594 * implies that flushers are not keeping up. In this case, flag
1595 * the zone ZONE_TAIL_LRU_DIRTY and kswapd will start writing
1596 * pages from reclaim context. It will forcibly stall in the
1597 * next check.
1598 */
1599 if (nr_unqueued_dirty == nr_taken)
1600 zone_set_flag(zone, ZONE_TAIL_LRU_DIRTY);
1601
1602 /*
1603 * In addition, if kswapd scans pages marked marked for
1604 * immediate reclaim and under writeback (nr_immediate), it
1605 * implies that pages are cycling through the LRU faster than
1606 * they are written so also forcibly stall.
1607 */
1608 if (nr_unqueued_dirty == nr_taken || nr_immediate)
1609 congestion_wait(BLK_RW_ASYNC, HZ/10);
1610 }
1611
1612 /*
1613 * Stall direct reclaim for IO completions if underlying BDIs or zone
1614 * is congested. Allow kswapd to continue until it starts encountering
1615 * unqueued dirty pages or cycling through the LRU too quickly.
1616 */
1617 if (!sc->hibernation_mode && !current_is_kswapd())
1618 wait_iff_congested(zone, BLK_RW_ASYNC, HZ/10);
1619
1620 trace_mm_vmscan_lru_shrink_inactive(zone->zone_pgdat->node_id,
1621 zone_idx(zone),
1622 nr_scanned, nr_reclaimed,
1623 sc->priority,
1624 trace_shrink_flags(file));
1625
1626 //ADDED DURING ASSIGNMENT 4
1627 evicted_from_inactive += nr_reclaimed;
1628
1629 return nr_reclaimed;
1630}
1631
1632/*
1633 * This moves pages from the active list to the inactive list.
1634 *
1635 * We move them the other way if the page is referenced by one or more
1636 * processes, from rmap.
1637 *
1638 * If the pages are mostly unmapped, the processing is fast and it is
1639 * appropriate to hold zone->lru_lock across the whole operation. But if
1640 * the pages are mapped, the processing is slow (page_referenced()) so we
1641 * should drop zone->lru_lock around each page. It's impossible to balance
1642 * this, so instead we remove the pages from the LRU while processing them.
1643 * It is safe to rely on PG_active against the non-LRU pages in here because
1644 * nobody will play with that bit on a non-LRU page.
1645 *
1646 * The downside is that we have to touch page->_count against each page.
1647 * But we had to alter page->flags anyway.
1648 */
1649
1650static void move_active_pages_to_lru(struct lruvec *lruvec,
1651 struct list_head *list,
1652 struct list_head *pages_to_free,
1653 enum lru_list lru)
1654{
1655 struct zone *zone = lruvec_zone(lruvec);
1656 unsigned long pgmoved = 0;
1657 struct page *page;
1658 int nr_pages;
1659
1660 while (!list_empty(list)) {
1661 page = lru_to_page(list);
1662 lruvec = mem_cgroup_page_lruvec(page, zone);
1663
1664 VM_BUG_ON_PAGE(PageLRU(page), page);
1665 SetPageLRU(page);
1666
1667 nr_pages = hpage_nr_pages(page);
1668 mem_cgroup_update_lru_size(lruvec, lru, nr_pages);
1669 list_move(&page->lru, &lruvec->lists[lru]);
1670 pgmoved += nr_pages;
1671
1672 if (put_page_testzero(page)) {
1673 __ClearPageLRU(page);
1674 __ClearPageActive(page);
1675 del_page_from_lru_list(page, lruvec, lru);
1676
1677 if (unlikely(PageCompound(page))) {
1678 spin_unlock_irq(&zone->lru_lock);
1679 (*get_compound_page_dtor(page))(page);
1680 spin_lock_irq(&zone->lru_lock);
1681 } else
1682 list_add(&page->lru, pages_to_free);
1683 }
1684 }
1685 __mod_zone_page_state(zone, NR_LRU_BASE + lru, pgmoved);
1686 if (!is_active_lru(lru))
1687 __count_vm_events(PGDEACTIVATE, pgmoved);
1688}
1689
1690static void shrink_active_list(unsigned long nr_to_scan,
1691 struct lruvec *lruvec,
1692 struct scan_control *sc,
1693 enum lru_list lru)
1694{
1695 unsigned long nr_taken;
1696 unsigned long nr_scanned;
1697 unsigned long vm_flags;
1698 LIST_HEAD(l_hold); /* The pages which were snipped off */
1699 LIST_HEAD(l_active);
1700 LIST_HEAD(l_inactive);
1701 struct page *page;
1702 struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1703 unsigned long nr_rotated = 0;
1704 isolate_mode_t isolate_mode = 0;
1705 int file = is_file_lru(lru);
1706 struct zone *zone = lruvec_zone(lruvec);
1707
1708 lru_add_drain();
1709
1710 if (!sc->may_unmap)
1711 isolate_mode |= ISOLATE_UNMAPPED;
1712 if (!sc->may_writepage)
1713 isolate_mode |= ISOLATE_CLEAN;
1714
1715 spin_lock_irq(&zone->lru_lock);
1716
1717 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
1718 &nr_scanned, sc, isolate_mode, lru);
1719 if (global_reclaim(sc))
1720 zone->pages_scanned += nr_scanned;
1721
1722 reclaim_stat->recent_scanned[file] += nr_taken;
1723
1724 __count_zone_vm_events(PGREFILL, zone, nr_scanned);
1725 __mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken);
1726 __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
1727 spin_unlock_irq(&zone->lru_lock);
1728
1729 while (!list_empty(&l_hold)) {
1730 cond_resched();
1731 page = lru_to_page(&l_hold);
1732 list_del(&page->lru);
1733
1734 if (unlikely(!page_evictable(page))) {
1735 putback_lru_page(page);
1736 continue;
1737 }
1738
1739 if (unlikely(buffer_heads_over_limit)) {
1740 if (page_has_private(page) && trylock_page(page)) {
1741 if (page_has_private(page))
1742 try_to_release_page(page, 0);
1743 unlock_page(page);
1744 }
1745 }
1746
1747 if (page_referenced(page, 0, sc->target_mem_cgroup,
1748 &vm_flags)) {
1749 nr_rotated += hpage_nr_pages(page);
1750 /*
1751 * Identify referenced, file-backed active pages and
1752 * give them one more trip around the active list. So
1753 * that executable code get better chances to stay in
1754 * memory under moderate memory pressure. Anon pages
1755 * are not likely to be evicted by use-once streaming
1756 * IO, plus JVM can create lots of anon VM_EXEC pages,
1757 * so we ignore them here.
1758 */
1759 if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
1760 list_add(&page->lru, &l_active);
1761 continue;
1762 }
1763 }
1764
1765 //ADDED DURING PROGRAM 4
1766 active_to_inactive++;
1767
1768 ClearPageActive(page); /* we are de-activating */
1769 list_add(&page->lru, &l_inactive);
1770 }
1771
1772 /*
1773 * Move pages back to the lru list.
1774 */
1775 spin_lock_irq(&zone->lru_lock);
1776 /*
1777 * Count referenced pages from currently used mappings as rotated,
1778 * even though only some of them are actually re-activated. This
1779 * helps balance scan pressure between file and anonymous pages in
1780 * get_scan_ratio.
1781 */
1782 reclaim_stat->recent_rotated[file] += nr_rotated;
1783
1784 move_active_pages_to_lru(lruvec, &l_active, &l_hold, lru);
1785 move_active_pages_to_lru(lruvec, &l_inactive, &l_hold, lru - LRU_ACTIVE);
1786 __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
1787 spin_unlock_irq(&zone->lru_lock);
1788
1789 free_hot_cold_page_list(&l_hold, true);
1790}
1791
1792#ifdef CONFIG_SWAP
1793static int inactive_anon_is_low_global(struct zone *zone)
1794{
1795 unsigned long active, inactive;
1796
1797 active = zone_page_state(zone, NR_ACTIVE_ANON);
1798 inactive = zone_page_state(zone, NR_INACTIVE_ANON);
1799
1800 if (inactive * zone->inactive_ratio < active)
1801 return 1;
1802
1803 return 0;
1804}
1805
1806/**
1807 * inactive_anon_is_low - check if anonymous pages need to be deactivated
1808 * @lruvec: LRU vector to check
1809 *
1810 * Returns true if the zone does not have enough inactive anon pages,
1811 * meaning some active anon pages need to be deactivated.
1812 */
1813static int inactive_anon_is_low(struct lruvec *lruvec)
1814{
1815 /*
1816 * If we don't have swap space, anonymous page deactivation
1817 * is pointless.
1818 */
1819 if (!total_swap_pages)
1820 return 0;
1821
1822 if (!mem_cgroup_disabled())
1823 return mem_cgroup_inactive_anon_is_low(lruvec);
1824
1825 return inactive_anon_is_low_global(lruvec_zone(lruvec));
1826}
1827#else
1828static inline int inactive_anon_is_low(struct lruvec *lruvec)
1829{
1830 return 0;
1831}
1832#endif
1833
1834/**
1835 * inactive_file_is_low - check if file pages need to be deactivated
1836 * @lruvec: LRU vector to check
1837 *
1838 * When the system is doing streaming IO, memory pressure here
1839 * ensures that active file pages get deactivated, until more
1840 * than half of the file pages are on the inactive list.
1841 *
1842 * Once we get to that situation, protect the system's working
1843 * set from being evicted by disabling active file page aging.
1844 *
1845 * This uses a different ratio than the anonymous pages, because
1846 * the page cache uses a use-once replacement algorithm.
1847 */
1848static int inactive_file_is_low(struct lruvec *lruvec)
1849{
1850 unsigned long inactive;
1851 unsigned long active;
1852
1853 inactive = get_lru_size(lruvec, LRU_INACTIVE_FILE);
1854 active = get_lru_size(lruvec, LRU_ACTIVE_FILE);
1855
1856 return active > inactive;
1857}
1858
1859static int inactive_list_is_low(struct lruvec *lruvec, enum lru_list lru)
1860{
1861 if (is_file_lru(lru))
1862 return inactive_file_is_low(lruvec);
1863 else
1864 return inactive_anon_is_low(lruvec);
1865}
1866
1867static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
1868 struct lruvec *lruvec, struct scan_control *sc)
1869{
1870 if (is_active_lru(lru)) {
1871 if (inactive_list_is_low(lruvec, lru))
1872 shrink_active_list(nr_to_scan, lruvec, sc, lru);
1873 return 0;
1874 }
1875
1876 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
1877}
1878
1879static int vmscan_swappiness(struct scan_control *sc)
1880{
1881 if (global_reclaim(sc))
1882 return vm_swappiness;
1883 return mem_cgroup_swappiness(sc->target_mem_cgroup);
1884}
1885
1886enum scan_balance {
1887 SCAN_EQUAL,
1888 SCAN_FRACT,
1889 SCAN_ANON,
1890 SCAN_FILE,
1891};
1892
1893/*
1894 * Determine how aggressively the anon and file LRU lists should be
1895 * scanned. The relative value of each set of LRU lists is determined
1896 * by looking at the fraction of the pages scanned we did rotate back
1897 * onto the active list instead of evict.
1898 *
1899 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
1900 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
1901 */
1902static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
1903 unsigned long *nr)
1904{
1905 struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1906 u64 fraction[2];
1907 u64 denominator = 0; /* gcc */
1908 struct zone *zone = lruvec_zone(lruvec);
1909 unsigned long anon_prio, file_prio;
1910 enum scan_balance scan_balance;
1911 unsigned long anon, file;
1912 bool force_scan = false;
1913 unsigned long ap, fp;
1914 enum lru_list lru;
1915
1916 /*
1917 * If the zone or memcg is small, nr[l] can be 0. This
1918 * results in no scanning on this priority and a potential
1919 * priority drop. Global direct reclaim can go to the next
1920 * zone and tends to have no problems. Global kswapd is for
1921 * zone balancing and it needs to scan a minimum amount. When
1922 * reclaiming for a memcg, a priority drop can cause high
1923 * latencies, so it's better to scan a minimum amount there as
1924 * well.
1925 */
1926 if (current_is_kswapd() && zone->all_unreclaimable)
1927 force_scan = true;
1928 if (!global_reclaim(sc))
1929 force_scan = true;
1930
1931 /* If we have no swap space, do not bother scanning anon pages. */
1932 if (!sc->may_swap || (get_nr_swap_pages() <= 0)) {
1933 scan_balance = SCAN_FILE;
1934 goto out;
1935 }
1936
1937 /*
1938 * Global reclaim will swap to prevent OOM even with no
1939 * swappiness, but memcg users want to use this knob to
1940 * disable swapping for individual groups completely when
1941 * using the memory controller's swap limit feature would be
1942 * too expensive.
1943 */
1944 if (!global_reclaim(sc) && !vmscan_swappiness(sc)) {
1945 scan_balance = SCAN_FILE;
1946 goto out;
1947 }
1948
1949 /*
1950 * Do not apply any pressure balancing cleverness when the
1951 * system is close to OOM, scan both anon and file equally
1952 * (unless the swappiness setting disagrees with swapping).
1953 */
1954 if (!sc->priority && vmscan_swappiness(sc)) {
1955 scan_balance = SCAN_EQUAL;
1956 goto out;
1957 }
1958
1959 anon = get_lru_size(lruvec, LRU_ACTIVE_ANON) +
1960 get_lru_size(lruvec, LRU_INACTIVE_ANON);
1961 file = get_lru_size(lruvec, LRU_ACTIVE_FILE) +
1962 get_lru_size(lruvec, LRU_INACTIVE_FILE);
1963
1964 /*
1965 * Prevent the reclaimer from falling into the cache trap: as
1966 * cache pages start out inactive, every cache fault will tip
1967 * the scan balance towards the file LRU. And as the file LRU
1968 * shrinks, so does the window for rotation from references.
1969 * This means we have a runaway feedback loop where a tiny
1970 * thrashing file LRU becomes infinitely more attractive than
1971 * anon pages. Try to detect this based on file LRU size.
1972 */
1973 if (global_reclaim(sc)) {
1974 unsigned long free = zone_page_state(zone, NR_FREE_PAGES);
1975 unsigned long zonefile =
1976 zone_page_state(zone, NR_LRU_BASE + LRU_ACTIVE_FILE) +
1977 zone_page_state(zone, NR_LRU_BASE + LRU_INACTIVE_FILE);
1978
1979 if (unlikely(zonefile + free <= high_wmark_pages(zone))) {
1980 scan_balance = SCAN_ANON;
1981 goto out;
1982 }
1983 }
1984
1985 /*
1986 * There is enough inactive page cache, do not reclaim
1987 * anything from the anonymous working set right now.
1988 */
1989 if (!inactive_file_is_low(lruvec)) {
1990 scan_balance = SCAN_FILE;
1991 goto out;
1992 }
1993
1994 scan_balance = SCAN_FRACT;
1995
1996 /*
1997 * With swappiness at 100, anonymous and file have the same priority.
1998 * This scanning priority is essentially the inverse of IO cost.
1999 */
2000 anon_prio = vmscan_swappiness(sc);
2001 file_prio = 200 - anon_prio;
2002
2003 /*
2004 * OK, so we have swap space and a fair amount of page cache
2005 * pages. We use the recently rotated / recently scanned
2006 * ratios to determine how valuable each cache is.
2007 *
2008 * Because workloads change over time (and to avoid overflow)
2009 * we keep these statistics as a floating average, which ends
2010 * up weighing recent references more than old ones.
2011 *
2012 * anon in [0], file in [1]
2013 */
2014 spin_lock_irq(&zone->lru_lock);
2015 if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
2016 reclaim_stat->recent_scanned[0] /= 2;
2017 reclaim_stat->recent_rotated[0] /= 2;
2018 }
2019
2020 if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
2021 reclaim_stat->recent_scanned[1] /= 2;
2022 reclaim_stat->recent_rotated[1] /= 2;
2023 }
2024
2025 /*
2026 * The amount of pressure on anon vs file pages is inversely
2027 * proportional to the fraction of recently scanned pages on
2028 * each list that were recently referenced and in active use.
2029 */
2030 ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
2031 ap /= reclaim_stat->recent_rotated[0] + 1;
2032
2033 fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
2034 fp /= reclaim_stat->recent_rotated[1] + 1;
2035 spin_unlock_irq(&zone->lru_lock);
2036
2037 fraction[0] = ap;
2038 fraction[1] = fp;
2039 denominator = ap + fp + 1;
2040out:
2041 for_each_evictable_lru(lru) {
2042 int file = is_file_lru(lru);
2043 unsigned long size;
2044 unsigned long scan;
2045
2046 size = get_lru_size(lruvec, lru);
2047 scan = size >> sc->priority;
2048
2049 if (!scan && force_scan)
2050 scan = min(size, SWAP_CLUSTER_MAX);
2051
2052 switch (scan_balance) {
2053 case SCAN_EQUAL:
2054 /* Scan lists relative to size */
2055 break;
2056 case SCAN_FRACT:
2057 /*
2058 * Scan types proportional to swappiness and
2059 * their relative recent reclaim efficiency.
2060 */
2061 scan = div64_u64(scan * fraction[file], denominator);
2062 break;
2063 case SCAN_FILE:
2064 case SCAN_ANON:
2065 /* Scan one type exclusively */
2066 if ((scan_balance == SCAN_FILE) != file)
2067 scan = 0;
2068 break;
2069 default:
2070 /* Look ma, no brain */
2071 BUG();
2072 }
2073 nr[lru] = scan;
2074 }
2075}
2076
2077#ifdef CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH
2078static void init_tlb_ubc(void)
2079{
2080 /*
2081 * This deliberately does not clear the cpumask as it's expensive
2082 * and unnecessary. If there happens to be data in there then the
2083 * first SWAP_CLUSTER_MAX pages will send an unnecessary IPI and
2084 * then will be cleared.
2085 */
2086 current->tlb_ubc.flush_required = false;
2087}
2088#else
2089static inline void init_tlb_ubc(void)
2090{
2091}
2092#endif /* CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH */
2093
2094/*
2095 * This is a basic per-zone page freer. Used by both kswapd and direct reclaim.
2096 */
2097static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
2098{
2099 unsigned long nr[NR_LRU_LISTS];
2100 unsigned long targets[NR_LRU_LISTS];
2101 unsigned long nr_to_scan;
2102 enum lru_list lru;
2103 unsigned long nr_reclaimed = 0;
2104 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
2105 struct blk_plug plug;
2106 bool scan_adjusted;
2107
2108 get_scan_count(lruvec, sc, nr);
2109
2110 /* Record the original scan target for proportional adjustments later */
2111 memcpy(targets, nr, sizeof(nr));
2112
2113 /*
2114 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
2115 * event that can occur when there is little memory pressure e.g.
2116 * multiple streaming readers/writers. Hence, we do not abort scanning
2117 * when the requested number of pages are reclaimed when scanning at
2118 * DEF_PRIORITY on the assumption that the fact we are direct
2119 * reclaiming implies that kswapd is not keeping up and it is best to
2120 * do a batch of work at once. For memcg reclaim one check is made to
2121 * abort proportional reclaim if either the file or anon lru has already
2122 * dropped to zero at the first pass.
2123 */
2124 scan_adjusted = (global_reclaim(sc) && !current_is_kswapd() &&
2125 sc->priority == DEF_PRIORITY);
2126
2127 init_tlb_ubc();
2128
2129 blk_start_plug(&plug);
2130 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
2131 nr[LRU_INACTIVE_FILE]) {
2132 unsigned long nr_anon, nr_file, percentage;
2133 unsigned long nr_scanned;
2134
2135 for_each_evictable_lru(lru) {
2136 if (nr[lru]) {
2137 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
2138 nr[lru] -= nr_to_scan;
2139
2140 nr_reclaimed += shrink_list(lru, nr_to_scan,
2141 lruvec, sc);
2142 }
2143 }
2144
2145 if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2146 continue;
2147
2148 /*
2149 * For kswapd and memcg, reclaim at least the number of pages
2150 * requested. Ensure that the anon and file LRUs are scanned
2151 * proportionally what was requested by get_scan_count(). We
2152 * stop reclaiming one LRU and reduce the amount scanning
2153 * proportional to the original scan target.
2154 */
2155 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2156 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2157
2158 /*
2159 * It's just vindictive to attack the larger once the smaller
2160 * has gone to zero. And given the way we stop scanning the
2161 * smaller below, this makes sure that we only make one nudge
2162 * towards proportionality once we've got nr_to_reclaim.
2163 */
2164 if (!nr_file || !nr_anon)
2165 break;
2166
2167 if (nr_file > nr_anon) {
2168 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2169 targets[LRU_ACTIVE_ANON] + 1;
2170 lru = LRU_BASE;
2171 percentage = nr_anon * 100 / scan_target;
2172 } else {
2173 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2174 targets[LRU_ACTIVE_FILE] + 1;
2175 lru = LRU_FILE;
2176 percentage = nr_file * 100 / scan_target;
2177 }
2178
2179 /* Stop scanning the smaller of the LRU */
2180 nr[lru] = 0;
2181 nr[lru + LRU_ACTIVE] = 0;
2182
2183 /*
2184 * Recalculate the other LRU scan count based on its original
2185 * scan target and the percentage scanning already complete
2186 */
2187 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2188 nr_scanned = targets[lru] - nr[lru];
2189 nr[lru] = targets[lru] * (100 - percentage) / 100;
2190 nr[lru] -= min(nr[lru], nr_scanned);
2191
2192 lru += LRU_ACTIVE;
2193 nr_scanned = targets[lru] - nr[lru];
2194 nr[lru] = targets[lru] * (100 - percentage) / 100;
2195 nr[lru] -= min(nr[lru], nr_scanned);
2196
2197 scan_adjusted = true;
2198 }
2199 blk_finish_plug(&plug);
2200 sc->nr_reclaimed += nr_reclaimed;
2201
2202 /*
2203 * Even if we did not try to evict anon pages at all, we want to
2204 * rebalance the anon lru active/inactive ratio.
2205 */
2206 if (inactive_anon_is_low(lruvec))
2207 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
2208 sc, LRU_ACTIVE_ANON);
2209
2210 throttle_vm_writeout(sc->gfp_mask);
2211}
2212
2213/* Use reclaim/compaction for costly allocs or under memory pressure */
2214static bool in_reclaim_compaction(struct scan_control *sc)
2215{
2216 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
2217 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
2218 sc->priority < DEF_PRIORITY - 2))
2219 return true;
2220
2221 return false;
2222}
2223
2224/*
2225 * Reclaim/compaction is used for high-order allocation requests. It reclaims
2226 * order-0 pages before compacting the zone. should_continue_reclaim() returns
2227 * true if more pages should be reclaimed such that when the page allocator
2228 * calls try_to_compact_zone() that it will have enough free pages to succeed.
2229 * It will give up earlier than that if there is difficulty reclaiming pages.
2230 */
2231static inline bool should_continue_reclaim(struct zone *zone,
2232 unsigned long nr_reclaimed,
2233 unsigned long nr_scanned,
2234 struct scan_control *sc)
2235{
2236 unsigned long pages_for_compaction;
2237 unsigned long inactive_lru_pages;
2238
2239 /* If not in reclaim/compaction mode, stop */
2240 if (!in_reclaim_compaction(sc))
2241 return false;
2242
2243 /* Consider stopping depending on scan and reclaim activity */
2244 if (sc->gfp_mask & __GFP_REPEAT) {
2245 /*
2246 * For __GFP_REPEAT allocations, stop reclaiming if the
2247 * full LRU list has been scanned and we are still failing
2248 * to reclaim pages. This full LRU scan is potentially
2249 * expensive but a __GFP_REPEAT caller really wants to succeed
2250 */
2251 if (!nr_reclaimed && !nr_scanned)
2252 return false;
2253 } else {
2254 /*
2255 * For non-__GFP_REPEAT allocations which can presumably
2256 * fail without consequence, stop if we failed to reclaim
2257 * any pages from the last SWAP_CLUSTER_MAX number of
2258 * pages that were scanned. This will return to the
2259 * caller faster at the risk reclaim/compaction and
2260 * the resulting allocation attempt fails
2261 */
2262 if (!nr_reclaimed)
2263 return false;
2264 }
2265
2266 /*
2267 * If we have not reclaimed enough pages for compaction and the
2268 * inactive lists are large enough, continue reclaiming
2269 */
2270 pages_for_compaction = (2UL << sc->order);
2271 inactive_lru_pages = zone_page_state(zone, NR_INACTIVE_FILE);
2272 if (get_nr_swap_pages() > 0)
2273 inactive_lru_pages += zone_page_state(zone, NR_INACTIVE_ANON);
2274 if (sc->nr_reclaimed < pages_for_compaction &&
2275 inactive_lru_pages > pages_for_compaction)
2276 return true;
2277
2278 /* If compaction would go ahead or the allocation would succeed, stop */
2279 switch (compaction_suitable(zone, sc->order)) {
2280 case COMPACT_PARTIAL:
2281 case COMPACT_CONTINUE:
2282 return false;
2283 default:
2284 return true;
2285 }
2286}
2287
2288static void shrink_zone(struct zone *zone, struct scan_control *sc)
2289{
2290 unsigned long nr_reclaimed, nr_scanned;
2291
2292 do {
2293 struct mem_cgroup *root = sc->target_mem_cgroup;
2294 struct mem_cgroup_reclaim_cookie reclaim = {
2295 .zone = zone,
2296 .priority = sc->priority,
2297 };
2298 struct mem_cgroup *memcg;
2299
2300 nr_reclaimed = sc->nr_reclaimed;
2301 nr_scanned = sc->nr_scanned;
2302
2303 memcg = mem_cgroup_iter(root, NULL, &reclaim);
2304 do {
2305 struct lruvec *lruvec;
2306
2307 lruvec = mem_cgroup_zone_lruvec(zone, memcg);
2308
2309 shrink_lruvec(lruvec, sc);
2310
2311 /*
2312 * Direct reclaim and kswapd have to scan all memory
2313 * cgroups to fulfill the overall scan target for the
2314 * zone.
2315 *
2316 * Limit reclaim, on the other hand, only cares about
2317 * nr_to_reclaim pages to be reclaimed and it will
2318 * retry with decreasing priority if one round over the
2319 * whole hierarchy is not sufficient.
2320 */
2321 if (!global_reclaim(sc) &&
2322 sc->nr_reclaimed >= sc->nr_to_reclaim) {
2323 mem_cgroup_iter_break(root, memcg);
2324 break;
2325 }
2326 memcg = mem_cgroup_iter(root, memcg, &reclaim);
2327 } while (memcg);
2328
2329 vmpressure(sc->gfp_mask, sc->target_mem_cgroup,
2330 sc->nr_scanned - nr_scanned,
2331 sc->nr_reclaimed - nr_reclaimed);
2332
2333 } while (should_continue_reclaim(zone, sc->nr_reclaimed - nr_reclaimed,
2334 sc->nr_scanned - nr_scanned, sc));
2335}
2336
2337/* Returns true if compaction should go ahead for a high-order request */
2338static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
2339{
2340 unsigned long balance_gap, watermark;
2341 bool watermark_ok;
2342
2343 /* Do not consider compaction for orders reclaim is meant to satisfy */
2344 if (sc->order <= PAGE_ALLOC_COSTLY_ORDER)
2345 return false;
2346
2347 /*
2348 * Compaction takes time to run and there are potentially other
2349 * callers using the pages just freed. Continue reclaiming until
2350 * there is a buffer of free pages available to give compaction
2351 * a reasonable chance of completing and allocating the page
2352 */
2353 balance_gap = min(low_wmark_pages(zone),
2354 (zone->managed_pages + KSWAPD_ZONE_BALANCE_GAP_RATIO-1) /
2355 KSWAPD_ZONE_BALANCE_GAP_RATIO);
2356 watermark = high_wmark_pages(zone) + balance_gap + (2UL << sc->order);
2357 watermark_ok = zone_watermark_ok_safe(zone, 0, watermark, 0, 0);
2358
2359 /*
2360 * If compaction is deferred, reclaim up to a point where
2361 * compaction will have a chance of success when re-enabled
2362 */
2363 if (compaction_deferred(zone, sc->order))
2364 return watermark_ok;
2365
2366 /* If compaction is not ready to start, keep reclaiming */
2367 if (!compaction_suitable(zone, sc->order))
2368 return false;
2369
2370 return watermark_ok;
2371}
2372
2373/*
2374 * This is the direct reclaim path, for page-allocating processes. We only
2375 * try to reclaim pages from zones which will satisfy the caller's allocation
2376 * request.
2377 *
2378 * We reclaim from a zone even if that zone is over high_wmark_pages(zone).
2379 * Because:
2380 * a) The caller may be trying to free *extra* pages to satisfy a higher-order
2381 * allocation or
2382 * b) The target zone may be at high_wmark_pages(zone) but the lower zones
2383 * must go *over* high_wmark_pages(zone) to satisfy the `incremental min'
2384 * zone defense algorithm.
2385 *
2386 * If a zone is deemed to be full of pinned pages then just give it a light
2387 * scan then give up on it.
2388 *
2389 * This function returns true if a zone is being reclaimed for a costly
2390 * high-order allocation and compaction is ready to begin. This indicates to
2391 * the caller that it should consider retrying the allocation instead of
2392 * further reclaim.
2393 */
2394static bool shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
2395{
2396 struct zoneref *z;
2397 struct zone *zone;
2398 unsigned long nr_soft_reclaimed;
2399 unsigned long nr_soft_scanned;
2400 bool aborted_reclaim = false;
2401
2402 /*
2403 * If the number of buffer_heads in the machine exceeds the maximum
2404 * allowed level, force direct reclaim to scan the highmem zone as
2405 * highmem pages could be pinning lowmem pages storing buffer_heads
2406 */
2407 if (buffer_heads_over_limit)
2408 sc->gfp_mask |= __GFP_HIGHMEM;
2409
2410 for_each_zone_zonelist_nodemask(zone, z, zonelist,
2411 gfp_zone(sc->gfp_mask), sc->nodemask) {
2412 if (!populated_zone(zone))
2413 continue;
2414 /*
2415 * Take care memory controller reclaiming has small influence
2416 * to global LRU.
2417 */
2418 if (global_reclaim(sc)) {
2419 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
2420 continue;
2421 if (zone->all_unreclaimable &&
2422 sc->priority != DEF_PRIORITY)
2423 continue; /* Let kswapd poll it */
2424 if (IS_ENABLED(CONFIG_COMPACTION)) {
2425 /*
2426 * If we already have plenty of memory free for
2427 * compaction in this zone, don't free any more.
2428 * Even though compaction is invoked for any
2429 * non-zero order, only frequent costly order
2430 * reclamation is disruptive enough to become a
2431 * noticeable problem, like transparent huge
2432 * page allocations.
2433 */
2434 if (compaction_ready(zone, sc)) {
2435 aborted_reclaim = true;
2436 continue;
2437 }
2438 }
2439 /*
2440 * This steals pages from memory cgroups over softlimit
2441 * and returns the number of reclaimed pages and
2442 * scanned pages. This works for global memory pressure
2443 * and balancing, not for a memcg's limit.
2444 */
2445 nr_soft_scanned = 0;
2446 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
2447 sc->order, sc->gfp_mask,
2448 &nr_soft_scanned);
2449 sc->nr_reclaimed += nr_soft_reclaimed;
2450 sc->nr_scanned += nr_soft_scanned;
2451 /* need some check for avoid more shrink_zone() */
2452 }
2453
2454 shrink_zone(zone, sc);
2455 }
2456
2457 return aborted_reclaim;
2458}
2459
2460/* All zones in zonelist are unreclaimable? */
2461static bool all_unreclaimable(struct zonelist *zonelist,
2462 struct scan_control *sc)
2463{
2464 struct zoneref *z;
2465 struct zone *zone;
2466
2467 for_each_zone_zonelist_nodemask(zone, z, zonelist,
2468 gfp_zone(sc->gfp_mask), sc->nodemask) {
2469 if (!populated_zone(zone))
2470 continue;
2471 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
2472 continue;
2473 if (!zone->all_unreclaimable)
2474 return false;
2475 }
2476
2477 return true;
2478}
2479
2480/*
2481 * This is the main entry point to direct page reclaim.
2482 *
2483 * If a full scan of the inactive list fails to free enough memory then we
2484 * are "out of memory" and something needs to be killed.
2485 *
2486 * If the caller is !__GFP_FS then the probability of a failure is reasonably
2487 * high - the zone may be full of dirty or under-writeback pages, which this
2488 * caller can't do much about. We kick the writeback threads and take explicit
2489 * naps in the hope that some of these pages can be written. But if the
2490 * allocating task holds filesystem locks which prevent writeout this might not
2491 * work, and the allocation attempt will fail.
2492 *
2493 * returns: 0, if no pages reclaimed
2494 * else, the number of pages reclaimed
2495 */
2496static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
2497 struct scan_control *sc,
2498 struct shrink_control *shrink)
2499{
2500 unsigned long total_scanned = 0;
2501 struct reclaim_state *reclaim_state = current->reclaim_state;
2502 struct zoneref *z;
2503 struct zone *zone;
2504 unsigned long writeback_threshold;
2505 bool aborted_reclaim;
2506
2507 delayacct_freepages_start();
2508
2509 if (global_reclaim(sc))
2510 count_vm_event(ALLOCSTALL);
2511
2512 do {
2513 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
2514 sc->priority);
2515 sc->nr_scanned = 0;
2516 aborted_reclaim = shrink_zones(zonelist, sc);
2517
2518 /*
2519 * Don't shrink slabs when reclaiming memory from over limit
2520 * cgroups but do shrink slab at least once when aborting
2521 * reclaim for compaction to avoid unevenly scanning file/anon
2522 * LRU pages over slab pages.
2523 */
2524 if (global_reclaim(sc)) {
2525 unsigned long lru_pages = 0;
2526 for_each_zone_zonelist(zone, z, zonelist,
2527 gfp_zone(sc->gfp_mask)) {
2528 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
2529 continue;
2530
2531 lru_pages += zone_reclaimable_pages(zone);
2532 }
2533
2534 shrink_slab(shrink, sc->nr_scanned, lru_pages);
2535 if (reclaim_state) {
2536 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
2537 reclaim_state->reclaimed_slab = 0;
2538 }
2539 }
2540 total_scanned += sc->nr_scanned;
2541 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
2542 goto out;
2543
2544 /*
2545 * If we're getting trouble reclaiming, start doing
2546 * writepage even in laptop mode.
2547 */
2548 if (sc->priority < DEF_PRIORITY - 2)
2549 sc->may_writepage = 1;
2550
2551 /*
2552 * Try to write back as many pages as we just scanned. This
2553 * tends to cause slow streaming writers to write data to the
2554 * disk smoothly, at the dirtying rate, which is nice. But
2555 * that's undesirable in laptop mode, where we *want* lumpy
2556 * writeout. So in laptop mode, write out the whole world.
2557 */
2558 writeback_threshold = sc->nr_to_reclaim + sc->nr_to_reclaim / 2;
2559 if (total_scanned > writeback_threshold) {
2560 wakeup_flusher_threads(laptop_mode ? 0 : total_scanned,
2561 WB_REASON_TRY_TO_FREE_PAGES);
2562 sc->may_writepage = 1;
2563 }
2564 } while (--sc->priority >= 0 && !aborted_reclaim);
2565
2566out:
2567 delayacct_freepages_end();
2568
2569 if (sc->nr_reclaimed)
2570 return sc->nr_reclaimed;
2571
2572 /*
2573 * As hibernation is going on, kswapd is freezed so that it can't mark
2574 * the zone into all_unreclaimable. Thus bypassing all_unreclaimable
2575 * check.
2576 */
2577 if (oom_killer_disabled)
2578 return 0;
2579
2580 /* Aborted reclaim to try compaction? don't OOM, then */
2581 if (aborted_reclaim)
2582 return 1;
2583
2584 /* top priority shrink_zones still had more to do? don't OOM, then */
2585 if (global_reclaim(sc) && !all_unreclaimable(zonelist, sc))
2586 return 1;
2587
2588 return 0;
2589}
2590
2591static bool pfmemalloc_watermark_ok(pg_data_t *pgdat)
2592{
2593 struct zone *zone;
2594 unsigned long pfmemalloc_reserve = 0;
2595 unsigned long free_pages = 0;
2596 int i;
2597 bool wmark_ok;
2598
2599 for (i = 0; i <= ZONE_NORMAL; i++) {
2600 zone = &pgdat->node_zones[i];
2601 if (!populated_zone(zone))
2602 continue;
2603
2604 pfmemalloc_reserve += min_wmark_pages(zone);
2605 free_pages += zone_page_state(zone, NR_FREE_PAGES);
2606 }
2607
2608 /* If there are no reserves (unexpected config) then do not throttle */
2609 if (!pfmemalloc_reserve)
2610 return true;
2611
2612 wmark_ok = free_pages > pfmemalloc_reserve / 2;
2613
2614 /* kswapd must be awake if processes are being throttled */
2615 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
2616 pgdat->classzone_idx = min(pgdat->classzone_idx,
2617 (enum zone_type)ZONE_NORMAL);
2618 wake_up_interruptible(&pgdat->kswapd_wait);
2619 }
2620
2621 return wmark_ok;
2622}
2623
2624/*
2625 * Throttle direct reclaimers if backing storage is backed by the network
2626 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
2627 * depleted. kswapd will continue to make progress and wake the processes
2628 * when the low watermark is reached.
2629 *
2630 * Returns true if a fatal signal was delivered during throttling. If this
2631 * happens, the page allocator should not consider triggering the OOM killer.
2632 */
2633static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
2634 nodemask_t *nodemask)
2635{
2636 struct zoneref *z;
2637 struct zone *zone;
2638 pg_data_t *pgdat = NULL;
2639
2640 /*
2641 * Kernel threads should not be throttled as they may be indirectly
2642 * responsible for cleaning pages necessary for reclaim to make forward
2643 * progress. kjournald for example may enter direct reclaim while
2644 * committing a transaction where throttling it could forcing other
2645 * processes to block on log_wait_commit().
2646 */
2647 if (current->flags & PF_KTHREAD)
2648 goto out;
2649
2650 /*
2651 * If a fatal signal is pending, this process should not throttle.
2652 * It should return quickly so it can exit and free its memory
2653 */
2654 if (fatal_signal_pending(current))
2655 goto out;
2656
2657 /*
2658 * Check if the pfmemalloc reserves are ok by finding the first node
2659 * with a usable ZONE_NORMAL or lower zone. The expectation is that
2660 * GFP_KERNEL will be required for allocating network buffers when
2661 * swapping over the network so ZONE_HIGHMEM is unusable.
2662 *
2663 * Throttling is based on the first usable node and throttled processes
2664 * wait on a queue until kswapd makes progress and wakes them. There
2665 * is an affinity then between processes waking up and where reclaim
2666 * progress has been made assuming the process wakes on the same node.
2667 * More importantly, processes running on remote nodes will not compete
2668 * for remote pfmemalloc reserves and processes on different nodes
2669 * should make reasonable progress.
2670 */
2671 for_each_zone_zonelist_nodemask(zone, z, zonelist,
2672 gfp_mask, nodemask) {
2673 if (zone_idx(zone) > ZONE_NORMAL)
2674 continue;
2675
2676 /* Throttle based on the first usable node */
2677 pgdat = zone->zone_pgdat;
2678 if (pfmemalloc_watermark_ok(pgdat))
2679 goto out;
2680 break;
2681 }
2682
2683 /* If no zone was usable by the allocation flags then do not throttle */
2684 if (!pgdat)
2685 goto out;
2686
2687 /* Account for the throttling */
2688 count_vm_event(PGSCAN_DIRECT_THROTTLE);
2689
2690 /*
2691 * If the caller cannot enter the filesystem, it's possible that it
2692 * is due to the caller holding an FS lock or performing a journal
2693 * transaction in the case of a filesystem like ext[3|4]. In this case,
2694 * it is not safe to block on pfmemalloc_wait as kswapd could be
2695 * blocked waiting on the same lock. Instead, throttle for up to a
2696 * second before continuing.
2697 */
2698 if (!(gfp_mask & __GFP_FS)) {
2699 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
2700 pfmemalloc_watermark_ok(pgdat), HZ);
2701
2702 goto check_pending;
2703 }
2704
2705 /* Throttle until kswapd wakes the process */
2706 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
2707 pfmemalloc_watermark_ok(pgdat));
2708
2709check_pending:
2710 if (fatal_signal_pending(current))
2711 return true;
2712
2713out:
2714 return false;
2715}
2716
2717unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
2718 gfp_t gfp_mask, nodemask_t *nodemask)
2719{
2720 unsigned long nr_reclaimed;
2721 struct scan_control sc = {
2722 .gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
2723 .may_writepage = !laptop_mode,
2724 .nr_to_reclaim = SWAP_CLUSTER_MAX,
2725 .may_unmap = 1,
2726 .may_swap = 1,
2727 .order = order,
2728 .priority = DEF_PRIORITY,
2729 .target_mem_cgroup = NULL,
2730 .nodemask = nodemask,
2731 };
2732 struct shrink_control shrink = {
2733 .gfp_mask = sc.gfp_mask,
2734 };
2735
2736 /*
2737 * Do not enter reclaim if fatal signal was delivered while throttled.
2738 * 1 is returned so that the page allocator does not OOM kill at this
2739 * point.
2740 */
2741 if (throttle_direct_reclaim(gfp_mask, zonelist, nodemask))
2742 return 1;
2743
2744 trace_mm_vmscan_direct_reclaim_begin(order,
2745 sc.may_writepage,
2746 gfp_mask);
2747
2748 nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
2749
2750 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
2751
2752 return nr_reclaimed;
2753}
2754
2755#ifdef CONFIG_MEMCG
2756
2757unsigned long mem_cgroup_shrink_node_zone(struct mem_cgroup *memcg,
2758 gfp_t gfp_mask, bool noswap,
2759 struct zone *zone,
2760 unsigned long *nr_scanned)
2761{
2762 struct scan_control sc = {
2763 .nr_scanned = 0,
2764 .nr_to_reclaim = SWAP_CLUSTER_MAX,
2765 .may_writepage = !laptop_mode,
2766 .may_unmap = 1,
2767 .may_swap = !noswap,
2768 .order = 0,
2769 .priority = 0,
2770 .target_mem_cgroup = memcg,
2771 };
2772 struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
2773
2774 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
2775 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
2776
2777 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
2778 sc.may_writepage,
2779 sc.gfp_mask);
2780
2781 /*
2782 * NOTE: Although we can get the priority field, using it
2783 * here is not a good idea, since it limits the pages we can scan.
2784 * if we don't reclaim here, the shrink_zone from balance_pgdat
2785 * will pick up pages from other mem cgroup's as well. We hack
2786 * the priority and make it zero.
2787 */
2788 shrink_lruvec(lruvec, &sc);
2789
2790 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
2791
2792 *nr_scanned = sc.nr_scanned;
2793 return sc.nr_reclaimed;
2794}
2795
2796unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
2797 gfp_t gfp_mask,
2798 bool noswap)
2799{
2800 struct zonelist *zonelist;
2801 unsigned long nr_reclaimed;
2802 int nid;
2803 struct scan_control sc = {
2804 .may_writepage = !laptop_mode,
2805 .may_unmap = 1,
2806 .may_swap = !noswap,
2807 .nr_to_reclaim = SWAP_CLUSTER_MAX,
2808 .order = 0,
2809 .priority = DEF_PRIORITY,
2810 .target_mem_cgroup = memcg,
2811 .nodemask = NULL, /* we don't care the placement */
2812 .gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
2813 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
2814 };
2815 struct shrink_control shrink = {
2816 .gfp_mask = sc.gfp_mask,
2817 };
2818
2819 /*
2820 * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
2821 * take care of from where we get pages. So the node where we start the
2822 * scan does not need to be the current node.
2823 */
2824 nid = mem_cgroup_select_victim_node(memcg);
2825
2826 zonelist = NODE_DATA(nid)->node_zonelists;
2827
2828 trace_mm_vmscan_memcg_reclaim_begin(0,
2829 sc.may_writepage,
2830 sc.gfp_mask);
2831
2832 current->flags |= PF_MEMALLOC;
2833 nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
2834 current->flags &= ~PF_MEMALLOC;
2835
2836 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
2837
2838 return nr_reclaimed;
2839}
2840#endif
2841
2842static void age_active_anon(struct zone *zone, struct scan_control *sc)
2843{
2844 struct mem_cgroup *memcg;
2845
2846 if (!total_swap_pages)
2847 return;
2848
2849 memcg = mem_cgroup_iter(NULL, NULL, NULL);
2850 do {
2851 struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
2852
2853 if (inactive_anon_is_low(lruvec))
2854 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
2855 sc, LRU_ACTIVE_ANON);
2856
2857 memcg = mem_cgroup_iter(NULL, memcg, NULL);
2858 } while (memcg);
2859}
2860
2861static bool zone_balanced(struct zone *zone, int order,
2862 unsigned long balance_gap, int classzone_idx)
2863{
2864 if (!zone_watermark_ok_safe(zone, order, high_wmark_pages(zone) +
2865 balance_gap, classzone_idx, 0))
2866 return false;
2867
2868 if (IS_ENABLED(CONFIG_COMPACTION) && order &&
2869 !compaction_suitable(zone, order))
2870 return false;
2871
2872 return true;
2873}
2874
2875/*
2876 * pgdat_balanced() is used when checking if a node is balanced.
2877 *
2878 * For order-0, all zones must be balanced!
2879 *
2880 * For high-order allocations only zones that meet watermarks and are in a
2881 * zone allowed by the callers classzone_idx are added to balanced_pages. The
2882 * total of balanced pages must be at least 25% of the zones allowed by
2883 * classzone_idx for the node to be considered balanced. Forcing all zones to
2884 * be balanced for high orders can cause excessive reclaim when there are
2885 * imbalanced zones.
2886 * The choice of 25% is due to
2887 * o a 16M DMA zone that is balanced will not balance a zone on any
2888 * reasonable sized machine
2889 * o On all other machines, the top zone must be at least a reasonable
2890 * percentage of the middle zones. For example, on 32-bit x86, highmem
2891 * would need to be at least 256M for it to be balance a whole node.
2892 * Similarly, on x86-64 the Normal zone would need to be at least 1G
2893 * to balance a node on its own. These seemed like reasonable ratios.
2894 */
2895static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx)
2896{
2897 unsigned long managed_pages = 0;
2898 unsigned long balanced_pages = 0;
2899 int i;
2900
2901 /* Check the watermark levels */
2902 for (i = 0; i <= classzone_idx; i++) {
2903 struct zone *zone = pgdat->node_zones + i;
2904
2905 if (!populated_zone(zone))
2906 continue;
2907
2908 managed_pages += zone->managed_pages;
2909
2910 /*
2911 * A special case here:
2912 *
2913 * balance_pgdat() skips over all_unreclaimable after
2914 * DEF_PRIORITY. Effectively, it considers them balanced so
2915 * they must be considered balanced here as well!
2916 */
2917 if (zone->all_unreclaimable) {
2918 balanced_pages += zone->managed_pages;
2919 continue;
2920 }
2921
2922 if (zone_balanced(zone, order, 0, i))
2923 balanced_pages += zone->managed_pages;
2924 else if (!order)
2925 return false;
2926 }
2927
2928 if (order)
2929 return balanced_pages >= (managed_pages >> 2);
2930 else
2931 return true;
2932}
2933
2934/*
2935 * Prepare kswapd for sleeping. This verifies that there are no processes
2936 * waiting in throttle_direct_reclaim() and that watermarks have been met.
2937 *
2938 * Returns true if kswapd is ready to sleep
2939 */
2940static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, long remaining,
2941 int classzone_idx)
2942{
2943 /* If a direct reclaimer woke kswapd within HZ/10, it's premature */
2944 if (remaining)
2945 return false;
2946
2947 /*
2948 * There is a potential race between when kswapd checks its watermarks
2949 * and a process gets throttled. There is also a potential race if
2950 * processes get throttled, kswapd wakes, a large process exits therby
2951 * balancing the zones that causes kswapd to miss a wakeup. If kswapd
2952 * is going to sleep, no process should be sleeping on pfmemalloc_wait
2953 * so wake them now if necessary. If necessary, processes will wake
2954 * kswapd and get throttled again
2955 */
2956 if (waitqueue_active(&pgdat->pfmemalloc_wait)) {
2957 wake_up(&pgdat->pfmemalloc_wait);
2958 return false;
2959 }
2960
2961 return pgdat_balanced(pgdat, order, classzone_idx);
2962}
2963
2964/*
2965 * kswapd shrinks the zone by the number of pages required to reach
2966 * the high watermark.
2967 *
2968 * Returns true if kswapd scanned at least the requested number of pages to
2969 * reclaim or if the lack of progress was due to pages under writeback.
2970 * This is used to determine if the scanning priority needs to be raised.
2971 */
2972static bool kswapd_shrink_zone(struct zone *zone,
2973 int classzone_idx,
2974 struct scan_control *sc,
2975 unsigned long lru_pages,
2976 unsigned long *nr_attempted)
2977{
2978 unsigned long nr_slab;
2979 int testorder = sc->order;
2980 unsigned long balance_gap;
2981 struct reclaim_state *reclaim_state = current->reclaim_state;
2982 struct shrink_control shrink = {
2983 .gfp_mask = sc->gfp_mask,
2984 };
2985 bool lowmem_pressure;
2986
2987 /* Reclaim above the high watermark. */
2988 sc->nr_to_reclaim = max(SWAP_CLUSTER_MAX, high_wmark_pages(zone));
2989
2990 /*
2991 * Kswapd reclaims only single pages with compaction enabled. Trying
2992 * too hard to reclaim until contiguous free pages have become
2993 * available can hurt performance by evicting too much useful data
2994 * from memory. Do not reclaim more than needed for compaction.
2995 */
2996 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
2997 compaction_suitable(zone, sc->order) !=
2998 COMPACT_SKIPPED)
2999 testorder = 0;
3000
3001 /*
3002 * We put equal pressure on every zone, unless one zone has way too
3003 * many pages free already. The "too many pages" is defined as the
3004 * high wmark plus a "gap" where the gap is either the low
3005 * watermark or 1% of the zone, whichever is smaller.
3006 */
3007 balance_gap = min(low_wmark_pages(zone),
3008 (zone->managed_pages + KSWAPD_ZONE_BALANCE_GAP_RATIO-1) /
3009 KSWAPD_ZONE_BALANCE_GAP_RATIO);
3010
3011 /*
3012 * If there is no low memory pressure or the zone is balanced then no
3013 * reclaim is necessary
3014 */
3015 lowmem_pressure = (buffer_heads_over_limit && is_highmem(zone));
3016 if (!lowmem_pressure && zone_balanced(zone, testorder,
3017 balance_gap, classzone_idx))
3018 return true;
3019
3020 shrink_zone(zone, sc);
3021
3022 reclaim_state->reclaimed_slab = 0;
3023 nr_slab = shrink_slab(&shrink, sc->nr_scanned, lru_pages);
3024 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
3025
3026 /* Account for the number of pages attempted to reclaim */
3027 *nr_attempted += sc->nr_to_reclaim;
3028
3029 if (nr_slab == 0 && !zone_reclaimable(zone))
3030 zone->all_unreclaimable = 1;
3031
3032 zone_clear_flag(zone, ZONE_WRITEBACK);
3033
3034 /*
3035 * If a zone reaches its high watermark, consider it to be no longer
3036 * congested. It's possible there are dirty pages backed by congested
3037 * BDIs but as pressure is relieved, speculatively avoid congestion
3038 * waits.
3039 */
3040 if (!zone->all_unreclaimable &&
3041 zone_balanced(zone, testorder, 0, classzone_idx)) {
3042 zone_clear_flag(zone, ZONE_CONGESTED);
3043 zone_clear_flag(zone, ZONE_TAIL_LRU_DIRTY);
3044 }
3045
3046 return sc->nr_scanned >= sc->nr_to_reclaim;
3047}
3048
3049/*
3050 * For kswapd, balance_pgdat() will work across all this node's zones until
3051 * they are all at high_wmark_pages(zone).
3052 *
3053 * Returns the final order kswapd was reclaiming at
3054 *
3055 * There is special handling here for zones which are full of pinned pages.
3056 * This can happen if the pages are all mlocked, or if they are all used by
3057 * device drivers (say, ZONE_DMA). Or if they are all in use by hugetlb.
3058 * What we do is to detect the case where all pages in the zone have been
3059 * scanned twice and there has been zero successful reclaim. Mark the zone as
3060 * dead and from now on, only perform a short scan. Basically we're polling
3061 * the zone for when the problem goes away.
3062 *
3063 * kswapd scans the zones in the highmem->normal->dma direction. It skips
3064 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
3065 * found to have free_pages <= high_wmark_pages(zone), we scan that zone and the
3066 * lower zones regardless of the number of free pages in the lower zones. This
3067 * interoperates with the page allocator fallback scheme to ensure that aging
3068 * of pages is balanced across the zones.
3069 */
3070static unsigned long balance_pgdat(pg_data_t *pgdat, int order,
3071 int *classzone_idx)
3072{
3073 int i;
3074 int end_zone = 0; /* Inclusive. 0 = ZONE_DMA */
3075 unsigned long nr_soft_reclaimed;
3076 unsigned long nr_soft_scanned;
3077 struct scan_control sc = {
3078 .gfp_mask = GFP_KERNEL,
3079 .priority = DEF_PRIORITY,
3080 .may_unmap = 1,
3081 .may_swap = 1,
3082 .may_writepage = !laptop_mode,
3083 .order = order,
3084 .target_mem_cgroup = NULL,
3085 };
3086 count_vm_event(PAGEOUTRUN);
3087
3088 do {
3089 unsigned long lru_pages = 0;
3090 unsigned long nr_attempted = 0;
3091 bool raise_priority = true;
3092 bool pgdat_needs_compaction = (order > 0);
3093
3094 sc.nr_reclaimed = 0;
3095
3096 /*
3097 * Scan in the highmem->dma direction for the highest
3098 * zone which needs scanning
3099 */
3100 for (i = pgdat->nr_zones - 1; i >= 0; i--) {
3101 struct zone *zone = pgdat->node_zones + i;
3102
3103 if (!populated_zone(zone))
3104 continue;
3105
3106 if (zone->all_unreclaimable &&
3107 sc.priority != DEF_PRIORITY)
3108 continue;
3109
3110 /*
3111 * Do some background aging of the anon list, to give
3112 * pages a chance to be referenced before reclaiming.
3113 */
3114 age_active_anon(zone, &sc);
3115
3116 /*
3117 * If the number of buffer_heads in the machine
3118 * exceeds the maximum allowed level and this node
3119 * has a highmem zone, force kswapd to reclaim from
3120 * it to relieve lowmem pressure.
3121 */
3122 if (buffer_heads_over_limit && is_highmem_idx(i)) {
3123 end_zone = i;
3124 break;
3125 }
3126
3127 if (!zone_balanced(zone, order, 0, 0)) {
3128 end_zone = i;
3129 break;
3130 } else {
3131 /*
3132 * If balanced, clear the dirty and congested
3133 * flags
3134 */
3135 zone_clear_flag(zone, ZONE_CONGESTED);
3136 zone_clear_flag(zone, ZONE_TAIL_LRU_DIRTY);
3137 }
3138 }
3139
3140 if (i < 0)
3141 goto out;
3142
3143 for (i = 0; i <= end_zone; i++) {
3144 struct zone *zone = pgdat->node_zones + i;
3145
3146 if (!populated_zone(zone))
3147 continue;
3148
3149 lru_pages += zone_reclaimable_pages(zone);
3150
3151 /*
3152 * If any zone is currently balanced then kswapd will
3153 * not call compaction as it is expected that the
3154 * necessary pages are already available.
3155 */
3156 if (pgdat_needs_compaction &&
3157 zone_watermark_ok(zone, order,
3158 low_wmark_pages(zone),
3159 *classzone_idx, 0))
3160 pgdat_needs_compaction = false;
3161 }
3162
3163 /*
3164 * If we're getting trouble reclaiming, start doing writepage
3165 * even in laptop mode.
3166 */
3167 if (sc.priority < DEF_PRIORITY - 2)
3168 sc.may_writepage = 1;
3169
3170 /*
3171 * Now scan the zone in the dma->highmem direction, stopping
3172 * at the last zone which needs scanning.
3173 *
3174 * We do this because the page allocator works in the opposite
3175 * direction. This prevents the page allocator from allocating
3176 * pages behind kswapd's direction of progress, which would
3177 * cause too much scanning of the lower zones.
3178 */
3179 for (i = 0; i <= end_zone; i++) {
3180 struct zone *zone = pgdat->node_zones + i;
3181
3182 if (!populated_zone(zone))
3183 continue;
3184
3185 if (zone->all_unreclaimable &&
3186 sc.priority != DEF_PRIORITY)
3187 continue;
3188
3189 sc.nr_scanned = 0;
3190
3191 nr_soft_scanned = 0;
3192 /*
3193 * Call soft limit reclaim before calling shrink_zone.
3194 */
3195 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
3196 order, sc.gfp_mask,
3197 &nr_soft_scanned);
3198 sc.nr_reclaimed += nr_soft_reclaimed;
3199
3200 /*
3201 * There should be no need to raise the scanning
3202 * priority if enough pages are already being scanned
3203 * that that high watermark would be met at 100%
3204 * efficiency.
3205 */
3206 if (kswapd_shrink_zone(zone, end_zone, &sc,
3207 lru_pages, &nr_attempted))
3208 raise_priority = false;
3209 }
3210
3211 /*
3212 * If the low watermark is met there is no need for processes
3213 * to be throttled on pfmemalloc_wait as they should not be
3214 * able to safely make forward progress. Wake them
3215 */
3216 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
3217 pfmemalloc_watermark_ok(pgdat))
3218 wake_up(&pgdat->pfmemalloc_wait);
3219
3220 /*
3221 * Fragmentation may mean that the system cannot be rebalanced
3222 * for high-order allocations in all zones. If twice the
3223 * allocation size has been reclaimed and the zones are still
3224 * not balanced then recheck the watermarks at order-0 to
3225 * prevent kswapd reclaiming excessively. Assume that a
3226 * process requested a high-order can direct reclaim/compact.
3227 */
3228 if (order && sc.nr_reclaimed >= 2UL << order)
3229 order = sc.order = 0;
3230
3231 /* Check if kswapd should be suspending */
3232 if (try_to_freeze() || kthread_should_stop())
3233 break;
3234
3235 /*
3236 * Compact if necessary and kswapd is reclaiming at least the
3237 * high watermark number of pages as requsted
3238 */
3239 if (pgdat_needs_compaction && sc.nr_reclaimed > nr_attempted)
3240 compact_pgdat(pgdat, order);
3241
3242 /*
3243 * Raise priority if scanning rate is too low or there was no
3244 * progress in reclaiming pages
3245 */
3246 if (raise_priority || !sc.nr_reclaimed)
3247 sc.priority--;
3248 } while (sc.priority >= 1 &&
3249 !pgdat_balanced(pgdat, order, *classzone_idx));
3250
3251out:
3252 /*
3253 * Return the order we were reclaiming at so prepare_kswapd_sleep()
3254 * makes a decision on the order we were last reclaiming at. However,
3255 * if another caller entered the allocator slow path while kswapd
3256 * was awake, order will remain at the higher level
3257 */
3258 *classzone_idx = end_zone;
3259 return order;
3260}
3261
3262static void kswapd_try_to_sleep(pg_data_t *pgdat, int order, int classzone_idx)
3263{
3264 long remaining = 0;
3265 DEFINE_WAIT(wait);
3266
3267 if (freezing(current) || kthread_should_stop())
3268 return;
3269
3270 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3271
3272 /* Try to sleep for a short interval */
3273 if (prepare_kswapd_sleep(pgdat, order, remaining, classzone_idx)) {
3274 remaining = schedule_timeout(HZ/10);
3275 finish_wait(&pgdat->kswapd_wait, &wait);
3276 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3277 }
3278
3279 /*
3280 * After a short sleep, check if it was a premature sleep. If not, then
3281 * go fully to sleep until explicitly woken up.
3282 */
3283 if (prepare_kswapd_sleep(pgdat, order, remaining, classzone_idx)) {
3284 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3285
3286 /*
3287 * vmstat counters are not perfectly accurate and the estimated
3288 * value for counters such as NR_FREE_PAGES can deviate from the
3289 * true value by nr_online_cpus * threshold. To avoid the zone
3290 * watermarks being breached while under pressure, we reduce the
3291 * per-cpu vmstat threshold while kswapd is awake and restore
3292 * them before going back to sleep.
3293 */
3294 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
3295
3296 /*
3297 * Compaction records what page blocks it recently failed to
3298 * isolate pages from and skips them in the future scanning.
3299 * When kswapd is going to sleep, it is reasonable to assume
3300 * that pages and compaction may succeed so reset the cache.
3301 */
3302 reset_isolation_suitable(pgdat);
3303
3304 if (!kthread_should_stop())
3305 schedule();
3306
3307 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3308 } else {
3309 if (remaining)
3310 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3311 else
3312 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3313 }
3314 finish_wait(&pgdat->kswapd_wait, &wait);
3315}
3316
3317/*
3318 * The background pageout daemon, started as a kernel thread
3319 * from the init process.
3320 *
3321 * This basically trickles out pages so that we have _some_
3322 * free memory available even if there is no other activity
3323 * that frees anything up. This is needed for things like routing
3324 * etc, where we otherwise might have all activity going on in
3325 * asynchronous contexts that cannot page things out.
3326 *
3327 * If there are applications that are active memory-allocators
3328 * (most normal use), this basically shouldn't matter.
3329 */
3330static int kswapd(void *p)
3331{
3332 unsigned long order, new_order;
3333 unsigned balanced_order;
3334 int classzone_idx, new_classzone_idx;
3335 int balanced_classzone_idx;
3336 pg_data_t *pgdat = (pg_data_t*)p;
3337 struct task_struct *tsk = current;
3338
3339 struct reclaim_state reclaim_state = {
3340 .reclaimed_slab = 0,
3341 };
3342 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
3343
3344 lockdep_set_current_reclaim_state(GFP_KERNEL);
3345
3346 if (!cpumask_empty(cpumask))
3347 set_cpus_allowed_ptr(tsk, cpumask);
3348 current->reclaim_state = &reclaim_state;
3349
3350 /*
3351 * Tell the memory management that we're a "memory allocator",
3352 * and that if we need more memory we should get access to it
3353 * regardless (see "__alloc_pages()"). "kswapd" should
3354 * never get caught in the normal page freeing logic.
3355 *
3356 * (Kswapd normally doesn't need memory anyway, but sometimes
3357 * you need a small amount of memory in order to be able to
3358 * page out something else, and this flag essentially protects
3359 * us from recursively trying to free more memory as we're
3360 * trying to free the first piece of memory in the first place).
3361 */
3362 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
3363 set_freezable();
3364
3365 order = new_order = 0;
3366 balanced_order = 0;
3367 classzone_idx = new_classzone_idx = pgdat->nr_zones - 1;
3368 balanced_classzone_idx = classzone_idx;
3369 for ( ; ; ) {
3370 bool ret;
3371
3372 /*
3373 * If the last balance_pgdat was unsuccessful it's unlikely a
3374 * new request of a similar or harder type will succeed soon
3375 * so consider going to sleep on the basis we reclaimed at
3376 */
3377 if (balanced_classzone_idx >= new_classzone_idx &&
3378 balanced_order == new_order) {
3379 new_order = pgdat->kswapd_max_order;
3380 new_classzone_idx = pgdat->classzone_idx;
3381 pgdat->kswapd_max_order = 0;
3382 pgdat->classzone_idx = pgdat->nr_zones - 1;
3383 }
3384
3385 if (order < new_order || classzone_idx > new_classzone_idx) {
3386 /*
3387 * Don't sleep if someone wants a larger 'order'
3388 * allocation or has tigher zone constraints
3389 */
3390 order = new_order;
3391 classzone_idx = new_classzone_idx;
3392 } else {
3393 kswapd_try_to_sleep(pgdat, balanced_order,
3394 balanced_classzone_idx);
3395 order = pgdat->kswapd_max_order;
3396 classzone_idx = pgdat->classzone_idx;
3397 new_order = order;
3398 new_classzone_idx = classzone_idx;
3399 pgdat->kswapd_max_order = 0;
3400 pgdat->classzone_idx = pgdat->nr_zones - 1;
3401 }
3402
3403 ret = try_to_freeze();
3404 if (kthread_should_stop())
3405 break;
3406
3407 /*
3408 * We can speed up thawing tasks if we don't call balance_pgdat
3409 * after returning from the refrigerator
3410 */
3411 if (!ret) {
3412 trace_mm_vmscan_kswapd_wake(pgdat->node_id, order);
3413 balanced_classzone_idx = classzone_idx;
3414 balanced_order = balance_pgdat(pgdat, order,
3415 &balanced_classzone_idx);
3416 }
3417 }
3418
3419 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
3420 current->reclaim_state = NULL;
3421 lockdep_clear_current_reclaim_state();
3422
3423 return 0;
3424}
3425
3426/*
3427 * A zone is low on free memory, so wake its kswapd task to service it.
3428 */
3429void wakeup_kswapd(struct zone *zone, int order, enum zone_type classzone_idx)
3430{
3431 pg_data_t *pgdat;
3432
3433 if (!populated_zone(zone))
3434 return;
3435
3436 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
3437 return;
3438 pgdat = zone->zone_pgdat;
3439 if (pgdat->kswapd_max_order < order) {
3440 pgdat->kswapd_max_order = order;
3441 pgdat->classzone_idx = min(pgdat->classzone_idx, classzone_idx);
3442 }
3443 if (!waitqueue_active(&pgdat->kswapd_wait))
3444 return;
3445 if (zone_watermark_ok_safe(zone, order, low_wmark_pages(zone), 0, 0))
3446 return;
3447
3448 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, zone_idx(zone), order);
3449 wake_up_interruptible(&pgdat->kswapd_wait);
3450}
3451
3452#ifdef CONFIG_HIBERNATION
3453/*
3454 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
3455 * freed pages.
3456 *
3457 * Rather than trying to age LRUs the aim is to preserve the overall
3458 * LRU order by reclaiming preferentially
3459 * inactive > active > active referenced > active mapped
3460 */
3461unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
3462{
3463 struct reclaim_state reclaim_state;
3464 struct scan_control sc = {
3465 .gfp_mask = GFP_HIGHUSER_MOVABLE,
3466 .may_swap = 1,
3467 .may_unmap = 1,
3468 .may_writepage = 1,
3469 .nr_to_reclaim = nr_to_reclaim,
3470 .hibernation_mode = 1,
3471 .order = 0,
3472 .priority = DEF_PRIORITY,
3473 };
3474 struct shrink_control shrink = {
3475 .gfp_mask = sc.gfp_mask,
3476 };
3477 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
3478 struct task_struct *p = current;
3479 unsigned long nr_reclaimed;
3480
3481 p->flags |= PF_MEMALLOC;
3482 lockdep_set_current_reclaim_state(sc.gfp_mask);
3483 reclaim_state.reclaimed_slab = 0;
3484 p->reclaim_state = &reclaim_state;
3485
3486 nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
3487
3488 p->reclaim_state = NULL;
3489 lockdep_clear_current_reclaim_state();
3490 p->flags &= ~PF_MEMALLOC;
3491
3492 return nr_reclaimed;
3493}
3494#endif /* CONFIG_HIBERNATION */
3495
3496/* It's optimal to keep kswapds on the same CPUs as their memory, but
3497 not required for correctness. So if the last cpu in a node goes
3498 away, we get changed to run anywhere: as the first one comes back,
3499 restore their cpu bindings. */
3500static int cpu_callback(struct notifier_block *nfb, unsigned long action,
3501 void *hcpu)
3502{
3503 int nid;
3504
3505 if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) {
3506 for_each_node_state(nid, N_MEMORY) {
3507 pg_data_t *pgdat = NODE_DATA(nid);
3508 const struct cpumask *mask;
3509
3510 mask = cpumask_of_node(pgdat->node_id);
3511
3512 if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
3513 /* One of our CPUs online: restore mask */
3514 set_cpus_allowed_ptr(pgdat->kswapd, mask);
3515 }
3516 }
3517 return NOTIFY_OK;
3518}
3519
3520/*
3521 * This kswapd start function will be called by init and node-hot-add.
3522 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
3523 */
3524int kswapd_run(int nid)
3525{
3526 pg_data_t *pgdat = NODE_DATA(nid);
3527 int ret = 0;
3528
3529 if (pgdat->kswapd)
3530 return 0;
3531
3532 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
3533 if (IS_ERR(pgdat->kswapd)) {
3534 /* failure at boot is fatal */
3535 BUG_ON(system_state == SYSTEM_BOOTING);
3536 pr_err("Failed to start kswapd on node %d\n", nid);
3537 ret = PTR_ERR(pgdat->kswapd);
3538 pgdat->kswapd = NULL;
3539 }
3540 return ret;
3541}
3542
3543/*
3544 * Called by memory hotplug when all memory in a node is offlined. Caller must
3545 * hold mem_hotplug_begin/end().
3546 */
3547void kswapd_stop(int nid)
3548{
3549 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
3550
3551 if (kswapd) {
3552 kthread_stop(kswapd);
3553 NODE_DATA(nid)->kswapd = NULL;
3554 }
3555}
3556
3557static int __init kswapd_init(void)
3558{
3559 int nid;
3560
3561 swap_setup();
3562 for_each_node_state(nid, N_MEMORY)
3563 kswapd_run(nid);
3564 hotcpu_notifier(cpu_callback, 0);
3565 return 0;
3566}
3567
3568module_init(kswapd_init)
3569
3570#ifdef CONFIG_NUMA
3571/*
3572 * Zone reclaim mode
3573 *
3574 * If non-zero call zone_reclaim when the number of free pages falls below
3575 * the watermarks.
3576 */
3577int zone_reclaim_mode __read_mostly;
3578
3579#define RECLAIM_OFF 0
3580#define RECLAIM_ZONE (1<<0) /* Run shrink_inactive_list on the zone */
3581#define RECLAIM_WRITE (1<<1) /* Writeout pages during reclaim */
3582#define RECLAIM_SWAP (1<<2) /* Swap pages out during reclaim */
3583
3584/*
3585 * Priority for ZONE_RECLAIM. This determines the fraction of pages
3586 * of a node considered for each zone_reclaim. 4 scans 1/16th of
3587 * a zone.
3588 */
3589#define ZONE_RECLAIM_PRIORITY 4
3590
3591/*
3592 * Percentage of pages in a zone that must be unmapped for zone_reclaim to
3593 * occur.
3594 */
3595int sysctl_min_unmapped_ratio = 1;
3596
3597/*
3598 * If the number of slab pages in a zone grows beyond this percentage then
3599 * slab reclaim needs to occur.
3600 */
3601int sysctl_min_slab_ratio = 5;
3602
3603static inline unsigned long zone_unmapped_file_pages(struct zone *zone)
3604{
3605 unsigned long file_mapped = zone_page_state(zone, NR_FILE_MAPPED);
3606 unsigned long file_lru = zone_page_state(zone, NR_INACTIVE_FILE) +
3607 zone_page_state(zone, NR_ACTIVE_FILE);
3608
3609 /*
3610 * It's possible for there to be more file mapped pages than
3611 * accounted for by the pages on the file LRU lists because
3612 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
3613 */
3614 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
3615}
3616
3617/* Work out how many page cache pages we can reclaim in this reclaim_mode */
3618static long zone_pagecache_reclaimable(struct zone *zone)
3619{
3620 long nr_pagecache_reclaimable;
3621 long delta = 0;
3622
3623 /*
3624 * If RECLAIM_SWAP is set, then all file pages are considered
3625 * potentially reclaimable. Otherwise, we have to worry about
3626 * pages like swapcache and zone_unmapped_file_pages() provides
3627 * a better estimate
3628 */
3629 if (zone_reclaim_mode & RECLAIM_SWAP)
3630 nr_pagecache_reclaimable = zone_page_state(zone, NR_FILE_PAGES);
3631 else
3632 nr_pagecache_reclaimable = zone_unmapped_file_pages(zone);
3633
3634 /* If we can't clean pages, remove dirty pages from consideration */
3635 if (!(zone_reclaim_mode & RECLAIM_WRITE))
3636 delta += zone_page_state(zone, NR_FILE_DIRTY);
3637
3638 /* Watch for any possible underflows due to delta */
3639 if (unlikely(delta > nr_pagecache_reclaimable))
3640 delta = nr_pagecache_reclaimable;
3641
3642 return nr_pagecache_reclaimable - delta;
3643}
3644
3645/*
3646 * Try to free up some pages from this zone through reclaim.
3647 */
3648static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
3649{
3650 /* Minimum pages needed in order to stay on node */
3651 const unsigned long nr_pages = 1 << order;
3652 struct task_struct *p = current;
3653 struct reclaim_state reclaim_state;
3654 struct scan_control sc = {
3655 .may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE),
3656 .may_unmap = !!(zone_reclaim_mode & RECLAIM_SWAP),
3657 .may_swap = 1,
3658 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
3659 .gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
3660 .order = order,
3661 .priority = ZONE_RECLAIM_PRIORITY,
3662 };
3663 struct shrink_control shrink = {
3664 .gfp_mask = sc.gfp_mask,
3665 };
3666 unsigned long nr_slab_pages0, nr_slab_pages1;
3667
3668 cond_resched();
3669 /*
3670 * We need to be able to allocate from the reserves for RECLAIM_SWAP
3671 * and we also need to be able to write out pages for RECLAIM_WRITE
3672 * and RECLAIM_SWAP.
3673 */
3674 p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
3675 lockdep_set_current_reclaim_state(gfp_mask);
3676 reclaim_state.reclaimed_slab = 0;
3677 p->reclaim_state = &reclaim_state;
3678
3679 if (zone_pagecache_reclaimable(zone) > zone->min_unmapped_pages) {
3680 /*
3681 * Free memory by calling shrink zone with increasing
3682 * priorities until we have enough memory freed.
3683 */
3684 do {
3685 shrink_zone(zone, &sc);
3686 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
3687 }
3688
3689 nr_slab_pages0 = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
3690 if (nr_slab_pages0 > zone->min_slab_pages) {
3691 /*
3692 * shrink_slab() does not currently allow us to determine how
3693 * many pages were freed in this zone. So we take the current
3694 * number of slab pages and shake the slab until it is reduced
3695 * by the same nr_pages that we used for reclaiming unmapped
3696 * pages.
3697 *
3698 * Note that shrink_slab will free memory on all zones and may
3699 * take a long time.
3700 */
3701 for (;;) {
3702 unsigned long lru_pages = zone_reclaimable_pages(zone);
3703
3704 /* No reclaimable slab or very low memory pressure */
3705 if (!shrink_slab(&shrink, sc.nr_scanned, lru_pages))
3706 break;
3707
3708 /* Freed enough memory */
3709 nr_slab_pages1 = zone_page_state(zone,
3710 NR_SLAB_RECLAIMABLE);
3711 if (nr_slab_pages1 + nr_pages <= nr_slab_pages0)
3712 break;
3713 }
3714
3715 /*
3716 * Update nr_reclaimed by the number of slab pages we
3717 * reclaimed from this zone.
3718 */
3719 nr_slab_pages1 = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
3720 if (nr_slab_pages1 < nr_slab_pages0)
3721 sc.nr_reclaimed += nr_slab_pages0 - nr_slab_pages1;
3722 }
3723
3724 p->reclaim_state = NULL;
3725 current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
3726 lockdep_clear_current_reclaim_state();
3727 return sc.nr_reclaimed >= nr_pages;
3728}
3729
3730int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
3731{
3732 int node_id;
3733 int ret;
3734
3735 /*
3736 * Zone reclaim reclaims unmapped file backed pages and
3737 * slab pages if we are over the defined limits.
3738 *
3739 * A small portion of unmapped file backed pages is needed for
3740 * file I/O otherwise pages read by file I/O will be immediately
3741 * thrown out if the zone is overallocated. So we do not reclaim
3742 * if less than a specified percentage of the zone is used by
3743 * unmapped file backed pages.
3744 */
3745 if (zone_pagecache_reclaimable(zone) <= zone->min_unmapped_pages &&
3746 zone_page_state(zone, NR_SLAB_RECLAIMABLE) <= zone->min_slab_pages)
3747 return ZONE_RECLAIM_FULL;
3748
3749 if (zone->all_unreclaimable)
3750 return ZONE_RECLAIM_FULL;
3751
3752 /*
3753 * Do not scan if the allocation should not be delayed.
3754 */
3755 if (!(gfp_mask & __GFP_WAIT) || (current->flags & PF_MEMALLOC))
3756 return ZONE_RECLAIM_NOSCAN;
3757
3758 /*
3759 * Only run zone reclaim on the local zone or on zones that do not
3760 * have associated processors. This will favor the local processor
3761 * over remote processors and spread off node memory allocations
3762 * as wide as possible.
3763 */
3764 node_id = zone_to_nid(zone);
3765 if (node_state(node_id, N_CPU) && node_id != numa_node_id())
3766 return ZONE_RECLAIM_NOSCAN;
3767
3768 if (zone_test_and_set_flag(zone, ZONE_RECLAIM_LOCKED))
3769 return ZONE_RECLAIM_NOSCAN;
3770
3771 ret = __zone_reclaim(zone, gfp_mask, order);
3772 zone_clear_flag(zone, ZONE_RECLAIM_LOCKED);
3773
3774 if (!ret)
3775 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
3776
3777 return ret;
3778}
3779#endif
3780
3781/*
3782 * page_evictable - test whether a page is evictable
3783 * @page: the page to test
3784 *
3785 * Test whether page is evictable--i.e., should be placed on active/inactive
3786 * lists vs unevictable list.
3787 *
3788 * Reasons page might not be evictable:
3789 * (1) page's mapping marked unevictable
3790 * (2) page is part of an mlocked VMA
3791 *
3792 */
3793int page_evictable(struct page *page)
3794{
3795 return !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
3796}
3797
3798#ifdef CONFIG_SHMEM
3799/**
3800 * check_move_unevictable_pages - check pages for evictability and move to appropriate zone lru list
3801 * @pages: array of pages to check
3802 * @nr_pages: number of pages to check
3803 *
3804 * Checks pages for evictability and moves them to the appropriate lru list.
3805 *
3806 * This function is only used for SysV IPC SHM_UNLOCK.
3807 */
3808void check_move_unevictable_pages(struct page **pages, int nr_pages)
3809{
3810 struct lruvec *lruvec;
3811 struct zone *zone = NULL;
3812 int pgscanned = 0;
3813 int pgrescued = 0;
3814 int i;
3815
3816 for (i = 0; i < nr_pages; i++) {
3817 struct page *page = pages[i];
3818 struct zone *pagezone;
3819
3820 pgscanned++;
3821 pagezone = page_zone(page);
3822 if (pagezone != zone) {
3823 if (zone)
3824 spin_unlock_irq(&zone->lru_lock);
3825 zone = pagezone;
3826 spin_lock_irq(&zone->lru_lock);
3827 }
3828 lruvec = mem_cgroup_page_lruvec(page, zone);
3829
3830 if (!PageLRU(page) || !PageUnevictable(page))
3831 continue;
3832
3833 if (page_evictable(page)) {
3834 enum lru_list lru = page_lru_base_type(page);
3835
3836 VM_BUG_ON_PAGE(PageActive(page), page);
3837 ClearPageUnevictable(page);
3838 del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
3839 add_page_to_lru_list(page, lruvec, lru);
3840 pgrescued++;
3841 }
3842 }
3843
3844 if (zone) {
3845 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
3846 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
3847 spin_unlock_irq(&zone->lru_lock);
3848 }
3849}
3850#endif /* CONFIG_SHMEM */