1 // SPDX-License-Identifier: GPL-2.0-or-later 2 /* memcontrol.c - Memory Controller 3 * 4 * Copyright IBM Corporation, 2007 5 * Author Balbir Singh <balbir@linux.vnet.ibm.com> 6 * 7 * Copyright 2007 OpenVZ SWsoft Inc 8 * Author: Pavel Emelianov <xemul@openvz.org> 9 * 10 * Memory thresholds 11 * Copyright (C) 2009 Nokia Corporation 12 * Author: Kirill A. Shutemov 13 * 14 * Kernel Memory Controller 15 * Copyright (C) 2012 Parallels Inc. and Google Inc. 16 * Authors: Glauber Costa and Suleiman Souhlal 17 * 18 * Native page reclaim 19 * Charge lifetime sanitation 20 * Lockless page tracking & accounting 21 * Unified hierarchy configuration model 22 * Copyright (C) 2015 Red Hat, Inc., Johannes Weiner 23 * 24 * Per memcg lru locking 25 * Copyright (C) 2020 Alibaba, Inc, Alex Shi 26 */ 27 28 #include <linux/cgroup-defs.h> 29 #include <linux/page_counter.h> 30 #include <linux/memcontrol.h> 31 #include <linux/cgroup.h> 32 #include <linux/cpuset.h> 33 #include <linux/sched/mm.h> 34 #include <linux/shmem_fs.h> 35 #include <linux/hugetlb.h> 36 #include <linux/pagemap.h> 37 #include <linux/folio_batch.h> 38 #include <linux/vm_event_item.h> 39 #include <linux/smp.h> 40 #include <linux/page-flags.h> 41 #include <linux/backing-dev.h> 42 #include <linux/bit_spinlock.h> 43 #include <linux/rcupdate.h> 44 #include <linux/limits.h> 45 #include <linux/export.h> 46 #include <linux/list.h> 47 #include <linux/mutex.h> 48 #include <linux/rbtree.h> 49 #include <linux/slab.h> 50 #include <linux/swapops.h> 51 #include <linux/spinlock.h> 52 #include <linux/fs.h> 53 #include <linux/seq_file.h> 54 #include <linux/vmpressure.h> 55 #include <linux/memremap.h> 56 #include <linux/mm_inline.h> 57 #include <linux/cpu.h> 58 #include <linux/oom.h> 59 #include <linux/lockdep.h> 60 #include <linux/resume_user_mode.h> 61 #include <linux/psi.h> 62 #include <linux/seq_buf.h> 63 #include <linux/sched/isolation.h> 64 #include <linux/kmemleak.h> 65 #include <linux/irq_work.h> 66 #include "internal.h" 67 #include "swap.h" 68 #include "swap_table.h" 69 #include <net/sock.h> 70 #include <net/ip.h> 71 #include "slab.h" 72 #include "memcontrol-v1.h" 73 74 #include <linux/uaccess.h> 75 76 #define CREATE_TRACE_POINTS 77 #include <trace/events/memcg.h> 78 #undef CREATE_TRACE_POINTS 79 80 #include <trace/events/vmscan.h> 81 82 struct cgroup_subsys memory_cgrp_subsys __read_mostly; 83 EXPORT_SYMBOL(memory_cgrp_subsys); 84 85 struct mem_cgroup *root_mem_cgroup __read_mostly; 86 EXPORT_SYMBOL(root_mem_cgroup); 87 88 /* Active memory cgroup to use from an interrupt context */ 89 DEFINE_PER_CPU(struct mem_cgroup *, int_active_memcg); 90 EXPORT_PER_CPU_SYMBOL_GPL(int_active_memcg); 91 92 /* Socket memory accounting disabled? */ 93 static bool cgroup_memory_nosocket __ro_after_init; 94 95 /* Kernel memory accounting disabled? */ 96 static bool cgroup_memory_nokmem __ro_after_init; 97 98 /* BPF memory accounting disabled? */ 99 static bool cgroup_memory_nobpf __ro_after_init; 100 101 static struct workqueue_struct *memcg_wq __ro_after_init; 102 103 static struct kmem_cache *memcg_cachep; 104 static struct kmem_cache *memcg_pn_cachep; 105 106 #ifdef CONFIG_CGROUP_WRITEBACK 107 static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq); 108 #endif 109 110 static inline bool task_is_dying(void) 111 { 112 return tsk_is_oom_victim(current) || fatal_signal_pending(current) || 113 (current->flags & PF_EXITING); 114 } 115 116 /* Some nice accessors for the vmpressure. */ 117 struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg) 118 { 119 if (!memcg) 120 memcg = root_mem_cgroup; 121 return &memcg->vmpressure; 122 } 123 124 struct mem_cgroup *vmpressure_to_memcg(struct vmpressure *vmpr) 125 { 126 return container_of(vmpr, struct mem_cgroup, vmpressure); 127 } 128 129 #define SEQ_BUF_SIZE SZ_4K 130 #define CURRENT_OBJCG_UPDATE_BIT 0 131 #define CURRENT_OBJCG_UPDATE_FLAG (1UL << CURRENT_OBJCG_UPDATE_BIT) 132 133 static DEFINE_SPINLOCK(objcg_lock); 134 135 bool mem_cgroup_kmem_disabled(void) 136 { 137 return cgroup_memory_nokmem; 138 } 139 140 static void memcg_uncharge(struct mem_cgroup *memcg, unsigned int nr_pages); 141 142 static void memcg_uncharge_kmem(struct mem_cgroup *memcg, unsigned int nr_pages) 143 { 144 mod_memcg_state(memcg, MEMCG_KMEM, -nr_pages); 145 memcg1_account_kmem(memcg, -nr_pages); 146 if (!mem_cgroup_is_root(memcg)) 147 memcg_uncharge(memcg, nr_pages); 148 } 149 150 static void obj_cgroup_release(struct percpu_ref *ref) 151 { 152 struct obj_cgroup *objcg = container_of(ref, struct obj_cgroup, refcnt); 153 unsigned int nr_bytes; 154 unsigned int nr_pages; 155 unsigned long flags; 156 157 /* 158 * At this point all allocated objects are freed, and 159 * objcg->nr_charged_bytes can't have an arbitrary byte value. 160 * However, it can be PAGE_SIZE or (x * PAGE_SIZE). 161 * 162 * The following sequence can lead to it: 163 * 1) CPU0: objcg cached in one of stock->cached[i] 164 * 2) CPU1: we do a small allocation (e.g. 92 bytes), 165 * PAGE_SIZE bytes are charged 166 * 3) CPU1: a process from another memcg is allocating something, 167 * the stock if flushed, 168 * objcg->nr_charged_bytes = PAGE_SIZE - 92 169 * 4) CPU0: we do release this object, 170 * 92 bytes are added to stock->nr_bytes[i] 171 * 5) CPU0: stock is flushed, 172 * 92 bytes are added to objcg->nr_charged_bytes 173 * 174 * In the result, nr_charged_bytes == PAGE_SIZE. 175 * This page will be uncharged in obj_cgroup_release(). 176 */ 177 nr_bytes = atomic_read(&objcg->nr_charged_bytes); 178 WARN_ON_ONCE(nr_bytes & (PAGE_SIZE - 1)); 179 nr_pages = nr_bytes >> PAGE_SHIFT; 180 181 if (nr_pages) { 182 struct mem_cgroup *memcg; 183 184 memcg = get_mem_cgroup_from_objcg(objcg); 185 memcg_uncharge_kmem(memcg, nr_pages); 186 mem_cgroup_put(memcg); 187 } 188 189 spin_lock_irqsave(&objcg_lock, flags); 190 list_del(&objcg->list); 191 spin_unlock_irqrestore(&objcg_lock, flags); 192 193 percpu_ref_exit(ref); 194 kfree_rcu(objcg, rcu); 195 } 196 197 static struct obj_cgroup *obj_cgroup_alloc(void) 198 { 199 struct obj_cgroup *objcg; 200 int ret; 201 202 objcg = kzalloc_obj(struct obj_cgroup); 203 if (!objcg) 204 return NULL; 205 206 ret = percpu_ref_init(&objcg->refcnt, obj_cgroup_release, 0, 207 GFP_KERNEL); 208 if (ret) { 209 kfree(objcg); 210 return NULL; 211 } 212 INIT_LIST_HEAD(&objcg->list); 213 return objcg; 214 } 215 216 static inline struct obj_cgroup *__memcg_reparent_objcgs(struct mem_cgroup *memcg, 217 struct mem_cgroup *parent, 218 int nid) 219 { 220 struct obj_cgroup *objcg, *iter; 221 struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid]; 222 struct mem_cgroup_per_node *parent_pn = parent->nodeinfo[nid]; 223 224 objcg = rcu_replace_pointer(pn->objcg, NULL, true); 225 /* 1) Ready to reparent active objcg. */ 226 list_add(&objcg->list, &pn->objcg_list); 227 /* 2) Reparent active objcg and already reparented objcgs to parent. */ 228 list_for_each_entry(iter, &pn->objcg_list, list) 229 WRITE_ONCE(iter->memcg, parent); 230 /* 3) Move already reparented objcgs to the parent's list */ 231 list_splice(&pn->objcg_list, &parent_pn->objcg_list); 232 233 return objcg; 234 } 235 236 static void __mem_cgroup_flush_stats(struct mem_cgroup *memcg, bool force); 237 238 /* 239 * Reparent the non-hierarchical lruvec stats that count_shadow_nodes() reads 240 * to approximate the shadow node budget. They are not exposed to userspace 241 * on cgroup v2, but they must follow the reparented folios; otherwise the 242 * ancestor would only receive the negative deltas when the folios are freed 243 * without ever having received the positive base, and its local stats would 244 * permanently underflow. 245 */ 246 static void reparent_v2_lruvec_state_local(struct mem_cgroup *memcg, struct mem_cgroup *parent) 247 { 248 int i; 249 250 for (i = 0; i < NR_LRU_LISTS; i++) 251 reparent_memcg_lruvec_state_local(memcg, parent, NR_LRU_BASE + i); 252 253 reparent_memcg_lruvec_state_local(memcg, parent, NR_SLAB_RECLAIMABLE_B); 254 reparent_memcg_lruvec_state_local(memcg, parent, NR_SLAB_UNRECLAIMABLE_B); 255 } 256 257 static inline void reparent_state_local(struct mem_cgroup *memcg, struct mem_cgroup *parent) 258 { 259 /* 260 * Reparent stats exposed non-hierarchically. Flush @memcg's stats first 261 * to read its stats accurately , and conservatively flush @parent's 262 * stats after reparenting to avoid hiding a potentially large stat 263 * update (e.g. from callers of mem_cgroup_flush_stats_ratelimited()). 264 */ 265 __mem_cgroup_flush_stats(memcg, true); 266 267 if (cgroup_subsys_on_dfl(memory_cgrp_subsys)) { 268 reparent_v2_lruvec_state_local(memcg, parent); 269 } else { 270 #ifdef CONFIG_MEMCG_V1 271 /* The following counts are all non-hierarchical and need to be reparented. */ 272 reparent_memcg1_state_local(memcg, parent); 273 reparent_memcg1_lruvec_state_local(memcg, parent); 274 #endif 275 } 276 277 __mem_cgroup_flush_stats(parent, true); 278 } 279 280 static inline void reparent_locks(struct mem_cgroup *memcg, struct mem_cgroup *parent, int nid) 281 { 282 spin_lock_irq(&objcg_lock); 283 spin_lock_nested(&mem_cgroup_lruvec(memcg, NODE_DATA(nid))->lru_lock, 1); 284 spin_lock_nested(&mem_cgroup_lruvec(parent, NODE_DATA(nid))->lru_lock, 2); 285 } 286 287 static inline void reparent_unlocks(struct mem_cgroup *memcg, struct mem_cgroup *parent, int nid) 288 { 289 spin_unlock(&mem_cgroup_lruvec(parent, NODE_DATA(nid))->lru_lock); 290 spin_unlock(&mem_cgroup_lruvec(memcg, NODE_DATA(nid))->lru_lock); 291 spin_unlock_irq(&objcg_lock); 292 } 293 294 static void memcg_reparent_objcgs(struct mem_cgroup *memcg) 295 { 296 struct obj_cgroup *objcg; 297 struct mem_cgroup *parent = parent_mem_cgroup(memcg); 298 int nid; 299 300 for_each_node(nid) { 301 retry: 302 if (lru_gen_enabled()) 303 max_lru_gen_memcg(parent, nid); 304 305 reparent_locks(memcg, parent, nid); 306 307 if (lru_gen_enabled()) { 308 if (!recheck_lru_gen_max_memcg(parent, nid)) { 309 reparent_unlocks(memcg, parent, nid); 310 cond_resched(); 311 goto retry; 312 } 313 lru_gen_reparent_memcg(memcg, parent, nid); 314 } else { 315 lru_reparent_memcg(memcg, parent, nid); 316 } 317 318 objcg = __memcg_reparent_objcgs(memcg, parent, nid); 319 320 reparent_unlocks(memcg, parent, nid); 321 322 percpu_ref_kill(&objcg->refcnt); 323 } 324 325 reparent_state_local(memcg, parent); 326 } 327 328 /* 329 * A lot of the calls to the cache allocation functions are expected to be 330 * inlined by the compiler. Since the calls to memcg_slab_post_alloc_hook() are 331 * conditional to this static branch, we'll have to allow modules that does 332 * kmem_cache_alloc and the such to see this symbol as well 333 */ 334 DEFINE_STATIC_KEY_FALSE(memcg_kmem_online_key); 335 EXPORT_SYMBOL(memcg_kmem_online_key); 336 337 DEFINE_STATIC_KEY_FALSE(memcg_bpf_enabled_key); 338 EXPORT_SYMBOL(memcg_bpf_enabled_key); 339 340 /** 341 * get_mem_cgroup_css_from_folio - acquire a css of the memcg associated with a folio 342 * @folio: folio of interest 343 * 344 * If memcg is bound to the default hierarchy, css of the memcg associated 345 * with @folio is returned. The returned css remains associated with @folio 346 * until it is released. 347 * 348 * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup 349 * is returned. 350 */ 351 struct cgroup_subsys_state *get_mem_cgroup_css_from_folio(const struct folio *folio) 352 { 353 struct mem_cgroup *memcg; 354 355 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) 356 return &root_mem_cgroup->css; 357 358 memcg = get_mem_cgroup_from_folio(folio); 359 360 return memcg ? &memcg->css : &root_mem_cgroup->css; 361 } 362 363 /** 364 * page_cgroup_ino - return inode number of the memcg a page is charged to 365 * @page: the page 366 * 367 * Look up the closest online ancestor of the memory cgroup @page is charged to 368 * and return its inode number or 0 if @page is not charged to any cgroup. It 369 * is safe to call this function without holding a reference to @page. 370 * 371 * Note, this function is inherently racy, because there is nothing to prevent 372 * the cgroup inode from getting torn down and potentially reallocated a moment 373 * after page_cgroup_ino() returns, so it only should be used by callers that 374 * do not care (such as procfs interfaces). 375 */ 376 ino_t page_cgroup_ino(const struct page *page) 377 { 378 struct mem_cgroup *memcg; 379 unsigned long ino = 0; 380 381 rcu_read_lock(); 382 /* page_folio() is racy here, but the entire function is racy anyway */ 383 memcg = folio_memcg_check(page_folio(page)); 384 385 while (memcg && !css_is_online(&memcg->css)) 386 memcg = parent_mem_cgroup(memcg); 387 if (memcg) 388 ino = cgroup_ino(memcg->css.cgroup); 389 rcu_read_unlock(); 390 return ino; 391 } 392 EXPORT_SYMBOL_GPL(page_cgroup_ino); 393 394 /* Subset of node_stat_item for memcg stats */ 395 static const unsigned int memcg_node_stat_items[] = { 396 NR_INACTIVE_ANON, 397 NR_ACTIVE_ANON, 398 NR_INACTIVE_FILE, 399 NR_ACTIVE_FILE, 400 NR_UNEVICTABLE, 401 NR_SLAB_RECLAIMABLE_B, 402 NR_SLAB_UNRECLAIMABLE_B, 403 WORKINGSET_REFAULT_ANON, 404 WORKINGSET_REFAULT_FILE, 405 WORKINGSET_ACTIVATE_ANON, 406 WORKINGSET_ACTIVATE_FILE, 407 WORKINGSET_RESTORE_ANON, 408 WORKINGSET_RESTORE_FILE, 409 WORKINGSET_NODERECLAIM, 410 NR_ANON_MAPPED, 411 NR_FILE_MAPPED, 412 NR_FILE_PAGES, 413 NR_FILE_DIRTY, 414 NR_WRITEBACK, 415 NR_SHMEM, 416 NR_SHMEM_THPS, 417 NR_FILE_THPS, 418 NR_ANON_THPS, 419 NR_VMSCAN_WRITE, 420 NR_VMALLOC, 421 NR_KERNEL_STACK_KB, 422 NR_PAGETABLE, 423 NR_SECONDARY_PAGETABLE, 424 #ifdef CONFIG_SWAP 425 NR_SWAPCACHE, 426 #endif 427 #ifdef CONFIG_NUMA_BALANCING 428 PGPROMOTE_SUCCESS, 429 #endif 430 PGDEMOTE_KSWAPD, 431 PGDEMOTE_DIRECT, 432 PGDEMOTE_KHUGEPAGED, 433 PGDEMOTE_PROACTIVE, 434 PGSTEAL_KSWAPD, 435 PGSTEAL_DIRECT, 436 PGSTEAL_KHUGEPAGED, 437 PGSTEAL_PROACTIVE, 438 PGSTEAL_ANON, 439 PGSTEAL_FILE, 440 PGSCAN_KSWAPD, 441 PGSCAN_DIRECT, 442 PGSCAN_KHUGEPAGED, 443 PGSCAN_PROACTIVE, 444 PGSCAN_ANON, 445 PGSCAN_FILE, 446 PGROTATE_ANON, 447 PGROTATE_FILE, 448 PGREFILL, 449 #ifdef CONFIG_HUGETLB_PAGE 450 NR_HUGETLB, 451 #endif 452 }; 453 454 static const unsigned int memcg_stat_items[] = { 455 MEMCG_SWAP, 456 MEMCG_SOCK, 457 MEMCG_PERCPU_B, 458 MEMCG_KMEM, 459 MEMCG_ZSWAP_B, 460 MEMCG_ZSWAPPED, 461 MEMCG_ZSWAP_INCOMP, 462 }; 463 464 #define NR_MEMCG_NODE_STAT_ITEMS ARRAY_SIZE(memcg_node_stat_items) 465 #define MEMCG_VMSTAT_SIZE (NR_MEMCG_NODE_STAT_ITEMS + \ 466 ARRAY_SIZE(memcg_stat_items)) 467 #define BAD_STAT_IDX(index) ((u32)(index) >= U8_MAX) 468 static u8 mem_cgroup_stats_index[MEMCG_NR_STAT] __read_mostly; 469 470 static void init_memcg_stats(void) 471 { 472 u8 i, j = 0; 473 474 BUILD_BUG_ON(MEMCG_NR_STAT >= U8_MAX); 475 476 memset(mem_cgroup_stats_index, U8_MAX, sizeof(mem_cgroup_stats_index)); 477 478 for (i = 0; i < NR_MEMCG_NODE_STAT_ITEMS; ++i, ++j) 479 mem_cgroup_stats_index[memcg_node_stat_items[i]] = j; 480 481 for (i = 0; i < ARRAY_SIZE(memcg_stat_items); ++i, ++j) 482 mem_cgroup_stats_index[memcg_stat_items[i]] = j; 483 } 484 485 static inline int memcg_stats_index(int idx) 486 { 487 return mem_cgroup_stats_index[idx]; 488 } 489 490 struct lruvec_stats_percpu { 491 /* Local (CPU and cgroup) state */ 492 long state[NR_MEMCG_NODE_STAT_ITEMS]; 493 494 /* Delta calculation for lockless upward propagation */ 495 long state_prev[NR_MEMCG_NODE_STAT_ITEMS]; 496 }; 497 498 struct lruvec_stats { 499 /* Aggregated (CPU and subtree) state */ 500 long state[NR_MEMCG_NODE_STAT_ITEMS]; 501 502 /* Non-hierarchical (CPU aggregated) state */ 503 long state_local[NR_MEMCG_NODE_STAT_ITEMS]; 504 505 /* Pending child counts during tree propagation */ 506 long state_pending[NR_MEMCG_NODE_STAT_ITEMS]; 507 }; 508 509 unsigned long lruvec_page_state(const struct lruvec *lruvec, enum node_stat_item idx) 510 { 511 const struct mem_cgroup_per_node *pn; 512 long x; 513 int i; 514 515 if (mem_cgroup_disabled()) 516 return node_page_state(lruvec_pgdat(lruvec), idx); 517 518 i = memcg_stats_index(idx); 519 if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx)) 520 return 0; 521 522 pn = container_of_const(lruvec, struct mem_cgroup_per_node, lruvec); 523 x = READ_ONCE(pn->lruvec_stats->state[i]); 524 #ifdef CONFIG_SMP 525 if (x < 0) 526 x = 0; 527 #endif 528 return x; 529 } 530 531 /** 532 * lruvec_page_state_monotonic - non-clamping lruvec stat read for delta sampling 533 * @lruvec: the LRU vector to read from 534 * @idx: the node_stat_item to read 535 * 536 * Returns the raw state[idx] value cast to unsigned long, skipping the 537 * clamp-negative-to-zero step in lruvec_page_state(). Intended for callers 538 * that snapshot a monotonically-incremented counter and subtract two 539 * samples: unsigned modular arithmetic then yields the correct delta across 540 * a signed-long wraparound (a real hazard on 32-bit) that the clamp would 541 * otherwise turn into a huge spurious delta. 542 * 543 * Do NOT use for non-monotonic page-count reads where a transient negative 544 * reading from per-CPU delta skew must present as zero. 545 * 546 * XXX: This helper (and its node/global peers) exists because some 547 * monotonically-incremented event counters are stored in 548 * enum node_stat_item. 549 */ 550 unsigned long lruvec_page_state_monotonic(const struct lruvec *lruvec, 551 enum node_stat_item idx) 552 { 553 const struct mem_cgroup_per_node *pn; 554 int i; 555 556 if (mem_cgroup_disabled()) 557 return node_page_state_monotonic(lruvec_pgdat(lruvec), idx); 558 559 i = memcg_stats_index(idx); 560 if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx)) 561 return 0; 562 563 pn = container_of_const(lruvec, struct mem_cgroup_per_node, lruvec); 564 return (unsigned long)READ_ONCE(pn->lruvec_stats->state[i]); 565 } 566 567 unsigned long lruvec_page_state_local(const struct lruvec *lruvec, 568 enum node_stat_item idx) 569 { 570 const struct mem_cgroup_per_node *pn; 571 long x; 572 int i; 573 574 if (mem_cgroup_disabled()) 575 return node_page_state(lruvec_pgdat(lruvec), idx); 576 577 i = memcg_stats_index(idx); 578 if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx)) 579 return 0; 580 581 pn = container_of_const(lruvec, struct mem_cgroup_per_node, lruvec); 582 x = READ_ONCE(pn->lruvec_stats->state_local[i]); 583 #ifdef CONFIG_SMP 584 if (x < 0) 585 x = 0; 586 #endif 587 return x; 588 } 589 590 static void __mod_memcg_lruvec_state(struct mem_cgroup_per_node *pn, 591 enum node_stat_item idx, long val); 592 593 void reparent_memcg_lruvec_state_local(struct mem_cgroup *memcg, 594 struct mem_cgroup *parent, int idx) 595 { 596 int nid; 597 598 for_each_node(nid) { 599 struct lruvec *child_lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid)); 600 struct lruvec *parent_lruvec = mem_cgroup_lruvec(parent, NODE_DATA(nid)); 601 unsigned long value = lruvec_page_state_local(child_lruvec, idx); 602 struct mem_cgroup_per_node *child_pn, *parent_pn; 603 604 child_pn = container_of(child_lruvec, struct mem_cgroup_per_node, lruvec); 605 parent_pn = container_of(parent_lruvec, struct mem_cgroup_per_node, lruvec); 606 607 __mod_memcg_lruvec_state(child_pn, idx, -value); 608 __mod_memcg_lruvec_state(parent_pn, idx, value); 609 } 610 } 611 612 /* Subset of vm_event_item to report for memcg event stats */ 613 static const unsigned int memcg_vm_event_stat[] = { 614 #ifdef CONFIG_MEMCG_V1 615 PGPGIN, 616 PGPGOUT, 617 #endif 618 PSWPIN, 619 PSWPOUT, 620 PGFAULT, 621 PGMAJFAULT, 622 PGACTIVATE, 623 PGDEACTIVATE, 624 PGLAZYFREE, 625 PGLAZYFREED, 626 #ifdef CONFIG_SWAP 627 SWPIN_ZERO, 628 SWPOUT_ZERO, 629 #endif 630 #ifdef CONFIG_ZSWAP 631 ZSWPIN, 632 ZSWPOUT, 633 ZSWPWB, 634 #endif 635 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 636 THP_FAULT_ALLOC, 637 THP_COLLAPSE_ALLOC, 638 THP_SWPOUT, 639 THP_SWPOUT_FALLBACK, 640 #endif 641 #ifdef CONFIG_NUMA_BALANCING 642 NUMA_PAGE_MIGRATE, 643 NUMA_PTE_UPDATES, 644 NUMA_HINT_FAULTS, 645 #endif 646 }; 647 648 #define NR_MEMCG_EVENTS ARRAY_SIZE(memcg_vm_event_stat) 649 static u8 mem_cgroup_events_index[NR_VM_EVENT_ITEMS] __read_mostly; 650 651 static void init_memcg_events(void) 652 { 653 u8 i; 654 655 BUILD_BUG_ON(NR_VM_EVENT_ITEMS >= U8_MAX); 656 657 memset(mem_cgroup_events_index, U8_MAX, 658 sizeof(mem_cgroup_events_index)); 659 660 for (i = 0; i < NR_MEMCG_EVENTS; ++i) 661 mem_cgroup_events_index[memcg_vm_event_stat[i]] = i; 662 } 663 664 static inline int memcg_events_index(enum vm_event_item idx) 665 { 666 return mem_cgroup_events_index[idx]; 667 } 668 669 struct memcg_vmstats_percpu { 670 /* Stats updates since the last flush */ 671 unsigned long stats_updates; 672 673 /* Cached pointers for fast iteration in memcg_rstat_updated() */ 674 struct memcg_vmstats_percpu __percpu *parent_pcpu; 675 struct memcg_vmstats *vmstats; 676 677 /* The above should fit a single cacheline for memcg_rstat_updated() */ 678 679 /* Local (CPU and cgroup) page state & events */ 680 long state[MEMCG_VMSTAT_SIZE]; 681 unsigned long events[NR_MEMCG_EVENTS]; 682 683 /* Delta calculation for lockless upward propagation */ 684 long state_prev[MEMCG_VMSTAT_SIZE]; 685 unsigned long events_prev[NR_MEMCG_EVENTS]; 686 } ____cacheline_aligned; 687 688 struct memcg_vmstats { 689 /* Aggregated (CPU and subtree) page state & events */ 690 long state[MEMCG_VMSTAT_SIZE]; 691 unsigned long events[NR_MEMCG_EVENTS]; 692 693 #ifdef CONFIG_MEMCG_V1 694 /* Non-hierarchical (CPU aggregated) page state & events */ 695 long state_local[MEMCG_VMSTAT_SIZE]; 696 unsigned long events_local[NR_MEMCG_EVENTS]; 697 #endif 698 699 /* Pending child counts during tree propagation */ 700 long state_pending[MEMCG_VMSTAT_SIZE]; 701 unsigned long events_pending[NR_MEMCG_EVENTS]; 702 703 /* Stats updates since the last flush */ 704 atomic_long_t stats_updates; 705 }; 706 707 /* 708 * The non-hierarchical memcg-wide counters are read back only by the legacy 709 * memory.stat and memory.numa_stat, and by reparenting on offline, all of which 710 * are v1-only. If the kernel is built without CONFIG_MEMCG_V1, or if the boot 711 * param cgroup_no_v1= has blocked the memory controller from v1 hierarchies, 712 * then nothing reads them and writers can skip the updates. 713 */ 714 static long *memcg_state_local_array(struct mem_cgroup *memcg) 715 { 716 #ifdef CONFIG_MEMCG_V1 717 if (!cgroup1_ssid_disabled(memory_cgrp_id)) 718 return memcg->vmstats->state_local; 719 #endif 720 return NULL; 721 } 722 723 static unsigned long *memcg_events_local_array(struct mem_cgroup *memcg) 724 { 725 #ifdef CONFIG_MEMCG_V1 726 if (!cgroup1_ssid_disabled(memory_cgrp_id)) 727 return memcg->vmstats->events_local; 728 #endif 729 return NULL; 730 } 731 732 /* 733 * memcg and lruvec stats flushing 734 * 735 * Many codepaths leading to stats update or read are performance sensitive and 736 * adding stats flushing in such codepaths is not desirable. So, to optimize the 737 * flushing the kernel does: 738 * 739 * 1) Periodically and asynchronously flush the stats every 2 seconds to not let 740 * rstat update tree grow unbounded. 741 * 742 * 2) Flush the stats synchronously on reader side only when there are more than 743 * (MEMCG_CHARGE_BATCH * nr_cpus) update events. Though this optimization 744 * will let stats be out of sync by at most (MEMCG_CHARGE_BATCH * nr_cpus) but 745 * only for 2 seconds due to (1). 746 */ 747 static void flush_memcg_stats_dwork(struct work_struct *w); 748 static DECLARE_DEFERRABLE_WORK(stats_flush_dwork, flush_memcg_stats_dwork); 749 static u64 flush_last_time; 750 751 #define FLUSH_TIME (2UL*HZ) 752 753 static bool memcg_vmstats_needs_flush(struct memcg_vmstats *vmstats) 754 { 755 return atomic_long_read(&vmstats->stats_updates) > 756 MEMCG_CHARGE_BATCH * num_online_cpus(); 757 } 758 759 static inline void memcg_rstat_updated(struct mem_cgroup *memcg, long val, 760 int cpu) 761 { 762 struct memcg_vmstats_percpu __percpu *statc_pcpu; 763 struct memcg_vmstats_percpu *statc; 764 unsigned long stats_updates; 765 766 if (!val) 767 return; 768 769 __css_rstat_updated(&memcg->css, cpu); 770 statc_pcpu = memcg->vmstats_percpu; 771 for (; statc_pcpu; statc_pcpu = statc->parent_pcpu) { 772 statc = this_cpu_ptr(statc_pcpu); 773 /* 774 * If @memcg is already flushable then all its ancestors are 775 * flushable as well and also there is no need to increase 776 * stats_updates. 777 */ 778 if (memcg_vmstats_needs_flush(statc->vmstats)) 779 break; 780 781 stats_updates = this_cpu_add_return(statc_pcpu->stats_updates, 782 abs(val)); 783 if (stats_updates < MEMCG_CHARGE_BATCH) 784 continue; 785 786 stats_updates = this_cpu_xchg(statc_pcpu->stats_updates, 0); 787 atomic_long_add(stats_updates, &statc->vmstats->stats_updates); 788 } 789 } 790 791 static void __mem_cgroup_flush_stats(struct mem_cgroup *memcg, bool force) 792 { 793 bool needs_flush = memcg_vmstats_needs_flush(memcg->vmstats); 794 795 trace_memcg_flush_stats(memcg, atomic_long_read(&memcg->vmstats->stats_updates), 796 force, needs_flush); 797 798 if (!force && !needs_flush) 799 return; 800 801 if (mem_cgroup_is_root(memcg)) 802 WRITE_ONCE(flush_last_time, get_jiffies_64()); 803 804 css_rstat_flush(&memcg->css); 805 } 806 807 /* 808 * mem_cgroup_flush_stats - flush the stats of a memory cgroup subtree 809 * @memcg: root of the subtree to flush 810 * 811 * Flushing is serialized by the underlying global rstat lock. There is also a 812 * minimum amount of work to be done even if there are no stat updates to flush. 813 * Hence, we only flush the stats if the updates delta exceeds a threshold. This 814 * avoids unnecessary work and contention on the underlying lock. 815 */ 816 void mem_cgroup_flush_stats(struct mem_cgroup *memcg) 817 { 818 if (mem_cgroup_disabled()) 819 return; 820 821 if (!memcg) 822 memcg = root_mem_cgroup; 823 824 __mem_cgroup_flush_stats(memcg, false); 825 } 826 827 void mem_cgroup_flush_stats_ratelimited(struct mem_cgroup *memcg) 828 { 829 /* Only flush if the periodic flusher is one full cycle late */ 830 if (time_after64(get_jiffies_64(), READ_ONCE(flush_last_time) + 2 * FLUSH_TIME)) 831 mem_cgroup_flush_stats(memcg); 832 } 833 834 static void flush_memcg_stats_dwork(struct work_struct *w) 835 { 836 /* 837 * Deliberately ignore memcg_vmstats_needs_flush() here so that flushing 838 * in latency-sensitive paths is as cheap as possible. 839 */ 840 __mem_cgroup_flush_stats(root_mem_cgroup, true); 841 queue_delayed_work(system_dfl_wq, &stats_flush_dwork, FLUSH_TIME); 842 } 843 844 unsigned long memcg_page_state(const struct mem_cgroup *memcg, int idx) 845 { 846 long x; 847 int i = memcg_stats_index(idx); 848 849 if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx)) 850 return 0; 851 852 x = READ_ONCE(memcg->vmstats->state[i]); 853 #ifdef CONFIG_SMP 854 if (x < 0) 855 x = 0; 856 #endif 857 return x; 858 } 859 860 bool memcg_stat_item_valid(int idx) 861 { 862 if ((u32)idx >= MEMCG_NR_STAT) 863 return false; 864 865 return !BAD_STAT_IDX(memcg_stats_index(idx)); 866 } 867 868 static int memcg_page_state_unit(int item); 869 870 /* 871 * Normalize the value passed into memcg_rstat_updated() to be in pages. Round 872 * up non-zero sub-page updates to 1 page as zero page updates are ignored. 873 */ 874 static long memcg_state_val_in_pages(int idx, long val) 875 { 876 int unit = memcg_page_state_unit(idx); 877 long res; 878 879 if (!val || unit == PAGE_SIZE) 880 return val; 881 882 /* Get the absolute value of (val * unit / PAGE_SIZE). */ 883 res = mult_frac(abs(val), unit, PAGE_SIZE); 884 /* Round up zero values. */ 885 res = res ? : 1; 886 887 return val < 0 ? -res : res; 888 } 889 890 /* 891 * Used in mod_memcg_state() and mod_memcg_lruvec_state() to avoid race 892 * with reparenting of non-hierarchical state_locals. Offlining a 893 * memcg is rare, so do the redirection for all cgroup hierarchies. 894 */ 895 static inline struct mem_cgroup * 896 get_non_dying_memcg_start(struct mem_cgroup *memcg, bool *rcu_locked) 897 { 898 /* 899 * Fast path: the caller holds a reference to @memcg, so reading 900 * its CSS_DYING flag without the RCU lock is safe. The RCU lock 901 * is only needed to walk up to a non-dying ancestor, which 902 * happens only while a memcg is actually being offlined. 903 */ 904 if (!memcg_is_dying(memcg)) { 905 *rcu_locked = false; 906 return memcg; 907 } 908 909 rcu_read_lock(); 910 *rcu_locked = true; 911 912 while (memcg_is_dying(memcg)) 913 memcg = parent_mem_cgroup(memcg); 914 915 return memcg; 916 } 917 918 static inline void get_non_dying_memcg_end(bool rcu_locked) 919 { 920 if (!rcu_locked) 921 return; 922 923 rcu_read_unlock(); 924 } 925 926 static void __mod_memcg_state(struct mem_cgroup *memcg, 927 enum memcg_stat_item idx, long val) 928 { 929 int i = memcg_stats_index(idx); 930 int cpu; 931 932 if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx)) 933 return; 934 935 cpu = get_cpu(); 936 937 this_cpu_add(memcg->vmstats_percpu->state[i], val); 938 val = memcg_state_val_in_pages(idx, val); 939 memcg_rstat_updated(memcg, val, cpu); 940 941 trace_mod_memcg_state(memcg, idx, val); 942 943 put_cpu(); 944 } 945 946 /** 947 * mod_memcg_state - update cgroup memory statistics 948 * @memcg: the memory cgroup 949 * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item 950 * @val: delta to add to the counter, can be negative 951 */ 952 void mod_memcg_state(struct mem_cgroup *memcg, enum memcg_stat_item idx, 953 int val) 954 { 955 bool rcu_locked = false; 956 957 if (mem_cgroup_disabled()) 958 return; 959 960 memcg = get_non_dying_memcg_start(memcg, &rcu_locked); 961 __mod_memcg_state(memcg, idx, val); 962 get_non_dying_memcg_end(rcu_locked); 963 } 964 965 #ifdef CONFIG_MEMCG_V1 966 /* idx can be of type enum memcg_stat_item or node_stat_item. */ 967 unsigned long memcg_page_state_local(const struct mem_cgroup *memcg, int idx) 968 { 969 long x; 970 int i = memcg_stats_index(idx); 971 972 if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx)) 973 return 0; 974 975 x = READ_ONCE(memcg->vmstats->state_local[i]); 976 #ifdef CONFIG_SMP 977 if (x < 0) 978 x = 0; 979 #endif 980 return x; 981 } 982 983 void reparent_memcg_state_local(struct mem_cgroup *memcg, 984 struct mem_cgroup *parent, int idx) 985 { 986 unsigned long value = memcg_page_state_local(memcg, idx); 987 988 __mod_memcg_state(memcg, idx, -value); 989 __mod_memcg_state(parent, idx, value); 990 } 991 #endif 992 993 static void __mod_memcg_lruvec_state(struct mem_cgroup_per_node *pn, 994 enum node_stat_item idx, long val) 995 { 996 struct mem_cgroup *memcg = pn->memcg; 997 int i = memcg_stats_index(idx); 998 int cpu; 999 1000 if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx)) 1001 return; 1002 1003 cpu = get_cpu(); 1004 1005 /* Update memcg */ 1006 this_cpu_add(memcg->vmstats_percpu->state[i], val); 1007 1008 /* Update lruvec */ 1009 this_cpu_add(pn->lruvec_stats_percpu->state[i], val); 1010 1011 val = memcg_state_val_in_pages(idx, val); 1012 memcg_rstat_updated(memcg, val, cpu); 1013 trace_mod_memcg_lruvec_state(memcg, idx, val); 1014 1015 put_cpu(); 1016 } 1017 1018 void mod_memcg_lruvec_state(struct lruvec *lruvec, 1019 enum node_stat_item idx, int val) 1020 { 1021 struct pglist_data *pgdat = lruvec_pgdat(lruvec); 1022 struct mem_cgroup_per_node *pn; 1023 struct mem_cgroup *memcg; 1024 bool rcu_locked = false; 1025 1026 pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec); 1027 memcg = get_non_dying_memcg_start(pn->memcg, &rcu_locked); 1028 pn = memcg->nodeinfo[pgdat->node_id]; 1029 1030 __mod_memcg_lruvec_state(pn, idx, val); 1031 1032 get_non_dying_memcg_end(rcu_locked); 1033 } 1034 1035 /** 1036 * mod_lruvec_state - update lruvec memory statistics 1037 * @lruvec: the lruvec 1038 * @idx: the stat item 1039 * @val: delta to add to the counter, can be negative 1040 * 1041 * The lruvec is the intersection of the NUMA node and a cgroup. This 1042 * function updates the all three counters that are affected by a 1043 * change of state at this level: per-node, per-cgroup, per-lruvec. 1044 */ 1045 void mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx, 1046 int val) 1047 { 1048 /* Update node */ 1049 mod_node_page_state(lruvec_pgdat(lruvec), idx, val); 1050 1051 /* Update memcg and lruvec */ 1052 if (!mem_cgroup_disabled()) 1053 mod_memcg_lruvec_state(lruvec, idx, val); 1054 } 1055 1056 void lruvec_stat_mod_folio(struct folio *folio, enum node_stat_item idx, 1057 int val) 1058 { 1059 struct mem_cgroup *memcg; 1060 pg_data_t *pgdat = folio_pgdat(folio); 1061 struct lruvec *lruvec; 1062 1063 rcu_read_lock(); 1064 memcg = folio_memcg(folio); 1065 /* Untracked pages have no memcg, no lruvec. Update only the node */ 1066 if (!memcg) { 1067 rcu_read_unlock(); 1068 mod_node_page_state(pgdat, idx, val); 1069 return; 1070 } 1071 1072 lruvec = mem_cgroup_lruvec(memcg, pgdat); 1073 mod_lruvec_state(lruvec, idx, val); 1074 rcu_read_unlock(); 1075 } 1076 EXPORT_SYMBOL(lruvec_stat_mod_folio); 1077 1078 void mod_lruvec_kmem_state(void *p, enum node_stat_item idx, int val) 1079 { 1080 pg_data_t *pgdat = page_pgdat(virt_to_page(p)); 1081 struct mem_cgroup *memcg; 1082 struct lruvec *lruvec; 1083 1084 rcu_read_lock(); 1085 memcg = mem_cgroup_from_virt(p); 1086 1087 /* 1088 * Untracked pages have no memcg, no lruvec. Update only the 1089 * node. If we reparent the slab objects to the root memcg, 1090 * when we free the slab object, we need to update the per-memcg 1091 * vmstats to keep it correct for the root memcg. 1092 */ 1093 if (!memcg) { 1094 mod_node_page_state(pgdat, idx, val); 1095 } else { 1096 lruvec = mem_cgroup_lruvec(memcg, pgdat); 1097 mod_lruvec_state(lruvec, idx, val); 1098 } 1099 rcu_read_unlock(); 1100 } 1101 1102 /** 1103 * count_memcg_events - account VM events in a cgroup 1104 * @memcg: the memory cgroup 1105 * @idx: the event item 1106 * @count: the number of events that occurred 1107 */ 1108 void count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx, 1109 unsigned long count) 1110 { 1111 int i = memcg_events_index(idx); 1112 int cpu; 1113 1114 if (mem_cgroup_disabled()) 1115 return; 1116 1117 if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx)) 1118 return; 1119 1120 cpu = get_cpu(); 1121 1122 this_cpu_add(memcg->vmstats_percpu->events[i], count); 1123 memcg_rstat_updated(memcg, count, cpu); 1124 trace_count_memcg_events(memcg, idx, count); 1125 1126 put_cpu(); 1127 } 1128 1129 unsigned long memcg_events(const struct mem_cgroup *memcg, int event) 1130 { 1131 int i = memcg_events_index(event); 1132 1133 if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, event)) 1134 return 0; 1135 1136 return READ_ONCE(memcg->vmstats->events[i]); 1137 } 1138 1139 bool memcg_vm_event_item_valid(enum vm_event_item idx) 1140 { 1141 if (idx >= NR_VM_EVENT_ITEMS) 1142 return false; 1143 1144 return !BAD_STAT_IDX(memcg_events_index(idx)); 1145 } 1146 1147 #ifdef CONFIG_MEMCG_V1 1148 unsigned long memcg_events_local(const struct mem_cgroup *memcg, int event) 1149 { 1150 int i = memcg_events_index(event); 1151 1152 if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, event)) 1153 return 0; 1154 1155 return READ_ONCE(memcg->vmstats->events_local[i]); 1156 } 1157 #endif 1158 1159 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p) 1160 { 1161 /* 1162 * mm_update_next_owner() may clear mm->owner to NULL 1163 * if it races with swapoff, page migration, etc. 1164 * So this can be called with p == NULL. 1165 */ 1166 if (unlikely(!p)) 1167 return NULL; 1168 1169 return mem_cgroup_from_css(task_css(p, memory_cgrp_id)); 1170 } 1171 EXPORT_SYMBOL(mem_cgroup_from_task); 1172 1173 static __always_inline struct mem_cgroup *active_memcg(void) 1174 { 1175 if (!in_task()) 1176 return this_cpu_read(int_active_memcg); 1177 else 1178 return current->active_memcg; 1179 } 1180 1181 /** 1182 * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg. 1183 * @mm: mm from which memcg should be extracted. It can be NULL. 1184 * 1185 * Obtain a reference on mm->memcg and returns it if successful. If mm 1186 * is NULL, then the memcg is chosen as follows: 1187 * 1) The active memcg, if set. 1188 * 2) current->mm->memcg, if available 1189 * 3) root memcg 1190 * If mem_cgroup is disabled, NULL is returned. 1191 */ 1192 struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm) 1193 { 1194 struct mem_cgroup *memcg; 1195 1196 if (mem_cgroup_disabled()) 1197 return NULL; 1198 1199 /* 1200 * Page cache insertions can happen without an 1201 * actual mm context, e.g. during disk probing 1202 * on boot, loopback IO, acct() writes etc. 1203 * 1204 * No need to css_get on root memcg as the reference 1205 * counting is disabled on the root level in the 1206 * cgroup core. See CSS_NO_REF. 1207 */ 1208 if (unlikely(!mm)) { 1209 memcg = active_memcg(); 1210 if (unlikely(memcg)) { 1211 /* remote memcg must hold a ref */ 1212 css_get(&memcg->css); 1213 return memcg; 1214 } 1215 mm = current->mm; 1216 if (unlikely(!mm)) 1217 return root_mem_cgroup; 1218 } 1219 1220 rcu_read_lock(); 1221 do { 1222 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner)); 1223 if (unlikely(!memcg)) 1224 memcg = root_mem_cgroup; 1225 } while (!css_tryget(&memcg->css)); 1226 rcu_read_unlock(); 1227 return memcg; 1228 } 1229 EXPORT_SYMBOL(get_mem_cgroup_from_mm); 1230 1231 /** 1232 * get_mem_cgroup_from_current - Obtain a reference on current task's memcg. 1233 */ 1234 struct mem_cgroup *get_mem_cgroup_from_current(void) 1235 { 1236 struct mem_cgroup *memcg; 1237 1238 if (mem_cgroup_disabled()) 1239 return NULL; 1240 1241 again: 1242 rcu_read_lock(); 1243 memcg = mem_cgroup_from_task(current); 1244 if (!css_tryget(&memcg->css)) { 1245 rcu_read_unlock(); 1246 goto again; 1247 } 1248 rcu_read_unlock(); 1249 return memcg; 1250 } 1251 1252 /** 1253 * get_mem_cgroup_from_folio - Obtain a reference on a given folio's memcg. 1254 * @folio: folio from which memcg should be extracted. 1255 * 1256 * See folio_memcg() for folio->objcg/memcg binding rules. 1257 */ 1258 struct mem_cgroup *get_mem_cgroup_from_folio(const struct folio *folio) 1259 { 1260 struct mem_cgroup *memcg; 1261 1262 if (mem_cgroup_disabled()) 1263 return NULL; 1264 1265 if (!folio_memcg_charged(folio)) 1266 return root_mem_cgroup; 1267 1268 rcu_read_lock(); 1269 do { 1270 memcg = folio_memcg(folio); 1271 } while (unlikely(!css_tryget(&memcg->css))); 1272 rcu_read_unlock(); 1273 return memcg; 1274 } 1275 1276 /** 1277 * mem_cgroup_iter - iterate over memory cgroup hierarchy 1278 * @root: hierarchy root 1279 * @prev: previously returned memcg, NULL on first invocation 1280 * @reclaim: cookie for shared reclaim walks, NULL for full walks 1281 * 1282 * Returns references to children of the hierarchy below @root, or 1283 * @root itself, or %NULL after a full round-trip. 1284 * 1285 * Caller must pass the return value in @prev on subsequent 1286 * invocations for reference counting, or use mem_cgroup_iter_break() 1287 * to cancel a hierarchy walk before the round-trip is complete. 1288 * 1289 * Reclaimers can specify a node in @reclaim to divide up the memcgs 1290 * in the hierarchy among all concurrent reclaimers operating on the 1291 * same node. 1292 */ 1293 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root, 1294 struct mem_cgroup *prev, 1295 struct mem_cgroup_reclaim_cookie *reclaim) 1296 { 1297 struct mem_cgroup_reclaim_iter *iter; 1298 struct cgroup_subsys_state *css; 1299 struct mem_cgroup *pos; 1300 struct mem_cgroup *next; 1301 1302 if (mem_cgroup_disabled()) 1303 return NULL; 1304 1305 if (!root) 1306 root = root_mem_cgroup; 1307 1308 rcu_read_lock(); 1309 restart: 1310 next = NULL; 1311 1312 if (reclaim) { 1313 int gen; 1314 int nid = reclaim->pgdat->node_id; 1315 1316 iter = &root->nodeinfo[nid]->iter; 1317 gen = atomic_read(&iter->generation); 1318 1319 /* 1320 * On start, join the current reclaim iteration cycle. 1321 * Exit when a concurrent walker completes it. 1322 */ 1323 if (!prev) 1324 reclaim->generation = gen; 1325 else if (reclaim->generation != gen) 1326 goto out_unlock; 1327 1328 pos = READ_ONCE(iter->position); 1329 } else 1330 pos = prev; 1331 1332 css = pos ? &pos->css : NULL; 1333 1334 while ((css = css_next_descendant_pre(css, &root->css))) { 1335 /* 1336 * Verify the css and acquire a reference. The root 1337 * is provided by the caller, so we know it's alive 1338 * and kicking, and don't take an extra reference. 1339 */ 1340 if (css == &root->css || css_tryget(css)) 1341 break; 1342 } 1343 1344 next = mem_cgroup_from_css(css); 1345 1346 if (reclaim) { 1347 /* 1348 * The position could have already been updated by a competing 1349 * thread, so check that the value hasn't changed since we read 1350 * it to avoid reclaiming from the same cgroup twice. 1351 */ 1352 if (cmpxchg(&iter->position, pos, next) != pos) { 1353 if (css && css != &root->css) 1354 css_put(css); 1355 goto restart; 1356 } 1357 1358 if (!next) { 1359 atomic_inc(&iter->generation); 1360 1361 /* 1362 * Reclaimers share the hierarchy walk, and a 1363 * new one might jump in right at the end of 1364 * the hierarchy - make sure they see at least 1365 * one group and restart from the beginning. 1366 */ 1367 if (!prev) 1368 goto restart; 1369 } 1370 } 1371 1372 out_unlock: 1373 rcu_read_unlock(); 1374 if (prev && prev != root) 1375 css_put(&prev->css); 1376 1377 return next; 1378 } 1379 1380 /** 1381 * mem_cgroup_iter_break - abort a hierarchy walk prematurely 1382 * @root: hierarchy root 1383 * @prev: last visited hierarchy member as returned by mem_cgroup_iter() 1384 */ 1385 void mem_cgroup_iter_break(struct mem_cgroup *root, 1386 struct mem_cgroup *prev) 1387 { 1388 if (!root) 1389 root = root_mem_cgroup; 1390 if (prev && prev != root) 1391 css_put(&prev->css); 1392 } 1393 1394 static void __invalidate_reclaim_iterators(struct mem_cgroup *from, 1395 struct mem_cgroup *dead_memcg) 1396 { 1397 struct mem_cgroup_reclaim_iter *iter; 1398 struct mem_cgroup_per_node *mz; 1399 int nid; 1400 1401 for_each_node(nid) { 1402 mz = from->nodeinfo[nid]; 1403 iter = &mz->iter; 1404 cmpxchg(&iter->position, dead_memcg, NULL); 1405 } 1406 } 1407 1408 static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg) 1409 { 1410 struct mem_cgroup *memcg = dead_memcg; 1411 struct mem_cgroup *last; 1412 1413 do { 1414 __invalidate_reclaim_iterators(memcg, dead_memcg); 1415 last = memcg; 1416 } while ((memcg = parent_mem_cgroup(memcg))); 1417 1418 /* 1419 * When cgroup1 non-hierarchy mode is used, 1420 * parent_mem_cgroup() does not walk all the way up to the 1421 * cgroup root (root_mem_cgroup). So we have to handle 1422 * dead_memcg from cgroup root separately. 1423 */ 1424 if (!mem_cgroup_is_root(last)) 1425 __invalidate_reclaim_iterators(root_mem_cgroup, 1426 dead_memcg); 1427 } 1428 1429 /** 1430 * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy 1431 * @memcg: hierarchy root 1432 * @fn: function to call for each task 1433 * @arg: argument passed to @fn 1434 * 1435 * This function iterates over tasks attached to @memcg or to any of its 1436 * descendants and calls @fn for each task. If @fn returns a non-zero 1437 * value, the function breaks the iteration loop. Otherwise, it will iterate 1438 * over all tasks and return 0. 1439 * 1440 * This function must not be called for the root memory cgroup. 1441 */ 1442 void mem_cgroup_scan_tasks(struct mem_cgroup *memcg, 1443 int (*fn)(struct task_struct *, void *), void *arg) 1444 { 1445 struct mem_cgroup *iter; 1446 int ret = 0; 1447 1448 BUG_ON(mem_cgroup_is_root(memcg)); 1449 1450 for_each_mem_cgroup_tree(iter, memcg) { 1451 struct css_task_iter it; 1452 struct task_struct *task; 1453 1454 css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it); 1455 while (!ret && (task = css_task_iter_next(&it))) { 1456 ret = fn(task, arg); 1457 /* Avoid potential softlockup warning */ 1458 cond_resched(); 1459 } 1460 css_task_iter_end(&it); 1461 if (ret) { 1462 mem_cgroup_iter_break(memcg, iter); 1463 break; 1464 } 1465 } 1466 } 1467 1468 /** 1469 * folio_lruvec_lock - Lock the lruvec for a folio. 1470 * @folio: Pointer to the folio. 1471 * 1472 * These functions are safe to use under any of the following conditions: 1473 * - folio locked 1474 * - folio_test_lru false 1475 * - folio frozen (refcount of 0) 1476 * 1477 * Return: The lruvec this folio is on with its lock held and rcu read lock held. 1478 */ 1479 struct lruvec *folio_lruvec_lock(const struct folio *folio) 1480 { 1481 struct lruvec *lruvec; 1482 1483 rcu_read_lock(); 1484 retry: 1485 lruvec = folio_lruvec(folio); 1486 spin_lock(&lruvec->lru_lock); 1487 if (unlikely(lruvec_memcg(lruvec) != folio_memcg(folio))) { 1488 spin_unlock(&lruvec->lru_lock); 1489 goto retry; 1490 } 1491 1492 return lruvec; 1493 } 1494 1495 /** 1496 * folio_lruvec_lock_irq - Lock the lruvec for a folio. 1497 * @folio: Pointer to the folio. 1498 * 1499 * These functions are safe to use under any of the following conditions: 1500 * - folio locked 1501 * - folio_test_lru false 1502 * - folio frozen (refcount of 0) 1503 * 1504 * Return: The lruvec this folio is on with its lock held and interrupts 1505 * disabled and rcu read lock held. 1506 */ 1507 struct lruvec *folio_lruvec_lock_irq(const struct folio *folio) 1508 { 1509 struct lruvec *lruvec; 1510 1511 rcu_read_lock(); 1512 retry: 1513 lruvec = folio_lruvec(folio); 1514 spin_lock_irq(&lruvec->lru_lock); 1515 if (unlikely(lruvec_memcg(lruvec) != folio_memcg(folio))) { 1516 spin_unlock_irq(&lruvec->lru_lock); 1517 goto retry; 1518 } 1519 1520 return lruvec; 1521 } 1522 1523 /** 1524 * folio_lruvec_lock_irqsave - Lock the lruvec for a folio. 1525 * @folio: Pointer to the folio. 1526 * @flags: Pointer to irqsave flags. 1527 * 1528 * These functions are safe to use under any of the following conditions: 1529 * - folio locked 1530 * - folio_test_lru false 1531 * - folio frozen (refcount of 0) 1532 * 1533 * Return: The lruvec this folio is on with its lock held and interrupts 1534 * disabled and rcu read lock held. 1535 */ 1536 struct lruvec *folio_lruvec_lock_irqsave(const struct folio *folio, 1537 unsigned long *flags) 1538 { 1539 struct lruvec *lruvec; 1540 1541 rcu_read_lock(); 1542 retry: 1543 lruvec = folio_lruvec(folio); 1544 spin_lock_irqsave(&lruvec->lru_lock, *flags); 1545 if (unlikely(lruvec_memcg(lruvec) != folio_memcg(folio))) { 1546 spin_unlock_irqrestore(&lruvec->lru_lock, *flags); 1547 goto retry; 1548 } 1549 1550 return lruvec; 1551 } 1552 1553 /** 1554 * mem_cgroup_update_lru_size - account for adding or removing an lru page 1555 * @lruvec: mem_cgroup per zone lru vector 1556 * @lru: index of lru list the page is sitting on 1557 * @zid: zone id of the accounted pages 1558 * @nr_pages: positive when adding or negative when removing 1559 * 1560 * This function must be called under lru_lock, just before a page is added 1561 * to or just after a page is removed from an lru list. 1562 */ 1563 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru, 1564 int zid, long nr_pages) 1565 { 1566 struct mem_cgroup_per_node *mz; 1567 1568 if (mem_cgroup_disabled()) 1569 return; 1570 1571 mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec); 1572 mz->lru_zone_size[zid][lru] += nr_pages; 1573 } 1574 1575 /** 1576 * mem_cgroup_margin - calculate chargeable space of a memory cgroup 1577 * @memcg: the memory cgroup 1578 * 1579 * Returns the maximum amount of memory @mem can be charged with, in 1580 * pages. 1581 */ 1582 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg) 1583 { 1584 unsigned long margin = 0; 1585 unsigned long count; 1586 unsigned long limit; 1587 1588 count = page_counter_read(&memcg->memory); 1589 limit = READ_ONCE(memcg->memory.max); 1590 if (count < limit) 1591 margin = limit - count; 1592 1593 if (do_memsw_account()) { 1594 count = page_counter_read(&memcg->memsw); 1595 limit = READ_ONCE(memcg->memsw.max); 1596 if (count < limit) 1597 margin = min(margin, limit - count); 1598 else 1599 margin = 0; 1600 } 1601 1602 return margin; 1603 } 1604 1605 struct memory_stat { 1606 const char *name; 1607 unsigned int idx; 1608 }; 1609 1610 static const struct memory_stat memory_stats[] = { 1611 { "anon", NR_ANON_MAPPED }, 1612 { "file", NR_FILE_PAGES }, 1613 { "kernel", MEMCG_KMEM }, 1614 { "kernel_stack", NR_KERNEL_STACK_KB }, 1615 { "pagetables", NR_PAGETABLE }, 1616 { "sec_pagetables", NR_SECONDARY_PAGETABLE }, 1617 { "percpu", MEMCG_PERCPU_B }, 1618 { "sock", MEMCG_SOCK }, 1619 { "vmalloc", NR_VMALLOC }, 1620 { "shmem", NR_SHMEM }, 1621 #ifdef CONFIG_ZSWAP 1622 { "zswap", MEMCG_ZSWAP_B }, 1623 { "zswapped", MEMCG_ZSWAPPED }, 1624 { "zswap_incomp", MEMCG_ZSWAP_INCOMP }, 1625 #endif 1626 { "file_mapped", NR_FILE_MAPPED }, 1627 { "file_dirty", NR_FILE_DIRTY }, 1628 { "file_writeback", NR_WRITEBACK }, 1629 #ifdef CONFIG_SWAP 1630 { "swapcached", NR_SWAPCACHE }, 1631 #endif 1632 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 1633 { "anon_thp", NR_ANON_THPS }, 1634 { "file_thp", NR_FILE_THPS }, 1635 { "shmem_thp", NR_SHMEM_THPS }, 1636 #endif 1637 { "inactive_anon", NR_INACTIVE_ANON }, 1638 { "active_anon", NR_ACTIVE_ANON }, 1639 { "inactive_file", NR_INACTIVE_FILE }, 1640 { "active_file", NR_ACTIVE_FILE }, 1641 { "unevictable", NR_UNEVICTABLE }, 1642 { "slab_reclaimable", NR_SLAB_RECLAIMABLE_B }, 1643 { "slab_unreclaimable", NR_SLAB_UNRECLAIMABLE_B }, 1644 #ifdef CONFIG_HUGETLB_PAGE 1645 { "hugetlb", NR_HUGETLB }, 1646 #endif 1647 1648 /* The memory events */ 1649 { "workingset_refault_anon", WORKINGSET_REFAULT_ANON }, 1650 { "workingset_refault_file", WORKINGSET_REFAULT_FILE }, 1651 { "workingset_activate_anon", WORKINGSET_ACTIVATE_ANON }, 1652 { "workingset_activate_file", WORKINGSET_ACTIVATE_FILE }, 1653 { "workingset_restore_anon", WORKINGSET_RESTORE_ANON }, 1654 { "workingset_restore_file", WORKINGSET_RESTORE_FILE }, 1655 { "workingset_nodereclaim", WORKINGSET_NODERECLAIM }, 1656 1657 { "pgdemote_kswapd", PGDEMOTE_KSWAPD }, 1658 { "pgdemote_direct", PGDEMOTE_DIRECT }, 1659 { "pgdemote_khugepaged", PGDEMOTE_KHUGEPAGED }, 1660 { "pgdemote_proactive", PGDEMOTE_PROACTIVE }, 1661 { "pgsteal_kswapd", PGSTEAL_KSWAPD }, 1662 { "pgsteal_direct", PGSTEAL_DIRECT }, 1663 { "pgsteal_khugepaged", PGSTEAL_KHUGEPAGED }, 1664 { "pgsteal_proactive", PGSTEAL_PROACTIVE }, 1665 { "pgscan_kswapd", PGSCAN_KSWAPD }, 1666 { "pgscan_direct", PGSCAN_DIRECT }, 1667 { "pgscan_khugepaged", PGSCAN_KHUGEPAGED }, 1668 { "pgscan_proactive", PGSCAN_PROACTIVE }, 1669 { "pgrefill", PGREFILL }, 1670 #ifdef CONFIG_NUMA_BALANCING 1671 { "pgpromote_success", PGPROMOTE_SUCCESS }, 1672 #endif 1673 }; 1674 1675 /* The actual unit of the state item, not the same as the output unit */ 1676 static int memcg_page_state_unit(int item) 1677 { 1678 switch (item) { 1679 case MEMCG_PERCPU_B: 1680 case MEMCG_ZSWAP_B: 1681 case NR_SLAB_RECLAIMABLE_B: 1682 case NR_SLAB_UNRECLAIMABLE_B: 1683 return 1; 1684 case NR_KERNEL_STACK_KB: 1685 return SZ_1K; 1686 default: 1687 return PAGE_SIZE; 1688 } 1689 } 1690 1691 /* Translate stat items to the correct unit for memory.stat output */ 1692 static int memcg_page_state_output_unit(int item) 1693 { 1694 /* 1695 * Workingset state is actually in pages, but we export it to userspace 1696 * as a scalar count of events, so special case it here. 1697 * 1698 * Demotion and promotion activities are exported in pages, consistent 1699 * with their global counterparts. 1700 */ 1701 switch (item) { 1702 case WORKINGSET_REFAULT_ANON: 1703 case WORKINGSET_REFAULT_FILE: 1704 case WORKINGSET_ACTIVATE_ANON: 1705 case WORKINGSET_ACTIVATE_FILE: 1706 case WORKINGSET_RESTORE_ANON: 1707 case WORKINGSET_RESTORE_FILE: 1708 case WORKINGSET_NODERECLAIM: 1709 case PGDEMOTE_KSWAPD: 1710 case PGDEMOTE_DIRECT: 1711 case PGDEMOTE_KHUGEPAGED: 1712 case PGDEMOTE_PROACTIVE: 1713 case PGSTEAL_KSWAPD: 1714 case PGSTEAL_DIRECT: 1715 case PGSTEAL_KHUGEPAGED: 1716 case PGSTEAL_PROACTIVE: 1717 case PGSCAN_KSWAPD: 1718 case PGSCAN_DIRECT: 1719 case PGSCAN_KHUGEPAGED: 1720 case PGSCAN_PROACTIVE: 1721 case PGREFILL: 1722 #ifdef CONFIG_NUMA_BALANCING 1723 case PGPROMOTE_SUCCESS: 1724 #endif 1725 return 1; 1726 default: 1727 return memcg_page_state_unit(item); 1728 } 1729 } 1730 1731 unsigned long memcg_page_state_output(const struct mem_cgroup *memcg, int item) 1732 { 1733 return memcg_page_state(memcg, item) * 1734 memcg_page_state_output_unit(item); 1735 } 1736 1737 #ifdef CONFIG_MEMCG_V1 1738 unsigned long memcg_page_state_local_output(const struct mem_cgroup *memcg, int item) 1739 { 1740 return memcg_page_state_local(memcg, item) * 1741 memcg_page_state_output_unit(item); 1742 } 1743 #endif 1744 1745 #ifdef CONFIG_HUGETLB_PAGE 1746 static bool memcg_accounts_hugetlb(void) 1747 { 1748 return cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_HUGETLB_ACCOUNTING; 1749 } 1750 #else /* CONFIG_HUGETLB_PAGE */ 1751 static bool memcg_accounts_hugetlb(void) 1752 { 1753 return false; 1754 } 1755 #endif /* CONFIG_HUGETLB_PAGE */ 1756 1757 static void memcg_stat_format(struct mem_cgroup *memcg, struct seq_buf *s) 1758 { 1759 int i; 1760 1761 /* 1762 * Provide statistics on the state of the memory subsystem as 1763 * well as cumulative event counters that show past behavior. 1764 * 1765 * This list is ordered following a combination of these gradients: 1766 * 1) generic big picture -> specifics and details 1767 * 2) reflecting userspace activity -> reflecting kernel heuristics 1768 * 1769 * Current memory state: 1770 */ 1771 mem_cgroup_flush_stats(memcg); 1772 1773 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) { 1774 u64 size; 1775 1776 #ifdef CONFIG_HUGETLB_PAGE 1777 if (unlikely(memory_stats[i].idx == NR_HUGETLB) && 1778 !memcg_accounts_hugetlb()) 1779 continue; 1780 #endif 1781 size = memcg_page_state_output(memcg, memory_stats[i].idx); 1782 seq_buf_printf(s, "%s %llu\n", memory_stats[i].name, size); 1783 1784 if (unlikely(memory_stats[i].idx == NR_SLAB_UNRECLAIMABLE_B)) { 1785 size += memcg_page_state_output(memcg, 1786 NR_SLAB_RECLAIMABLE_B); 1787 seq_buf_printf(s, "slab %llu\n", size); 1788 } 1789 } 1790 1791 /* Accumulated memory events */ 1792 seq_buf_printf(s, "pgscan %lu\n", 1793 memcg_page_state(memcg, PGSCAN_KSWAPD) + 1794 memcg_page_state(memcg, PGSCAN_DIRECT) + 1795 memcg_page_state(memcg, PGSCAN_PROACTIVE) + 1796 memcg_page_state(memcg, PGSCAN_KHUGEPAGED)); 1797 seq_buf_printf(s, "pgsteal %lu\n", 1798 memcg_page_state(memcg, PGSTEAL_KSWAPD) + 1799 memcg_page_state(memcg, PGSTEAL_DIRECT) + 1800 memcg_page_state(memcg, PGSTEAL_PROACTIVE) + 1801 memcg_page_state(memcg, PGSTEAL_KHUGEPAGED)); 1802 1803 for (i = 0; i < ARRAY_SIZE(memcg_vm_event_stat); i++) { 1804 #ifdef CONFIG_MEMCG_V1 1805 if (memcg_vm_event_stat[i] == PGPGIN || 1806 memcg_vm_event_stat[i] == PGPGOUT) 1807 continue; 1808 #endif 1809 seq_buf_printf(s, "%s %lu\n", 1810 vm_event_name(memcg_vm_event_stat[i]), 1811 memcg_events(memcg, memcg_vm_event_stat[i])); 1812 } 1813 } 1814 1815 static void memory_stat_format(struct mem_cgroup *memcg, struct seq_buf *s) 1816 { 1817 if (cgroup_subsys_on_dfl(memory_cgrp_subsys)) 1818 memcg_stat_format(memcg, s); 1819 else 1820 memcg1_stat_format(memcg, s); 1821 if (seq_buf_has_overflowed(s)) 1822 pr_warn("%s: Warning, stat buffer overflow, please report\n", __func__); 1823 } 1824 1825 /** 1826 * mem_cgroup_print_oom_context: Print OOM information relevant to 1827 * memory controller. 1828 * @memcg: The memory cgroup that went over limit 1829 * @p: Task that is going to be killed 1830 * 1831 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is 1832 * enabled 1833 */ 1834 void mem_cgroup_print_oom_context(const struct mem_cgroup *memcg, 1835 struct task_struct *p) 1836 { 1837 rcu_read_lock(); 1838 1839 if (memcg) { 1840 pr_cont(",oom_memcg="); 1841 pr_cont_cgroup_path(memcg->css.cgroup); 1842 } else 1843 pr_cont(",global_oom"); 1844 if (p) { 1845 pr_cont(",task_memcg="); 1846 pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id)); 1847 } 1848 rcu_read_unlock(); 1849 } 1850 1851 /** 1852 * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to 1853 * memory controller. 1854 * @memcg: The memory cgroup that went over limit 1855 */ 1856 void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg) 1857 { 1858 /* Use static buffer, for the caller is holding oom_lock. */ 1859 static char buf[SEQ_BUF_SIZE]; 1860 struct seq_buf s; 1861 unsigned long memory_failcnt; 1862 1863 lockdep_assert_held(&oom_lock); 1864 1865 if (cgroup_subsys_on_dfl(memory_cgrp_subsys)) 1866 memory_failcnt = atomic_long_read(&memcg->memory_events[MEMCG_MAX]); 1867 else 1868 memory_failcnt = memcg->memory.failcnt; 1869 1870 pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n", 1871 K((u64)page_counter_read(&memcg->memory)), 1872 K((u64)READ_ONCE(memcg->memory.max)), memory_failcnt); 1873 if (cgroup_subsys_on_dfl(memory_cgrp_subsys)) 1874 pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n", 1875 K((u64)page_counter_read(&memcg->swap)), 1876 K((u64)READ_ONCE(memcg->swap.max)), 1877 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX])); 1878 #ifdef CONFIG_MEMCG_V1 1879 else { 1880 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n", 1881 K((u64)page_counter_read(&memcg->memsw)), 1882 K((u64)memcg->memsw.max), memcg->memsw.failcnt); 1883 pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n", 1884 K((u64)page_counter_read(&memcg->kmem)), 1885 K((u64)memcg->kmem.max), memcg->kmem.failcnt); 1886 } 1887 #endif 1888 1889 pr_info("Memory cgroup stats for "); 1890 pr_cont_cgroup_path(memcg->css.cgroup); 1891 pr_cont(":"); 1892 seq_buf_init(&s, buf, SEQ_BUF_SIZE); 1893 memory_stat_format(memcg, &s); 1894 seq_buf_do_printk(&s, KERN_INFO); 1895 } 1896 1897 /* 1898 * Return the memory (and swap, if configured) limit for a memcg. 1899 */ 1900 unsigned long mem_cgroup_get_max(const struct mem_cgroup *memcg) 1901 { 1902 unsigned long max = READ_ONCE(memcg->memory.max); 1903 1904 if (do_memsw_account()) { 1905 if (mem_cgroup_swappiness(memcg)) { 1906 /* Calculate swap excess capacity from memsw limit */ 1907 unsigned long swap = READ_ONCE(memcg->memsw.max) - max; 1908 1909 max += min(swap, (unsigned long)total_swap_pages); 1910 } 1911 } else { 1912 if (mem_cgroup_swappiness(memcg)) 1913 max += min(READ_ONCE(memcg->swap.max), 1914 (unsigned long)total_swap_pages); 1915 } 1916 return max; 1917 } 1918 1919 void __memcg_memory_event(struct mem_cgroup *memcg, 1920 enum memcg_memory_event event, bool allow_spinning) 1921 { 1922 bool swap_event = event == MEMCG_SWAP_HIGH || event == MEMCG_SWAP_MAX || 1923 event == MEMCG_SWAP_FAIL; 1924 1925 /* For now only MEMCG_MAX can happen with !allow_spinning context. */ 1926 VM_WARN_ON_ONCE(!allow_spinning && event != MEMCG_MAX); 1927 1928 atomic_long_inc(&memcg->memory_events_local[event]); 1929 if (!swap_event && allow_spinning) 1930 cgroup_file_notify(&memcg->events_local_file); 1931 1932 do { 1933 atomic_long_inc(&memcg->memory_events[event]); 1934 if (allow_spinning) { 1935 if (swap_event) 1936 cgroup_file_notify(&memcg->swap_events_file); 1937 else 1938 cgroup_file_notify(&memcg->events_file); 1939 } 1940 1941 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) 1942 break; 1943 if (cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_LOCAL_EVENTS) 1944 break; 1945 } while ((memcg = parent_mem_cgroup(memcg)) && 1946 !mem_cgroup_is_root(memcg)); 1947 } 1948 EXPORT_SYMBOL_GPL(__memcg_memory_event); 1949 1950 static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask, 1951 int order) 1952 { 1953 struct oom_control oc = { 1954 .zonelist = NULL, 1955 .nodemask = NULL, 1956 .memcg = memcg, 1957 .gfp_mask = gfp_mask, 1958 .order = order, 1959 }; 1960 bool ret = true; 1961 1962 if (mutex_lock_killable(&oom_lock)) 1963 return true; 1964 1965 if (mem_cgroup_margin(memcg) >= (1 << order)) 1966 goto unlock; 1967 1968 /* 1969 * A few threads which were not waiting at mutex_lock_killable() can 1970 * fail to bail out. Therefore, check again after holding oom_lock. 1971 */ 1972 ret = out_of_memory(&oc); 1973 1974 unlock: 1975 mutex_unlock(&oom_lock); 1976 return ret; 1977 } 1978 1979 /* 1980 * Returns true if successfully killed one or more processes. Though in some 1981 * corner cases it can return true even without killing any process. 1982 */ 1983 static bool mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order) 1984 { 1985 bool locked, ret; 1986 1987 if (order > PAGE_ALLOC_COSTLY_ORDER) 1988 return false; 1989 1990 memcg_memory_event(memcg, MEMCG_OOM); 1991 1992 if (!memcg1_oom_prepare(memcg, &locked)) 1993 return false; 1994 1995 ret = mem_cgroup_out_of_memory(memcg, mask, order); 1996 1997 memcg1_oom_finish(memcg, locked); 1998 1999 return ret; 2000 } 2001 2002 /** 2003 * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM 2004 * @victim: task to be killed by the OOM killer 2005 * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM 2006 * 2007 * Returns a pointer to a memory cgroup, which has to be cleaned up 2008 * by killing all belonging OOM-killable tasks. 2009 * 2010 * Caller has to call mem_cgroup_put() on the returned non-NULL memcg. 2011 */ 2012 struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim, 2013 struct mem_cgroup *oom_domain) 2014 { 2015 struct mem_cgroup *oom_group = NULL; 2016 struct mem_cgroup *memcg; 2017 2018 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) 2019 return NULL; 2020 2021 if (!oom_domain) 2022 oom_domain = root_mem_cgroup; 2023 2024 rcu_read_lock(); 2025 2026 memcg = mem_cgroup_from_task(victim); 2027 if (mem_cgroup_is_root(memcg)) 2028 goto out; 2029 2030 /* 2031 * If the victim task has been asynchronously moved to a different 2032 * memory cgroup, we might end up killing tasks outside oom_domain. 2033 * In this case it's better to ignore memory.group.oom. 2034 */ 2035 if (unlikely(!mem_cgroup_is_descendant(memcg, oom_domain))) 2036 goto out; 2037 2038 /* 2039 * Traverse the memory cgroup hierarchy from the victim task's 2040 * cgroup up to the OOMing cgroup (or root) to find the 2041 * highest-level memory cgroup with oom.group set. 2042 */ 2043 for (; memcg; memcg = parent_mem_cgroup(memcg)) { 2044 if (READ_ONCE(memcg->oom_group)) 2045 oom_group = memcg; 2046 2047 if (memcg == oom_domain) 2048 break; 2049 } 2050 2051 if (oom_group) 2052 css_get(&oom_group->css); 2053 out: 2054 rcu_read_unlock(); 2055 2056 return oom_group; 2057 } 2058 2059 void mem_cgroup_print_oom_group(struct mem_cgroup *memcg) 2060 { 2061 pr_info("Tasks in "); 2062 pr_cont_cgroup_path(memcg->css.cgroup); 2063 pr_cont(" are going to be killed due to memory.oom.group set\n"); 2064 } 2065 2066 /* 2067 * The value of NR_MEMCG_STOCK is selected to keep the cached memcgs and their 2068 * nr_pages in a single cacheline. This may change in future. 2069 */ 2070 #define NR_MEMCG_STOCK 7 2071 2072 /* 2073 * Watermarks for a charge stock slot, in the spirit of pcp->high and 2074 * pcp->batch: MEMCG_STOCK_HIGH is the high watermark at which a slot is 2075 * trimmed, and it is trimmed down to MEMCG_STOCK_LOW rather than emptied. 2076 */ 2077 #define MEMCG_STOCK_LOW (MEMCG_CHARGE_BATCH / 2) 2078 #define MEMCG_STOCK_HIGH (MEMCG_CHARGE_BATCH) 2079 2080 #define FLUSHING_CACHED_CHARGE 0 2081 struct memcg_stock_pcp { 2082 local_trylock_t lock; 2083 uint8_t nr_pages[NR_MEMCG_STOCK]; 2084 struct mem_cgroup *cached[NR_MEMCG_STOCK]; 2085 2086 struct work_struct work; 2087 unsigned long flags; 2088 uint8_t drain_idx; 2089 }; 2090 2091 static DEFINE_PER_CPU_ALIGNED(struct memcg_stock_pcp, memcg_stock) = { 2092 .lock = INIT_LOCAL_TRYLOCK(lock), 2093 }; 2094 2095 /* 2096 * NR_OBJ_STOCK is sized so the entire hot path of obj_stock_pcp 2097 * (lock, accounting metadata, nr_bytes[] and cached[]) fits within a 2098 * single 64-byte cache line on non-debug 64-bit builds. With 5 slots: 2099 * lock(1) + index(1) + node_id(2) + slab stats(4) + nr_bytes(10) 2100 * + pad(6) + cached(40) == 64 bytes. 2101 * A CPU can thus consume/refill/account against five different objcgs 2102 * (typically per-node variants of the same memcg) while incurring at 2103 * most one cache miss on the stock. 2104 */ 2105 #define NR_OBJ_STOCK 5 2106 struct obj_stock_pcp { 2107 local_trylock_t lock; 2108 int8_t index; 2109 int16_t node_id; 2110 int16_t nr_slab_reclaimable_b; 2111 int16_t nr_slab_unreclaimable_b; 2112 #if PAGE_SHIFT > 16 2113 /* 2114 * On rare archs with 256KiB base page size (hexagon and powerpc 44x) 2115 * keep nr_bytes to unsigned int as uint16_t cannot represent the full 2116 * sub-page remainder. Such archs are not cacheline optimization targets. 2117 */ 2118 unsigned int nr_bytes[NR_OBJ_STOCK]; 2119 #else 2120 uint16_t nr_bytes[NR_OBJ_STOCK]; 2121 #endif 2122 struct obj_cgroup *cached[NR_OBJ_STOCK]; 2123 2124 struct work_struct work; 2125 unsigned long flags; 2126 uint8_t drain_idx; 2127 }; 2128 2129 static DEFINE_PER_CPU_ALIGNED(struct obj_stock_pcp, obj_stock) = { 2130 .lock = INIT_LOCAL_TRYLOCK(lock), 2131 .index = -1, 2132 .node_id = NUMA_NO_NODE, 2133 }; 2134 2135 static DEFINE_MUTEX(percpu_charge_mutex); 2136 2137 static void drain_obj_stock_slot(struct obj_stock_pcp *stock, int i); 2138 static void drain_obj_stock(struct obj_stock_pcp *stock); 2139 static bool obj_stock_flush_required(struct obj_stock_pcp *stock, 2140 struct mem_cgroup *root_memcg); 2141 2142 /** 2143 * consume_stock: Try to consume stocked charge on this cpu. 2144 * @memcg: memcg to consume from. 2145 * @nr_pages: how many pages to charge. 2146 * 2147 * Consume the cached charge if enough nr_pages are present otherwise return 2148 * failure. Also return failure for charge request larger than 2149 * MEMCG_CHARGE_BATCH or if the local lock is already taken. 2150 * 2151 * returns true if successful, false otherwise. 2152 */ 2153 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages) 2154 { 2155 struct memcg_stock_pcp *stock; 2156 uint8_t stock_pages; 2157 bool ret = false; 2158 int i; 2159 2160 if (nr_pages > MEMCG_CHARGE_BATCH || 2161 !local_trylock(&memcg_stock.lock)) 2162 return ret; 2163 2164 stock = this_cpu_ptr(&memcg_stock); 2165 2166 for (i = 0; i < NR_MEMCG_STOCK; ++i) { 2167 if (memcg != READ_ONCE(stock->cached[i])) 2168 continue; 2169 2170 stock_pages = READ_ONCE(stock->nr_pages[i]); 2171 if (stock_pages >= nr_pages) { 2172 stock_pages -= nr_pages; 2173 WRITE_ONCE(stock->nr_pages[i], stock_pages); 2174 if (!stock_pages) { 2175 WRITE_ONCE(stock->cached[i], NULL); 2176 css_put(&memcg->css); 2177 } 2178 ret = true; 2179 } 2180 break; 2181 } 2182 2183 local_unlock(&memcg_stock.lock); 2184 2185 return ret; 2186 } 2187 2188 static void memcg_uncharge(struct mem_cgroup *memcg, unsigned int nr_pages) 2189 { 2190 page_counter_uncharge(&memcg->memory, nr_pages); 2191 if (do_memsw_account()) 2192 page_counter_uncharge(&memcg->memsw, nr_pages); 2193 } 2194 2195 /* 2196 * Returns stocks cached in percpu and reset cached information. 2197 */ 2198 static void drain_stock(struct memcg_stock_pcp *stock, int i) 2199 { 2200 struct mem_cgroup *old = READ_ONCE(stock->cached[i]); 2201 uint8_t stock_pages; 2202 2203 if (!old) 2204 return; 2205 2206 stock_pages = READ_ONCE(stock->nr_pages[i]); 2207 if (stock_pages) { 2208 memcg_uncharge(old, stock_pages); 2209 WRITE_ONCE(stock->nr_pages[i], 0); 2210 } 2211 2212 WRITE_ONCE(stock->cached[i], NULL); 2213 css_put(&old->css); 2214 } 2215 2216 static void drain_stock_fully(struct memcg_stock_pcp *stock) 2217 { 2218 int i; 2219 2220 for (i = 0; i < NR_MEMCG_STOCK; ++i) 2221 drain_stock(stock, i); 2222 } 2223 2224 static void drain_local_memcg_stock(struct work_struct *dummy) 2225 { 2226 struct memcg_stock_pcp *stock; 2227 2228 if (WARN_ONCE(!in_task(), "drain in non-task context")) 2229 return; 2230 2231 local_lock(&memcg_stock.lock); 2232 2233 stock = this_cpu_ptr(&memcg_stock); 2234 drain_stock_fully(stock); 2235 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags); 2236 2237 local_unlock(&memcg_stock.lock); 2238 } 2239 2240 static void drain_local_obj_stock(struct work_struct *dummy) 2241 { 2242 struct obj_stock_pcp *stock; 2243 2244 if (WARN_ONCE(!in_task(), "drain in non-task context")) 2245 return; 2246 2247 local_lock(&obj_stock.lock); 2248 2249 stock = this_cpu_ptr(&obj_stock); 2250 drain_obj_stock(stock); 2251 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags); 2252 2253 local_unlock(&obj_stock.lock); 2254 } 2255 2256 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages) 2257 { 2258 struct memcg_stock_pcp *stock; 2259 struct mem_cgroup *cached; 2260 unsigned int stock_pages; 2261 bool success = false; 2262 int empty_slot = -1; 2263 int i; 2264 2265 /* 2266 * nr_pages[] is a uint8_t and a slot's count is capped at 2267 * MEMCG_STOCK_HIGH. Raising MEMCG_CHARGE_BATCH beyond 127 would need 2268 * more careful handling of nr_pages[] in struct memcg_stock_pcp. 2269 */ 2270 BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S8_MAX); 2271 BUILD_BUG_ON(MEMCG_STOCK_HIGH > U8_MAX); 2272 2273 VM_WARN_ON_ONCE(mem_cgroup_is_root(memcg)); 2274 2275 if (nr_pages > MEMCG_CHARGE_BATCH || 2276 !local_trylock(&memcg_stock.lock)) { 2277 /* 2278 * In case of larger than batch refill or unlikely failure to 2279 * lock the percpu memcg_stock.lock, uncharge memcg directly. 2280 */ 2281 memcg_uncharge(memcg, nr_pages); 2282 return; 2283 } 2284 2285 stock = this_cpu_ptr(&memcg_stock); 2286 for (i = 0; i < NR_MEMCG_STOCK; ++i) { 2287 cached = READ_ONCE(stock->cached[i]); 2288 if (!cached && empty_slot == -1) 2289 empty_slot = i; 2290 if (memcg == READ_ONCE(stock->cached[i])) { 2291 stock_pages = READ_ONCE(stock->nr_pages[i]) + nr_pages; 2292 if (stock_pages > MEMCG_STOCK_HIGH) { 2293 memcg_uncharge(memcg, 2294 stock_pages - MEMCG_STOCK_LOW); 2295 stock_pages = MEMCG_STOCK_LOW; 2296 } 2297 WRITE_ONCE(stock->nr_pages[i], stock_pages); 2298 success = true; 2299 break; 2300 } 2301 } 2302 2303 if (!success) { 2304 i = empty_slot; 2305 if (i == -1) { 2306 i = stock->drain_idx++; 2307 if (stock->drain_idx == NR_MEMCG_STOCK) 2308 stock->drain_idx = 0; 2309 drain_stock(stock, i); 2310 } 2311 css_get(&memcg->css); 2312 WRITE_ONCE(stock->cached[i], memcg); 2313 WRITE_ONCE(stock->nr_pages[i], nr_pages); 2314 } 2315 2316 local_unlock(&memcg_stock.lock); 2317 } 2318 2319 static bool is_memcg_drain_needed(struct memcg_stock_pcp *stock, 2320 struct mem_cgroup *root_memcg) 2321 { 2322 struct mem_cgroup *memcg; 2323 bool flush = false; 2324 int i; 2325 2326 rcu_read_lock(); 2327 for (i = 0; i < NR_MEMCG_STOCK; ++i) { 2328 memcg = READ_ONCE(stock->cached[i]); 2329 if (!memcg) 2330 continue; 2331 2332 if (READ_ONCE(stock->nr_pages[i]) && 2333 mem_cgroup_is_descendant(memcg, root_memcg)) { 2334 flush = true; 2335 break; 2336 } 2337 } 2338 rcu_read_unlock(); 2339 return flush; 2340 } 2341 2342 static bool schedule_drain_work(int cpu, struct work_struct *work) 2343 { 2344 /* 2345 * Protect housekeeping cpumask read and work enqueue together 2346 * in the same RCU critical section so that later cpuset isolated 2347 * partition update only need to wait for an RCU GP and flush the 2348 * pending work on newly isolated CPUs. 2349 */ 2350 guard(rcu)(); 2351 if (cpu_is_isolated(cpu)) 2352 return false; 2353 2354 queue_work_on(cpu, memcg_wq, work); 2355 return true; 2356 } 2357 2358 /* 2359 * Drains all per-CPU charge caches for given root_memcg resp. subtree 2360 * of the hierarchy under it. 2361 */ 2362 void drain_all_stock(struct mem_cgroup *root_memcg) 2363 { 2364 int cpu, curcpu; 2365 2366 /* If someone's already draining, avoid adding running more workers. */ 2367 if (!mutex_trylock(&percpu_charge_mutex)) 2368 return; 2369 /* 2370 * Notify other cpus that system-wide "drain" is running 2371 * We do not care about races with the cpu hotplug because cpu down 2372 * as well as workers from this path always operate on the local 2373 * per-cpu data. CPU up doesn't touch memcg_stock at all. 2374 */ 2375 migrate_disable(); 2376 curcpu = smp_processor_id(); 2377 for_each_online_cpu(cpu) { 2378 struct memcg_stock_pcp *memcg_st = &per_cpu(memcg_stock, cpu); 2379 struct obj_stock_pcp *obj_st = &per_cpu(obj_stock, cpu); 2380 2381 if (!test_bit(FLUSHING_CACHED_CHARGE, &memcg_st->flags) && 2382 is_memcg_drain_needed(memcg_st, root_memcg) && 2383 !test_and_set_bit(FLUSHING_CACHED_CHARGE, 2384 &memcg_st->flags)) { 2385 if (cpu == curcpu) 2386 drain_local_memcg_stock(&memcg_st->work); 2387 else if (!schedule_drain_work(cpu, &memcg_st->work)) 2388 clear_bit(FLUSHING_CACHED_CHARGE, 2389 &memcg_st->flags); 2390 } 2391 2392 if (!test_bit(FLUSHING_CACHED_CHARGE, &obj_st->flags) && 2393 obj_stock_flush_required(obj_st, root_memcg) && 2394 !test_and_set_bit(FLUSHING_CACHED_CHARGE, 2395 &obj_st->flags)) { 2396 if (cpu == curcpu) 2397 drain_local_obj_stock(&obj_st->work); 2398 else if (!schedule_drain_work(cpu, &obj_st->work)) 2399 clear_bit(FLUSHING_CACHED_CHARGE, 2400 &obj_st->flags); 2401 } 2402 } 2403 migrate_enable(); 2404 mutex_unlock(&percpu_charge_mutex); 2405 } 2406 2407 static int memcg_hotplug_cpu_dead(unsigned int cpu) 2408 { 2409 struct memcg_stock_pcp *memcg_st = &per_cpu(memcg_stock, cpu); 2410 struct obj_stock_pcp *obj_st = &per_cpu(obj_stock, cpu); 2411 2412 /* no need for the local lock */ 2413 drain_obj_stock(obj_st); 2414 drain_stock_fully(memcg_st); 2415 2416 /* 2417 * A drain work queued before the CPU went away is executed by an 2418 * unbound worker on some other CPU and clears that CPU's flag, so 2419 * clear the flags here to make these stocks drainable again once 2420 * the CPU comes back online. 2421 */ 2422 clear_bit(FLUSHING_CACHED_CHARGE, &memcg_st->flags); 2423 clear_bit(FLUSHING_CACHED_CHARGE, &obj_st->flags); 2424 2425 return 0; 2426 } 2427 2428 static unsigned long reclaim_high(struct mem_cgroup *memcg, 2429 unsigned int nr_pages, 2430 gfp_t gfp_mask) 2431 { 2432 unsigned long nr_reclaimed = 0; 2433 2434 do { 2435 unsigned long pflags; 2436 2437 if (page_counter_read(&memcg->memory) <= 2438 READ_ONCE(memcg->memory.high)) 2439 continue; 2440 2441 memcg_memory_event(memcg, MEMCG_HIGH); 2442 2443 psi_memstall_enter(&pflags); 2444 nr_reclaimed += try_to_free_mem_cgroup_pages(memcg, nr_pages, 2445 gfp_mask, 2446 MEMCG_RECLAIM_MAY_SWAP, 2447 NULL); 2448 psi_memstall_leave(&pflags); 2449 } while ((memcg = parent_mem_cgroup(memcg)) && 2450 !mem_cgroup_is_root(memcg)); 2451 2452 return nr_reclaimed; 2453 } 2454 2455 static void high_work_func(struct work_struct *work) 2456 { 2457 struct mem_cgroup *memcg; 2458 2459 memcg = container_of(work, struct mem_cgroup, high_work); 2460 if (!css_tryget_online(&memcg->css)) 2461 return; 2462 reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL); 2463 css_put(&memcg->css); 2464 } 2465 2466 static void high_irq_work_func(struct irq_work *work) 2467 { 2468 schedule_work(&container_of(work, struct mem_cgroup, high_irq_work)->high_work); 2469 } 2470 2471 /* 2472 * Clamp the maximum sleep time per allocation batch to 2 seconds. This is 2473 * enough to still cause a significant slowdown in most cases, while still 2474 * allowing diagnostics and tracing to proceed without becoming stuck. 2475 */ 2476 #define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ) 2477 2478 /* 2479 * When calculating the delay, we use these either side of the exponentiation to 2480 * maintain precision and scale to a reasonable number of jiffies (see the table 2481 * below. 2482 * 2483 * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the 2484 * overage ratio to a delay. 2485 * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down the 2486 * proposed penalty in order to reduce to a reasonable number of jiffies, and 2487 * to produce a reasonable delay curve. 2488 * 2489 * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a 2490 * reasonable delay curve compared to precision-adjusted overage, not 2491 * penalising heavily at first, but still making sure that growth beyond the 2492 * limit penalises misbehaviour cgroups by slowing them down exponentially. For 2493 * example, with a high of 100 megabytes: 2494 * 2495 * +-------+------------------------+ 2496 * | usage | time to allocate in ms | 2497 * +-------+------------------------+ 2498 * | 100M | 0 | 2499 * | 101M | 6 | 2500 * | 102M | 25 | 2501 * | 103M | 57 | 2502 * | 104M | 102 | 2503 * | 105M | 159 | 2504 * | 106M | 230 | 2505 * | 107M | 313 | 2506 * | 108M | 409 | 2507 * | 109M | 518 | 2508 * | 110M | 639 | 2509 * | 111M | 774 | 2510 * | 112M | 921 | 2511 * | 113M | 1081 | 2512 * | 114M | 1254 | 2513 * | 115M | 1439 | 2514 * | 116M | 1638 | 2515 * | 117M | 1849 | 2516 * | 118M | 2000 | 2517 * | 119M | 2000 | 2518 * | 120M | 2000 | 2519 * +-------+------------------------+ 2520 */ 2521 #define MEMCG_DELAY_PRECISION_SHIFT 20 2522 #define MEMCG_DELAY_SCALING_SHIFT 14 2523 2524 static u64 calculate_overage(unsigned long usage, unsigned long high) 2525 { 2526 u64 overage; 2527 2528 if (usage <= high) 2529 return 0; 2530 2531 /* 2532 * Prevent division by 0 in overage calculation by acting as if 2533 * it was a threshold of 1 page 2534 */ 2535 high = max(high, 1UL); 2536 2537 overage = usage - high; 2538 overage <<= MEMCG_DELAY_PRECISION_SHIFT; 2539 return div64_u64(overage, high); 2540 } 2541 2542 static u64 mem_find_max_overage(struct mem_cgroup *memcg) 2543 { 2544 u64 overage, max_overage = 0; 2545 2546 do { 2547 overage = calculate_overage(page_counter_read(&memcg->memory), 2548 READ_ONCE(memcg->memory.high)); 2549 max_overage = max(overage, max_overage); 2550 } while ((memcg = parent_mem_cgroup(memcg)) && 2551 !mem_cgroup_is_root(memcg)); 2552 2553 return max_overage; 2554 } 2555 2556 static u64 swap_find_max_overage(struct mem_cgroup *memcg) 2557 { 2558 u64 overage, max_overage = 0; 2559 2560 do { 2561 overage = calculate_overage(page_counter_read(&memcg->swap), 2562 READ_ONCE(memcg->swap.high)); 2563 if (overage) 2564 memcg_memory_event(memcg, MEMCG_SWAP_HIGH); 2565 max_overage = max(overage, max_overage); 2566 } while ((memcg = parent_mem_cgroup(memcg)) && 2567 !mem_cgroup_is_root(memcg)); 2568 2569 return max_overage; 2570 } 2571 2572 /* 2573 * Get the number of jiffies that we should penalise a mischievous cgroup which 2574 * is exceeding its memory.high by checking both it and its ancestors. 2575 */ 2576 static unsigned long calculate_high_delay(unsigned int nr_pages, 2577 u64 max_overage) 2578 { 2579 unsigned long penalty_jiffies; 2580 2581 if (!max_overage) 2582 return 0; 2583 2584 /* 2585 * We use overage compared to memory.high to calculate the number of 2586 * jiffies to sleep (penalty_jiffies). Ideally this value should be 2587 * fairly lenient on small overages, and increasingly harsh when the 2588 * memcg in question makes it clear that it has no intention of stopping 2589 * its crazy behaviour, so we exponentially increase the delay based on 2590 * overage amount. 2591 */ 2592 penalty_jiffies = max_overage * max_overage * HZ; 2593 penalty_jiffies >>= MEMCG_DELAY_PRECISION_SHIFT; 2594 penalty_jiffies >>= MEMCG_DELAY_SCALING_SHIFT; 2595 2596 /* 2597 * Factor in the task's own contribution to the overage, such that four 2598 * N-sized allocations are throttled approximately the same as one 2599 * 4N-sized allocation. 2600 * 2601 * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or 2602 * larger the current charge patch is than that. 2603 */ 2604 return penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH; 2605 } 2606 2607 /* 2608 * Reclaims memory over the high limit. Called directly from 2609 * try_charge() (context permitting), as well as from the userland 2610 * return path where reclaim is always able to block. 2611 */ 2612 void __mem_cgroup_handle_over_high(gfp_t gfp_mask) 2613 { 2614 unsigned long penalty_jiffies; 2615 unsigned long pflags; 2616 unsigned long nr_reclaimed; 2617 unsigned int nr_pages = current->memcg_nr_pages_over_high; 2618 int nr_retries = MAX_RECLAIM_RETRIES; 2619 struct mem_cgroup *memcg; 2620 bool in_retry = false; 2621 2622 memcg = get_mem_cgroup_from_mm(current->mm); 2623 current->memcg_nr_pages_over_high = 0; 2624 2625 retry_reclaim: 2626 /* 2627 * Bail if the task is already exiting. Unlike memory.max, 2628 * memory.high enforcement isn't as strict, and there is no 2629 * OOM killer involved, which means the excess could already 2630 * be much bigger (and still growing) than it could for 2631 * memory.max; the dying task could get stuck in fruitless 2632 * reclaim for a long time, which isn't desirable. 2633 */ 2634 if (task_is_dying()) 2635 goto out; 2636 2637 /* 2638 * The allocating task should reclaim at least the batch size, but for 2639 * subsequent retries we only want to do what's necessary to prevent oom 2640 * or breaching resource isolation. 2641 * 2642 * This is distinct from memory.max or page allocator behaviour because 2643 * memory.high is currently batched, whereas memory.max and the page 2644 * allocator run every time an allocation is made. 2645 */ 2646 nr_reclaimed = reclaim_high(memcg, 2647 in_retry ? SWAP_CLUSTER_MAX : nr_pages, 2648 gfp_mask); 2649 2650 /* 2651 * memory.high is breached and reclaim is unable to keep up. Throttle 2652 * allocators proactively to slow down excessive growth. 2653 */ 2654 penalty_jiffies = calculate_high_delay(nr_pages, 2655 mem_find_max_overage(memcg)); 2656 2657 penalty_jiffies += calculate_high_delay(nr_pages, 2658 swap_find_max_overage(memcg)); 2659 2660 /* 2661 * Clamp the max delay per usermode return so as to still keep the 2662 * application moving forwards and also permit diagnostics, albeit 2663 * extremely slowly. 2664 */ 2665 penalty_jiffies = min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES); 2666 2667 /* 2668 * Don't sleep if the amount of jiffies this memcg owes us is so low 2669 * that it's not even worth doing, in an attempt to be nice to those who 2670 * go only a small amount over their memory.high value and maybe haven't 2671 * been aggressively reclaimed enough yet. 2672 */ 2673 if (penalty_jiffies <= HZ / 100) 2674 goto out; 2675 2676 /* 2677 * If reclaim is making forward progress but we're still over 2678 * memory.high, we want to encourage that rather than doing allocator 2679 * throttling. 2680 */ 2681 if (nr_reclaimed || nr_retries--) { 2682 in_retry = true; 2683 goto retry_reclaim; 2684 } 2685 2686 /* 2687 * Reclaim didn't manage to push usage below the limit, slow 2688 * this allocating task down. 2689 * 2690 * If we exit early, we're guaranteed to die (since 2691 * schedule_timeout_killable sets TASK_KILLABLE). This means we don't 2692 * need to account for any ill-begotten jiffies to pay them off later. 2693 */ 2694 psi_memstall_enter(&pflags); 2695 schedule_timeout_killable(penalty_jiffies); 2696 psi_memstall_leave(&pflags); 2697 2698 out: 2699 css_put(&memcg->css); 2700 } 2701 2702 static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask, 2703 unsigned int nr_pages) 2704 { 2705 unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages); 2706 int nr_retries = MAX_RECLAIM_RETRIES; 2707 struct mem_cgroup *mem_over_limit; 2708 struct page_counter *counter; 2709 unsigned long nr_reclaimed; 2710 bool passed_oom = false; 2711 unsigned int reclaim_options; 2712 bool drained = false; 2713 bool raised_max_event = false; 2714 unsigned long pflags; 2715 bool allow_spinning = gfpflags_allow_spinning(gfp_mask); 2716 int ret = 0; 2717 2718 retry: 2719 if (consume_stock(memcg, nr_pages)) 2720 return ret; 2721 2722 if (!allow_spinning) 2723 /* Avoid the refill and flush of the older stock */ 2724 batch = nr_pages; 2725 2726 reclaim_options = MEMCG_RECLAIM_MAY_SWAP; 2727 if (!do_memsw_account() || 2728 page_counter_try_charge(&memcg->memsw, batch, &counter)) { 2729 if (page_counter_try_charge(&memcg->memory, batch, &counter)) 2730 goto done_restock; 2731 if (do_memsw_account()) 2732 page_counter_uncharge(&memcg->memsw, batch); 2733 mem_over_limit = mem_cgroup_from_counter(counter, memory); 2734 } else { 2735 mem_over_limit = mem_cgroup_from_counter(counter, memsw); 2736 reclaim_options &= ~MEMCG_RECLAIM_MAY_SWAP; 2737 } 2738 2739 if (batch > nr_pages) { 2740 batch = nr_pages; 2741 goto retry; 2742 } 2743 2744 /* 2745 * Prevent unbounded recursion when reclaim operations need to 2746 * allocate memory. This might exceed the limits temporarily, 2747 * but we prefer facilitating memory reclaim and getting back 2748 * under the limit over triggering OOM kills in these cases. 2749 */ 2750 if (unlikely(current->flags & PF_MEMALLOC)) 2751 goto force; 2752 2753 if (unlikely(task_in_memcg_oom(current))) 2754 goto nomem; 2755 2756 if (!gfpflags_allow_blocking(gfp_mask)) 2757 goto nomem; 2758 2759 /* 2760 * OOM victim still needs to charge memory to exit. OOM reaper should 2761 * help but it might fail on mmap_lock contention. If the victim is a 2762 * large thread group then all exiting threads might compete on oom_lock 2763 * just to learn that there is nothing really killable anymore. Bail 2764 * out early and fail the charge to expedite their exit. They are 2765 * considered fully reclaimed by the oom reaper and they shouldn't 2766 * contribute further charges. 2767 */ 2768 if (tsk_is_oom_victim(current) && 2769 mm_flags_test(MMF_OOM_SKIP, current->signal->oom_mm)) 2770 goto nomem; 2771 2772 __memcg_memory_event(mem_over_limit, MEMCG_MAX, allow_spinning); 2773 raised_max_event = true; 2774 2775 psi_memstall_enter(&pflags); 2776 nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages, 2777 gfp_mask, reclaim_options, NULL); 2778 psi_memstall_leave(&pflags); 2779 2780 if (mem_cgroup_margin(mem_over_limit) >= nr_pages) 2781 goto retry; 2782 2783 if (!drained) { 2784 drain_all_stock(mem_over_limit); 2785 drained = true; 2786 goto retry; 2787 } 2788 2789 if (gfp_mask & __GFP_NORETRY) 2790 goto nomem; 2791 /* 2792 * Even though the limit is exceeded at this point, reclaim 2793 * may have been able to free some pages. Retry the charge 2794 * before killing the task. 2795 * 2796 * Only for regular pages, though: huge pages are rather 2797 * unlikely to succeed so close to the limit, and we fall back 2798 * to regular pages anyway in case of failure. 2799 */ 2800 if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER)) 2801 goto retry; 2802 2803 if (nr_retries--) 2804 goto retry; 2805 2806 if (gfp_mask & __GFP_RETRY_MAYFAIL) 2807 goto nomem; 2808 2809 /* Avoid endless loop for tasks bypassed by the oom killer */ 2810 if (passed_oom && task_is_dying()) 2811 goto nomem; 2812 2813 /* 2814 * keep retrying as long as the memcg oom killer is able to make 2815 * a forward progress or bypass the charge if the oom killer 2816 * couldn't make any progress. 2817 */ 2818 if (mem_cgroup_oom(mem_over_limit, gfp_mask, 2819 get_order(nr_pages * PAGE_SIZE))) { 2820 passed_oom = true; 2821 nr_retries = MAX_RECLAIM_RETRIES; 2822 goto retry; 2823 } 2824 nomem: 2825 /* 2826 * Memcg doesn't have a dedicated reserve for atomic 2827 * allocations. But like the global atomic pool, we need to 2828 * put the burden of reclaim on regular allocation requests 2829 * and let these go through as privileged allocations. 2830 */ 2831 if (!(gfp_mask & (__GFP_NOFAIL | __GFP_HIGH))) { 2832 ret = -ENOMEM; 2833 goto out; 2834 } 2835 force: 2836 /* 2837 * The allocation either can't fail or will lead to more memory 2838 * being freed very soon. Allow memory usage go over the limit 2839 * temporarily by force charging it. 2840 */ 2841 page_counter_charge(&memcg->memory, nr_pages); 2842 if (do_memsw_account()) 2843 page_counter_charge(&memcg->memsw, nr_pages); 2844 2845 out: 2846 /* 2847 * Don't forget to raise a MEMCG_MAX event for forced or rejected 2848 * requests. 2849 */ 2850 if (!raised_max_event) 2851 __memcg_memory_event(mem_over_limit, MEMCG_MAX, allow_spinning); 2852 2853 return ret; 2854 2855 done_restock: 2856 if (batch > nr_pages) 2857 refill_stock(memcg, batch - nr_pages); 2858 2859 /* 2860 * If the hierarchy is above the normal consumption range, schedule 2861 * reclaim on returning to userland. We can perform reclaim here 2862 * if __GFP_RECLAIM but let's always punt for simplicity and so that 2863 * GFP_KERNEL can consistently be used during reclaim. @memcg is 2864 * not recorded as it most likely matches current's and won't 2865 * change in the meantime. As high limit is checked again before 2866 * reclaim, the cost of mismatch is negligible. 2867 */ 2868 do { 2869 bool mem_high, swap_high; 2870 2871 mem_high = page_counter_read(&memcg->memory) > 2872 READ_ONCE(memcg->memory.high); 2873 swap_high = page_counter_read(&memcg->swap) > 2874 READ_ONCE(memcg->swap.high); 2875 2876 /* Don't bother a random interrupted task */ 2877 if (!in_task()) { 2878 if (mem_high) { 2879 if (allow_spinning) 2880 schedule_work(&memcg->high_work); 2881 else 2882 irq_work_queue(&memcg->high_irq_work); 2883 break; 2884 } 2885 continue; 2886 } 2887 2888 if (mem_high || swap_high) { 2889 /* 2890 * The allocating tasks in this cgroup will need to do 2891 * reclaim or be throttled to prevent further growth 2892 * of the memory or swap footprints. 2893 * 2894 * Target some best-effort fairness between the tasks, 2895 * and distribute reclaim work and delay penalties 2896 * based on how much each task is actually allocating. 2897 */ 2898 current->memcg_nr_pages_over_high += batch; 2899 set_notify_resume(current); 2900 break; 2901 } 2902 } while ((memcg = parent_mem_cgroup(memcg))); 2903 2904 /* 2905 * Reclaim is set up above to be called from the userland 2906 * return path. But also attempt synchronous reclaim to avoid 2907 * excessive overrun while the task is still inside the 2908 * kernel. If this is successful, the return path will see it 2909 * when it rechecks the overage and simply bail out. 2910 */ 2911 if (current->memcg_nr_pages_over_high > MEMCG_CHARGE_BATCH && 2912 !(current->flags & PF_MEMALLOC) && 2913 gfpflags_allow_blocking(gfp_mask)) 2914 __mem_cgroup_handle_over_high(gfp_mask); 2915 return ret; 2916 } 2917 2918 static inline int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask, 2919 unsigned int nr_pages) 2920 { 2921 if (mem_cgroup_is_root(memcg)) 2922 return 0; 2923 2924 return try_charge_memcg(memcg, gfp_mask, nr_pages); 2925 } 2926 2927 static void commit_charge(struct folio *folio, struct obj_cgroup *objcg) 2928 { 2929 VM_BUG_ON_FOLIO(folio_memcg_charged(folio), folio); 2930 /* 2931 * Any of the following ensures folio's objcg stability: 2932 * 2933 * - the page lock 2934 * - LRU isolation 2935 * - exclusive reference 2936 */ 2937 folio->memcg_data = (unsigned long)objcg; 2938 } 2939 2940 #ifdef CONFIG_MEMCG_NMI_SAFETY_REQUIRES_ATOMIC 2941 static inline void account_slab_nmi_safe(struct mem_cgroup *memcg, 2942 struct pglist_data *pgdat, 2943 enum node_stat_item idx, int nr) 2944 { 2945 struct lruvec *lruvec; 2946 2947 if (likely(!in_nmi())) { 2948 lruvec = mem_cgroup_lruvec(memcg, pgdat); 2949 mod_memcg_lruvec_state(lruvec, idx, nr); 2950 } else { 2951 struct mem_cgroup_per_node *pn = memcg->nodeinfo[pgdat->node_id]; 2952 2953 /* preemption is disabled in_nmi(). */ 2954 __css_rstat_updated(&memcg->css, smp_processor_id()); 2955 if (idx == NR_SLAB_RECLAIMABLE_B) 2956 atomic_add(nr, &pn->slab_reclaimable); 2957 else 2958 atomic_add(nr, &pn->slab_unreclaimable); 2959 } 2960 } 2961 #else 2962 static inline void account_slab_nmi_safe(struct mem_cgroup *memcg, 2963 struct pglist_data *pgdat, 2964 enum node_stat_item idx, int nr) 2965 { 2966 struct lruvec *lruvec; 2967 2968 lruvec = mem_cgroup_lruvec(memcg, pgdat); 2969 mod_memcg_lruvec_state(lruvec, idx, nr); 2970 } 2971 #endif 2972 2973 static inline void mod_objcg_mlstate(struct obj_cgroup *objcg, 2974 struct pglist_data *pgdat, 2975 enum node_stat_item idx, int nr) 2976 { 2977 struct mem_cgroup *memcg; 2978 2979 rcu_read_lock(); 2980 memcg = obj_cgroup_memcg(objcg); 2981 account_slab_nmi_safe(memcg, pgdat, idx, nr); 2982 rcu_read_unlock(); 2983 } 2984 2985 static __always_inline 2986 struct mem_cgroup *mem_cgroup_from_obj_slab(struct slab *slab, void *p) 2987 { 2988 /* 2989 * Slab objects are accounted individually, not per-page. 2990 * Memcg membership data for each individual object is saved in 2991 * slab->obj_exts. 2992 */ 2993 unsigned long obj_exts; 2994 struct slabobj_ext *obj_ext; 2995 struct obj_cgroup *objcg; 2996 2997 obj_exts = slab_obj_exts(slab); 2998 if (!obj_exts) 2999 return NULL; 3000 3001 if (!slab_needs_objcg(slab)) 3002 return NULL; 3003 3004 get_slab_obj_exts(obj_exts); 3005 obj_ext = slab_obj_ext(slab->slab_cache, slab, obj_exts, p); 3006 objcg = slab_obj_ext_objcg(slab, obj_ext); 3007 if (objcg) { 3008 put_slab_obj_exts(obj_exts); 3009 return obj_cgroup_memcg(objcg); 3010 } 3011 put_slab_obj_exts(obj_exts); 3012 3013 return NULL; 3014 } 3015 3016 /* 3017 * Returns a pointer to the memory cgroup to which the kernel object is charged. 3018 * It is not suitable for objects allocated using vmalloc(). 3019 * 3020 * A passed kernel object must be a slab object or a generic kernel page. 3021 * 3022 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(), 3023 * cgroup_mutex, etc. 3024 */ 3025 struct mem_cgroup *mem_cgroup_from_virt(void *p) 3026 { 3027 struct slab *slab; 3028 3029 if (mem_cgroup_disabled()) 3030 return NULL; 3031 3032 slab = virt_to_slab(p); 3033 if (slab) 3034 return mem_cgroup_from_obj_slab(slab, p); 3035 return folio_memcg_check(virt_to_folio(p)); 3036 } 3037 3038 static struct obj_cgroup *__get_obj_cgroup_from_memcg(struct mem_cgroup *memcg, 3039 int nid) 3040 { 3041 for (; memcg; memcg = parent_mem_cgroup(memcg)) { 3042 struct obj_cgroup *objcg = rcu_dereference(memcg->nodeinfo[nid]->objcg); 3043 3044 if (likely(objcg && obj_cgroup_tryget(objcg))) 3045 return objcg; 3046 } 3047 3048 return NULL; 3049 } 3050 3051 static inline struct obj_cgroup *get_obj_cgroup_from_memcg(struct mem_cgroup *memcg, 3052 int nid) 3053 { 3054 struct obj_cgroup *objcg; 3055 3056 rcu_read_lock(); 3057 objcg = __get_obj_cgroup_from_memcg(memcg, nid); 3058 rcu_read_unlock(); 3059 3060 return objcg; 3061 } 3062 3063 static struct obj_cgroup *current_objcg_update(void) 3064 { 3065 struct mem_cgroup *memcg; 3066 struct obj_cgroup *old, *objcg = NULL; 3067 3068 do { 3069 /* Atomically drop the update bit. */ 3070 old = xchg(¤t->objcg, NULL); 3071 if (old) { 3072 old = (struct obj_cgroup *) 3073 ((unsigned long)old & ~CURRENT_OBJCG_UPDATE_FLAG); 3074 obj_cgroup_put(old); 3075 3076 old = NULL; 3077 } 3078 3079 /* If new objcg is NULL, no reason for the second atomic update. */ 3080 if (!current->mm || (current->flags & PF_KTHREAD)) 3081 return NULL; 3082 3083 /* 3084 * Release the objcg pointer from the previous iteration, 3085 * if try_cmpxcg() below fails. 3086 */ 3087 if (unlikely(objcg)) { 3088 obj_cgroup_put(objcg); 3089 objcg = NULL; 3090 } 3091 3092 /* 3093 * Obtain the new objcg pointer. The current task can be 3094 * asynchronously moved to another memcg and the previous 3095 * memcg can be offlined. So let's get the memcg pointer 3096 * and try get a reference to objcg under a rcu read lock. 3097 */ 3098 3099 rcu_read_lock(); 3100 memcg = mem_cgroup_from_task(current); 3101 objcg = __get_obj_cgroup_from_memcg(memcg, numa_node_id()); 3102 rcu_read_unlock(); 3103 3104 /* 3105 * Try set up a new objcg pointer atomically. If it 3106 * fails, it means the update flag was set concurrently, so 3107 * the whole procedure should be repeated. 3108 */ 3109 } while (!try_cmpxchg(¤t->objcg, &old, objcg)); 3110 3111 return objcg; 3112 } 3113 3114 __always_inline struct obj_cgroup *current_obj_cgroup(void) 3115 { 3116 struct mem_cgroup *memcg; 3117 struct obj_cgroup *objcg; 3118 int nid = numa_node_id(); 3119 3120 if (IS_ENABLED(CONFIG_MEMCG_NMI_UNSAFE) && in_nmi()) 3121 return NULL; 3122 3123 if (in_task()) { 3124 memcg = current->active_memcg; 3125 if (unlikely(memcg)) 3126 goto from_memcg; 3127 3128 objcg = READ_ONCE(current->objcg); 3129 if (unlikely((unsigned long)objcg & CURRENT_OBJCG_UPDATE_FLAG)) 3130 objcg = current_objcg_update(); 3131 /* 3132 * Objcg reference is kept by the task, so it's safe 3133 * to use the objcg by the current task. 3134 */ 3135 return objcg ? : rcu_dereference_check(root_mem_cgroup->nodeinfo[nid]->objcg, 1); 3136 } 3137 3138 memcg = this_cpu_read(int_active_memcg); 3139 if (unlikely(memcg)) 3140 goto from_memcg; 3141 3142 return rcu_dereference_check(root_mem_cgroup->nodeinfo[nid]->objcg, 1); 3143 3144 from_memcg: 3145 for (; memcg; memcg = parent_mem_cgroup(memcg)) { 3146 /* 3147 * Memcg pointer is protected by scope (see set_active_memcg()) 3148 * and is pinning the corresponding objcg, so objcg can't go 3149 * away and can be used within the scope without any additional 3150 * protection. 3151 */ 3152 objcg = rcu_dereference_check(memcg->nodeinfo[nid]->objcg, 1); 3153 if (likely(objcg)) 3154 return objcg; 3155 } 3156 3157 return rcu_dereference_check(root_mem_cgroup->nodeinfo[nid]->objcg, 1); 3158 } 3159 3160 struct obj_cgroup *get_obj_cgroup_from_folio(const struct folio *folio) 3161 { 3162 struct obj_cgroup *objcg; 3163 3164 objcg = folio_objcg(folio); 3165 if (objcg) 3166 obj_cgroup_get(objcg); 3167 3168 return objcg; 3169 } 3170 3171 #ifdef CONFIG_MEMCG_NMI_SAFETY_REQUIRES_ATOMIC 3172 static inline void account_kmem_nmi_safe(struct mem_cgroup *memcg, int val) 3173 { 3174 if (likely(!in_nmi())) { 3175 mod_memcg_state(memcg, MEMCG_KMEM, val); 3176 } else { 3177 /* preemption is disabled in_nmi(). */ 3178 __css_rstat_updated(&memcg->css, smp_processor_id()); 3179 atomic_add(val, &memcg->kmem_stat); 3180 } 3181 } 3182 #else 3183 static inline void account_kmem_nmi_safe(struct mem_cgroup *memcg, int val) 3184 { 3185 mod_memcg_state(memcg, MEMCG_KMEM, val); 3186 } 3187 #endif 3188 3189 /* 3190 * obj_cgroup_uncharge_pages: uncharge a number of kernel pages from a objcg 3191 * @objcg: object cgroup to uncharge 3192 * @nr_pages: number of pages to uncharge 3193 */ 3194 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg, 3195 unsigned int nr_pages) 3196 { 3197 struct mem_cgroup *memcg; 3198 3199 memcg = get_mem_cgroup_from_objcg(objcg); 3200 3201 account_kmem_nmi_safe(memcg, -nr_pages); 3202 memcg1_account_kmem(memcg, -nr_pages); 3203 if (!mem_cgroup_is_root(memcg)) 3204 refill_stock(memcg, nr_pages); 3205 3206 css_put(&memcg->css); 3207 } 3208 3209 /* 3210 * obj_cgroup_charge_pages: charge a number of kernel pages to a objcg 3211 * @objcg: object cgroup to charge 3212 * @gfp: reclaim mode 3213 * @nr_pages: number of pages to charge 3214 * 3215 * Returns 0 on success, an error code on failure. 3216 */ 3217 static int obj_cgroup_charge_pages(struct obj_cgroup *objcg, gfp_t gfp, 3218 unsigned int nr_pages) 3219 { 3220 struct mem_cgroup *memcg; 3221 int ret; 3222 3223 memcg = get_mem_cgroup_from_objcg(objcg); 3224 3225 ret = try_charge(memcg, gfp, nr_pages); 3226 if (ret) 3227 goto out; 3228 3229 account_kmem_nmi_safe(memcg, nr_pages); 3230 memcg1_account_kmem(memcg, nr_pages); 3231 out: 3232 css_put(&memcg->css); 3233 3234 return ret; 3235 } 3236 3237 static struct obj_cgroup *page_objcg(const struct page *page) 3238 { 3239 unsigned long memcg_data = page->memcg_data; 3240 3241 if (mem_cgroup_disabled() || !memcg_data) 3242 return NULL; 3243 3244 VM_BUG_ON_PAGE((memcg_data & OBJEXTS_FLAGS_MASK) != MEMCG_DATA_KMEM, 3245 page); 3246 return (struct obj_cgroup *)(memcg_data - MEMCG_DATA_KMEM); 3247 } 3248 3249 static void page_set_objcg(struct page *page, const struct obj_cgroup *objcg) 3250 { 3251 page->memcg_data = (unsigned long)objcg | MEMCG_DATA_KMEM; 3252 } 3253 3254 /** 3255 * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup 3256 * @page: page to charge 3257 * @gfp: reclaim mode 3258 * @order: allocation order 3259 * 3260 * Returns 0 on success, an error code on failure. 3261 */ 3262 int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order) 3263 { 3264 struct obj_cgroup *objcg; 3265 int ret = 0; 3266 3267 objcg = current_obj_cgroup(); 3268 if (objcg && !obj_cgroup_is_root(objcg)) { 3269 ret = obj_cgroup_charge_pages(objcg, gfp, 1 << order); 3270 if (!ret) { 3271 obj_cgroup_get(objcg); 3272 page_set_objcg(page, objcg); 3273 return 0; 3274 } 3275 } 3276 return ret; 3277 } 3278 3279 /** 3280 * __memcg_kmem_uncharge_page: uncharge a kmem page 3281 * @page: page to uncharge 3282 * @order: allocation order 3283 */ 3284 void __memcg_kmem_uncharge_page(struct page *page, int order) 3285 { 3286 struct obj_cgroup *objcg = page_objcg(page); 3287 unsigned int nr_pages = 1 << order; 3288 3289 if (!objcg) 3290 return; 3291 3292 obj_cgroup_uncharge_pages(objcg, nr_pages); 3293 page->memcg_data = 0; 3294 obj_cgroup_put(objcg); 3295 } 3296 3297 static struct obj_stock_pcp *trylock_stock(void) 3298 { 3299 if (local_trylock(&obj_stock.lock)) 3300 return this_cpu_ptr(&obj_stock); 3301 3302 return NULL; 3303 } 3304 3305 static void unlock_stock(struct obj_stock_pcp *stock) 3306 { 3307 if (stock) 3308 local_unlock(&obj_stock.lock); 3309 } 3310 3311 /* Call after __refill_obj_stock() so a slot for objcg exists in the stock */ 3312 static void __account_obj_stock(struct obj_cgroup *objcg, 3313 struct obj_stock_pcp *stock, int nr, 3314 struct pglist_data *pgdat, enum node_stat_item idx) 3315 { 3316 int16_t *bytes; 3317 int i; 3318 3319 /* 3320 * Though at the moment MAX_NUMNODES <= 1024 in all archs but let's make 3321 * sure it does not exceed S16_MAX otherwise we need to fix node_id type 3322 * in struct obj_stock_pcp. 3323 */ 3324 BUILD_BUG_ON(MAX_NUMNODES >= S16_MAX); 3325 3326 if (!stock) 3327 goto direct; 3328 3329 for (i = 0; i < NR_OBJ_STOCK; ++i) { 3330 if (READ_ONCE(stock->cached[i]) == objcg) 3331 break; 3332 } 3333 if (i == NR_OBJ_STOCK) 3334 goto direct; 3335 3336 /* 3337 * Save vmstat data in stock and skip vmstat array update unless 3338 * accumulating over a page of vmstat data or when the objcg slot or 3339 * pgdat the stats belong to changes. 3340 */ 3341 if (stock->index < 0) { 3342 stock->index = i; 3343 stock->node_id = pgdat->node_id; 3344 } else if (stock->index != i || stock->node_id != pgdat->node_id) { 3345 struct obj_cgroup *old = READ_ONCE(stock->cached[stock->index]); 3346 struct pglist_data *oldpg = NODE_DATA(stock->node_id); 3347 3348 if (stock->nr_slab_reclaimable_b) { 3349 mod_objcg_mlstate(old, oldpg, NR_SLAB_RECLAIMABLE_B, 3350 stock->nr_slab_reclaimable_b); 3351 stock->nr_slab_reclaimable_b = 0; 3352 } 3353 if (stock->nr_slab_unreclaimable_b) { 3354 mod_objcg_mlstate(old, oldpg, NR_SLAB_UNRECLAIMABLE_B, 3355 stock->nr_slab_unreclaimable_b); 3356 stock->nr_slab_unreclaimable_b = 0; 3357 } 3358 stock->index = i; 3359 stock->node_id = pgdat->node_id; 3360 } 3361 3362 bytes = (idx == NR_SLAB_RECLAIMABLE_B) ? &stock->nr_slab_reclaimable_b 3363 : &stock->nr_slab_unreclaimable_b; 3364 3365 /* 3366 * Fold @nr into the cached value and decide whether to keep it cached 3367 * or flush it directly. Cache the combined value when it fits in the 3368 * int16_t storage and either the cache was empty (so even a value 3369 * above PAGE_SIZE gets a chance to be canceled by a paired delta) or 3370 * the combined value is within the PAGE_SIZE flush threshold. 3371 */ 3372 nr += *bytes; 3373 if (abs(nr) <= S16_MAX && (!*bytes || abs(nr) <= PAGE_SIZE)) { 3374 *bytes = nr; 3375 nr = 0; 3376 } else { 3377 *bytes = 0; 3378 } 3379 direct: 3380 if (nr) 3381 mod_objcg_mlstate(objcg, pgdat, idx, nr); 3382 } 3383 3384 static bool __consume_obj_stock(struct obj_cgroup *objcg, 3385 struct obj_stock_pcp *stock, 3386 unsigned int nr_bytes) 3387 { 3388 int i; 3389 3390 for (i = 0; i < NR_OBJ_STOCK; ++i) { 3391 if (READ_ONCE(stock->cached[i]) != objcg) 3392 continue; 3393 if (stock->nr_bytes[i] >= nr_bytes) { 3394 stock->nr_bytes[i] -= nr_bytes; 3395 return true; 3396 } 3397 return false; 3398 } 3399 3400 return false; 3401 } 3402 3403 static bool consume_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes) 3404 { 3405 struct obj_stock_pcp *stock; 3406 bool ret = false; 3407 3408 stock = trylock_stock(); 3409 if (!stock) 3410 return ret; 3411 3412 ret = __consume_obj_stock(objcg, stock, nr_bytes); 3413 unlock_stock(stock); 3414 3415 return ret; 3416 } 3417 3418 /* Flush the cached slab stats (if any) back to their owning objcg/pgdat. */ 3419 static void drain_obj_stock_stats(struct obj_stock_pcp *stock) 3420 { 3421 struct obj_cgroup *old; 3422 struct pglist_data *oldpg; 3423 3424 if (stock->index < 0) 3425 return; 3426 3427 old = READ_ONCE(stock->cached[stock->index]); 3428 oldpg = NODE_DATA(stock->node_id); 3429 3430 if (stock->nr_slab_reclaimable_b) { 3431 mod_objcg_mlstate(old, oldpg, NR_SLAB_RECLAIMABLE_B, 3432 stock->nr_slab_reclaimable_b); 3433 stock->nr_slab_reclaimable_b = 0; 3434 } 3435 if (stock->nr_slab_unreclaimable_b) { 3436 mod_objcg_mlstate(old, oldpg, NR_SLAB_UNRECLAIMABLE_B, 3437 stock->nr_slab_unreclaimable_b); 3438 stock->nr_slab_unreclaimable_b = 0; 3439 } 3440 stock->index = -1; 3441 stock->node_id = NUMA_NO_NODE; 3442 } 3443 3444 static void drain_obj_stock_slot(struct obj_stock_pcp *stock, int i) 3445 { 3446 struct obj_cgroup *old = READ_ONCE(stock->cached[i]); 3447 3448 if (!old) 3449 return; 3450 3451 if (stock->nr_bytes[i]) { 3452 unsigned int nr_pages = stock->nr_bytes[i] >> PAGE_SHIFT; 3453 unsigned int nr_bytes = stock->nr_bytes[i] & (PAGE_SIZE - 1); 3454 3455 if (nr_pages) { 3456 struct mem_cgroup *memcg; 3457 3458 memcg = get_mem_cgroup_from_objcg(old); 3459 3460 memcg_uncharge_kmem(memcg, nr_pages); 3461 3462 css_put(&memcg->css); 3463 } 3464 3465 /* 3466 * The leftover is flushed to the centralized per-memcg value. 3467 * On the next attempt to refill obj stock it will be moved 3468 * to a per-cpu stock (probably, on an other CPU), see 3469 * refill_obj_stock(). 3470 * 3471 * How often it's flushed is a trade-off between the memory 3472 * limit enforcement accuracy and potential CPU contention, 3473 * so it might be changed in the future. 3474 */ 3475 atomic_add(nr_bytes, &old->nr_charged_bytes); 3476 stock->nr_bytes[i] = 0; 3477 } 3478 3479 /* Flush vmstat data when its owning slot is being drained. */ 3480 if (stock->index == i) 3481 drain_obj_stock_stats(stock); 3482 3483 WRITE_ONCE(stock->cached[i], NULL); 3484 obj_cgroup_put(old); 3485 } 3486 3487 static void drain_obj_stock(struct obj_stock_pcp *stock) 3488 { 3489 int i; 3490 3491 for (i = 0; i < NR_OBJ_STOCK; ++i) 3492 drain_obj_stock_slot(stock, i); 3493 } 3494 3495 static bool obj_stock_flush_required(struct obj_stock_pcp *stock, 3496 struct mem_cgroup *root_memcg) 3497 { 3498 struct obj_cgroup *objcg; 3499 struct mem_cgroup *memcg; 3500 bool flush = false; 3501 int i; 3502 3503 rcu_read_lock(); 3504 for (i = 0; i < NR_OBJ_STOCK; ++i) { 3505 objcg = READ_ONCE(stock->cached[i]); 3506 if (!objcg) 3507 continue; 3508 memcg = obj_cgroup_memcg(objcg); 3509 if (memcg && mem_cgroup_is_descendant(memcg, root_memcg)) { 3510 flush = true; 3511 break; 3512 } 3513 } 3514 rcu_read_unlock(); 3515 3516 return flush; 3517 } 3518 3519 static void __refill_obj_stock(struct obj_cgroup *objcg, 3520 struct obj_stock_pcp *stock, 3521 unsigned int nr_bytes, 3522 bool allow_uncharge) 3523 { 3524 unsigned int nr_pages = 0; 3525 unsigned int stock_nr_bytes; 3526 int i, slot = -1, empty_slot = -1; 3527 3528 if (!stock) { 3529 nr_pages = nr_bytes >> PAGE_SHIFT; 3530 nr_bytes = nr_bytes & (PAGE_SIZE - 1); 3531 atomic_add(nr_bytes, &objcg->nr_charged_bytes); 3532 goto out; 3533 } 3534 3535 for (i = 0; i < NR_OBJ_STOCK; ++i) { 3536 struct obj_cgroup *cached = READ_ONCE(stock->cached[i]); 3537 3538 if (!cached) { 3539 if (empty_slot == -1) 3540 empty_slot = i; 3541 continue; 3542 } 3543 if (cached == objcg) { 3544 slot = i; 3545 break; 3546 } 3547 } 3548 3549 if (slot == -1) { 3550 slot = empty_slot; 3551 if (slot == -1) { 3552 slot = stock->drain_idx++; 3553 if (stock->drain_idx == NR_OBJ_STOCK) 3554 stock->drain_idx = 0; 3555 drain_obj_stock_slot(stock, slot); 3556 } 3557 obj_cgroup_get(objcg); 3558 /* 3559 * Keep the xchg result in the unsigned int local; storing 3560 * it directly into stock->nr_bytes[slot] (uint16_t) would 3561 * silently truncate values >= U16_MAX and bypass the flush 3562 * guard below, leaking page-counter charges. 3563 */ 3564 stock_nr_bytes = atomic_read(&objcg->nr_charged_bytes) 3565 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0; 3566 WRITE_ONCE(stock->cached[slot], objcg); 3567 3568 allow_uncharge = true; /* Allow uncharge when objcg changes */ 3569 } else { 3570 stock_nr_bytes = stock->nr_bytes[slot]; 3571 } 3572 3573 stock_nr_bytes += nr_bytes; 3574 3575 if ((allow_uncharge && (stock_nr_bytes > PAGE_SIZE)) || 3576 stock_nr_bytes > U16_MAX) { 3577 nr_pages = stock_nr_bytes >> PAGE_SHIFT; 3578 stock_nr_bytes &= (PAGE_SIZE - 1); 3579 } 3580 stock->nr_bytes[slot] = stock_nr_bytes; 3581 3582 out: 3583 if (nr_pages) 3584 obj_cgroup_uncharge_pages(objcg, nr_pages); 3585 } 3586 3587 static void refill_obj_stock(struct obj_cgroup *objcg, 3588 unsigned int nr_bytes, 3589 bool allow_uncharge) 3590 { 3591 struct obj_stock_pcp *stock = trylock_stock(); 3592 __refill_obj_stock(objcg, stock, nr_bytes, allow_uncharge); 3593 unlock_stock(stock); 3594 } 3595 3596 static int __obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, 3597 size_t size, size_t *remainder) 3598 { 3599 size_t charge_size; 3600 int ret; 3601 3602 charge_size = PAGE_ALIGN(size); 3603 ret = obj_cgroup_charge_pages(objcg, gfp, charge_size >> PAGE_SHIFT); 3604 if (!ret) 3605 *remainder = charge_size - size; 3606 3607 return ret; 3608 } 3609 3610 int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size) 3611 { 3612 size_t remainder; 3613 int ret; 3614 3615 if (likely(consume_obj_stock(objcg, size))) 3616 return 0; 3617 3618 /* 3619 * In theory, objcg->nr_charged_bytes can have enough 3620 * pre-charged bytes to satisfy the allocation. However, 3621 * flushing objcg->nr_charged_bytes requires two atomic 3622 * operations, and objcg->nr_charged_bytes can't be big. 3623 * The shared objcg->nr_charged_bytes can also become a 3624 * performance bottleneck if all tasks of the same memcg are 3625 * trying to update it. So it's better to ignore it and try 3626 * grab some new pages. The stock's nr_bytes will be flushed to 3627 * objcg->nr_charged_bytes later on when objcg changes. 3628 * 3629 * The stock's nr_bytes may contain enough pre-charged bytes 3630 * to allow one less page from being charged, but we can't rely 3631 * on the pre-charged bytes not being changed outside of 3632 * consume_obj_stock() or refill_obj_stock(). So ignore those 3633 * pre-charged bytes as well when charging pages. To avoid a 3634 * page uncharge right after a page charge, we set the 3635 * allow_uncharge flag to false when calling refill_obj_stock() 3636 * to temporarily allow the pre-charged bytes to exceed the page 3637 * size limit. The maximum reachable value of the pre-charged 3638 * bytes is (sizeof(object) + PAGE_SIZE - 2) if there is no data 3639 * race. 3640 */ 3641 ret = __obj_cgroup_charge(objcg, gfp, size, &remainder); 3642 if (!ret && remainder) 3643 refill_obj_stock(objcg, remainder, false); 3644 3645 return ret; 3646 } 3647 3648 void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size) 3649 { 3650 refill_obj_stock(objcg, size, true); 3651 } 3652 3653 static inline size_t obj_full_size(struct kmem_cache *s) 3654 { 3655 /* 3656 * For each accounted object there is an extra space which is used 3657 * to store obj_cgroup membership. Charge it too. 3658 */ 3659 return s->size + sizeof(struct obj_cgroup *); 3660 } 3661 3662 bool __memcg_slab_post_alloc_hook(struct kmem_cache *s, struct list_lru *lru, 3663 gfp_t flags, unsigned int slab_alloc_flags, 3664 size_t size, void **p) 3665 { 3666 size_t obj_size = obj_full_size(s); 3667 struct obj_cgroup *objcg; 3668 struct slab *slab; 3669 size_t i; 3670 3671 /* 3672 * The obtained objcg pointer is safe to use within the current scope, 3673 * defined by current task or set_active_memcg() pair. 3674 * obj_cgroup_get() is used to get a permanent reference. 3675 */ 3676 objcg = current_obj_cgroup(); 3677 if (!objcg || obj_cgroup_is_root(objcg)) 3678 return true; 3679 3680 /* 3681 * slab_alloc_node() avoids the NULL check, so we might be called with a 3682 * single NULL object. kmem_cache_alloc_bulk() aborts if it can't fill 3683 * the whole requested size. 3684 * return success as there's nothing to free back 3685 */ 3686 if (unlikely(*p == NULL)) 3687 return true; 3688 3689 flags &= gfp_allowed_mask; 3690 3691 if (lru) { 3692 int ret; 3693 struct mem_cgroup *memcg; 3694 3695 memcg = get_mem_cgroup_from_objcg(objcg); 3696 ret = memcg_list_lru_alloc(memcg, lru, flags); 3697 css_put(&memcg->css); 3698 3699 if (ret) 3700 return false; 3701 } 3702 3703 for (i = 0; i < size; i++) { 3704 unsigned long obj_exts; 3705 struct slabobj_ext *obj_ext; 3706 struct obj_stock_pcp *stock; 3707 3708 slab = virt_to_slab(p[i]); 3709 3710 if (!slab_obj_exts(slab)) { 3711 if (is_kfence_address(p[i])) 3712 continue; 3713 if (alloc_slab_obj_exts(slab, s, flags, slab_alloc_flags)) 3714 continue; 3715 } 3716 3717 /* 3718 * if we fail and size is 1, memcg_alloc_abort_single() will 3719 * just free the object, which is ok as we have not assigned 3720 * objcg to its obj_ext yet 3721 * 3722 * for larger sizes, kmem_cache_free_bulk() will uncharge 3723 * any objects that were already charged and obj_ext assigned 3724 * 3725 * TODO: we could batch this until slab_pgdat(slab) changes 3726 * between iterations, with a more complicated undo 3727 */ 3728 stock = trylock_stock(); 3729 if (!stock || !__consume_obj_stock(objcg, stock, obj_size)) { 3730 size_t remainder; 3731 3732 unlock_stock(stock); 3733 if (__obj_cgroup_charge(objcg, flags, obj_size, &remainder)) 3734 return false; 3735 stock = trylock_stock(); 3736 if (remainder) 3737 __refill_obj_stock(objcg, stock, remainder, false); 3738 } 3739 __account_obj_stock(objcg, stock, obj_size, 3740 slab_pgdat(slab), cache_vmstat_idx(s)); 3741 unlock_stock(stock); 3742 3743 obj_exts = slab_obj_exts(slab); 3744 get_slab_obj_exts(obj_exts); 3745 obj_ext = slab_obj_ext(s, slab, obj_exts, p[i]); 3746 3747 obj_cgroup_get(objcg); 3748 slab_obj_ext_set_objcg(slab, obj_ext, objcg); 3749 3750 put_slab_obj_exts(obj_exts); 3751 } 3752 3753 return true; 3754 } 3755 3756 void __memcg_slab_free_hook(struct kmem_cache *s, struct slab *slab, 3757 void **p, int objects, unsigned long obj_exts) 3758 { 3759 size_t obj_size = obj_full_size(s); 3760 3761 for (int i = 0; i < objects; i++) { 3762 struct obj_cgroup *objcg; 3763 struct slabobj_ext *obj_ext; 3764 struct obj_stock_pcp *stock; 3765 3766 obj_ext = slab_obj_ext(s, slab, obj_exts, p[i]); 3767 objcg = slab_obj_ext_objcg(slab, obj_ext); 3768 if (!objcg) 3769 continue; 3770 3771 slab_obj_ext_set_objcg(slab, obj_ext, NULL); 3772 3773 stock = trylock_stock(); 3774 __refill_obj_stock(objcg, stock, obj_size, true); 3775 __account_obj_stock(objcg, stock, -obj_size, 3776 slab_pgdat(slab), cache_vmstat_idx(s)); 3777 unlock_stock(stock); 3778 3779 obj_cgroup_put(objcg); 3780 } 3781 } 3782 3783 /* 3784 * The objcg is only set on the first page, so transfer it to all the 3785 * other pages. 3786 */ 3787 void split_page_memcg(struct page *page, unsigned order) 3788 { 3789 struct obj_cgroup *objcg = page_objcg(page); 3790 unsigned int i, nr = 1 << order; 3791 3792 if (!objcg) 3793 return; 3794 3795 for (i = 1; i < nr; i++) 3796 page_set_objcg(&page[i], objcg); 3797 3798 obj_cgroup_get_many(objcg, nr - 1); 3799 } 3800 3801 void folio_split_memcg_refs(struct folio *folio, unsigned old_order, 3802 unsigned new_order) 3803 { 3804 unsigned new_refs; 3805 3806 if (mem_cgroup_disabled() || !folio_memcg_charged(folio)) 3807 return; 3808 3809 new_refs = (1 << (old_order - new_order)) - 1; 3810 obj_cgroup_get_many(folio_objcg(folio), new_refs); 3811 } 3812 3813 static void memcg_online_kmem(struct mem_cgroup *memcg) 3814 { 3815 if (mem_cgroup_kmem_disabled()) 3816 return; 3817 3818 if (unlikely(mem_cgroup_is_root(memcg))) 3819 return; 3820 3821 static_branch_enable(&memcg_kmem_online_key); 3822 3823 memcg->kmemcg_id = memcg->private_id; 3824 } 3825 3826 static void memcg_offline_kmem(struct mem_cgroup *memcg) 3827 { 3828 struct mem_cgroup *parent; 3829 3830 if (mem_cgroup_kmem_disabled()) 3831 return; 3832 3833 if (unlikely(mem_cgroup_is_root(memcg))) 3834 return; 3835 3836 parent = parent_mem_cgroup(memcg); 3837 memcg_reparent_list_lrus(memcg, parent); 3838 } 3839 3840 #ifdef CONFIG_CGROUP_WRITEBACK 3841 3842 #include <trace/events/writeback.h> 3843 3844 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp) 3845 { 3846 return wb_domain_init(&memcg->cgwb_domain, gfp); 3847 } 3848 3849 static void memcg_wb_domain_exit(struct mem_cgroup *memcg) 3850 { 3851 wb_domain_exit(&memcg->cgwb_domain); 3852 } 3853 3854 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg) 3855 { 3856 wb_domain_size_changed(&memcg->cgwb_domain); 3857 } 3858 3859 struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb) 3860 { 3861 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css); 3862 3863 if (!memcg->css.parent) 3864 return NULL; 3865 3866 return &memcg->cgwb_domain; 3867 } 3868 3869 /** 3870 * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg 3871 * @wb: bdi_writeback in question 3872 * @pfilepages: out parameter for number of file pages 3873 * @pheadroom: out parameter for number of allocatable pages according to memcg 3874 * @pdirty: out parameter for number of dirty pages 3875 * @pwriteback: out parameter for number of pages under writeback 3876 * 3877 * Determine the numbers of file, headroom, dirty, and writeback pages in 3878 * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom 3879 * is a bit more involved. 3880 * 3881 * A memcg's headroom is "min(max, high) - used". In the hierarchy, the 3882 * headroom is calculated as the lowest headroom of itself and the 3883 * ancestors. Note that this doesn't consider the actual amount of 3884 * available memory in the system. The caller should further cap 3885 * *@pheadroom accordingly. 3886 */ 3887 void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages, 3888 unsigned long *pheadroom, unsigned long *pdirty, 3889 unsigned long *pwriteback) 3890 { 3891 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css); 3892 struct mem_cgroup *parent; 3893 3894 mem_cgroup_flush_stats_ratelimited(memcg); 3895 3896 *pdirty = memcg_page_state(memcg, NR_FILE_DIRTY); 3897 *pwriteback = memcg_page_state(memcg, NR_WRITEBACK); 3898 *pfilepages = memcg_page_state(memcg, NR_INACTIVE_FILE) + 3899 memcg_page_state(memcg, NR_ACTIVE_FILE); 3900 3901 *pheadroom = PAGE_COUNTER_MAX; 3902 while ((parent = parent_mem_cgroup(memcg))) { 3903 unsigned long ceiling = min(READ_ONCE(memcg->memory.max), 3904 READ_ONCE(memcg->memory.high)); 3905 unsigned long used = page_counter_read(&memcg->memory); 3906 3907 *pheadroom = min(*pheadroom, ceiling - min(ceiling, used)); 3908 memcg = parent; 3909 } 3910 } 3911 3912 /* 3913 * Foreign dirty flushing 3914 * 3915 * There's an inherent mismatch between memcg and writeback. The former 3916 * tracks ownership per-page while the latter per-inode. This was a 3917 * deliberate design decision because honoring per-page ownership in the 3918 * writeback path is complicated, may lead to higher CPU and IO overheads 3919 * and deemed unnecessary given that write-sharing an inode across 3920 * different cgroups isn't a common use-case. 3921 * 3922 * Combined with inode majority-writer ownership switching, this works well 3923 * enough in most cases but there are some pathological cases. For 3924 * example, let's say there are two cgroups A and B which keep writing to 3925 * different but confined parts of the same inode. B owns the inode and 3926 * A's memory is limited far below B's. A's dirty ratio can rise enough to 3927 * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid 3928 * triggering background writeback. A will be slowed down without a way to 3929 * make writeback of the dirty pages happen. 3930 * 3931 * Conditions like the above can lead to a cgroup getting repeatedly and 3932 * severely throttled after making some progress after each 3933 * dirty_expire_interval while the underlying IO device is almost 3934 * completely idle. 3935 * 3936 * Solving this problem completely requires matching the ownership tracking 3937 * granularities between memcg and writeback in either direction. However, 3938 * the more egregious behaviors can be avoided by simply remembering the 3939 * most recent foreign dirtying events and initiating remote flushes on 3940 * them when local writeback isn't enough to keep the memory clean enough. 3941 * 3942 * The following two functions implement such mechanism. When a foreign 3943 * page - a page whose memcg and writeback ownerships don't match - is 3944 * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning 3945 * bdi_writeback on the page owning memcg. When balance_dirty_pages() 3946 * decides that the memcg needs to sleep due to high dirty ratio, it calls 3947 * mem_cgroup_flush_foreign() which queues writeback on the recorded 3948 * foreign bdi_writebacks which haven't expired. Both the numbers of 3949 * recorded bdi_writebacks and concurrent in-flight foreign writebacks are 3950 * limited to MEMCG_CGWB_FRN_CNT. 3951 * 3952 * The mechanism only remembers IDs and doesn't hold any object references. 3953 * As being wrong occasionally doesn't matter, updates and accesses to the 3954 * records are lockless and racy. 3955 */ 3956 void mem_cgroup_track_foreign_dirty_slowpath(struct folio *folio, 3957 struct bdi_writeback *wb) 3958 { 3959 struct mem_cgroup *memcg = folio_memcg(folio); 3960 struct memcg_cgwb_frn *frn; 3961 u64 now = get_jiffies_64(); 3962 u64 oldest_at = now; 3963 int oldest = -1; 3964 int i; 3965 3966 trace_track_foreign_dirty(folio, wb); 3967 3968 /* 3969 * Pick the slot to use. If there is already a slot for @wb, keep 3970 * using it. If not replace the oldest one which isn't being 3971 * written out. 3972 */ 3973 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) { 3974 frn = &memcg->cgwb_frn[i]; 3975 if (frn->bdi_id == wb->bdi->id && 3976 frn->memcg_id == wb->memcg_css->id) 3977 break; 3978 if (time_before64(frn->at, oldest_at) && 3979 atomic_read(&frn->done.cnt) == 1) { 3980 oldest = i; 3981 oldest_at = frn->at; 3982 } 3983 } 3984 3985 if (i < MEMCG_CGWB_FRN_CNT) { 3986 /* 3987 * Re-using an existing one. Update timestamp lazily to 3988 * avoid making the cacheline hot. We want them to be 3989 * reasonably up-to-date and significantly shorter than 3990 * dirty_expire_interval as that's what expires the record. 3991 * Use the shorter of 1s and dirty_expire_interval / 8. 3992 */ 3993 unsigned long update_intv = 3994 min_t(unsigned long, HZ, 3995 msecs_to_jiffies(dirty_expire_interval * 10) / 8); 3996 3997 if (time_before64(frn->at, now - update_intv)) 3998 frn->at = now; 3999 } else if (oldest >= 0) { 4000 /* replace the oldest free one */ 4001 frn = &memcg->cgwb_frn[oldest]; 4002 frn->bdi_id = wb->bdi->id; 4003 frn->memcg_id = wb->memcg_css->id; 4004 frn->at = now; 4005 } 4006 } 4007 4008 /* issue foreign writeback flushes for recorded foreign dirtying events */ 4009 void mem_cgroup_flush_foreign(struct bdi_writeback *wb) 4010 { 4011 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css); 4012 unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10); 4013 u64 now = get_jiffies_64(); 4014 int i; 4015 4016 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) { 4017 struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i]; 4018 4019 /* 4020 * If the record is older than dirty_expire_interval, 4021 * writeback on it has already started. No need to kick it 4022 * off again. Also, don't start a new one if there's 4023 * already one in flight. 4024 */ 4025 if (time_after64(frn->at, now - intv) && 4026 atomic_read(&frn->done.cnt) == 1) { 4027 frn->at = 0; 4028 trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id); 4029 cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id, 4030 WB_REASON_FOREIGN_FLUSH, 4031 &frn->done); 4032 } 4033 } 4034 } 4035 4036 #else /* CONFIG_CGROUP_WRITEBACK */ 4037 4038 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp) 4039 { 4040 return 0; 4041 } 4042 4043 static void memcg_wb_domain_exit(struct mem_cgroup *memcg) 4044 { 4045 } 4046 4047 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg) 4048 { 4049 } 4050 4051 #endif /* CONFIG_CGROUP_WRITEBACK */ 4052 4053 /* 4054 * Private memory cgroup IDR 4055 * 4056 * Swap-out records and page cache shadow entries need to store memcg 4057 * references in constrained space, so we maintain an ID space that is 4058 * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of 4059 * memory-controlled cgroups to 64k. 4060 * 4061 * However, there usually are many references to the offline CSS after 4062 * the cgroup has been destroyed, such as page cache or reclaimable 4063 * slab objects, that don't need to hang on to the ID. We want to keep 4064 * those dead CSS from occupying IDs, or we might quickly exhaust the 4065 * relatively small ID space and prevent the creation of new cgroups 4066 * even when there are much fewer than 64k cgroups - possibly none. 4067 * 4068 * Maintain a private 16-bit ID space for memcg, and allow the ID to 4069 * be freed and recycled when it's no longer needed, which is usually 4070 * when the CSS is offlined. 4071 * 4072 * The only exception to that are records of swapped out tmpfs/shmem 4073 * pages that need to be attributed to live ancestors on swapin. But 4074 * those references are manageable from userspace. 4075 */ 4076 4077 #define MEM_CGROUP_ID_MAX ((1UL << MEM_CGROUP_ID_SHIFT) - 1) 4078 static DEFINE_XARRAY_ALLOC1(mem_cgroup_private_ids); 4079 4080 static inline struct obj_cgroup *obj_cgroup_from_private_id(unsigned short id) 4081 { 4082 lockdep_assert_once(rcu_read_lock_held()); 4083 4084 return xa_load(&mem_cgroup_private_ids, id); 4085 } 4086 4087 static void mem_cgroup_private_id_remove(struct mem_cgroup *memcg) 4088 { 4089 if (memcg->private_id > 0) { 4090 xa_erase(&mem_cgroup_private_ids, memcg->private_id); 4091 memcg->private_id = 0; 4092 } 4093 } 4094 4095 static void __mem_cgroup_private_id_put(struct obj_cgroup *objcg, 4096 unsigned short id, unsigned int n) 4097 { 4098 struct obj_cgroup *objcg_free; 4099 4100 if (refcount_sub_and_test(n, &objcg->private_id_ref)) { 4101 objcg_free = xa_erase(&mem_cgroup_private_ids, id); 4102 VM_WARN_ON(objcg_free != objcg); 4103 4104 /* Memcg ID pins the objcg */ 4105 obj_cgroup_put(objcg); 4106 } 4107 } 4108 4109 static inline void mem_cgroup_private_id_put(unsigned short id, unsigned int n) 4110 { 4111 struct obj_cgroup *objcg; 4112 4113 lockdep_assert_in_rcu_read_lock(); 4114 4115 objcg = obj_cgroup_from_private_id(id); 4116 __mem_cgroup_private_id_put(objcg, id, n); 4117 } 4118 4119 static void mem_cgroup_private_id_kill(struct mem_cgroup *memcg) 4120 { 4121 __mem_cgroup_private_id_put(memcg->private_id_objcg, memcg->private_id, 1); 4122 } 4123 4124 unsigned short mem_cgroup_private_id_get(struct mem_cgroup *memcg, unsigned int n) 4125 { 4126 struct obj_cgroup *objcg; 4127 4128 lockdep_assert_once(rcu_read_lock_held()); 4129 4130 objcg = memcg->private_id_objcg; 4131 4132 while (!refcount_add_not_zero(n, &objcg->private_id_ref)) { 4133 /* 4134 * The root cgroup cannot be destroyed, so it's refcount must 4135 * always be >= 1. 4136 */ 4137 if (WARN_ON_ONCE(mem_cgroup_is_root(memcg))) { 4138 VM_BUG_ON(1); 4139 break; 4140 } 4141 memcg = parent_mem_cgroup(memcg); 4142 objcg = memcg->private_id_objcg; 4143 } 4144 4145 return mem_cgroup_private_id(memcg); 4146 } 4147 4148 /** 4149 * mem_cgroup_from_private_id - look up a memcg from a memcg id 4150 * @id: the memcg id to look up 4151 * 4152 * Caller must hold rcu_read_lock(). 4153 * 4154 * @return: the memcg, or NULL if the memcg referred to is already dead. 4155 */ 4156 struct mem_cgroup *mem_cgroup_from_private_id(unsigned short id) 4157 { 4158 struct obj_cgroup *objcg; 4159 struct mem_cgroup *memcg; 4160 4161 WARN_ON_ONCE(!rcu_read_lock_held()); 4162 4163 objcg = obj_cgroup_from_private_id(id); 4164 if (!objcg) 4165 return NULL; 4166 4167 memcg = obj_cgroup_memcg(objcg); 4168 if (mem_cgroup_private_id(memcg) != id) 4169 return NULL; 4170 4171 return memcg; 4172 } 4173 4174 struct mem_cgroup *mem_cgroup_get_from_id(u64 id) 4175 { 4176 struct cgroup *cgrp; 4177 struct cgroup_subsys_state *css; 4178 struct mem_cgroup *memcg = NULL; 4179 4180 cgrp = cgroup_get_from_id(id); 4181 if (IS_ERR(cgrp)) 4182 return NULL; 4183 4184 css = cgroup_get_e_css(cgrp, &memory_cgrp_subsys); 4185 if (css) 4186 memcg = container_of(css, struct mem_cgroup, css); 4187 4188 cgroup_put(cgrp); 4189 4190 return memcg; 4191 } 4192 4193 static void free_mem_cgroup_per_node_info(struct mem_cgroup_per_node *pn) 4194 { 4195 if (!pn) 4196 return; 4197 4198 free_percpu(pn->lruvec_stats_percpu); 4199 kfree(pn->lruvec_stats); 4200 kfree(pn); 4201 } 4202 4203 static bool alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node) 4204 { 4205 struct mem_cgroup_per_node *pn; 4206 4207 pn = kmem_cache_alloc_node(memcg_pn_cachep, GFP_KERNEL | __GFP_ZERO, 4208 node); 4209 if (!pn) 4210 return false; 4211 4212 pn->lruvec_stats = kzalloc_node(sizeof(struct lruvec_stats), 4213 GFP_KERNEL_ACCOUNT, node); 4214 if (!pn->lruvec_stats) 4215 goto fail; 4216 4217 pn->lruvec_stats_percpu = alloc_percpu_gfp(struct lruvec_stats_percpu, 4218 GFP_KERNEL_ACCOUNT); 4219 if (!pn->lruvec_stats_percpu) 4220 goto fail; 4221 4222 INIT_LIST_HEAD(&pn->objcg_list); 4223 4224 lruvec_init(&pn->lruvec); 4225 pn->memcg = memcg; 4226 4227 memcg->nodeinfo[node] = pn; 4228 return true; 4229 fail: 4230 free_mem_cgroup_per_node_info(pn); 4231 return false; 4232 } 4233 4234 static void __mem_cgroup_free(struct mem_cgroup *memcg) 4235 { 4236 int node; 4237 4238 for_each_node(node) { 4239 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node]; 4240 if (!pn) 4241 continue; 4242 4243 obj_cgroup_put(pn->orig_objcg); 4244 free_mem_cgroup_per_node_info(pn); 4245 } 4246 memcg1_free_events(memcg); 4247 kfree(memcg->vmstats); 4248 free_percpu(memcg->vmstats_percpu); 4249 kfree(memcg); 4250 } 4251 4252 static void mem_cgroup_free(struct mem_cgroup *memcg) 4253 { 4254 lru_gen_exit_memcg(memcg); 4255 memcg_wb_domain_exit(memcg); 4256 __mem_cgroup_free(memcg); 4257 } 4258 4259 static struct mem_cgroup *mem_cgroup_alloc(struct mem_cgroup *parent) 4260 { 4261 struct memcg_vmstats_percpu *statc; 4262 struct memcg_vmstats_percpu __percpu *pstatc_pcpu; 4263 struct mem_cgroup *memcg; 4264 int node, cpu; 4265 int __maybe_unused i; 4266 long error; 4267 4268 memcg = kmem_cache_zalloc(memcg_cachep, GFP_KERNEL); 4269 if (!memcg) 4270 return ERR_PTR(-ENOMEM); 4271 4272 error = xa_alloc(&mem_cgroup_private_ids, &memcg->private_id, NULL, 4273 XA_LIMIT(1, MEM_CGROUP_ID_MAX), GFP_KERNEL); 4274 if (error) 4275 goto fail; 4276 error = -ENOMEM; 4277 4278 memcg->vmstats = kzalloc_obj(struct memcg_vmstats, GFP_KERNEL_ACCOUNT); 4279 if (!memcg->vmstats) 4280 goto fail; 4281 4282 memcg->vmstats_percpu = alloc_percpu_gfp(struct memcg_vmstats_percpu, 4283 GFP_KERNEL_ACCOUNT); 4284 if (!memcg->vmstats_percpu) 4285 goto fail; 4286 4287 if (!memcg1_alloc_events(memcg)) 4288 goto fail; 4289 4290 pstatc_pcpu = parent ? parent->vmstats_percpu : NULL; 4291 for_each_possible_cpu(cpu) { 4292 statc = per_cpu_ptr(memcg->vmstats_percpu, cpu); 4293 statc->parent_pcpu = pstatc_pcpu; 4294 statc->vmstats = memcg->vmstats; 4295 } 4296 4297 for_each_node(node) 4298 if (!alloc_mem_cgroup_per_node_info(memcg, node)) 4299 goto fail; 4300 4301 if (memcg_wb_domain_init(memcg, GFP_KERNEL)) 4302 goto fail; 4303 4304 INIT_WORK(&memcg->high_work, high_work_func); 4305 init_irq_work(&memcg->high_irq_work, high_irq_work_func); 4306 vmpressure_init(&memcg->vmpressure); 4307 INIT_LIST_HEAD(&memcg->memory_peaks); 4308 INIT_LIST_HEAD(&memcg->swap_peaks); 4309 spin_lock_init(&memcg->peaks_lock); 4310 memcg->socket_pressure = get_jiffies_64(); 4311 #if BITS_PER_LONG < 64 4312 seqlock_init(&memcg->socket_pressure_seqlock); 4313 #endif 4314 memcg1_memcg_init(memcg); 4315 memcg->kmemcg_id = -1; 4316 #ifdef CONFIG_CGROUP_WRITEBACK 4317 INIT_LIST_HEAD(&memcg->cgwb_list); 4318 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) 4319 memcg->cgwb_frn[i].done = 4320 __WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq); 4321 #endif 4322 lru_gen_init_memcg(memcg); 4323 return memcg; 4324 fail: 4325 mem_cgroup_private_id_remove(memcg); 4326 __mem_cgroup_free(memcg); 4327 return ERR_PTR(error); 4328 } 4329 4330 static struct cgroup_subsys_state * __ref 4331 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css) 4332 { 4333 struct mem_cgroup *parent = mem_cgroup_from_css(parent_css); 4334 struct mem_cgroup *memcg, *old_memcg; 4335 bool memcg_on_dfl = cgroup_subsys_on_dfl(memory_cgrp_subsys); 4336 4337 old_memcg = set_active_memcg(parent); 4338 memcg = mem_cgroup_alloc(parent); 4339 set_active_memcg(old_memcg); 4340 if (IS_ERR(memcg)) 4341 return ERR_CAST(memcg); 4342 4343 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX); 4344 #ifdef CONFIG_ZSWAP 4345 memcg->zswap_max = PAGE_COUNTER_MAX; 4346 WRITE_ONCE(memcg->zswap_writeback, true); 4347 #endif 4348 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX); 4349 if (parent) { 4350 page_counter_init(&memcg->memory, &parent->memory, memcg_on_dfl); 4351 page_counter_init(&memcg->swap, &parent->swap, false); 4352 #ifdef CONFIG_MEMCG_V1 4353 WRITE_ONCE(memcg->swappiness, mem_cgroup_swappiness(parent)); 4354 memcg->memory.track_failcnt = !memcg_on_dfl; 4355 memcg->memsw.track_failcnt = !memcg_on_dfl; 4356 WRITE_ONCE(memcg->oom_kill_disable, READ_ONCE(parent->oom_kill_disable)); 4357 page_counter_init(&memcg->kmem, &parent->kmem, false); 4358 page_counter_init(&memcg->tcpmem, &parent->tcpmem, false); 4359 memcg->tcpmem.track_failcnt = !memcg_on_dfl; 4360 #endif 4361 } else { 4362 init_memcg_stats(); 4363 init_memcg_events(); 4364 page_counter_init(&memcg->memory, NULL, true); 4365 page_counter_init(&memcg->swap, NULL, false); 4366 #ifdef CONFIG_MEMCG_V1 4367 page_counter_init(&memcg->kmem, NULL, false); 4368 page_counter_init(&memcg->tcpmem, NULL, false); 4369 #endif 4370 root_mem_cgroup = memcg; 4371 return &memcg->css; 4372 } 4373 4374 if (memcg_on_dfl && !cgroup_memory_nosocket) 4375 static_branch_inc(&memcg_sockets_enabled_key); 4376 4377 if (!cgroup_memory_nobpf) 4378 static_branch_inc(&memcg_bpf_enabled_key); 4379 4380 return &memcg->css; 4381 } 4382 4383 static int mem_cgroup_css_online(struct cgroup_subsys_state *css) 4384 { 4385 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 4386 struct obj_cgroup *objcg; 4387 int nid; 4388 4389 memcg_online_kmem(memcg); 4390 4391 /* 4392 * A memcg must be visible for expand_shrinker_info() 4393 * by the time the maps are allocated. So, we allocate maps 4394 * here, when mem_cgroup_iter() can't skip it. 4395 */ 4396 if (alloc_shrinker_info(memcg)) 4397 goto offline_kmem; 4398 4399 for_each_node(nid) { 4400 objcg = obj_cgroup_alloc(); 4401 if (!objcg) 4402 goto free_objcg; 4403 4404 if (unlikely(mem_cgroup_is_root(memcg))) 4405 objcg->is_root = true; 4406 4407 objcg->memcg = memcg; 4408 rcu_assign_pointer(memcg->nodeinfo[nid]->objcg, objcg); 4409 obj_cgroup_get(objcg); 4410 memcg->nodeinfo[nid]->orig_objcg = objcg; 4411 } 4412 4413 if (unlikely(mem_cgroup_is_root(memcg)) && !mem_cgroup_disabled()) 4414 queue_delayed_work(system_dfl_wq, &stats_flush_dwork, 4415 FLUSH_TIME); 4416 lru_gen_online_memcg(memcg); 4417 4418 /* CSS pins memcg ID, memcg ID pins obj cgroup */ 4419 memcg->private_id_objcg = objcg; 4420 refcount_set(&memcg->private_id_objcg->private_id_ref, 1); 4421 obj_cgroup_get(memcg->private_id_objcg); 4422 4423 /* 4424 * Ensure mem_cgroup_from_private_id() works once we're fully online. 4425 * 4426 * We could do this earlier and require callers to filter with 4427 * css_tryget_online(). But right now there are no users that 4428 * need earlier access, and the workingset code relies on the 4429 * cgroup tree linkage (mem_cgroup_get_nr_swap_pages()). So 4430 * publish it here at the end of onlining. This matches the 4431 * regular ID destruction during offlining. 4432 */ 4433 xa_store(&mem_cgroup_private_ids, memcg->private_id, memcg->private_id_objcg, GFP_KERNEL); 4434 4435 return 0; 4436 free_objcg: 4437 for_each_node(nid) { 4438 struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid]; 4439 4440 objcg = rcu_replace_pointer(pn->objcg, NULL, true); 4441 if (objcg) 4442 percpu_ref_kill(&objcg->refcnt); 4443 4444 if (pn->orig_objcg) { 4445 obj_cgroup_put(pn->orig_objcg); 4446 /* 4447 * Reset pn->orig_objcg to NULL to prevent 4448 * obj_cgroup_put() from being called again in 4449 * __mem_cgroup_free(). 4450 */ 4451 pn->orig_objcg = NULL; 4452 } 4453 } 4454 free_shrinker_info(memcg); 4455 offline_kmem: 4456 memcg_offline_kmem(memcg); 4457 mem_cgroup_private_id_remove(memcg); 4458 return -ENOMEM; 4459 } 4460 4461 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css) 4462 { 4463 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 4464 4465 memcg1_css_offline(memcg); 4466 4467 page_counter_set_min(&memcg->memory, 0); 4468 page_counter_set_low(&memcg->memory, 0); 4469 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX); 4470 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX); 4471 4472 zswap_memcg_offline_cleanup(memcg); 4473 4474 memcg_offline_kmem(memcg); 4475 /* 4476 * The reparenting of objcg must be after the reparenting of 4477 * the list_lru in memcg_offline_kmem(), which ensures that 4478 * they will not mistakenly get the parent list_lru. 4479 */ 4480 memcg_reparent_objcgs(memcg); 4481 reparent_shrinker_deferred(memcg); 4482 wb_memcg_offline(memcg); 4483 lru_gen_offline_memcg(memcg); 4484 4485 drain_all_stock(memcg); 4486 4487 mem_cgroup_private_id_kill(memcg); 4488 } 4489 4490 static void mem_cgroup_css_released(struct cgroup_subsys_state *css) 4491 { 4492 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 4493 4494 invalidate_reclaim_iterators(memcg); 4495 lru_gen_release_memcg(memcg); 4496 } 4497 4498 static void mem_cgroup_css_free(struct cgroup_subsys_state *css) 4499 { 4500 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 4501 int __maybe_unused i; 4502 4503 #ifdef CONFIG_CGROUP_WRITEBACK 4504 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) 4505 wb_wait_for_completion(&memcg->cgwb_frn[i].done); 4506 #endif 4507 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket) 4508 static_branch_dec(&memcg_sockets_enabled_key); 4509 4510 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg1_tcpmem_active(memcg)) 4511 static_branch_dec(&memcg_sockets_enabled_key); 4512 4513 if (!cgroup_memory_nobpf) 4514 static_branch_dec(&memcg_bpf_enabled_key); 4515 4516 vmpressure_cleanup(&memcg->vmpressure); 4517 irq_work_sync(&memcg->high_irq_work); 4518 cancel_work_sync(&memcg->high_work); 4519 free_shrinker_info(memcg); 4520 mem_cgroup_free(memcg); 4521 } 4522 4523 /** 4524 * mem_cgroup_css_reset - reset the states of a mem_cgroup 4525 * @css: the target css 4526 * 4527 * Reset the states of the mem_cgroup associated with @css. This is 4528 * invoked when the userland requests disabling on the default hierarchy 4529 * but the memcg is pinned through dependency. The memcg should stop 4530 * applying policies and should revert to the vanilla state as it may be 4531 * made visible again. 4532 * 4533 * The current implementation only resets the essential configurations. 4534 * This needs to be expanded to cover all the visible parts. 4535 */ 4536 static void mem_cgroup_css_reset(struct cgroup_subsys_state *css) 4537 { 4538 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 4539 4540 page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX); 4541 page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX); 4542 WRITE_ONCE(memcg->oom_group, false); 4543 #ifdef CONFIG_ZSWAP 4544 WRITE_ONCE(memcg->zswap_max, PAGE_COUNTER_MAX); 4545 WRITE_ONCE(memcg->zswap_writeback, true); 4546 #endif 4547 #ifdef CONFIG_MEMCG_V1 4548 page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX); 4549 page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX); 4550 #endif 4551 page_counter_set_min(&memcg->memory, 0); 4552 page_counter_set_low(&memcg->memory, 0); 4553 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX); 4554 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX); 4555 memcg_wb_domain_size_changed(memcg); 4556 } 4557 4558 struct aggregate_control { 4559 /* pointer to the aggregated (CPU and subtree aggregated) counters */ 4560 long *aggregate; 4561 /* 4562 * pointer to the non-hierarchical (CPU aggregated) counters or NULL to 4563 * skip updating them (see memcg_state_local_array()) 4564 */ 4565 long *local; 4566 /* pointer to the pending child counters during tree propagation */ 4567 long *pending; 4568 /* pointer to the parent's pending counters, could be NULL */ 4569 long *ppending; 4570 /* pointer to the percpu counters to be aggregated */ 4571 long *cstat; 4572 /* pointer to the percpu counters of the last aggregation*/ 4573 long *cstat_prev; 4574 /* size of the above counters */ 4575 int size; 4576 }; 4577 4578 static void mem_cgroup_stat_aggregate(struct aggregate_control *ac) 4579 { 4580 int i; 4581 long delta, delta_cpu, v; 4582 4583 for (i = 0; i < ac->size; i++) { 4584 /* 4585 * Collect the aggregated propagation counts of groups 4586 * below us. We're in a per-cpu loop here and this is 4587 * a global counter, so the first cycle will get them. 4588 */ 4589 delta = ac->pending[i]; 4590 if (delta) 4591 ac->pending[i] = 0; 4592 4593 /* Add CPU changes on this level since the last flush */ 4594 delta_cpu = 0; 4595 v = READ_ONCE(ac->cstat[i]); 4596 if (v != ac->cstat_prev[i]) { 4597 delta_cpu = v - ac->cstat_prev[i]; 4598 delta += delta_cpu; 4599 ac->cstat_prev[i] = v; 4600 } 4601 4602 /* Aggregate counts on this level and propagate upwards */ 4603 if (delta_cpu && ac->local) 4604 ac->local[i] += delta_cpu; 4605 4606 if (delta) { 4607 ac->aggregate[i] += delta; 4608 if (ac->ppending) 4609 ac->ppending[i] += delta; 4610 } 4611 } 4612 } 4613 4614 #ifdef CONFIG_MEMCG_NMI_SAFETY_REQUIRES_ATOMIC 4615 static void flush_nmi_stats(struct mem_cgroup *memcg, struct mem_cgroup *parent) 4616 { 4617 long *state_local = memcg_state_local_array(memcg); 4618 int nid; 4619 4620 if (atomic_read(&memcg->kmem_stat)) { 4621 int kmem = atomic_xchg(&memcg->kmem_stat, 0); 4622 int index = memcg_stats_index(MEMCG_KMEM); 4623 4624 memcg->vmstats->state[index] += kmem; 4625 if (state_local) 4626 state_local[index] += kmem; 4627 if (parent) 4628 parent->vmstats->state_pending[index] += kmem; 4629 } 4630 4631 for_each_node_state(nid, N_MEMORY) { 4632 struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid]; 4633 struct lruvec_stats *lstats = pn->lruvec_stats; 4634 struct lruvec_stats *plstats = NULL; 4635 4636 if (parent) 4637 plstats = parent->nodeinfo[nid]->lruvec_stats; 4638 4639 if (atomic_read(&pn->slab_reclaimable)) { 4640 int slab = atomic_xchg(&pn->slab_reclaimable, 0); 4641 int index = memcg_stats_index(NR_SLAB_RECLAIMABLE_B); 4642 4643 lstats->state[index] += slab; 4644 lstats->state_local[index] += slab; 4645 if (plstats) 4646 plstats->state_pending[index] += slab; 4647 memcg->vmstats->state[index] += slab; 4648 if (state_local) 4649 state_local[index] += slab; 4650 if (parent) 4651 parent->vmstats->state_pending[index] += slab; 4652 } 4653 if (atomic_read(&pn->slab_unreclaimable)) { 4654 int slab = atomic_xchg(&pn->slab_unreclaimable, 0); 4655 int index = memcg_stats_index(NR_SLAB_UNRECLAIMABLE_B); 4656 4657 lstats->state[index] += slab; 4658 lstats->state_local[index] += slab; 4659 if (plstats) 4660 plstats->state_pending[index] += slab; 4661 memcg->vmstats->state[index] += slab; 4662 if (state_local) 4663 state_local[index] += slab; 4664 if (parent) 4665 parent->vmstats->state_pending[index] += slab; 4666 } 4667 } 4668 } 4669 #else 4670 static void flush_nmi_stats(struct mem_cgroup *memcg, struct mem_cgroup *parent) 4671 {} 4672 #endif 4673 4674 static void mem_cgroup_css_rstat_flush(struct cgroup_subsys_state *css, int cpu) 4675 { 4676 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 4677 struct mem_cgroup *parent = parent_mem_cgroup(memcg); 4678 struct memcg_vmstats_percpu *statc; 4679 struct aggregate_control ac; 4680 int nid; 4681 4682 flush_nmi_stats(memcg, parent); 4683 4684 statc = per_cpu_ptr(memcg->vmstats_percpu, cpu); 4685 4686 ac = (struct aggregate_control) { 4687 .aggregate = memcg->vmstats->state, 4688 .local = memcg_state_local_array(memcg), 4689 .pending = memcg->vmstats->state_pending, 4690 .ppending = parent ? parent->vmstats->state_pending : NULL, 4691 .cstat = statc->state, 4692 .cstat_prev = statc->state_prev, 4693 .size = MEMCG_VMSTAT_SIZE, 4694 }; 4695 mem_cgroup_stat_aggregate(&ac); 4696 4697 ac = (struct aggregate_control) { 4698 .aggregate = memcg->vmstats->events, 4699 .local = memcg_events_local_array(memcg), 4700 .pending = memcg->vmstats->events_pending, 4701 .ppending = parent ? parent->vmstats->events_pending : NULL, 4702 .cstat = statc->events, 4703 .cstat_prev = statc->events_prev, 4704 .size = NR_MEMCG_EVENTS, 4705 }; 4706 mem_cgroup_stat_aggregate(&ac); 4707 4708 for_each_node_state(nid, N_MEMORY) { 4709 struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid]; 4710 struct lruvec_stats *lstats = pn->lruvec_stats; 4711 struct lruvec_stats *plstats = NULL; 4712 struct lruvec_stats_percpu *lstatc; 4713 4714 if (parent) 4715 plstats = parent->nodeinfo[nid]->lruvec_stats; 4716 4717 lstatc = per_cpu_ptr(pn->lruvec_stats_percpu, cpu); 4718 4719 ac = (struct aggregate_control) { 4720 .aggregate = lstats->state, 4721 .local = lstats->state_local, 4722 .pending = lstats->state_pending, 4723 .ppending = plstats ? plstats->state_pending : NULL, 4724 .cstat = lstatc->state, 4725 .cstat_prev = lstatc->state_prev, 4726 .size = NR_MEMCG_NODE_STAT_ITEMS, 4727 }; 4728 mem_cgroup_stat_aggregate(&ac); 4729 4730 } 4731 WRITE_ONCE(statc->stats_updates, 0); 4732 /* We are in a per-cpu loop here, only do the atomic write once */ 4733 if (atomic_long_read(&memcg->vmstats->stats_updates)) 4734 atomic_long_set(&memcg->vmstats->stats_updates, 0); 4735 } 4736 4737 static void mem_cgroup_fork(struct task_struct *task) 4738 { 4739 /* 4740 * Set the update flag to cause task->objcg to be initialized lazily 4741 * on the first allocation. It can be done without any synchronization 4742 * because it's always performed on the current task, so does 4743 * current_objcg_update(). 4744 */ 4745 task->objcg = (struct obj_cgroup *)CURRENT_OBJCG_UPDATE_FLAG; 4746 } 4747 4748 static void mem_cgroup_exit(struct task_struct *task) 4749 { 4750 struct obj_cgroup *objcg = task->objcg; 4751 4752 objcg = (struct obj_cgroup *) 4753 ((unsigned long)objcg & ~CURRENT_OBJCG_UPDATE_FLAG); 4754 obj_cgroup_put(objcg); 4755 4756 /* 4757 * Some kernel allocations can happen after this point, 4758 * but let's ignore them. It can be done without any synchronization 4759 * because it's always performed on the current task, so does 4760 * current_objcg_update(). 4761 */ 4762 task->objcg = NULL; 4763 } 4764 4765 #ifdef CONFIG_LRU_GEN 4766 static void mem_cgroup_lru_gen_attach(struct cgroup_taskset *tset) 4767 { 4768 struct task_struct *task; 4769 struct cgroup_subsys_state *css; 4770 4771 /* find the first leader if there is any */ 4772 cgroup_taskset_for_each_leader(task, css, tset) 4773 break; 4774 4775 if (!task) 4776 return; 4777 4778 task_lock(task); 4779 if (task->mm && READ_ONCE(task->mm->owner) == task) 4780 lru_gen_migrate_mm(task->mm); 4781 task_unlock(task); 4782 } 4783 #else 4784 static void mem_cgroup_lru_gen_attach(struct cgroup_taskset *tset) {} 4785 #endif /* CONFIG_LRU_GEN */ 4786 4787 static void mem_cgroup_kmem_attach(struct cgroup_taskset *tset) 4788 { 4789 struct task_struct *task; 4790 struct cgroup_subsys_state *css; 4791 4792 cgroup_taskset_for_each(task, css, tset) { 4793 /* atomically set the update bit */ 4794 set_bit(CURRENT_OBJCG_UPDATE_BIT, (unsigned long *)&task->objcg); 4795 } 4796 } 4797 4798 static void mem_cgroup_attach(struct cgroup_taskset *tset) 4799 { 4800 mem_cgroup_lru_gen_attach(tset); 4801 mem_cgroup_kmem_attach(tset); 4802 } 4803 4804 static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value) 4805 { 4806 if (value == PAGE_COUNTER_MAX) 4807 seq_puts(m, "max\n"); 4808 else 4809 seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE); 4810 4811 return 0; 4812 } 4813 4814 static u64 memory_current_read(struct cgroup_subsys_state *css, 4815 struct cftype *cft) 4816 { 4817 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 4818 4819 return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE; 4820 } 4821 4822 #define OFP_PEAK_UNSET (((-1UL))) 4823 4824 static int peak_show(struct seq_file *sf, void *v, struct page_counter *pc) 4825 { 4826 struct cgroup_of_peak *ofp = of_peak(sf->private); 4827 u64 fd_peak = READ_ONCE(ofp->value), peak; 4828 4829 /* User wants global or local peak? */ 4830 if (fd_peak == OFP_PEAK_UNSET) 4831 peak = pc->watermark; 4832 else 4833 peak = max(fd_peak, READ_ONCE(pc->local_watermark)); 4834 4835 seq_printf(sf, "%llu\n", peak * PAGE_SIZE); 4836 return 0; 4837 } 4838 4839 static int memory_peak_show(struct seq_file *sf, void *v) 4840 { 4841 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(sf)); 4842 4843 guard(spinlock)(&memcg->peaks_lock); 4844 return peak_show(sf, v, &memcg->memory); 4845 } 4846 4847 static int peak_open(struct kernfs_open_file *of) 4848 { 4849 struct cgroup_of_peak *ofp = of_peak(of); 4850 4851 ofp->value = OFP_PEAK_UNSET; 4852 return 0; 4853 } 4854 4855 static void peak_release(struct kernfs_open_file *of) 4856 { 4857 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 4858 struct cgroup_of_peak *ofp = of_peak(of); 4859 4860 if (ofp->value == OFP_PEAK_UNSET) { 4861 /* fast path (no writes on this fd) */ 4862 return; 4863 } 4864 spin_lock(&memcg->peaks_lock); 4865 list_del(&ofp->list); 4866 spin_unlock(&memcg->peaks_lock); 4867 } 4868 4869 static ssize_t peak_write(struct kernfs_open_file *of, char *buf, size_t nbytes, 4870 loff_t off, struct page_counter *pc, 4871 struct list_head *watchers) 4872 { 4873 unsigned long usage, old_watermark; 4874 struct cgroup_of_peak *peer_ctx; 4875 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 4876 struct cgroup_of_peak *ofp = of_peak(of); 4877 4878 spin_lock(&memcg->peaks_lock); 4879 4880 usage = page_counter_read(pc); 4881 old_watermark = READ_ONCE(pc->local_watermark); 4882 WRITE_ONCE(pc->local_watermark, usage); 4883 4884 list_for_each_entry(peer_ctx, watchers, list) 4885 if (peer_ctx != ofp && old_watermark > peer_ctx->value) 4886 WRITE_ONCE(peer_ctx->value, old_watermark); 4887 4888 /* initial write, register watcher */ 4889 if (ofp->value == OFP_PEAK_UNSET) 4890 list_add(&ofp->list, watchers); 4891 4892 WRITE_ONCE(ofp->value, usage); 4893 spin_unlock(&memcg->peaks_lock); 4894 4895 return nbytes; 4896 } 4897 4898 static ssize_t memory_peak_write(struct kernfs_open_file *of, char *buf, 4899 size_t nbytes, loff_t off) 4900 { 4901 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 4902 4903 return peak_write(of, buf, nbytes, off, &memcg->memory, 4904 &memcg->memory_peaks); 4905 } 4906 4907 #undef OFP_PEAK_UNSET 4908 4909 static int memory_min_show(struct seq_file *m, void *v) 4910 { 4911 return seq_puts_memcg_tunable(m, 4912 READ_ONCE(mem_cgroup_from_seq(m)->memory.min)); 4913 } 4914 4915 static ssize_t memory_min_write(struct kernfs_open_file *of, 4916 char *buf, size_t nbytes, loff_t off) 4917 { 4918 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 4919 unsigned long min; 4920 int err; 4921 4922 buf = strstrip(buf); 4923 err = page_counter_memparse(buf, "max", &min); 4924 if (err) 4925 return err; 4926 4927 page_counter_set_min(&memcg->memory, min); 4928 4929 return nbytes; 4930 } 4931 4932 static int memory_low_show(struct seq_file *m, void *v) 4933 { 4934 return seq_puts_memcg_tunable(m, 4935 READ_ONCE(mem_cgroup_from_seq(m)->memory.low)); 4936 } 4937 4938 static ssize_t memory_low_write(struct kernfs_open_file *of, 4939 char *buf, size_t nbytes, loff_t off) 4940 { 4941 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 4942 unsigned long low; 4943 int err; 4944 4945 buf = strstrip(buf); 4946 err = page_counter_memparse(buf, "max", &low); 4947 if (err) 4948 return err; 4949 4950 page_counter_set_low(&memcg->memory, low); 4951 4952 return nbytes; 4953 } 4954 4955 static int memory_high_show(struct seq_file *m, void *v) 4956 { 4957 return seq_puts_memcg_tunable(m, 4958 READ_ONCE(mem_cgroup_from_seq(m)->memory.high)); 4959 } 4960 4961 static ssize_t memory_high_write(struct kernfs_open_file *of, 4962 char *buf, size_t nbytes, loff_t off) 4963 { 4964 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 4965 unsigned int nr_retries = MAX_RECLAIM_RETRIES; 4966 bool drained = false; 4967 unsigned long high; 4968 int err; 4969 4970 buf = strstrip(buf); 4971 err = page_counter_memparse(buf, "max", &high); 4972 if (err) 4973 return err; 4974 4975 page_counter_set_high(&memcg->memory, high); 4976 4977 if (of->file->f_flags & O_NONBLOCK) 4978 goto out; 4979 4980 for (;;) { 4981 unsigned long nr_pages = page_counter_read(&memcg->memory); 4982 unsigned long reclaimed; 4983 4984 if (high != READ_ONCE(memcg->memory.high)) 4985 break; 4986 4987 if (nr_pages <= high) 4988 break; 4989 4990 if (signal_pending(current)) 4991 break; 4992 4993 /* cgroup_rmdir() waits for us with cgroup_mutex held. */ 4994 if (memcg_is_dying(memcg)) 4995 break; 4996 4997 if (!drained) { 4998 drain_all_stock(memcg); 4999 drained = true; 5000 continue; 5001 } 5002 5003 reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high, 5004 GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP, NULL); 5005 5006 if (!reclaimed && !nr_retries--) 5007 break; 5008 } 5009 out: 5010 memcg_wb_domain_size_changed(memcg); 5011 return nbytes; 5012 } 5013 5014 static int memory_max_show(struct seq_file *m, void *v) 5015 { 5016 return seq_puts_memcg_tunable(m, 5017 READ_ONCE(mem_cgroup_from_seq(m)->memory.max)); 5018 } 5019 5020 static ssize_t memory_max_write(struct kernfs_open_file *of, 5021 char *buf, size_t nbytes, loff_t off) 5022 { 5023 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 5024 unsigned int nr_reclaims = MAX_RECLAIM_RETRIES; 5025 bool drained = false; 5026 unsigned long max; 5027 int err; 5028 5029 buf = strstrip(buf); 5030 err = page_counter_memparse(buf, "max", &max); 5031 if (err) 5032 return err; 5033 5034 xchg(&memcg->memory.max, max); 5035 5036 if (of->file->f_flags & O_NONBLOCK) 5037 goto out; 5038 5039 for (;;) { 5040 unsigned long nr_pages = page_counter_read(&memcg->memory); 5041 5042 if (max != READ_ONCE(memcg->memory.max)) 5043 break; 5044 5045 if (nr_pages <= max) 5046 break; 5047 5048 if (signal_pending(current)) 5049 break; 5050 5051 /* cgroup_rmdir() waits for us with cgroup_mutex held. */ 5052 if (memcg_is_dying(memcg)) 5053 break; 5054 5055 if (!drained) { 5056 drain_all_stock(memcg); 5057 drained = true; 5058 continue; 5059 } 5060 5061 if (nr_reclaims) { 5062 if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max, 5063 GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP, NULL)) 5064 nr_reclaims--; 5065 continue; 5066 } 5067 5068 memcg_memory_event(memcg, MEMCG_OOM); 5069 if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0)) 5070 break; 5071 cond_resched(); 5072 } 5073 out: 5074 memcg_wb_domain_size_changed(memcg); 5075 return nbytes; 5076 } 5077 5078 /* 5079 * Note: don't forget to update the 'samples/cgroup/memcg_event_listener' 5080 * if any new events become available. 5081 */ 5082 static void __memory_events_show(struct seq_file *m, atomic_long_t *events) 5083 { 5084 seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW])); 5085 seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH])); 5086 seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX])); 5087 seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM])); 5088 seq_printf(m, "oom_kill %lu\n", 5089 atomic_long_read(&events[MEMCG_OOM_KILL])); 5090 seq_printf(m, "oom_group_kill %lu\n", 5091 atomic_long_read(&events[MEMCG_OOM_GROUP_KILL])); 5092 seq_printf(m, "sock_throttled %lu\n", 5093 atomic_long_read(&events[MEMCG_SOCK_THROTTLED])); 5094 } 5095 5096 static int memory_events_show(struct seq_file *m, void *v) 5097 { 5098 struct mem_cgroup *memcg = mem_cgroup_from_seq(m); 5099 5100 __memory_events_show(m, memcg->memory_events); 5101 return 0; 5102 } 5103 5104 static int memory_events_local_show(struct seq_file *m, void *v) 5105 { 5106 struct mem_cgroup *memcg = mem_cgroup_from_seq(m); 5107 5108 __memory_events_show(m, memcg->memory_events_local); 5109 return 0; 5110 } 5111 5112 int memory_stat_show(struct seq_file *m, void *v) 5113 { 5114 struct mem_cgroup *memcg = mem_cgroup_from_seq(m); 5115 char *buf = kmalloc(SEQ_BUF_SIZE, GFP_KERNEL); 5116 struct seq_buf s; 5117 5118 if (!buf) 5119 return -ENOMEM; 5120 seq_buf_init(&s, buf, SEQ_BUF_SIZE); 5121 memory_stat_format(memcg, &s); 5122 seq_puts(m, buf); 5123 kfree(buf); 5124 return 0; 5125 } 5126 5127 #ifdef CONFIG_NUMA 5128 static inline unsigned long lruvec_page_state_output(struct lruvec *lruvec, 5129 int item) 5130 { 5131 return lruvec_page_state(lruvec, item) * 5132 memcg_page_state_output_unit(item); 5133 } 5134 5135 static int memory_numa_stat_show(struct seq_file *m, void *v) 5136 { 5137 int i; 5138 struct mem_cgroup *memcg = mem_cgroup_from_seq(m); 5139 5140 mem_cgroup_flush_stats(memcg); 5141 5142 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) { 5143 int nid; 5144 5145 if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS) 5146 continue; 5147 5148 seq_printf(m, "%s", memory_stats[i].name); 5149 for_each_node_state(nid, N_MEMORY) { 5150 u64 size; 5151 struct lruvec *lruvec; 5152 5153 lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid)); 5154 size = lruvec_page_state_output(lruvec, 5155 memory_stats[i].idx); 5156 seq_printf(m, " N%d=%llu", nid, size); 5157 } 5158 seq_putc(m, '\n'); 5159 } 5160 5161 return 0; 5162 } 5163 #endif 5164 5165 static int memory_oom_group_show(struct seq_file *m, void *v) 5166 { 5167 struct mem_cgroup *memcg = mem_cgroup_from_seq(m); 5168 5169 seq_printf(m, "%d\n", READ_ONCE(memcg->oom_group)); 5170 5171 return 0; 5172 } 5173 5174 static ssize_t memory_oom_group_write(struct kernfs_open_file *of, 5175 char *buf, size_t nbytes, loff_t off) 5176 { 5177 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 5178 int ret, oom_group; 5179 5180 buf = strstrip(buf); 5181 if (!buf) 5182 return -EINVAL; 5183 5184 ret = kstrtoint(buf, 0, &oom_group); 5185 if (ret) 5186 return ret; 5187 5188 if (oom_group != 0 && oom_group != 1) 5189 return -EINVAL; 5190 5191 WRITE_ONCE(memcg->oom_group, oom_group); 5192 5193 return nbytes; 5194 } 5195 5196 static ssize_t memory_reclaim(struct kernfs_open_file *of, char *buf, 5197 size_t nbytes, loff_t off) 5198 { 5199 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 5200 int ret; 5201 5202 ret = user_proactive_reclaim(buf, memcg, NULL); 5203 if (ret) 5204 return ret; 5205 5206 return nbytes; 5207 } 5208 5209 static struct cftype memory_files[] = { 5210 { 5211 .name = "current", 5212 .flags = CFTYPE_NOT_ON_ROOT, 5213 .read_u64 = memory_current_read, 5214 }, 5215 { 5216 .name = "peak", 5217 .flags = CFTYPE_NOT_ON_ROOT, 5218 .open = peak_open, 5219 .release = peak_release, 5220 .seq_show = memory_peak_show, 5221 .write = memory_peak_write, 5222 }, 5223 { 5224 .name = "min", 5225 .flags = CFTYPE_NOT_ON_ROOT, 5226 .seq_show = memory_min_show, 5227 .write = memory_min_write, 5228 }, 5229 { 5230 .name = "low", 5231 .flags = CFTYPE_NOT_ON_ROOT, 5232 .seq_show = memory_low_show, 5233 .write = memory_low_write, 5234 }, 5235 { 5236 .name = "high", 5237 .flags = CFTYPE_NOT_ON_ROOT, 5238 .seq_show = memory_high_show, 5239 .write = memory_high_write, 5240 }, 5241 { 5242 .name = "max", 5243 .flags = CFTYPE_NOT_ON_ROOT, 5244 .seq_show = memory_max_show, 5245 .write = memory_max_write, 5246 }, 5247 { 5248 .name = "events", 5249 .flags = CFTYPE_NOT_ON_ROOT, 5250 .file_offset = offsetof(struct mem_cgroup, events_file), 5251 .seq_show = memory_events_show, 5252 }, 5253 { 5254 .name = "events.local", 5255 .flags = CFTYPE_NOT_ON_ROOT, 5256 .file_offset = offsetof(struct mem_cgroup, events_local_file), 5257 .seq_show = memory_events_local_show, 5258 }, 5259 { 5260 .name = "stat", 5261 .seq_show = memory_stat_show, 5262 }, 5263 #ifdef CONFIG_NUMA 5264 { 5265 .name = "numa_stat", 5266 .seq_show = memory_numa_stat_show, 5267 }, 5268 #endif 5269 { 5270 .name = "oom.group", 5271 .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE, 5272 .seq_show = memory_oom_group_show, 5273 .write = memory_oom_group_write, 5274 }, 5275 { 5276 .name = "reclaim", 5277 .flags = CFTYPE_NS_DELEGATABLE, 5278 .write = memory_reclaim, 5279 }, 5280 { } /* terminate */ 5281 }; 5282 5283 struct cgroup_subsys memory_cgrp_subsys = { 5284 .css_alloc = mem_cgroup_css_alloc, 5285 .css_online = mem_cgroup_css_online, 5286 .css_offline = mem_cgroup_css_offline, 5287 .css_released = mem_cgroup_css_released, 5288 .css_free = mem_cgroup_css_free, 5289 .css_reset = mem_cgroup_css_reset, 5290 .css_rstat_flush = mem_cgroup_css_rstat_flush, 5291 .attach = mem_cgroup_attach, 5292 .fork = mem_cgroup_fork, 5293 .exit = mem_cgroup_exit, 5294 .dfl_cftypes = memory_files, 5295 #ifdef CONFIG_MEMCG_V1 5296 .legacy_cftypes = mem_cgroup_legacy_files, 5297 #endif 5298 .early_init = 0, 5299 }; 5300 5301 /** 5302 * mem_cgroup_calculate_protection - check if memory consumption is in the normal range 5303 * @root: the top ancestor of the sub-tree being checked 5304 * @memcg: the memory cgroup to check 5305 * 5306 * WARNING: This function is not stateless! It can only be used as part 5307 * of a top-down tree iteration, not for isolated queries. 5308 */ 5309 void mem_cgroup_calculate_protection(struct mem_cgroup *root, 5310 struct mem_cgroup *memcg) 5311 { 5312 bool recursive_protection = 5313 cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT; 5314 5315 if (mem_cgroup_disabled()) 5316 return; 5317 5318 if (!root) 5319 root = root_mem_cgroup; 5320 5321 page_counter_calculate_protection(&root->memory, &memcg->memory, recursive_protection); 5322 } 5323 5324 #ifdef CONFIG_LRU_GEN 5325 /** 5326 * mem_cgroup_calculate_protection_path - compute protection along a path 5327 * @root: the top ancestor of the sub-tree being checked (NULL for root_mem_cgroup) 5328 * @memcg: the target memory cgroup 5329 * 5330 * Walk the ancestor path from @root down to @memcg and compute the effective 5331 * protection at each level. This is safe for isolated queries because it 5332 * ensures parents are computed before children. 5333 */ 5334 void mem_cgroup_calculate_protection_path(struct mem_cgroup *root, 5335 struct mem_cgroup *memcg) 5336 { 5337 bool recursive_protection = 5338 cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT; 5339 struct cgroup *cg; 5340 int root_level, i; 5341 5342 if (mem_cgroup_disabled()) 5343 return; 5344 5345 if (!root) 5346 root = root_mem_cgroup; 5347 5348 if (memcg == root) 5349 return; 5350 5351 root_level = root->css.cgroup->level; 5352 cg = memcg->css.cgroup; 5353 5354 rcu_read_lock(); 5355 for (i = root_level + 1; i <= cg->level; i++) { 5356 struct mem_cgroup *cur; 5357 5358 cur = mem_cgroup_from_css(cgroup_css(cg->ancestors[i], 5359 &memory_cgrp_subsys)); 5360 if (cur) 5361 page_counter_calculate_protection(&root->memory, 5362 &cur->memory, 5363 recursive_protection); 5364 } 5365 rcu_read_unlock(); 5366 } 5367 #endif /* CONFIG_LRU_GEN */ 5368 5369 static int charge_memcg(struct folio *folio, struct mem_cgroup *memcg, 5370 gfp_t gfp) 5371 { 5372 int ret = 0; 5373 struct obj_cgroup *objcg; 5374 5375 objcg = get_obj_cgroup_from_memcg(memcg, folio_nid(folio)); 5376 /* Do not account at the root objcg level. */ 5377 if (!obj_cgroup_is_root(objcg)) 5378 ret = try_charge_memcg(memcg, gfp, folio_nr_pages(folio)); 5379 if (ret) { 5380 obj_cgroup_put(objcg); 5381 return ret; 5382 } 5383 commit_charge(folio, objcg); 5384 memcg1_commit_charge(folio, memcg); 5385 5386 return ret; 5387 } 5388 5389 int __mem_cgroup_charge(struct folio *folio, struct mm_struct *mm, gfp_t gfp) 5390 { 5391 struct mem_cgroup *memcg; 5392 int ret; 5393 5394 memcg = get_mem_cgroup_from_mm(mm); 5395 ret = charge_memcg(folio, memcg, gfp); 5396 css_put(&memcg->css); 5397 5398 return ret; 5399 } 5400 5401 /** 5402 * mem_cgroup_charge_hugetlb - charge the memcg for a hugetlb folio 5403 * @folio: folio being charged 5404 * @mm: mm context of the allocation target 5405 * @gfp: reclaim mode 5406 * 5407 * This function is called when allocating a huge page folio, after the page has 5408 * already been obtained and charged to the appropriate hugetlb cgroup 5409 * controller (if it is enabled). 5410 * 5411 * Returns ENOMEM if the memcg is already full. 5412 * Returns 0 if either the charge was successful, or if we skip the charging. 5413 */ 5414 int mem_cgroup_charge_hugetlb(struct folio *folio, struct mm_struct *mm, 5415 gfp_t gfp) 5416 { 5417 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm); 5418 int ret = 0; 5419 5420 /* 5421 * Even memcg does not account for hugetlb, we still want to update 5422 * system-level stats via lruvec_stat_mod_folio. Return 0, and skip 5423 * charging the memcg. 5424 */ 5425 if (mem_cgroup_disabled() || !memcg_accounts_hugetlb() || 5426 !memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys)) 5427 goto out; 5428 5429 if (charge_memcg(folio, memcg, gfp)) 5430 ret = -ENOMEM; 5431 5432 out: 5433 mem_cgroup_put(memcg); 5434 return ret; 5435 } 5436 5437 /** 5438 * mem_cgroup_swapin_charge_folio - Charge a newly allocated folio for swapin. 5439 * @folio: the folio to charge 5440 * @id: memory cgroup id 5441 * @mm: mm context of the victim 5442 * @gfp: reclaim mode 5443 * 5444 * This function charges a folio allocated for swapin. Please call this before 5445 * adding the folio to the swapcache. 5446 * 5447 * Returns 0 on success. Otherwise, an error code is returned. 5448 */ 5449 int mem_cgroup_swapin_charge_folio(struct folio *folio, unsigned short id, 5450 struct mm_struct *mm, gfp_t gfp) 5451 { 5452 struct mem_cgroup *memcg; 5453 int ret; 5454 5455 if (mem_cgroup_disabled()) 5456 return 0; 5457 5458 rcu_read_lock(); 5459 memcg = mem_cgroup_from_private_id(id); 5460 if (!memcg || !css_tryget_online(&memcg->css)) 5461 memcg = get_mem_cgroup_from_mm(mm); 5462 rcu_read_unlock(); 5463 5464 ret = charge_memcg(folio, memcg, gfp); 5465 5466 css_put(&memcg->css); 5467 return ret; 5468 } 5469 5470 struct uncharge_gather { 5471 struct obj_cgroup *objcg; 5472 unsigned long nr_memory; 5473 unsigned long pgpgout; 5474 unsigned long nr_kmem; 5475 }; 5476 5477 static inline void uncharge_gather_clear(struct uncharge_gather *ug) 5478 { 5479 memset(ug, 0, sizeof(*ug)); 5480 } 5481 5482 static void uncharge_batch(const struct uncharge_gather *ug) 5483 { 5484 struct mem_cgroup *memcg; 5485 5486 rcu_read_lock(); 5487 memcg = obj_cgroup_memcg(ug->objcg); 5488 if (ug->nr_memory) { 5489 memcg_uncharge(memcg, ug->nr_memory); 5490 if (ug->nr_kmem) { 5491 mod_memcg_state(memcg, MEMCG_KMEM, -ug->nr_kmem); 5492 memcg1_account_kmem(memcg, -ug->nr_kmem); 5493 } 5494 memcg1_oom_recover(memcg); 5495 } 5496 5497 memcg1_uncharge_batch(memcg, ug->pgpgout, ug->nr_memory); 5498 rcu_read_unlock(); 5499 5500 /* drop reference from uncharge_folio */ 5501 obj_cgroup_put(ug->objcg); 5502 } 5503 5504 static void uncharge_folio(struct folio *folio, struct uncharge_gather *ug) 5505 { 5506 long nr_pages; 5507 struct obj_cgroup *objcg; 5508 5509 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio); 5510 5511 /* 5512 * Nobody should be changing or seriously looking at 5513 * folio objcg at this point, we have fully exclusive 5514 * access to the folio. 5515 */ 5516 objcg = folio_objcg(folio); 5517 if (!objcg) 5518 return; 5519 5520 if (ug->objcg != objcg) { 5521 if (ug->objcg) { 5522 uncharge_batch(ug); 5523 uncharge_gather_clear(ug); 5524 } 5525 ug->objcg = objcg; 5526 5527 /* pairs with obj_cgroup_put in uncharge_batch */ 5528 obj_cgroup_get(objcg); 5529 } 5530 5531 nr_pages = folio_nr_pages(folio); 5532 5533 if (folio_memcg_kmem(folio)) { 5534 ug->nr_memory += nr_pages; 5535 ug->nr_kmem += nr_pages; 5536 } else { 5537 /* LRU pages aren't accounted at the root level */ 5538 if (!obj_cgroup_is_root(objcg)) 5539 ug->nr_memory += nr_pages; 5540 ug->pgpgout++; 5541 5542 WARN_ON_ONCE(folio_unqueue_deferred_split(folio)); 5543 } 5544 5545 folio->memcg_data = 0; 5546 obj_cgroup_put(objcg); 5547 } 5548 5549 void __mem_cgroup_uncharge(struct folio *folio) 5550 { 5551 struct uncharge_gather ug; 5552 5553 /* Don't touch folio->lru of any random page, pre-check: */ 5554 if (!folio_memcg_charged(folio)) 5555 return; 5556 5557 uncharge_gather_clear(&ug); 5558 uncharge_folio(folio, &ug); 5559 uncharge_batch(&ug); 5560 } 5561 5562 void __mem_cgroup_uncharge_folios(struct folio_batch *folios) 5563 { 5564 struct uncharge_gather ug; 5565 unsigned int i; 5566 5567 uncharge_gather_clear(&ug); 5568 for (i = 0; i < folios->nr; i++) 5569 uncharge_folio(folios->folios[i], &ug); 5570 if (ug.objcg) 5571 uncharge_batch(&ug); 5572 } 5573 5574 /* 5575 * An LRU folio must hold the objcg belonging to its own node. 5576 * 5577 * memcg_reparent_objcgs() reparents a dying cgroup one node at a time: the 5578 * folios on that node's LRU lists move to the parent and that node's objcg is 5579 * redirected to the parent, atomically under the node's lru_lock. 5580 * folio_lruvec_lock() relies on this to provide a stable folio<->lruvec 5581 * binding. If a folio holds another node's objcg, its list membership and its 5582 * lruvec resolution change in separate lock sections, and an LRU operation in 5583 * between can re-add the folio to, and strand it on, the LRU list of a dead 5584 * memcg. 5585 * 5586 * So when migration transfers the memcg state to a folio on another node, 5587 * re-derive the objcg for the destination node. If the memcg is dying and the 5588 * destination node has already been reparented, the lookup walks up to the 5589 * nearest live ancestor - which is also where that node's LRU lists went. 5590 * 5591 * Returns the objcg to commit to @new, with a reference for the caller. 5592 */ 5593 static struct obj_cgroup *get_migration_objcg(struct folio *old, 5594 struct folio *new) 5595 { 5596 struct obj_cgroup *old_objcg, *new_objcg; 5597 int new_nid = folio_nid(new); 5598 5599 old_objcg = get_obj_cgroup_from_folio(old); 5600 5601 if (folio_nid(old) == new_nid) 5602 return old_objcg; 5603 5604 rcu_read_lock(); 5605 new_objcg = __get_obj_cgroup_from_memcg(obj_cgroup_memcg(old_objcg), 5606 new_nid); 5607 rcu_read_unlock(); 5608 5609 obj_cgroup_put(old_objcg); 5610 5611 return new_objcg; 5612 } 5613 5614 /** 5615 * mem_cgroup_replace_folio - Charge a folio's replacement. 5616 * @old: Currently circulating folio. 5617 * @new: Replacement folio. 5618 * 5619 * Charge @new as a replacement folio for @old. @old will 5620 * be uncharged upon free. 5621 * 5622 * Both folios must be locked, @new->mapping must be set up. 5623 */ 5624 void mem_cgroup_replace_folio(struct folio *old, struct folio *new) 5625 { 5626 struct mem_cgroup *memcg; 5627 struct obj_cgroup *objcg; 5628 long nr_pages = folio_nr_pages(new); 5629 5630 VM_BUG_ON_FOLIO(!folio_test_locked(old), old); 5631 VM_BUG_ON_FOLIO(!folio_test_locked(new), new); 5632 VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new); 5633 VM_BUG_ON_FOLIO(folio_nr_pages(old) != nr_pages, new); 5634 5635 if (mem_cgroup_disabled()) 5636 return; 5637 5638 /* Page cache replacement: new folio already charged? */ 5639 if (folio_memcg_charged(new)) 5640 return; 5641 5642 VM_WARN_ON_ONCE_FOLIO(!folio_objcg(old), old); 5643 if (!folio_objcg(old)) 5644 return; 5645 5646 objcg = get_migration_objcg(old, new); 5647 5648 rcu_read_lock(); 5649 memcg = obj_cgroup_memcg(objcg); 5650 5651 /* 5652 * Force-charge the new page. The old one will be freed soon. 5653 * 5654 * The rootness of the committed objcg decides whether the final 5655 * uncharge of @new goes through the page counters (see 5656 * uncharge_folio()); charge them only if the uncharge will. 5657 */ 5658 if (!obj_cgroup_is_root(objcg)) { 5659 page_counter_charge(&memcg->memory, nr_pages); 5660 if (do_memsw_account()) 5661 page_counter_charge(&memcg->memsw, nr_pages); 5662 } 5663 5664 commit_charge(new, objcg); 5665 memcg1_commit_charge(new, memcg); 5666 rcu_read_unlock(); 5667 } 5668 5669 /** 5670 * mem_cgroup_migrate - Transfer the memcg data from the old to the new folio. 5671 * @old: Currently circulating folio. 5672 * @new: Replacement folio. 5673 * 5674 * Transfer the memcg data from the old folio to the new folio for migration. 5675 * The old folio's data info will be cleared. The memory counters remain 5676 * unchanged, unless the charge moves out of a fully reparented ancestry 5677 * and has to be settled (see below). 5678 * 5679 * Both folios must be locked, @new->mapping must be set up. 5680 */ 5681 void mem_cgroup_migrate(struct folio *old, struct folio *new) 5682 { 5683 struct obj_cgroup *objcg, *new_objcg; 5684 5685 VM_BUG_ON_FOLIO(!folio_test_locked(old), old); 5686 VM_BUG_ON_FOLIO(!folio_test_locked(new), new); 5687 VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new); 5688 VM_BUG_ON_FOLIO(folio_nr_pages(old) != folio_nr_pages(new), new); 5689 VM_BUG_ON_FOLIO(folio_test_lru(old), old); 5690 5691 if (mem_cgroup_disabled()) 5692 return; 5693 5694 objcg = folio_objcg(old); 5695 /* 5696 * Note that it is normal to see !objcg for a hugetlb folio. 5697 * For e.g, it could have been allocated when memory_hugetlb_accounting 5698 * was not selected. 5699 */ 5700 VM_WARN_ON_ONCE_FOLIO(!folio_test_hugetlb(old) && !objcg, old); 5701 if (!objcg) 5702 return; 5703 5704 new_objcg = get_migration_objcg(old, new); 5705 5706 /* 5707 * @old was charged through a non-root objcg, so its charge is in the 5708 * page counters. If the re-derivation walked up to the root objcg - 5709 * @old's entire ancestry is dying and already reparented - the final 5710 * uncharge of @new will skip the page counters (see uncharge_folio()). 5711 * Settle them now: this is @old's eventual uncharge, moved up to the 5712 * point where its charge record ends. 5713 */ 5714 if (obj_cgroup_is_root(new_objcg) && !obj_cgroup_is_root(objcg)) { 5715 rcu_read_lock(); 5716 memcg_uncharge(obj_cgroup_memcg(objcg), folio_nr_pages(old)); 5717 rcu_read_unlock(); 5718 } 5719 5720 commit_charge(new, new_objcg); 5721 5722 /* Warning should never happen, so don't worry about refcount non-0 */ 5723 WARN_ON_ONCE(folio_unqueue_deferred_split(old)); 5724 old->memcg_data = 0; 5725 5726 /* @new holds its own reference now, drop @old's */ 5727 obj_cgroup_put(objcg); 5728 } 5729 5730 DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key); 5731 EXPORT_SYMBOL(memcg_sockets_enabled_key); 5732 5733 void mem_cgroup_sk_alloc(struct sock *sk) 5734 { 5735 struct mem_cgroup *memcg; 5736 5737 if (!mem_cgroup_sockets_enabled) 5738 return; 5739 5740 /* Do not associate the sock with unrelated interrupted task's memcg. */ 5741 if (!in_task()) 5742 return; 5743 5744 rcu_read_lock(); 5745 memcg = mem_cgroup_from_task(current); 5746 if (mem_cgroup_is_root(memcg)) 5747 goto out; 5748 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg1_tcpmem_active(memcg)) 5749 goto out; 5750 if (css_tryget(&memcg->css)) 5751 sk->sk_memcg = memcg; 5752 out: 5753 rcu_read_unlock(); 5754 } 5755 5756 void mem_cgroup_sk_free(struct sock *sk) 5757 { 5758 struct mem_cgroup *memcg = mem_cgroup_from_sk(sk); 5759 5760 if (memcg) 5761 css_put(&memcg->css); 5762 } 5763 5764 void mem_cgroup_sk_inherit(const struct sock *sk, struct sock *newsk) 5765 { 5766 struct mem_cgroup *memcg; 5767 5768 if (sk->sk_memcg == newsk->sk_memcg) 5769 return; 5770 5771 mem_cgroup_sk_free(newsk); 5772 5773 memcg = mem_cgroup_from_sk(sk); 5774 if (memcg) 5775 css_get(&memcg->css); 5776 5777 newsk->sk_memcg = sk->sk_memcg; 5778 } 5779 5780 /** 5781 * mem_cgroup_sk_charge - charge socket memory 5782 * @sk: socket in memcg to charge 5783 * @nr_pages: number of pages to charge 5784 * @gfp_mask: reclaim mode 5785 * 5786 * Charges @nr_pages to @memcg. Returns %true if the charge fit within 5787 * @memcg's configured limit, %false if it doesn't. 5788 */ 5789 bool mem_cgroup_sk_charge(const struct sock *sk, unsigned int nr_pages, 5790 gfp_t gfp_mask) 5791 { 5792 struct mem_cgroup *memcg = mem_cgroup_from_sk(sk); 5793 5794 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) 5795 return memcg1_charge_skmem(memcg, nr_pages, gfp_mask); 5796 5797 if (try_charge_memcg(memcg, gfp_mask, nr_pages) == 0) { 5798 mod_memcg_state(memcg, MEMCG_SOCK, nr_pages); 5799 return true; 5800 } 5801 5802 return false; 5803 } 5804 5805 /** 5806 * mem_cgroup_sk_uncharge - uncharge socket memory 5807 * @sk: socket in memcg to uncharge 5808 * @nr_pages: number of pages to uncharge 5809 */ 5810 void mem_cgroup_sk_uncharge(const struct sock *sk, unsigned int nr_pages) 5811 { 5812 struct mem_cgroup *memcg = mem_cgroup_from_sk(sk); 5813 5814 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) { 5815 memcg1_uncharge_skmem(memcg, nr_pages); 5816 return; 5817 } 5818 5819 mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages); 5820 5821 refill_stock(memcg, nr_pages); 5822 } 5823 5824 void mem_cgroup_flush_workqueue(void) 5825 { 5826 flush_workqueue(memcg_wq); 5827 } 5828 5829 static int __init cgroup_memory(char *s) 5830 { 5831 char *token; 5832 5833 while ((token = strsep(&s, ",")) != NULL) { 5834 if (!*token) 5835 continue; 5836 if (!strcmp(token, "nosocket")) 5837 cgroup_memory_nosocket = true; 5838 if (!strcmp(token, "nokmem")) 5839 cgroup_memory_nokmem = true; 5840 if (!strcmp(token, "nobpf")) 5841 cgroup_memory_nobpf = true; 5842 } 5843 return 1; 5844 } 5845 __setup("cgroup.memory=", cgroup_memory); 5846 5847 /* 5848 * Memory controller init before cgroup_init() initialize root_mem_cgroup. 5849 * 5850 * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this 5851 * context because of lock dependencies (cgroup_lock -> cpu hotplug) but 5852 * basically everything that doesn't depend on a specific mem_cgroup structure 5853 * should be initialized from here. 5854 */ 5855 /* 5856 * Fields are grouped by access pattern. Putting a field in the wrong group 5857 * breaks the build here. 5858 */ 5859 static void __init memcg_struct_check(void) 5860 { 5861 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_write_hot, 5862 socket_pressure); 5863 #if BITS_PER_LONG < 64 5864 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_write_hot, 5865 socket_pressure_seqlock); 5866 #endif 5867 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_write_hot, 5868 memory_events); 5869 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_write_hot, 5870 memory_events_local); 5871 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_write_hot, 5872 vmpressure); 5873 #ifdef CONFIG_MEMCG_NMI_SAFETY_REQUIRES_ATOMIC 5874 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_write_hot, 5875 kmem_stat); 5876 #endif 5877 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_write_hot, 5878 high_irq_work); 5879 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_write_hot, 5880 high_work); 5881 5882 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_cold, 5883 memory_peaks); 5884 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_cold, 5885 swap_peaks); 5886 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_cold, 5887 peaks_lock); 5888 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_cold, 5889 events_file); 5890 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_cold, 5891 events_local_file); 5892 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_cold, 5893 swap_events_file); 5894 #ifdef CONFIG_CGROUP_WRITEBACK 5895 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_cold, 5896 cgwb_list); 5897 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_cold, 5898 cgwb_domain); 5899 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_cold, 5900 cgwb_frn); 5901 #endif 5902 #ifdef CONFIG_LRU_GEN_WALKS_MMU 5903 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_cold, 5904 mm_list); 5905 #endif 5906 5907 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_read_mostly, 5908 vmstats_percpu); 5909 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_read_mostly, 5910 vmstats); 5911 #ifdef CONFIG_ZSWAP 5912 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_read_mostly, 5913 zswap_max); 5914 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_read_mostly, 5915 zswap_writeback); 5916 #endif 5917 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_read_mostly, 5918 private_id_objcg); 5919 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_read_mostly, 5920 private_id); 5921 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_read_mostly, 5922 kmemcg_id); 5923 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_read_mostly, 5924 oom_group); 5925 5926 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup_per_node, 5927 memcg_pn_read_mostly, memcg); 5928 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup_per_node, 5929 memcg_pn_read_mostly, lruvec_stats_percpu); 5930 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup_per_node, 5931 memcg_pn_read_mostly, lruvec_stats); 5932 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup_per_node, 5933 memcg_pn_read_mostly, shrinker_info); 5934 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup_per_node, 5935 memcg_pn_read_mostly, objcg); 5936 5937 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup_per_node, 5938 memcg_pn_lruvec, lruvec); 5939 5940 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup_per_node, 5941 memcg_pn_write_hot, lru_zone_size); 5942 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup_per_node, 5943 memcg_pn_write_hot, iter); 5944 #ifdef CONFIG_MEMCG_NMI_SAFETY_REQUIRES_ATOMIC 5945 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup_per_node, 5946 memcg_pn_write_hot, slab_reclaimable); 5947 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup_per_node, 5948 memcg_pn_write_hot, slab_unreclaimable); 5949 #endif 5950 5951 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup_per_node, 5952 memcg_pn_cold, orig_objcg); 5953 CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup_per_node, 5954 memcg_pn_cold, objcg_list); 5955 } 5956 5957 int __init mem_cgroup_init(void) 5958 { 5959 unsigned int memcg_size; 5960 int cpu; 5961 5962 /* 5963 * Currently s32 type (can refer to struct batched_lruvec_stat) is 5964 * used for per-memcg-per-cpu caching of per-node statistics. In order 5965 * to work fine, we should make sure that the overfill threshold can't 5966 * exceed S32_MAX / PAGE_SIZE. 5967 */ 5968 BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE); 5969 5970 memcg_struct_check(); 5971 5972 cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL, 5973 memcg_hotplug_cpu_dead); 5974 5975 memcg_wq = alloc_workqueue("memcg", WQ_PERCPU, 0); 5976 WARN_ON(!memcg_wq); 5977 5978 for_each_possible_cpu(cpu) { 5979 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work, 5980 drain_local_memcg_stock); 5981 INIT_WORK(&per_cpu_ptr(&obj_stock, cpu)->work, 5982 drain_local_obj_stock); 5983 } 5984 5985 memcg_size = struct_size_t(struct mem_cgroup, nodeinfo, nr_node_ids); 5986 memcg_cachep = kmem_cache_create("mem_cgroup", memcg_size, 0, 5987 SLAB_PANIC | SLAB_HWCACHE_ALIGN, NULL); 5988 5989 memcg_pn_cachep = KMEM_CACHE(mem_cgroup_per_node, 5990 SLAB_PANIC | SLAB_HWCACHE_ALIGN); 5991 5992 shrinker_unit_cache_init(); 5993 5994 return 0; 5995 } 5996 5997 #ifdef CONFIG_SWAP 5998 /** 5999 * __mem_cgroup_try_charge_swap - try charging swap space for a folio 6000 * @folio: folio being added to swap 6001 * 6002 * Try to charge @folio's memcg for the swap space at folio->swap. 6003 * 6004 * Returns 0 on success, -ENOMEM on failure. 6005 */ 6006 int __mem_cgroup_try_charge_swap(struct folio *folio) 6007 { 6008 unsigned int nr_pages = folio_nr_pages(folio); 6009 struct swap_cluster_info *ci; 6010 struct page_counter *counter; 6011 struct mem_cgroup *memcg; 6012 struct obj_cgroup *objcg; 6013 unsigned short private_id; 6014 6015 if (do_memsw_account()) 6016 return 0; 6017 6018 objcg = folio_objcg(folio); 6019 VM_WARN_ON_ONCE_FOLIO(!objcg, folio); 6020 if (!objcg) 6021 return 0; 6022 6023 scoped_guard(rcu) { 6024 memcg = obj_cgroup_memcg(objcg); 6025 if (!folio_test_swapcache(folio)) { 6026 memcg_memory_event(memcg, MEMCG_SWAP_FAIL); 6027 return 0; 6028 } 6029 6030 private_id = mem_cgroup_private_id_get(memcg, nr_pages); 6031 6032 if (!mem_cgroup_private_id_is_root(private_id) && 6033 !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) { 6034 memcg_memory_event(memcg, MEMCG_SWAP_MAX); 6035 memcg_memory_event(memcg, MEMCG_SWAP_FAIL); 6036 mem_cgroup_private_id_put(private_id, nr_pages); 6037 return -ENOMEM; 6038 } 6039 mod_memcg_state(memcg, MEMCG_SWAP, nr_pages); 6040 } 6041 6042 ci = swap_cluster_get_and_lock(folio); 6043 __swap_cgroup_set(ci, swp_cluster_offset(folio->swap), nr_pages, private_id); 6044 swap_cluster_unlock(ci); 6045 6046 return 0; 6047 } 6048 6049 /** 6050 * __mem_cgroup_uncharge_swap - uncharge swap space 6051 * @id: cgroup id to uncharge 6052 * @nr_pages: the amount of swap space to uncharge 6053 */ 6054 void __mem_cgroup_uncharge_swap(unsigned short id, unsigned int nr_pages) 6055 { 6056 struct obj_cgroup *objcg; 6057 struct mem_cgroup *memcg; 6058 6059 rcu_read_lock(); 6060 objcg = obj_cgroup_from_private_id(id); 6061 memcg = obj_cgroup_memcg(objcg); 6062 if (memcg) { 6063 if (!mem_cgroup_private_id_is_root(id)) { 6064 if (do_memsw_account()) 6065 page_counter_uncharge(&memcg->memsw, nr_pages); 6066 else 6067 page_counter_uncharge(&memcg->swap, nr_pages); 6068 } 6069 mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages); 6070 __mem_cgroup_private_id_put(objcg, id, nr_pages); 6071 } 6072 rcu_read_unlock(); 6073 } 6074 6075 long mem_cgroup_get_nr_swap_pages(const struct mem_cgroup *memcg) 6076 { 6077 long nr_swap_pages = get_nr_swap_pages(); 6078 6079 if (!mem_cgroup_disabled() && !do_memsw_account()) 6080 nr_swap_pages = min(nr_swap_pages, page_counter_margin(&memcg->swap)); 6081 6082 return nr_swap_pages; 6083 } 6084 6085 /** 6086 * mem_cgroup_get_folio_swap_margin - get a folio's memcg swap margin 6087 * @folio: folio whose memcg margin is queried 6088 * 6089 * Return: Remaining chargeable pages in the folio's memcg hierarchy. 6090 */ 6091 long mem_cgroup_get_folio_swap_margin(const struct folio *folio) 6092 { 6093 struct mem_cgroup *memcg; 6094 long margin; 6095 6096 if (mem_cgroup_disabled() || do_memsw_account() || 6097 !folio_memcg_charged(folio)) 6098 return PAGE_COUNTER_MAX; 6099 6100 rcu_read_lock(); 6101 memcg = folio_memcg(folio); 6102 margin = page_counter_margin(&memcg->swap); 6103 rcu_read_unlock(); 6104 6105 return margin; 6106 } 6107 6108 bool mem_cgroup_swap_full(const struct folio *folio) 6109 { 6110 struct mem_cgroup *memcg; 6111 bool ret = false; 6112 6113 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); 6114 6115 if (vm_swap_full()) 6116 return true; 6117 if (do_memsw_account() || !folio_memcg_charged(folio)) 6118 return ret; 6119 6120 rcu_read_lock(); 6121 memcg = folio_memcg(folio); 6122 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) { 6123 unsigned long usage = page_counter_read(&memcg->swap); 6124 6125 if (usage * 2 >= READ_ONCE(memcg->swap.high) || 6126 usage * 2 >= READ_ONCE(memcg->swap.max)) { 6127 ret = true; 6128 break; 6129 } 6130 } 6131 rcu_read_unlock(); 6132 6133 return ret; 6134 } 6135 6136 static int __init setup_swap_account(char *s) 6137 { 6138 bool res; 6139 6140 if (!kstrtobool(s, &res) && !res) 6141 pr_warn_once("The swapaccount=0 commandline option is deprecated " 6142 "in favor of configuring swap control via cgroupfs. " 6143 "Please report your usecase to linux-mm@kvack.org if you " 6144 "depend on this functionality.\n"); 6145 return 1; 6146 } 6147 __setup("swapaccount=", setup_swap_account); 6148 6149 static u64 swap_current_read(struct cgroup_subsys_state *css, 6150 struct cftype *cft) 6151 { 6152 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 6153 6154 return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE; 6155 } 6156 6157 static int swap_peak_show(struct seq_file *sf, void *v) 6158 { 6159 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(sf)); 6160 6161 guard(spinlock)(&memcg->peaks_lock); 6162 return peak_show(sf, v, &memcg->swap); 6163 } 6164 6165 static ssize_t swap_peak_write(struct kernfs_open_file *of, char *buf, 6166 size_t nbytes, loff_t off) 6167 { 6168 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 6169 6170 return peak_write(of, buf, nbytes, off, &memcg->swap, 6171 &memcg->swap_peaks); 6172 } 6173 6174 static int swap_high_show(struct seq_file *m, void *v) 6175 { 6176 return seq_puts_memcg_tunable(m, 6177 READ_ONCE(mem_cgroup_from_seq(m)->swap.high)); 6178 } 6179 6180 static ssize_t swap_high_write(struct kernfs_open_file *of, 6181 char *buf, size_t nbytes, loff_t off) 6182 { 6183 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 6184 unsigned long high; 6185 int err; 6186 6187 buf = strstrip(buf); 6188 err = page_counter_memparse(buf, "max", &high); 6189 if (err) 6190 return err; 6191 6192 page_counter_set_high(&memcg->swap, high); 6193 6194 return nbytes; 6195 } 6196 6197 static int swap_max_show(struct seq_file *m, void *v) 6198 { 6199 return seq_puts_memcg_tunable(m, 6200 READ_ONCE(mem_cgroup_from_seq(m)->swap.max)); 6201 } 6202 6203 static ssize_t swap_max_write(struct kernfs_open_file *of, 6204 char *buf, size_t nbytes, loff_t off) 6205 { 6206 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 6207 unsigned long max; 6208 int err; 6209 6210 buf = strstrip(buf); 6211 err = page_counter_memparse(buf, "max", &max); 6212 if (err) 6213 return err; 6214 6215 xchg(&memcg->swap.max, max); 6216 6217 return nbytes; 6218 } 6219 6220 static int swap_events_show(struct seq_file *m, void *v) 6221 { 6222 struct mem_cgroup *memcg = mem_cgroup_from_seq(m); 6223 6224 seq_printf(m, "high %lu\n", 6225 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH])); 6226 seq_printf(m, "max %lu\n", 6227 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX])); 6228 seq_printf(m, "fail %lu\n", 6229 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL])); 6230 6231 return 0; 6232 } 6233 6234 static struct cftype swap_files[] = { 6235 { 6236 .name = "swap.current", 6237 .flags = CFTYPE_NOT_ON_ROOT, 6238 .read_u64 = swap_current_read, 6239 }, 6240 { 6241 .name = "swap.high", 6242 .flags = CFTYPE_NOT_ON_ROOT, 6243 .seq_show = swap_high_show, 6244 .write = swap_high_write, 6245 }, 6246 { 6247 .name = "swap.max", 6248 .flags = CFTYPE_NOT_ON_ROOT, 6249 .seq_show = swap_max_show, 6250 .write = swap_max_write, 6251 }, 6252 { 6253 .name = "swap.peak", 6254 .flags = CFTYPE_NOT_ON_ROOT, 6255 .open = peak_open, 6256 .release = peak_release, 6257 .seq_show = swap_peak_show, 6258 .write = swap_peak_write, 6259 }, 6260 { 6261 .name = "swap.events", 6262 .flags = CFTYPE_NOT_ON_ROOT, 6263 .file_offset = offsetof(struct mem_cgroup, swap_events_file), 6264 .seq_show = swap_events_show, 6265 }, 6266 { } /* terminate */ 6267 }; 6268 6269 #ifdef CONFIG_ZSWAP 6270 /** 6271 * obj_cgroup_may_zswap - check if this cgroup can zswap 6272 * @objcg: the object cgroup 6273 * 6274 * Check if the hierarchical zswap limit has been reached. 6275 * 6276 * This doesn't check for specific headroom, and it is not atomic 6277 * either. But with zswap, the size of the allocation is only known 6278 * once compression has occurred, and this optimistic pre-check avoids 6279 * spending cycles on compression when there is already no room left 6280 * or zswap is disabled altogether somewhere in the hierarchy. 6281 */ 6282 bool obj_cgroup_may_zswap(struct obj_cgroup *objcg) 6283 { 6284 struct mem_cgroup *memcg, *original_memcg; 6285 bool ret = true; 6286 6287 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) 6288 return true; 6289 6290 original_memcg = get_mem_cgroup_from_objcg(objcg); 6291 for (memcg = original_memcg; !mem_cgroup_is_root(memcg); 6292 memcg = parent_mem_cgroup(memcg)) { 6293 unsigned long max = READ_ONCE(memcg->zswap_max); 6294 unsigned long pages; 6295 6296 if (max == PAGE_COUNTER_MAX) 6297 continue; 6298 if (max == 0) { 6299 ret = false; 6300 break; 6301 } 6302 6303 /* Force flush to get accurate stats for charging */ 6304 __mem_cgroup_flush_stats(memcg, true); 6305 pages = memcg_page_state(memcg, MEMCG_ZSWAP_B) / PAGE_SIZE; 6306 if (pages < max) 6307 continue; 6308 ret = false; 6309 break; 6310 } 6311 mem_cgroup_put(original_memcg); 6312 return ret; 6313 } 6314 6315 /** 6316 * obj_cgroup_charge_zswap - charge compression backend memory 6317 * @objcg: the object cgroup 6318 * @size: size of compressed object 6319 * 6320 * This forces the charge after obj_cgroup_may_zswap() allowed 6321 * compression and storage in zswap for this cgroup to go ahead. 6322 */ 6323 void obj_cgroup_charge_zswap(struct obj_cgroup *objcg, size_t size) 6324 { 6325 struct mem_cgroup *memcg; 6326 6327 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) 6328 return; 6329 6330 if (obj_cgroup_is_root(objcg)) 6331 return; 6332 6333 VM_WARN_ON_ONCE(!(current->flags & PF_MEMALLOC)); 6334 6335 /* PF_MEMALLOC context, charging must succeed */ 6336 if (obj_cgroup_charge(objcg, GFP_KERNEL, size)) 6337 VM_WARN_ON_ONCE(1); 6338 6339 rcu_read_lock(); 6340 memcg = obj_cgroup_memcg(objcg); 6341 mod_memcg_state(memcg, MEMCG_ZSWAP_B, size); 6342 mod_memcg_state(memcg, MEMCG_ZSWAPPED, 1); 6343 if (size == PAGE_SIZE) 6344 mod_memcg_state(memcg, MEMCG_ZSWAP_INCOMP, 1); 6345 rcu_read_unlock(); 6346 } 6347 6348 /** 6349 * obj_cgroup_uncharge_zswap - uncharge compression backend memory 6350 * @objcg: the object cgroup 6351 * @size: size of compressed object 6352 * 6353 * Uncharges zswap memory on page in. 6354 */ 6355 void obj_cgroup_uncharge_zswap(struct obj_cgroup *objcg, size_t size) 6356 { 6357 struct mem_cgroup *memcg; 6358 6359 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) 6360 return; 6361 6362 if (obj_cgroup_is_root(objcg)) 6363 return; 6364 6365 obj_cgroup_uncharge(objcg, size); 6366 6367 rcu_read_lock(); 6368 memcg = obj_cgroup_memcg(objcg); 6369 mod_memcg_state(memcg, MEMCG_ZSWAP_B, -size); 6370 mod_memcg_state(memcg, MEMCG_ZSWAPPED, -1); 6371 if (size == PAGE_SIZE) 6372 mod_memcg_state(memcg, MEMCG_ZSWAP_INCOMP, -1); 6373 rcu_read_unlock(); 6374 } 6375 6376 bool mem_cgroup_zswap_writeback_enabled(const struct mem_cgroup *memcg) 6377 { 6378 /* if zswap is disabled, do not block pages going to the swapping device */ 6379 if (!zswap_is_enabled()) 6380 return true; 6381 6382 for (; memcg; memcg = parent_mem_cgroup(memcg)) 6383 if (!READ_ONCE(memcg->zswap_writeback)) 6384 return false; 6385 6386 return true; 6387 } 6388 6389 static u64 zswap_current_read(struct cgroup_subsys_state *css, 6390 struct cftype *cft) 6391 { 6392 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 6393 6394 mem_cgroup_flush_stats(memcg); 6395 return memcg_page_state(memcg, MEMCG_ZSWAP_B); 6396 } 6397 6398 static int zswap_max_show(struct seq_file *m, void *v) 6399 { 6400 return seq_puts_memcg_tunable(m, 6401 READ_ONCE(mem_cgroup_from_seq(m)->zswap_max)); 6402 } 6403 6404 static ssize_t zswap_max_write(struct kernfs_open_file *of, 6405 char *buf, size_t nbytes, loff_t off) 6406 { 6407 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 6408 unsigned long max; 6409 int err; 6410 6411 buf = strstrip(buf); 6412 err = page_counter_memparse(buf, "max", &max); 6413 if (err) 6414 return err; 6415 6416 xchg(&memcg->zswap_max, max); 6417 6418 return nbytes; 6419 } 6420 6421 static int zswap_writeback_show(struct seq_file *m, void *v) 6422 { 6423 struct mem_cgroup *memcg = mem_cgroup_from_seq(m); 6424 6425 seq_printf(m, "%d\n", READ_ONCE(memcg->zswap_writeback)); 6426 return 0; 6427 } 6428 6429 static ssize_t zswap_writeback_write(struct kernfs_open_file *of, 6430 char *buf, size_t nbytes, loff_t off) 6431 { 6432 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 6433 int zswap_writeback; 6434 ssize_t parse_ret = kstrtoint(strstrip(buf), 0, &zswap_writeback); 6435 6436 if (parse_ret) 6437 return parse_ret; 6438 6439 if (zswap_writeback != 0 && zswap_writeback != 1) 6440 return -EINVAL; 6441 6442 WRITE_ONCE(memcg->zswap_writeback, zswap_writeback); 6443 return nbytes; 6444 } 6445 6446 static struct cftype zswap_files[] = { 6447 { 6448 .name = "zswap.current", 6449 .flags = CFTYPE_NOT_ON_ROOT, 6450 .read_u64 = zswap_current_read, 6451 }, 6452 { 6453 .name = "zswap.max", 6454 .flags = CFTYPE_NOT_ON_ROOT, 6455 .seq_show = zswap_max_show, 6456 .write = zswap_max_write, 6457 }, 6458 { 6459 .name = "zswap.writeback", 6460 .seq_show = zswap_writeback_show, 6461 .write = zswap_writeback_write, 6462 }, 6463 { } /* terminate */ 6464 }; 6465 #endif /* CONFIG_ZSWAP */ 6466 6467 static int __init mem_cgroup_swap_init(void) 6468 { 6469 if (mem_cgroup_disabled()) 6470 return 0; 6471 6472 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files)); 6473 #ifdef CONFIG_MEMCG_V1 6474 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files)); 6475 #endif 6476 #ifdef CONFIG_ZSWAP 6477 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, zswap_files)); 6478 #endif 6479 return 0; 6480 } 6481 subsys_initcall(mem_cgroup_swap_init); 6482 6483 #endif /* CONFIG_SWAP */ 6484 6485 void mem_cgroup_node_filter_allowed(struct mem_cgroup *memcg, nodemask_t *mask) 6486 { 6487 nodemask_t allowed; 6488 6489 if (!memcg) 6490 return; 6491 6492 /* 6493 * Since this interface is intended for use by migration paths, and 6494 * reclaim and migration are subject to race conditions such as changes 6495 * in effective_mems and hot-unpluging of nodes, inaccurate allowed 6496 * mask is acceptable. 6497 */ 6498 cpuset_nodes_allowed(memcg->css.cgroup, &allowed); 6499 nodes_and(*mask, *mask, allowed); 6500 } 6501 6502 void mem_cgroup_show_protected_memory(struct mem_cgroup *memcg) 6503 { 6504 if (mem_cgroup_disabled() || !cgroup_subsys_on_dfl(memory_cgrp_subsys)) 6505 return; 6506 6507 if (!memcg) 6508 memcg = root_mem_cgroup; 6509 6510 pr_warn("Memory cgroup min protection %lukB -- low protection %lukB", 6511 K(atomic_long_read(&memcg->memory.children_min_usage)), 6512 K(atomic_long_read(&memcg->memory.children_low_usage))); 6513 } 6514