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