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 { 2917 int nid = numa_node_id(); 2918 2919 for (; memcg; memcg = parent_mem_cgroup(memcg)) { 2920 struct obj_cgroup *objcg = rcu_dereference(memcg->nodeinfo[nid]->objcg); 2921 2922 if (likely(objcg && obj_cgroup_tryget(objcg))) 2923 return objcg; 2924 } 2925 2926 return NULL; 2927 } 2928 2929 static inline struct obj_cgroup *get_obj_cgroup_from_memcg(struct mem_cgroup *memcg) 2930 { 2931 struct obj_cgroup *objcg; 2932 2933 rcu_read_lock(); 2934 objcg = __get_obj_cgroup_from_memcg(memcg); 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); 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 WRITE_ONCE(memcg->oom_kill_disable, READ_ONCE(parent->oom_kill_disable)); 4186 page_counter_init(&memcg->kmem, &parent->kmem, false); 4187 page_counter_init(&memcg->tcpmem, &parent->tcpmem, false); 4188 #endif 4189 } else { 4190 init_memcg_stats(); 4191 init_memcg_events(); 4192 page_counter_init(&memcg->memory, NULL, true); 4193 page_counter_init(&memcg->swap, NULL, false); 4194 #ifdef CONFIG_MEMCG_V1 4195 page_counter_init(&memcg->kmem, NULL, false); 4196 page_counter_init(&memcg->tcpmem, NULL, false); 4197 #endif 4198 root_mem_cgroup = memcg; 4199 return &memcg->css; 4200 } 4201 4202 if (memcg_on_dfl && !cgroup_memory_nosocket) 4203 static_branch_inc(&memcg_sockets_enabled_key); 4204 4205 if (!cgroup_memory_nobpf) 4206 static_branch_inc(&memcg_bpf_enabled_key); 4207 4208 return &memcg->css; 4209 } 4210 4211 static int mem_cgroup_css_online(struct cgroup_subsys_state *css) 4212 { 4213 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 4214 struct obj_cgroup *objcg; 4215 int nid; 4216 4217 memcg_online_kmem(memcg); 4218 4219 /* 4220 * A memcg must be visible for expand_shrinker_info() 4221 * by the time the maps are allocated. So, we allocate maps 4222 * here, when mem_cgroup_iter() can't skip it. 4223 */ 4224 if (alloc_shrinker_info(memcg)) 4225 goto offline_kmem; 4226 4227 for_each_node(nid) { 4228 objcg = obj_cgroup_alloc(); 4229 if (!objcg) 4230 goto free_objcg; 4231 4232 if (unlikely(mem_cgroup_is_root(memcg))) 4233 objcg->is_root = true; 4234 4235 objcg->memcg = memcg; 4236 rcu_assign_pointer(memcg->nodeinfo[nid]->objcg, objcg); 4237 obj_cgroup_get(objcg); 4238 memcg->nodeinfo[nid]->orig_objcg = objcg; 4239 } 4240 4241 if (unlikely(mem_cgroup_is_root(memcg)) && !mem_cgroup_disabled()) 4242 queue_delayed_work(system_dfl_wq, &stats_flush_dwork, 4243 FLUSH_TIME); 4244 lru_gen_online_memcg(memcg); 4245 4246 /* Online state pins memcg ID, memcg ID pins CSS */ 4247 refcount_set(&memcg->id.ref, 1); 4248 css_get(css); 4249 4250 /* 4251 * Ensure mem_cgroup_from_private_id() works once we're fully online. 4252 * 4253 * We could do this earlier and require callers to filter with 4254 * css_tryget_online(). But right now there are no users that 4255 * need earlier access, and the workingset code relies on the 4256 * cgroup tree linkage (mem_cgroup_get_nr_swap_pages()). So 4257 * publish it here at the end of onlining. This matches the 4258 * regular ID destruction during offlining. 4259 */ 4260 xa_store(&mem_cgroup_private_ids, memcg->id.id, memcg, GFP_KERNEL); 4261 4262 return 0; 4263 free_objcg: 4264 for_each_node(nid) { 4265 struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid]; 4266 4267 objcg = rcu_replace_pointer(pn->objcg, NULL, true); 4268 if (objcg) 4269 percpu_ref_kill(&objcg->refcnt); 4270 4271 if (pn->orig_objcg) { 4272 obj_cgroup_put(pn->orig_objcg); 4273 /* 4274 * Reset pn->orig_objcg to NULL to prevent 4275 * obj_cgroup_put() from being called again in 4276 * __mem_cgroup_free(). 4277 */ 4278 pn->orig_objcg = NULL; 4279 } 4280 } 4281 free_shrinker_info(memcg); 4282 offline_kmem: 4283 memcg_offline_kmem(memcg); 4284 mem_cgroup_private_id_remove(memcg); 4285 return -ENOMEM; 4286 } 4287 4288 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css) 4289 { 4290 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 4291 4292 memcg1_css_offline(memcg); 4293 4294 page_counter_set_min(&memcg->memory, 0); 4295 page_counter_set_low(&memcg->memory, 0); 4296 4297 zswap_memcg_offline_cleanup(memcg); 4298 4299 memcg_offline_kmem(memcg); 4300 /* 4301 * The reparenting of objcg must be after the reparenting of 4302 * the list_lru in memcg_offline_kmem(), which ensures that 4303 * they will not mistakenly get the parent list_lru. 4304 */ 4305 memcg_reparent_objcgs(memcg); 4306 reparent_shrinker_deferred(memcg); 4307 wb_memcg_offline(memcg); 4308 lru_gen_offline_memcg(memcg); 4309 4310 drain_all_stock(memcg); 4311 4312 mem_cgroup_private_id_put(memcg, 1); 4313 } 4314 4315 static void mem_cgroup_css_released(struct cgroup_subsys_state *css) 4316 { 4317 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 4318 4319 invalidate_reclaim_iterators(memcg); 4320 lru_gen_release_memcg(memcg); 4321 } 4322 4323 static void mem_cgroup_css_free(struct cgroup_subsys_state *css) 4324 { 4325 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 4326 int __maybe_unused i; 4327 4328 #ifdef CONFIG_CGROUP_WRITEBACK 4329 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) 4330 wb_wait_for_completion(&memcg->cgwb_frn[i].done); 4331 #endif 4332 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket) 4333 static_branch_dec(&memcg_sockets_enabled_key); 4334 4335 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg1_tcpmem_active(memcg)) 4336 static_branch_dec(&memcg_sockets_enabled_key); 4337 4338 if (!cgroup_memory_nobpf) 4339 static_branch_dec(&memcg_bpf_enabled_key); 4340 4341 vmpressure_cleanup(&memcg->vmpressure); 4342 cancel_work_sync(&memcg->high_work); 4343 memcg1_remove_from_trees(memcg); 4344 free_shrinker_info(memcg); 4345 mem_cgroup_free(memcg); 4346 } 4347 4348 /** 4349 * mem_cgroup_css_reset - reset the states of a mem_cgroup 4350 * @css: the target css 4351 * 4352 * Reset the states of the mem_cgroup associated with @css. This is 4353 * invoked when the userland requests disabling on the default hierarchy 4354 * but the memcg is pinned through dependency. The memcg should stop 4355 * applying policies and should revert to the vanilla state as it may be 4356 * made visible again. 4357 * 4358 * The current implementation only resets the essential configurations. 4359 * This needs to be expanded to cover all the visible parts. 4360 */ 4361 static void mem_cgroup_css_reset(struct cgroup_subsys_state *css) 4362 { 4363 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 4364 4365 page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX); 4366 page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX); 4367 WRITE_ONCE(memcg->oom_group, false); 4368 #ifdef CONFIG_ZSWAP 4369 WRITE_ONCE(memcg->zswap_max, PAGE_COUNTER_MAX); 4370 WRITE_ONCE(memcg->zswap_writeback, true); 4371 #endif 4372 #ifdef CONFIG_MEMCG_V1 4373 page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX); 4374 page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX); 4375 #endif 4376 page_counter_set_min(&memcg->memory, 0); 4377 page_counter_set_low(&memcg->memory, 0); 4378 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX); 4379 memcg1_soft_limit_reset(memcg); 4380 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX); 4381 memcg_wb_domain_size_changed(memcg); 4382 } 4383 4384 struct aggregate_control { 4385 /* pointer to the aggregated (CPU and subtree aggregated) counters */ 4386 long *aggregate; 4387 /* pointer to the non-hierarchichal (CPU aggregated) counters */ 4388 long *local; 4389 /* pointer to the pending child counters during tree propagation */ 4390 long *pending; 4391 /* pointer to the parent's pending counters, could be NULL */ 4392 long *ppending; 4393 /* pointer to the percpu counters to be aggregated */ 4394 long *cstat; 4395 /* pointer to the percpu counters of the last aggregation*/ 4396 long *cstat_prev; 4397 /* size of the above counters */ 4398 int size; 4399 }; 4400 4401 static void mem_cgroup_stat_aggregate(struct aggregate_control *ac) 4402 { 4403 int i; 4404 long delta, delta_cpu, v; 4405 4406 for (i = 0; i < ac->size; i++) { 4407 /* 4408 * Collect the aggregated propagation counts of groups 4409 * below us. We're in a per-cpu loop here and this is 4410 * a global counter, so the first cycle will get them. 4411 */ 4412 delta = ac->pending[i]; 4413 if (delta) 4414 ac->pending[i] = 0; 4415 4416 /* Add CPU changes on this level since the last flush */ 4417 delta_cpu = 0; 4418 v = READ_ONCE(ac->cstat[i]); 4419 if (v != ac->cstat_prev[i]) { 4420 delta_cpu = v - ac->cstat_prev[i]; 4421 delta += delta_cpu; 4422 ac->cstat_prev[i] = v; 4423 } 4424 4425 /* Aggregate counts on this level and propagate upwards */ 4426 if (delta_cpu) 4427 ac->local[i] += delta_cpu; 4428 4429 if (delta) { 4430 ac->aggregate[i] += delta; 4431 if (ac->ppending) 4432 ac->ppending[i] += delta; 4433 } 4434 } 4435 } 4436 4437 #ifdef CONFIG_MEMCG_NMI_SAFETY_REQUIRES_ATOMIC 4438 static void flush_nmi_stats(struct mem_cgroup *memcg, struct mem_cgroup *parent) 4439 { 4440 int nid; 4441 4442 if (atomic_read(&memcg->kmem_stat)) { 4443 int kmem = atomic_xchg(&memcg->kmem_stat, 0); 4444 int index = memcg_stats_index(MEMCG_KMEM); 4445 4446 memcg->vmstats->state[index] += kmem; 4447 memcg->vmstats->state_local[index] += kmem; 4448 if (parent) 4449 parent->vmstats->state_pending[index] += kmem; 4450 } 4451 4452 for_each_node_state(nid, N_MEMORY) { 4453 struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid]; 4454 struct lruvec_stats *lstats = pn->lruvec_stats; 4455 struct lruvec_stats *plstats = NULL; 4456 4457 if (parent) 4458 plstats = parent->nodeinfo[nid]->lruvec_stats; 4459 4460 if (atomic_read(&pn->slab_reclaimable)) { 4461 int slab = atomic_xchg(&pn->slab_reclaimable, 0); 4462 int index = memcg_stats_index(NR_SLAB_RECLAIMABLE_B); 4463 4464 lstats->state[index] += slab; 4465 lstats->state_local[index] += slab; 4466 if (plstats) 4467 plstats->state_pending[index] += slab; 4468 memcg->vmstats->state[index] += slab; 4469 memcg->vmstats->state_local[index] += slab; 4470 if (parent) 4471 parent->vmstats->state_pending[index] += slab; 4472 } 4473 if (atomic_read(&pn->slab_unreclaimable)) { 4474 int slab = atomic_xchg(&pn->slab_unreclaimable, 0); 4475 int index = memcg_stats_index(NR_SLAB_UNRECLAIMABLE_B); 4476 4477 lstats->state[index] += slab; 4478 lstats->state_local[index] += slab; 4479 if (plstats) 4480 plstats->state_pending[index] += slab; 4481 memcg->vmstats->state[index] += slab; 4482 memcg->vmstats->state_local[index] += slab; 4483 if (parent) 4484 parent->vmstats->state_pending[index] += slab; 4485 } 4486 } 4487 } 4488 #else 4489 static void flush_nmi_stats(struct mem_cgroup *memcg, struct mem_cgroup *parent) 4490 {} 4491 #endif 4492 4493 static void mem_cgroup_css_rstat_flush(struct cgroup_subsys_state *css, int cpu) 4494 { 4495 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 4496 struct mem_cgroup *parent = parent_mem_cgroup(memcg); 4497 struct memcg_vmstats_percpu *statc; 4498 struct aggregate_control ac; 4499 int nid; 4500 4501 flush_nmi_stats(memcg, parent); 4502 4503 statc = per_cpu_ptr(memcg->vmstats_percpu, cpu); 4504 4505 ac = (struct aggregate_control) { 4506 .aggregate = memcg->vmstats->state, 4507 .local = memcg->vmstats->state_local, 4508 .pending = memcg->vmstats->state_pending, 4509 .ppending = parent ? parent->vmstats->state_pending : NULL, 4510 .cstat = statc->state, 4511 .cstat_prev = statc->state_prev, 4512 .size = MEMCG_VMSTAT_SIZE, 4513 }; 4514 mem_cgroup_stat_aggregate(&ac); 4515 4516 ac = (struct aggregate_control) { 4517 .aggregate = memcg->vmstats->events, 4518 .local = memcg->vmstats->events_local, 4519 .pending = memcg->vmstats->events_pending, 4520 .ppending = parent ? parent->vmstats->events_pending : NULL, 4521 .cstat = statc->events, 4522 .cstat_prev = statc->events_prev, 4523 .size = NR_MEMCG_EVENTS, 4524 }; 4525 mem_cgroup_stat_aggregate(&ac); 4526 4527 for_each_node_state(nid, N_MEMORY) { 4528 struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid]; 4529 struct lruvec_stats *lstats = pn->lruvec_stats; 4530 struct lruvec_stats *plstats = NULL; 4531 struct lruvec_stats_percpu *lstatc; 4532 4533 if (parent) 4534 plstats = parent->nodeinfo[nid]->lruvec_stats; 4535 4536 lstatc = per_cpu_ptr(pn->lruvec_stats_percpu, cpu); 4537 4538 ac = (struct aggregate_control) { 4539 .aggregate = lstats->state, 4540 .local = lstats->state_local, 4541 .pending = lstats->state_pending, 4542 .ppending = plstats ? plstats->state_pending : NULL, 4543 .cstat = lstatc->state, 4544 .cstat_prev = lstatc->state_prev, 4545 .size = NR_MEMCG_NODE_STAT_ITEMS, 4546 }; 4547 mem_cgroup_stat_aggregate(&ac); 4548 4549 } 4550 WRITE_ONCE(statc->stats_updates, 0); 4551 /* We are in a per-cpu loop here, only do the atomic write once */ 4552 if (atomic_long_read(&memcg->vmstats->stats_updates)) 4553 atomic_long_set(&memcg->vmstats->stats_updates, 0); 4554 } 4555 4556 static void mem_cgroup_fork(struct task_struct *task) 4557 { 4558 /* 4559 * Set the update flag to cause task->objcg to be initialized lazily 4560 * on the first allocation. It can be done without any synchronization 4561 * because it's always performed on the current task, so does 4562 * current_objcg_update(). 4563 */ 4564 task->objcg = (struct obj_cgroup *)CURRENT_OBJCG_UPDATE_FLAG; 4565 } 4566 4567 static void mem_cgroup_exit(struct task_struct *task) 4568 { 4569 struct obj_cgroup *objcg = task->objcg; 4570 4571 objcg = (struct obj_cgroup *) 4572 ((unsigned long)objcg & ~CURRENT_OBJCG_UPDATE_FLAG); 4573 obj_cgroup_put(objcg); 4574 4575 /* 4576 * Some kernel allocations can happen after this point, 4577 * but let's ignore them. It can be done without any synchronization 4578 * because it's always performed on the current task, so does 4579 * current_objcg_update(). 4580 */ 4581 task->objcg = NULL; 4582 } 4583 4584 #ifdef CONFIG_LRU_GEN 4585 static void mem_cgroup_lru_gen_attach(struct cgroup_taskset *tset) 4586 { 4587 struct task_struct *task; 4588 struct cgroup_subsys_state *css; 4589 4590 /* find the first leader if there is any */ 4591 cgroup_taskset_for_each_leader(task, css, tset) 4592 break; 4593 4594 if (!task) 4595 return; 4596 4597 task_lock(task); 4598 if (task->mm && READ_ONCE(task->mm->owner) == task) 4599 lru_gen_migrate_mm(task->mm); 4600 task_unlock(task); 4601 } 4602 #else 4603 static void mem_cgroup_lru_gen_attach(struct cgroup_taskset *tset) {} 4604 #endif /* CONFIG_LRU_GEN */ 4605 4606 static void mem_cgroup_kmem_attach(struct cgroup_taskset *tset) 4607 { 4608 struct task_struct *task; 4609 struct cgroup_subsys_state *css; 4610 4611 cgroup_taskset_for_each(task, css, tset) { 4612 /* atomically set the update bit */ 4613 set_bit(CURRENT_OBJCG_UPDATE_BIT, (unsigned long *)&task->objcg); 4614 } 4615 } 4616 4617 static void mem_cgroup_attach(struct cgroup_taskset *tset) 4618 { 4619 mem_cgroup_lru_gen_attach(tset); 4620 mem_cgroup_kmem_attach(tset); 4621 } 4622 4623 static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value) 4624 { 4625 if (value == PAGE_COUNTER_MAX) 4626 seq_puts(m, "max\n"); 4627 else 4628 seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE); 4629 4630 return 0; 4631 } 4632 4633 static u64 memory_current_read(struct cgroup_subsys_state *css, 4634 struct cftype *cft) 4635 { 4636 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 4637 4638 return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE; 4639 } 4640 4641 #define OFP_PEAK_UNSET (((-1UL))) 4642 4643 static int peak_show(struct seq_file *sf, void *v, struct page_counter *pc) 4644 { 4645 struct cgroup_of_peak *ofp = of_peak(sf->private); 4646 u64 fd_peak = READ_ONCE(ofp->value), peak; 4647 4648 /* User wants global or local peak? */ 4649 if (fd_peak == OFP_PEAK_UNSET) 4650 peak = pc->watermark; 4651 else 4652 peak = max(fd_peak, READ_ONCE(pc->local_watermark)); 4653 4654 seq_printf(sf, "%llu\n", peak * PAGE_SIZE); 4655 return 0; 4656 } 4657 4658 static int memory_peak_show(struct seq_file *sf, void *v) 4659 { 4660 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(sf)); 4661 4662 return peak_show(sf, v, &memcg->memory); 4663 } 4664 4665 static int peak_open(struct kernfs_open_file *of) 4666 { 4667 struct cgroup_of_peak *ofp = of_peak(of); 4668 4669 ofp->value = OFP_PEAK_UNSET; 4670 return 0; 4671 } 4672 4673 static void peak_release(struct kernfs_open_file *of) 4674 { 4675 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 4676 struct cgroup_of_peak *ofp = of_peak(of); 4677 4678 if (ofp->value == OFP_PEAK_UNSET) { 4679 /* fast path (no writes on this fd) */ 4680 return; 4681 } 4682 spin_lock(&memcg->peaks_lock); 4683 list_del(&ofp->list); 4684 spin_unlock(&memcg->peaks_lock); 4685 } 4686 4687 static ssize_t peak_write(struct kernfs_open_file *of, char *buf, size_t nbytes, 4688 loff_t off, struct page_counter *pc, 4689 struct list_head *watchers) 4690 { 4691 unsigned long usage; 4692 struct cgroup_of_peak *peer_ctx; 4693 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 4694 struct cgroup_of_peak *ofp = of_peak(of); 4695 4696 spin_lock(&memcg->peaks_lock); 4697 4698 usage = page_counter_read(pc); 4699 WRITE_ONCE(pc->local_watermark, usage); 4700 4701 list_for_each_entry(peer_ctx, watchers, list) 4702 if (usage > peer_ctx->value) 4703 WRITE_ONCE(peer_ctx->value, usage); 4704 4705 /* initial write, register watcher */ 4706 if (ofp->value == OFP_PEAK_UNSET) 4707 list_add(&ofp->list, watchers); 4708 4709 WRITE_ONCE(ofp->value, usage); 4710 spin_unlock(&memcg->peaks_lock); 4711 4712 return nbytes; 4713 } 4714 4715 static ssize_t memory_peak_write(struct kernfs_open_file *of, char *buf, 4716 size_t nbytes, loff_t off) 4717 { 4718 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 4719 4720 return peak_write(of, buf, nbytes, off, &memcg->memory, 4721 &memcg->memory_peaks); 4722 } 4723 4724 #undef OFP_PEAK_UNSET 4725 4726 static int memory_min_show(struct seq_file *m, void *v) 4727 { 4728 return seq_puts_memcg_tunable(m, 4729 READ_ONCE(mem_cgroup_from_seq(m)->memory.min)); 4730 } 4731 4732 static ssize_t memory_min_write(struct kernfs_open_file *of, 4733 char *buf, size_t nbytes, loff_t off) 4734 { 4735 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 4736 unsigned long min; 4737 int err; 4738 4739 buf = strstrip(buf); 4740 err = page_counter_memparse(buf, "max", &min); 4741 if (err) 4742 return err; 4743 4744 page_counter_set_min(&memcg->memory, min); 4745 4746 return nbytes; 4747 } 4748 4749 static int memory_low_show(struct seq_file *m, void *v) 4750 { 4751 return seq_puts_memcg_tunable(m, 4752 READ_ONCE(mem_cgroup_from_seq(m)->memory.low)); 4753 } 4754 4755 static ssize_t memory_low_write(struct kernfs_open_file *of, 4756 char *buf, size_t nbytes, loff_t off) 4757 { 4758 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 4759 unsigned long low; 4760 int err; 4761 4762 buf = strstrip(buf); 4763 err = page_counter_memparse(buf, "max", &low); 4764 if (err) 4765 return err; 4766 4767 page_counter_set_low(&memcg->memory, low); 4768 4769 return nbytes; 4770 } 4771 4772 static int memory_high_show(struct seq_file *m, void *v) 4773 { 4774 return seq_puts_memcg_tunable(m, 4775 READ_ONCE(mem_cgroup_from_seq(m)->memory.high)); 4776 } 4777 4778 static ssize_t memory_high_write(struct kernfs_open_file *of, 4779 char *buf, size_t nbytes, loff_t off) 4780 { 4781 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 4782 unsigned int nr_retries = MAX_RECLAIM_RETRIES; 4783 bool drained = false; 4784 unsigned long high; 4785 int err; 4786 4787 buf = strstrip(buf); 4788 err = page_counter_memparse(buf, "max", &high); 4789 if (err) 4790 return err; 4791 4792 page_counter_set_high(&memcg->memory, high); 4793 4794 if (of->file->f_flags & O_NONBLOCK) 4795 goto out; 4796 4797 for (;;) { 4798 unsigned long nr_pages = page_counter_read(&memcg->memory); 4799 unsigned long reclaimed; 4800 4801 if (nr_pages <= high) 4802 break; 4803 4804 if (signal_pending(current)) 4805 break; 4806 4807 /* cgroup_rmdir() waits for us with cgroup_mutex held. */ 4808 if (memcg_is_dying(memcg)) 4809 break; 4810 4811 if (!drained) { 4812 drain_all_stock(memcg); 4813 drained = true; 4814 continue; 4815 } 4816 4817 reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high, 4818 GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP, NULL); 4819 4820 if (!reclaimed && !nr_retries--) 4821 break; 4822 } 4823 out: 4824 memcg_wb_domain_size_changed(memcg); 4825 return nbytes; 4826 } 4827 4828 static int memory_max_show(struct seq_file *m, void *v) 4829 { 4830 return seq_puts_memcg_tunable(m, 4831 READ_ONCE(mem_cgroup_from_seq(m)->memory.max)); 4832 } 4833 4834 static ssize_t memory_max_write(struct kernfs_open_file *of, 4835 char *buf, size_t nbytes, loff_t off) 4836 { 4837 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 4838 unsigned int nr_reclaims = MAX_RECLAIM_RETRIES; 4839 bool drained = false; 4840 unsigned long max; 4841 int err; 4842 4843 buf = strstrip(buf); 4844 err = page_counter_memparse(buf, "max", &max); 4845 if (err) 4846 return err; 4847 4848 xchg(&memcg->memory.max, max); 4849 4850 if (of->file->f_flags & O_NONBLOCK) 4851 goto out; 4852 4853 for (;;) { 4854 unsigned long nr_pages = page_counter_read(&memcg->memory); 4855 4856 if (nr_pages <= max) 4857 break; 4858 4859 if (signal_pending(current)) 4860 break; 4861 4862 /* cgroup_rmdir() waits for us with cgroup_mutex held. */ 4863 if (memcg_is_dying(memcg)) 4864 break; 4865 4866 if (!drained) { 4867 drain_all_stock(memcg); 4868 drained = true; 4869 continue; 4870 } 4871 4872 if (nr_reclaims) { 4873 if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max, 4874 GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP, NULL)) 4875 nr_reclaims--; 4876 continue; 4877 } 4878 4879 memcg_memory_event(memcg, MEMCG_OOM); 4880 if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0)) 4881 break; 4882 cond_resched(); 4883 } 4884 out: 4885 memcg_wb_domain_size_changed(memcg); 4886 return nbytes; 4887 } 4888 4889 /* 4890 * Note: don't forget to update the 'samples/cgroup/memcg_event_listener' 4891 * if any new events become available. 4892 */ 4893 static void __memory_events_show(struct seq_file *m, atomic_long_t *events) 4894 { 4895 seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW])); 4896 seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH])); 4897 seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX])); 4898 seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM])); 4899 seq_printf(m, "oom_kill %lu\n", 4900 atomic_long_read(&events[MEMCG_OOM_KILL])); 4901 seq_printf(m, "oom_group_kill %lu\n", 4902 atomic_long_read(&events[MEMCG_OOM_GROUP_KILL])); 4903 seq_printf(m, "sock_throttled %lu\n", 4904 atomic_long_read(&events[MEMCG_SOCK_THROTTLED])); 4905 } 4906 4907 static int memory_events_show(struct seq_file *m, void *v) 4908 { 4909 struct mem_cgroup *memcg = mem_cgroup_from_seq(m); 4910 4911 __memory_events_show(m, memcg->memory_events); 4912 return 0; 4913 } 4914 4915 static int memory_events_local_show(struct seq_file *m, void *v) 4916 { 4917 struct mem_cgroup *memcg = mem_cgroup_from_seq(m); 4918 4919 __memory_events_show(m, memcg->memory_events_local); 4920 return 0; 4921 } 4922 4923 int memory_stat_show(struct seq_file *m, void *v) 4924 { 4925 struct mem_cgroup *memcg = mem_cgroup_from_seq(m); 4926 char *buf = kmalloc(SEQ_BUF_SIZE, GFP_KERNEL); 4927 struct seq_buf s; 4928 4929 if (!buf) 4930 return -ENOMEM; 4931 seq_buf_init(&s, buf, SEQ_BUF_SIZE); 4932 memory_stat_format(memcg, &s); 4933 seq_puts(m, buf); 4934 kfree(buf); 4935 return 0; 4936 } 4937 4938 #ifdef CONFIG_NUMA 4939 static inline unsigned long lruvec_page_state_output(struct lruvec *lruvec, 4940 int item) 4941 { 4942 return lruvec_page_state(lruvec, item) * 4943 memcg_page_state_output_unit(item); 4944 } 4945 4946 static int memory_numa_stat_show(struct seq_file *m, void *v) 4947 { 4948 int i; 4949 struct mem_cgroup *memcg = mem_cgroup_from_seq(m); 4950 4951 mem_cgroup_flush_stats(memcg); 4952 4953 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) { 4954 int nid; 4955 4956 if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS) 4957 continue; 4958 4959 seq_printf(m, "%s", memory_stats[i].name); 4960 for_each_node_state(nid, N_MEMORY) { 4961 u64 size; 4962 struct lruvec *lruvec; 4963 4964 lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid)); 4965 size = lruvec_page_state_output(lruvec, 4966 memory_stats[i].idx); 4967 seq_printf(m, " N%d=%llu", nid, size); 4968 } 4969 seq_putc(m, '\n'); 4970 } 4971 4972 return 0; 4973 } 4974 #endif 4975 4976 static int memory_oom_group_show(struct seq_file *m, void *v) 4977 { 4978 struct mem_cgroup *memcg = mem_cgroup_from_seq(m); 4979 4980 seq_printf(m, "%d\n", READ_ONCE(memcg->oom_group)); 4981 4982 return 0; 4983 } 4984 4985 static ssize_t memory_oom_group_write(struct kernfs_open_file *of, 4986 char *buf, size_t nbytes, loff_t off) 4987 { 4988 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 4989 int ret, oom_group; 4990 4991 buf = strstrip(buf); 4992 if (!buf) 4993 return -EINVAL; 4994 4995 ret = kstrtoint(buf, 0, &oom_group); 4996 if (ret) 4997 return ret; 4998 4999 if (oom_group != 0 && oom_group != 1) 5000 return -EINVAL; 5001 5002 WRITE_ONCE(memcg->oom_group, oom_group); 5003 5004 return nbytes; 5005 } 5006 5007 static ssize_t memory_reclaim(struct kernfs_open_file *of, char *buf, 5008 size_t nbytes, loff_t off) 5009 { 5010 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 5011 int ret; 5012 5013 ret = user_proactive_reclaim(buf, memcg, NULL); 5014 if (ret) 5015 return ret; 5016 5017 return nbytes; 5018 } 5019 5020 static struct cftype memory_files[] = { 5021 { 5022 .name = "current", 5023 .flags = CFTYPE_NOT_ON_ROOT, 5024 .read_u64 = memory_current_read, 5025 }, 5026 { 5027 .name = "peak", 5028 .flags = CFTYPE_NOT_ON_ROOT, 5029 .open = peak_open, 5030 .release = peak_release, 5031 .seq_show = memory_peak_show, 5032 .write = memory_peak_write, 5033 }, 5034 { 5035 .name = "min", 5036 .flags = CFTYPE_NOT_ON_ROOT, 5037 .seq_show = memory_min_show, 5038 .write = memory_min_write, 5039 }, 5040 { 5041 .name = "low", 5042 .flags = CFTYPE_NOT_ON_ROOT, 5043 .seq_show = memory_low_show, 5044 .write = memory_low_write, 5045 }, 5046 { 5047 .name = "high", 5048 .flags = CFTYPE_NOT_ON_ROOT, 5049 .seq_show = memory_high_show, 5050 .write = memory_high_write, 5051 }, 5052 { 5053 .name = "max", 5054 .flags = CFTYPE_NOT_ON_ROOT, 5055 .seq_show = memory_max_show, 5056 .write = memory_max_write, 5057 }, 5058 { 5059 .name = "events", 5060 .flags = CFTYPE_NOT_ON_ROOT, 5061 .file_offset = offsetof(struct mem_cgroup, events_file), 5062 .seq_show = memory_events_show, 5063 }, 5064 { 5065 .name = "events.local", 5066 .flags = CFTYPE_NOT_ON_ROOT, 5067 .file_offset = offsetof(struct mem_cgroup, events_local_file), 5068 .seq_show = memory_events_local_show, 5069 }, 5070 { 5071 .name = "stat", 5072 .seq_show = memory_stat_show, 5073 }, 5074 #ifdef CONFIG_NUMA 5075 { 5076 .name = "numa_stat", 5077 .seq_show = memory_numa_stat_show, 5078 }, 5079 #endif 5080 { 5081 .name = "oom.group", 5082 .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE, 5083 .seq_show = memory_oom_group_show, 5084 .write = memory_oom_group_write, 5085 }, 5086 { 5087 .name = "reclaim", 5088 .flags = CFTYPE_NS_DELEGATABLE, 5089 .write = memory_reclaim, 5090 }, 5091 { } /* terminate */ 5092 }; 5093 5094 struct cgroup_subsys memory_cgrp_subsys = { 5095 .css_alloc = mem_cgroup_css_alloc, 5096 .css_online = mem_cgroup_css_online, 5097 .css_offline = mem_cgroup_css_offline, 5098 .css_released = mem_cgroup_css_released, 5099 .css_free = mem_cgroup_css_free, 5100 .css_reset = mem_cgroup_css_reset, 5101 .css_rstat_flush = mem_cgroup_css_rstat_flush, 5102 .attach = mem_cgroup_attach, 5103 .fork = mem_cgroup_fork, 5104 .exit = mem_cgroup_exit, 5105 .dfl_cftypes = memory_files, 5106 #ifdef CONFIG_MEMCG_V1 5107 .legacy_cftypes = mem_cgroup_legacy_files, 5108 #endif 5109 .early_init = 0, 5110 }; 5111 5112 /** 5113 * mem_cgroup_calculate_protection - check if memory consumption is in the normal range 5114 * @root: the top ancestor of the sub-tree being checked 5115 * @memcg: the memory cgroup to check 5116 * 5117 * WARNING: This function is not stateless! It can only be used as part 5118 * of a top-down tree iteration, not for isolated queries. 5119 */ 5120 void mem_cgroup_calculate_protection(struct mem_cgroup *root, 5121 struct mem_cgroup *memcg) 5122 { 5123 bool recursive_protection = 5124 cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT; 5125 5126 if (mem_cgroup_disabled()) 5127 return; 5128 5129 if (!root) 5130 root = root_mem_cgroup; 5131 5132 page_counter_calculate_protection(&root->memory, &memcg->memory, recursive_protection); 5133 } 5134 5135 static int charge_memcg(struct folio *folio, struct mem_cgroup *memcg, 5136 gfp_t gfp) 5137 { 5138 int ret = 0; 5139 struct obj_cgroup *objcg; 5140 5141 objcg = get_obj_cgroup_from_memcg(memcg); 5142 /* Do not account at the root objcg level. */ 5143 if (!obj_cgroup_is_root(objcg)) 5144 ret = try_charge_memcg(memcg, gfp, folio_nr_pages(folio)); 5145 if (ret) { 5146 obj_cgroup_put(objcg); 5147 return ret; 5148 } 5149 commit_charge(folio, objcg); 5150 memcg1_commit_charge(folio, memcg); 5151 5152 return ret; 5153 } 5154 5155 int __mem_cgroup_charge(struct folio *folio, struct mm_struct *mm, gfp_t gfp) 5156 { 5157 struct mem_cgroup *memcg; 5158 int ret; 5159 5160 memcg = get_mem_cgroup_from_mm(mm); 5161 ret = charge_memcg(folio, memcg, gfp); 5162 css_put(&memcg->css); 5163 5164 return ret; 5165 } 5166 5167 /** 5168 * mem_cgroup_charge_hugetlb - charge the memcg for a hugetlb folio 5169 * @folio: folio being charged 5170 * @gfp: reclaim mode 5171 * 5172 * This function is called when allocating a huge page folio, after the page has 5173 * already been obtained and charged to the appropriate hugetlb cgroup 5174 * controller (if it is enabled). 5175 * 5176 * Returns ENOMEM if the memcg is already full. 5177 * Returns 0 if either the charge was successful, or if we skip the charging. 5178 */ 5179 int mem_cgroup_charge_hugetlb(struct folio *folio, gfp_t gfp) 5180 { 5181 struct mem_cgroup *memcg = get_mem_cgroup_from_current(); 5182 int ret = 0; 5183 5184 /* 5185 * Even memcg does not account for hugetlb, we still want to update 5186 * system-level stats via lruvec_stat_mod_folio. Return 0, and skip 5187 * charging the memcg. 5188 */ 5189 if (mem_cgroup_disabled() || !memcg_accounts_hugetlb() || 5190 !memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys)) 5191 goto out; 5192 5193 if (charge_memcg(folio, memcg, gfp)) 5194 ret = -ENOMEM; 5195 5196 out: 5197 mem_cgroup_put(memcg); 5198 return ret; 5199 } 5200 5201 /** 5202 * mem_cgroup_swapin_charge_folio - Charge a newly allocated folio for swapin. 5203 * @folio: the folio to charge 5204 * @id: memory cgroup id 5205 * @mm: mm context of the victim 5206 * @gfp: reclaim mode 5207 * 5208 * This function charges a folio allocated for swapin. Please call this before 5209 * adding the folio to the swapcache. 5210 * 5211 * Returns 0 on success. Otherwise, an error code is returned. 5212 */ 5213 int mem_cgroup_swapin_charge_folio(struct folio *folio, unsigned short id, 5214 struct mm_struct *mm, gfp_t gfp) 5215 { 5216 struct mem_cgroup *memcg; 5217 int ret; 5218 5219 if (mem_cgroup_disabled()) 5220 return 0; 5221 5222 rcu_read_lock(); 5223 memcg = mem_cgroup_from_private_id(id); 5224 if (!memcg || !css_tryget_online(&memcg->css)) 5225 memcg = get_mem_cgroup_from_mm(mm); 5226 rcu_read_unlock(); 5227 5228 ret = charge_memcg(folio, memcg, gfp); 5229 5230 css_put(&memcg->css); 5231 return ret; 5232 } 5233 5234 struct uncharge_gather { 5235 struct obj_cgroup *objcg; 5236 unsigned long nr_memory; 5237 unsigned long pgpgout; 5238 unsigned long nr_kmem; 5239 int nid; 5240 }; 5241 5242 static inline void uncharge_gather_clear(struct uncharge_gather *ug) 5243 { 5244 memset(ug, 0, sizeof(*ug)); 5245 } 5246 5247 static void uncharge_batch(const struct uncharge_gather *ug) 5248 { 5249 struct mem_cgroup *memcg; 5250 5251 rcu_read_lock(); 5252 memcg = obj_cgroup_memcg(ug->objcg); 5253 if (ug->nr_memory) { 5254 memcg_uncharge(memcg, ug->nr_memory); 5255 if (ug->nr_kmem) { 5256 mod_memcg_state(memcg, MEMCG_KMEM, -ug->nr_kmem); 5257 memcg1_account_kmem(memcg, -ug->nr_kmem); 5258 } 5259 memcg1_oom_recover(memcg); 5260 } 5261 5262 memcg1_uncharge_batch(memcg, ug->pgpgout, ug->nr_memory, ug->nid); 5263 rcu_read_unlock(); 5264 5265 /* drop reference from uncharge_folio */ 5266 obj_cgroup_put(ug->objcg); 5267 } 5268 5269 static void uncharge_folio(struct folio *folio, struct uncharge_gather *ug) 5270 { 5271 long nr_pages; 5272 struct obj_cgroup *objcg; 5273 5274 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio); 5275 5276 /* 5277 * Nobody should be changing or seriously looking at 5278 * folio objcg at this point, we have fully exclusive 5279 * access to the folio. 5280 */ 5281 objcg = folio_objcg(folio); 5282 if (!objcg) 5283 return; 5284 5285 if (ug->objcg != objcg) { 5286 if (ug->objcg) { 5287 uncharge_batch(ug); 5288 uncharge_gather_clear(ug); 5289 } 5290 ug->objcg = objcg; 5291 ug->nid = folio_nid(folio); 5292 5293 /* pairs with obj_cgroup_put in uncharge_batch */ 5294 obj_cgroup_get(objcg); 5295 } 5296 5297 nr_pages = folio_nr_pages(folio); 5298 5299 if (folio_memcg_kmem(folio)) { 5300 ug->nr_memory += nr_pages; 5301 ug->nr_kmem += nr_pages; 5302 } else { 5303 /* LRU pages aren't accounted at the root level */ 5304 if (!obj_cgroup_is_root(objcg)) 5305 ug->nr_memory += nr_pages; 5306 ug->pgpgout++; 5307 5308 WARN_ON_ONCE(folio_unqueue_deferred_split(folio)); 5309 } 5310 5311 folio->memcg_data = 0; 5312 obj_cgroup_put(objcg); 5313 } 5314 5315 void __mem_cgroup_uncharge(struct folio *folio) 5316 { 5317 struct uncharge_gather ug; 5318 5319 /* Don't touch folio->lru of any random page, pre-check: */ 5320 if (!folio_memcg_charged(folio)) 5321 return; 5322 5323 uncharge_gather_clear(&ug); 5324 uncharge_folio(folio, &ug); 5325 uncharge_batch(&ug); 5326 } 5327 5328 void __mem_cgroup_uncharge_folios(struct folio_batch *folios) 5329 { 5330 struct uncharge_gather ug; 5331 unsigned int i; 5332 5333 uncharge_gather_clear(&ug); 5334 for (i = 0; i < folios->nr; i++) 5335 uncharge_folio(folios->folios[i], &ug); 5336 if (ug.objcg) 5337 uncharge_batch(&ug); 5338 } 5339 5340 /** 5341 * mem_cgroup_replace_folio - Charge a folio's replacement. 5342 * @old: Currently circulating folio. 5343 * @new: Replacement folio. 5344 * 5345 * Charge @new as a replacement folio for @old. @old will 5346 * be uncharged upon free. 5347 * 5348 * Both folios must be locked, @new->mapping must be set up. 5349 */ 5350 void mem_cgroup_replace_folio(struct folio *old, struct folio *new) 5351 { 5352 struct mem_cgroup *memcg; 5353 struct obj_cgroup *objcg; 5354 long nr_pages = folio_nr_pages(new); 5355 5356 VM_BUG_ON_FOLIO(!folio_test_locked(old), old); 5357 VM_BUG_ON_FOLIO(!folio_test_locked(new), new); 5358 VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new); 5359 VM_BUG_ON_FOLIO(folio_nr_pages(old) != nr_pages, new); 5360 5361 if (mem_cgroup_disabled()) 5362 return; 5363 5364 /* Page cache replacement: new folio already charged? */ 5365 if (folio_memcg_charged(new)) 5366 return; 5367 5368 objcg = folio_objcg(old); 5369 VM_WARN_ON_ONCE_FOLIO(!objcg, old); 5370 if (!objcg) 5371 return; 5372 5373 rcu_read_lock(); 5374 memcg = obj_cgroup_memcg(objcg); 5375 /* Force-charge the new page. The old one will be freed soon */ 5376 if (!obj_cgroup_is_root(objcg)) { 5377 page_counter_charge(&memcg->memory, nr_pages); 5378 if (do_memsw_account()) 5379 page_counter_charge(&memcg->memsw, nr_pages); 5380 } 5381 5382 obj_cgroup_get(objcg); 5383 commit_charge(new, objcg); 5384 memcg1_commit_charge(new, memcg); 5385 rcu_read_unlock(); 5386 } 5387 5388 /** 5389 * mem_cgroup_migrate - Transfer the memcg data from the old to the new folio. 5390 * @old: Currently circulating folio. 5391 * @new: Replacement folio. 5392 * 5393 * Transfer the memcg data from the old folio to the new folio for migration. 5394 * The old folio's data info will be cleared. Note that the memory counters 5395 * will remain unchanged throughout the process. 5396 * 5397 * Both folios must be locked, @new->mapping must be set up. 5398 */ 5399 void mem_cgroup_migrate(struct folio *old, struct folio *new) 5400 { 5401 struct obj_cgroup *objcg; 5402 5403 VM_BUG_ON_FOLIO(!folio_test_locked(old), old); 5404 VM_BUG_ON_FOLIO(!folio_test_locked(new), new); 5405 VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new); 5406 VM_BUG_ON_FOLIO(folio_nr_pages(old) != folio_nr_pages(new), new); 5407 VM_BUG_ON_FOLIO(folio_test_lru(old), old); 5408 5409 if (mem_cgroup_disabled()) 5410 return; 5411 5412 objcg = folio_objcg(old); 5413 /* 5414 * Note that it is normal to see !objcg for a hugetlb folio. 5415 * For e.g, it could have been allocated when memory_hugetlb_accounting 5416 * was not selected. 5417 */ 5418 VM_WARN_ON_ONCE_FOLIO(!folio_test_hugetlb(old) && !objcg, old); 5419 if (!objcg) 5420 return; 5421 5422 /* Transfer the charge and the objcg ref */ 5423 commit_charge(new, objcg); 5424 5425 /* Warning should never happen, so don't worry about refcount non-0 */ 5426 WARN_ON_ONCE(folio_unqueue_deferred_split(old)); 5427 old->memcg_data = 0; 5428 } 5429 5430 DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key); 5431 EXPORT_SYMBOL(memcg_sockets_enabled_key); 5432 5433 void mem_cgroup_sk_alloc(struct sock *sk) 5434 { 5435 struct mem_cgroup *memcg; 5436 5437 if (!mem_cgroup_sockets_enabled) 5438 return; 5439 5440 /* Do not associate the sock with unrelated interrupted task's memcg. */ 5441 if (!in_task()) 5442 return; 5443 5444 rcu_read_lock(); 5445 memcg = mem_cgroup_from_task(current); 5446 if (mem_cgroup_is_root(memcg)) 5447 goto out; 5448 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg1_tcpmem_active(memcg)) 5449 goto out; 5450 if (css_tryget(&memcg->css)) 5451 sk->sk_memcg = memcg; 5452 out: 5453 rcu_read_unlock(); 5454 } 5455 5456 void mem_cgroup_sk_free(struct sock *sk) 5457 { 5458 struct mem_cgroup *memcg = mem_cgroup_from_sk(sk); 5459 5460 if (memcg) 5461 css_put(&memcg->css); 5462 } 5463 5464 void mem_cgroup_sk_inherit(const struct sock *sk, struct sock *newsk) 5465 { 5466 struct mem_cgroup *memcg; 5467 5468 if (sk->sk_memcg == newsk->sk_memcg) 5469 return; 5470 5471 mem_cgroup_sk_free(newsk); 5472 5473 memcg = mem_cgroup_from_sk(sk); 5474 if (memcg) 5475 css_get(&memcg->css); 5476 5477 newsk->sk_memcg = sk->sk_memcg; 5478 } 5479 5480 /** 5481 * mem_cgroup_sk_charge - charge socket memory 5482 * @sk: socket in memcg to charge 5483 * @nr_pages: number of pages to charge 5484 * @gfp_mask: reclaim mode 5485 * 5486 * Charges @nr_pages to @memcg. Returns %true if the charge fit within 5487 * @memcg's configured limit, %false if it doesn't. 5488 */ 5489 bool mem_cgroup_sk_charge(const struct sock *sk, unsigned int nr_pages, 5490 gfp_t gfp_mask) 5491 { 5492 struct mem_cgroup *memcg = mem_cgroup_from_sk(sk); 5493 5494 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) 5495 return memcg1_charge_skmem(memcg, nr_pages, gfp_mask); 5496 5497 if (try_charge_memcg(memcg, gfp_mask, nr_pages) == 0) { 5498 mod_memcg_state(memcg, MEMCG_SOCK, nr_pages); 5499 return true; 5500 } 5501 5502 return false; 5503 } 5504 5505 /** 5506 * mem_cgroup_sk_uncharge - uncharge socket memory 5507 * @sk: socket in memcg to uncharge 5508 * @nr_pages: number of pages to uncharge 5509 */ 5510 void mem_cgroup_sk_uncharge(const struct sock *sk, unsigned int nr_pages) 5511 { 5512 struct mem_cgroup *memcg = mem_cgroup_from_sk(sk); 5513 5514 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) { 5515 memcg1_uncharge_skmem(memcg, nr_pages); 5516 return; 5517 } 5518 5519 mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages); 5520 5521 refill_stock(memcg, nr_pages); 5522 } 5523 5524 void mem_cgroup_flush_workqueue(void) 5525 { 5526 flush_workqueue(memcg_wq); 5527 } 5528 5529 static int __init cgroup_memory(char *s) 5530 { 5531 char *token; 5532 5533 while ((token = strsep(&s, ",")) != NULL) { 5534 if (!*token) 5535 continue; 5536 if (!strcmp(token, "nosocket")) 5537 cgroup_memory_nosocket = true; 5538 if (!strcmp(token, "nokmem")) 5539 cgroup_memory_nokmem = true; 5540 if (!strcmp(token, "nobpf")) 5541 cgroup_memory_nobpf = true; 5542 } 5543 return 1; 5544 } 5545 __setup("cgroup.memory=", cgroup_memory); 5546 5547 /* 5548 * Memory controller init before cgroup_init() initialize root_mem_cgroup. 5549 * 5550 * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this 5551 * context because of lock dependencies (cgroup_lock -> cpu hotplug) but 5552 * basically everything that doesn't depend on a specific mem_cgroup structure 5553 * should be initialized from here. 5554 */ 5555 int __init mem_cgroup_init(void) 5556 { 5557 unsigned int memcg_size; 5558 int cpu; 5559 5560 /* 5561 * Currently s32 type (can refer to struct batched_lruvec_stat) is 5562 * used for per-memcg-per-cpu caching of per-node statistics. In order 5563 * to work fine, we should make sure that the overfill threshold can't 5564 * exceed S32_MAX / PAGE_SIZE. 5565 */ 5566 BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE); 5567 5568 cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL, 5569 memcg_hotplug_cpu_dead); 5570 5571 memcg_wq = alloc_workqueue("memcg", WQ_PERCPU, 0); 5572 WARN_ON(!memcg_wq); 5573 5574 for_each_possible_cpu(cpu) { 5575 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work, 5576 drain_local_memcg_stock); 5577 INIT_WORK(&per_cpu_ptr(&obj_stock, cpu)->work, 5578 drain_local_obj_stock); 5579 } 5580 5581 memcg_size = struct_size_t(struct mem_cgroup, nodeinfo, nr_node_ids); 5582 memcg_cachep = kmem_cache_create("mem_cgroup", memcg_size, 0, 5583 SLAB_PANIC | SLAB_HWCACHE_ALIGN, NULL); 5584 5585 memcg_pn_cachep = KMEM_CACHE(mem_cgroup_per_node, 5586 SLAB_PANIC | SLAB_HWCACHE_ALIGN); 5587 5588 return 0; 5589 } 5590 5591 #ifdef CONFIG_SWAP 5592 /** 5593 * __mem_cgroup_try_charge_swap - try charging swap space for a folio 5594 * @folio: folio being added to swap 5595 * 5596 * Try to charge @folio's memcg for the swap space at folio->swap. 5597 * 5598 * Returns 0 on success, -ENOMEM on failure. 5599 */ 5600 int __mem_cgroup_try_charge_swap(struct folio *folio) 5601 { 5602 unsigned int nr_pages = folio_nr_pages(folio); 5603 struct swap_cluster_info *ci; 5604 struct page_counter *counter; 5605 struct mem_cgroup *memcg; 5606 struct obj_cgroup *objcg; 5607 5608 if (do_memsw_account()) 5609 return 0; 5610 5611 objcg = folio_objcg(folio); 5612 VM_WARN_ON_ONCE_FOLIO(!objcg, folio); 5613 if (!objcg) 5614 return 0; 5615 5616 rcu_read_lock(); 5617 memcg = obj_cgroup_memcg(objcg); 5618 if (!folio_test_swapcache(folio)) { 5619 memcg_memory_event(memcg, MEMCG_SWAP_FAIL); 5620 rcu_read_unlock(); 5621 return 0; 5622 } 5623 5624 memcg = mem_cgroup_private_id_get_online(memcg, nr_pages); 5625 /* memcg is pined by memcg ID. */ 5626 rcu_read_unlock(); 5627 5628 if (!mem_cgroup_is_root(memcg) && 5629 !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) { 5630 memcg_memory_event(memcg, MEMCG_SWAP_MAX); 5631 memcg_memory_event(memcg, MEMCG_SWAP_FAIL); 5632 mem_cgroup_private_id_put(memcg, nr_pages); 5633 return -ENOMEM; 5634 } 5635 mod_memcg_state(memcg, MEMCG_SWAP, nr_pages); 5636 5637 ci = swap_cluster_get_and_lock(folio); 5638 __swap_cgroup_set(ci, swp_cluster_offset(folio->swap), nr_pages, 5639 mem_cgroup_private_id(memcg)); 5640 swap_cluster_unlock(ci); 5641 5642 return 0; 5643 } 5644 5645 /** 5646 * __mem_cgroup_uncharge_swap - uncharge swap space 5647 * @id: cgroup id to uncharge 5648 * @nr_pages: the amount of swap space to uncharge 5649 */ 5650 void __mem_cgroup_uncharge_swap(unsigned short id, unsigned int nr_pages) 5651 { 5652 struct mem_cgroup *memcg; 5653 5654 rcu_read_lock(); 5655 memcg = mem_cgroup_from_private_id(id); 5656 if (memcg) { 5657 if (!mem_cgroup_is_root(memcg)) { 5658 if (do_memsw_account()) 5659 page_counter_uncharge(&memcg->memsw, nr_pages); 5660 else 5661 page_counter_uncharge(&memcg->swap, nr_pages); 5662 } 5663 mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages); 5664 mem_cgroup_private_id_put(memcg, nr_pages); 5665 } 5666 rcu_read_unlock(); 5667 } 5668 5669 long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg) 5670 { 5671 long nr_swap_pages = get_nr_swap_pages(); 5672 5673 if (mem_cgroup_disabled() || do_memsw_account()) 5674 return nr_swap_pages; 5675 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) 5676 nr_swap_pages = min_t(long, nr_swap_pages, 5677 READ_ONCE(memcg->swap.max) - 5678 page_counter_read(&memcg->swap)); 5679 return nr_swap_pages; 5680 } 5681 5682 bool mem_cgroup_swap_full(struct folio *folio) 5683 { 5684 struct mem_cgroup *memcg; 5685 bool ret = false; 5686 5687 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); 5688 5689 if (vm_swap_full()) 5690 return true; 5691 if (do_memsw_account() || !folio_memcg_charged(folio)) 5692 return ret; 5693 5694 rcu_read_lock(); 5695 memcg = folio_memcg(folio); 5696 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) { 5697 unsigned long usage = page_counter_read(&memcg->swap); 5698 5699 if (usage * 2 >= READ_ONCE(memcg->swap.high) || 5700 usage * 2 >= READ_ONCE(memcg->swap.max)) { 5701 ret = true; 5702 break; 5703 } 5704 } 5705 rcu_read_unlock(); 5706 5707 return ret; 5708 } 5709 5710 static int __init setup_swap_account(char *s) 5711 { 5712 bool res; 5713 5714 if (!kstrtobool(s, &res) && !res) 5715 pr_warn_once("The swapaccount=0 commandline option is deprecated " 5716 "in favor of configuring swap control via cgroupfs. " 5717 "Please report your usecase to linux-mm@kvack.org if you " 5718 "depend on this functionality.\n"); 5719 return 1; 5720 } 5721 __setup("swapaccount=", setup_swap_account); 5722 5723 static u64 swap_current_read(struct cgroup_subsys_state *css, 5724 struct cftype *cft) 5725 { 5726 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 5727 5728 return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE; 5729 } 5730 5731 static int swap_peak_show(struct seq_file *sf, void *v) 5732 { 5733 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(sf)); 5734 5735 return peak_show(sf, v, &memcg->swap); 5736 } 5737 5738 static ssize_t swap_peak_write(struct kernfs_open_file *of, char *buf, 5739 size_t nbytes, loff_t off) 5740 { 5741 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 5742 5743 return peak_write(of, buf, nbytes, off, &memcg->swap, 5744 &memcg->swap_peaks); 5745 } 5746 5747 static int swap_high_show(struct seq_file *m, void *v) 5748 { 5749 return seq_puts_memcg_tunable(m, 5750 READ_ONCE(mem_cgroup_from_seq(m)->swap.high)); 5751 } 5752 5753 static ssize_t swap_high_write(struct kernfs_open_file *of, 5754 char *buf, size_t nbytes, loff_t off) 5755 { 5756 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 5757 unsigned long high; 5758 int err; 5759 5760 buf = strstrip(buf); 5761 err = page_counter_memparse(buf, "max", &high); 5762 if (err) 5763 return err; 5764 5765 page_counter_set_high(&memcg->swap, high); 5766 5767 return nbytes; 5768 } 5769 5770 static int swap_max_show(struct seq_file *m, void *v) 5771 { 5772 return seq_puts_memcg_tunable(m, 5773 READ_ONCE(mem_cgroup_from_seq(m)->swap.max)); 5774 } 5775 5776 static ssize_t swap_max_write(struct kernfs_open_file *of, 5777 char *buf, size_t nbytes, loff_t off) 5778 { 5779 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 5780 unsigned long max; 5781 int err; 5782 5783 buf = strstrip(buf); 5784 err = page_counter_memparse(buf, "max", &max); 5785 if (err) 5786 return err; 5787 5788 xchg(&memcg->swap.max, max); 5789 5790 return nbytes; 5791 } 5792 5793 static int swap_events_show(struct seq_file *m, void *v) 5794 { 5795 struct mem_cgroup *memcg = mem_cgroup_from_seq(m); 5796 5797 seq_printf(m, "high %lu\n", 5798 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH])); 5799 seq_printf(m, "max %lu\n", 5800 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX])); 5801 seq_printf(m, "fail %lu\n", 5802 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL])); 5803 5804 return 0; 5805 } 5806 5807 static struct cftype swap_files[] = { 5808 { 5809 .name = "swap.current", 5810 .flags = CFTYPE_NOT_ON_ROOT, 5811 .read_u64 = swap_current_read, 5812 }, 5813 { 5814 .name = "swap.high", 5815 .flags = CFTYPE_NOT_ON_ROOT, 5816 .seq_show = swap_high_show, 5817 .write = swap_high_write, 5818 }, 5819 { 5820 .name = "swap.max", 5821 .flags = CFTYPE_NOT_ON_ROOT, 5822 .seq_show = swap_max_show, 5823 .write = swap_max_write, 5824 }, 5825 { 5826 .name = "swap.peak", 5827 .flags = CFTYPE_NOT_ON_ROOT, 5828 .open = peak_open, 5829 .release = peak_release, 5830 .seq_show = swap_peak_show, 5831 .write = swap_peak_write, 5832 }, 5833 { 5834 .name = "swap.events", 5835 .flags = CFTYPE_NOT_ON_ROOT, 5836 .file_offset = offsetof(struct mem_cgroup, swap_events_file), 5837 .seq_show = swap_events_show, 5838 }, 5839 { } /* terminate */ 5840 }; 5841 5842 #ifdef CONFIG_ZSWAP 5843 /** 5844 * obj_cgroup_may_zswap - check if this cgroup can zswap 5845 * @objcg: the object cgroup 5846 * 5847 * Check if the hierarchical zswap limit has been reached. 5848 * 5849 * This doesn't check for specific headroom, and it is not atomic 5850 * either. But with zswap, the size of the allocation is only known 5851 * once compression has occurred, and this optimistic pre-check avoids 5852 * spending cycles on compression when there is already no room left 5853 * or zswap is disabled altogether somewhere in the hierarchy. 5854 */ 5855 bool obj_cgroup_may_zswap(struct obj_cgroup *objcg) 5856 { 5857 struct mem_cgroup *memcg, *original_memcg; 5858 bool ret = true; 5859 5860 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) 5861 return true; 5862 5863 original_memcg = get_mem_cgroup_from_objcg(objcg); 5864 for (memcg = original_memcg; !mem_cgroup_is_root(memcg); 5865 memcg = parent_mem_cgroup(memcg)) { 5866 unsigned long max = READ_ONCE(memcg->zswap_max); 5867 unsigned long pages; 5868 5869 if (max == PAGE_COUNTER_MAX) 5870 continue; 5871 if (max == 0) { 5872 ret = false; 5873 break; 5874 } 5875 5876 /* Force flush to get accurate stats for charging */ 5877 __mem_cgroup_flush_stats(memcg, true); 5878 pages = memcg_page_state(memcg, MEMCG_ZSWAP_B) / PAGE_SIZE; 5879 if (pages < max) 5880 continue; 5881 ret = false; 5882 break; 5883 } 5884 mem_cgroup_put(original_memcg); 5885 return ret; 5886 } 5887 5888 /** 5889 * obj_cgroup_charge_zswap - charge compression backend memory 5890 * @objcg: the object cgroup 5891 * @size: size of compressed object 5892 * 5893 * This forces the charge after obj_cgroup_may_zswap() allowed 5894 * compression and storage in zswap for this cgroup to go ahead. 5895 */ 5896 void obj_cgroup_charge_zswap(struct obj_cgroup *objcg, size_t size) 5897 { 5898 struct mem_cgroup *memcg; 5899 5900 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) 5901 return; 5902 5903 if (obj_cgroup_is_root(objcg)) 5904 return; 5905 5906 VM_WARN_ON_ONCE(!(current->flags & PF_MEMALLOC)); 5907 5908 /* PF_MEMALLOC context, charging must succeed */ 5909 if (obj_cgroup_charge(objcg, GFP_KERNEL, size)) 5910 VM_WARN_ON_ONCE(1); 5911 5912 rcu_read_lock(); 5913 memcg = obj_cgroup_memcg(objcg); 5914 mod_memcg_state(memcg, MEMCG_ZSWAP_B, size); 5915 mod_memcg_state(memcg, MEMCG_ZSWAPPED, 1); 5916 if (size == PAGE_SIZE) 5917 mod_memcg_state(memcg, MEMCG_ZSWAP_INCOMP, 1); 5918 rcu_read_unlock(); 5919 } 5920 5921 /** 5922 * obj_cgroup_uncharge_zswap - uncharge compression backend memory 5923 * @objcg: the object cgroup 5924 * @size: size of compressed object 5925 * 5926 * Uncharges zswap memory on page in. 5927 */ 5928 void obj_cgroup_uncharge_zswap(struct obj_cgroup *objcg, size_t size) 5929 { 5930 struct mem_cgroup *memcg; 5931 5932 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) 5933 return; 5934 5935 if (obj_cgroup_is_root(objcg)) 5936 return; 5937 5938 obj_cgroup_uncharge(objcg, size); 5939 5940 rcu_read_lock(); 5941 memcg = obj_cgroup_memcg(objcg); 5942 mod_memcg_state(memcg, MEMCG_ZSWAP_B, -size); 5943 mod_memcg_state(memcg, MEMCG_ZSWAPPED, -1); 5944 if (size == PAGE_SIZE) 5945 mod_memcg_state(memcg, MEMCG_ZSWAP_INCOMP, -1); 5946 rcu_read_unlock(); 5947 } 5948 5949 bool mem_cgroup_zswap_writeback_enabled(struct mem_cgroup *memcg) 5950 { 5951 /* if zswap is disabled, do not block pages going to the swapping device */ 5952 if (!zswap_is_enabled()) 5953 return true; 5954 5955 for (; memcg; memcg = parent_mem_cgroup(memcg)) 5956 if (!READ_ONCE(memcg->zswap_writeback)) 5957 return false; 5958 5959 return true; 5960 } 5961 5962 static u64 zswap_current_read(struct cgroup_subsys_state *css, 5963 struct cftype *cft) 5964 { 5965 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 5966 5967 mem_cgroup_flush_stats(memcg); 5968 return memcg_page_state(memcg, MEMCG_ZSWAP_B); 5969 } 5970 5971 static int zswap_max_show(struct seq_file *m, void *v) 5972 { 5973 return seq_puts_memcg_tunable(m, 5974 READ_ONCE(mem_cgroup_from_seq(m)->zswap_max)); 5975 } 5976 5977 static ssize_t zswap_max_write(struct kernfs_open_file *of, 5978 char *buf, size_t nbytes, loff_t off) 5979 { 5980 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 5981 unsigned long max; 5982 int err; 5983 5984 buf = strstrip(buf); 5985 err = page_counter_memparse(buf, "max", &max); 5986 if (err) 5987 return err; 5988 5989 xchg(&memcg->zswap_max, max); 5990 5991 return nbytes; 5992 } 5993 5994 static int zswap_writeback_show(struct seq_file *m, void *v) 5995 { 5996 struct mem_cgroup *memcg = mem_cgroup_from_seq(m); 5997 5998 seq_printf(m, "%d\n", READ_ONCE(memcg->zswap_writeback)); 5999 return 0; 6000 } 6001 6002 static ssize_t zswap_writeback_write(struct kernfs_open_file *of, 6003 char *buf, size_t nbytes, loff_t off) 6004 { 6005 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 6006 int zswap_writeback; 6007 ssize_t parse_ret = kstrtoint(strstrip(buf), 0, &zswap_writeback); 6008 6009 if (parse_ret) 6010 return parse_ret; 6011 6012 if (zswap_writeback != 0 && zswap_writeback != 1) 6013 return -EINVAL; 6014 6015 WRITE_ONCE(memcg->zswap_writeback, zswap_writeback); 6016 return nbytes; 6017 } 6018 6019 static struct cftype zswap_files[] = { 6020 { 6021 .name = "zswap.current", 6022 .flags = CFTYPE_NOT_ON_ROOT, 6023 .read_u64 = zswap_current_read, 6024 }, 6025 { 6026 .name = "zswap.max", 6027 .flags = CFTYPE_NOT_ON_ROOT, 6028 .seq_show = zswap_max_show, 6029 .write = zswap_max_write, 6030 }, 6031 { 6032 .name = "zswap.writeback", 6033 .seq_show = zswap_writeback_show, 6034 .write = zswap_writeback_write, 6035 }, 6036 { } /* terminate */ 6037 }; 6038 #endif /* CONFIG_ZSWAP */ 6039 6040 static int __init mem_cgroup_swap_init(void) 6041 { 6042 if (mem_cgroup_disabled()) 6043 return 0; 6044 6045 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files)); 6046 #ifdef CONFIG_MEMCG_V1 6047 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files)); 6048 #endif 6049 #ifdef CONFIG_ZSWAP 6050 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, zswap_files)); 6051 #endif 6052 return 0; 6053 } 6054 subsys_initcall(mem_cgroup_swap_init); 6055 6056 #endif /* CONFIG_SWAP */ 6057 6058 void mem_cgroup_node_filter_allowed(struct mem_cgroup *memcg, nodemask_t *mask) 6059 { 6060 nodemask_t allowed; 6061 6062 if (!memcg) 6063 return; 6064 6065 /* 6066 * Since this interface is intended for use by migration paths, and 6067 * reclaim and migration are subject to race conditions such as changes 6068 * in effective_mems and hot-unpluging of nodes, inaccurate allowed 6069 * mask is acceptable. 6070 */ 6071 cpuset_nodes_allowed(memcg->css.cgroup, &allowed); 6072 nodes_and(*mask, *mask, allowed); 6073 } 6074 6075 void mem_cgroup_show_protected_memory(struct mem_cgroup *memcg) 6076 { 6077 if (mem_cgroup_disabled() || !cgroup_subsys_on_dfl(memory_cgrp_subsys)) 6078 return; 6079 6080 if (!memcg) 6081 memcg = root_mem_cgroup; 6082 6083 pr_warn("Memory cgroup min protection %lukB -- low protection %lukB", 6084 K(atomic_long_read(&memcg->memory.children_min_usage)), 6085 K(atomic_long_read(&memcg->memory.children_low_usage))); 6086 } 6087