workingset.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Workingset detection
  4. *
  5. * Copyright (C) 2013 Red Hat, Inc., Johannes Weiner
  6. */
  7. #include <linux/memcontrol.h>
  8. #include <linux/mm_inline.h>
  9. #include <linux/writeback.h>
  10. #include <linux/shmem_fs.h>
  11. #include <linux/pagemap.h>
  12. #include <linux/atomic.h>
  13. #include <linux/module.h>
  14. #include <linux/swap.h>
  15. #include <linux/dax.h>
  16. #include <linux/fs.h>
  17. #include <linux/mm.h>
  18. #include "internal.h"
  19. /*
  20. * Double CLOCK lists
  21. *
  22. * Per node, two clock lists are maintained for file pages: the
  23. * inactive and the active list. Freshly faulted pages start out at
  24. * the head of the inactive list and page reclaim scans pages from the
  25. * tail. Pages that are accessed multiple times on the inactive list
  26. * are promoted to the active list, to protect them from reclaim,
  27. * whereas active pages are demoted to the inactive list when the
  28. * active list grows too big.
  29. *
  30. * fault ------------------------+
  31. * |
  32. * +--------------+ | +-------------+
  33. * reclaim <- | inactive | <-+-- demotion | active | <--+
  34. * +--------------+ +-------------+ |
  35. * | |
  36. * +-------------- promotion ------------------+
  37. *
  38. *
  39. * Access frequency and refault distance
  40. *
  41. * A workload is thrashing when its pages are frequently used but they
  42. * are evicted from the inactive list every time before another access
  43. * would have promoted them to the active list.
  44. *
  45. * In cases where the average access distance between thrashing pages
  46. * is bigger than the size of memory there is nothing that can be
  47. * done - the thrashing set could never fit into memory under any
  48. * circumstance.
  49. *
  50. * However, the average access distance could be bigger than the
  51. * inactive list, yet smaller than the size of memory. In this case,
  52. * the set could fit into memory if it weren't for the currently
  53. * active pages - which may be used more, hopefully less frequently:
  54. *
  55. * +-memory available to cache-+
  56. * | |
  57. * +-inactive------+-active----+
  58. * a b | c d e f g h i | J K L M N |
  59. * +---------------+-----------+
  60. *
  61. * It is prohibitively expensive to accurately track access frequency
  62. * of pages. But a reasonable approximation can be made to measure
  63. * thrashing on the inactive list, after which refaulting pages can be
  64. * activated optimistically to compete with the existing active pages.
  65. *
  66. * Approximating inactive page access frequency - Observations:
  67. *
  68. * 1. When a page is accessed for the first time, it is added to the
  69. * head of the inactive list, slides every existing inactive page
  70. * towards the tail by one slot, and pushes the current tail page
  71. * out of memory.
  72. *
  73. * 2. When a page is accessed for the second time, it is promoted to
  74. * the active list, shrinking the inactive list by one slot. This
  75. * also slides all inactive pages that were faulted into the cache
  76. * more recently than the activated page towards the tail of the
  77. * inactive list.
  78. *
  79. * Thus:
  80. *
  81. * 1. The sum of evictions and activations between any two points in
  82. * time indicate the minimum number of inactive pages accessed in
  83. * between.
  84. *
  85. * 2. Moving one inactive page N page slots towards the tail of the
  86. * list requires at least N inactive page accesses.
  87. *
  88. * Combining these:
  89. *
  90. * 1. When a page is finally evicted from memory, the number of
  91. * inactive pages accessed while the page was in cache is at least
  92. * the number of page slots on the inactive list.
  93. *
  94. * 2. In addition, measuring the sum of evictions and activations (E)
  95. * at the time of a page's eviction, and comparing it to another
  96. * reading (R) at the time the page faults back into memory tells
  97. * the minimum number of accesses while the page was not cached.
  98. * This is called the refault distance.
  99. *
  100. * Because the first access of the page was the fault and the second
  101. * access the refault, we combine the in-cache distance with the
  102. * out-of-cache distance to get the complete minimum access distance
  103. * of this page:
  104. *
  105. * NR_inactive + (R - E)
  106. *
  107. * And knowing the minimum access distance of a page, we can easily
  108. * tell if the page would be able to stay in cache assuming all page
  109. * slots in the cache were available:
  110. *
  111. * NR_inactive + (R - E) <= NR_inactive + NR_active
  112. *
  113. * If we have swap we should consider about NR_inactive_anon and
  114. * NR_active_anon, so for page cache and anonymous respectively:
  115. *
  116. * NR_inactive_file + (R - E) <= NR_inactive_file + NR_active_file
  117. * + NR_inactive_anon + NR_active_anon
  118. *
  119. * NR_inactive_anon + (R - E) <= NR_inactive_anon + NR_active_anon
  120. * + NR_inactive_file + NR_active_file
  121. *
  122. * Which can be further simplified to:
  123. *
  124. * (R - E) <= NR_active_file + NR_inactive_anon + NR_active_anon
  125. *
  126. * (R - E) <= NR_active_anon + NR_inactive_file + NR_active_file
  127. *
  128. * Put into words, the refault distance (out-of-cache) can be seen as
  129. * a deficit in inactive list space (in-cache). If the inactive list
  130. * had (R - E) more page slots, the page would not have been evicted
  131. * in between accesses, but activated instead. And on a full system,
  132. * the only thing eating into inactive list space is active pages.
  133. *
  134. *
  135. * Refaulting inactive pages
  136. *
  137. * All that is known about the active list is that the pages have been
  138. * accessed more than once in the past. This means that at any given
  139. * time there is actually a good chance that pages on the active list
  140. * are no longer in active use.
  141. *
  142. * So when a refault distance of (R - E) is observed and there are at
  143. * least (R - E) pages in the userspace workingset, the refaulting page
  144. * is activated optimistically in the hope that (R - E) pages are actually
  145. * used less frequently than the refaulting page - or even not used at
  146. * all anymore.
  147. *
  148. * That means if inactive cache is refaulting with a suitable refault
  149. * distance, we assume the cache workingset is transitioning and put
  150. * pressure on the current workingset.
  151. *
  152. * If this is wrong and demotion kicks in, the pages which are truly
  153. * used more frequently will be reactivated while the less frequently
  154. * used once will be evicted from memory.
  155. *
  156. * But if this is right, the stale pages will be pushed out of memory
  157. * and the used pages get to stay in cache.
  158. *
  159. * Refaulting active pages
  160. *
  161. * If on the other hand the refaulting pages have recently been
  162. * deactivated, it means that the active list is no longer protecting
  163. * actively used cache from reclaim. The cache is NOT transitioning to
  164. * a different workingset; the existing workingset is thrashing in the
  165. * space allocated to the page cache.
  166. *
  167. *
  168. * Implementation
  169. *
  170. * For each node's LRU lists, a counter for inactive evictions and
  171. * activations is maintained (node->nonresident_age).
  172. *
  173. * On eviction, a snapshot of this counter (along with some bits to
  174. * identify the node) is stored in the now empty page cache
  175. * slot of the evicted page. This is called a shadow entry.
  176. *
  177. * On cache misses for which there are shadow entries, an eligible
  178. * refault distance will immediately activate the refaulting page.
  179. */
  180. #define WORKINGSET_SHIFT 1
  181. #define EVICTION_SHIFT ((BITS_PER_LONG - BITS_PER_XA_VALUE) + \
  182. WORKINGSET_SHIFT + NODES_SHIFT + \
  183. MEM_CGROUP_ID_SHIFT)
  184. #define EVICTION_MASK (~0UL >> EVICTION_SHIFT)
  185. /*
  186. * Eviction timestamps need to be able to cover the full range of
  187. * actionable refaults. However, bits are tight in the xarray
  188. * entry, and after storing the identifier for the lruvec there might
  189. * not be enough left to represent every single actionable refault. In
  190. * that case, we have to sacrifice granularity for distance, and group
  191. * evictions into coarser buckets by shaving off lower timestamp bits.
  192. */
  193. static unsigned int bucket_order __read_mostly;
  194. static void *pack_shadow(int memcgid, pg_data_t *pgdat, unsigned long eviction,
  195. bool workingset)
  196. {
  197. eviction &= EVICTION_MASK;
  198. eviction = (eviction << MEM_CGROUP_ID_SHIFT) | memcgid;
  199. eviction = (eviction << NODES_SHIFT) | pgdat->node_id;
  200. eviction = (eviction << WORKINGSET_SHIFT) | workingset;
  201. return xa_mk_value(eviction);
  202. }
  203. static void unpack_shadow(void *shadow, int *memcgidp, pg_data_t **pgdat,
  204. unsigned long *evictionp, bool *workingsetp)
  205. {
  206. unsigned long entry = xa_to_value(shadow);
  207. int memcgid, nid;
  208. bool workingset;
  209. workingset = entry & ((1UL << WORKINGSET_SHIFT) - 1);
  210. entry >>= WORKINGSET_SHIFT;
  211. nid = entry & ((1UL << NODES_SHIFT) - 1);
  212. entry >>= NODES_SHIFT;
  213. memcgid = entry & ((1UL << MEM_CGROUP_ID_SHIFT) - 1);
  214. entry >>= MEM_CGROUP_ID_SHIFT;
  215. *memcgidp = memcgid;
  216. *pgdat = NODE_DATA(nid);
  217. *evictionp = entry;
  218. *workingsetp = workingset;
  219. }
  220. #ifdef CONFIG_LRU_GEN
  221. static void *lru_gen_eviction(struct folio *folio)
  222. {
  223. int hist;
  224. unsigned long token;
  225. unsigned long min_seq;
  226. struct lruvec *lruvec;
  227. struct lru_gen_folio *lrugen;
  228. int type = folio_is_file_lru(folio);
  229. int delta = folio_nr_pages(folio);
  230. int refs = folio_lru_refs(folio);
  231. bool workingset = folio_test_workingset(folio);
  232. int tier = lru_tier_from_refs(refs, workingset);
  233. struct mem_cgroup *memcg = folio_memcg(folio);
  234. struct pglist_data *pgdat = folio_pgdat(folio);
  235. BUILD_BUG_ON(LRU_GEN_WIDTH + LRU_REFS_WIDTH > BITS_PER_LONG - EVICTION_SHIFT);
  236. lruvec = mem_cgroup_lruvec(memcg, pgdat);
  237. lrugen = &lruvec->lrugen;
  238. min_seq = READ_ONCE(lrugen->min_seq[type]);
  239. token = (min_seq << LRU_REFS_WIDTH) | max(refs - 1, 0);
  240. hist = lru_hist_from_seq(min_seq);
  241. atomic_long_add(delta, &lrugen->evicted[hist][type][tier]);
  242. return pack_shadow(mem_cgroup_private_id(memcg), pgdat, token, workingset);
  243. }
  244. /*
  245. * Tests if the shadow entry is for a folio that was recently evicted.
  246. * Fills in @lruvec, @token, @workingset with the values unpacked from shadow.
  247. */
  248. static bool lru_gen_test_recent(void *shadow, struct lruvec **lruvec,
  249. unsigned long *token, bool *workingset)
  250. {
  251. int memcg_id;
  252. unsigned long max_seq;
  253. struct mem_cgroup *memcg;
  254. struct pglist_data *pgdat;
  255. unpack_shadow(shadow, &memcg_id, &pgdat, token, workingset);
  256. memcg = mem_cgroup_from_private_id(memcg_id);
  257. *lruvec = mem_cgroup_lruvec(memcg, pgdat);
  258. max_seq = READ_ONCE((*lruvec)->lrugen.max_seq);
  259. max_seq &= EVICTION_MASK >> LRU_REFS_WIDTH;
  260. return abs_diff(max_seq, *token >> LRU_REFS_WIDTH) < MAX_NR_GENS;
  261. }
  262. static void lru_gen_refault(struct folio *folio, void *shadow)
  263. {
  264. bool recent;
  265. int hist, tier, refs;
  266. bool workingset;
  267. unsigned long token;
  268. struct lruvec *lruvec;
  269. struct lru_gen_folio *lrugen;
  270. int type = folio_is_file_lru(folio);
  271. int delta = folio_nr_pages(folio);
  272. rcu_read_lock();
  273. recent = lru_gen_test_recent(shadow, &lruvec, &token, &workingset);
  274. if (lruvec != folio_lruvec(folio))
  275. goto unlock;
  276. mod_lruvec_state(lruvec, WORKINGSET_REFAULT_BASE + type, delta);
  277. if (!recent)
  278. goto unlock;
  279. lrugen = &lruvec->lrugen;
  280. hist = lru_hist_from_seq(READ_ONCE(lrugen->min_seq[type]));
  281. refs = (token & (BIT(LRU_REFS_WIDTH) - 1)) + 1;
  282. tier = lru_tier_from_refs(refs, workingset);
  283. atomic_long_add(delta, &lrugen->refaulted[hist][type][tier]);
  284. /* see folio_add_lru() where folio_set_active() will be called */
  285. if (lru_gen_in_fault())
  286. mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
  287. if (workingset) {
  288. folio_set_workingset(folio);
  289. mod_lruvec_state(lruvec, WORKINGSET_RESTORE_BASE + type, delta);
  290. } else
  291. set_mask_bits(&folio->flags.f, LRU_REFS_MASK, (refs - 1UL) << LRU_REFS_PGOFF);
  292. unlock:
  293. rcu_read_unlock();
  294. }
  295. #else /* !CONFIG_LRU_GEN */
  296. static void *lru_gen_eviction(struct folio *folio)
  297. {
  298. return NULL;
  299. }
  300. static bool lru_gen_test_recent(void *shadow, struct lruvec **lruvec,
  301. unsigned long *token, bool *workingset)
  302. {
  303. return false;
  304. }
  305. static void lru_gen_refault(struct folio *folio, void *shadow)
  306. {
  307. }
  308. #endif /* CONFIG_LRU_GEN */
  309. /**
  310. * workingset_age_nonresident - age non-resident entries as LRU ages
  311. * @lruvec: the lruvec that was aged
  312. * @nr_pages: the number of pages to count
  313. *
  314. * As in-memory pages are aged, non-resident pages need to be aged as
  315. * well, in order for the refault distances later on to be comparable
  316. * to the in-memory dimensions. This function allows reclaim and LRU
  317. * operations to drive the non-resident aging along in parallel.
  318. */
  319. void workingset_age_nonresident(struct lruvec *lruvec, unsigned long nr_pages)
  320. {
  321. /*
  322. * Reclaiming a cgroup means reclaiming all its children in a
  323. * round-robin fashion. That means that each cgroup has an LRU
  324. * order that is composed of the LRU orders of its child
  325. * cgroups; and every page has an LRU position not just in the
  326. * cgroup that owns it, but in all of that group's ancestors.
  327. *
  328. * So when the physical inactive list of a leaf cgroup ages,
  329. * the virtual inactive lists of all its parents, including
  330. * the root cgroup's, age as well.
  331. */
  332. do {
  333. atomic_long_add(nr_pages, &lruvec->nonresident_age);
  334. } while ((lruvec = parent_lruvec(lruvec)));
  335. }
  336. /**
  337. * workingset_eviction - note the eviction of a folio from memory
  338. * @target_memcg: the cgroup that is causing the reclaim
  339. * @folio: the folio being evicted
  340. *
  341. * Return: a shadow entry to be stored in @folio->mapping->i_pages in place
  342. * of the evicted @folio so that a later refault can be detected.
  343. */
  344. void *workingset_eviction(struct folio *folio, struct mem_cgroup *target_memcg)
  345. {
  346. struct pglist_data *pgdat = folio_pgdat(folio);
  347. unsigned long eviction;
  348. struct lruvec *lruvec;
  349. int memcgid;
  350. /* Folio is fully exclusive and pins folio's memory cgroup pointer */
  351. VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
  352. VM_BUG_ON_FOLIO(folio_ref_count(folio), folio);
  353. VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
  354. if (lru_gen_enabled())
  355. return lru_gen_eviction(folio);
  356. lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
  357. /* XXX: target_memcg can be NULL, go through lruvec */
  358. memcgid = mem_cgroup_private_id(lruvec_memcg(lruvec));
  359. eviction = atomic_long_read(&lruvec->nonresident_age);
  360. eviction >>= bucket_order;
  361. workingset_age_nonresident(lruvec, folio_nr_pages(folio));
  362. return pack_shadow(memcgid, pgdat, eviction,
  363. folio_test_workingset(folio));
  364. }
  365. /**
  366. * workingset_test_recent - tests if the shadow entry is for a folio that was
  367. * recently evicted. Also fills in @workingset with the value unpacked from
  368. * shadow.
  369. * @shadow: the shadow entry to be tested.
  370. * @file: whether the corresponding folio is from the file lru.
  371. * @workingset: where the workingset value unpacked from shadow should
  372. * be stored.
  373. * @flush: whether to flush cgroup rstat.
  374. *
  375. * Return: true if the shadow is for a recently evicted folio; false otherwise.
  376. */
  377. bool workingset_test_recent(void *shadow, bool file, bool *workingset,
  378. bool flush)
  379. {
  380. struct mem_cgroup *eviction_memcg;
  381. struct lruvec *eviction_lruvec;
  382. unsigned long refault_distance;
  383. unsigned long workingset_size;
  384. unsigned long refault;
  385. int memcgid;
  386. struct pglist_data *pgdat;
  387. unsigned long eviction;
  388. if (lru_gen_enabled()) {
  389. bool recent;
  390. rcu_read_lock();
  391. recent = lru_gen_test_recent(shadow, &eviction_lruvec, &eviction, workingset);
  392. rcu_read_unlock();
  393. return recent;
  394. }
  395. rcu_read_lock();
  396. unpack_shadow(shadow, &memcgid, &pgdat, &eviction, workingset);
  397. eviction <<= bucket_order;
  398. /*
  399. * Look up the memcg associated with the stored ID. It might
  400. * have been deleted since the folio's eviction.
  401. *
  402. * Note that in rare events the ID could have been recycled
  403. * for a new cgroup that refaults a shared folio. This is
  404. * impossible to tell from the available data. However, this
  405. * should be a rare and limited disturbance, and activations
  406. * are always speculative anyway. Ultimately, it's the aging
  407. * algorithm's job to shake out the minimum access frequency
  408. * for the active cache.
  409. *
  410. * XXX: On !CONFIG_MEMCG, this will always return NULL; it
  411. * would be better if the root_mem_cgroup existed in all
  412. * configurations instead.
  413. */
  414. eviction_memcg = mem_cgroup_from_private_id(memcgid);
  415. if (!mem_cgroup_tryget(eviction_memcg))
  416. eviction_memcg = NULL;
  417. rcu_read_unlock();
  418. if (!mem_cgroup_disabled() && !eviction_memcg)
  419. return false;
  420. /*
  421. * Flush stats (and potentially sleep) outside the RCU read section.
  422. *
  423. * Note that workingset_test_recent() itself might be called in RCU read
  424. * section (for e.g, in cachestat) - these callers need to skip flushing
  425. * stats (via the flush argument).
  426. *
  427. * XXX: With per-memcg flushing and thresholding, is ratelimiting
  428. * still needed here?
  429. */
  430. if (flush)
  431. mem_cgroup_flush_stats_ratelimited(eviction_memcg);
  432. eviction_lruvec = mem_cgroup_lruvec(eviction_memcg, pgdat);
  433. refault = atomic_long_read(&eviction_lruvec->nonresident_age);
  434. /*
  435. * Calculate the refault distance
  436. *
  437. * The unsigned subtraction here gives an accurate distance
  438. * across nonresident_age overflows in most cases. There is a
  439. * special case: usually, shadow entries have a short lifetime
  440. * and are either refaulted or reclaimed along with the inode
  441. * before they get too old. But it is not impossible for the
  442. * nonresident_age to lap a shadow entry in the field, which
  443. * can then result in a false small refault distance, leading
  444. * to a false activation should this old entry actually
  445. * refault again. However, earlier kernels used to deactivate
  446. * unconditionally with *every* reclaim invocation for the
  447. * longest time, so the occasional inappropriate activation
  448. * leading to pressure on the active list is not a problem.
  449. */
  450. refault_distance = (refault - eviction) & EVICTION_MASK;
  451. /*
  452. * Compare the distance to the existing workingset size. We
  453. * don't activate pages that couldn't stay resident even if
  454. * all the memory was available to the workingset. Whether
  455. * workingset competition needs to consider anon or not depends
  456. * on having free swap space.
  457. */
  458. workingset_size = lruvec_page_state(eviction_lruvec, NR_ACTIVE_FILE);
  459. if (!file) {
  460. workingset_size += lruvec_page_state(eviction_lruvec,
  461. NR_INACTIVE_FILE);
  462. }
  463. if (mem_cgroup_get_nr_swap_pages(eviction_memcg) > 0) {
  464. workingset_size += lruvec_page_state(eviction_lruvec,
  465. NR_ACTIVE_ANON);
  466. if (file) {
  467. workingset_size += lruvec_page_state(eviction_lruvec,
  468. NR_INACTIVE_ANON);
  469. }
  470. }
  471. mem_cgroup_put(eviction_memcg);
  472. return refault_distance <= workingset_size;
  473. }
  474. /**
  475. * workingset_refault - Evaluate the refault of a previously evicted folio.
  476. * @folio: The freshly allocated replacement folio.
  477. * @shadow: Shadow entry of the evicted folio.
  478. *
  479. * Calculates and evaluates the refault distance of the previously
  480. * evicted folio in the context of the node and the memcg whose memory
  481. * pressure caused the eviction.
  482. */
  483. void workingset_refault(struct folio *folio, void *shadow)
  484. {
  485. bool file = folio_is_file_lru(folio);
  486. struct pglist_data *pgdat;
  487. struct mem_cgroup *memcg;
  488. struct lruvec *lruvec;
  489. bool workingset;
  490. long nr;
  491. VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
  492. if (lru_gen_enabled()) {
  493. lru_gen_refault(folio, shadow);
  494. return;
  495. }
  496. /*
  497. * The activation decision for this folio is made at the level
  498. * where the eviction occurred, as that is where the LRU order
  499. * during folio reclaim is being determined.
  500. *
  501. * However, the cgroup that will own the folio is the one that
  502. * is actually experiencing the refault event. Make sure the folio is
  503. * locked to guarantee folio_memcg() stability throughout.
  504. */
  505. nr = folio_nr_pages(folio);
  506. memcg = folio_memcg(folio);
  507. pgdat = folio_pgdat(folio);
  508. lruvec = mem_cgroup_lruvec(memcg, pgdat);
  509. mod_lruvec_state(lruvec, WORKINGSET_REFAULT_BASE + file, nr);
  510. if (!workingset_test_recent(shadow, file, &workingset, true))
  511. return;
  512. folio_set_active(folio);
  513. workingset_age_nonresident(lruvec, nr);
  514. mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + file, nr);
  515. /* Folio was active prior to eviction */
  516. if (workingset) {
  517. folio_set_workingset(folio);
  518. /*
  519. * XXX: Move to folio_add_lru() when it supports new vs
  520. * putback
  521. */
  522. lru_note_cost_refault(folio);
  523. mod_lruvec_state(lruvec, WORKINGSET_RESTORE_BASE + file, nr);
  524. }
  525. }
  526. /**
  527. * workingset_activation - note a page activation
  528. * @folio: Folio that is being activated.
  529. */
  530. void workingset_activation(struct folio *folio)
  531. {
  532. /*
  533. * Filter non-memcg pages here, e.g. unmap can call
  534. * mark_page_accessed() on VDSO pages.
  535. */
  536. if (mem_cgroup_disabled() || folio_memcg_charged(folio))
  537. workingset_age_nonresident(folio_lruvec(folio), folio_nr_pages(folio));
  538. }
  539. /*
  540. * Shadow entries reflect the share of the working set that does not
  541. * fit into memory, so their number depends on the access pattern of
  542. * the workload. In most cases, they will refault or get reclaimed
  543. * along with the inode, but a (malicious) workload that streams
  544. * through files with a total size several times that of available
  545. * memory, while preventing the inodes from being reclaimed, can
  546. * create excessive amounts of shadow nodes. To keep a lid on this,
  547. * track shadow nodes and reclaim them when they grow way past the
  548. * point where they would still be useful.
  549. */
  550. struct list_lru shadow_nodes;
  551. void workingset_update_node(struct xa_node *node)
  552. {
  553. struct page *page = virt_to_page(node);
  554. /*
  555. * Track non-empty nodes that contain only shadow entries;
  556. * unlink those that contain pages or are being freed.
  557. *
  558. * Avoid acquiring the list_lru lock when the nodes are
  559. * already where they should be. The list_empty() test is safe
  560. * as node->private_list is protected by the i_pages lock.
  561. */
  562. lockdep_assert_held(&node->array->xa_lock);
  563. if (node->count && node->count == node->nr_values) {
  564. if (list_empty(&node->private_list)) {
  565. list_lru_add_obj(&shadow_nodes, &node->private_list);
  566. __inc_node_page_state(page, WORKINGSET_NODES);
  567. }
  568. } else {
  569. if (!list_empty(&node->private_list)) {
  570. list_lru_del_obj(&shadow_nodes, &node->private_list);
  571. __dec_node_page_state(page, WORKINGSET_NODES);
  572. }
  573. }
  574. }
  575. static unsigned long count_shadow_nodes(struct shrinker *shrinker,
  576. struct shrink_control *sc)
  577. {
  578. unsigned long max_nodes;
  579. unsigned long nodes;
  580. unsigned long pages;
  581. nodes = list_lru_shrink_count(&shadow_nodes, sc);
  582. if (!nodes)
  583. return SHRINK_EMPTY;
  584. /*
  585. * Approximate a reasonable limit for the nodes
  586. * containing shadow entries. We don't need to keep more
  587. * shadow entries than possible pages on the active list,
  588. * since refault distances bigger than that are dismissed.
  589. *
  590. * The size of the active list converges toward 100% of
  591. * overall page cache as memory grows, with only a tiny
  592. * inactive list. Assume the total cache size for that.
  593. *
  594. * Nodes might be sparsely populated, with only one shadow
  595. * entry in the extreme case. Obviously, we cannot keep one
  596. * node for every eligible shadow entry, so compromise on a
  597. * worst-case density of 1/8th. Below that, not all eligible
  598. * refaults can be detected anymore.
  599. *
  600. * On 64-bit with 7 xa_nodes per page and 64 slots
  601. * each, this will reclaim shadow entries when they consume
  602. * ~1.8% of available memory:
  603. *
  604. * PAGE_SIZE / xa_nodes / node_entries * 8 / PAGE_SIZE
  605. */
  606. #ifdef CONFIG_MEMCG
  607. if (sc->memcg) {
  608. struct lruvec *lruvec;
  609. int i;
  610. mem_cgroup_flush_stats_ratelimited(sc->memcg);
  611. lruvec = mem_cgroup_lruvec(sc->memcg, NODE_DATA(sc->nid));
  612. for (pages = 0, i = 0; i < NR_LRU_LISTS; i++)
  613. pages += lruvec_page_state_local(lruvec,
  614. NR_LRU_BASE + i);
  615. pages += lruvec_page_state_local(
  616. lruvec, NR_SLAB_RECLAIMABLE_B) >> PAGE_SHIFT;
  617. pages += lruvec_page_state_local(
  618. lruvec, NR_SLAB_UNRECLAIMABLE_B) >> PAGE_SHIFT;
  619. } else
  620. #endif
  621. pages = node_present_pages(sc->nid);
  622. max_nodes = pages >> (XA_CHUNK_SHIFT - 3);
  623. if (nodes <= max_nodes)
  624. return 0;
  625. return nodes - max_nodes;
  626. }
  627. static enum lru_status shadow_lru_isolate(struct list_head *item,
  628. struct list_lru_one *lru,
  629. void *arg) __must_hold(lru->lock)
  630. {
  631. struct xa_node *node = container_of(item, struct xa_node, private_list);
  632. struct address_space *mapping;
  633. int ret;
  634. /*
  635. * Page cache insertions and deletions synchronously maintain
  636. * the shadow node LRU under the i_pages lock and the
  637. * &lru->lock. Because the page cache tree is emptied before
  638. * the inode can be destroyed, holding the &lru->lock pins any
  639. * address_space that has nodes on the LRU.
  640. *
  641. * We can then safely transition to the i_pages lock to
  642. * pin only the address_space of the particular node we want
  643. * to reclaim, take the node off-LRU, and drop the &lru->lock.
  644. */
  645. mapping = container_of(node->array, struct address_space, i_pages);
  646. /* Coming from the list, invert the lock order */
  647. if (!xa_trylock(&mapping->i_pages)) {
  648. spin_unlock_irq(&lru->lock);
  649. ret = LRU_RETRY;
  650. goto out;
  651. }
  652. /* For page cache we need to hold i_lock */
  653. if (mapping->host != NULL) {
  654. if (!spin_trylock(&mapping->host->i_lock)) {
  655. xa_unlock(&mapping->i_pages);
  656. spin_unlock_irq(&lru->lock);
  657. ret = LRU_RETRY;
  658. goto out;
  659. }
  660. }
  661. list_lru_isolate(lru, item);
  662. __dec_node_page_state(virt_to_page(node), WORKINGSET_NODES);
  663. spin_unlock(&lru->lock);
  664. /*
  665. * The nodes should only contain one or more shadow entries,
  666. * no pages, so we expect to be able to remove them all and
  667. * delete and free the empty node afterwards.
  668. */
  669. if (WARN_ON_ONCE(!node->nr_values))
  670. goto out_invalid;
  671. if (WARN_ON_ONCE(node->count != node->nr_values))
  672. goto out_invalid;
  673. xa_delete_node(node, workingset_update_node);
  674. mod_lruvec_kmem_state(node, WORKINGSET_NODERECLAIM, 1);
  675. out_invalid:
  676. xa_unlock_irq(&mapping->i_pages);
  677. if (mapping->host != NULL) {
  678. if (mapping_shrinkable(mapping))
  679. inode_lru_list_add(mapping->host);
  680. spin_unlock(&mapping->host->i_lock);
  681. }
  682. ret = LRU_REMOVED_RETRY;
  683. out:
  684. cond_resched();
  685. return ret;
  686. }
  687. static unsigned long scan_shadow_nodes(struct shrinker *shrinker,
  688. struct shrink_control *sc)
  689. {
  690. /* list_lru lock nests inside the IRQ-safe i_pages lock */
  691. return list_lru_shrink_walk_irq(&shadow_nodes, sc, shadow_lru_isolate,
  692. NULL);
  693. }
  694. /*
  695. * Our list_lru->lock is IRQ-safe as it nests inside the IRQ-safe
  696. * i_pages lock.
  697. */
  698. static struct lock_class_key shadow_nodes_key;
  699. static int __init workingset_init(void)
  700. {
  701. struct shrinker *workingset_shadow_shrinker;
  702. unsigned int timestamp_bits;
  703. unsigned int max_order;
  704. int ret = -ENOMEM;
  705. BUILD_BUG_ON(BITS_PER_LONG < EVICTION_SHIFT);
  706. /*
  707. * Calculate the eviction bucket size to cover the longest
  708. * actionable refault distance, which is currently half of
  709. * memory (totalram_pages/2). However, memory hotplug may add
  710. * some more pages at runtime, so keep working with up to
  711. * double the initial memory by using totalram_pages as-is.
  712. */
  713. timestamp_bits = BITS_PER_LONG - EVICTION_SHIFT;
  714. max_order = fls_long(totalram_pages() - 1);
  715. if (max_order > timestamp_bits)
  716. bucket_order = max_order - timestamp_bits;
  717. pr_info("workingset: timestamp_bits=%d max_order=%d bucket_order=%u\n",
  718. timestamp_bits, max_order, bucket_order);
  719. workingset_shadow_shrinker = shrinker_alloc(SHRINKER_NUMA_AWARE |
  720. SHRINKER_MEMCG_AWARE,
  721. "mm-shadow");
  722. if (!workingset_shadow_shrinker)
  723. goto err;
  724. ret = list_lru_init_memcg_key(&shadow_nodes, workingset_shadow_shrinker,
  725. &shadow_nodes_key);
  726. if (ret)
  727. goto err_list_lru;
  728. workingset_shadow_shrinker->count_objects = count_shadow_nodes;
  729. workingset_shadow_shrinker->scan_objects = scan_shadow_nodes;
  730. /* ->count reports only fully expendable nodes */
  731. workingset_shadow_shrinker->seeks = 0;
  732. shrinker_register(workingset_shadow_shrinker);
  733. return 0;
  734. err_list_lru:
  735. shrinker_free(workingset_shadow_shrinker);
  736. err:
  737. return ret;
  738. }
  739. module_init(workingset_init);