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 unsigned int off; 2874 2875 obj_exts = slab_obj_exts(slab); 2876 if (!obj_exts) 2877 return NULL; 2878 2879 get_slab_obj_exts(obj_exts); 2880 off = obj_to_index(slab->slab_cache, slab, p); 2881 obj_ext = slab_obj_ext(slab, obj_exts, off); 2882 if (obj_ext->objcg) { 2883 struct obj_cgroup *objcg = obj_ext->objcg; 2884 2885 put_slab_obj_exts(obj_exts); 2886 return obj_cgroup_memcg(objcg); 2887 } 2888 put_slab_obj_exts(obj_exts); 2889 2890 return NULL; 2891 } 2892 2893 /* 2894 * Returns a pointer to the memory cgroup to which the kernel object is charged. 2895 * It is not suitable for objects allocated using vmalloc(). 2896 * 2897 * A passed kernel object must be a slab object or a generic kernel page. 2898 * 2899 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(), 2900 * cgroup_mutex, etc. 2901 */ 2902 struct mem_cgroup *mem_cgroup_from_virt(void *p) 2903 { 2904 struct slab *slab; 2905 2906 if (mem_cgroup_disabled()) 2907 return NULL; 2908 2909 slab = virt_to_slab(p); 2910 if (slab) 2911 return mem_cgroup_from_obj_slab(slab, p); 2912 return folio_memcg_check(virt_to_folio(p)); 2913 } 2914 2915 static struct obj_cgroup *__get_obj_cgroup_from_memcg(struct mem_cgroup *memcg, 2916 int nid) 2917 { 2918 for (; memcg; memcg = parent_mem_cgroup(memcg)) { 2919 struct obj_cgroup *objcg = rcu_dereference(memcg->nodeinfo[nid]->objcg); 2920 2921 if (likely(objcg && obj_cgroup_tryget(objcg))) 2922 return objcg; 2923 } 2924 2925 return NULL; 2926 } 2927 2928 static inline struct obj_cgroup *get_obj_cgroup_from_memcg(struct mem_cgroup *memcg, 2929 int nid) 2930 { 2931 struct obj_cgroup *objcg; 2932 2933 rcu_read_lock(); 2934 objcg = __get_obj_cgroup_from_memcg(memcg, nid); 2935 rcu_read_unlock(); 2936 2937 return objcg; 2938 } 2939 2940 static struct obj_cgroup *current_objcg_update(void) 2941 { 2942 struct mem_cgroup *memcg; 2943 struct obj_cgroup *old, *objcg = NULL; 2944 2945 do { 2946 /* Atomically drop the update bit. */ 2947 old = xchg(¤t->objcg, NULL); 2948 if (old) { 2949 old = (struct obj_cgroup *) 2950 ((unsigned long)old & ~CURRENT_OBJCG_UPDATE_FLAG); 2951 obj_cgroup_put(old); 2952 2953 old = NULL; 2954 } 2955 2956 /* If new objcg is NULL, no reason for the second atomic update. */ 2957 if (!current->mm || (current->flags & PF_KTHREAD)) 2958 return NULL; 2959 2960 /* 2961 * Release the objcg pointer from the previous iteration, 2962 * if try_cmpxcg() below fails. 2963 */ 2964 if (unlikely(objcg)) { 2965 obj_cgroup_put(objcg); 2966 objcg = NULL; 2967 } 2968 2969 /* 2970 * Obtain the new objcg pointer. The current task can be 2971 * asynchronously moved to another memcg and the previous 2972 * memcg can be offlined. So let's get the memcg pointer 2973 * and try get a reference to objcg under a rcu read lock. 2974 */ 2975 2976 rcu_read_lock(); 2977 memcg = mem_cgroup_from_task(current); 2978 objcg = __get_obj_cgroup_from_memcg(memcg, numa_node_id()); 2979 rcu_read_unlock(); 2980 2981 /* 2982 * Try set up a new objcg pointer atomically. If it 2983 * fails, it means the update flag was set concurrently, so 2984 * the whole procedure should be repeated. 2985 */ 2986 } while (!try_cmpxchg(¤t->objcg, &old, objcg)); 2987 2988 return objcg; 2989 } 2990 2991 __always_inline struct obj_cgroup *current_obj_cgroup(void) 2992 { 2993 struct mem_cgroup *memcg; 2994 struct obj_cgroup *objcg; 2995 int nid = numa_node_id(); 2996 2997 if (IS_ENABLED(CONFIG_MEMCG_NMI_UNSAFE) && in_nmi()) 2998 return NULL; 2999 3000 if (in_task()) { 3001 memcg = current->active_memcg; 3002 if (unlikely(memcg)) 3003 goto from_memcg; 3004 3005 objcg = READ_ONCE(current->objcg); 3006 if (unlikely((unsigned long)objcg & CURRENT_OBJCG_UPDATE_FLAG)) 3007 objcg = current_objcg_update(); 3008 /* 3009 * Objcg reference is kept by the task, so it's safe 3010 * to use the objcg by the current task. 3011 */ 3012 return objcg ? : rcu_dereference_check(root_mem_cgroup->nodeinfo[nid]->objcg, 1); 3013 } 3014 3015 memcg = this_cpu_read(int_active_memcg); 3016 if (unlikely(memcg)) 3017 goto from_memcg; 3018 3019 return rcu_dereference_check(root_mem_cgroup->nodeinfo[nid]->objcg, 1); 3020 3021 from_memcg: 3022 for (; memcg; memcg = parent_mem_cgroup(memcg)) { 3023 /* 3024 * Memcg pointer is protected by scope (see set_active_memcg()) 3025 * and is pinning the corresponding objcg, so objcg can't go 3026 * away and can be used within the scope without any additional 3027 * protection. 3028 */ 3029 objcg = rcu_dereference_check(memcg->nodeinfo[nid]->objcg, 1); 3030 if (likely(objcg)) 3031 return objcg; 3032 } 3033 3034 return rcu_dereference_check(root_mem_cgroup->nodeinfo[nid]->objcg, 1); 3035 } 3036 3037 struct obj_cgroup *get_obj_cgroup_from_folio(struct folio *folio) 3038 { 3039 struct obj_cgroup *objcg; 3040 3041 objcg = folio_objcg(folio); 3042 if (objcg) 3043 obj_cgroup_get(objcg); 3044 3045 return objcg; 3046 } 3047 3048 #ifdef CONFIG_MEMCG_NMI_SAFETY_REQUIRES_ATOMIC 3049 static inline void account_kmem_nmi_safe(struct mem_cgroup *memcg, int val) 3050 { 3051 if (likely(!in_nmi())) { 3052 mod_memcg_state(memcg, MEMCG_KMEM, val); 3053 } else { 3054 /* preemption is disabled in_nmi(). */ 3055 __css_rstat_updated(&memcg->css, smp_processor_id()); 3056 atomic_add(val, &memcg->kmem_stat); 3057 } 3058 } 3059 #else 3060 static inline void account_kmem_nmi_safe(struct mem_cgroup *memcg, int val) 3061 { 3062 mod_memcg_state(memcg, MEMCG_KMEM, val); 3063 } 3064 #endif 3065 3066 /* 3067 * obj_cgroup_uncharge_pages: uncharge a number of kernel pages from a objcg 3068 * @objcg: object cgroup to uncharge 3069 * @nr_pages: number of pages to uncharge 3070 */ 3071 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg, 3072 unsigned int nr_pages) 3073 { 3074 struct mem_cgroup *memcg; 3075 3076 memcg = get_mem_cgroup_from_objcg(objcg); 3077 3078 account_kmem_nmi_safe(memcg, -nr_pages); 3079 memcg1_account_kmem(memcg, -nr_pages); 3080 if (!mem_cgroup_is_root(memcg)) 3081 refill_stock(memcg, nr_pages); 3082 3083 css_put(&memcg->css); 3084 } 3085 3086 /* 3087 * obj_cgroup_charge_pages: charge a number of kernel pages to a objcg 3088 * @objcg: object cgroup to charge 3089 * @gfp: reclaim mode 3090 * @nr_pages: number of pages to charge 3091 * 3092 * Returns 0 on success, an error code on failure. 3093 */ 3094 static int obj_cgroup_charge_pages(struct obj_cgroup *objcg, gfp_t gfp, 3095 unsigned int nr_pages) 3096 { 3097 struct mem_cgroup *memcg; 3098 int ret; 3099 3100 memcg = get_mem_cgroup_from_objcg(objcg); 3101 3102 ret = try_charge_memcg(memcg, gfp, nr_pages); 3103 if (ret) 3104 goto out; 3105 3106 account_kmem_nmi_safe(memcg, nr_pages); 3107 memcg1_account_kmem(memcg, nr_pages); 3108 out: 3109 css_put(&memcg->css); 3110 3111 return ret; 3112 } 3113 3114 static struct obj_cgroup *page_objcg(const struct page *page) 3115 { 3116 unsigned long memcg_data = page->memcg_data; 3117 3118 if (mem_cgroup_disabled() || !memcg_data) 3119 return NULL; 3120 3121 VM_BUG_ON_PAGE((memcg_data & OBJEXTS_FLAGS_MASK) != MEMCG_DATA_KMEM, 3122 page); 3123 return (struct obj_cgroup *)(memcg_data - MEMCG_DATA_KMEM); 3124 } 3125 3126 static void page_set_objcg(struct page *page, const struct obj_cgroup *objcg) 3127 { 3128 page->memcg_data = (unsigned long)objcg | MEMCG_DATA_KMEM; 3129 } 3130 3131 /** 3132 * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup 3133 * @page: page to charge 3134 * @gfp: reclaim mode 3135 * @order: allocation order 3136 * 3137 * Returns 0 on success, an error code on failure. 3138 */ 3139 int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order) 3140 { 3141 struct obj_cgroup *objcg; 3142 int ret = 0; 3143 3144 objcg = current_obj_cgroup(); 3145 if (objcg && !obj_cgroup_is_root(objcg)) { 3146 ret = obj_cgroup_charge_pages(objcg, gfp, 1 << order); 3147 if (!ret) { 3148 obj_cgroup_get(objcg); 3149 page_set_objcg(page, objcg); 3150 return 0; 3151 } 3152 } 3153 return ret; 3154 } 3155 3156 /** 3157 * __memcg_kmem_uncharge_page: uncharge a kmem page 3158 * @page: page to uncharge 3159 * @order: allocation order 3160 */ 3161 void __memcg_kmem_uncharge_page(struct page *page, int order) 3162 { 3163 struct obj_cgroup *objcg = page_objcg(page); 3164 unsigned int nr_pages = 1 << order; 3165 3166 if (!objcg) 3167 return; 3168 3169 obj_cgroup_uncharge_pages(objcg, nr_pages); 3170 page->memcg_data = 0; 3171 obj_cgroup_put(objcg); 3172 } 3173 3174 static struct obj_stock_pcp *trylock_stock(void) 3175 { 3176 if (local_trylock(&obj_stock.lock)) 3177 return this_cpu_ptr(&obj_stock); 3178 3179 return NULL; 3180 } 3181 3182 static void unlock_stock(struct obj_stock_pcp *stock) 3183 { 3184 if (stock) 3185 local_unlock(&obj_stock.lock); 3186 } 3187 3188 /* Call after __refill_obj_stock() so a slot for objcg exists in the stock */ 3189 static void __account_obj_stock(struct obj_cgroup *objcg, 3190 struct obj_stock_pcp *stock, int nr, 3191 struct pglist_data *pgdat, enum node_stat_item idx) 3192 { 3193 int16_t *bytes; 3194 int i; 3195 3196 /* 3197 * Though at the moment MAX_NUMNODES <= 1024 in all archs but let's make 3198 * sure it does not exceed S16_MAX otherwise we need to fix node_id type 3199 * in struct obj_stock_pcp. 3200 */ 3201 BUILD_BUG_ON(MAX_NUMNODES >= S16_MAX); 3202 3203 if (!stock) 3204 goto direct; 3205 3206 for (i = 0; i < NR_OBJ_STOCK; ++i) { 3207 if (READ_ONCE(stock->cached[i]) == objcg) 3208 break; 3209 } 3210 if (i == NR_OBJ_STOCK) 3211 goto direct; 3212 3213 /* 3214 * Save vmstat data in stock and skip vmstat array update unless 3215 * accumulating over a page of vmstat data or when the objcg slot or 3216 * pgdat the stats belong to changes. 3217 */ 3218 if (stock->index < 0) { 3219 stock->index = i; 3220 stock->node_id = pgdat->node_id; 3221 } else if (stock->index != i || stock->node_id != pgdat->node_id) { 3222 struct obj_cgroup *old = READ_ONCE(stock->cached[stock->index]); 3223 struct pglist_data *oldpg = NODE_DATA(stock->node_id); 3224 3225 if (stock->nr_slab_reclaimable_b) { 3226 mod_objcg_mlstate(old, oldpg, NR_SLAB_RECLAIMABLE_B, 3227 stock->nr_slab_reclaimable_b); 3228 stock->nr_slab_reclaimable_b = 0; 3229 } 3230 if (stock->nr_slab_unreclaimable_b) { 3231 mod_objcg_mlstate(old, oldpg, NR_SLAB_UNRECLAIMABLE_B, 3232 stock->nr_slab_unreclaimable_b); 3233 stock->nr_slab_unreclaimable_b = 0; 3234 } 3235 stock->index = i; 3236 stock->node_id = pgdat->node_id; 3237 } 3238 3239 bytes = (idx == NR_SLAB_RECLAIMABLE_B) ? &stock->nr_slab_reclaimable_b 3240 : &stock->nr_slab_unreclaimable_b; 3241 3242 /* 3243 * Fold @nr into the cached value and decide whether to keep it cached 3244 * or flush it directly. Cache the combined value when it fits in the 3245 * int16_t storage and either the cache was empty (so even a value 3246 * above PAGE_SIZE gets a chance to be canceled by a paired delta) or 3247 * the combined value is within the PAGE_SIZE flush threshold. 3248 */ 3249 nr += *bytes; 3250 if (abs(nr) <= S16_MAX && (!*bytes || abs(nr) <= PAGE_SIZE)) { 3251 *bytes = nr; 3252 nr = 0; 3253 } else { 3254 *bytes = 0; 3255 } 3256 direct: 3257 if (nr) 3258 mod_objcg_mlstate(objcg, pgdat, idx, nr); 3259 } 3260 3261 static bool __consume_obj_stock(struct obj_cgroup *objcg, 3262 struct obj_stock_pcp *stock, 3263 unsigned int nr_bytes) 3264 { 3265 int i; 3266 3267 for (i = 0; i < NR_OBJ_STOCK; ++i) { 3268 if (READ_ONCE(stock->cached[i]) != objcg) 3269 continue; 3270 if (stock->nr_bytes[i] >= nr_bytes) { 3271 stock->nr_bytes[i] -= nr_bytes; 3272 return true; 3273 } 3274 return false; 3275 } 3276 3277 return false; 3278 } 3279 3280 static bool consume_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes) 3281 { 3282 struct obj_stock_pcp *stock; 3283 bool ret = false; 3284 3285 stock = trylock_stock(); 3286 if (!stock) 3287 return ret; 3288 3289 ret = __consume_obj_stock(objcg, stock, nr_bytes); 3290 unlock_stock(stock); 3291 3292 return ret; 3293 } 3294 3295 /* Flush the cached slab stats (if any) back to their owning objcg/pgdat. */ 3296 static void drain_obj_stock_stats(struct obj_stock_pcp *stock) 3297 { 3298 struct obj_cgroup *old; 3299 struct pglist_data *oldpg; 3300 3301 if (stock->index < 0) 3302 return; 3303 3304 old = READ_ONCE(stock->cached[stock->index]); 3305 oldpg = NODE_DATA(stock->node_id); 3306 3307 if (stock->nr_slab_reclaimable_b) { 3308 mod_objcg_mlstate(old, oldpg, NR_SLAB_RECLAIMABLE_B, 3309 stock->nr_slab_reclaimable_b); 3310 stock->nr_slab_reclaimable_b = 0; 3311 } 3312 if (stock->nr_slab_unreclaimable_b) { 3313 mod_objcg_mlstate(old, oldpg, NR_SLAB_UNRECLAIMABLE_B, 3314 stock->nr_slab_unreclaimable_b); 3315 stock->nr_slab_unreclaimable_b = 0; 3316 } 3317 stock->index = -1; 3318 stock->node_id = NUMA_NO_NODE; 3319 } 3320 3321 static void drain_obj_stock_slot(struct obj_stock_pcp *stock, int i) 3322 { 3323 struct obj_cgroup *old = READ_ONCE(stock->cached[i]); 3324 3325 if (!old) 3326 return; 3327 3328 if (stock->nr_bytes[i]) { 3329 unsigned int nr_pages = stock->nr_bytes[i] >> PAGE_SHIFT; 3330 unsigned int nr_bytes = stock->nr_bytes[i] & (PAGE_SIZE - 1); 3331 3332 if (nr_pages) { 3333 struct mem_cgroup *memcg; 3334 3335 memcg = get_mem_cgroup_from_objcg(old); 3336 3337 memcg_uncharge_kmem(memcg, nr_pages); 3338 3339 css_put(&memcg->css); 3340 } 3341 3342 /* 3343 * The leftover is flushed to the centralized per-memcg value. 3344 * On the next attempt to refill obj stock it will be moved 3345 * to a per-cpu stock (probably, on an other CPU), see 3346 * refill_obj_stock(). 3347 * 3348 * How often it's flushed is a trade-off between the memory 3349 * limit enforcement accuracy and potential CPU contention, 3350 * so it might be changed in the future. 3351 */ 3352 atomic_add(nr_bytes, &old->nr_charged_bytes); 3353 stock->nr_bytes[i] = 0; 3354 } 3355 3356 /* Flush vmstat data when its owning slot is being drained. */ 3357 if (stock->index == i) 3358 drain_obj_stock_stats(stock); 3359 3360 WRITE_ONCE(stock->cached[i], NULL); 3361 obj_cgroup_put(old); 3362 } 3363 3364 static void drain_obj_stock(struct obj_stock_pcp *stock) 3365 { 3366 int i; 3367 3368 for (i = 0; i < NR_OBJ_STOCK; ++i) 3369 drain_obj_stock_slot(stock, i); 3370 } 3371 3372 static bool obj_stock_flush_required(struct obj_stock_pcp *stock, 3373 struct mem_cgroup *root_memcg) 3374 { 3375 struct obj_cgroup *objcg; 3376 struct mem_cgroup *memcg; 3377 bool flush = false; 3378 int i; 3379 3380 rcu_read_lock(); 3381 for (i = 0; i < NR_OBJ_STOCK; ++i) { 3382 objcg = READ_ONCE(stock->cached[i]); 3383 if (!objcg) 3384 continue; 3385 memcg = obj_cgroup_memcg(objcg); 3386 if (memcg && mem_cgroup_is_descendant(memcg, root_memcg)) { 3387 flush = true; 3388 break; 3389 } 3390 } 3391 rcu_read_unlock(); 3392 3393 return flush; 3394 } 3395 3396 static void __refill_obj_stock(struct obj_cgroup *objcg, 3397 struct obj_stock_pcp *stock, 3398 unsigned int nr_bytes, 3399 bool allow_uncharge) 3400 { 3401 unsigned int nr_pages = 0; 3402 unsigned int stock_nr_bytes; 3403 int i, slot = -1, empty_slot = -1; 3404 3405 if (!stock) { 3406 nr_pages = nr_bytes >> PAGE_SHIFT; 3407 nr_bytes = nr_bytes & (PAGE_SIZE - 1); 3408 atomic_add(nr_bytes, &objcg->nr_charged_bytes); 3409 goto out; 3410 } 3411 3412 for (i = 0; i < NR_OBJ_STOCK; ++i) { 3413 struct obj_cgroup *cached = READ_ONCE(stock->cached[i]); 3414 3415 if (!cached) { 3416 if (empty_slot == -1) 3417 empty_slot = i; 3418 continue; 3419 } 3420 if (cached == objcg) { 3421 slot = i; 3422 break; 3423 } 3424 } 3425 3426 if (slot == -1) { 3427 slot = empty_slot; 3428 if (slot == -1) { 3429 slot = stock->drain_idx++; 3430 if (stock->drain_idx == NR_OBJ_STOCK) 3431 stock->drain_idx = 0; 3432 drain_obj_stock_slot(stock, slot); 3433 } 3434 obj_cgroup_get(objcg); 3435 /* 3436 * Keep the xchg result in the unsigned int local; storing 3437 * it directly into stock->nr_bytes[slot] (uint16_t) would 3438 * silently truncate values >= U16_MAX and bypass the flush 3439 * guard below, leaking page-counter charges. 3440 */ 3441 stock_nr_bytes = atomic_read(&objcg->nr_charged_bytes) 3442 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0; 3443 WRITE_ONCE(stock->cached[slot], objcg); 3444 3445 allow_uncharge = true; /* Allow uncharge when objcg changes */ 3446 } else { 3447 stock_nr_bytes = stock->nr_bytes[slot]; 3448 } 3449 3450 stock_nr_bytes += nr_bytes; 3451 3452 if ((allow_uncharge && (stock_nr_bytes > PAGE_SIZE)) || 3453 stock_nr_bytes > U16_MAX) { 3454 nr_pages = stock_nr_bytes >> PAGE_SHIFT; 3455 stock_nr_bytes &= (PAGE_SIZE - 1); 3456 } 3457 stock->nr_bytes[slot] = stock_nr_bytes; 3458 3459 out: 3460 if (nr_pages) 3461 obj_cgroup_uncharge_pages(objcg, nr_pages); 3462 } 3463 3464 static void refill_obj_stock(struct obj_cgroup *objcg, 3465 unsigned int nr_bytes, 3466 bool allow_uncharge) 3467 { 3468 struct obj_stock_pcp *stock = trylock_stock(); 3469 __refill_obj_stock(objcg, stock, nr_bytes, allow_uncharge); 3470 unlock_stock(stock); 3471 } 3472 3473 static int __obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, 3474 size_t size, size_t *remainder) 3475 { 3476 size_t charge_size; 3477 int ret; 3478 3479 charge_size = PAGE_ALIGN(size); 3480 ret = obj_cgroup_charge_pages(objcg, gfp, charge_size >> PAGE_SHIFT); 3481 if (!ret) 3482 *remainder = charge_size - size; 3483 3484 return ret; 3485 } 3486 3487 int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size) 3488 { 3489 size_t remainder; 3490 int ret; 3491 3492 if (likely(consume_obj_stock(objcg, size))) 3493 return 0; 3494 3495 /* 3496 * In theory, objcg->nr_charged_bytes can have enough 3497 * pre-charged bytes to satisfy the allocation. However, 3498 * flushing objcg->nr_charged_bytes requires two atomic 3499 * operations, and objcg->nr_charged_bytes can't be big. 3500 * The shared objcg->nr_charged_bytes can also become a 3501 * performance bottleneck if all tasks of the same memcg are 3502 * trying to update it. So it's better to ignore it and try 3503 * grab some new pages. The stock's nr_bytes will be flushed to 3504 * objcg->nr_charged_bytes later on when objcg changes. 3505 * 3506 * The stock's nr_bytes may contain enough pre-charged bytes 3507 * to allow one less page from being charged, but we can't rely 3508 * on the pre-charged bytes not being changed outside of 3509 * consume_obj_stock() or refill_obj_stock(). So ignore those 3510 * pre-charged bytes as well when charging pages. To avoid a 3511 * page uncharge right after a page charge, we set the 3512 * allow_uncharge flag to false when calling refill_obj_stock() 3513 * to temporarily allow the pre-charged bytes to exceed the page 3514 * size limit. The maximum reachable value of the pre-charged 3515 * bytes is (sizeof(object) + PAGE_SIZE - 2) if there is no data 3516 * race. 3517 */ 3518 ret = __obj_cgroup_charge(objcg, gfp, size, &remainder); 3519 if (!ret && remainder) 3520 refill_obj_stock(objcg, remainder, false); 3521 3522 return ret; 3523 } 3524 3525 void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size) 3526 { 3527 refill_obj_stock(objcg, size, true); 3528 } 3529 3530 static inline size_t obj_full_size(struct kmem_cache *s) 3531 { 3532 /* 3533 * For each accounted object there is an extra space which is used 3534 * to store obj_cgroup membership. Charge it too. 3535 */ 3536 return s->size + sizeof(struct obj_cgroup *); 3537 } 3538 3539 bool __memcg_slab_post_alloc_hook(struct kmem_cache *s, struct list_lru *lru, 3540 gfp_t flags, unsigned int slab_alloc_flags, 3541 size_t size, void **p) 3542 { 3543 size_t obj_size = obj_full_size(s); 3544 struct obj_cgroup *objcg; 3545 struct slab *slab; 3546 unsigned long off; 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 alloc_slab_obj_exts(slab, s, flags, slab_alloc_flags)) { 3590 continue; 3591 } 3592 3593 /* 3594 * if we fail and size is 1, memcg_alloc_abort_single() will 3595 * just free the object, which is ok as we have not assigned 3596 * objcg to its obj_ext yet 3597 * 3598 * for larger sizes, kmem_cache_free_bulk() will uncharge 3599 * any objects that were already charged and obj_ext assigned 3600 * 3601 * TODO: we could batch this until slab_pgdat(slab) changes 3602 * between iterations, with a more complicated undo 3603 */ 3604 stock = trylock_stock(); 3605 if (!stock || !__consume_obj_stock(objcg, stock, obj_size)) { 3606 size_t remainder; 3607 3608 unlock_stock(stock); 3609 if (__obj_cgroup_charge(objcg, flags, obj_size, &remainder)) 3610 return false; 3611 stock = trylock_stock(); 3612 if (remainder) 3613 __refill_obj_stock(objcg, stock, remainder, false); 3614 } 3615 __account_obj_stock(objcg, stock, obj_size, 3616 slab_pgdat(slab), cache_vmstat_idx(s)); 3617 unlock_stock(stock); 3618 3619 obj_exts = slab_obj_exts(slab); 3620 get_slab_obj_exts(obj_exts); 3621 off = obj_to_index(s, slab, p[i]); 3622 obj_ext = slab_obj_ext(slab, obj_exts, off); 3623 obj_cgroup_get(objcg); 3624 obj_ext->objcg = objcg; 3625 put_slab_obj_exts(obj_exts); 3626 } 3627 3628 return true; 3629 } 3630 3631 void __memcg_slab_free_hook(struct kmem_cache *s, struct slab *slab, 3632 void **p, int objects, unsigned long obj_exts) 3633 { 3634 size_t obj_size = obj_full_size(s); 3635 3636 for (int i = 0; i < objects; i++) { 3637 struct obj_cgroup *objcg; 3638 struct slabobj_ext *obj_ext; 3639 struct obj_stock_pcp *stock; 3640 unsigned int off; 3641 3642 off = obj_to_index(s, slab, p[i]); 3643 obj_ext = slab_obj_ext(slab, obj_exts, off); 3644 objcg = obj_ext->objcg; 3645 if (!objcg) 3646 continue; 3647 3648 obj_ext->objcg = NULL; 3649 3650 stock = trylock_stock(); 3651 __refill_obj_stock(objcg, stock, obj_size, true); 3652 __account_obj_stock(objcg, stock, -obj_size, 3653 slab_pgdat(slab), cache_vmstat_idx(s)); 3654 unlock_stock(stock); 3655 3656 obj_cgroup_put(objcg); 3657 } 3658 } 3659 3660 /* 3661 * The objcg is only set on the first page, so transfer it to all the 3662 * other pages. 3663 */ 3664 void split_page_memcg(struct page *page, unsigned order) 3665 { 3666 struct obj_cgroup *objcg = page_objcg(page); 3667 unsigned int i, nr = 1 << order; 3668 3669 if (!objcg) 3670 return; 3671 3672 for (i = 1; i < nr; i++) 3673 page_set_objcg(&page[i], objcg); 3674 3675 obj_cgroup_get_many(objcg, nr - 1); 3676 } 3677 3678 void folio_split_memcg_refs(struct folio *folio, unsigned old_order, 3679 unsigned new_order) 3680 { 3681 unsigned new_refs; 3682 3683 if (mem_cgroup_disabled() || !folio_memcg_charged(folio)) 3684 return; 3685 3686 new_refs = (1 << (old_order - new_order)) - 1; 3687 obj_cgroup_get_many(folio_objcg(folio), new_refs); 3688 } 3689 3690 static void memcg_online_kmem(struct mem_cgroup *memcg) 3691 { 3692 if (mem_cgroup_kmem_disabled()) 3693 return; 3694 3695 if (unlikely(mem_cgroup_is_root(memcg))) 3696 return; 3697 3698 static_branch_enable(&memcg_kmem_online_key); 3699 3700 memcg->kmemcg_id = memcg->id.id; 3701 } 3702 3703 static void memcg_offline_kmem(struct mem_cgroup *memcg) 3704 { 3705 struct mem_cgroup *parent; 3706 3707 if (mem_cgroup_kmem_disabled()) 3708 return; 3709 3710 if (unlikely(mem_cgroup_is_root(memcg))) 3711 return; 3712 3713 parent = parent_mem_cgroup(memcg); 3714 memcg_reparent_list_lrus(memcg, parent); 3715 } 3716 3717 #ifdef CONFIG_CGROUP_WRITEBACK 3718 3719 #include <trace/events/writeback.h> 3720 3721 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp) 3722 { 3723 return wb_domain_init(&memcg->cgwb_domain, gfp); 3724 } 3725 3726 static void memcg_wb_domain_exit(struct mem_cgroup *memcg) 3727 { 3728 wb_domain_exit(&memcg->cgwb_domain); 3729 } 3730 3731 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg) 3732 { 3733 wb_domain_size_changed(&memcg->cgwb_domain); 3734 } 3735 3736 struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb) 3737 { 3738 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css); 3739 3740 if (!memcg->css.parent) 3741 return NULL; 3742 3743 return &memcg->cgwb_domain; 3744 } 3745 3746 /** 3747 * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg 3748 * @wb: bdi_writeback in question 3749 * @pfilepages: out parameter for number of file pages 3750 * @pheadroom: out parameter for number of allocatable pages according to memcg 3751 * @pdirty: out parameter for number of dirty pages 3752 * @pwriteback: out parameter for number of pages under writeback 3753 * 3754 * Determine the numbers of file, headroom, dirty, and writeback pages in 3755 * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom 3756 * is a bit more involved. 3757 * 3758 * A memcg's headroom is "min(max, high) - used". In the hierarchy, the 3759 * headroom is calculated as the lowest headroom of itself and the 3760 * ancestors. Note that this doesn't consider the actual amount of 3761 * available memory in the system. The caller should further cap 3762 * *@pheadroom accordingly. 3763 */ 3764 void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages, 3765 unsigned long *pheadroom, unsigned long *pdirty, 3766 unsigned long *pwriteback) 3767 { 3768 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css); 3769 struct mem_cgroup *parent; 3770 3771 mem_cgroup_flush_stats_ratelimited(memcg); 3772 3773 *pdirty = memcg_page_state(memcg, NR_FILE_DIRTY); 3774 *pwriteback = memcg_page_state(memcg, NR_WRITEBACK); 3775 *pfilepages = memcg_page_state(memcg, NR_INACTIVE_FILE) + 3776 memcg_page_state(memcg, NR_ACTIVE_FILE); 3777 3778 *pheadroom = PAGE_COUNTER_MAX; 3779 while ((parent = parent_mem_cgroup(memcg))) { 3780 unsigned long ceiling = min(READ_ONCE(memcg->memory.max), 3781 READ_ONCE(memcg->memory.high)); 3782 unsigned long used = page_counter_read(&memcg->memory); 3783 3784 *pheadroom = min(*pheadroom, ceiling - min(ceiling, used)); 3785 memcg = parent; 3786 } 3787 } 3788 3789 /* 3790 * Foreign dirty flushing 3791 * 3792 * There's an inherent mismatch between memcg and writeback. The former 3793 * tracks ownership per-page while the latter per-inode. This was a 3794 * deliberate design decision because honoring per-page ownership in the 3795 * writeback path is complicated, may lead to higher CPU and IO overheads 3796 * and deemed unnecessary given that write-sharing an inode across 3797 * different cgroups isn't a common use-case. 3798 * 3799 * Combined with inode majority-writer ownership switching, this works well 3800 * enough in most cases but there are some pathological cases. For 3801 * example, let's say there are two cgroups A and B which keep writing to 3802 * different but confined parts of the same inode. B owns the inode and 3803 * A's memory is limited far below B's. A's dirty ratio can rise enough to 3804 * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid 3805 * triggering background writeback. A will be slowed down without a way to 3806 * make writeback of the dirty pages happen. 3807 * 3808 * Conditions like the above can lead to a cgroup getting repeatedly and 3809 * severely throttled after making some progress after each 3810 * dirty_expire_interval while the underlying IO device is almost 3811 * completely idle. 3812 * 3813 * Solving this problem completely requires matching the ownership tracking 3814 * granularities between memcg and writeback in either direction. However, 3815 * the more egregious behaviors can be avoided by simply remembering the 3816 * most recent foreign dirtying events and initiating remote flushes on 3817 * them when local writeback isn't enough to keep the memory clean enough. 3818 * 3819 * The following two functions implement such mechanism. When a foreign 3820 * page - a page whose memcg and writeback ownerships don't match - is 3821 * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning 3822 * bdi_writeback on the page owning memcg. When balance_dirty_pages() 3823 * decides that the memcg needs to sleep due to high dirty ratio, it calls 3824 * mem_cgroup_flush_foreign() which queues writeback on the recorded 3825 * foreign bdi_writebacks which haven't expired. Both the numbers of 3826 * recorded bdi_writebacks and concurrent in-flight foreign writebacks are 3827 * limited to MEMCG_CGWB_FRN_CNT. 3828 * 3829 * The mechanism only remembers IDs and doesn't hold any object references. 3830 * As being wrong occasionally doesn't matter, updates and accesses to the 3831 * records are lockless and racy. 3832 */ 3833 void mem_cgroup_track_foreign_dirty_slowpath(struct folio *folio, 3834 struct bdi_writeback *wb) 3835 { 3836 struct mem_cgroup *memcg = folio_memcg(folio); 3837 struct memcg_cgwb_frn *frn; 3838 u64 now = get_jiffies_64(); 3839 u64 oldest_at = now; 3840 int oldest = -1; 3841 int i; 3842 3843 trace_track_foreign_dirty(folio, wb); 3844 3845 /* 3846 * Pick the slot to use. If there is already a slot for @wb, keep 3847 * using it. If not replace the oldest one which isn't being 3848 * written out. 3849 */ 3850 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) { 3851 frn = &memcg->cgwb_frn[i]; 3852 if (frn->bdi_id == wb->bdi->id && 3853 frn->memcg_id == wb->memcg_css->id) 3854 break; 3855 if (time_before64(frn->at, oldest_at) && 3856 atomic_read(&frn->done.cnt) == 1) { 3857 oldest = i; 3858 oldest_at = frn->at; 3859 } 3860 } 3861 3862 if (i < MEMCG_CGWB_FRN_CNT) { 3863 /* 3864 * Re-using an existing one. Update timestamp lazily to 3865 * avoid making the cacheline hot. We want them to be 3866 * reasonably up-to-date and significantly shorter than 3867 * dirty_expire_interval as that's what expires the record. 3868 * Use the shorter of 1s and dirty_expire_interval / 8. 3869 */ 3870 unsigned long update_intv = 3871 min_t(unsigned long, HZ, 3872 msecs_to_jiffies(dirty_expire_interval * 10) / 8); 3873 3874 if (time_before64(frn->at, now - update_intv)) 3875 frn->at = now; 3876 } else if (oldest >= 0) { 3877 /* replace the oldest free one */ 3878 frn = &memcg->cgwb_frn[oldest]; 3879 frn->bdi_id = wb->bdi->id; 3880 frn->memcg_id = wb->memcg_css->id; 3881 frn->at = now; 3882 } 3883 } 3884 3885 /* issue foreign writeback flushes for recorded foreign dirtying events */ 3886 void mem_cgroup_flush_foreign(struct bdi_writeback *wb) 3887 { 3888 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css); 3889 unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10); 3890 u64 now = jiffies_64; 3891 int i; 3892 3893 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) { 3894 struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i]; 3895 3896 /* 3897 * If the record is older than dirty_expire_interval, 3898 * writeback on it has already started. No need to kick it 3899 * off again. Also, don't start a new one if there's 3900 * already one in flight. 3901 */ 3902 if (time_after64(frn->at, now - intv) && 3903 atomic_read(&frn->done.cnt) == 1) { 3904 frn->at = 0; 3905 trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id); 3906 cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id, 3907 WB_REASON_FOREIGN_FLUSH, 3908 &frn->done); 3909 } 3910 } 3911 } 3912 3913 #else /* CONFIG_CGROUP_WRITEBACK */ 3914 3915 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp) 3916 { 3917 return 0; 3918 } 3919 3920 static void memcg_wb_domain_exit(struct mem_cgroup *memcg) 3921 { 3922 } 3923 3924 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg) 3925 { 3926 } 3927 3928 #endif /* CONFIG_CGROUP_WRITEBACK */ 3929 3930 /* 3931 * Private memory cgroup IDR 3932 * 3933 * Swap-out records and page cache shadow entries need to store memcg 3934 * references in constrained space, so we maintain an ID space that is 3935 * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of 3936 * memory-controlled cgroups to 64k. 3937 * 3938 * However, there usually are many references to the offline CSS after 3939 * the cgroup has been destroyed, such as page cache or reclaimable 3940 * slab objects, that don't need to hang on to the ID. We want to keep 3941 * those dead CSS from occupying IDs, or we might quickly exhaust the 3942 * relatively small ID space and prevent the creation of new cgroups 3943 * even when there are much fewer than 64k cgroups - possibly none. 3944 * 3945 * Maintain a private 16-bit ID space for memcg, and allow the ID to 3946 * be freed and recycled when it's no longer needed, which is usually 3947 * when the CSS is offlined. 3948 * 3949 * The only exception to that are records of swapped out tmpfs/shmem 3950 * pages that need to be attributed to live ancestors on swapin. But 3951 * those references are manageable from userspace. 3952 */ 3953 3954 #define MEM_CGROUP_ID_MAX ((1UL << MEM_CGROUP_ID_SHIFT) - 1) 3955 static DEFINE_XARRAY_ALLOC1(mem_cgroup_private_ids); 3956 3957 static void mem_cgroup_private_id_remove(struct mem_cgroup *memcg) 3958 { 3959 if (memcg->id.id > 0) { 3960 xa_erase(&mem_cgroup_private_ids, memcg->id.id); 3961 memcg->id.id = 0; 3962 } 3963 } 3964 3965 static inline void mem_cgroup_private_id_put(struct mem_cgroup *memcg, unsigned int n) 3966 { 3967 if (refcount_sub_and_test(n, &memcg->id.ref)) { 3968 mem_cgroup_private_id_remove(memcg); 3969 3970 /* Memcg ID pins CSS */ 3971 css_put(&memcg->css); 3972 } 3973 } 3974 3975 struct mem_cgroup *mem_cgroup_private_id_get_online(struct mem_cgroup *memcg, unsigned int n) 3976 { 3977 while (!refcount_add_not_zero(n, &memcg->id.ref)) { 3978 /* 3979 * The root cgroup cannot be destroyed, so it's refcount must 3980 * always be >= 1. 3981 */ 3982 if (WARN_ON_ONCE(mem_cgroup_is_root(memcg))) { 3983 VM_BUG_ON(1); 3984 break; 3985 } 3986 memcg = parent_mem_cgroup(memcg); 3987 } 3988 return memcg; 3989 } 3990 3991 /** 3992 * mem_cgroup_from_private_id - look up a memcg from a memcg id 3993 * @id: the memcg id to look up 3994 * 3995 * Caller must hold rcu_read_lock(). 3996 */ 3997 struct mem_cgroup *mem_cgroup_from_private_id(unsigned short id) 3998 { 3999 WARN_ON_ONCE(!rcu_read_lock_held()); 4000 return xa_load(&mem_cgroup_private_ids, id); 4001 } 4002 4003 struct mem_cgroup *mem_cgroup_get_from_id(u64 id) 4004 { 4005 struct cgroup *cgrp; 4006 struct cgroup_subsys_state *css; 4007 struct mem_cgroup *memcg = NULL; 4008 4009 cgrp = cgroup_get_from_id(id); 4010 if (IS_ERR(cgrp)) 4011 return NULL; 4012 4013 css = cgroup_get_e_css(cgrp, &memory_cgrp_subsys); 4014 if (css) 4015 memcg = container_of(css, struct mem_cgroup, css); 4016 4017 cgroup_put(cgrp); 4018 4019 return memcg; 4020 } 4021 4022 static void free_mem_cgroup_per_node_info(struct mem_cgroup_per_node *pn) 4023 { 4024 if (!pn) 4025 return; 4026 4027 free_percpu(pn->lruvec_stats_percpu); 4028 kfree(pn->lruvec_stats); 4029 kfree(pn); 4030 } 4031 4032 static bool alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node) 4033 { 4034 struct mem_cgroup_per_node *pn; 4035 4036 pn = kmem_cache_alloc_node(memcg_pn_cachep, GFP_KERNEL | __GFP_ZERO, 4037 node); 4038 if (!pn) 4039 return false; 4040 4041 pn->lruvec_stats = kzalloc_node(sizeof(struct lruvec_stats), 4042 GFP_KERNEL_ACCOUNT, node); 4043 if (!pn->lruvec_stats) 4044 goto fail; 4045 4046 pn->lruvec_stats_percpu = alloc_percpu_gfp(struct lruvec_stats_percpu, 4047 GFP_KERNEL_ACCOUNT); 4048 if (!pn->lruvec_stats_percpu) 4049 goto fail; 4050 4051 INIT_LIST_HEAD(&pn->objcg_list); 4052 4053 lruvec_init(&pn->lruvec); 4054 pn->memcg = memcg; 4055 4056 memcg->nodeinfo[node] = pn; 4057 return true; 4058 fail: 4059 free_mem_cgroup_per_node_info(pn); 4060 return false; 4061 } 4062 4063 static void __mem_cgroup_free(struct mem_cgroup *memcg) 4064 { 4065 int node; 4066 4067 for_each_node(node) { 4068 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node]; 4069 if (!pn) 4070 continue; 4071 4072 obj_cgroup_put(pn->orig_objcg); 4073 free_mem_cgroup_per_node_info(pn); 4074 } 4075 memcg1_free_events(memcg); 4076 kfree(memcg->vmstats); 4077 free_percpu(memcg->vmstats_percpu); 4078 kfree(memcg); 4079 } 4080 4081 static void mem_cgroup_free(struct mem_cgroup *memcg) 4082 { 4083 lru_gen_exit_memcg(memcg); 4084 memcg_wb_domain_exit(memcg); 4085 __mem_cgroup_free(memcg); 4086 } 4087 4088 static struct mem_cgroup *mem_cgroup_alloc(struct mem_cgroup *parent) 4089 { 4090 struct memcg_vmstats_percpu *statc; 4091 struct memcg_vmstats_percpu __percpu *pstatc_pcpu; 4092 struct mem_cgroup *memcg; 4093 int node, cpu; 4094 int __maybe_unused i; 4095 long error; 4096 4097 memcg = kmem_cache_zalloc(memcg_cachep, GFP_KERNEL); 4098 if (!memcg) 4099 return ERR_PTR(-ENOMEM); 4100 4101 error = xa_alloc(&mem_cgroup_private_ids, &memcg->id.id, NULL, 4102 XA_LIMIT(1, MEM_CGROUP_ID_MAX), GFP_KERNEL); 4103 if (error) 4104 goto fail; 4105 error = -ENOMEM; 4106 4107 memcg->vmstats = kzalloc_obj(struct memcg_vmstats, GFP_KERNEL_ACCOUNT); 4108 if (!memcg->vmstats) 4109 goto fail; 4110 4111 memcg->vmstats_percpu = alloc_percpu_gfp(struct memcg_vmstats_percpu, 4112 GFP_KERNEL_ACCOUNT); 4113 if (!memcg->vmstats_percpu) 4114 goto fail; 4115 4116 if (!memcg1_alloc_events(memcg)) 4117 goto fail; 4118 4119 pstatc_pcpu = parent ? parent->vmstats_percpu : NULL; 4120 for_each_possible_cpu(cpu) { 4121 statc = per_cpu_ptr(memcg->vmstats_percpu, cpu); 4122 statc->parent_pcpu = pstatc_pcpu; 4123 statc->vmstats = memcg->vmstats; 4124 } 4125 4126 for_each_node(node) 4127 if (!alloc_mem_cgroup_per_node_info(memcg, node)) 4128 goto fail; 4129 4130 if (memcg_wb_domain_init(memcg, GFP_KERNEL)) 4131 goto fail; 4132 4133 INIT_WORK(&memcg->high_work, high_work_func); 4134 vmpressure_init(&memcg->vmpressure); 4135 INIT_LIST_HEAD(&memcg->memory_peaks); 4136 INIT_LIST_HEAD(&memcg->swap_peaks); 4137 spin_lock_init(&memcg->peaks_lock); 4138 memcg->socket_pressure = get_jiffies_64(); 4139 #if BITS_PER_LONG < 64 4140 seqlock_init(&memcg->socket_pressure_seqlock); 4141 #endif 4142 memcg1_memcg_init(memcg); 4143 memcg->kmemcg_id = -1; 4144 #ifdef CONFIG_CGROUP_WRITEBACK 4145 INIT_LIST_HEAD(&memcg->cgwb_list); 4146 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) 4147 memcg->cgwb_frn[i].done = 4148 __WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq); 4149 #endif 4150 lru_gen_init_memcg(memcg); 4151 return memcg; 4152 fail: 4153 mem_cgroup_private_id_remove(memcg); 4154 __mem_cgroup_free(memcg); 4155 return ERR_PTR(error); 4156 } 4157 4158 static struct cgroup_subsys_state * __ref 4159 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css) 4160 { 4161 struct mem_cgroup *parent = mem_cgroup_from_css(parent_css); 4162 struct mem_cgroup *memcg, *old_memcg; 4163 bool memcg_on_dfl = cgroup_subsys_on_dfl(memory_cgrp_subsys); 4164 4165 old_memcg = set_active_memcg(parent); 4166 memcg = mem_cgroup_alloc(parent); 4167 set_active_memcg(old_memcg); 4168 if (IS_ERR(memcg)) 4169 return ERR_CAST(memcg); 4170 4171 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX); 4172 memcg1_soft_limit_reset(memcg); 4173 #ifdef CONFIG_ZSWAP 4174 memcg->zswap_max = PAGE_COUNTER_MAX; 4175 WRITE_ONCE(memcg->zswap_writeback, true); 4176 #endif 4177 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX); 4178 if (parent) { 4179 WRITE_ONCE(memcg->swappiness, mem_cgroup_swappiness(parent)); 4180 4181 page_counter_init(&memcg->memory, &parent->memory, memcg_on_dfl); 4182 page_counter_init(&memcg->swap, &parent->swap, false); 4183 #ifdef CONFIG_MEMCG_V1 4184 memcg->memory.track_failcnt = !memcg_on_dfl; 4185 memcg->memsw.track_failcnt = !memcg_on_dfl; 4186 WRITE_ONCE(memcg->oom_kill_disable, READ_ONCE(parent->oom_kill_disable)); 4187 page_counter_init(&memcg->kmem, &parent->kmem, false); 4188 page_counter_init(&memcg->tcpmem, &parent->tcpmem, false); 4189 memcg->tcpmem.track_failcnt = !memcg_on_dfl; 4190 #endif 4191 } else { 4192 init_memcg_stats(); 4193 init_memcg_events(); 4194 page_counter_init(&memcg->memory, NULL, true); 4195 page_counter_init(&memcg->swap, NULL, false); 4196 #ifdef CONFIG_MEMCG_V1 4197 page_counter_init(&memcg->kmem, NULL, false); 4198 page_counter_init(&memcg->tcpmem, NULL, false); 4199 #endif 4200 root_mem_cgroup = memcg; 4201 return &memcg->css; 4202 } 4203 4204 if (memcg_on_dfl && !cgroup_memory_nosocket) 4205 static_branch_inc(&memcg_sockets_enabled_key); 4206 4207 if (!cgroup_memory_nobpf) 4208 static_branch_inc(&memcg_bpf_enabled_key); 4209 4210 return &memcg->css; 4211 } 4212 4213 static int mem_cgroup_css_online(struct cgroup_subsys_state *css) 4214 { 4215 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 4216 struct obj_cgroup *objcg; 4217 int nid; 4218 4219 memcg_online_kmem(memcg); 4220 4221 /* 4222 * A memcg must be visible for expand_shrinker_info() 4223 * by the time the maps are allocated. So, we allocate maps 4224 * here, when mem_cgroup_iter() can't skip it. 4225 */ 4226 if (alloc_shrinker_info(memcg)) 4227 goto offline_kmem; 4228 4229 for_each_node(nid) { 4230 objcg = obj_cgroup_alloc(); 4231 if (!objcg) 4232 goto free_objcg; 4233 4234 if (unlikely(mem_cgroup_is_root(memcg))) 4235 objcg->is_root = true; 4236 4237 objcg->memcg = memcg; 4238 rcu_assign_pointer(memcg->nodeinfo[nid]->objcg, objcg); 4239 obj_cgroup_get(objcg); 4240 memcg->nodeinfo[nid]->orig_objcg = objcg; 4241 } 4242 4243 if (unlikely(mem_cgroup_is_root(memcg)) && !mem_cgroup_disabled()) 4244 queue_delayed_work(system_dfl_wq, &stats_flush_dwork, 4245 FLUSH_TIME); 4246 lru_gen_online_memcg(memcg); 4247 4248 /* Online state pins memcg ID, memcg ID pins CSS */ 4249 refcount_set(&memcg->id.ref, 1); 4250 css_get(css); 4251 4252 /* 4253 * Ensure mem_cgroup_from_private_id() works once we're fully online. 4254 * 4255 * We could do this earlier and require callers to filter with 4256 * css_tryget_online(). But right now there are no users that 4257 * need earlier access, and the workingset code relies on the 4258 * cgroup tree linkage (mem_cgroup_get_nr_swap_pages()). So 4259 * publish it here at the end of onlining. This matches the 4260 * regular ID destruction during offlining. 4261 */ 4262 xa_store(&mem_cgroup_private_ids, memcg->id.id, memcg, GFP_KERNEL); 4263 4264 return 0; 4265 free_objcg: 4266 for_each_node(nid) { 4267 struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid]; 4268 4269 objcg = rcu_replace_pointer(pn->objcg, NULL, true); 4270 if (objcg) 4271 percpu_ref_kill(&objcg->refcnt); 4272 4273 if (pn->orig_objcg) { 4274 obj_cgroup_put(pn->orig_objcg); 4275 /* 4276 * Reset pn->orig_objcg to NULL to prevent 4277 * obj_cgroup_put() from being called again in 4278 * __mem_cgroup_free(). 4279 */ 4280 pn->orig_objcg = NULL; 4281 } 4282 } 4283 free_shrinker_info(memcg); 4284 offline_kmem: 4285 memcg_offline_kmem(memcg); 4286 mem_cgroup_private_id_remove(memcg); 4287 return -ENOMEM; 4288 } 4289 4290 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css) 4291 { 4292 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 4293 4294 memcg1_css_offline(memcg); 4295 4296 page_counter_set_min(&memcg->memory, 0); 4297 page_counter_set_low(&memcg->memory, 0); 4298 4299 zswap_memcg_offline_cleanup(memcg); 4300 4301 memcg_offline_kmem(memcg); 4302 /* 4303 * The reparenting of objcg must be after the reparenting of 4304 * the list_lru in memcg_offline_kmem(), which ensures that 4305 * they will not mistakenly get the parent list_lru. 4306 */ 4307 memcg_reparent_objcgs(memcg); 4308 reparent_shrinker_deferred(memcg); 4309 wb_memcg_offline(memcg); 4310 lru_gen_offline_memcg(memcg); 4311 4312 drain_all_stock(memcg); 4313 4314 mem_cgroup_private_id_put(memcg, 1); 4315 } 4316 4317 static void mem_cgroup_css_released(struct cgroup_subsys_state *css) 4318 { 4319 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 4320 4321 invalidate_reclaim_iterators(memcg); 4322 lru_gen_release_memcg(memcg); 4323 } 4324 4325 static void mem_cgroup_css_free(struct cgroup_subsys_state *css) 4326 { 4327 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 4328 int __maybe_unused i; 4329 4330 #ifdef CONFIG_CGROUP_WRITEBACK 4331 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) 4332 wb_wait_for_completion(&memcg->cgwb_frn[i].done); 4333 #endif 4334 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket) 4335 static_branch_dec(&memcg_sockets_enabled_key); 4336 4337 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg1_tcpmem_active(memcg)) 4338 static_branch_dec(&memcg_sockets_enabled_key); 4339 4340 if (!cgroup_memory_nobpf) 4341 static_branch_dec(&memcg_bpf_enabled_key); 4342 4343 vmpressure_cleanup(&memcg->vmpressure); 4344 cancel_work_sync(&memcg->high_work); 4345 memcg1_remove_from_trees(memcg); 4346 free_shrinker_info(memcg); 4347 mem_cgroup_free(memcg); 4348 } 4349 4350 /** 4351 * mem_cgroup_css_reset - reset the states of a mem_cgroup 4352 * @css: the target css 4353 * 4354 * Reset the states of the mem_cgroup associated with @css. This is 4355 * invoked when the userland requests disabling on the default hierarchy 4356 * but the memcg is pinned through dependency. The memcg should stop 4357 * applying policies and should revert to the vanilla state as it may be 4358 * made visible again. 4359 * 4360 * The current implementation only resets the essential configurations. 4361 * This needs to be expanded to cover all the visible parts. 4362 */ 4363 static void mem_cgroup_css_reset(struct cgroup_subsys_state *css) 4364 { 4365 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 4366 4367 page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX); 4368 page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX); 4369 WRITE_ONCE(memcg->oom_group, false); 4370 #ifdef CONFIG_ZSWAP 4371 WRITE_ONCE(memcg->zswap_max, PAGE_COUNTER_MAX); 4372 WRITE_ONCE(memcg->zswap_writeback, true); 4373 #endif 4374 #ifdef CONFIG_MEMCG_V1 4375 page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX); 4376 page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX); 4377 #endif 4378 page_counter_set_min(&memcg->memory, 0); 4379 page_counter_set_low(&memcg->memory, 0); 4380 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX); 4381 memcg1_soft_limit_reset(memcg); 4382 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX); 4383 memcg_wb_domain_size_changed(memcg); 4384 } 4385 4386 struct aggregate_control { 4387 /* pointer to the aggregated (CPU and subtree aggregated) counters */ 4388 long *aggregate; 4389 /* pointer to the non-hierarchichal (CPU aggregated) counters */ 4390 long *local; 4391 /* pointer to the pending child counters during tree propagation */ 4392 long *pending; 4393 /* pointer to the parent's pending counters, could be NULL */ 4394 long *ppending; 4395 /* pointer to the percpu counters to be aggregated */ 4396 long *cstat; 4397 /* pointer to the percpu counters of the last aggregation*/ 4398 long *cstat_prev; 4399 /* size of the above counters */ 4400 int size; 4401 }; 4402 4403 static void mem_cgroup_stat_aggregate(struct aggregate_control *ac) 4404 { 4405 int i; 4406 long delta, delta_cpu, v; 4407 4408 for (i = 0; i < ac->size; i++) { 4409 /* 4410 * Collect the aggregated propagation counts of groups 4411 * below us. We're in a per-cpu loop here and this is 4412 * a global counter, so the first cycle will get them. 4413 */ 4414 delta = ac->pending[i]; 4415 if (delta) 4416 ac->pending[i] = 0; 4417 4418 /* Add CPU changes on this level since the last flush */ 4419 delta_cpu = 0; 4420 v = READ_ONCE(ac->cstat[i]); 4421 if (v != ac->cstat_prev[i]) { 4422 delta_cpu = v - ac->cstat_prev[i]; 4423 delta += delta_cpu; 4424 ac->cstat_prev[i] = v; 4425 } 4426 4427 /* Aggregate counts on this level and propagate upwards */ 4428 if (delta_cpu) 4429 ac->local[i] += delta_cpu; 4430 4431 if (delta) { 4432 ac->aggregate[i] += delta; 4433 if (ac->ppending) 4434 ac->ppending[i] += delta; 4435 } 4436 } 4437 } 4438 4439 #ifdef CONFIG_MEMCG_NMI_SAFETY_REQUIRES_ATOMIC 4440 static void flush_nmi_stats(struct mem_cgroup *memcg, struct mem_cgroup *parent) 4441 { 4442 int nid; 4443 4444 if (atomic_read(&memcg->kmem_stat)) { 4445 int kmem = atomic_xchg(&memcg->kmem_stat, 0); 4446 int index = memcg_stats_index(MEMCG_KMEM); 4447 4448 memcg->vmstats->state[index] += kmem; 4449 memcg->vmstats->state_local[index] += kmem; 4450 if (parent) 4451 parent->vmstats->state_pending[index] += kmem; 4452 } 4453 4454 for_each_node_state(nid, N_MEMORY) { 4455 struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid]; 4456 struct lruvec_stats *lstats = pn->lruvec_stats; 4457 struct lruvec_stats *plstats = NULL; 4458 4459 if (parent) 4460 plstats = parent->nodeinfo[nid]->lruvec_stats; 4461 4462 if (atomic_read(&pn->slab_reclaimable)) { 4463 int slab = atomic_xchg(&pn->slab_reclaimable, 0); 4464 int index = memcg_stats_index(NR_SLAB_RECLAIMABLE_B); 4465 4466 lstats->state[index] += slab; 4467 lstats->state_local[index] += slab; 4468 if (plstats) 4469 plstats->state_pending[index] += slab; 4470 memcg->vmstats->state[index] += slab; 4471 memcg->vmstats->state_local[index] += slab; 4472 if (parent) 4473 parent->vmstats->state_pending[index] += slab; 4474 } 4475 if (atomic_read(&pn->slab_unreclaimable)) { 4476 int slab = atomic_xchg(&pn->slab_unreclaimable, 0); 4477 int index = memcg_stats_index(NR_SLAB_UNRECLAIMABLE_B); 4478 4479 lstats->state[index] += slab; 4480 lstats->state_local[index] += slab; 4481 if (plstats) 4482 plstats->state_pending[index] += slab; 4483 memcg->vmstats->state[index] += slab; 4484 memcg->vmstats->state_local[index] += slab; 4485 if (parent) 4486 parent->vmstats->state_pending[index] += slab; 4487 } 4488 } 4489 } 4490 #else 4491 static void flush_nmi_stats(struct mem_cgroup *memcg, struct mem_cgroup *parent) 4492 {} 4493 #endif 4494 4495 static void mem_cgroup_css_rstat_flush(struct cgroup_subsys_state *css, int cpu) 4496 { 4497 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 4498 struct mem_cgroup *parent = parent_mem_cgroup(memcg); 4499 struct memcg_vmstats_percpu *statc; 4500 struct aggregate_control ac; 4501 int nid; 4502 4503 flush_nmi_stats(memcg, parent); 4504 4505 statc = per_cpu_ptr(memcg->vmstats_percpu, cpu); 4506 4507 ac = (struct aggregate_control) { 4508 .aggregate = memcg->vmstats->state, 4509 .local = memcg->vmstats->state_local, 4510 .pending = memcg->vmstats->state_pending, 4511 .ppending = parent ? parent->vmstats->state_pending : NULL, 4512 .cstat = statc->state, 4513 .cstat_prev = statc->state_prev, 4514 .size = MEMCG_VMSTAT_SIZE, 4515 }; 4516 mem_cgroup_stat_aggregate(&ac); 4517 4518 ac = (struct aggregate_control) { 4519 .aggregate = memcg->vmstats->events, 4520 .local = memcg->vmstats->events_local, 4521 .pending = memcg->vmstats->events_pending, 4522 .ppending = parent ? parent->vmstats->events_pending : NULL, 4523 .cstat = statc->events, 4524 .cstat_prev = statc->events_prev, 4525 .size = NR_MEMCG_EVENTS, 4526 }; 4527 mem_cgroup_stat_aggregate(&ac); 4528 4529 for_each_node_state(nid, N_MEMORY) { 4530 struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid]; 4531 struct lruvec_stats *lstats = pn->lruvec_stats; 4532 struct lruvec_stats *plstats = NULL; 4533 struct lruvec_stats_percpu *lstatc; 4534 4535 if (parent) 4536 plstats = parent->nodeinfo[nid]->lruvec_stats; 4537 4538 lstatc = per_cpu_ptr(pn->lruvec_stats_percpu, cpu); 4539 4540 ac = (struct aggregate_control) { 4541 .aggregate = lstats->state, 4542 .local = lstats->state_local, 4543 .pending = lstats->state_pending, 4544 .ppending = plstats ? plstats->state_pending : NULL, 4545 .cstat = lstatc->state, 4546 .cstat_prev = lstatc->state_prev, 4547 .size = NR_MEMCG_NODE_STAT_ITEMS, 4548 }; 4549 mem_cgroup_stat_aggregate(&ac); 4550 4551 } 4552 WRITE_ONCE(statc->stats_updates, 0); 4553 /* We are in a per-cpu loop here, only do the atomic write once */ 4554 if (atomic_long_read(&memcg->vmstats->stats_updates)) 4555 atomic_long_set(&memcg->vmstats->stats_updates, 0); 4556 } 4557 4558 static void mem_cgroup_fork(struct task_struct *task) 4559 { 4560 /* 4561 * Set the update flag to cause task->objcg to be initialized lazily 4562 * on the first allocation. It can be done without any synchronization 4563 * because it's always performed on the current task, so does 4564 * current_objcg_update(). 4565 */ 4566 task->objcg = (struct obj_cgroup *)CURRENT_OBJCG_UPDATE_FLAG; 4567 } 4568 4569 static void mem_cgroup_exit(struct task_struct *task) 4570 { 4571 struct obj_cgroup *objcg = task->objcg; 4572 4573 objcg = (struct obj_cgroup *) 4574 ((unsigned long)objcg & ~CURRENT_OBJCG_UPDATE_FLAG); 4575 obj_cgroup_put(objcg); 4576 4577 /* 4578 * Some kernel allocations can happen after this point, 4579 * but let's ignore them. It can be done without any synchronization 4580 * because it's always performed on the current task, so does 4581 * current_objcg_update(). 4582 */ 4583 task->objcg = NULL; 4584 } 4585 4586 #ifdef CONFIG_LRU_GEN 4587 static void mem_cgroup_lru_gen_attach(struct cgroup_taskset *tset) 4588 { 4589 struct task_struct *task; 4590 struct cgroup_subsys_state *css; 4591 4592 /* find the first leader if there is any */ 4593 cgroup_taskset_for_each_leader(task, css, tset) 4594 break; 4595 4596 if (!task) 4597 return; 4598 4599 task_lock(task); 4600 if (task->mm && READ_ONCE(task->mm->owner) == task) 4601 lru_gen_migrate_mm(task->mm); 4602 task_unlock(task); 4603 } 4604 #else 4605 static void mem_cgroup_lru_gen_attach(struct cgroup_taskset *tset) {} 4606 #endif /* CONFIG_LRU_GEN */ 4607 4608 static void mem_cgroup_kmem_attach(struct cgroup_taskset *tset) 4609 { 4610 struct task_struct *task; 4611 struct cgroup_subsys_state *css; 4612 4613 cgroup_taskset_for_each(task, css, tset) { 4614 /* atomically set the update bit */ 4615 set_bit(CURRENT_OBJCG_UPDATE_BIT, (unsigned long *)&task->objcg); 4616 } 4617 } 4618 4619 static void mem_cgroup_attach(struct cgroup_taskset *tset) 4620 { 4621 mem_cgroup_lru_gen_attach(tset); 4622 mem_cgroup_kmem_attach(tset); 4623 } 4624 4625 static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value) 4626 { 4627 if (value == PAGE_COUNTER_MAX) 4628 seq_puts(m, "max\n"); 4629 else 4630 seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE); 4631 4632 return 0; 4633 } 4634 4635 static u64 memory_current_read(struct cgroup_subsys_state *css, 4636 struct cftype *cft) 4637 { 4638 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 4639 4640 return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE; 4641 } 4642 4643 #define OFP_PEAK_UNSET (((-1UL))) 4644 4645 static int peak_show(struct seq_file *sf, void *v, struct page_counter *pc) 4646 { 4647 struct cgroup_of_peak *ofp = of_peak(sf->private); 4648 u64 fd_peak = READ_ONCE(ofp->value), peak; 4649 4650 /* User wants global or local peak? */ 4651 if (fd_peak == OFP_PEAK_UNSET) 4652 peak = pc->watermark; 4653 else 4654 peak = max(fd_peak, READ_ONCE(pc->local_watermark)); 4655 4656 seq_printf(sf, "%llu\n", peak * PAGE_SIZE); 4657 return 0; 4658 } 4659 4660 static int memory_peak_show(struct seq_file *sf, void *v) 4661 { 4662 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(sf)); 4663 4664 return peak_show(sf, v, &memcg->memory); 4665 } 4666 4667 static int peak_open(struct kernfs_open_file *of) 4668 { 4669 struct cgroup_of_peak *ofp = of_peak(of); 4670 4671 ofp->value = OFP_PEAK_UNSET; 4672 return 0; 4673 } 4674 4675 static void peak_release(struct kernfs_open_file *of) 4676 { 4677 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 4678 struct cgroup_of_peak *ofp = of_peak(of); 4679 4680 if (ofp->value == OFP_PEAK_UNSET) { 4681 /* fast path (no writes on this fd) */ 4682 return; 4683 } 4684 spin_lock(&memcg->peaks_lock); 4685 list_del(&ofp->list); 4686 spin_unlock(&memcg->peaks_lock); 4687 } 4688 4689 static ssize_t peak_write(struct kernfs_open_file *of, char *buf, size_t nbytes, 4690 loff_t off, struct page_counter *pc, 4691 struct list_head *watchers) 4692 { 4693 unsigned long usage; 4694 struct cgroup_of_peak *peer_ctx; 4695 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 4696 struct cgroup_of_peak *ofp = of_peak(of); 4697 4698 spin_lock(&memcg->peaks_lock); 4699 4700 usage = page_counter_read(pc); 4701 WRITE_ONCE(pc->local_watermark, usage); 4702 4703 list_for_each_entry(peer_ctx, watchers, list) 4704 if (usage > peer_ctx->value) 4705 WRITE_ONCE(peer_ctx->value, usage); 4706 4707 /* initial write, register watcher */ 4708 if (ofp->value == OFP_PEAK_UNSET) 4709 list_add(&ofp->list, watchers); 4710 4711 WRITE_ONCE(ofp->value, usage); 4712 spin_unlock(&memcg->peaks_lock); 4713 4714 return nbytes; 4715 } 4716 4717 static ssize_t memory_peak_write(struct kernfs_open_file *of, char *buf, 4718 size_t nbytes, loff_t off) 4719 { 4720 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 4721 4722 return peak_write(of, buf, nbytes, off, &memcg->memory, 4723 &memcg->memory_peaks); 4724 } 4725 4726 #undef OFP_PEAK_UNSET 4727 4728 static int memory_min_show(struct seq_file *m, void *v) 4729 { 4730 return seq_puts_memcg_tunable(m, 4731 READ_ONCE(mem_cgroup_from_seq(m)->memory.min)); 4732 } 4733 4734 static ssize_t memory_min_write(struct kernfs_open_file *of, 4735 char *buf, size_t nbytes, loff_t off) 4736 { 4737 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 4738 unsigned long min; 4739 int err; 4740 4741 buf = strstrip(buf); 4742 err = page_counter_memparse(buf, "max", &min); 4743 if (err) 4744 return err; 4745 4746 page_counter_set_min(&memcg->memory, min); 4747 4748 return nbytes; 4749 } 4750 4751 static int memory_low_show(struct seq_file *m, void *v) 4752 { 4753 return seq_puts_memcg_tunable(m, 4754 READ_ONCE(mem_cgroup_from_seq(m)->memory.low)); 4755 } 4756 4757 static ssize_t memory_low_write(struct kernfs_open_file *of, 4758 char *buf, size_t nbytes, loff_t off) 4759 { 4760 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 4761 unsigned long low; 4762 int err; 4763 4764 buf = strstrip(buf); 4765 err = page_counter_memparse(buf, "max", &low); 4766 if (err) 4767 return err; 4768 4769 page_counter_set_low(&memcg->memory, low); 4770 4771 return nbytes; 4772 } 4773 4774 static int memory_high_show(struct seq_file *m, void *v) 4775 { 4776 return seq_puts_memcg_tunable(m, 4777 READ_ONCE(mem_cgroup_from_seq(m)->memory.high)); 4778 } 4779 4780 static ssize_t memory_high_write(struct kernfs_open_file *of, 4781 char *buf, size_t nbytes, loff_t off) 4782 { 4783 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 4784 unsigned int nr_retries = MAX_RECLAIM_RETRIES; 4785 bool drained = false; 4786 unsigned long high; 4787 int err; 4788 4789 buf = strstrip(buf); 4790 err = page_counter_memparse(buf, "max", &high); 4791 if (err) 4792 return err; 4793 4794 page_counter_set_high(&memcg->memory, high); 4795 4796 if (of->file->f_flags & O_NONBLOCK) 4797 goto out; 4798 4799 for (;;) { 4800 unsigned long nr_pages = page_counter_read(&memcg->memory); 4801 unsigned long reclaimed; 4802 4803 if (nr_pages <= high) 4804 break; 4805 4806 if (signal_pending(current)) 4807 break; 4808 4809 /* cgroup_rmdir() waits for us with cgroup_mutex held. */ 4810 if (memcg_is_dying(memcg)) 4811 break; 4812 4813 if (!drained) { 4814 drain_all_stock(memcg); 4815 drained = true; 4816 continue; 4817 } 4818 4819 reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high, 4820 GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP, NULL); 4821 4822 if (!reclaimed && !nr_retries--) 4823 break; 4824 } 4825 out: 4826 memcg_wb_domain_size_changed(memcg); 4827 return nbytes; 4828 } 4829 4830 static int memory_max_show(struct seq_file *m, void *v) 4831 { 4832 return seq_puts_memcg_tunable(m, 4833 READ_ONCE(mem_cgroup_from_seq(m)->memory.max)); 4834 } 4835 4836 static ssize_t memory_max_write(struct kernfs_open_file *of, 4837 char *buf, size_t nbytes, loff_t off) 4838 { 4839 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 4840 unsigned int nr_reclaims = MAX_RECLAIM_RETRIES; 4841 bool drained = false; 4842 unsigned long max; 4843 int err; 4844 4845 buf = strstrip(buf); 4846 err = page_counter_memparse(buf, "max", &max); 4847 if (err) 4848 return err; 4849 4850 xchg(&memcg->memory.max, max); 4851 4852 if (of->file->f_flags & O_NONBLOCK) 4853 goto out; 4854 4855 for (;;) { 4856 unsigned long nr_pages = page_counter_read(&memcg->memory); 4857 4858 if (nr_pages <= max) 4859 break; 4860 4861 if (signal_pending(current)) 4862 break; 4863 4864 /* cgroup_rmdir() waits for us with cgroup_mutex held. */ 4865 if (memcg_is_dying(memcg)) 4866 break; 4867 4868 if (!drained) { 4869 drain_all_stock(memcg); 4870 drained = true; 4871 continue; 4872 } 4873 4874 if (nr_reclaims) { 4875 if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max, 4876 GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP, NULL)) 4877 nr_reclaims--; 4878 continue; 4879 } 4880 4881 memcg_memory_event(memcg, MEMCG_OOM); 4882 if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0)) 4883 break; 4884 cond_resched(); 4885 } 4886 out: 4887 memcg_wb_domain_size_changed(memcg); 4888 return nbytes; 4889 } 4890 4891 /* 4892 * Note: don't forget to update the 'samples/cgroup/memcg_event_listener' 4893 * if any new events become available. 4894 */ 4895 static void __memory_events_show(struct seq_file *m, atomic_long_t *events) 4896 { 4897 seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW])); 4898 seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH])); 4899 seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX])); 4900 seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM])); 4901 seq_printf(m, "oom_kill %lu\n", 4902 atomic_long_read(&events[MEMCG_OOM_KILL])); 4903 seq_printf(m, "oom_group_kill %lu\n", 4904 atomic_long_read(&events[MEMCG_OOM_GROUP_KILL])); 4905 seq_printf(m, "sock_throttled %lu\n", 4906 atomic_long_read(&events[MEMCG_SOCK_THROTTLED])); 4907 } 4908 4909 static int memory_events_show(struct seq_file *m, void *v) 4910 { 4911 struct mem_cgroup *memcg = mem_cgroup_from_seq(m); 4912 4913 __memory_events_show(m, memcg->memory_events); 4914 return 0; 4915 } 4916 4917 static int memory_events_local_show(struct seq_file *m, void *v) 4918 { 4919 struct mem_cgroup *memcg = mem_cgroup_from_seq(m); 4920 4921 __memory_events_show(m, memcg->memory_events_local); 4922 return 0; 4923 } 4924 4925 int memory_stat_show(struct seq_file *m, void *v) 4926 { 4927 struct mem_cgroup *memcg = mem_cgroup_from_seq(m); 4928 char *buf = kmalloc(SEQ_BUF_SIZE, GFP_KERNEL); 4929 struct seq_buf s; 4930 4931 if (!buf) 4932 return -ENOMEM; 4933 seq_buf_init(&s, buf, SEQ_BUF_SIZE); 4934 memory_stat_format(memcg, &s); 4935 seq_puts(m, buf); 4936 kfree(buf); 4937 return 0; 4938 } 4939 4940 #ifdef CONFIG_NUMA 4941 static inline unsigned long lruvec_page_state_output(struct lruvec *lruvec, 4942 int item) 4943 { 4944 return lruvec_page_state(lruvec, item) * 4945 memcg_page_state_output_unit(item); 4946 } 4947 4948 static int memory_numa_stat_show(struct seq_file *m, void *v) 4949 { 4950 int i; 4951 struct mem_cgroup *memcg = mem_cgroup_from_seq(m); 4952 4953 mem_cgroup_flush_stats(memcg); 4954 4955 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) { 4956 int nid; 4957 4958 if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS) 4959 continue; 4960 4961 seq_printf(m, "%s", memory_stats[i].name); 4962 for_each_node_state(nid, N_MEMORY) { 4963 u64 size; 4964 struct lruvec *lruvec; 4965 4966 lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid)); 4967 size = lruvec_page_state_output(lruvec, 4968 memory_stats[i].idx); 4969 seq_printf(m, " N%d=%llu", nid, size); 4970 } 4971 seq_putc(m, '\n'); 4972 } 4973 4974 return 0; 4975 } 4976 #endif 4977 4978 static int memory_oom_group_show(struct seq_file *m, void *v) 4979 { 4980 struct mem_cgroup *memcg = mem_cgroup_from_seq(m); 4981 4982 seq_printf(m, "%d\n", READ_ONCE(memcg->oom_group)); 4983 4984 return 0; 4985 } 4986 4987 static ssize_t memory_oom_group_write(struct kernfs_open_file *of, 4988 char *buf, size_t nbytes, loff_t off) 4989 { 4990 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 4991 int ret, oom_group; 4992 4993 buf = strstrip(buf); 4994 if (!buf) 4995 return -EINVAL; 4996 4997 ret = kstrtoint(buf, 0, &oom_group); 4998 if (ret) 4999 return ret; 5000 5001 if (oom_group != 0 && oom_group != 1) 5002 return -EINVAL; 5003 5004 WRITE_ONCE(memcg->oom_group, oom_group); 5005 5006 return nbytes; 5007 } 5008 5009 static ssize_t memory_reclaim(struct kernfs_open_file *of, char *buf, 5010 size_t nbytes, loff_t off) 5011 { 5012 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 5013 int ret; 5014 5015 ret = user_proactive_reclaim(buf, memcg, NULL); 5016 if (ret) 5017 return ret; 5018 5019 return nbytes; 5020 } 5021 5022 static struct cftype memory_files[] = { 5023 { 5024 .name = "current", 5025 .flags = CFTYPE_NOT_ON_ROOT, 5026 .read_u64 = memory_current_read, 5027 }, 5028 { 5029 .name = "peak", 5030 .flags = CFTYPE_NOT_ON_ROOT, 5031 .open = peak_open, 5032 .release = peak_release, 5033 .seq_show = memory_peak_show, 5034 .write = memory_peak_write, 5035 }, 5036 { 5037 .name = "min", 5038 .flags = CFTYPE_NOT_ON_ROOT, 5039 .seq_show = memory_min_show, 5040 .write = memory_min_write, 5041 }, 5042 { 5043 .name = "low", 5044 .flags = CFTYPE_NOT_ON_ROOT, 5045 .seq_show = memory_low_show, 5046 .write = memory_low_write, 5047 }, 5048 { 5049 .name = "high", 5050 .flags = CFTYPE_NOT_ON_ROOT, 5051 .seq_show = memory_high_show, 5052 .write = memory_high_write, 5053 }, 5054 { 5055 .name = "max", 5056 .flags = CFTYPE_NOT_ON_ROOT, 5057 .seq_show = memory_max_show, 5058 .write = memory_max_write, 5059 }, 5060 { 5061 .name = "events", 5062 .flags = CFTYPE_NOT_ON_ROOT, 5063 .file_offset = offsetof(struct mem_cgroup, events_file), 5064 .seq_show = memory_events_show, 5065 }, 5066 { 5067 .name = "events.local", 5068 .flags = CFTYPE_NOT_ON_ROOT, 5069 .file_offset = offsetof(struct mem_cgroup, events_local_file), 5070 .seq_show = memory_events_local_show, 5071 }, 5072 { 5073 .name = "stat", 5074 .seq_show = memory_stat_show, 5075 }, 5076 #ifdef CONFIG_NUMA 5077 { 5078 .name = "numa_stat", 5079 .seq_show = memory_numa_stat_show, 5080 }, 5081 #endif 5082 { 5083 .name = "oom.group", 5084 .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE, 5085 .seq_show = memory_oom_group_show, 5086 .write = memory_oom_group_write, 5087 }, 5088 { 5089 .name = "reclaim", 5090 .flags = CFTYPE_NS_DELEGATABLE, 5091 .write = memory_reclaim, 5092 }, 5093 { } /* terminate */ 5094 }; 5095 5096 struct cgroup_subsys memory_cgrp_subsys = { 5097 .css_alloc = mem_cgroup_css_alloc, 5098 .css_online = mem_cgroup_css_online, 5099 .css_offline = mem_cgroup_css_offline, 5100 .css_released = mem_cgroup_css_released, 5101 .css_free = mem_cgroup_css_free, 5102 .css_reset = mem_cgroup_css_reset, 5103 .css_rstat_flush = mem_cgroup_css_rstat_flush, 5104 .attach = mem_cgroup_attach, 5105 .fork = mem_cgroup_fork, 5106 .exit = mem_cgroup_exit, 5107 .dfl_cftypes = memory_files, 5108 #ifdef CONFIG_MEMCG_V1 5109 .legacy_cftypes = mem_cgroup_legacy_files, 5110 #endif 5111 .early_init = 0, 5112 }; 5113 5114 /** 5115 * mem_cgroup_calculate_protection - check if memory consumption is in the normal range 5116 * @root: the top ancestor of the sub-tree being checked 5117 * @memcg: the memory cgroup to check 5118 * 5119 * WARNING: This function is not stateless! It can only be used as part 5120 * of a top-down tree iteration, not for isolated queries. 5121 */ 5122 void mem_cgroup_calculate_protection(struct mem_cgroup *root, 5123 struct mem_cgroup *memcg) 5124 { 5125 bool recursive_protection = 5126 cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT; 5127 5128 if (mem_cgroup_disabled()) 5129 return; 5130 5131 if (!root) 5132 root = root_mem_cgroup; 5133 5134 page_counter_calculate_protection(&root->memory, &memcg->memory, recursive_protection); 5135 } 5136 5137 static int charge_memcg(struct folio *folio, struct mem_cgroup *memcg, 5138 gfp_t gfp) 5139 { 5140 int ret = 0; 5141 struct obj_cgroup *objcg; 5142 5143 objcg = get_obj_cgroup_from_memcg(memcg, folio_nid(folio)); 5144 /* Do not account at the root objcg level. */ 5145 if (!obj_cgroup_is_root(objcg)) 5146 ret = try_charge_memcg(memcg, gfp, folio_nr_pages(folio)); 5147 if (ret) { 5148 obj_cgroup_put(objcg); 5149 return ret; 5150 } 5151 commit_charge(folio, objcg); 5152 memcg1_commit_charge(folio, memcg); 5153 5154 return ret; 5155 } 5156 5157 int __mem_cgroup_charge(struct folio *folio, struct mm_struct *mm, gfp_t gfp) 5158 { 5159 struct mem_cgroup *memcg; 5160 int ret; 5161 5162 memcg = get_mem_cgroup_from_mm(mm); 5163 ret = charge_memcg(folio, memcg, gfp); 5164 css_put(&memcg->css); 5165 5166 return ret; 5167 } 5168 5169 /** 5170 * mem_cgroup_charge_hugetlb - charge the memcg for a hugetlb folio 5171 * @folio: folio being charged 5172 * @gfp: reclaim mode 5173 * 5174 * This function is called when allocating a huge page folio, after the page has 5175 * already been obtained and charged to the appropriate hugetlb cgroup 5176 * controller (if it is enabled). 5177 * 5178 * Returns ENOMEM if the memcg is already full. 5179 * Returns 0 if either the charge was successful, or if we skip the charging. 5180 */ 5181 int mem_cgroup_charge_hugetlb(struct folio *folio, gfp_t gfp) 5182 { 5183 struct mem_cgroup *memcg = get_mem_cgroup_from_current(); 5184 int ret = 0; 5185 5186 /* 5187 * Even memcg does not account for hugetlb, we still want to update 5188 * system-level stats via lruvec_stat_mod_folio. Return 0, and skip 5189 * charging the memcg. 5190 */ 5191 if (mem_cgroup_disabled() || !memcg_accounts_hugetlb() || 5192 !memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys)) 5193 goto out; 5194 5195 if (charge_memcg(folio, memcg, gfp)) 5196 ret = -ENOMEM; 5197 5198 out: 5199 mem_cgroup_put(memcg); 5200 return ret; 5201 } 5202 5203 /** 5204 * mem_cgroup_swapin_charge_folio - Charge a newly allocated folio for swapin. 5205 * @folio: the folio to charge 5206 * @id: memory cgroup id 5207 * @mm: mm context of the victim 5208 * @gfp: reclaim mode 5209 * 5210 * This function charges a folio allocated for swapin. Please call this before 5211 * adding the folio to the swapcache. 5212 * 5213 * Returns 0 on success. Otherwise, an error code is returned. 5214 */ 5215 int mem_cgroup_swapin_charge_folio(struct folio *folio, unsigned short id, 5216 struct mm_struct *mm, gfp_t gfp) 5217 { 5218 struct mem_cgroup *memcg; 5219 int ret; 5220 5221 if (mem_cgroup_disabled()) 5222 return 0; 5223 5224 rcu_read_lock(); 5225 memcg = mem_cgroup_from_private_id(id); 5226 if (!memcg || !css_tryget_online(&memcg->css)) 5227 memcg = get_mem_cgroup_from_mm(mm); 5228 rcu_read_unlock(); 5229 5230 ret = charge_memcg(folio, memcg, gfp); 5231 5232 css_put(&memcg->css); 5233 return ret; 5234 } 5235 5236 struct uncharge_gather { 5237 struct obj_cgroup *objcg; 5238 unsigned long nr_memory; 5239 unsigned long pgpgout; 5240 unsigned long nr_kmem; 5241 int nid; 5242 }; 5243 5244 static inline void uncharge_gather_clear(struct uncharge_gather *ug) 5245 { 5246 memset(ug, 0, sizeof(*ug)); 5247 } 5248 5249 static void uncharge_batch(const struct uncharge_gather *ug) 5250 { 5251 struct mem_cgroup *memcg; 5252 5253 rcu_read_lock(); 5254 memcg = obj_cgroup_memcg(ug->objcg); 5255 if (ug->nr_memory) { 5256 memcg_uncharge(memcg, ug->nr_memory); 5257 if (ug->nr_kmem) { 5258 mod_memcg_state(memcg, MEMCG_KMEM, -ug->nr_kmem); 5259 memcg1_account_kmem(memcg, -ug->nr_kmem); 5260 } 5261 memcg1_oom_recover(memcg); 5262 } 5263 5264 memcg1_uncharge_batch(memcg, ug->pgpgout, ug->nr_memory, ug->nid); 5265 rcu_read_unlock(); 5266 5267 /* drop reference from uncharge_folio */ 5268 obj_cgroup_put(ug->objcg); 5269 } 5270 5271 static void uncharge_folio(struct folio *folio, struct uncharge_gather *ug) 5272 { 5273 long nr_pages; 5274 struct obj_cgroup *objcg; 5275 5276 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio); 5277 5278 /* 5279 * Nobody should be changing or seriously looking at 5280 * folio objcg at this point, we have fully exclusive 5281 * access to the folio. 5282 */ 5283 objcg = folio_objcg(folio); 5284 if (!objcg) 5285 return; 5286 5287 if (ug->objcg != objcg) { 5288 if (ug->objcg) { 5289 uncharge_batch(ug); 5290 uncharge_gather_clear(ug); 5291 } 5292 ug->objcg = objcg; 5293 ug->nid = folio_nid(folio); 5294 5295 /* pairs with obj_cgroup_put in uncharge_batch */ 5296 obj_cgroup_get(objcg); 5297 } 5298 5299 nr_pages = folio_nr_pages(folio); 5300 5301 if (folio_memcg_kmem(folio)) { 5302 ug->nr_memory += nr_pages; 5303 ug->nr_kmem += nr_pages; 5304 } else { 5305 /* LRU pages aren't accounted at the root level */ 5306 if (!obj_cgroup_is_root(objcg)) 5307 ug->nr_memory += nr_pages; 5308 ug->pgpgout++; 5309 5310 WARN_ON_ONCE(folio_unqueue_deferred_split(folio)); 5311 } 5312 5313 folio->memcg_data = 0; 5314 obj_cgroup_put(objcg); 5315 } 5316 5317 void __mem_cgroup_uncharge(struct folio *folio) 5318 { 5319 struct uncharge_gather ug; 5320 5321 /* Don't touch folio->lru of any random page, pre-check: */ 5322 if (!folio_memcg_charged(folio)) 5323 return; 5324 5325 uncharge_gather_clear(&ug); 5326 uncharge_folio(folio, &ug); 5327 uncharge_batch(&ug); 5328 } 5329 5330 void __mem_cgroup_uncharge_folios(struct folio_batch *folios) 5331 { 5332 struct uncharge_gather ug; 5333 unsigned int i; 5334 5335 uncharge_gather_clear(&ug); 5336 for (i = 0; i < folios->nr; i++) 5337 uncharge_folio(folios->folios[i], &ug); 5338 if (ug.objcg) 5339 uncharge_batch(&ug); 5340 } 5341 5342 /* 5343 * An LRU folio must hold the objcg belonging to its own node. 5344 * 5345 * memcg_reparent_objcgs() reparents a dying cgroup one node at a time: the 5346 * folios on that node's LRU lists move to the parent and that node's objcg is 5347 * redirected to the parent, atomically under the node's lru_lock. 5348 * folio_lruvec_lock() relies on this to provide a stable folio<->lruvec 5349 * binding. If a folio holds another node's objcg, its list membership and its 5350 * lruvec resolution change in separate lock sections, and an LRU operation in 5351 * between can re-add the folio to, and strand it on, the LRU list of a dead 5352 * memcg. 5353 * 5354 * So when migration transfers the memcg state to a folio on another node, 5355 * re-derive the objcg for the destination node. If the memcg is dying and the 5356 * destination node has already been reparented, the lookup walks up to the 5357 * nearest live ancestor - which is also where that node's LRU lists went. 5358 * 5359 * Returns the objcg to commit to @new, with a reference for the caller. 5360 */ 5361 static struct obj_cgroup *get_migration_objcg(struct folio *old, 5362 struct folio *new) 5363 { 5364 struct obj_cgroup *old_objcg, *new_objcg; 5365 int new_nid = folio_nid(new); 5366 5367 old_objcg = get_obj_cgroup_from_folio(old); 5368 5369 if (folio_nid(old) == new_nid) 5370 return old_objcg; 5371 5372 rcu_read_lock(); 5373 new_objcg = __get_obj_cgroup_from_memcg(obj_cgroup_memcg(old_objcg), 5374 new_nid); 5375 rcu_read_unlock(); 5376 5377 obj_cgroup_put(old_objcg); 5378 5379 return new_objcg; 5380 } 5381 5382 /** 5383 * mem_cgroup_replace_folio - Charge a folio's replacement. 5384 * @old: Currently circulating folio. 5385 * @new: Replacement folio. 5386 * 5387 * Charge @new as a replacement folio for @old. @old will 5388 * be uncharged upon free. 5389 * 5390 * Both folios must be locked, @new->mapping must be set up. 5391 */ 5392 void mem_cgroup_replace_folio(struct folio *old, struct folio *new) 5393 { 5394 struct mem_cgroup *memcg; 5395 struct obj_cgroup *objcg; 5396 long nr_pages = folio_nr_pages(new); 5397 5398 VM_BUG_ON_FOLIO(!folio_test_locked(old), old); 5399 VM_BUG_ON_FOLIO(!folio_test_locked(new), new); 5400 VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new); 5401 VM_BUG_ON_FOLIO(folio_nr_pages(old) != nr_pages, new); 5402 5403 if (mem_cgroup_disabled()) 5404 return; 5405 5406 /* Page cache replacement: new folio already charged? */ 5407 if (folio_memcg_charged(new)) 5408 return; 5409 5410 VM_WARN_ON_ONCE_FOLIO(!folio_objcg(old), old); 5411 if (!folio_objcg(old)) 5412 return; 5413 5414 objcg = get_migration_objcg(old, new); 5415 5416 rcu_read_lock(); 5417 memcg = obj_cgroup_memcg(objcg); 5418 5419 /* 5420 * Force-charge the new page. The old one will be freed soon. 5421 * 5422 * The rootness of the committed objcg decides whether the final 5423 * uncharge of @new goes through the page counters (see 5424 * uncharge_folio()); charge them only if the uncharge will. 5425 */ 5426 if (!obj_cgroup_is_root(objcg)) { 5427 page_counter_charge(&memcg->memory, nr_pages); 5428 if (do_memsw_account()) 5429 page_counter_charge(&memcg->memsw, nr_pages); 5430 } 5431 5432 commit_charge(new, objcg); 5433 memcg1_commit_charge(new, memcg); 5434 rcu_read_unlock(); 5435 } 5436 5437 /** 5438 * mem_cgroup_migrate - Transfer the memcg data from the old to the new folio. 5439 * @old: Currently circulating folio. 5440 * @new: Replacement folio. 5441 * 5442 * Transfer the memcg data from the old folio to the new folio for migration. 5443 * The old folio's data info will be cleared. The memory counters remain 5444 * unchanged, unless the charge moves out of a fully reparented ancestry 5445 * and has to be settled (see below). 5446 * 5447 * Both folios must be locked, @new->mapping must be set up. 5448 */ 5449 void mem_cgroup_migrate(struct folio *old, struct folio *new) 5450 { 5451 struct obj_cgroup *objcg, *new_objcg; 5452 5453 VM_BUG_ON_FOLIO(!folio_test_locked(old), old); 5454 VM_BUG_ON_FOLIO(!folio_test_locked(new), new); 5455 VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new); 5456 VM_BUG_ON_FOLIO(folio_nr_pages(old) != folio_nr_pages(new), new); 5457 VM_BUG_ON_FOLIO(folio_test_lru(old), old); 5458 5459 if (mem_cgroup_disabled()) 5460 return; 5461 5462 objcg = folio_objcg(old); 5463 /* 5464 * Note that it is normal to see !objcg for a hugetlb folio. 5465 * For e.g, it could have been allocated when memory_hugetlb_accounting 5466 * was not selected. 5467 */ 5468 VM_WARN_ON_ONCE_FOLIO(!folio_test_hugetlb(old) && !objcg, old); 5469 if (!objcg) 5470 return; 5471 5472 new_objcg = get_migration_objcg(old, new); 5473 5474 /* 5475 * @old was charged through a non-root objcg, so its charge is in the 5476 * page counters. If the re-derivation walked up to the root objcg - 5477 * @old's entire ancestry is dying and already reparented - the final 5478 * uncharge of @new will skip the page counters (see uncharge_folio()). 5479 * Settle them now: this is @old's eventual uncharge, moved up to the 5480 * point where its charge record ends. 5481 */ 5482 if (obj_cgroup_is_root(new_objcg) && !obj_cgroup_is_root(objcg)) { 5483 rcu_read_lock(); 5484 memcg_uncharge(obj_cgroup_memcg(objcg), folio_nr_pages(old)); 5485 rcu_read_unlock(); 5486 } 5487 5488 commit_charge(new, new_objcg); 5489 5490 /* Warning should never happen, so don't worry about refcount non-0 */ 5491 WARN_ON_ONCE(folio_unqueue_deferred_split(old)); 5492 old->memcg_data = 0; 5493 5494 /* @new holds its own reference now, drop @old's */ 5495 obj_cgroup_put(objcg); 5496 } 5497 5498 DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key); 5499 EXPORT_SYMBOL(memcg_sockets_enabled_key); 5500 5501 void mem_cgroup_sk_alloc(struct sock *sk) 5502 { 5503 struct mem_cgroup *memcg; 5504 5505 if (!mem_cgroup_sockets_enabled) 5506 return; 5507 5508 /* Do not associate the sock with unrelated interrupted task's memcg. */ 5509 if (!in_task()) 5510 return; 5511 5512 rcu_read_lock(); 5513 memcg = mem_cgroup_from_task(current); 5514 if (mem_cgroup_is_root(memcg)) 5515 goto out; 5516 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg1_tcpmem_active(memcg)) 5517 goto out; 5518 if (css_tryget(&memcg->css)) 5519 sk->sk_memcg = memcg; 5520 out: 5521 rcu_read_unlock(); 5522 } 5523 5524 void mem_cgroup_sk_free(struct sock *sk) 5525 { 5526 struct mem_cgroup *memcg = mem_cgroup_from_sk(sk); 5527 5528 if (memcg) 5529 css_put(&memcg->css); 5530 } 5531 5532 void mem_cgroup_sk_inherit(const struct sock *sk, struct sock *newsk) 5533 { 5534 struct mem_cgroup *memcg; 5535 5536 if (sk->sk_memcg == newsk->sk_memcg) 5537 return; 5538 5539 mem_cgroup_sk_free(newsk); 5540 5541 memcg = mem_cgroup_from_sk(sk); 5542 if (memcg) 5543 css_get(&memcg->css); 5544 5545 newsk->sk_memcg = sk->sk_memcg; 5546 } 5547 5548 /** 5549 * mem_cgroup_sk_charge - charge socket memory 5550 * @sk: socket in memcg to charge 5551 * @nr_pages: number of pages to charge 5552 * @gfp_mask: reclaim mode 5553 * 5554 * Charges @nr_pages to @memcg. Returns %true if the charge fit within 5555 * @memcg's configured limit, %false if it doesn't. 5556 */ 5557 bool mem_cgroup_sk_charge(const struct sock *sk, unsigned int nr_pages, 5558 gfp_t gfp_mask) 5559 { 5560 struct mem_cgroup *memcg = mem_cgroup_from_sk(sk); 5561 5562 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) 5563 return memcg1_charge_skmem(memcg, nr_pages, gfp_mask); 5564 5565 if (try_charge_memcg(memcg, gfp_mask, nr_pages) == 0) { 5566 mod_memcg_state(memcg, MEMCG_SOCK, nr_pages); 5567 return true; 5568 } 5569 5570 return false; 5571 } 5572 5573 /** 5574 * mem_cgroup_sk_uncharge - uncharge socket memory 5575 * @sk: socket in memcg to uncharge 5576 * @nr_pages: number of pages to uncharge 5577 */ 5578 void mem_cgroup_sk_uncharge(const struct sock *sk, unsigned int nr_pages) 5579 { 5580 struct mem_cgroup *memcg = mem_cgroup_from_sk(sk); 5581 5582 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) { 5583 memcg1_uncharge_skmem(memcg, nr_pages); 5584 return; 5585 } 5586 5587 mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages); 5588 5589 refill_stock(memcg, nr_pages); 5590 } 5591 5592 void mem_cgroup_flush_workqueue(void) 5593 { 5594 flush_workqueue(memcg_wq); 5595 } 5596 5597 static int __init cgroup_memory(char *s) 5598 { 5599 char *token; 5600 5601 while ((token = strsep(&s, ",")) != NULL) { 5602 if (!*token) 5603 continue; 5604 if (!strcmp(token, "nosocket")) 5605 cgroup_memory_nosocket = true; 5606 if (!strcmp(token, "nokmem")) 5607 cgroup_memory_nokmem = true; 5608 if (!strcmp(token, "nobpf")) 5609 cgroup_memory_nobpf = true; 5610 } 5611 return 1; 5612 } 5613 __setup("cgroup.memory=", cgroup_memory); 5614 5615 /* 5616 * Memory controller init before cgroup_init() initialize root_mem_cgroup. 5617 * 5618 * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this 5619 * context because of lock dependencies (cgroup_lock -> cpu hotplug) but 5620 * basically everything that doesn't depend on a specific mem_cgroup structure 5621 * should be initialized from here. 5622 */ 5623 int __init mem_cgroup_init(void) 5624 { 5625 unsigned int memcg_size; 5626 int cpu; 5627 5628 /* 5629 * Currently s32 type (can refer to struct batched_lruvec_stat) is 5630 * used for per-memcg-per-cpu caching of per-node statistics. In order 5631 * to work fine, we should make sure that the overfill threshold can't 5632 * exceed S32_MAX / PAGE_SIZE. 5633 */ 5634 BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE); 5635 5636 cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL, 5637 memcg_hotplug_cpu_dead); 5638 5639 memcg_wq = alloc_workqueue("memcg", WQ_PERCPU, 0); 5640 WARN_ON(!memcg_wq); 5641 5642 for_each_possible_cpu(cpu) { 5643 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work, 5644 drain_local_memcg_stock); 5645 INIT_WORK(&per_cpu_ptr(&obj_stock, cpu)->work, 5646 drain_local_obj_stock); 5647 } 5648 5649 memcg_size = struct_size_t(struct mem_cgroup, nodeinfo, nr_node_ids); 5650 memcg_cachep = kmem_cache_create("mem_cgroup", memcg_size, 0, 5651 SLAB_PANIC | SLAB_HWCACHE_ALIGN, NULL); 5652 5653 memcg_pn_cachep = KMEM_CACHE(mem_cgroup_per_node, 5654 SLAB_PANIC | SLAB_HWCACHE_ALIGN); 5655 5656 return 0; 5657 } 5658 5659 #ifdef CONFIG_SWAP 5660 /** 5661 * __mem_cgroup_try_charge_swap - try charging swap space for a folio 5662 * @folio: folio being added to swap 5663 * 5664 * Try to charge @folio's memcg for the swap space at folio->swap. 5665 * 5666 * Returns 0 on success, -ENOMEM on failure. 5667 */ 5668 int __mem_cgroup_try_charge_swap(struct folio *folio) 5669 { 5670 unsigned int nr_pages = folio_nr_pages(folio); 5671 struct swap_cluster_info *ci; 5672 struct page_counter *counter; 5673 struct mem_cgroup *memcg; 5674 struct obj_cgroup *objcg; 5675 5676 if (do_memsw_account()) 5677 return 0; 5678 5679 objcg = folio_objcg(folio); 5680 VM_WARN_ON_ONCE_FOLIO(!objcg, folio); 5681 if (!objcg) 5682 return 0; 5683 5684 rcu_read_lock(); 5685 memcg = obj_cgroup_memcg(objcg); 5686 if (!folio_test_swapcache(folio)) { 5687 memcg_memory_event(memcg, MEMCG_SWAP_FAIL); 5688 rcu_read_unlock(); 5689 return 0; 5690 } 5691 5692 memcg = mem_cgroup_private_id_get_online(memcg, nr_pages); 5693 /* memcg is pined by memcg ID. */ 5694 rcu_read_unlock(); 5695 5696 if (!mem_cgroup_is_root(memcg) && 5697 !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) { 5698 memcg_memory_event(memcg, MEMCG_SWAP_MAX); 5699 memcg_memory_event(memcg, MEMCG_SWAP_FAIL); 5700 mem_cgroup_private_id_put(memcg, nr_pages); 5701 return -ENOMEM; 5702 } 5703 mod_memcg_state(memcg, MEMCG_SWAP, nr_pages); 5704 5705 ci = swap_cluster_get_and_lock(folio); 5706 __swap_cgroup_set(ci, swp_cluster_offset(folio->swap), nr_pages, 5707 mem_cgroup_private_id(memcg)); 5708 swap_cluster_unlock(ci); 5709 5710 return 0; 5711 } 5712 5713 /** 5714 * __mem_cgroup_uncharge_swap - uncharge swap space 5715 * @id: cgroup id to uncharge 5716 * @nr_pages: the amount of swap space to uncharge 5717 */ 5718 void __mem_cgroup_uncharge_swap(unsigned short id, unsigned int nr_pages) 5719 { 5720 struct mem_cgroup *memcg; 5721 5722 rcu_read_lock(); 5723 memcg = mem_cgroup_from_private_id(id); 5724 if (memcg) { 5725 if (!mem_cgroup_is_root(memcg)) { 5726 if (do_memsw_account()) 5727 page_counter_uncharge(&memcg->memsw, nr_pages); 5728 else 5729 page_counter_uncharge(&memcg->swap, nr_pages); 5730 } 5731 mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages); 5732 mem_cgroup_private_id_put(memcg, nr_pages); 5733 } 5734 rcu_read_unlock(); 5735 } 5736 5737 long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg) 5738 { 5739 long nr_swap_pages = get_nr_swap_pages(); 5740 5741 if (mem_cgroup_disabled() || do_memsw_account()) 5742 return nr_swap_pages; 5743 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) 5744 nr_swap_pages = min_t(long, nr_swap_pages, 5745 READ_ONCE(memcg->swap.max) - 5746 page_counter_read(&memcg->swap)); 5747 return nr_swap_pages; 5748 } 5749 5750 bool mem_cgroup_swap_full(struct folio *folio) 5751 { 5752 struct mem_cgroup *memcg; 5753 bool ret = false; 5754 5755 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); 5756 5757 if (vm_swap_full()) 5758 return true; 5759 if (do_memsw_account() || !folio_memcg_charged(folio)) 5760 return ret; 5761 5762 rcu_read_lock(); 5763 memcg = folio_memcg(folio); 5764 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) { 5765 unsigned long usage = page_counter_read(&memcg->swap); 5766 5767 if (usage * 2 >= READ_ONCE(memcg->swap.high) || 5768 usage * 2 >= READ_ONCE(memcg->swap.max)) { 5769 ret = true; 5770 break; 5771 } 5772 } 5773 rcu_read_unlock(); 5774 5775 return ret; 5776 } 5777 5778 static int __init setup_swap_account(char *s) 5779 { 5780 bool res; 5781 5782 if (!kstrtobool(s, &res) && !res) 5783 pr_warn_once("The swapaccount=0 commandline option is deprecated " 5784 "in favor of configuring swap control via cgroupfs. " 5785 "Please report your usecase to linux-mm@kvack.org if you " 5786 "depend on this functionality.\n"); 5787 return 1; 5788 } 5789 __setup("swapaccount=", setup_swap_account); 5790 5791 static u64 swap_current_read(struct cgroup_subsys_state *css, 5792 struct cftype *cft) 5793 { 5794 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 5795 5796 return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE; 5797 } 5798 5799 static int swap_peak_show(struct seq_file *sf, void *v) 5800 { 5801 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(sf)); 5802 5803 return peak_show(sf, v, &memcg->swap); 5804 } 5805 5806 static ssize_t swap_peak_write(struct kernfs_open_file *of, char *buf, 5807 size_t nbytes, loff_t off) 5808 { 5809 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 5810 5811 return peak_write(of, buf, nbytes, off, &memcg->swap, 5812 &memcg->swap_peaks); 5813 } 5814 5815 static int swap_high_show(struct seq_file *m, void *v) 5816 { 5817 return seq_puts_memcg_tunable(m, 5818 READ_ONCE(mem_cgroup_from_seq(m)->swap.high)); 5819 } 5820 5821 static ssize_t swap_high_write(struct kernfs_open_file *of, 5822 char *buf, size_t nbytes, loff_t off) 5823 { 5824 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 5825 unsigned long high; 5826 int err; 5827 5828 buf = strstrip(buf); 5829 err = page_counter_memparse(buf, "max", &high); 5830 if (err) 5831 return err; 5832 5833 page_counter_set_high(&memcg->swap, high); 5834 5835 return nbytes; 5836 } 5837 5838 static int swap_max_show(struct seq_file *m, void *v) 5839 { 5840 return seq_puts_memcg_tunable(m, 5841 READ_ONCE(mem_cgroup_from_seq(m)->swap.max)); 5842 } 5843 5844 static ssize_t swap_max_write(struct kernfs_open_file *of, 5845 char *buf, size_t nbytes, loff_t off) 5846 { 5847 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 5848 unsigned long max; 5849 int err; 5850 5851 buf = strstrip(buf); 5852 err = page_counter_memparse(buf, "max", &max); 5853 if (err) 5854 return err; 5855 5856 xchg(&memcg->swap.max, max); 5857 5858 return nbytes; 5859 } 5860 5861 static int swap_events_show(struct seq_file *m, void *v) 5862 { 5863 struct mem_cgroup *memcg = mem_cgroup_from_seq(m); 5864 5865 seq_printf(m, "high %lu\n", 5866 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH])); 5867 seq_printf(m, "max %lu\n", 5868 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX])); 5869 seq_printf(m, "fail %lu\n", 5870 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL])); 5871 5872 return 0; 5873 } 5874 5875 static struct cftype swap_files[] = { 5876 { 5877 .name = "swap.current", 5878 .flags = CFTYPE_NOT_ON_ROOT, 5879 .read_u64 = swap_current_read, 5880 }, 5881 { 5882 .name = "swap.high", 5883 .flags = CFTYPE_NOT_ON_ROOT, 5884 .seq_show = swap_high_show, 5885 .write = swap_high_write, 5886 }, 5887 { 5888 .name = "swap.max", 5889 .flags = CFTYPE_NOT_ON_ROOT, 5890 .seq_show = swap_max_show, 5891 .write = swap_max_write, 5892 }, 5893 { 5894 .name = "swap.peak", 5895 .flags = CFTYPE_NOT_ON_ROOT, 5896 .open = peak_open, 5897 .release = peak_release, 5898 .seq_show = swap_peak_show, 5899 .write = swap_peak_write, 5900 }, 5901 { 5902 .name = "swap.events", 5903 .flags = CFTYPE_NOT_ON_ROOT, 5904 .file_offset = offsetof(struct mem_cgroup, swap_events_file), 5905 .seq_show = swap_events_show, 5906 }, 5907 { } /* terminate */ 5908 }; 5909 5910 #ifdef CONFIG_ZSWAP 5911 /** 5912 * obj_cgroup_may_zswap - check if this cgroup can zswap 5913 * @objcg: the object cgroup 5914 * 5915 * Check if the hierarchical zswap limit has been reached. 5916 * 5917 * This doesn't check for specific headroom, and it is not atomic 5918 * either. But with zswap, the size of the allocation is only known 5919 * once compression has occurred, and this optimistic pre-check avoids 5920 * spending cycles on compression when there is already no room left 5921 * or zswap is disabled altogether somewhere in the hierarchy. 5922 */ 5923 bool obj_cgroup_may_zswap(struct obj_cgroup *objcg) 5924 { 5925 struct mem_cgroup *memcg, *original_memcg; 5926 bool ret = true; 5927 5928 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) 5929 return true; 5930 5931 original_memcg = get_mem_cgroup_from_objcg(objcg); 5932 for (memcg = original_memcg; !mem_cgroup_is_root(memcg); 5933 memcg = parent_mem_cgroup(memcg)) { 5934 unsigned long max = READ_ONCE(memcg->zswap_max); 5935 unsigned long pages; 5936 5937 if (max == PAGE_COUNTER_MAX) 5938 continue; 5939 if (max == 0) { 5940 ret = false; 5941 break; 5942 } 5943 5944 /* Force flush to get accurate stats for charging */ 5945 __mem_cgroup_flush_stats(memcg, true); 5946 pages = memcg_page_state(memcg, MEMCG_ZSWAP_B) / PAGE_SIZE; 5947 if (pages < max) 5948 continue; 5949 ret = false; 5950 break; 5951 } 5952 mem_cgroup_put(original_memcg); 5953 return ret; 5954 } 5955 5956 /** 5957 * obj_cgroup_charge_zswap - charge compression backend memory 5958 * @objcg: the object cgroup 5959 * @size: size of compressed object 5960 * 5961 * This forces the charge after obj_cgroup_may_zswap() allowed 5962 * compression and storage in zswap for this cgroup to go ahead. 5963 */ 5964 void obj_cgroup_charge_zswap(struct obj_cgroup *objcg, size_t size) 5965 { 5966 struct mem_cgroup *memcg; 5967 5968 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) 5969 return; 5970 5971 if (obj_cgroup_is_root(objcg)) 5972 return; 5973 5974 VM_WARN_ON_ONCE(!(current->flags & PF_MEMALLOC)); 5975 5976 /* PF_MEMALLOC context, charging must succeed */ 5977 if (obj_cgroup_charge(objcg, GFP_KERNEL, size)) 5978 VM_WARN_ON_ONCE(1); 5979 5980 rcu_read_lock(); 5981 memcg = obj_cgroup_memcg(objcg); 5982 mod_memcg_state(memcg, MEMCG_ZSWAP_B, size); 5983 mod_memcg_state(memcg, MEMCG_ZSWAPPED, 1); 5984 if (size == PAGE_SIZE) 5985 mod_memcg_state(memcg, MEMCG_ZSWAP_INCOMP, 1); 5986 rcu_read_unlock(); 5987 } 5988 5989 /** 5990 * obj_cgroup_uncharge_zswap - uncharge compression backend memory 5991 * @objcg: the object cgroup 5992 * @size: size of compressed object 5993 * 5994 * Uncharges zswap memory on page in. 5995 */ 5996 void obj_cgroup_uncharge_zswap(struct obj_cgroup *objcg, size_t size) 5997 { 5998 struct mem_cgroup *memcg; 5999 6000 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) 6001 return; 6002 6003 if (obj_cgroup_is_root(objcg)) 6004 return; 6005 6006 obj_cgroup_uncharge(objcg, size); 6007 6008 rcu_read_lock(); 6009 memcg = obj_cgroup_memcg(objcg); 6010 mod_memcg_state(memcg, MEMCG_ZSWAP_B, -size); 6011 mod_memcg_state(memcg, MEMCG_ZSWAPPED, -1); 6012 if (size == PAGE_SIZE) 6013 mod_memcg_state(memcg, MEMCG_ZSWAP_INCOMP, -1); 6014 rcu_read_unlock(); 6015 } 6016 6017 bool mem_cgroup_zswap_writeback_enabled(struct mem_cgroup *memcg) 6018 { 6019 /* if zswap is disabled, do not block pages going to the swapping device */ 6020 if (!zswap_is_enabled()) 6021 return true; 6022 6023 for (; memcg; memcg = parent_mem_cgroup(memcg)) 6024 if (!READ_ONCE(memcg->zswap_writeback)) 6025 return false; 6026 6027 return true; 6028 } 6029 6030 static u64 zswap_current_read(struct cgroup_subsys_state *css, 6031 struct cftype *cft) 6032 { 6033 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 6034 6035 mem_cgroup_flush_stats(memcg); 6036 return memcg_page_state(memcg, MEMCG_ZSWAP_B); 6037 } 6038 6039 static int zswap_max_show(struct seq_file *m, void *v) 6040 { 6041 return seq_puts_memcg_tunable(m, 6042 READ_ONCE(mem_cgroup_from_seq(m)->zswap_max)); 6043 } 6044 6045 static ssize_t zswap_max_write(struct kernfs_open_file *of, 6046 char *buf, size_t nbytes, loff_t off) 6047 { 6048 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 6049 unsigned long max; 6050 int err; 6051 6052 buf = strstrip(buf); 6053 err = page_counter_memparse(buf, "max", &max); 6054 if (err) 6055 return err; 6056 6057 xchg(&memcg->zswap_max, max); 6058 6059 return nbytes; 6060 } 6061 6062 static int zswap_writeback_show(struct seq_file *m, void *v) 6063 { 6064 struct mem_cgroup *memcg = mem_cgroup_from_seq(m); 6065 6066 seq_printf(m, "%d\n", READ_ONCE(memcg->zswap_writeback)); 6067 return 0; 6068 } 6069 6070 static ssize_t zswap_writeback_write(struct kernfs_open_file *of, 6071 char *buf, size_t nbytes, loff_t off) 6072 { 6073 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 6074 int zswap_writeback; 6075 ssize_t parse_ret = kstrtoint(strstrip(buf), 0, &zswap_writeback); 6076 6077 if (parse_ret) 6078 return parse_ret; 6079 6080 if (zswap_writeback != 0 && zswap_writeback != 1) 6081 return -EINVAL; 6082 6083 WRITE_ONCE(memcg->zswap_writeback, zswap_writeback); 6084 return nbytes; 6085 } 6086 6087 static struct cftype zswap_files[] = { 6088 { 6089 .name = "zswap.current", 6090 .flags = CFTYPE_NOT_ON_ROOT, 6091 .read_u64 = zswap_current_read, 6092 }, 6093 { 6094 .name = "zswap.max", 6095 .flags = CFTYPE_NOT_ON_ROOT, 6096 .seq_show = zswap_max_show, 6097 .write = zswap_max_write, 6098 }, 6099 { 6100 .name = "zswap.writeback", 6101 .seq_show = zswap_writeback_show, 6102 .write = zswap_writeback_write, 6103 }, 6104 { } /* terminate */ 6105 }; 6106 #endif /* CONFIG_ZSWAP */ 6107 6108 static int __init mem_cgroup_swap_init(void) 6109 { 6110 if (mem_cgroup_disabled()) 6111 return 0; 6112 6113 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files)); 6114 #ifdef CONFIG_MEMCG_V1 6115 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files)); 6116 #endif 6117 #ifdef CONFIG_ZSWAP 6118 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, zswap_files)); 6119 #endif 6120 return 0; 6121 } 6122 subsys_initcall(mem_cgroup_swap_init); 6123 6124 #endif /* CONFIG_SWAP */ 6125 6126 void mem_cgroup_node_filter_allowed(struct mem_cgroup *memcg, nodemask_t *mask) 6127 { 6128 nodemask_t allowed; 6129 6130 if (!memcg) 6131 return; 6132 6133 /* 6134 * Since this interface is intended for use by migration paths, and 6135 * reclaim and migration are subject to race conditions such as changes 6136 * in effective_mems and hot-unpluging of nodes, inaccurate allowed 6137 * mask is acceptable. 6138 */ 6139 cpuset_nodes_allowed(memcg->css.cgroup, &allowed); 6140 nodes_and(*mask, *mask, allowed); 6141 } 6142 6143 void mem_cgroup_show_protected_memory(struct mem_cgroup *memcg) 6144 { 6145 if (mem_cgroup_disabled() || !cgroup_subsys_on_dfl(memory_cgrp_subsys)) 6146 return; 6147 6148 if (!memcg) 6149 memcg = root_mem_cgroup; 6150 6151 pr_warn("Memory cgroup min protection %lukB -- low protection %lukB", 6152 K(atomic_long_read(&memcg->memory.children_min_usage)), 6153 K(atomic_long_read(&memcg->memory.children_low_usage))); 6154 } 6155