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