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