vmpressure.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * Linux VM pressure
  4. *
  5. * Copyright 2012 Linaro Ltd.
  6. * Anton Vorontsov <[email protected]>
  7. *
  8. * Based on ideas from Andrew Morton, David Rientjes, KOSAKI Motohiro,
  9. * Leonid Moiseichuk, Mel Gorman, Minchan Kim and Pekka Enberg.
  10. */
  11. #include <linux/cgroup.h>
  12. #include <linux/fs.h>
  13. #include <linux/log2.h>
  14. #include <linux/sched.h>
  15. #include <linux/mm.h>
  16. #include <linux/vmstat.h>
  17. #include <linux/eventfd.h>
  18. #include <linux/slab.h>
  19. #include <linux/swap.h>
  20. #include <linux/printk.h>
  21. #include <linux/vmpressure.h>
  22. /*
  23. * The window size (vmpressure_win) is the number of scanned pages before
  24. * we try to analyze scanned/reclaimed ratio. So the window is used as a
  25. * rate-limit tunable for the "low" level notification, and also for
  26. * averaging the ratio for medium/critical levels. Using small window
  27. * sizes can cause lot of false positives, but too big window size will
  28. * delay the notifications.
  29. *
  30. * As the vmscan reclaimer logic works with chunks which are multiple of
  31. * SWAP_CLUSTER_MAX, it makes sense to use it for the window size as well.
  32. *
  33. * TODO: Make the window size depend on machine size, as we do for vmstat
  34. * thresholds. Currently we set it to 512 pages (2MB for 4KB pages).
  35. */
  36. static const unsigned long vmpressure_win = SWAP_CLUSTER_MAX * 16;
  37. /*
  38. * These thresholds are used when we account memory pressure through
  39. * scanned/reclaimed ratio. The current values were chosen empirically. In
  40. * essence, they are percents: the higher the value, the more number
  41. * unsuccessful reclaims there were.
  42. */
  43. static const unsigned int vmpressure_level_med = 60;
  44. static const unsigned int vmpressure_level_critical = 95;
  45. /*
  46. * When there are too little pages left to scan, vmpressure() may miss the
  47. * critical pressure as number of pages will be less than "window size".
  48. * However, in that case the vmscan priority will raise fast as the
  49. * reclaimer will try to scan LRUs more deeply.
  50. *
  51. * The vmscan logic considers these special priorities:
  52. *
  53. * prio == DEF_PRIORITY (12): reclaimer starts with that value
  54. * prio <= DEF_PRIORITY - 2 : kswapd becomes somewhat overwhelmed
  55. * prio == 0 : close to OOM, kernel scans every page in an lru
  56. *
  57. * Any value in this range is acceptable for this tunable (i.e. from 12 to
  58. * 0). Current value for the vmpressure_level_critical_prio is chosen
  59. * empirically, but the number, in essence, means that we consider
  60. * critical level when scanning depth is ~10% of the lru size (vmscan
  61. * scans 'lru_size >> prio' pages, so it is actually 12.5%, or one
  62. * eights).
  63. */
  64. static const unsigned int vmpressure_level_critical_prio = ilog2(100 / 10);
  65. static struct vmpressure *work_to_vmpressure(struct work_struct *work)
  66. {
  67. return container_of(work, struct vmpressure, work);
  68. }
  69. static struct vmpressure *vmpressure_parent(struct vmpressure *vmpr)
  70. {
  71. struct mem_cgroup *memcg = vmpressure_to_memcg(vmpr);
  72. memcg = parent_mem_cgroup(memcg);
  73. if (!memcg)
  74. return NULL;
  75. return memcg_to_vmpressure(memcg);
  76. }
  77. enum vmpressure_levels {
  78. VMPRESSURE_LOW = 0,
  79. VMPRESSURE_MEDIUM,
  80. VMPRESSURE_CRITICAL,
  81. VMPRESSURE_NUM_LEVELS,
  82. };
  83. enum vmpressure_modes {
  84. VMPRESSURE_NO_PASSTHROUGH = 0,
  85. VMPRESSURE_HIERARCHY,
  86. VMPRESSURE_LOCAL,
  87. VMPRESSURE_NUM_MODES,
  88. };
  89. static const char * const vmpressure_str_levels[] = {
  90. [VMPRESSURE_LOW] = "low",
  91. [VMPRESSURE_MEDIUM] = "medium",
  92. [VMPRESSURE_CRITICAL] = "critical",
  93. };
  94. static const char * const vmpressure_str_modes[] = {
  95. [VMPRESSURE_NO_PASSTHROUGH] = "default",
  96. [VMPRESSURE_HIERARCHY] = "hierarchy",
  97. [VMPRESSURE_LOCAL] = "local",
  98. };
  99. static enum vmpressure_levels vmpressure_level(unsigned long pressure)
  100. {
  101. if (pressure >= vmpressure_level_critical)
  102. return VMPRESSURE_CRITICAL;
  103. else if (pressure >= vmpressure_level_med)
  104. return VMPRESSURE_MEDIUM;
  105. return VMPRESSURE_LOW;
  106. }
  107. static enum vmpressure_levels vmpressure_calc_level(unsigned long scanned,
  108. unsigned long reclaimed)
  109. {
  110. unsigned long scale = scanned + reclaimed;
  111. unsigned long pressure = 0;
  112. /*
  113. * reclaimed can be greater than scanned for things such as reclaimed
  114. * slab pages. shrink_node() just adds reclaimed pages without a
  115. * related increment to scanned pages.
  116. */
  117. if (reclaimed >= scanned)
  118. goto out;
  119. /*
  120. * We calculate the ratio (in percents) of how many pages were
  121. * scanned vs. reclaimed in a given time frame (window). Note that
  122. * time is in VM reclaimer's "ticks", i.e. number of pages
  123. * scanned. This makes it possible to set desired reaction time
  124. * and serves as a ratelimit.
  125. */
  126. pressure = scale - (reclaimed * scale / scanned);
  127. pressure = pressure * 100 / scale;
  128. out:
  129. pr_debug("%s: %3lu (s: %lu r: %lu)\n", __func__, pressure,
  130. scanned, reclaimed);
  131. return vmpressure_level(pressure);
  132. }
  133. struct vmpressure_event {
  134. struct eventfd_ctx *efd;
  135. enum vmpressure_levels level;
  136. enum vmpressure_modes mode;
  137. struct list_head node;
  138. };
  139. static bool vmpressure_event(struct vmpressure *vmpr,
  140. const enum vmpressure_levels level,
  141. bool ancestor, bool signalled)
  142. {
  143. struct vmpressure_event *ev;
  144. bool ret = false;
  145. mutex_lock(&vmpr->events_lock);
  146. list_for_each_entry(ev, &vmpr->events, node) {
  147. if (ancestor && ev->mode == VMPRESSURE_LOCAL)
  148. continue;
  149. if (signalled && ev->mode == VMPRESSURE_NO_PASSTHROUGH)
  150. continue;
  151. if (level < ev->level)
  152. continue;
  153. eventfd_signal(ev->efd, 1);
  154. ret = true;
  155. }
  156. mutex_unlock(&vmpr->events_lock);
  157. return ret;
  158. }
  159. static void vmpressure_work_fn(struct work_struct *work)
  160. {
  161. struct vmpressure *vmpr = work_to_vmpressure(work);
  162. unsigned long scanned;
  163. unsigned long reclaimed;
  164. enum vmpressure_levels level;
  165. bool ancestor = false;
  166. bool signalled = false;
  167. spin_lock(&vmpr->sr_lock);
  168. /*
  169. * Several contexts might be calling vmpressure(), so it is
  170. * possible that the work was rescheduled again before the old
  171. * work context cleared the counters. In that case we will run
  172. * just after the old work returns, but then scanned might be zero
  173. * here. No need for any locks here since we don't care if
  174. * vmpr->reclaimed is in sync.
  175. */
  176. scanned = vmpr->tree_scanned;
  177. if (!scanned) {
  178. spin_unlock(&vmpr->sr_lock);
  179. return;
  180. }
  181. reclaimed = vmpr->tree_reclaimed;
  182. vmpr->tree_scanned = 0;
  183. vmpr->tree_reclaimed = 0;
  184. spin_unlock(&vmpr->sr_lock);
  185. level = vmpressure_calc_level(scanned, reclaimed);
  186. do {
  187. if (vmpressure_event(vmpr, level, ancestor, signalled))
  188. signalled = true;
  189. ancestor = true;
  190. } while ((vmpr = vmpressure_parent(vmpr)));
  191. }
  192. /**
  193. * vmpressure() - Account memory pressure through scanned/reclaimed ratio
  194. * @gfp: reclaimer's gfp mask
  195. * @memcg: cgroup memory controller handle
  196. * @tree: legacy subtree mode
  197. * @scanned: number of pages scanned
  198. * @reclaimed: number of pages reclaimed
  199. *
  200. * This function should be called from the vmscan reclaim path to account
  201. * "instantaneous" memory pressure (scanned/reclaimed ratio). The raw
  202. * pressure index is then further refined and averaged over time.
  203. *
  204. * If @tree is set, vmpressure is in traditional userspace reporting
  205. * mode: @memcg is considered the pressure root and userspace is
  206. * notified of the entire subtree's reclaim efficiency.
  207. *
  208. * If @tree is not set, reclaim efficiency is recorded for @memcg, and
  209. * only in-kernel users are notified.
  210. *
  211. * This function does not return any value.
  212. */
  213. void vmpressure(gfp_t gfp, struct mem_cgroup *memcg, bool tree,
  214. unsigned long scanned, unsigned long reclaimed)
  215. {
  216. struct vmpressure *vmpr;
  217. if (mem_cgroup_disabled())
  218. return;
  219. /*
  220. * The in-kernel users only care about the reclaim efficiency
  221. * for this @memcg rather than the whole subtree, and there
  222. * isn't and won't be any in-kernel user in a legacy cgroup.
  223. */
  224. if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !tree)
  225. return;
  226. vmpr = memcg_to_vmpressure(memcg);
  227. /*
  228. * Here we only want to account pressure that userland is able to
  229. * help us with. For example, suppose that DMA zone is under
  230. * pressure; if we notify userland about that kind of pressure,
  231. * then it will be mostly a waste as it will trigger unnecessary
  232. * freeing of memory by userland (since userland is more likely to
  233. * have HIGHMEM/MOVABLE pages instead of the DMA fallback). That
  234. * is why we include only movable, highmem and FS/IO pages.
  235. * Indirect reclaim (kswapd) sets sc->gfp_mask to GFP_KERNEL, so
  236. * we account it too.
  237. */
  238. if (!(gfp & (__GFP_HIGHMEM | __GFP_MOVABLE | __GFP_IO | __GFP_FS)))
  239. return;
  240. /*
  241. * If we got here with no pages scanned, then that is an indicator
  242. * that reclaimer was unable to find any shrinkable LRUs at the
  243. * current scanning depth. But it does not mean that we should
  244. * report the critical pressure, yet. If the scanning priority
  245. * (scanning depth) goes too high (deep), we will be notified
  246. * through vmpressure_prio(). But so far, keep calm.
  247. */
  248. if (!scanned)
  249. return;
  250. if (tree) {
  251. spin_lock(&vmpr->sr_lock);
  252. scanned = vmpr->tree_scanned += scanned;
  253. vmpr->tree_reclaimed += reclaimed;
  254. spin_unlock(&vmpr->sr_lock);
  255. if (scanned < vmpressure_win)
  256. return;
  257. schedule_work(&vmpr->work);
  258. } else {
  259. enum vmpressure_levels level;
  260. /* For now, no users for root-level efficiency */
  261. if (!memcg || mem_cgroup_is_root(memcg))
  262. return;
  263. spin_lock(&vmpr->sr_lock);
  264. scanned = vmpr->scanned += scanned;
  265. reclaimed = vmpr->reclaimed += reclaimed;
  266. if (scanned < vmpressure_win) {
  267. spin_unlock(&vmpr->sr_lock);
  268. return;
  269. }
  270. vmpr->scanned = vmpr->reclaimed = 0;
  271. spin_unlock(&vmpr->sr_lock);
  272. level = vmpressure_calc_level(scanned, reclaimed);
  273. if (level > VMPRESSURE_LOW) {
  274. /*
  275. * Let the socket buffer allocator know that
  276. * we are having trouble reclaiming LRU pages.
  277. *
  278. * For hysteresis keep the pressure state
  279. * asserted for a second in which subsequent
  280. * pressure events can occur.
  281. */
  282. WRITE_ONCE(memcg->socket_pressure, jiffies + HZ);
  283. }
  284. }
  285. }
  286. /**
  287. * vmpressure_prio() - Account memory pressure through reclaimer priority level
  288. * @gfp: reclaimer's gfp mask
  289. * @memcg: cgroup memory controller handle
  290. * @prio: reclaimer's priority
  291. *
  292. * This function should be called from the reclaim path every time when
  293. * the vmscan's reclaiming priority (scanning depth) changes.
  294. *
  295. * This function does not return any value.
  296. */
  297. void vmpressure_prio(gfp_t gfp, struct mem_cgroup *memcg, int prio)
  298. {
  299. /*
  300. * We only use prio for accounting critical level. For more info
  301. * see comment for vmpressure_level_critical_prio variable above.
  302. */
  303. if (prio > vmpressure_level_critical_prio)
  304. return;
  305. /*
  306. * OK, the prio is below the threshold, updating vmpressure
  307. * information before shrinker dives into long shrinking of long
  308. * range vmscan. Passing scanned = vmpressure_win, reclaimed = 0
  309. * to the vmpressure() basically means that we signal 'critical'
  310. * level.
  311. */
  312. vmpressure(gfp, memcg, true, vmpressure_win, 0);
  313. }
  314. #define MAX_VMPRESSURE_ARGS_LEN (strlen("critical") + strlen("hierarchy") + 2)
  315. /**
  316. * vmpressure_register_event() - Bind vmpressure notifications to an eventfd
  317. * @memcg: memcg that is interested in vmpressure notifications
  318. * @eventfd: eventfd context to link notifications with
  319. * @args: event arguments (pressure level threshold, optional mode)
  320. *
  321. * This function associates eventfd context with the vmpressure
  322. * infrastructure, so that the notifications will be delivered to the
  323. * @eventfd. The @args parameter is a comma-delimited string that denotes a
  324. * pressure level threshold (one of vmpressure_str_levels, i.e. "low", "medium",
  325. * or "critical") and an optional mode (one of vmpressure_str_modes, i.e.
  326. * "hierarchy" or "local").
  327. *
  328. * To be used as memcg event method.
  329. *
  330. * Return: 0 on success, -ENOMEM on memory failure or -EINVAL if @args could
  331. * not be parsed.
  332. */
  333. int vmpressure_register_event(struct mem_cgroup *memcg,
  334. struct eventfd_ctx *eventfd, const char *args)
  335. {
  336. struct vmpressure *vmpr = memcg_to_vmpressure(memcg);
  337. struct vmpressure_event *ev;
  338. enum vmpressure_modes mode = VMPRESSURE_NO_PASSTHROUGH;
  339. enum vmpressure_levels level;
  340. char *spec, *spec_orig;
  341. char *token;
  342. int ret = 0;
  343. spec_orig = spec = kstrndup(args, MAX_VMPRESSURE_ARGS_LEN, GFP_KERNEL);
  344. if (!spec)
  345. return -ENOMEM;
  346. /* Find required level */
  347. token = strsep(&spec, ",");
  348. ret = match_string(vmpressure_str_levels, VMPRESSURE_NUM_LEVELS, token);
  349. if (ret < 0)
  350. goto out;
  351. level = ret;
  352. /* Find optional mode */
  353. token = strsep(&spec, ",");
  354. if (token) {
  355. ret = match_string(vmpressure_str_modes, VMPRESSURE_NUM_MODES, token);
  356. if (ret < 0)
  357. goto out;
  358. mode = ret;
  359. }
  360. ev = kzalloc(sizeof(*ev), GFP_KERNEL);
  361. if (!ev) {
  362. ret = -ENOMEM;
  363. goto out;
  364. }
  365. ev->efd = eventfd;
  366. ev->level = level;
  367. ev->mode = mode;
  368. mutex_lock(&vmpr->events_lock);
  369. list_add(&ev->node, &vmpr->events);
  370. mutex_unlock(&vmpr->events_lock);
  371. ret = 0;
  372. out:
  373. kfree(spec_orig);
  374. return ret;
  375. }
  376. /**
  377. * vmpressure_unregister_event() - Unbind eventfd from vmpressure
  378. * @memcg: memcg handle
  379. * @eventfd: eventfd context that was used to link vmpressure with the @cg
  380. *
  381. * This function does internal manipulations to detach the @eventfd from
  382. * the vmpressure notifications, and then frees internal resources
  383. * associated with the @eventfd (but the @eventfd itself is not freed).
  384. *
  385. * To be used as memcg event method.
  386. */
  387. void vmpressure_unregister_event(struct mem_cgroup *memcg,
  388. struct eventfd_ctx *eventfd)
  389. {
  390. struct vmpressure *vmpr = memcg_to_vmpressure(memcg);
  391. struct vmpressure_event *ev;
  392. mutex_lock(&vmpr->events_lock);
  393. list_for_each_entry(ev, &vmpr->events, node) {
  394. if (ev->efd != eventfd)
  395. continue;
  396. list_del(&ev->node);
  397. kfree(ev);
  398. break;
  399. }
  400. mutex_unlock(&vmpr->events_lock);
  401. }
  402. /**
  403. * vmpressure_init() - Initialize vmpressure control structure
  404. * @vmpr: Structure to be initialized
  405. *
  406. * This function should be called on every allocated vmpressure structure
  407. * before any usage.
  408. */
  409. void vmpressure_init(struct vmpressure *vmpr)
  410. {
  411. spin_lock_init(&vmpr->sr_lock);
  412. mutex_init(&vmpr->events_lock);
  413. INIT_LIST_HEAD(&vmpr->events);
  414. INIT_WORK(&vmpr->work, vmpressure_work_fn);
  415. }
  416. /**
  417. * vmpressure_cleanup() - shuts down vmpressure control structure
  418. * @vmpr: Structure to be cleaned up
  419. *
  420. * This function should be called before the structure in which it is
  421. * embedded is cleaned up.
  422. */
  423. void vmpressure_cleanup(struct vmpressure *vmpr)
  424. {
  425. /*
  426. * Make sure there is no pending work before eventfd infrastructure
  427. * goes away.
  428. */
  429. flush_work(&vmpr->work);
  430. }