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