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