workingset.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843
  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. int tier = lru_tier_from_refs(refs);
  232. struct mem_cgroup *memcg = folio_memcg(folio);
  233. struct pglist_data *pgdat = folio_pgdat(folio);
  234. BUILD_BUG_ON(LRU_GEN_WIDTH + LRU_REFS_WIDTH > BITS_PER_LONG - EVICTION_SHIFT);
  235. lruvec = mem_cgroup_lruvec(memcg, pgdat);
  236. lrugen = &lruvec->lrugen;
  237. min_seq = READ_ONCE(lrugen->min_seq[type]);
  238. token = (min_seq << LRU_REFS_WIDTH) | max(refs - 1, 0);
  239. hist = lru_hist_from_seq(min_seq);
  240. atomic_long_add(delta, &lrugen->evicted[hist][type][tier]);
  241. return pack_shadow(mem_cgroup_id(memcg), pgdat, token, refs);
  242. }
  243. /*
  244. * Tests if the shadow entry is for a folio that was recently evicted.
  245. * Fills in @lruvec, @token, @workingset with the values unpacked from shadow.
  246. */
  247. static bool lru_gen_test_recent(void *shadow, bool file, struct lruvec **lruvec,
  248. unsigned long *token, bool *workingset)
  249. {
  250. int memcg_id;
  251. unsigned long min_seq;
  252. struct mem_cgroup *memcg;
  253. struct pglist_data *pgdat;
  254. unpack_shadow(shadow, &memcg_id, &pgdat, token, workingset);
  255. memcg = mem_cgroup_from_id(memcg_id);
  256. *lruvec = mem_cgroup_lruvec(memcg, pgdat);
  257. min_seq = READ_ONCE((*lruvec)->lrugen.min_seq[file]);
  258. return (*token >> LRU_REFS_WIDTH) == (min_seq & (EVICTION_MASK >> LRU_REFS_WIDTH));
  259. }
  260. static void lru_gen_refault(struct folio *folio, void *shadow)
  261. {
  262. bool recent;
  263. int hist, tier, refs;
  264. bool workingset;
  265. unsigned long token;
  266. struct lruvec *lruvec;
  267. struct lru_gen_folio *lrugen;
  268. int type = folio_is_file_lru(folio);
  269. int delta = folio_nr_pages(folio);
  270. rcu_read_lock();
  271. recent = lru_gen_test_recent(shadow, type, &lruvec, &token, &workingset);
  272. if (lruvec != folio_lruvec(folio))
  273. goto unlock;
  274. mod_lruvec_state(lruvec, WORKINGSET_REFAULT_BASE + type, delta);
  275. if (!recent)
  276. goto unlock;
  277. lrugen = &lruvec->lrugen;
  278. hist = lru_hist_from_seq(READ_ONCE(lrugen->min_seq[type]));
  279. /* see the comment in folio_lru_refs() */
  280. refs = (token & (BIT(LRU_REFS_WIDTH) - 1)) + workingset;
  281. tier = lru_tier_from_refs(refs);
  282. atomic_long_add(delta, &lrugen->refaulted[hist][type][tier]);
  283. mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
  284. /*
  285. * Count the following two cases as stalls:
  286. * 1. For pages accessed through page tables, hotter pages pushed out
  287. * hot pages which refaulted immediately.
  288. * 2. For pages accessed multiple times through file descriptors,
  289. * they would have been protected by sort_folio().
  290. */
  291. if (lru_gen_in_fault() || refs >= BIT(LRU_REFS_WIDTH) - 1) {
  292. set_mask_bits(&folio->flags, 0, LRU_REFS_MASK | BIT(PG_workingset));
  293. mod_lruvec_state(lruvec, WORKINGSET_RESTORE_BASE + type, delta);
  294. }
  295. unlock:
  296. rcu_read_unlock();
  297. }
  298. #else /* !CONFIG_LRU_GEN */
  299. static void *lru_gen_eviction(struct folio *folio)
  300. {
  301. return NULL;
  302. }
  303. static bool lru_gen_test_recent(void *shadow, bool file, struct lruvec **lruvec,
  304. unsigned long *token, bool *workingset)
  305. {
  306. return false;
  307. }
  308. static void lru_gen_refault(struct folio *folio, void *shadow)
  309. {
  310. }
  311. #endif /* CONFIG_LRU_GEN */
  312. /**
  313. * workingset_age_nonresident - age non-resident entries as LRU ages
  314. * @lruvec: the lruvec that was aged
  315. * @nr_pages: the number of pages to count
  316. *
  317. * As in-memory pages are aged, non-resident pages need to be aged as
  318. * well, in order for the refault distances later on to be comparable
  319. * to the in-memory dimensions. This function allows reclaim and LRU
  320. * operations to drive the non-resident aging along in parallel.
  321. */
  322. void workingset_age_nonresident(struct lruvec *lruvec, unsigned long nr_pages)
  323. {
  324. /*
  325. * Reclaiming a cgroup means reclaiming all its children in a
  326. * round-robin fashion. That means that each cgroup has an LRU
  327. * order that is composed of the LRU orders of its child
  328. * cgroups; and every page has an LRU position not just in the
  329. * cgroup that owns it, but in all of that group's ancestors.
  330. *
  331. * So when the physical inactive list of a leaf cgroup ages,
  332. * the virtual inactive lists of all its parents, including
  333. * the root cgroup's, age as well.
  334. */
  335. do {
  336. atomic_long_add(nr_pages, &lruvec->nonresident_age);
  337. } while ((lruvec = parent_lruvec(lruvec)));
  338. }
  339. /**
  340. * workingset_eviction - note the eviction of a folio from memory
  341. * @target_memcg: the cgroup that is causing the reclaim
  342. * @folio: the folio being evicted
  343. *
  344. * Return: a shadow entry to be stored in @folio->mapping->i_pages in place
  345. * of the evicted @folio so that a later refault can be detected.
  346. */
  347. void *workingset_eviction(struct folio *folio, struct mem_cgroup *target_memcg)
  348. {
  349. struct pglist_data *pgdat = folio_pgdat(folio);
  350. unsigned long eviction;
  351. struct lruvec *lruvec;
  352. int memcgid;
  353. /* Folio is fully exclusive and pins folio's memory cgroup pointer */
  354. VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
  355. VM_BUG_ON_FOLIO(folio_ref_count(folio), folio);
  356. VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
  357. if (lru_gen_enabled())
  358. return lru_gen_eviction(folio);
  359. lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
  360. /* XXX: target_memcg can be NULL, go through lruvec */
  361. memcgid = mem_cgroup_id(lruvec_memcg(lruvec));
  362. eviction = atomic_long_read(&lruvec->nonresident_age);
  363. eviction >>= bucket_order;
  364. workingset_age_nonresident(lruvec, folio_nr_pages(folio));
  365. return pack_shadow(memcgid, pgdat, eviction,
  366. folio_test_workingset(folio));
  367. }
  368. /**
  369. * workingset_test_recent - tests if the shadow entry is for a folio that was
  370. * recently evicted. Also fills in @workingset with the value unpacked from
  371. * shadow.
  372. * @shadow: the shadow entry to be tested.
  373. * @file: whether the corresponding folio is from the file lru.
  374. * @workingset: where the workingset value unpacked from shadow should
  375. * be stored.
  376. * @flush: whether to flush cgroup rstat.
  377. *
  378. * Return: true if the shadow is for a recently evicted folio; false otherwise.
  379. */
  380. bool workingset_test_recent(void *shadow, bool file, bool *workingset,
  381. bool flush)
  382. {
  383. struct mem_cgroup *eviction_memcg;
  384. struct lruvec *eviction_lruvec;
  385. unsigned long refault_distance;
  386. unsigned long workingset_size;
  387. unsigned long refault;
  388. int memcgid;
  389. struct pglist_data *pgdat;
  390. unsigned long eviction;
  391. rcu_read_lock();
  392. if (lru_gen_enabled()) {
  393. bool recent = lru_gen_test_recent(shadow, file,
  394. &eviction_lruvec, &eviction, workingset);
  395. rcu_read_unlock();
  396. return recent;
  397. }
  398. unpack_shadow(shadow, &memcgid, &pgdat, &eviction, workingset);
  399. eviction <<= bucket_order;
  400. /*
  401. * Look up the memcg associated with the stored ID. It might
  402. * have been deleted since the folio's eviction.
  403. *
  404. * Note that in rare events the ID could have been recycled
  405. * for a new cgroup that refaults a shared folio. This is
  406. * impossible to tell from the available data. However, this
  407. * should be a rare and limited disturbance, and activations
  408. * are always speculative anyway. Ultimately, it's the aging
  409. * algorithm's job to shake out the minimum access frequency
  410. * for the active cache.
  411. *
  412. * XXX: On !CONFIG_MEMCG, this will always return NULL; it
  413. * would be better if the root_mem_cgroup existed in all
  414. * configurations instead.
  415. */
  416. eviction_memcg = mem_cgroup_from_id(memcgid);
  417. if (!mem_cgroup_disabled() &&
  418. (!eviction_memcg || !mem_cgroup_tryget(eviction_memcg))) {
  419. rcu_read_unlock();
  420. return false;
  421. }
  422. rcu_read_unlock();
  423. /*
  424. * Flush stats (and potentially sleep) outside the RCU read section.
  425. *
  426. * Note that workingset_test_recent() itself might be called in RCU read
  427. * section (for e.g, in cachestat) - these callers need to skip flushing
  428. * stats (via the flush argument).
  429. *
  430. * XXX: With per-memcg flushing and thresholding, is ratelimiting
  431. * still needed here?
  432. */
  433. if (flush)
  434. mem_cgroup_flush_stats_ratelimited(eviction_memcg);
  435. eviction_lruvec = mem_cgroup_lruvec(eviction_memcg, pgdat);
  436. refault = atomic_long_read(&eviction_lruvec->nonresident_age);
  437. /*
  438. * Calculate the refault distance
  439. *
  440. * The unsigned subtraction here gives an accurate distance
  441. * across nonresident_age overflows in most cases. There is a
  442. * special case: usually, shadow entries have a short lifetime
  443. * and are either refaulted or reclaimed along with the inode
  444. * before they get too old. But it is not impossible for the
  445. * nonresident_age to lap a shadow entry in the field, which
  446. * can then result in a false small refault distance, leading
  447. * to a false activation should this old entry actually
  448. * refault again. However, earlier kernels used to deactivate
  449. * unconditionally with *every* reclaim invocation for the
  450. * longest time, so the occasional inappropriate activation
  451. * leading to pressure on the active list is not a problem.
  452. */
  453. refault_distance = (refault - eviction) & EVICTION_MASK;
  454. /*
  455. * Compare the distance to the existing workingset size. We
  456. * don't activate pages that couldn't stay resident even if
  457. * all the memory was available to the workingset. Whether
  458. * workingset competition needs to consider anon or not depends
  459. * on having free swap space.
  460. */
  461. workingset_size = lruvec_page_state(eviction_lruvec, NR_ACTIVE_FILE);
  462. if (!file) {
  463. workingset_size += lruvec_page_state(eviction_lruvec,
  464. NR_INACTIVE_FILE);
  465. }
  466. if (mem_cgroup_get_nr_swap_pages(eviction_memcg) > 0) {
  467. workingset_size += lruvec_page_state(eviction_lruvec,
  468. NR_ACTIVE_ANON);
  469. if (file) {
  470. workingset_size += lruvec_page_state(eviction_lruvec,
  471. NR_INACTIVE_ANON);
  472. }
  473. }
  474. mem_cgroup_put(eviction_memcg);
  475. return refault_distance <= workingset_size;
  476. }
  477. /**
  478. * workingset_refault - Evaluate the refault of a previously evicted folio.
  479. * @folio: The freshly allocated replacement folio.
  480. * @shadow: Shadow entry of the evicted folio.
  481. *
  482. * Calculates and evaluates the refault distance of the previously
  483. * evicted folio in the context of the node and the memcg whose memory
  484. * pressure caused the eviction.
  485. */
  486. void workingset_refault(struct folio *folio, void *shadow)
  487. {
  488. bool file = folio_is_file_lru(folio);
  489. struct pglist_data *pgdat;
  490. struct mem_cgroup *memcg;
  491. struct lruvec *lruvec;
  492. bool workingset;
  493. long nr;
  494. if (lru_gen_enabled()) {
  495. lru_gen_refault(folio, shadow);
  496. return;
  497. }
  498. /*
  499. * The activation decision for this folio is made at the level
  500. * where the eviction occurred, as that is where the LRU order
  501. * during folio reclaim is being determined.
  502. *
  503. * However, the cgroup that will own the folio is the one that
  504. * is actually experiencing the refault event. Make sure the folio is
  505. * locked to guarantee folio_memcg() stability throughout.
  506. */
  507. VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
  508. nr = folio_nr_pages(folio);
  509. memcg = folio_memcg(folio);
  510. pgdat = folio_pgdat(folio);
  511. lruvec = mem_cgroup_lruvec(memcg, pgdat);
  512. mod_lruvec_state(lruvec, WORKINGSET_REFAULT_BASE + file, nr);
  513. if (!workingset_test_recent(shadow, file, &workingset, true))
  514. return;
  515. folio_set_active(folio);
  516. workingset_age_nonresident(lruvec, nr);
  517. mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + file, nr);
  518. /* Folio was active prior to eviction */
  519. if (workingset) {
  520. folio_set_workingset(folio);
  521. /*
  522. * XXX: Move to folio_add_lru() when it supports new vs
  523. * putback
  524. */
  525. lru_note_cost_refault(folio);
  526. mod_lruvec_state(lruvec, WORKINGSET_RESTORE_BASE + file, nr);
  527. }
  528. }
  529. /**
  530. * workingset_activation - note a page activation
  531. * @folio: Folio that is being activated.
  532. */
  533. void workingset_activation(struct folio *folio)
  534. {
  535. struct mem_cgroup *memcg;
  536. rcu_read_lock();
  537. /*
  538. * Filter non-memcg pages here, e.g. unmap can call
  539. * mark_page_accessed() on VDSO pages.
  540. *
  541. * XXX: See workingset_refault() - this should return
  542. * root_mem_cgroup even for !CONFIG_MEMCG.
  543. */
  544. memcg = folio_memcg_rcu(folio);
  545. if (!mem_cgroup_disabled() && !memcg)
  546. goto out;
  547. workingset_age_nonresident(folio_lruvec(folio), folio_nr_pages(folio));
  548. out:
  549. rcu_read_unlock();
  550. }
  551. /*
  552. * Shadow entries reflect the share of the working set that does not
  553. * fit into memory, so their number depends on the access pattern of
  554. * the workload. In most cases, they will refault or get reclaimed
  555. * along with the inode, but a (malicious) workload that streams
  556. * through files with a total size several times that of available
  557. * memory, while preventing the inodes from being reclaimed, can
  558. * create excessive amounts of shadow nodes. To keep a lid on this,
  559. * track shadow nodes and reclaim them when they grow way past the
  560. * point where they would still be useful.
  561. */
  562. struct list_lru shadow_nodes;
  563. void workingset_update_node(struct xa_node *node)
  564. {
  565. struct address_space *mapping;
  566. struct page *page = virt_to_page(node);
  567. /*
  568. * Track non-empty nodes that contain only shadow entries;
  569. * unlink those that contain pages or are being freed.
  570. *
  571. * Avoid acquiring the list_lru lock when the nodes are
  572. * already where they should be. The list_empty() test is safe
  573. * as node->private_list is protected by the i_pages lock.
  574. */
  575. mapping = container_of(node->array, struct address_space, i_pages);
  576. lockdep_assert_held(&mapping->i_pages.xa_lock);
  577. if (node->count && node->count == node->nr_values) {
  578. if (list_empty(&node->private_list)) {
  579. list_lru_add_obj(&shadow_nodes, &node->private_list);
  580. __inc_node_page_state(page, WORKINGSET_NODES);
  581. }
  582. } else {
  583. if (!list_empty(&node->private_list)) {
  584. list_lru_del_obj(&shadow_nodes, &node->private_list);
  585. __dec_node_page_state(page, WORKINGSET_NODES);
  586. }
  587. }
  588. }
  589. static unsigned long count_shadow_nodes(struct shrinker *shrinker,
  590. struct shrink_control *sc)
  591. {
  592. unsigned long max_nodes;
  593. unsigned long nodes;
  594. unsigned long pages;
  595. nodes = list_lru_shrink_count(&shadow_nodes, sc);
  596. if (!nodes)
  597. return SHRINK_EMPTY;
  598. /*
  599. * Approximate a reasonable limit for the nodes
  600. * containing shadow entries. We don't need to keep more
  601. * shadow entries than possible pages on the active list,
  602. * since refault distances bigger than that are dismissed.
  603. *
  604. * The size of the active list converges toward 100% of
  605. * overall page cache as memory grows, with only a tiny
  606. * inactive list. Assume the total cache size for that.
  607. *
  608. * Nodes might be sparsely populated, with only one shadow
  609. * entry in the extreme case. Obviously, we cannot keep one
  610. * node for every eligible shadow entry, so compromise on a
  611. * worst-case density of 1/8th. Below that, not all eligible
  612. * refaults can be detected anymore.
  613. *
  614. * On 64-bit with 7 xa_nodes per page and 64 slots
  615. * each, this will reclaim shadow entries when they consume
  616. * ~1.8% of available memory:
  617. *
  618. * PAGE_SIZE / xa_nodes / node_entries * 8 / PAGE_SIZE
  619. */
  620. #ifdef CONFIG_MEMCG
  621. if (sc->memcg) {
  622. struct lruvec *lruvec;
  623. int i;
  624. mem_cgroup_flush_stats_ratelimited(sc->memcg);
  625. lruvec = mem_cgroup_lruvec(sc->memcg, NODE_DATA(sc->nid));
  626. for (pages = 0, i = 0; i < NR_LRU_LISTS; i++)
  627. pages += lruvec_page_state_local(lruvec,
  628. NR_LRU_BASE + i);
  629. pages += lruvec_page_state_local(
  630. lruvec, NR_SLAB_RECLAIMABLE_B) >> PAGE_SHIFT;
  631. pages += lruvec_page_state_local(
  632. lruvec, NR_SLAB_UNRECLAIMABLE_B) >> PAGE_SHIFT;
  633. } else
  634. #endif
  635. pages = node_present_pages(sc->nid);
  636. max_nodes = pages >> (XA_CHUNK_SHIFT - 3);
  637. if (nodes <= max_nodes)
  638. return 0;
  639. return nodes - max_nodes;
  640. }
  641. static enum lru_status shadow_lru_isolate(struct list_head *item,
  642. struct list_lru_one *lru,
  643. spinlock_t *lru_lock,
  644. void *arg) __must_hold(lru_lock)
  645. {
  646. struct xa_node *node = container_of(item, struct xa_node, private_list);
  647. struct address_space *mapping;
  648. int ret;
  649. /*
  650. * Page cache insertions and deletions synchronously maintain
  651. * the shadow node LRU under the i_pages lock and the
  652. * lru_lock. Because the page cache tree is emptied before
  653. * the inode can be destroyed, holding the lru_lock pins any
  654. * address_space that has nodes on the LRU.
  655. *
  656. * We can then safely transition to the i_pages lock to
  657. * pin only the address_space of the particular node we want
  658. * to reclaim, take the node off-LRU, and drop the lru_lock.
  659. */
  660. mapping = container_of(node->array, struct address_space, i_pages);
  661. /* Coming from the list, invert the lock order */
  662. if (!xa_trylock(&mapping->i_pages)) {
  663. spin_unlock_irq(lru_lock);
  664. ret = LRU_RETRY;
  665. goto out;
  666. }
  667. /* For page cache we need to hold i_lock */
  668. if (mapping->host != NULL) {
  669. if (!spin_trylock(&mapping->host->i_lock)) {
  670. xa_unlock(&mapping->i_pages);
  671. spin_unlock_irq(lru_lock);
  672. ret = LRU_RETRY;
  673. goto out;
  674. }
  675. }
  676. list_lru_isolate(lru, item);
  677. __dec_node_page_state(virt_to_page(node), WORKINGSET_NODES);
  678. spin_unlock(lru_lock);
  679. /*
  680. * The nodes should only contain one or more shadow entries,
  681. * no pages, so we expect to be able to remove them all and
  682. * delete and free the empty node afterwards.
  683. */
  684. if (WARN_ON_ONCE(!node->nr_values))
  685. goto out_invalid;
  686. if (WARN_ON_ONCE(node->count != node->nr_values))
  687. goto out_invalid;
  688. xa_delete_node(node, workingset_update_node);
  689. __inc_lruvec_kmem_state(node, WORKINGSET_NODERECLAIM);
  690. out_invalid:
  691. xa_unlock_irq(&mapping->i_pages);
  692. if (mapping->host != NULL) {
  693. if (mapping_shrinkable(mapping))
  694. inode_add_lru(mapping->host);
  695. spin_unlock(&mapping->host->i_lock);
  696. }
  697. ret = LRU_REMOVED_RETRY;
  698. out:
  699. cond_resched();
  700. spin_lock_irq(lru_lock);
  701. return ret;
  702. }
  703. static unsigned long scan_shadow_nodes(struct shrinker *shrinker,
  704. struct shrink_control *sc)
  705. {
  706. /* list_lru lock nests inside the IRQ-safe i_pages lock */
  707. return list_lru_shrink_walk_irq(&shadow_nodes, sc, shadow_lru_isolate,
  708. NULL);
  709. }
  710. /*
  711. * Our list_lru->lock is IRQ-safe as it nests inside the IRQ-safe
  712. * i_pages lock.
  713. */
  714. static struct lock_class_key shadow_nodes_key;
  715. static int __init workingset_init(void)
  716. {
  717. struct shrinker *workingset_shadow_shrinker;
  718. unsigned int timestamp_bits;
  719. unsigned int max_order;
  720. int ret = -ENOMEM;
  721. BUILD_BUG_ON(BITS_PER_LONG < EVICTION_SHIFT);
  722. /*
  723. * Calculate the eviction bucket size to cover the longest
  724. * actionable refault distance, which is currently half of
  725. * memory (totalram_pages/2). However, memory hotplug may add
  726. * some more pages at runtime, so keep working with up to
  727. * double the initial memory by using totalram_pages as-is.
  728. */
  729. timestamp_bits = BITS_PER_LONG - EVICTION_SHIFT;
  730. max_order = fls_long(totalram_pages() - 1);
  731. if (max_order > timestamp_bits)
  732. bucket_order = max_order - timestamp_bits;
  733. pr_info("workingset: timestamp_bits=%d max_order=%d bucket_order=%u\n",
  734. timestamp_bits, max_order, bucket_order);
  735. workingset_shadow_shrinker = shrinker_alloc(SHRINKER_NUMA_AWARE |
  736. SHRINKER_MEMCG_AWARE,
  737. "mm-shadow");
  738. if (!workingset_shadow_shrinker)
  739. goto err;
  740. ret = __list_lru_init(&shadow_nodes, true, &shadow_nodes_key,
  741. workingset_shadow_shrinker);
  742. if (ret)
  743. goto err_list_lru;
  744. workingset_shadow_shrinker->count_objects = count_shadow_nodes;
  745. workingset_shadow_shrinker->scan_objects = scan_shadow_nodes;
  746. /* ->count reports only fully expendable nodes */
  747. workingset_shadow_shrinker->seeks = 0;
  748. shrinker_register(workingset_shadow_shrinker);
  749. return 0;
  750. err_list_lru:
  751. shrinker_free(workingset_shadow_shrinker);
  752. err:
  753. return ret;
  754. }
  755. module_init(workingset_init);