page_counter.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Lockless hierarchical page accounting & limiting
  4. *
  5. * Copyright (C) 2014 Red Hat, Inc., Johannes Weiner
  6. */
  7. #include <linux/page_counter.h>
  8. #include <linux/atomic.h>
  9. #include <linux/kernel.h>
  10. #include <linux/string.h>
  11. #include <linux/sched.h>
  12. #include <linux/bug.h>
  13. #include <asm/page.h>
  14. static bool track_protection(struct page_counter *c)
  15. {
  16. return c->protection_support;
  17. }
  18. static void propagate_protected_usage(struct page_counter *c,
  19. unsigned long usage)
  20. {
  21. unsigned long protected, old_protected;
  22. long delta;
  23. if (!c->parent)
  24. return;
  25. protected = min(usage, READ_ONCE(c->min));
  26. old_protected = atomic_long_read(&c->min_usage);
  27. if (protected != old_protected) {
  28. old_protected = atomic_long_xchg(&c->min_usage, protected);
  29. delta = protected - old_protected;
  30. if (delta)
  31. atomic_long_add(delta, &c->parent->children_min_usage);
  32. }
  33. protected = min(usage, READ_ONCE(c->low));
  34. old_protected = atomic_long_read(&c->low_usage);
  35. if (protected != old_protected) {
  36. old_protected = atomic_long_xchg(&c->low_usage, protected);
  37. delta = protected - old_protected;
  38. if (delta)
  39. atomic_long_add(delta, &c->parent->children_low_usage);
  40. }
  41. }
  42. /**
  43. * page_counter_cancel - take pages out of the local counter
  44. * @counter: counter
  45. * @nr_pages: number of pages to cancel
  46. */
  47. void page_counter_cancel(struct page_counter *counter, unsigned long nr_pages)
  48. {
  49. long new;
  50. new = atomic_long_sub_return(nr_pages, &counter->usage);
  51. /* More uncharges than charges? */
  52. if (WARN_ONCE(new < 0, "page_counter underflow: %ld nr_pages=%lu\n",
  53. new, nr_pages)) {
  54. new = 0;
  55. atomic_long_set(&counter->usage, new);
  56. }
  57. if (track_protection(counter))
  58. propagate_protected_usage(counter, new);
  59. }
  60. /**
  61. * page_counter_charge - hierarchically charge pages
  62. * @counter: counter
  63. * @nr_pages: number of pages to charge
  64. *
  65. * NOTE: This does not consider any configured counter limits.
  66. */
  67. void page_counter_charge(struct page_counter *counter, unsigned long nr_pages)
  68. {
  69. struct page_counter *c;
  70. bool protection = track_protection(counter);
  71. for (c = counter; c; c = c->parent) {
  72. long new;
  73. new = atomic_long_add_return(nr_pages, &c->usage);
  74. if (protection)
  75. propagate_protected_usage(c, new);
  76. /*
  77. * This is indeed racy, but we can live with some
  78. * inaccuracy in the watermark.
  79. *
  80. * Notably, we have two watermarks to allow for both a globally
  81. * visible peak and one that can be reset at a smaller scope.
  82. *
  83. * Since we reset both watermarks when the global reset occurs,
  84. * we can guarantee that watermark >= local_watermark, so we
  85. * don't need to do both comparisons every time.
  86. *
  87. * On systems with branch predictors, the inner condition should
  88. * be almost free.
  89. */
  90. if (new > READ_ONCE(c->local_watermark)) {
  91. WRITE_ONCE(c->local_watermark, new);
  92. if (new > READ_ONCE(c->watermark))
  93. WRITE_ONCE(c->watermark, new);
  94. }
  95. }
  96. }
  97. /**
  98. * page_counter_try_charge - try to hierarchically charge pages
  99. * @counter: counter
  100. * @nr_pages: number of pages to charge
  101. * @fail: points first counter to hit its limit, if any
  102. *
  103. * Returns %true on success, or %false and @fail if the counter or one
  104. * of its ancestors has hit its configured limit.
  105. */
  106. bool page_counter_try_charge(struct page_counter *counter,
  107. unsigned long nr_pages,
  108. struct page_counter **fail)
  109. {
  110. struct page_counter *c;
  111. bool protection = track_protection(counter);
  112. bool track_failcnt = counter->track_failcnt;
  113. for (c = counter; c; c = c->parent) {
  114. long new;
  115. /*
  116. * Charge speculatively to avoid an expensive CAS. If
  117. * a bigger charge fails, it might falsely lock out a
  118. * racing smaller charge and send it into reclaim
  119. * early, but the error is limited to the difference
  120. * between the two sizes, which is less than 2M/4M in
  121. * case of a THP locking out a regular page charge.
  122. *
  123. * The atomic_long_add_return() implies a full memory
  124. * barrier between incrementing the count and reading
  125. * the limit. When racing with page_counter_set_max(),
  126. * we either see the new limit or the setter sees the
  127. * counter has changed and retries.
  128. */
  129. new = atomic_long_add_return(nr_pages, &c->usage);
  130. if (new > c->max) {
  131. atomic_long_sub(nr_pages, &c->usage);
  132. /*
  133. * This is racy, but we can live with some
  134. * inaccuracy in the failcnt which is only used
  135. * to report stats.
  136. */
  137. if (track_failcnt)
  138. data_race(c->failcnt++);
  139. *fail = c;
  140. goto failed;
  141. }
  142. if (protection)
  143. propagate_protected_usage(c, new);
  144. /* see comment on page_counter_charge */
  145. if (new > READ_ONCE(c->local_watermark)) {
  146. WRITE_ONCE(c->local_watermark, new);
  147. if (new > READ_ONCE(c->watermark))
  148. WRITE_ONCE(c->watermark, new);
  149. }
  150. }
  151. return true;
  152. failed:
  153. for (c = counter; c != *fail; c = c->parent)
  154. page_counter_cancel(c, nr_pages);
  155. return false;
  156. }
  157. /**
  158. * page_counter_uncharge - hierarchically uncharge pages
  159. * @counter: counter
  160. * @nr_pages: number of pages to uncharge
  161. */
  162. void page_counter_uncharge(struct page_counter *counter, unsigned long nr_pages)
  163. {
  164. struct page_counter *c;
  165. for (c = counter; c; c = c->parent)
  166. page_counter_cancel(c, nr_pages);
  167. }
  168. /**
  169. * page_counter_set_max - set the maximum number of pages allowed
  170. * @counter: counter
  171. * @nr_pages: limit to set
  172. *
  173. * Returns 0 on success, -EBUSY if the current number of pages on the
  174. * counter already exceeds the specified limit.
  175. *
  176. * The caller must serialize invocations on the same counter.
  177. */
  178. int page_counter_set_max(struct page_counter *counter, unsigned long nr_pages)
  179. {
  180. for (;;) {
  181. unsigned long old;
  182. long usage;
  183. /*
  184. * Update the limit while making sure that it's not
  185. * below the concurrently-changing counter value.
  186. *
  187. * The xchg implies two full memory barriers before
  188. * and after, so the read-swap-read is ordered and
  189. * ensures coherency with page_counter_try_charge():
  190. * that function modifies the count before checking
  191. * the limit, so if it sees the old limit, we see the
  192. * modified counter and retry.
  193. */
  194. usage = page_counter_read(counter);
  195. if (usage > nr_pages)
  196. return -EBUSY;
  197. old = xchg(&counter->max, nr_pages);
  198. if (page_counter_read(counter) <= usage || nr_pages >= old)
  199. return 0;
  200. counter->max = old;
  201. cond_resched();
  202. }
  203. }
  204. /**
  205. * page_counter_set_min - set the amount of protected memory
  206. * @counter: counter
  207. * @nr_pages: value to set
  208. *
  209. * The caller must serialize invocations on the same counter.
  210. */
  211. void page_counter_set_min(struct page_counter *counter, unsigned long nr_pages)
  212. {
  213. struct page_counter *c;
  214. WRITE_ONCE(counter->min, nr_pages);
  215. for (c = counter; c; c = c->parent)
  216. propagate_protected_usage(c, atomic_long_read(&c->usage));
  217. }
  218. /**
  219. * page_counter_set_low - set the amount of protected memory
  220. * @counter: counter
  221. * @nr_pages: value to set
  222. *
  223. * The caller must serialize invocations on the same counter.
  224. */
  225. void page_counter_set_low(struct page_counter *counter, unsigned long nr_pages)
  226. {
  227. struct page_counter *c;
  228. WRITE_ONCE(counter->low, nr_pages);
  229. for (c = counter; c; c = c->parent)
  230. propagate_protected_usage(c, atomic_long_read(&c->usage));
  231. }
  232. /**
  233. * page_counter_memparse - memparse() for page counter limits
  234. * @buf: string to parse
  235. * @max: string meaning maximum possible value
  236. * @nr_pages: returns the result in number of pages
  237. *
  238. * Returns -EINVAL, or 0 and @nr_pages on success. @nr_pages will be
  239. * limited to %PAGE_COUNTER_MAX.
  240. */
  241. int page_counter_memparse(const char *buf, const char *max,
  242. unsigned long *nr_pages)
  243. {
  244. char *end;
  245. u64 bytes;
  246. if (!strcmp(buf, max)) {
  247. *nr_pages = PAGE_COUNTER_MAX;
  248. return 0;
  249. }
  250. bytes = memparse(buf, &end);
  251. if (*end != '\0')
  252. return -EINVAL;
  253. *nr_pages = min(bytes / PAGE_SIZE, (u64)PAGE_COUNTER_MAX);
  254. return 0;
  255. }
  256. #if IS_ENABLED(CONFIG_MEMCG) || IS_ENABLED(CONFIG_CGROUP_DMEM)
  257. /*
  258. * This function calculates an individual page counter's effective
  259. * protection which is derived from its own memory.min/low, its
  260. * parent's and siblings' settings, as well as the actual memory
  261. * distribution in the tree.
  262. *
  263. * The following rules apply to the effective protection values:
  264. *
  265. * 1. At the first level of reclaim, effective protection is equal to
  266. * the declared protection in memory.min and memory.low.
  267. *
  268. * 2. To enable safe delegation of the protection configuration, at
  269. * subsequent levels the effective protection is capped to the
  270. * parent's effective protection.
  271. *
  272. * 3. To make complex and dynamic subtrees easier to configure, the
  273. * user is allowed to overcommit the declared protection at a given
  274. * level. If that is the case, the parent's effective protection is
  275. * distributed to the children in proportion to how much protection
  276. * they have declared and how much of it they are utilizing.
  277. *
  278. * This makes distribution proportional, but also work-conserving:
  279. * if one counter claims much more protection than it uses memory,
  280. * the unused remainder is available to its siblings.
  281. *
  282. * 4. Conversely, when the declared protection is undercommitted at a
  283. * given level, the distribution of the larger parental protection
  284. * budget is NOT proportional. A counter's protection from a sibling
  285. * is capped to its own memory.min/low setting.
  286. *
  287. * 5. However, to allow protecting recursive subtrees from each other
  288. * without having to declare each individual counter's fixed share
  289. * of the ancestor's claim to protection, any unutilized -
  290. * "floating" - protection from up the tree is distributed in
  291. * proportion to each counter's *usage*. This makes the protection
  292. * neutral wrt sibling cgroups and lets them compete freely over
  293. * the shared parental protection budget, but it protects the
  294. * subtree as a whole from neighboring subtrees.
  295. *
  296. * Note that 4. and 5. are not in conflict: 4. is about protecting
  297. * against immediate siblings whereas 5. is about protecting against
  298. * neighboring subtrees.
  299. */
  300. static unsigned long effective_protection(unsigned long usage,
  301. unsigned long parent_usage,
  302. unsigned long setting,
  303. unsigned long parent_effective,
  304. unsigned long siblings_protected,
  305. bool recursive_protection)
  306. {
  307. unsigned long protected;
  308. unsigned long ep;
  309. protected = min(usage, setting);
  310. /*
  311. * If all cgroups at this level combined claim and use more
  312. * protection than what the parent affords them, distribute
  313. * shares in proportion to utilization.
  314. *
  315. * We are using actual utilization rather than the statically
  316. * claimed protection in order to be work-conserving: claimed
  317. * but unused protection is available to siblings that would
  318. * otherwise get a smaller chunk than what they claimed.
  319. */
  320. if (siblings_protected > parent_effective)
  321. return protected * parent_effective / siblings_protected;
  322. /*
  323. * Ok, utilized protection of all children is within what the
  324. * parent affords them, so we know whatever this child claims
  325. * and utilizes is effectively protected.
  326. *
  327. * If there is unprotected usage beyond this value, reclaim
  328. * will apply pressure in proportion to that amount.
  329. *
  330. * If there is unutilized protection, the cgroup will be fully
  331. * shielded from reclaim, but we do return a smaller value for
  332. * protection than what the group could enjoy in theory. This
  333. * is okay. With the overcommit distribution above, effective
  334. * protection is always dependent on how memory is actually
  335. * consumed among the siblings anyway.
  336. */
  337. ep = protected;
  338. /*
  339. * If the children aren't claiming (all of) the protection
  340. * afforded to them by the parent, distribute the remainder in
  341. * proportion to the (unprotected) memory of each cgroup. That
  342. * way, cgroups that aren't explicitly prioritized wrt each
  343. * other compete freely over the allowance, but they are
  344. * collectively protected from neighboring trees.
  345. *
  346. * We're using unprotected memory for the weight so that if
  347. * some cgroups DO claim explicit protection, we don't protect
  348. * the same bytes twice.
  349. *
  350. * Check both usage and parent_usage against the respective
  351. * protected values. One should imply the other, but they
  352. * aren't read atomically - make sure the division is sane.
  353. */
  354. if (!recursive_protection)
  355. return ep;
  356. if (parent_effective > siblings_protected &&
  357. parent_usage > siblings_protected &&
  358. usage > protected) {
  359. unsigned long unclaimed;
  360. unclaimed = parent_effective - siblings_protected;
  361. unclaimed *= usage - protected;
  362. unclaimed /= parent_usage - siblings_protected;
  363. ep += unclaimed;
  364. }
  365. return ep;
  366. }
  367. /**
  368. * page_counter_calculate_protection - check if memory consumption is in the normal range
  369. * @root: the top ancestor of the sub-tree being checked
  370. * @counter: the page_counter the counter to update
  371. * @recursive_protection: Whether to use memory_recursiveprot behavior.
  372. *
  373. * Calculates elow/emin thresholds for given page_counter.
  374. *
  375. * WARNING: This function is not stateless! It can only be used as part
  376. * of a top-down tree iteration, not for isolated queries.
  377. */
  378. void page_counter_calculate_protection(struct page_counter *root,
  379. struct page_counter *counter,
  380. bool recursive_protection)
  381. {
  382. unsigned long usage, parent_usage;
  383. struct page_counter *parent = counter->parent;
  384. /*
  385. * Effective values of the reclaim targets are ignored so they
  386. * can be stale. Have a look at mem_cgroup_protection for more
  387. * details.
  388. * TODO: calculation should be more robust so that we do not need
  389. * that special casing.
  390. */
  391. if (root == counter)
  392. return;
  393. usage = page_counter_read(counter);
  394. if (!usage)
  395. return;
  396. if (parent == root) {
  397. counter->emin = READ_ONCE(counter->min);
  398. counter->elow = READ_ONCE(counter->low);
  399. return;
  400. }
  401. parent_usage = page_counter_read(parent);
  402. WRITE_ONCE(counter->emin, effective_protection(usage, parent_usage,
  403. READ_ONCE(counter->min),
  404. READ_ONCE(parent->emin),
  405. atomic_long_read(&parent->children_min_usage),
  406. recursive_protection));
  407. WRITE_ONCE(counter->elow, effective_protection(usage, parent_usage,
  408. READ_ONCE(counter->low),
  409. READ_ONCE(parent->elow),
  410. atomic_long_read(&parent->children_low_usage),
  411. recursive_protection));
  412. }
  413. #endif /* CONFIG_MEMCG || CONFIG_CGROUP_DMEM */