memcontrol-v1.c 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. #include <linux/memcontrol.h>
  3. #include <linux/swap.h>
  4. #include <linux/mm_inline.h>
  5. #include <linux/pagewalk.h>
  6. #include <linux/backing-dev.h>
  7. #include <linux/swap_cgroup.h>
  8. #include <linux/eventfd.h>
  9. #include <linux/poll.h>
  10. #include <linux/sort.h>
  11. #include <linux/file.h>
  12. #include <linux/seq_buf.h>
  13. #include "internal.h"
  14. #include "swap.h"
  15. #include "memcontrol-v1.h"
  16. /*
  17. * Cgroups above their limits are maintained in a RB-Tree, independent of
  18. * their hierarchy representation
  19. */
  20. struct mem_cgroup_tree_per_node {
  21. struct rb_root rb_root;
  22. struct rb_node *rb_rightmost;
  23. spinlock_t lock;
  24. };
  25. struct mem_cgroup_tree {
  26. struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
  27. };
  28. static struct mem_cgroup_tree soft_limit_tree __read_mostly;
  29. /*
  30. * Maximum loops in mem_cgroup_soft_reclaim(), used for soft
  31. * limit reclaim to prevent infinite loops, if they ever occur.
  32. */
  33. #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
  34. #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
  35. /* for OOM */
  36. struct mem_cgroup_eventfd_list {
  37. struct list_head list;
  38. struct eventfd_ctx *eventfd;
  39. };
  40. /*
  41. * cgroup_event represents events which userspace want to receive.
  42. */
  43. struct mem_cgroup_event {
  44. /*
  45. * memcg which the event belongs to.
  46. */
  47. struct mem_cgroup *memcg;
  48. /*
  49. * eventfd to signal userspace about the event.
  50. */
  51. struct eventfd_ctx *eventfd;
  52. /*
  53. * Each of these stored in a list by the cgroup.
  54. */
  55. struct list_head list;
  56. /*
  57. * register_event() callback will be used to add new userspace
  58. * waiter for changes related to this event. Use eventfd_signal()
  59. * on eventfd to send notification to userspace.
  60. */
  61. int (*register_event)(struct mem_cgroup *memcg,
  62. struct eventfd_ctx *eventfd, const char *args);
  63. /*
  64. * unregister_event() callback will be called when userspace closes
  65. * the eventfd or on cgroup removing. This callback must be set,
  66. * if you want provide notification functionality.
  67. */
  68. void (*unregister_event)(struct mem_cgroup *memcg,
  69. struct eventfd_ctx *eventfd);
  70. /*
  71. * All fields below needed to unregister event when
  72. * userspace closes eventfd.
  73. */
  74. poll_table pt;
  75. wait_queue_head_t *wqh;
  76. wait_queue_entry_t wait;
  77. struct work_struct remove;
  78. };
  79. #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
  80. #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
  81. #define MEMFILE_ATTR(val) ((val) & 0xffff)
  82. enum {
  83. RES_USAGE,
  84. RES_LIMIT,
  85. RES_MAX_USAGE,
  86. RES_FAILCNT,
  87. RES_SOFT_LIMIT,
  88. };
  89. #ifdef CONFIG_LOCKDEP
  90. static struct lockdep_map memcg_oom_lock_dep_map = {
  91. .name = "memcg_oom_lock",
  92. };
  93. #endif
  94. DEFINE_SPINLOCK(memcg_oom_lock);
  95. static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_node *mz,
  96. struct mem_cgroup_tree_per_node *mctz,
  97. unsigned long new_usage_in_excess)
  98. {
  99. struct rb_node **p = &mctz->rb_root.rb_node;
  100. struct rb_node *parent = NULL;
  101. struct mem_cgroup_per_node *mz_node;
  102. bool rightmost = true;
  103. if (mz->on_tree)
  104. return;
  105. mz->usage_in_excess = new_usage_in_excess;
  106. if (!mz->usage_in_excess)
  107. return;
  108. while (*p) {
  109. parent = *p;
  110. mz_node = rb_entry(parent, struct mem_cgroup_per_node,
  111. tree_node);
  112. if (mz->usage_in_excess < mz_node->usage_in_excess) {
  113. p = &(*p)->rb_left;
  114. rightmost = false;
  115. } else {
  116. p = &(*p)->rb_right;
  117. }
  118. }
  119. if (rightmost)
  120. mctz->rb_rightmost = &mz->tree_node;
  121. rb_link_node(&mz->tree_node, parent, p);
  122. rb_insert_color(&mz->tree_node, &mctz->rb_root);
  123. mz->on_tree = true;
  124. }
  125. static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
  126. struct mem_cgroup_tree_per_node *mctz)
  127. {
  128. if (!mz->on_tree)
  129. return;
  130. if (&mz->tree_node == mctz->rb_rightmost)
  131. mctz->rb_rightmost = rb_prev(&mz->tree_node);
  132. rb_erase(&mz->tree_node, &mctz->rb_root);
  133. mz->on_tree = false;
  134. }
  135. static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
  136. struct mem_cgroup_tree_per_node *mctz)
  137. {
  138. unsigned long flags;
  139. spin_lock_irqsave(&mctz->lock, flags);
  140. __mem_cgroup_remove_exceeded(mz, mctz);
  141. spin_unlock_irqrestore(&mctz->lock, flags);
  142. }
  143. static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
  144. {
  145. unsigned long nr_pages = page_counter_read(&memcg->memory);
  146. unsigned long soft_limit = READ_ONCE(memcg->soft_limit);
  147. unsigned long excess = 0;
  148. if (nr_pages > soft_limit)
  149. excess = nr_pages - soft_limit;
  150. return excess;
  151. }
  152. static void memcg1_update_tree(struct mem_cgroup *memcg, int nid)
  153. {
  154. unsigned long excess;
  155. struct mem_cgroup_per_node *mz;
  156. struct mem_cgroup_tree_per_node *mctz;
  157. if (lru_gen_enabled()) {
  158. if (soft_limit_excess(memcg))
  159. lru_gen_soft_reclaim(memcg, nid);
  160. return;
  161. }
  162. mctz = soft_limit_tree.rb_tree_per_node[nid];
  163. if (!mctz)
  164. return;
  165. /*
  166. * Necessary to update all ancestors when hierarchy is used.
  167. * because their event counter is not touched.
  168. */
  169. for (; memcg; memcg = parent_mem_cgroup(memcg)) {
  170. mz = memcg->nodeinfo[nid];
  171. excess = soft_limit_excess(memcg);
  172. /*
  173. * We have to update the tree if mz is on RB-tree or
  174. * mem is over its softlimit.
  175. */
  176. if (excess || mz->on_tree) {
  177. unsigned long flags;
  178. spin_lock_irqsave(&mctz->lock, flags);
  179. /* if on-tree, remove it */
  180. if (mz->on_tree)
  181. __mem_cgroup_remove_exceeded(mz, mctz);
  182. /*
  183. * Insert again. mz->usage_in_excess will be updated.
  184. * If excess is 0, no tree ops.
  185. */
  186. __mem_cgroup_insert_exceeded(mz, mctz, excess);
  187. spin_unlock_irqrestore(&mctz->lock, flags);
  188. }
  189. }
  190. }
  191. void memcg1_remove_from_trees(struct mem_cgroup *memcg)
  192. {
  193. struct mem_cgroup_tree_per_node *mctz;
  194. struct mem_cgroup_per_node *mz;
  195. int nid;
  196. for_each_node(nid) {
  197. mz = memcg->nodeinfo[nid];
  198. mctz = soft_limit_tree.rb_tree_per_node[nid];
  199. if (mctz)
  200. mem_cgroup_remove_exceeded(mz, mctz);
  201. }
  202. }
  203. static struct mem_cgroup_per_node *
  204. __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
  205. {
  206. struct mem_cgroup_per_node *mz;
  207. retry:
  208. mz = NULL;
  209. if (!mctz->rb_rightmost)
  210. goto done; /* Nothing to reclaim from */
  211. mz = rb_entry(mctz->rb_rightmost,
  212. struct mem_cgroup_per_node, tree_node);
  213. /*
  214. * Remove the node now but someone else can add it back,
  215. * we will to add it back at the end of reclaim to its correct
  216. * position in the tree.
  217. */
  218. __mem_cgroup_remove_exceeded(mz, mctz);
  219. if (!soft_limit_excess(mz->memcg) ||
  220. !css_tryget(&mz->memcg->css))
  221. goto retry;
  222. done:
  223. return mz;
  224. }
  225. static struct mem_cgroup_per_node *
  226. mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
  227. {
  228. struct mem_cgroup_per_node *mz;
  229. spin_lock_irq(&mctz->lock);
  230. mz = __mem_cgroup_largest_soft_limit_node(mctz);
  231. spin_unlock_irq(&mctz->lock);
  232. return mz;
  233. }
  234. static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
  235. pg_data_t *pgdat,
  236. gfp_t gfp_mask,
  237. unsigned long *total_scanned)
  238. {
  239. struct mem_cgroup *victim = NULL;
  240. int total = 0;
  241. int loop = 0;
  242. unsigned long excess;
  243. unsigned long nr_scanned;
  244. struct mem_cgroup_reclaim_cookie reclaim = {
  245. .pgdat = pgdat,
  246. };
  247. excess = soft_limit_excess(root_memcg);
  248. while (1) {
  249. victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
  250. if (!victim) {
  251. loop++;
  252. if (loop >= 2) {
  253. /*
  254. * If we have not been able to reclaim
  255. * anything, it might because there are
  256. * no reclaimable pages under this hierarchy
  257. */
  258. if (!total)
  259. break;
  260. /*
  261. * We want to do more targeted reclaim.
  262. * excess >> 2 is not to excessive so as to
  263. * reclaim too much, nor too less that we keep
  264. * coming back to reclaim from this cgroup
  265. */
  266. if (total >= (excess >> 2) ||
  267. (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
  268. break;
  269. }
  270. continue;
  271. }
  272. total += mem_cgroup_shrink_node(victim, gfp_mask, false,
  273. pgdat, &nr_scanned);
  274. *total_scanned += nr_scanned;
  275. if (!soft_limit_excess(root_memcg))
  276. break;
  277. }
  278. mem_cgroup_iter_break(root_memcg, victim);
  279. return total;
  280. }
  281. unsigned long memcg1_soft_limit_reclaim(pg_data_t *pgdat, int order,
  282. gfp_t gfp_mask,
  283. unsigned long *total_scanned)
  284. {
  285. unsigned long nr_reclaimed = 0;
  286. struct mem_cgroup_per_node *mz, *next_mz = NULL;
  287. unsigned long reclaimed;
  288. int loop = 0;
  289. struct mem_cgroup_tree_per_node *mctz;
  290. unsigned long excess;
  291. if (lru_gen_enabled())
  292. return 0;
  293. if (order > 0)
  294. return 0;
  295. mctz = soft_limit_tree.rb_tree_per_node[pgdat->node_id];
  296. /*
  297. * Do not even bother to check the largest node if the root
  298. * is empty. Do it lockless to prevent lock bouncing. Races
  299. * are acceptable as soft limit is best effort anyway.
  300. */
  301. if (!mctz || RB_EMPTY_ROOT(&mctz->rb_root))
  302. return 0;
  303. /*
  304. * This loop can run a while, specially if mem_cgroup's continuously
  305. * keep exceeding their soft limit and putting the system under
  306. * pressure
  307. */
  308. do {
  309. if (next_mz)
  310. mz = next_mz;
  311. else
  312. mz = mem_cgroup_largest_soft_limit_node(mctz);
  313. if (!mz)
  314. break;
  315. reclaimed = mem_cgroup_soft_reclaim(mz->memcg, pgdat,
  316. gfp_mask, total_scanned);
  317. nr_reclaimed += reclaimed;
  318. spin_lock_irq(&mctz->lock);
  319. /*
  320. * If we failed to reclaim anything from this memory cgroup
  321. * it is time to move on to the next cgroup
  322. */
  323. next_mz = NULL;
  324. if (!reclaimed)
  325. next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
  326. excess = soft_limit_excess(mz->memcg);
  327. /*
  328. * One school of thought says that we should not add
  329. * back the node to the tree if reclaim returns 0.
  330. * But our reclaim could return 0, simply because due
  331. * to priority we are exposing a smaller subset of
  332. * memory to reclaim from. Consider this as a longer
  333. * term TODO.
  334. */
  335. /* If excess == 0, no tree ops */
  336. __mem_cgroup_insert_exceeded(mz, mctz, excess);
  337. spin_unlock_irq(&mctz->lock);
  338. css_put(&mz->memcg->css);
  339. loop++;
  340. /*
  341. * Could not reclaim anything and there are no more
  342. * mem cgroups to try or we seem to be looping without
  343. * reclaiming anything.
  344. */
  345. if (!nr_reclaimed &&
  346. (next_mz == NULL ||
  347. loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
  348. break;
  349. } while (!nr_reclaimed);
  350. if (next_mz)
  351. css_put(&next_mz->memcg->css);
  352. return nr_reclaimed;
  353. }
  354. static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
  355. struct cftype *cft)
  356. {
  357. return 0;
  358. }
  359. #ifdef CONFIG_MMU
  360. static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
  361. struct cftype *cft, u64 val)
  362. {
  363. pr_warn_once("Cgroup memory moving (move_charge_at_immigrate) is deprecated. "
  364. "Please report your usecase to linux-mm@kvack.org if you "
  365. "depend on this functionality.\n");
  366. if (val != 0)
  367. return -EINVAL;
  368. return 0;
  369. }
  370. #else
  371. static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
  372. struct cftype *cft, u64 val)
  373. {
  374. return -ENOSYS;
  375. }
  376. #endif
  377. static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
  378. {
  379. unsigned long val;
  380. if (mem_cgroup_is_root(memcg)) {
  381. /*
  382. * Approximate root's usage from global state. This isn't
  383. * perfect, but the root usage was always an approximation.
  384. */
  385. val = global_node_page_state(NR_FILE_PAGES) +
  386. global_node_page_state(NR_ANON_MAPPED);
  387. if (swap)
  388. val += total_swap_pages - get_nr_swap_pages();
  389. } else {
  390. if (!swap)
  391. val = page_counter_read(&memcg->memory);
  392. else
  393. val = page_counter_read(&memcg->memsw);
  394. }
  395. return val;
  396. }
  397. static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
  398. {
  399. struct mem_cgroup_threshold_ary *t;
  400. unsigned long usage;
  401. int i;
  402. rcu_read_lock();
  403. if (!swap)
  404. t = rcu_dereference(memcg->thresholds.primary);
  405. else
  406. t = rcu_dereference(memcg->memsw_thresholds.primary);
  407. if (!t)
  408. goto unlock;
  409. usage = mem_cgroup_usage(memcg, swap);
  410. /*
  411. * current_threshold points to threshold just below or equal to usage.
  412. * If it's not true, a threshold was crossed after last
  413. * call of __mem_cgroup_threshold().
  414. */
  415. i = t->current_threshold;
  416. /*
  417. * Iterate backward over array of thresholds starting from
  418. * current_threshold and check if a threshold is crossed.
  419. * If none of thresholds below usage is crossed, we read
  420. * only one element of the array here.
  421. */
  422. for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
  423. eventfd_signal(t->entries[i].eventfd);
  424. /* i = current_threshold + 1 */
  425. i++;
  426. /*
  427. * Iterate forward over array of thresholds starting from
  428. * current_threshold+1 and check if a threshold is crossed.
  429. * If none of thresholds above usage is crossed, we read
  430. * only one element of the array here.
  431. */
  432. for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
  433. eventfd_signal(t->entries[i].eventfd);
  434. /* Update current_threshold */
  435. t->current_threshold = i - 1;
  436. unlock:
  437. rcu_read_unlock();
  438. }
  439. static void mem_cgroup_threshold(struct mem_cgroup *memcg)
  440. {
  441. while (memcg) {
  442. __mem_cgroup_threshold(memcg, false);
  443. if (do_memsw_account())
  444. __mem_cgroup_threshold(memcg, true);
  445. memcg = parent_mem_cgroup(memcg);
  446. }
  447. }
  448. /* Cgroup1: threshold notifications & softlimit tree updates */
  449. /*
  450. * Per memcg event counter is incremented at every pagein/pageout. With THP,
  451. * it will be incremented by the number of pages. This counter is used
  452. * to trigger some periodic events. This is straightforward and better
  453. * than using jiffies etc. to handle periodic memcg event.
  454. */
  455. enum mem_cgroup_events_target {
  456. MEM_CGROUP_TARGET_THRESH,
  457. MEM_CGROUP_TARGET_SOFTLIMIT,
  458. MEM_CGROUP_NTARGETS,
  459. };
  460. struct memcg1_events_percpu {
  461. unsigned long nr_page_events;
  462. unsigned long targets[MEM_CGROUP_NTARGETS];
  463. };
  464. static void memcg1_charge_statistics(struct mem_cgroup *memcg, int nr_pages)
  465. {
  466. /* pagein of a big page is an event. So, ignore page size */
  467. if (nr_pages > 0)
  468. count_memcg_events(memcg, PGPGIN, 1);
  469. else {
  470. count_memcg_events(memcg, PGPGOUT, 1);
  471. nr_pages = -nr_pages; /* for event */
  472. }
  473. __this_cpu_add(memcg->events_percpu->nr_page_events, nr_pages);
  474. }
  475. #define THRESHOLDS_EVENTS_TARGET 128
  476. #define SOFTLIMIT_EVENTS_TARGET 1024
  477. static bool memcg1_event_ratelimit(struct mem_cgroup *memcg,
  478. enum mem_cgroup_events_target target)
  479. {
  480. unsigned long val, next;
  481. val = __this_cpu_read(memcg->events_percpu->nr_page_events);
  482. next = __this_cpu_read(memcg->events_percpu->targets[target]);
  483. /* from time_after() in jiffies.h */
  484. if ((long)(next - val) < 0) {
  485. switch (target) {
  486. case MEM_CGROUP_TARGET_THRESH:
  487. next = val + THRESHOLDS_EVENTS_TARGET;
  488. break;
  489. case MEM_CGROUP_TARGET_SOFTLIMIT:
  490. next = val + SOFTLIMIT_EVENTS_TARGET;
  491. break;
  492. default:
  493. break;
  494. }
  495. __this_cpu_write(memcg->events_percpu->targets[target], next);
  496. return true;
  497. }
  498. return false;
  499. }
  500. /*
  501. * Check events in order.
  502. *
  503. */
  504. static void memcg1_check_events(struct mem_cgroup *memcg, int nid)
  505. {
  506. if (IS_ENABLED(CONFIG_PREEMPT_RT))
  507. return;
  508. /* threshold event is triggered in finer grain than soft limit */
  509. if (unlikely(memcg1_event_ratelimit(memcg,
  510. MEM_CGROUP_TARGET_THRESH))) {
  511. bool do_softlimit;
  512. do_softlimit = memcg1_event_ratelimit(memcg,
  513. MEM_CGROUP_TARGET_SOFTLIMIT);
  514. mem_cgroup_threshold(memcg);
  515. if (unlikely(do_softlimit))
  516. memcg1_update_tree(memcg, nid);
  517. }
  518. }
  519. void memcg1_commit_charge(struct folio *folio, struct mem_cgroup *memcg)
  520. {
  521. unsigned long flags;
  522. local_irq_save(flags);
  523. memcg1_charge_statistics(memcg, folio_nr_pages(folio));
  524. memcg1_check_events(memcg, folio_nid(folio));
  525. local_irq_restore(flags);
  526. }
  527. /**
  528. * memcg1_swapout - transfer a memsw charge to swap
  529. * @folio: folio whose memsw charge to transfer
  530. * @entry: swap entry to move the charge to
  531. *
  532. * Transfer the memsw charge of @folio to @entry.
  533. */
  534. void memcg1_swapout(struct folio *folio, swp_entry_t entry)
  535. {
  536. struct mem_cgroup *memcg, *swap_memcg;
  537. unsigned int nr_entries;
  538. VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
  539. VM_BUG_ON_FOLIO(folio_ref_count(folio), folio);
  540. if (mem_cgroup_disabled())
  541. return;
  542. if (!do_memsw_account())
  543. return;
  544. memcg = folio_memcg(folio);
  545. VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
  546. if (!memcg)
  547. return;
  548. /*
  549. * In case the memcg owning these pages has been offlined and doesn't
  550. * have an ID allocated to it anymore, charge the closest online
  551. * ancestor for the swap instead and transfer the memory+swap charge.
  552. */
  553. swap_memcg = mem_cgroup_private_id_get_online(memcg);
  554. nr_entries = folio_nr_pages(folio);
  555. /* Get references for the tail pages, too */
  556. if (nr_entries > 1)
  557. mem_cgroup_private_id_get_many(swap_memcg, nr_entries - 1);
  558. mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries);
  559. swap_cgroup_record(folio, mem_cgroup_private_id(swap_memcg), entry);
  560. folio_unqueue_deferred_split(folio);
  561. folio->memcg_data = 0;
  562. if (!mem_cgroup_is_root(memcg))
  563. page_counter_uncharge(&memcg->memory, nr_entries);
  564. if (memcg != swap_memcg) {
  565. if (!mem_cgroup_is_root(swap_memcg))
  566. page_counter_charge(&swap_memcg->memsw, nr_entries);
  567. page_counter_uncharge(&memcg->memsw, nr_entries);
  568. }
  569. /*
  570. * Interrupts should be disabled here because the caller holds the
  571. * i_pages lock which is taken with interrupts-off. It is
  572. * important here to have the interrupts disabled because it is the
  573. * only synchronisation we have for updating the per-CPU variables.
  574. */
  575. preempt_disable_nested();
  576. VM_WARN_ON_IRQS_ENABLED();
  577. memcg1_charge_statistics(memcg, -folio_nr_pages(folio));
  578. preempt_enable_nested();
  579. memcg1_check_events(memcg, folio_nid(folio));
  580. css_put(&memcg->css);
  581. }
  582. /*
  583. * memcg1_swapin - uncharge swap slot
  584. * @entry: the first swap entry for which the pages are charged
  585. * @nr_pages: number of pages which will be uncharged
  586. *
  587. * Call this function after successfully adding the charged page to swapcache.
  588. *
  589. * Note: This function assumes the page for which swap slot is being uncharged
  590. * is order 0 page.
  591. */
  592. void memcg1_swapin(swp_entry_t entry, unsigned int nr_pages)
  593. {
  594. /*
  595. * Cgroup1's unified memory+swap counter has been charged with the
  596. * new swapcache page, finish the transfer by uncharging the swap
  597. * slot. The swap slot would also get uncharged when it dies, but
  598. * it can stick around indefinitely and we'd count the page twice
  599. * the entire time.
  600. *
  601. * Cgroup2 has separate resource counters for memory and swap,
  602. * so this is a non-issue here. Memory and swap charge lifetimes
  603. * correspond 1:1 to page and swap slot lifetimes: we charge the
  604. * page to memory here, and uncharge swap when the slot is freed.
  605. */
  606. if (do_memsw_account()) {
  607. /*
  608. * The swap entry might not get freed for a long time,
  609. * let's not wait for it. The page already received a
  610. * memory+swap charge, drop the swap entry duplicate.
  611. */
  612. mem_cgroup_uncharge_swap(entry, nr_pages);
  613. }
  614. }
  615. void memcg1_uncharge_batch(struct mem_cgroup *memcg, unsigned long pgpgout,
  616. unsigned long nr_memory, int nid)
  617. {
  618. unsigned long flags;
  619. local_irq_save(flags);
  620. count_memcg_events(memcg, PGPGOUT, pgpgout);
  621. __this_cpu_add(memcg->events_percpu->nr_page_events, nr_memory);
  622. memcg1_check_events(memcg, nid);
  623. local_irq_restore(flags);
  624. }
  625. static int compare_thresholds(const void *a, const void *b)
  626. {
  627. const struct mem_cgroup_threshold *_a = a;
  628. const struct mem_cgroup_threshold *_b = b;
  629. if (_a->threshold > _b->threshold)
  630. return 1;
  631. if (_a->threshold < _b->threshold)
  632. return -1;
  633. return 0;
  634. }
  635. static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
  636. {
  637. struct mem_cgroup_eventfd_list *ev;
  638. spin_lock(&memcg_oom_lock);
  639. list_for_each_entry(ev, &memcg->oom_notify, list)
  640. eventfd_signal(ev->eventfd);
  641. spin_unlock(&memcg_oom_lock);
  642. return 0;
  643. }
  644. static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
  645. {
  646. struct mem_cgroup *iter;
  647. for_each_mem_cgroup_tree(iter, memcg)
  648. mem_cgroup_oom_notify_cb(iter);
  649. }
  650. static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
  651. struct eventfd_ctx *eventfd, const char *args, enum res_type type)
  652. {
  653. struct mem_cgroup_thresholds *thresholds;
  654. struct mem_cgroup_threshold_ary *new;
  655. unsigned long threshold;
  656. unsigned long usage;
  657. int i, size, ret;
  658. ret = page_counter_memparse(args, "-1", &threshold);
  659. if (ret)
  660. return ret;
  661. mutex_lock(&memcg->thresholds_lock);
  662. if (type == _MEM) {
  663. thresholds = &memcg->thresholds;
  664. usage = mem_cgroup_usage(memcg, false);
  665. } else if (type == _MEMSWAP) {
  666. thresholds = &memcg->memsw_thresholds;
  667. usage = mem_cgroup_usage(memcg, true);
  668. } else
  669. BUG();
  670. /* Check if a threshold crossed before adding a new one */
  671. if (thresholds->primary)
  672. __mem_cgroup_threshold(memcg, type == _MEMSWAP);
  673. size = thresholds->primary ? thresholds->primary->size + 1 : 1;
  674. /* Allocate memory for new array of thresholds */
  675. new = kmalloc_flex(*new, entries, size, GFP_KERNEL_ACCOUNT);
  676. if (!new) {
  677. ret = -ENOMEM;
  678. goto unlock;
  679. }
  680. new->size = size;
  681. /* Copy thresholds (if any) to new array */
  682. if (thresholds->primary)
  683. memcpy(new->entries, thresholds->primary->entries,
  684. flex_array_size(new, entries, size - 1));
  685. /* Add new threshold */
  686. new->entries[size - 1].eventfd = eventfd;
  687. new->entries[size - 1].threshold = threshold;
  688. /* Sort thresholds. Registering of new threshold isn't time-critical */
  689. sort(new->entries, size, sizeof(*new->entries),
  690. compare_thresholds, NULL);
  691. /* Find current threshold */
  692. new->current_threshold = -1;
  693. for (i = 0; i < size; i++) {
  694. if (new->entries[i].threshold <= usage) {
  695. /*
  696. * new->current_threshold will not be used until
  697. * rcu_assign_pointer(), so it's safe to increment
  698. * it here.
  699. */
  700. ++new->current_threshold;
  701. } else
  702. break;
  703. }
  704. /* Free old spare buffer and save old primary buffer as spare */
  705. kfree(thresholds->spare);
  706. thresholds->spare = thresholds->primary;
  707. rcu_assign_pointer(thresholds->primary, new);
  708. /* To be sure that nobody uses thresholds */
  709. synchronize_rcu();
  710. unlock:
  711. mutex_unlock(&memcg->thresholds_lock);
  712. return ret;
  713. }
  714. static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
  715. struct eventfd_ctx *eventfd, const char *args)
  716. {
  717. return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
  718. }
  719. static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
  720. struct eventfd_ctx *eventfd, const char *args)
  721. {
  722. return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
  723. }
  724. static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
  725. struct eventfd_ctx *eventfd, enum res_type type)
  726. {
  727. struct mem_cgroup_thresholds *thresholds;
  728. struct mem_cgroup_threshold_ary *new;
  729. unsigned long usage;
  730. int i, j, size, entries;
  731. mutex_lock(&memcg->thresholds_lock);
  732. if (type == _MEM) {
  733. thresholds = &memcg->thresholds;
  734. usage = mem_cgroup_usage(memcg, false);
  735. } else if (type == _MEMSWAP) {
  736. thresholds = &memcg->memsw_thresholds;
  737. usage = mem_cgroup_usage(memcg, true);
  738. } else
  739. BUG();
  740. if (!thresholds->primary)
  741. goto unlock;
  742. /* Check if a threshold crossed before removing */
  743. __mem_cgroup_threshold(memcg, type == _MEMSWAP);
  744. /* Calculate new number of threshold */
  745. size = entries = 0;
  746. for (i = 0; i < thresholds->primary->size; i++) {
  747. if (thresholds->primary->entries[i].eventfd != eventfd)
  748. size++;
  749. else
  750. entries++;
  751. }
  752. new = thresholds->spare;
  753. /* If no items related to eventfd have been cleared, nothing to do */
  754. if (!entries)
  755. goto unlock;
  756. /* Set thresholds array to NULL if we don't have thresholds */
  757. if (!size) {
  758. kfree(new);
  759. new = NULL;
  760. goto swap_buffers;
  761. }
  762. new->size = size;
  763. /* Copy thresholds and find current threshold */
  764. new->current_threshold = -1;
  765. for (i = 0, j = 0; i < thresholds->primary->size; i++) {
  766. if (thresholds->primary->entries[i].eventfd == eventfd)
  767. continue;
  768. new->entries[j] = thresholds->primary->entries[i];
  769. if (new->entries[j].threshold <= usage) {
  770. /*
  771. * new->current_threshold will not be used
  772. * until rcu_assign_pointer(), so it's safe to increment
  773. * it here.
  774. */
  775. ++new->current_threshold;
  776. }
  777. j++;
  778. }
  779. swap_buffers:
  780. /* Swap primary and spare array */
  781. thresholds->spare = thresholds->primary;
  782. rcu_assign_pointer(thresholds->primary, new);
  783. /* To be sure that nobody uses thresholds */
  784. synchronize_rcu();
  785. /* If all events are unregistered, free the spare array */
  786. if (!new) {
  787. kfree(thresholds->spare);
  788. thresholds->spare = NULL;
  789. }
  790. unlock:
  791. mutex_unlock(&memcg->thresholds_lock);
  792. }
  793. static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
  794. struct eventfd_ctx *eventfd)
  795. {
  796. return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
  797. }
  798. static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
  799. struct eventfd_ctx *eventfd)
  800. {
  801. return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
  802. }
  803. static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
  804. struct eventfd_ctx *eventfd, const char *args)
  805. {
  806. struct mem_cgroup_eventfd_list *event;
  807. event = kmalloc_obj(*event, GFP_KERNEL_ACCOUNT);
  808. if (!event)
  809. return -ENOMEM;
  810. spin_lock(&memcg_oom_lock);
  811. event->eventfd = eventfd;
  812. list_add(&event->list, &memcg->oom_notify);
  813. /* already in OOM ? */
  814. if (memcg->under_oom)
  815. eventfd_signal(eventfd);
  816. spin_unlock(&memcg_oom_lock);
  817. return 0;
  818. }
  819. static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
  820. struct eventfd_ctx *eventfd)
  821. {
  822. struct mem_cgroup_eventfd_list *ev, *tmp;
  823. spin_lock(&memcg_oom_lock);
  824. list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
  825. if (ev->eventfd == eventfd) {
  826. list_del(&ev->list);
  827. kfree(ev);
  828. }
  829. }
  830. spin_unlock(&memcg_oom_lock);
  831. }
  832. /*
  833. * DO NOT USE IN NEW FILES.
  834. *
  835. * "cgroup.event_control" implementation.
  836. *
  837. * This is way over-engineered. It tries to support fully configurable
  838. * events for each user. Such level of flexibility is completely
  839. * unnecessary especially in the light of the planned unified hierarchy.
  840. *
  841. * Please deprecate this and replace with something simpler if at all
  842. * possible.
  843. */
  844. /*
  845. * Unregister event and free resources.
  846. *
  847. * Gets called from workqueue.
  848. */
  849. static void memcg_event_remove(struct work_struct *work)
  850. {
  851. struct mem_cgroup_event *event =
  852. container_of(work, struct mem_cgroup_event, remove);
  853. struct mem_cgroup *memcg = event->memcg;
  854. remove_wait_queue(event->wqh, &event->wait);
  855. event->unregister_event(memcg, event->eventfd);
  856. /* Notify userspace the event is going away. */
  857. eventfd_signal(event->eventfd);
  858. eventfd_ctx_put(event->eventfd);
  859. kfree(event);
  860. css_put(&memcg->css);
  861. }
  862. /*
  863. * Gets called on EPOLLHUP on eventfd when user closes it.
  864. *
  865. * Called with wqh->lock held and interrupts disabled.
  866. */
  867. static int memcg_event_wake(wait_queue_entry_t *wait, unsigned int mode,
  868. int sync, void *key)
  869. {
  870. struct mem_cgroup_event *event =
  871. container_of(wait, struct mem_cgroup_event, wait);
  872. struct mem_cgroup *memcg = event->memcg;
  873. __poll_t flags = key_to_poll(key);
  874. if (flags & EPOLLHUP) {
  875. /*
  876. * If the event has been detached at cgroup removal, we
  877. * can simply return knowing the other side will cleanup
  878. * for us.
  879. *
  880. * We can't race against event freeing since the other
  881. * side will require wqh->lock via remove_wait_queue(),
  882. * which we hold.
  883. */
  884. spin_lock(&memcg->event_list_lock);
  885. if (!list_empty(&event->list)) {
  886. list_del_init(&event->list);
  887. /*
  888. * We are in atomic context, but cgroup_event_remove()
  889. * may sleep, so we have to call it in workqueue.
  890. */
  891. schedule_work(&event->remove);
  892. }
  893. spin_unlock(&memcg->event_list_lock);
  894. }
  895. return 0;
  896. }
  897. static void memcg_event_ptable_queue_proc(struct file *file,
  898. wait_queue_head_t *wqh, poll_table *pt)
  899. {
  900. struct mem_cgroup_event *event =
  901. container_of(pt, struct mem_cgroup_event, pt);
  902. event->wqh = wqh;
  903. add_wait_queue(wqh, &event->wait);
  904. }
  905. /*
  906. * DO NOT USE IN NEW FILES.
  907. *
  908. * Parse input and register new cgroup event handler.
  909. *
  910. * Input must be in format '<event_fd> <control_fd> <args>'.
  911. * Interpretation of args is defined by control file implementation.
  912. */
  913. static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
  914. char *buf, size_t nbytes, loff_t off)
  915. {
  916. struct cgroup_subsys_state *css = of_css(of);
  917. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  918. struct mem_cgroup_event *event;
  919. struct cgroup_subsys_state *cfile_css;
  920. unsigned int efd, cfd;
  921. struct dentry *cdentry;
  922. const char *name;
  923. char *endp;
  924. int ret;
  925. if (IS_ENABLED(CONFIG_PREEMPT_RT))
  926. return -EOPNOTSUPP;
  927. buf = strstrip(buf);
  928. efd = simple_strtoul(buf, &endp, 10);
  929. if (*endp != ' ')
  930. return -EINVAL;
  931. buf = endp + 1;
  932. cfd = simple_strtoul(buf, &endp, 10);
  933. if (*endp == '\0')
  934. buf = endp;
  935. else if (*endp == ' ')
  936. buf = endp + 1;
  937. else
  938. return -EINVAL;
  939. CLASS(fd, efile)(efd);
  940. if (fd_empty(efile))
  941. return -EBADF;
  942. CLASS(fd, cfile)(cfd);
  943. event = kzalloc_obj(*event, GFP_KERNEL_ACCOUNT);
  944. if (!event)
  945. return -ENOMEM;
  946. event->memcg = memcg;
  947. INIT_LIST_HEAD(&event->list);
  948. init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
  949. init_waitqueue_func_entry(&event->wait, memcg_event_wake);
  950. INIT_WORK(&event->remove, memcg_event_remove);
  951. event->eventfd = eventfd_ctx_fileget(fd_file(efile));
  952. if (IS_ERR(event->eventfd)) {
  953. ret = PTR_ERR(event->eventfd);
  954. goto out_kfree;
  955. }
  956. if (fd_empty(cfile)) {
  957. ret = -EBADF;
  958. goto out_put_eventfd;
  959. }
  960. /* the process need read permission on control file */
  961. /* AV: shouldn't we check that it's been opened for read instead? */
  962. ret = file_permission(fd_file(cfile), MAY_READ);
  963. if (ret < 0)
  964. goto out_put_eventfd;
  965. /*
  966. * The control file must be a regular cgroup1 file. As a regular cgroup
  967. * file can't be renamed, it's safe to access its name afterwards.
  968. */
  969. cdentry = fd_file(cfile)->f_path.dentry;
  970. if (cdentry->d_sb->s_type != &cgroup_fs_type || !d_is_reg(cdentry)) {
  971. ret = -EINVAL;
  972. goto out_put_eventfd;
  973. }
  974. /*
  975. * Determine the event callbacks and set them in @event. This used
  976. * to be done via struct cftype but cgroup core no longer knows
  977. * about these events. The following is crude but the whole thing
  978. * is for compatibility anyway.
  979. *
  980. * DO NOT ADD NEW FILES.
  981. */
  982. name = cdentry->d_name.name;
  983. if (!strcmp(name, "memory.usage_in_bytes")) {
  984. event->register_event = mem_cgroup_usage_register_event;
  985. event->unregister_event = mem_cgroup_usage_unregister_event;
  986. } else if (!strcmp(name, "memory.oom_control")) {
  987. pr_warn_once("oom_control is deprecated and will be removed. "
  988. "Please report your usecase to linux-mm-@kvack.org"
  989. " if you depend on this functionality.\n");
  990. event->register_event = mem_cgroup_oom_register_event;
  991. event->unregister_event = mem_cgroup_oom_unregister_event;
  992. } else if (!strcmp(name, "memory.pressure_level")) {
  993. pr_warn_once("pressure_level is deprecated and will be removed. "
  994. "Please report your usecase to linux-mm-@kvack.org "
  995. "if you depend on this functionality.\n");
  996. event->register_event = vmpressure_register_event;
  997. event->unregister_event = vmpressure_unregister_event;
  998. } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
  999. event->register_event = memsw_cgroup_usage_register_event;
  1000. event->unregister_event = memsw_cgroup_usage_unregister_event;
  1001. } else {
  1002. ret = -EINVAL;
  1003. goto out_put_eventfd;
  1004. }
  1005. /*
  1006. * Verify @cfile should belong to @css. Also, remaining events are
  1007. * automatically removed on cgroup destruction but the removal is
  1008. * asynchronous, so take an extra ref on @css.
  1009. */
  1010. cfile_css = css_tryget_online_from_dir(cdentry->d_parent,
  1011. &memory_cgrp_subsys);
  1012. ret = -EINVAL;
  1013. if (IS_ERR(cfile_css))
  1014. goto out_put_eventfd;
  1015. if (cfile_css != css)
  1016. goto out_put_css;
  1017. ret = event->register_event(memcg, event->eventfd, buf);
  1018. if (ret)
  1019. goto out_put_css;
  1020. vfs_poll(fd_file(efile), &event->pt);
  1021. spin_lock_irq(&memcg->event_list_lock);
  1022. list_add(&event->list, &memcg->event_list);
  1023. spin_unlock_irq(&memcg->event_list_lock);
  1024. return nbytes;
  1025. out_put_css:
  1026. css_put(cfile_css);
  1027. out_put_eventfd:
  1028. eventfd_ctx_put(event->eventfd);
  1029. out_kfree:
  1030. kfree(event);
  1031. return ret;
  1032. }
  1033. void memcg1_memcg_init(struct mem_cgroup *memcg)
  1034. {
  1035. INIT_LIST_HEAD(&memcg->oom_notify);
  1036. mutex_init(&memcg->thresholds_lock);
  1037. INIT_LIST_HEAD(&memcg->event_list);
  1038. spin_lock_init(&memcg->event_list_lock);
  1039. }
  1040. void memcg1_css_offline(struct mem_cgroup *memcg)
  1041. {
  1042. struct mem_cgroup_event *event, *tmp;
  1043. /*
  1044. * Unregister events and notify userspace.
  1045. * Notify userspace about cgroup removing only after rmdir of cgroup
  1046. * directory to avoid race between userspace and kernelspace.
  1047. */
  1048. spin_lock_irq(&memcg->event_list_lock);
  1049. list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
  1050. list_del_init(&event->list);
  1051. schedule_work(&event->remove);
  1052. }
  1053. spin_unlock_irq(&memcg->event_list_lock);
  1054. }
  1055. /*
  1056. * Check OOM-Killer is already running under our hierarchy.
  1057. * If someone is running, return false.
  1058. */
  1059. static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
  1060. {
  1061. struct mem_cgroup *iter, *failed = NULL;
  1062. spin_lock(&memcg_oom_lock);
  1063. for_each_mem_cgroup_tree(iter, memcg) {
  1064. if (iter->oom_lock) {
  1065. /*
  1066. * this subtree of our hierarchy is already locked
  1067. * so we cannot give a lock.
  1068. */
  1069. failed = iter;
  1070. mem_cgroup_iter_break(memcg, iter);
  1071. break;
  1072. }
  1073. iter->oom_lock = true;
  1074. }
  1075. if (failed) {
  1076. /*
  1077. * OK, we failed to lock the whole subtree so we have
  1078. * to clean up what we set up to the failing subtree
  1079. */
  1080. for_each_mem_cgroup_tree(iter, memcg) {
  1081. if (iter == failed) {
  1082. mem_cgroup_iter_break(memcg, iter);
  1083. break;
  1084. }
  1085. iter->oom_lock = false;
  1086. }
  1087. } else
  1088. mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
  1089. spin_unlock(&memcg_oom_lock);
  1090. return !failed;
  1091. }
  1092. static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
  1093. {
  1094. struct mem_cgroup *iter;
  1095. spin_lock(&memcg_oom_lock);
  1096. mutex_release(&memcg_oom_lock_dep_map, _RET_IP_);
  1097. for_each_mem_cgroup_tree(iter, memcg)
  1098. iter->oom_lock = false;
  1099. spin_unlock(&memcg_oom_lock);
  1100. }
  1101. static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
  1102. {
  1103. struct mem_cgroup *iter;
  1104. spin_lock(&memcg_oom_lock);
  1105. for_each_mem_cgroup_tree(iter, memcg)
  1106. iter->under_oom++;
  1107. spin_unlock(&memcg_oom_lock);
  1108. }
  1109. static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
  1110. {
  1111. struct mem_cgroup *iter;
  1112. /*
  1113. * Be careful about under_oom underflows because a child memcg
  1114. * could have been added after mem_cgroup_mark_under_oom.
  1115. */
  1116. spin_lock(&memcg_oom_lock);
  1117. for_each_mem_cgroup_tree(iter, memcg)
  1118. if (iter->under_oom > 0)
  1119. iter->under_oom--;
  1120. spin_unlock(&memcg_oom_lock);
  1121. }
  1122. static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
  1123. struct oom_wait_info {
  1124. struct mem_cgroup *memcg;
  1125. wait_queue_entry_t wait;
  1126. };
  1127. static int memcg_oom_wake_function(wait_queue_entry_t *wait,
  1128. unsigned int mode, int sync, void *arg)
  1129. {
  1130. struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
  1131. struct mem_cgroup *oom_wait_memcg;
  1132. struct oom_wait_info *oom_wait_info;
  1133. oom_wait_info = container_of(wait, struct oom_wait_info, wait);
  1134. oom_wait_memcg = oom_wait_info->memcg;
  1135. if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
  1136. !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
  1137. return 0;
  1138. return autoremove_wake_function(wait, mode, sync, arg);
  1139. }
  1140. void memcg1_oom_recover(struct mem_cgroup *memcg)
  1141. {
  1142. /*
  1143. * For the following lockless ->under_oom test, the only required
  1144. * guarantee is that it must see the state asserted by an OOM when
  1145. * this function is called as a result of userland actions
  1146. * triggered by the notification of the OOM. This is trivially
  1147. * achieved by invoking mem_cgroup_mark_under_oom() before
  1148. * triggering notification.
  1149. */
  1150. if (memcg && memcg->under_oom)
  1151. __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
  1152. }
  1153. /**
  1154. * mem_cgroup_oom_synchronize - complete memcg OOM handling
  1155. * @handle: actually kill/wait or just clean up the OOM state
  1156. *
  1157. * This has to be called at the end of a page fault if the memcg OOM
  1158. * handler was enabled.
  1159. *
  1160. * Memcg supports userspace OOM handling where failed allocations must
  1161. * sleep on a waitqueue until the userspace task resolves the
  1162. * situation. Sleeping directly in the charge context with all kinds
  1163. * of locks held is not a good idea, instead we remember an OOM state
  1164. * in the task and mem_cgroup_oom_synchronize() has to be called at
  1165. * the end of the page fault to complete the OOM handling.
  1166. *
  1167. * Returns %true if an ongoing memcg OOM situation was detected and
  1168. * completed, %false otherwise.
  1169. */
  1170. bool mem_cgroup_oom_synchronize(bool handle)
  1171. {
  1172. struct mem_cgroup *memcg = current->memcg_in_oom;
  1173. struct oom_wait_info owait;
  1174. bool locked;
  1175. /* OOM is global, do not handle */
  1176. if (!memcg)
  1177. return false;
  1178. if (!handle)
  1179. goto cleanup;
  1180. owait.memcg = memcg;
  1181. owait.wait.flags = 0;
  1182. owait.wait.func = memcg_oom_wake_function;
  1183. owait.wait.private = current;
  1184. INIT_LIST_HEAD(&owait.wait.entry);
  1185. prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
  1186. mem_cgroup_mark_under_oom(memcg);
  1187. locked = mem_cgroup_oom_trylock(memcg);
  1188. if (locked)
  1189. mem_cgroup_oom_notify(memcg);
  1190. schedule();
  1191. mem_cgroup_unmark_under_oom(memcg);
  1192. finish_wait(&memcg_oom_waitq, &owait.wait);
  1193. if (locked)
  1194. mem_cgroup_oom_unlock(memcg);
  1195. cleanup:
  1196. current->memcg_in_oom = NULL;
  1197. css_put(&memcg->css);
  1198. return true;
  1199. }
  1200. bool memcg1_oom_prepare(struct mem_cgroup *memcg, bool *locked)
  1201. {
  1202. /*
  1203. * We are in the middle of the charge context here, so we
  1204. * don't want to block when potentially sitting on a callstack
  1205. * that holds all kinds of filesystem and mm locks.
  1206. *
  1207. * cgroup1 allows disabling the OOM killer and waiting for outside
  1208. * handling until the charge can succeed; remember the context and put
  1209. * the task to sleep at the end of the page fault when all locks are
  1210. * released.
  1211. *
  1212. * On the other hand, in-kernel OOM killer allows for an async victim
  1213. * memory reclaim (oom_reaper) and that means that we are not solely
  1214. * relying on the oom victim to make a forward progress and we can
  1215. * invoke the oom killer here.
  1216. *
  1217. * Please note that mem_cgroup_out_of_memory might fail to find a
  1218. * victim and then we have to bail out from the charge path.
  1219. */
  1220. if (READ_ONCE(memcg->oom_kill_disable)) {
  1221. if (current->in_user_fault) {
  1222. css_get(&memcg->css);
  1223. current->memcg_in_oom = memcg;
  1224. }
  1225. return false;
  1226. }
  1227. mem_cgroup_mark_under_oom(memcg);
  1228. *locked = mem_cgroup_oom_trylock(memcg);
  1229. if (*locked)
  1230. mem_cgroup_oom_notify(memcg);
  1231. mem_cgroup_unmark_under_oom(memcg);
  1232. return true;
  1233. }
  1234. void memcg1_oom_finish(struct mem_cgroup *memcg, bool locked)
  1235. {
  1236. if (locked)
  1237. mem_cgroup_oom_unlock(memcg);
  1238. }
  1239. static DEFINE_MUTEX(memcg_max_mutex);
  1240. static int mem_cgroup_resize_max(struct mem_cgroup *memcg,
  1241. unsigned long max, bool memsw)
  1242. {
  1243. bool enlarge = false;
  1244. bool drained = false;
  1245. int ret;
  1246. bool limits_invariant;
  1247. struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory;
  1248. do {
  1249. if (signal_pending(current)) {
  1250. ret = -EINTR;
  1251. break;
  1252. }
  1253. mutex_lock(&memcg_max_mutex);
  1254. /*
  1255. * Make sure that the new limit (memsw or memory limit) doesn't
  1256. * break our basic invariant rule memory.max <= memsw.max.
  1257. */
  1258. limits_invariant = memsw ? max >= READ_ONCE(memcg->memory.max) :
  1259. max <= memcg->memsw.max;
  1260. if (!limits_invariant) {
  1261. mutex_unlock(&memcg_max_mutex);
  1262. ret = -EINVAL;
  1263. break;
  1264. }
  1265. if (max > counter->max)
  1266. enlarge = true;
  1267. ret = page_counter_set_max(counter, max);
  1268. mutex_unlock(&memcg_max_mutex);
  1269. if (!ret)
  1270. break;
  1271. if (!drained) {
  1272. drain_all_stock(memcg);
  1273. drained = true;
  1274. continue;
  1275. }
  1276. if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,
  1277. memsw ? 0 : MEMCG_RECLAIM_MAY_SWAP, NULL)) {
  1278. ret = -EBUSY;
  1279. break;
  1280. }
  1281. } while (true);
  1282. if (!ret && enlarge)
  1283. memcg1_oom_recover(memcg);
  1284. return ret;
  1285. }
  1286. /*
  1287. * Reclaims as many pages from the given memcg as possible.
  1288. *
  1289. * Caller is responsible for holding css reference for memcg.
  1290. */
  1291. static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
  1292. {
  1293. int nr_retries = MAX_RECLAIM_RETRIES;
  1294. /* we call try-to-free pages for make this cgroup empty */
  1295. lru_add_drain_all();
  1296. drain_all_stock(memcg);
  1297. /* try to free all pages in this cgroup */
  1298. while (nr_retries && page_counter_read(&memcg->memory)) {
  1299. if (signal_pending(current))
  1300. return -EINTR;
  1301. if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,
  1302. MEMCG_RECLAIM_MAY_SWAP, NULL))
  1303. nr_retries--;
  1304. }
  1305. return 0;
  1306. }
  1307. static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
  1308. char *buf, size_t nbytes,
  1309. loff_t off)
  1310. {
  1311. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  1312. if (mem_cgroup_is_root(memcg))
  1313. return -EINVAL;
  1314. return mem_cgroup_force_empty(memcg) ?: nbytes;
  1315. }
  1316. static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
  1317. struct cftype *cft)
  1318. {
  1319. return 1;
  1320. }
  1321. static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
  1322. struct cftype *cft, u64 val)
  1323. {
  1324. if (val == 1)
  1325. return 0;
  1326. pr_warn_once("Non-hierarchical mode is deprecated. "
  1327. "Please report your usecase to linux-mm@kvack.org if you "
  1328. "depend on this functionality.\n");
  1329. return -EINVAL;
  1330. }
  1331. static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
  1332. struct cftype *cft)
  1333. {
  1334. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  1335. struct page_counter *counter;
  1336. switch (MEMFILE_TYPE(cft->private)) {
  1337. case _MEM:
  1338. counter = &memcg->memory;
  1339. break;
  1340. case _MEMSWAP:
  1341. counter = &memcg->memsw;
  1342. break;
  1343. case _KMEM:
  1344. counter = &memcg->kmem;
  1345. break;
  1346. case _TCP:
  1347. counter = &memcg->tcpmem;
  1348. break;
  1349. default:
  1350. BUG();
  1351. }
  1352. switch (MEMFILE_ATTR(cft->private)) {
  1353. case RES_USAGE:
  1354. if (counter == &memcg->memory)
  1355. return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
  1356. if (counter == &memcg->memsw)
  1357. return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
  1358. return (u64)page_counter_read(counter) * PAGE_SIZE;
  1359. case RES_LIMIT:
  1360. return (u64)counter->max * PAGE_SIZE;
  1361. case RES_MAX_USAGE:
  1362. return (u64)counter->watermark * PAGE_SIZE;
  1363. case RES_FAILCNT:
  1364. return counter->failcnt;
  1365. case RES_SOFT_LIMIT:
  1366. return (u64)READ_ONCE(memcg->soft_limit) * PAGE_SIZE;
  1367. default:
  1368. BUG();
  1369. }
  1370. }
  1371. /*
  1372. * This function doesn't do anything useful. Its only job is to provide a read
  1373. * handler for a file so that cgroup_file_mode() will add read permissions.
  1374. */
  1375. static int mem_cgroup_dummy_seq_show(__always_unused struct seq_file *m,
  1376. __always_unused void *v)
  1377. {
  1378. return -EINVAL;
  1379. }
  1380. static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max)
  1381. {
  1382. int ret;
  1383. mutex_lock(&memcg_max_mutex);
  1384. ret = page_counter_set_max(&memcg->tcpmem, max);
  1385. if (ret)
  1386. goto out;
  1387. if (!memcg->tcpmem_active) {
  1388. /*
  1389. * The active flag needs to be written after the static_key
  1390. * update. This is what guarantees that the socket activation
  1391. * function is the last one to run. See mem_cgroup_sk_alloc()
  1392. * for details, and note that we don't mark any socket as
  1393. * belonging to this memcg until that flag is up.
  1394. *
  1395. * We need to do this, because static_keys will span multiple
  1396. * sites, but we can't control their order. If we mark a socket
  1397. * as accounted, but the accounting functions are not patched in
  1398. * yet, we'll lose accounting.
  1399. *
  1400. * We never race with the readers in mem_cgroup_sk_alloc(),
  1401. * because when this value change, the code to process it is not
  1402. * patched in yet.
  1403. */
  1404. static_branch_inc(&memcg_sockets_enabled_key);
  1405. memcg->tcpmem_active = true;
  1406. }
  1407. out:
  1408. mutex_unlock(&memcg_max_mutex);
  1409. return ret;
  1410. }
  1411. /*
  1412. * The user of this function is...
  1413. * RES_LIMIT.
  1414. */
  1415. static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
  1416. char *buf, size_t nbytes, loff_t off)
  1417. {
  1418. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  1419. unsigned long nr_pages;
  1420. int ret;
  1421. buf = strstrip(buf);
  1422. ret = page_counter_memparse(buf, "-1", &nr_pages);
  1423. if (ret)
  1424. return ret;
  1425. switch (MEMFILE_ATTR(of_cft(of)->private)) {
  1426. case RES_LIMIT:
  1427. if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
  1428. ret = -EINVAL;
  1429. break;
  1430. }
  1431. switch (MEMFILE_TYPE(of_cft(of)->private)) {
  1432. case _MEM:
  1433. ret = mem_cgroup_resize_max(memcg, nr_pages, false);
  1434. break;
  1435. case _MEMSWAP:
  1436. ret = mem_cgroup_resize_max(memcg, nr_pages, true);
  1437. break;
  1438. case _KMEM:
  1439. pr_warn_once("kmem.limit_in_bytes is deprecated and will be removed. "
  1440. "Writing any value to this file has no effect. "
  1441. "Please report your usecase to linux-mm@kvack.org if you "
  1442. "depend on this functionality.\n");
  1443. ret = 0;
  1444. break;
  1445. case _TCP:
  1446. pr_warn_once("kmem.tcp.limit_in_bytes is deprecated and will be removed. "
  1447. "Please report your usecase to linux-mm@kvack.org if you "
  1448. "depend on this functionality.\n");
  1449. ret = memcg_update_tcp_max(memcg, nr_pages);
  1450. break;
  1451. }
  1452. break;
  1453. case RES_SOFT_LIMIT:
  1454. if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
  1455. ret = -EOPNOTSUPP;
  1456. } else {
  1457. pr_warn_once("soft_limit_in_bytes is deprecated and will be removed. "
  1458. "Please report your usecase to linux-mm@kvack.org if you "
  1459. "depend on this functionality.\n");
  1460. WRITE_ONCE(memcg->soft_limit, nr_pages);
  1461. ret = 0;
  1462. }
  1463. break;
  1464. }
  1465. return ret ?: nbytes;
  1466. }
  1467. static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
  1468. size_t nbytes, loff_t off)
  1469. {
  1470. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  1471. struct page_counter *counter;
  1472. switch (MEMFILE_TYPE(of_cft(of)->private)) {
  1473. case _MEM:
  1474. counter = &memcg->memory;
  1475. break;
  1476. case _MEMSWAP:
  1477. counter = &memcg->memsw;
  1478. break;
  1479. case _KMEM:
  1480. counter = &memcg->kmem;
  1481. break;
  1482. case _TCP:
  1483. counter = &memcg->tcpmem;
  1484. break;
  1485. default:
  1486. BUG();
  1487. }
  1488. switch (MEMFILE_ATTR(of_cft(of)->private)) {
  1489. case RES_MAX_USAGE:
  1490. page_counter_reset_watermark(counter);
  1491. break;
  1492. case RES_FAILCNT:
  1493. counter->failcnt = 0;
  1494. break;
  1495. default:
  1496. BUG();
  1497. }
  1498. return nbytes;
  1499. }
  1500. #ifdef CONFIG_NUMA
  1501. #define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE))
  1502. #define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON))
  1503. #define LRU_ALL ((1 << NR_LRU_LISTS) - 1)
  1504. static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
  1505. int nid, unsigned int lru_mask, bool tree)
  1506. {
  1507. struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
  1508. unsigned long nr = 0;
  1509. enum lru_list lru;
  1510. VM_BUG_ON((unsigned int)nid >= nr_node_ids);
  1511. for_each_lru(lru) {
  1512. if (!(BIT(lru) & lru_mask))
  1513. continue;
  1514. if (tree)
  1515. nr += lruvec_page_state(lruvec, NR_LRU_BASE + lru);
  1516. else
  1517. nr += lruvec_page_state_local(lruvec, NR_LRU_BASE + lru);
  1518. }
  1519. return nr;
  1520. }
  1521. static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
  1522. unsigned int lru_mask,
  1523. bool tree)
  1524. {
  1525. unsigned long nr = 0;
  1526. enum lru_list lru;
  1527. for_each_lru(lru) {
  1528. if (!(BIT(lru) & lru_mask))
  1529. continue;
  1530. if (tree)
  1531. nr += memcg_page_state(memcg, NR_LRU_BASE + lru);
  1532. else
  1533. nr += memcg_page_state_local(memcg, NR_LRU_BASE + lru);
  1534. }
  1535. return nr;
  1536. }
  1537. static int memcg_numa_stat_show(struct seq_file *m, void *v)
  1538. {
  1539. struct numa_stat {
  1540. const char *name;
  1541. unsigned int lru_mask;
  1542. };
  1543. static const struct numa_stat stats[] = {
  1544. { "total", LRU_ALL },
  1545. { "file", LRU_ALL_FILE },
  1546. { "anon", LRU_ALL_ANON },
  1547. { "unevictable", BIT(LRU_UNEVICTABLE) },
  1548. };
  1549. const struct numa_stat *stat;
  1550. int nid;
  1551. struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
  1552. mem_cgroup_flush_stats(memcg);
  1553. for (stat = stats; stat < ARRAY_END(stats); stat++) {
  1554. seq_printf(m, "%s=%lu", stat->name,
  1555. mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
  1556. false));
  1557. for_each_node_state(nid, N_MEMORY)
  1558. seq_printf(m, " N%d=%lu", nid,
  1559. mem_cgroup_node_nr_lru_pages(memcg, nid,
  1560. stat->lru_mask, false));
  1561. seq_putc(m, '\n');
  1562. }
  1563. for (stat = stats; stat < ARRAY_END(stats); stat++) {
  1564. seq_printf(m, "hierarchical_%s=%lu", stat->name,
  1565. mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
  1566. true));
  1567. for_each_node_state(nid, N_MEMORY)
  1568. seq_printf(m, " N%d=%lu", nid,
  1569. mem_cgroup_node_nr_lru_pages(memcg, nid,
  1570. stat->lru_mask, true));
  1571. seq_putc(m, '\n');
  1572. }
  1573. return 0;
  1574. }
  1575. #endif /* CONFIG_NUMA */
  1576. static const unsigned int memcg1_stats[] = {
  1577. NR_FILE_PAGES,
  1578. NR_ANON_MAPPED,
  1579. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  1580. NR_ANON_THPS,
  1581. #endif
  1582. NR_SHMEM,
  1583. NR_FILE_MAPPED,
  1584. NR_FILE_DIRTY,
  1585. NR_WRITEBACK,
  1586. WORKINGSET_REFAULT_ANON,
  1587. WORKINGSET_REFAULT_FILE,
  1588. #ifdef CONFIG_SWAP
  1589. MEMCG_SWAP,
  1590. NR_SWAPCACHE,
  1591. #endif
  1592. };
  1593. static const char *const memcg1_stat_names[] = {
  1594. "cache",
  1595. "rss",
  1596. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  1597. "rss_huge",
  1598. #endif
  1599. "shmem",
  1600. "mapped_file",
  1601. "dirty",
  1602. "writeback",
  1603. "workingset_refault_anon",
  1604. "workingset_refault_file",
  1605. #ifdef CONFIG_SWAP
  1606. "swap",
  1607. "swapcached",
  1608. #endif
  1609. };
  1610. /* Universal VM events cgroup1 shows, original sort order */
  1611. static const unsigned int memcg1_events[] = {
  1612. PGPGIN,
  1613. PGPGOUT,
  1614. PGFAULT,
  1615. PGMAJFAULT,
  1616. };
  1617. void memcg1_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
  1618. {
  1619. unsigned long memory, memsw;
  1620. struct mem_cgroup *mi;
  1621. unsigned int i;
  1622. BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats));
  1623. mem_cgroup_flush_stats(memcg);
  1624. for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
  1625. unsigned long nr;
  1626. nr = memcg_page_state_local_output(memcg, memcg1_stats[i]);
  1627. seq_buf_printf(s, "%s %lu\n", memcg1_stat_names[i], nr);
  1628. }
  1629. for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
  1630. seq_buf_printf(s, "%s %lu\n", vm_event_name(memcg1_events[i]),
  1631. memcg_events_local(memcg, memcg1_events[i]));
  1632. for (i = 0; i < NR_LRU_LISTS; i++)
  1633. seq_buf_printf(s, "%s %lu\n", lru_list_name(i),
  1634. memcg_page_state_local(memcg, NR_LRU_BASE + i) *
  1635. PAGE_SIZE);
  1636. /* Hierarchical information */
  1637. memory = memsw = PAGE_COUNTER_MAX;
  1638. for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
  1639. memory = min(memory, READ_ONCE(mi->memory.max));
  1640. memsw = min(memsw, READ_ONCE(mi->memsw.max));
  1641. }
  1642. seq_buf_printf(s, "hierarchical_memory_limit %llu\n",
  1643. (u64)memory * PAGE_SIZE);
  1644. seq_buf_printf(s, "hierarchical_memsw_limit %llu\n",
  1645. (u64)memsw * PAGE_SIZE);
  1646. for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
  1647. unsigned long nr;
  1648. nr = memcg_page_state_output(memcg, memcg1_stats[i]);
  1649. seq_buf_printf(s, "total_%s %llu\n", memcg1_stat_names[i],
  1650. (u64)nr);
  1651. }
  1652. for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
  1653. seq_buf_printf(s, "total_%s %llu\n",
  1654. vm_event_name(memcg1_events[i]),
  1655. (u64)memcg_events(memcg, memcg1_events[i]));
  1656. for (i = 0; i < NR_LRU_LISTS; i++)
  1657. seq_buf_printf(s, "total_%s %llu\n", lru_list_name(i),
  1658. (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
  1659. PAGE_SIZE);
  1660. #ifdef CONFIG_DEBUG_VM
  1661. {
  1662. pg_data_t *pgdat;
  1663. struct mem_cgroup_per_node *mz;
  1664. unsigned long anon_cost = 0;
  1665. unsigned long file_cost = 0;
  1666. for_each_online_pgdat(pgdat) {
  1667. mz = memcg->nodeinfo[pgdat->node_id];
  1668. anon_cost += mz->lruvec.anon_cost;
  1669. file_cost += mz->lruvec.file_cost;
  1670. }
  1671. seq_buf_printf(s, "anon_cost %lu\n", anon_cost);
  1672. seq_buf_printf(s, "file_cost %lu\n", file_cost);
  1673. }
  1674. #endif
  1675. }
  1676. static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
  1677. struct cftype *cft)
  1678. {
  1679. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  1680. return mem_cgroup_swappiness(memcg);
  1681. }
  1682. static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
  1683. struct cftype *cft, u64 val)
  1684. {
  1685. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  1686. if (val > MAX_SWAPPINESS)
  1687. return -EINVAL;
  1688. if (!mem_cgroup_is_root(memcg)) {
  1689. pr_info_once("Per memcg swappiness does not exist in cgroup v2. "
  1690. "See memory.reclaim or memory.swap.max there\n ");
  1691. WRITE_ONCE(memcg->swappiness, val);
  1692. } else
  1693. WRITE_ONCE(vm_swappiness, val);
  1694. return 0;
  1695. }
  1696. static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
  1697. {
  1698. struct mem_cgroup *memcg = mem_cgroup_from_seq(sf);
  1699. seq_printf(sf, "oom_kill_disable %d\n", READ_ONCE(memcg->oom_kill_disable));
  1700. seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
  1701. seq_printf(sf, "oom_kill %lu\n",
  1702. atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
  1703. return 0;
  1704. }
  1705. static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
  1706. struct cftype *cft, u64 val)
  1707. {
  1708. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  1709. pr_warn_once("oom_control is deprecated and will be removed. "
  1710. "Please report your usecase to linux-mm-@kvack.org if you "
  1711. "depend on this functionality.\n");
  1712. /* cannot set to root cgroup and only 0 and 1 are allowed */
  1713. if (mem_cgroup_is_root(memcg) || !((val == 0) || (val == 1)))
  1714. return -EINVAL;
  1715. WRITE_ONCE(memcg->oom_kill_disable, val);
  1716. if (!val)
  1717. memcg1_oom_recover(memcg);
  1718. return 0;
  1719. }
  1720. #ifdef CONFIG_SLUB_DEBUG
  1721. static int mem_cgroup_slab_show(struct seq_file *m, void *p)
  1722. {
  1723. /*
  1724. * Deprecated.
  1725. * Please, take a look at tools/cgroup/memcg_slabinfo.py .
  1726. */
  1727. return 0;
  1728. }
  1729. #endif
  1730. struct cftype mem_cgroup_legacy_files[] = {
  1731. {
  1732. .name = "usage_in_bytes",
  1733. .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
  1734. .read_u64 = mem_cgroup_read_u64,
  1735. },
  1736. {
  1737. .name = "max_usage_in_bytes",
  1738. .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
  1739. .write = mem_cgroup_reset,
  1740. .read_u64 = mem_cgroup_read_u64,
  1741. },
  1742. {
  1743. .name = "limit_in_bytes",
  1744. .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
  1745. .write = mem_cgroup_write,
  1746. .read_u64 = mem_cgroup_read_u64,
  1747. },
  1748. {
  1749. .name = "soft_limit_in_bytes",
  1750. .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
  1751. .write = mem_cgroup_write,
  1752. .read_u64 = mem_cgroup_read_u64,
  1753. },
  1754. {
  1755. .name = "failcnt",
  1756. .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
  1757. .write = mem_cgroup_reset,
  1758. .read_u64 = mem_cgroup_read_u64,
  1759. },
  1760. {
  1761. .name = "stat",
  1762. .seq_show = memory_stat_show,
  1763. },
  1764. {
  1765. .name = "force_empty",
  1766. .write = mem_cgroup_force_empty_write,
  1767. },
  1768. {
  1769. .name = "use_hierarchy",
  1770. .write_u64 = mem_cgroup_hierarchy_write,
  1771. .read_u64 = mem_cgroup_hierarchy_read,
  1772. },
  1773. {
  1774. .name = "cgroup.event_control", /* XXX: for compat */
  1775. .write = memcg_write_event_control,
  1776. .flags = CFTYPE_NO_PREFIX,
  1777. },
  1778. {
  1779. .name = "swappiness",
  1780. .read_u64 = mem_cgroup_swappiness_read,
  1781. .write_u64 = mem_cgroup_swappiness_write,
  1782. },
  1783. {
  1784. .name = "move_charge_at_immigrate",
  1785. .read_u64 = mem_cgroup_move_charge_read,
  1786. .write_u64 = mem_cgroup_move_charge_write,
  1787. },
  1788. {
  1789. .name = "oom_control",
  1790. .seq_show = mem_cgroup_oom_control_read,
  1791. .write_u64 = mem_cgroup_oom_control_write,
  1792. },
  1793. {
  1794. .name = "pressure_level",
  1795. .seq_show = mem_cgroup_dummy_seq_show,
  1796. },
  1797. #ifdef CONFIG_NUMA
  1798. {
  1799. .name = "numa_stat",
  1800. .seq_show = memcg_numa_stat_show,
  1801. },
  1802. #endif
  1803. {
  1804. .name = "kmem.limit_in_bytes",
  1805. .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
  1806. .write = mem_cgroup_write,
  1807. .read_u64 = mem_cgroup_read_u64,
  1808. },
  1809. {
  1810. .name = "kmem.usage_in_bytes",
  1811. .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
  1812. .read_u64 = mem_cgroup_read_u64,
  1813. },
  1814. {
  1815. .name = "kmem.failcnt",
  1816. .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
  1817. .write = mem_cgroup_reset,
  1818. .read_u64 = mem_cgroup_read_u64,
  1819. },
  1820. {
  1821. .name = "kmem.max_usage_in_bytes",
  1822. .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
  1823. .write = mem_cgroup_reset,
  1824. .read_u64 = mem_cgroup_read_u64,
  1825. },
  1826. #ifdef CONFIG_SLUB_DEBUG
  1827. {
  1828. .name = "kmem.slabinfo",
  1829. .seq_show = mem_cgroup_slab_show,
  1830. },
  1831. #endif
  1832. {
  1833. .name = "kmem.tcp.limit_in_bytes",
  1834. .private = MEMFILE_PRIVATE(_TCP, RES_LIMIT),
  1835. .write = mem_cgroup_write,
  1836. .read_u64 = mem_cgroup_read_u64,
  1837. },
  1838. {
  1839. .name = "kmem.tcp.usage_in_bytes",
  1840. .private = MEMFILE_PRIVATE(_TCP, RES_USAGE),
  1841. .read_u64 = mem_cgroup_read_u64,
  1842. },
  1843. {
  1844. .name = "kmem.tcp.failcnt",
  1845. .private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT),
  1846. .write = mem_cgroup_reset,
  1847. .read_u64 = mem_cgroup_read_u64,
  1848. },
  1849. {
  1850. .name = "kmem.tcp.max_usage_in_bytes",
  1851. .private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE),
  1852. .write = mem_cgroup_reset,
  1853. .read_u64 = mem_cgroup_read_u64,
  1854. },
  1855. { }, /* terminate */
  1856. };
  1857. struct cftype memsw_files[] = {
  1858. {
  1859. .name = "memsw.usage_in_bytes",
  1860. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
  1861. .read_u64 = mem_cgroup_read_u64,
  1862. },
  1863. {
  1864. .name = "memsw.max_usage_in_bytes",
  1865. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
  1866. .write = mem_cgroup_reset,
  1867. .read_u64 = mem_cgroup_read_u64,
  1868. },
  1869. {
  1870. .name = "memsw.limit_in_bytes",
  1871. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
  1872. .write = mem_cgroup_write,
  1873. .read_u64 = mem_cgroup_read_u64,
  1874. },
  1875. {
  1876. .name = "memsw.failcnt",
  1877. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
  1878. .write = mem_cgroup_reset,
  1879. .read_u64 = mem_cgroup_read_u64,
  1880. },
  1881. { }, /* terminate */
  1882. };
  1883. void memcg1_account_kmem(struct mem_cgroup *memcg, int nr_pages)
  1884. {
  1885. if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
  1886. if (nr_pages > 0)
  1887. page_counter_charge(&memcg->kmem, nr_pages);
  1888. else
  1889. page_counter_uncharge(&memcg->kmem, -nr_pages);
  1890. }
  1891. }
  1892. bool memcg1_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages,
  1893. gfp_t gfp_mask)
  1894. {
  1895. struct page_counter *fail;
  1896. if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) {
  1897. memcg->tcpmem_pressure = 0;
  1898. return true;
  1899. }
  1900. memcg->tcpmem_pressure = 1;
  1901. if (gfp_mask & __GFP_NOFAIL) {
  1902. page_counter_charge(&memcg->tcpmem, nr_pages);
  1903. return true;
  1904. }
  1905. return false;
  1906. }
  1907. bool memcg1_alloc_events(struct mem_cgroup *memcg)
  1908. {
  1909. memcg->events_percpu = alloc_percpu_gfp(struct memcg1_events_percpu,
  1910. GFP_KERNEL_ACCOUNT);
  1911. return !!memcg->events_percpu;
  1912. }
  1913. void memcg1_free_events(struct mem_cgroup *memcg)
  1914. {
  1915. free_percpu(memcg->events_percpu);
  1916. }
  1917. static int __init memcg1_init(void)
  1918. {
  1919. int node;
  1920. for_each_node(node) {
  1921. struct mem_cgroup_tree_per_node *rtpn;
  1922. rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, node);
  1923. rtpn->rb_root = RB_ROOT;
  1924. rtpn->rb_rightmost = NULL;
  1925. spin_lock_init(&rtpn->lock);
  1926. soft_limit_tree.rb_tree_per_node[node] = rtpn;
  1927. }
  1928. return 0;
  1929. }
  1930. subsys_initcall(memcg1_init);