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