page_counter.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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. for (c = counter; c; c = c->parent) {
  113. long new;
  114. /*
  115. * Charge speculatively to avoid an expensive CAS. If
  116. * a bigger charge fails, it might falsely lock out a
  117. * racing smaller charge and send it into reclaim
  118. * early, but the error is limited to the difference
  119. * between the two sizes, which is less than 2M/4M in
  120. * case of a THP locking out a regular page charge.
  121. *
  122. * The atomic_long_add_return() implies a full memory
  123. * barrier between incrementing the count and reading
  124. * the limit. When racing with page_counter_set_max(),
  125. * we either see the new limit or the setter sees the
  126. * counter has changed and retries.
  127. */
  128. new = atomic_long_add_return(nr_pages, &c->usage);
  129. if (new > c->max) {
  130. atomic_long_sub(nr_pages, &c->usage);
  131. /*
  132. * This is racy, but we can live with some
  133. * inaccuracy in the failcnt which is only used
  134. * to report stats.
  135. */
  136. data_race(c->failcnt++);
  137. *fail = c;
  138. goto failed;
  139. }
  140. if (protection)
  141. propagate_protected_usage(c, new);
  142. /* see comment on page_counter_charge */
  143. if (new > READ_ONCE(c->local_watermark)) {
  144. WRITE_ONCE(c->local_watermark, new);
  145. if (new > READ_ONCE(c->watermark))
  146. WRITE_ONCE(c->watermark, new);
  147. }
  148. }
  149. return true;
  150. failed:
  151. for (c = counter; c != *fail; c = c->parent)
  152. page_counter_cancel(c, nr_pages);
  153. return false;
  154. }
  155. /**
  156. * page_counter_uncharge - hierarchically uncharge pages
  157. * @counter: counter
  158. * @nr_pages: number of pages to uncharge
  159. */
  160. void page_counter_uncharge(struct page_counter *counter, unsigned long nr_pages)
  161. {
  162. struct page_counter *c;
  163. for (c = counter; c; c = c->parent)
  164. page_counter_cancel(c, nr_pages);
  165. }
  166. /**
  167. * page_counter_set_max - set the maximum number of pages allowed
  168. * @counter: counter
  169. * @nr_pages: limit to set
  170. *
  171. * Returns 0 on success, -EBUSY if the current number of pages on the
  172. * counter already exceeds the specified limit.
  173. *
  174. * The caller must serialize invocations on the same counter.
  175. */
  176. int page_counter_set_max(struct page_counter *counter, unsigned long nr_pages)
  177. {
  178. for (;;) {
  179. unsigned long old;
  180. long usage;
  181. /*
  182. * Update the limit while making sure that it's not
  183. * below the concurrently-changing counter value.
  184. *
  185. * The xchg implies two full memory barriers before
  186. * and after, so the read-swap-read is ordered and
  187. * ensures coherency with page_counter_try_charge():
  188. * that function modifies the count before checking
  189. * the limit, so if it sees the old limit, we see the
  190. * modified counter and retry.
  191. */
  192. usage = page_counter_read(counter);
  193. if (usage > nr_pages)
  194. return -EBUSY;
  195. old = xchg(&counter->max, nr_pages);
  196. if (page_counter_read(counter) <= usage || nr_pages >= old)
  197. return 0;
  198. counter->max = old;
  199. cond_resched();
  200. }
  201. }
  202. /**
  203. * page_counter_set_min - set the amount of protected memory
  204. * @counter: counter
  205. * @nr_pages: value to set
  206. *
  207. * The caller must serialize invocations on the same counter.
  208. */
  209. void page_counter_set_min(struct page_counter *counter, unsigned long nr_pages)
  210. {
  211. struct page_counter *c;
  212. WRITE_ONCE(counter->min, nr_pages);
  213. for (c = counter; c; c = c->parent)
  214. propagate_protected_usage(c, atomic_long_read(&c->usage));
  215. }
  216. /**
  217. * page_counter_set_low - set the amount of protected memory
  218. * @counter: counter
  219. * @nr_pages: value to set
  220. *
  221. * The caller must serialize invocations on the same counter.
  222. */
  223. void page_counter_set_low(struct page_counter *counter, unsigned long nr_pages)
  224. {
  225. struct page_counter *c;
  226. WRITE_ONCE(counter->low, nr_pages);
  227. for (c = counter; c; c = c->parent)
  228. propagate_protected_usage(c, atomic_long_read(&c->usage));
  229. }
  230. /**
  231. * page_counter_memparse - memparse() for page counter limits
  232. * @buf: string to parse
  233. * @max: string meaning maximum possible value
  234. * @nr_pages: returns the result in number of pages
  235. *
  236. * Returns -EINVAL, or 0 and @nr_pages on success. @nr_pages will be
  237. * limited to %PAGE_COUNTER_MAX.
  238. */
  239. int page_counter_memparse(const char *buf, const char *max,
  240. unsigned long *nr_pages)
  241. {
  242. char *end;
  243. u64 bytes;
  244. if (!strcmp(buf, max)) {
  245. *nr_pages = PAGE_COUNTER_MAX;
  246. return 0;
  247. }
  248. bytes = memparse(buf, &end);
  249. if (*end != '\0')
  250. return -EINVAL;
  251. *nr_pages = min(bytes / PAGE_SIZE, (u64)PAGE_COUNTER_MAX);
  252. return 0;
  253. }
  254. #ifdef CONFIG_MEMCG
  255. /*
  256. * This function calculates an individual page counter's effective
  257. * protection which is derived from its own memory.min/low, its
  258. * parent's and siblings' settings, as well as the actual memory
  259. * distribution in the tree.
  260. *
  261. * The following rules apply to the effective protection values:
  262. *
  263. * 1. At the first level of reclaim, effective protection is equal to
  264. * the declared protection in memory.min and memory.low.
  265. *
  266. * 2. To enable safe delegation of the protection configuration, at
  267. * subsequent levels the effective protection is capped to the
  268. * parent's effective protection.
  269. *
  270. * 3. To make complex and dynamic subtrees easier to configure, the
  271. * user is allowed to overcommit the declared protection at a given
  272. * level. If that is the case, the parent's effective protection is
  273. * distributed to the children in proportion to how much protection
  274. * they have declared and how much of it they are utilizing.
  275. *
  276. * This makes distribution proportional, but also work-conserving:
  277. * if one counter claims much more protection than it uses memory,
  278. * the unused remainder is available to its siblings.
  279. *
  280. * 4. Conversely, when the declared protection is undercommitted at a
  281. * given level, the distribution of the larger parental protection
  282. * budget is NOT proportional. A counter's protection from a sibling
  283. * is capped to its own memory.min/low setting.
  284. *
  285. * 5. However, to allow protecting recursive subtrees from each other
  286. * without having to declare each individual counter's fixed share
  287. * of the ancestor's claim to protection, any unutilized -
  288. * "floating" - protection from up the tree is distributed in
  289. * proportion to each counter's *usage*. This makes the protection
  290. * neutral wrt sibling cgroups and lets them compete freely over
  291. * the shared parental protection budget, but it protects the
  292. * subtree as a whole from neighboring subtrees.
  293. *
  294. * Note that 4. and 5. are not in conflict: 4. is about protecting
  295. * against immediate siblings whereas 5. is about protecting against
  296. * neighboring subtrees.
  297. */
  298. static unsigned long effective_protection(unsigned long usage,
  299. unsigned long parent_usage,
  300. unsigned long setting,
  301. unsigned long parent_effective,
  302. unsigned long siblings_protected,
  303. bool recursive_protection)
  304. {
  305. unsigned long protected;
  306. unsigned long ep;
  307. protected = min(usage, setting);
  308. /*
  309. * If all cgroups at this level combined claim and use more
  310. * protection than what the parent affords them, distribute
  311. * shares in proportion to utilization.
  312. *
  313. * We are using actual utilization rather than the statically
  314. * claimed protection in order to be work-conserving: claimed
  315. * but unused protection is available to siblings that would
  316. * otherwise get a smaller chunk than what they claimed.
  317. */
  318. if (siblings_protected > parent_effective)
  319. return protected * parent_effective / siblings_protected;
  320. /*
  321. * Ok, utilized protection of all children is within what the
  322. * parent affords them, so we know whatever this child claims
  323. * and utilizes is effectively protected.
  324. *
  325. * If there is unprotected usage beyond this value, reclaim
  326. * will apply pressure in proportion to that amount.
  327. *
  328. * If there is unutilized protection, the cgroup will be fully
  329. * shielded from reclaim, but we do return a smaller value for
  330. * protection than what the group could enjoy in theory. This
  331. * is okay. With the overcommit distribution above, effective
  332. * protection is always dependent on how memory is actually
  333. * consumed among the siblings anyway.
  334. */
  335. ep = protected;
  336. /*
  337. * If the children aren't claiming (all of) the protection
  338. * afforded to them by the parent, distribute the remainder in
  339. * proportion to the (unprotected) memory of each cgroup. That
  340. * way, cgroups that aren't explicitly prioritized wrt each
  341. * other compete freely over the allowance, but they are
  342. * collectively protected from neighboring trees.
  343. *
  344. * We're using unprotected memory for the weight so that if
  345. * some cgroups DO claim explicit protection, we don't protect
  346. * the same bytes twice.
  347. *
  348. * Check both usage and parent_usage against the respective
  349. * protected values. One should imply the other, but they
  350. * aren't read atomically - make sure the division is sane.
  351. */
  352. if (!recursive_protection)
  353. return ep;
  354. if (parent_effective > siblings_protected &&
  355. parent_usage > siblings_protected &&
  356. usage > protected) {
  357. unsigned long unclaimed;
  358. unclaimed = parent_effective - siblings_protected;
  359. unclaimed *= usage - protected;
  360. unclaimed /= parent_usage - siblings_protected;
  361. ep += unclaimed;
  362. }
  363. return ep;
  364. }
  365. /**
  366. * page_counter_calculate_protection - check if memory consumption is in the normal range
  367. * @root: the top ancestor of the sub-tree being checked
  368. * @counter: the page_counter the counter to update
  369. * @recursive_protection: Whether to use memory_recursiveprot behavior.
  370. *
  371. * Calculates elow/emin thresholds for given page_counter.
  372. *
  373. * WARNING: This function is not stateless! It can only be used as part
  374. * of a top-down tree iteration, not for isolated queries.
  375. */
  376. void page_counter_calculate_protection(struct page_counter *root,
  377. struct page_counter *counter,
  378. bool recursive_protection)
  379. {
  380. unsigned long usage, parent_usage;
  381. struct page_counter *parent = counter->parent;
  382. /*
  383. * Effective values of the reclaim targets are ignored so they
  384. * can be stale. Have a look at mem_cgroup_protection for more
  385. * details.
  386. * TODO: calculation should be more robust so that we do not need
  387. * that special casing.
  388. */
  389. if (root == counter)
  390. return;
  391. usage = page_counter_read(counter);
  392. if (!usage)
  393. return;
  394. if (parent == root) {
  395. counter->emin = READ_ONCE(counter->min);
  396. counter->elow = READ_ONCE(counter->low);
  397. return;
  398. }
  399. parent_usage = page_counter_read(parent);
  400. WRITE_ONCE(counter->emin, effective_protection(usage, parent_usage,
  401. READ_ONCE(counter->min),
  402. READ_ONCE(parent->emin),
  403. atomic_long_read(&parent->children_min_usage),
  404. recursive_protection));
  405. WRITE_ONCE(counter->elow, effective_protection(usage, parent_usage,
  406. READ_ONCE(counter->low),
  407. READ_ONCE(parent->elow),
  408. atomic_long_read(&parent->children_low_usage),
  409. recursive_protection));
  410. }
  411. #endif /* CONFIG_MEMCG */