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