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/page_counter.h> 29 #include <linux/memcontrol.h> 30 #include <linux/cgroup.h> 31 #include <linux/pagewalk.h> 32 #include <linux/sched/mm.h> 33 #include <linux/shmem_fs.h> 34 #include <linux/hugetlb.h> 35 #include <linux/pagemap.h> 36 #include <linux/vm_event_item.h> 37 #include <linux/smp.h> 38 #include <linux/page-flags.h> 39 #include <linux/backing-dev.h> 40 #include <linux/bit_spinlock.h> 41 #include <linux/rcupdate.h> 42 #include <linux/limits.h> 43 #include <linux/export.h> 44 #include <linux/mutex.h> 45 #include <linux/rbtree.h> 46 #include <linux/slab.h> 47 #include <linux/swap.h> 48 #include <linux/swapops.h> 49 #include <linux/spinlock.h> 50 #include <linux/eventfd.h> 51 #include <linux/poll.h> 52 #include <linux/sort.h> 53 #include <linux/fs.h> 54 #include <linux/seq_file.h> 55 #include <linux/vmpressure.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/file.h> 62 #include <linux/tracehook.h> 63 #include <linux/psi.h> 64 #include <linux/seq_buf.h> 65 #include "internal.h" 66 #include <net/sock.h> 67 #include <net/ip.h> 68 #include "slab.h" 69 70 #include <linux/uaccess.h> 71 72 #include <trace/events/vmscan.h> 73 74 struct cgroup_subsys memory_cgrp_subsys __read_mostly; 75 EXPORT_SYMBOL(memory_cgrp_subsys); 76 77 struct mem_cgroup *root_mem_cgroup __read_mostly; 78 79 /* Active memory cgroup to use from an interrupt context */ 80 DEFINE_PER_CPU(struct mem_cgroup *, int_active_memcg); 81 EXPORT_PER_CPU_SYMBOL_GPL(int_active_memcg); 82 83 /* Socket memory accounting disabled? */ 84 static bool cgroup_memory_nosocket __ro_after_init; 85 86 /* Kernel memory accounting disabled? */ 87 static bool cgroup_memory_nokmem __ro_after_init; 88 89 /* Whether the swap controller is active */ 90 #ifdef CONFIG_MEMCG_SWAP 91 bool cgroup_memory_noswap __ro_after_init; 92 #else 93 #define cgroup_memory_noswap 1 94 #endif 95 96 #ifdef CONFIG_CGROUP_WRITEBACK 97 static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq); 98 #endif 99 100 /* Whether legacy memory+swap accounting is active */ 101 static bool do_memsw_account(void) 102 { 103 return !cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_noswap; 104 } 105 106 #define THRESHOLDS_EVENTS_TARGET 128 107 #define SOFTLIMIT_EVENTS_TARGET 1024 108 109 /* 110 * Cgroups above their limits are maintained in a RB-Tree, independent of 111 * their hierarchy representation 112 */ 113 114 struct mem_cgroup_tree_per_node { 115 struct rb_root rb_root; 116 struct rb_node *rb_rightmost; 117 spinlock_t lock; 118 }; 119 120 struct mem_cgroup_tree { 121 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES]; 122 }; 123 124 static struct mem_cgroup_tree soft_limit_tree __read_mostly; 125 126 /* for OOM */ 127 struct mem_cgroup_eventfd_list { 128 struct list_head list; 129 struct eventfd_ctx *eventfd; 130 }; 131 132 /* 133 * cgroup_event represents events which userspace want to receive. 134 */ 135 struct mem_cgroup_event { 136 /* 137 * memcg which the event belongs to. 138 */ 139 struct mem_cgroup *memcg; 140 /* 141 * eventfd to signal userspace about the event. 142 */ 143 struct eventfd_ctx *eventfd; 144 /* 145 * Each of these stored in a list by the cgroup. 146 */ 147 struct list_head list; 148 /* 149 * register_event() callback will be used to add new userspace 150 * waiter for changes related to this event. Use eventfd_signal() 151 * on eventfd to send notification to userspace. 152 */ 153 int (*register_event)(struct mem_cgroup *memcg, 154 struct eventfd_ctx *eventfd, const char *args); 155 /* 156 * unregister_event() callback will be called when userspace closes 157 * the eventfd or on cgroup removing. This callback must be set, 158 * if you want provide notification functionality. 159 */ 160 void (*unregister_event)(struct mem_cgroup *memcg, 161 struct eventfd_ctx *eventfd); 162 /* 163 * All fields below needed to unregister event when 164 * userspace closes eventfd. 165 */ 166 poll_table pt; 167 wait_queue_head_t *wqh; 168 wait_queue_entry_t wait; 169 struct work_struct remove; 170 }; 171 172 static void mem_cgroup_threshold(struct mem_cgroup *memcg); 173 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg); 174 175 /* Stuffs for move charges at task migration. */ 176 /* 177 * Types of charges to be moved. 178 */ 179 #define MOVE_ANON 0x1U 180 #define MOVE_FILE 0x2U 181 #define MOVE_MASK (MOVE_ANON | MOVE_FILE) 182 183 /* "mc" and its members are protected by cgroup_mutex */ 184 static struct move_charge_struct { 185 spinlock_t lock; /* for from, to */ 186 struct mm_struct *mm; 187 struct mem_cgroup *from; 188 struct mem_cgroup *to; 189 unsigned long flags; 190 unsigned long precharge; 191 unsigned long moved_charge; 192 unsigned long moved_swap; 193 struct task_struct *moving_task; /* a task moving charges */ 194 wait_queue_head_t waitq; /* a waitq for other context */ 195 } mc = { 196 .lock = __SPIN_LOCK_UNLOCKED(mc.lock), 197 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq), 198 }; 199 200 /* 201 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft 202 * limit reclaim to prevent infinite loops, if they ever occur. 203 */ 204 #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100 205 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2 206 207 /* for encoding cft->private value on file */ 208 enum res_type { 209 _MEM, 210 _MEMSWAP, 211 _OOM_TYPE, 212 _KMEM, 213 _TCP, 214 }; 215 216 #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val)) 217 #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff) 218 #define MEMFILE_ATTR(val) ((val) & 0xffff) 219 /* Used for OOM notifier */ 220 #define OOM_CONTROL (0) 221 222 /* 223 * Iteration constructs for visiting all cgroups (under a tree). If 224 * loops are exited prematurely (break), mem_cgroup_iter_break() must 225 * be used for reference counting. 226 */ 227 #define for_each_mem_cgroup_tree(iter, root) \ 228 for (iter = mem_cgroup_iter(root, NULL, NULL); \ 229 iter != NULL; \ 230 iter = mem_cgroup_iter(root, iter, NULL)) 231 232 #define for_each_mem_cgroup(iter) \ 233 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \ 234 iter != NULL; \ 235 iter = mem_cgroup_iter(NULL, iter, NULL)) 236 237 static inline bool task_is_dying(void) 238 { 239 return tsk_is_oom_victim(current) || fatal_signal_pending(current) || 240 (current->flags & PF_EXITING); 241 } 242 243 /* Some nice accessors for the vmpressure. */ 244 struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg) 245 { 246 if (!memcg) 247 memcg = root_mem_cgroup; 248 return &memcg->vmpressure; 249 } 250 251 struct mem_cgroup *vmpressure_to_memcg(struct vmpressure *vmpr) 252 { 253 return container_of(vmpr, struct mem_cgroup, vmpressure); 254 } 255 256 #ifdef CONFIG_MEMCG_KMEM 257 static DEFINE_SPINLOCK(objcg_lock); 258 259 bool mem_cgroup_kmem_disabled(void) 260 { 261 return cgroup_memory_nokmem; 262 } 263 264 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg, 265 unsigned int nr_pages); 266 267 static void obj_cgroup_release(struct percpu_ref *ref) 268 { 269 struct obj_cgroup *objcg = container_of(ref, struct obj_cgroup, refcnt); 270 unsigned int nr_bytes; 271 unsigned int nr_pages; 272 unsigned long flags; 273 274 /* 275 * At this point all allocated objects are freed, and 276 * objcg->nr_charged_bytes can't have an arbitrary byte value. 277 * However, it can be PAGE_SIZE or (x * PAGE_SIZE). 278 * 279 * The following sequence can lead to it: 280 * 1) CPU0: objcg == stock->cached_objcg 281 * 2) CPU1: we do a small allocation (e.g. 92 bytes), 282 * PAGE_SIZE bytes are charged 283 * 3) CPU1: a process from another memcg is allocating something, 284 * the stock if flushed, 285 * objcg->nr_charged_bytes = PAGE_SIZE - 92 286 * 5) CPU0: we do release this object, 287 * 92 bytes are added to stock->nr_bytes 288 * 6) CPU0: stock is flushed, 289 * 92 bytes are added to objcg->nr_charged_bytes 290 * 291 * In the result, nr_charged_bytes == PAGE_SIZE. 292 * This page will be uncharged in obj_cgroup_release(). 293 */ 294 nr_bytes = atomic_read(&objcg->nr_charged_bytes); 295 WARN_ON_ONCE(nr_bytes & (PAGE_SIZE - 1)); 296 nr_pages = nr_bytes >> PAGE_SHIFT; 297 298 if (nr_pages) 299 obj_cgroup_uncharge_pages(objcg, nr_pages); 300 301 spin_lock_irqsave(&objcg_lock, flags); 302 list_del(&objcg->list); 303 spin_unlock_irqrestore(&objcg_lock, flags); 304 305 percpu_ref_exit(ref); 306 kfree_rcu(objcg, rcu); 307 } 308 309 static struct obj_cgroup *obj_cgroup_alloc(void) 310 { 311 struct obj_cgroup *objcg; 312 int ret; 313 314 objcg = kzalloc(sizeof(struct obj_cgroup), GFP_KERNEL); 315 if (!objcg) 316 return NULL; 317 318 ret = percpu_ref_init(&objcg->refcnt, obj_cgroup_release, 0, 319 GFP_KERNEL); 320 if (ret) { 321 kfree(objcg); 322 return NULL; 323 } 324 INIT_LIST_HEAD(&objcg->list); 325 return objcg; 326 } 327 328 static void memcg_reparent_objcgs(struct mem_cgroup *memcg, 329 struct mem_cgroup *parent) 330 { 331 struct obj_cgroup *objcg, *iter; 332 333 objcg = rcu_replace_pointer(memcg->objcg, NULL, true); 334 335 spin_lock_irq(&objcg_lock); 336 337 /* 1) Ready to reparent active objcg. */ 338 list_add(&objcg->list, &memcg->objcg_list); 339 /* 2) Reparent active objcg and already reparented objcgs to parent. */ 340 list_for_each_entry(iter, &memcg->objcg_list, list) 341 WRITE_ONCE(iter->memcg, parent); 342 /* 3) Move already reparented objcgs to the parent's list */ 343 list_splice(&memcg->objcg_list, &parent->objcg_list); 344 345 spin_unlock_irq(&objcg_lock); 346 347 percpu_ref_kill(&objcg->refcnt); 348 } 349 350 /* 351 * A lot of the calls to the cache allocation functions are expected to be 352 * inlined by the compiler. Since the calls to memcg_slab_pre_alloc_hook() are 353 * conditional to this static branch, we'll have to allow modules that does 354 * kmem_cache_alloc and the such to see this symbol as well 355 */ 356 DEFINE_STATIC_KEY_FALSE(memcg_kmem_enabled_key); 357 EXPORT_SYMBOL(memcg_kmem_enabled_key); 358 #endif 359 360 /** 361 * mem_cgroup_css_from_page - css of the memcg associated with a page 362 * @page: page of interest 363 * 364 * If memcg is bound to the default hierarchy, css of the memcg associated 365 * with @page is returned. The returned css remains associated with @page 366 * until it is released. 367 * 368 * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup 369 * is returned. 370 */ 371 struct cgroup_subsys_state *mem_cgroup_css_from_page(struct page *page) 372 { 373 struct mem_cgroup *memcg; 374 375 memcg = page_memcg(page); 376 377 if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys)) 378 memcg = root_mem_cgroup; 379 380 return &memcg->css; 381 } 382 383 /** 384 * page_cgroup_ino - return inode number of the memcg a page is charged to 385 * @page: the page 386 * 387 * Look up the closest online ancestor of the memory cgroup @page is charged to 388 * and return its inode number or 0 if @page is not charged to any cgroup. It 389 * is safe to call this function without holding a reference to @page. 390 * 391 * Note, this function is inherently racy, because there is nothing to prevent 392 * the cgroup inode from getting torn down and potentially reallocated a moment 393 * after page_cgroup_ino() returns, so it only should be used by callers that 394 * do not care (such as procfs interfaces). 395 */ 396 ino_t page_cgroup_ino(struct page *page) 397 { 398 struct mem_cgroup *memcg; 399 unsigned long ino = 0; 400 401 rcu_read_lock(); 402 memcg = page_memcg_check(page); 403 404 while (memcg && !(memcg->css.flags & CSS_ONLINE)) 405 memcg = parent_mem_cgroup(memcg); 406 if (memcg) 407 ino = cgroup_ino(memcg->css.cgroup); 408 rcu_read_unlock(); 409 return ino; 410 } 411 412 static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_node *mz, 413 struct mem_cgroup_tree_per_node *mctz, 414 unsigned long new_usage_in_excess) 415 { 416 struct rb_node **p = &mctz->rb_root.rb_node; 417 struct rb_node *parent = NULL; 418 struct mem_cgroup_per_node *mz_node; 419 bool rightmost = true; 420 421 if (mz->on_tree) 422 return; 423 424 mz->usage_in_excess = new_usage_in_excess; 425 if (!mz->usage_in_excess) 426 return; 427 while (*p) { 428 parent = *p; 429 mz_node = rb_entry(parent, struct mem_cgroup_per_node, 430 tree_node); 431 if (mz->usage_in_excess < mz_node->usage_in_excess) { 432 p = &(*p)->rb_left; 433 rightmost = false; 434 } else { 435 p = &(*p)->rb_right; 436 } 437 } 438 439 if (rightmost) 440 mctz->rb_rightmost = &mz->tree_node; 441 442 rb_link_node(&mz->tree_node, parent, p); 443 rb_insert_color(&mz->tree_node, &mctz->rb_root); 444 mz->on_tree = true; 445 } 446 447 static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz, 448 struct mem_cgroup_tree_per_node *mctz) 449 { 450 if (!mz->on_tree) 451 return; 452 453 if (&mz->tree_node == mctz->rb_rightmost) 454 mctz->rb_rightmost = rb_prev(&mz->tree_node); 455 456 rb_erase(&mz->tree_node, &mctz->rb_root); 457 mz->on_tree = false; 458 } 459 460 static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz, 461 struct mem_cgroup_tree_per_node *mctz) 462 { 463 unsigned long flags; 464 465 spin_lock_irqsave(&mctz->lock, flags); 466 __mem_cgroup_remove_exceeded(mz, mctz); 467 spin_unlock_irqrestore(&mctz->lock, flags); 468 } 469 470 static unsigned long soft_limit_excess(struct mem_cgroup *memcg) 471 { 472 unsigned long nr_pages = page_counter_read(&memcg->memory); 473 unsigned long soft_limit = READ_ONCE(memcg->soft_limit); 474 unsigned long excess = 0; 475 476 if (nr_pages > soft_limit) 477 excess = nr_pages - soft_limit; 478 479 return excess; 480 } 481 482 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, int nid) 483 { 484 unsigned long excess; 485 struct mem_cgroup_per_node *mz; 486 struct mem_cgroup_tree_per_node *mctz; 487 488 mctz = soft_limit_tree.rb_tree_per_node[nid]; 489 if (!mctz) 490 return; 491 /* 492 * Necessary to update all ancestors when hierarchy is used. 493 * because their event counter is not touched. 494 */ 495 for (; memcg; memcg = parent_mem_cgroup(memcg)) { 496 mz = memcg->nodeinfo[nid]; 497 excess = soft_limit_excess(memcg); 498 /* 499 * We have to update the tree if mz is on RB-tree or 500 * mem is over its softlimit. 501 */ 502 if (excess || mz->on_tree) { 503 unsigned long flags; 504 505 spin_lock_irqsave(&mctz->lock, flags); 506 /* if on-tree, remove it */ 507 if (mz->on_tree) 508 __mem_cgroup_remove_exceeded(mz, mctz); 509 /* 510 * Insert again. mz->usage_in_excess will be updated. 511 * If excess is 0, no tree ops. 512 */ 513 __mem_cgroup_insert_exceeded(mz, mctz, excess); 514 spin_unlock_irqrestore(&mctz->lock, flags); 515 } 516 } 517 } 518 519 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg) 520 { 521 struct mem_cgroup_tree_per_node *mctz; 522 struct mem_cgroup_per_node *mz; 523 int nid; 524 525 for_each_node(nid) { 526 mz = memcg->nodeinfo[nid]; 527 mctz = soft_limit_tree.rb_tree_per_node[nid]; 528 if (mctz) 529 mem_cgroup_remove_exceeded(mz, mctz); 530 } 531 } 532 533 static struct mem_cgroup_per_node * 534 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz) 535 { 536 struct mem_cgroup_per_node *mz; 537 538 retry: 539 mz = NULL; 540 if (!mctz->rb_rightmost) 541 goto done; /* Nothing to reclaim from */ 542 543 mz = rb_entry(mctz->rb_rightmost, 544 struct mem_cgroup_per_node, tree_node); 545 /* 546 * Remove the node now but someone else can add it back, 547 * we will to add it back at the end of reclaim to its correct 548 * position in the tree. 549 */ 550 __mem_cgroup_remove_exceeded(mz, mctz); 551 if (!soft_limit_excess(mz->memcg) || 552 !css_tryget(&mz->memcg->css)) 553 goto retry; 554 done: 555 return mz; 556 } 557 558 static struct mem_cgroup_per_node * 559 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz) 560 { 561 struct mem_cgroup_per_node *mz; 562 563 spin_lock_irq(&mctz->lock); 564 mz = __mem_cgroup_largest_soft_limit_node(mctz); 565 spin_unlock_irq(&mctz->lock); 566 return mz; 567 } 568 569 /* 570 * memcg and lruvec stats flushing 571 * 572 * Many codepaths leading to stats update or read are performance sensitive and 573 * adding stats flushing in such codepaths is not desirable. So, to optimize the 574 * flushing the kernel does: 575 * 576 * 1) Periodically and asynchronously flush the stats every 2 seconds to not let 577 * rstat update tree grow unbounded. 578 * 579 * 2) Flush the stats synchronously on reader side only when there are more than 580 * (MEMCG_CHARGE_BATCH * nr_cpus) update events. Though this optimization 581 * will let stats be out of sync by atmost (MEMCG_CHARGE_BATCH * nr_cpus) but 582 * only for 2 seconds due to (1). 583 */ 584 static void flush_memcg_stats_dwork(struct work_struct *w); 585 static DECLARE_DEFERRABLE_WORK(stats_flush_dwork, flush_memcg_stats_dwork); 586 static DEFINE_SPINLOCK(stats_flush_lock); 587 static DEFINE_PER_CPU(unsigned int, stats_updates); 588 static atomic_t stats_flush_threshold = ATOMIC_INIT(0); 589 590 /* 591 * Accessors to ensure that preemption is disabled on PREEMPT_RT because it can 592 * not rely on this as part of an acquired spinlock_t lock. These functions are 593 * never used in hardirq context on PREEMPT_RT and therefore disabling preemtion 594 * is sufficient. 595 */ 596 static void memcg_stats_lock(void) 597 { 598 #ifdef CONFIG_PREEMPT_RT 599 preempt_disable(); 600 #else 601 VM_BUG_ON(!irqs_disabled()); 602 #endif 603 } 604 605 static void __memcg_stats_lock(void) 606 { 607 #ifdef CONFIG_PREEMPT_RT 608 preempt_disable(); 609 #endif 610 } 611 612 static void memcg_stats_unlock(void) 613 { 614 #ifdef CONFIG_PREEMPT_RT 615 preempt_enable(); 616 #endif 617 } 618 619 static inline void memcg_rstat_updated(struct mem_cgroup *memcg, int val) 620 { 621 unsigned int x; 622 623 cgroup_rstat_updated(memcg->css.cgroup, smp_processor_id()); 624 625 x = __this_cpu_add_return(stats_updates, abs(val)); 626 if (x > MEMCG_CHARGE_BATCH) { 627 atomic_add(x / MEMCG_CHARGE_BATCH, &stats_flush_threshold); 628 __this_cpu_write(stats_updates, 0); 629 } 630 } 631 632 static void __mem_cgroup_flush_stats(void) 633 { 634 unsigned long flag; 635 636 if (!spin_trylock_irqsave(&stats_flush_lock, flag)) 637 return; 638 639 cgroup_rstat_flush_irqsafe(root_mem_cgroup->css.cgroup); 640 atomic_set(&stats_flush_threshold, 0); 641 spin_unlock_irqrestore(&stats_flush_lock, flag); 642 } 643 644 void mem_cgroup_flush_stats(void) 645 { 646 if (atomic_read(&stats_flush_threshold) > num_online_cpus()) 647 __mem_cgroup_flush_stats(); 648 } 649 650 static void flush_memcg_stats_dwork(struct work_struct *w) 651 { 652 __mem_cgroup_flush_stats(); 653 queue_delayed_work(system_unbound_wq, &stats_flush_dwork, 2UL*HZ); 654 } 655 656 /** 657 * __mod_memcg_state - update cgroup memory statistics 658 * @memcg: the memory cgroup 659 * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item 660 * @val: delta to add to the counter, can be negative 661 */ 662 void __mod_memcg_state(struct mem_cgroup *memcg, int idx, int val) 663 { 664 if (mem_cgroup_disabled()) 665 return; 666 667 __this_cpu_add(memcg->vmstats_percpu->state[idx], val); 668 memcg_rstat_updated(memcg, val); 669 } 670 671 /* idx can be of type enum memcg_stat_item or node_stat_item. */ 672 static unsigned long memcg_page_state_local(struct mem_cgroup *memcg, int idx) 673 { 674 long x = 0; 675 int cpu; 676 677 for_each_possible_cpu(cpu) 678 x += per_cpu(memcg->vmstats_percpu->state[idx], cpu); 679 #ifdef CONFIG_SMP 680 if (x < 0) 681 x = 0; 682 #endif 683 return x; 684 } 685 686 void __mod_memcg_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx, 687 int val) 688 { 689 struct mem_cgroup_per_node *pn; 690 struct mem_cgroup *memcg; 691 692 pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec); 693 memcg = pn->memcg; 694 695 /* 696 * The caller from rmap relay on disabled preemption becase they never 697 * update their counter from in-interrupt context. For these two 698 * counters we check that the update is never performed from an 699 * interrupt context while other caller need to have disabled interrupt. 700 */ 701 __memcg_stats_lock(); 702 if (IS_ENABLED(CONFIG_DEBUG_VM) && !IS_ENABLED(CONFIG_PREEMPT_RT)) { 703 switch (idx) { 704 case NR_ANON_MAPPED: 705 case NR_FILE_MAPPED: 706 case NR_ANON_THPS: 707 case NR_SHMEM_PMDMAPPED: 708 case NR_FILE_PMDMAPPED: 709 WARN_ON_ONCE(!in_task()); 710 break; 711 default: 712 WARN_ON_ONCE(!irqs_disabled()); 713 } 714 } 715 716 /* Update memcg */ 717 __this_cpu_add(memcg->vmstats_percpu->state[idx], val); 718 719 /* Update lruvec */ 720 __this_cpu_add(pn->lruvec_stats_percpu->state[idx], val); 721 722 memcg_rstat_updated(memcg, val); 723 memcg_stats_unlock(); 724 } 725 726 /** 727 * __mod_lruvec_state - update lruvec memory statistics 728 * @lruvec: the lruvec 729 * @idx: the stat item 730 * @val: delta to add to the counter, can be negative 731 * 732 * The lruvec is the intersection of the NUMA node and a cgroup. This 733 * function updates the all three counters that are affected by a 734 * change of state at this level: per-node, per-cgroup, per-lruvec. 735 */ 736 void __mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx, 737 int val) 738 { 739 /* Update node */ 740 __mod_node_page_state(lruvec_pgdat(lruvec), idx, val); 741 742 /* Update memcg and lruvec */ 743 if (!mem_cgroup_disabled()) 744 __mod_memcg_lruvec_state(lruvec, idx, val); 745 } 746 747 void __mod_lruvec_page_state(struct page *page, enum node_stat_item idx, 748 int val) 749 { 750 struct page *head = compound_head(page); /* rmap on tail pages */ 751 struct mem_cgroup *memcg; 752 pg_data_t *pgdat = page_pgdat(page); 753 struct lruvec *lruvec; 754 755 rcu_read_lock(); 756 memcg = page_memcg(head); 757 /* Untracked pages have no memcg, no lruvec. Update only the node */ 758 if (!memcg) { 759 rcu_read_unlock(); 760 __mod_node_page_state(pgdat, idx, val); 761 return; 762 } 763 764 lruvec = mem_cgroup_lruvec(memcg, pgdat); 765 __mod_lruvec_state(lruvec, idx, val); 766 rcu_read_unlock(); 767 } 768 EXPORT_SYMBOL(__mod_lruvec_page_state); 769 770 void __mod_lruvec_kmem_state(void *p, enum node_stat_item idx, int val) 771 { 772 pg_data_t *pgdat = page_pgdat(virt_to_page(p)); 773 struct mem_cgroup *memcg; 774 struct lruvec *lruvec; 775 776 rcu_read_lock(); 777 memcg = mem_cgroup_from_obj(p); 778 779 /* 780 * Untracked pages have no memcg, no lruvec. Update only the 781 * node. If we reparent the slab objects to the root memcg, 782 * when we free the slab object, we need to update the per-memcg 783 * vmstats to keep it correct for the root memcg. 784 */ 785 if (!memcg) { 786 __mod_node_page_state(pgdat, idx, val); 787 } else { 788 lruvec = mem_cgroup_lruvec(memcg, pgdat); 789 __mod_lruvec_state(lruvec, idx, val); 790 } 791 rcu_read_unlock(); 792 } 793 794 /** 795 * __count_memcg_events - account VM events in a cgroup 796 * @memcg: the memory cgroup 797 * @idx: the event item 798 * @count: the number of events that occurred 799 */ 800 void __count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx, 801 unsigned long count) 802 { 803 if (mem_cgroup_disabled()) 804 return; 805 806 memcg_stats_lock(); 807 __this_cpu_add(memcg->vmstats_percpu->events[idx], count); 808 memcg_rstat_updated(memcg, count); 809 memcg_stats_unlock(); 810 } 811 812 static unsigned long memcg_events(struct mem_cgroup *memcg, int event) 813 { 814 return READ_ONCE(memcg->vmstats.events[event]); 815 } 816 817 static unsigned long memcg_events_local(struct mem_cgroup *memcg, int event) 818 { 819 long x = 0; 820 int cpu; 821 822 for_each_possible_cpu(cpu) 823 x += per_cpu(memcg->vmstats_percpu->events[event], cpu); 824 return x; 825 } 826 827 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg, 828 int nr_pages) 829 { 830 /* pagein of a big page is an event. So, ignore page size */ 831 if (nr_pages > 0) 832 __count_memcg_events(memcg, PGPGIN, 1); 833 else { 834 __count_memcg_events(memcg, PGPGOUT, 1); 835 nr_pages = -nr_pages; /* for event */ 836 } 837 838 __this_cpu_add(memcg->vmstats_percpu->nr_page_events, nr_pages); 839 } 840 841 static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg, 842 enum mem_cgroup_events_target target) 843 { 844 unsigned long val, next; 845 846 val = __this_cpu_read(memcg->vmstats_percpu->nr_page_events); 847 next = __this_cpu_read(memcg->vmstats_percpu->targets[target]); 848 /* from time_after() in jiffies.h */ 849 if ((long)(next - val) < 0) { 850 switch (target) { 851 case MEM_CGROUP_TARGET_THRESH: 852 next = val + THRESHOLDS_EVENTS_TARGET; 853 break; 854 case MEM_CGROUP_TARGET_SOFTLIMIT: 855 next = val + SOFTLIMIT_EVENTS_TARGET; 856 break; 857 default: 858 break; 859 } 860 __this_cpu_write(memcg->vmstats_percpu->targets[target], next); 861 return true; 862 } 863 return false; 864 } 865 866 /* 867 * Check events in order. 868 * 869 */ 870 static void memcg_check_events(struct mem_cgroup *memcg, int nid) 871 { 872 if (IS_ENABLED(CONFIG_PREEMPT_RT)) 873 return; 874 875 /* threshold event is triggered in finer grain than soft limit */ 876 if (unlikely(mem_cgroup_event_ratelimit(memcg, 877 MEM_CGROUP_TARGET_THRESH))) { 878 bool do_softlimit; 879 880 do_softlimit = mem_cgroup_event_ratelimit(memcg, 881 MEM_CGROUP_TARGET_SOFTLIMIT); 882 mem_cgroup_threshold(memcg); 883 if (unlikely(do_softlimit)) 884 mem_cgroup_update_tree(memcg, nid); 885 } 886 } 887 888 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p) 889 { 890 /* 891 * mm_update_next_owner() may clear mm->owner to NULL 892 * if it races with swapoff, page migration, etc. 893 * So this can be called with p == NULL. 894 */ 895 if (unlikely(!p)) 896 return NULL; 897 898 return mem_cgroup_from_css(task_css(p, memory_cgrp_id)); 899 } 900 EXPORT_SYMBOL(mem_cgroup_from_task); 901 902 static __always_inline struct mem_cgroup *active_memcg(void) 903 { 904 if (!in_task()) 905 return this_cpu_read(int_active_memcg); 906 else 907 return current->active_memcg; 908 } 909 910 /** 911 * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg. 912 * @mm: mm from which memcg should be extracted. It can be NULL. 913 * 914 * Obtain a reference on mm->memcg and returns it if successful. If mm 915 * is NULL, then the memcg is chosen as follows: 916 * 1) The active memcg, if set. 917 * 2) current->mm->memcg, if available 918 * 3) root memcg 919 * If mem_cgroup is disabled, NULL is returned. 920 */ 921 struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm) 922 { 923 struct mem_cgroup *memcg; 924 925 if (mem_cgroup_disabled()) 926 return NULL; 927 928 /* 929 * Page cache insertions can happen without an 930 * actual mm context, e.g. during disk probing 931 * on boot, loopback IO, acct() writes etc. 932 * 933 * No need to css_get on root memcg as the reference 934 * counting is disabled on the root level in the 935 * cgroup core. See CSS_NO_REF. 936 */ 937 if (unlikely(!mm)) { 938 memcg = active_memcg(); 939 if (unlikely(memcg)) { 940 /* remote memcg must hold a ref */ 941 css_get(&memcg->css); 942 return memcg; 943 } 944 mm = current->mm; 945 if (unlikely(!mm)) 946 return root_mem_cgroup; 947 } 948 949 rcu_read_lock(); 950 do { 951 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner)); 952 if (unlikely(!memcg)) 953 memcg = root_mem_cgroup; 954 } while (!css_tryget(&memcg->css)); 955 rcu_read_unlock(); 956 return memcg; 957 } 958 EXPORT_SYMBOL(get_mem_cgroup_from_mm); 959 960 static __always_inline bool memcg_kmem_bypass(void) 961 { 962 /* Allow remote memcg charging from any context. */ 963 if (unlikely(active_memcg())) 964 return false; 965 966 /* Memcg to charge can't be determined. */ 967 if (!in_task() || !current->mm || (current->flags & PF_KTHREAD)) 968 return true; 969 970 return false; 971 } 972 973 /** 974 * mem_cgroup_iter - iterate over memory cgroup hierarchy 975 * @root: hierarchy root 976 * @prev: previously returned memcg, NULL on first invocation 977 * @reclaim: cookie for shared reclaim walks, NULL for full walks 978 * 979 * Returns references to children of the hierarchy below @root, or 980 * @root itself, or %NULL after a full round-trip. 981 * 982 * Caller must pass the return value in @prev on subsequent 983 * invocations for reference counting, or use mem_cgroup_iter_break() 984 * to cancel a hierarchy walk before the round-trip is complete. 985 * 986 * Reclaimers can specify a node in @reclaim to divide up the memcgs 987 * in the hierarchy among all concurrent reclaimers operating on the 988 * same node. 989 */ 990 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root, 991 struct mem_cgroup *prev, 992 struct mem_cgroup_reclaim_cookie *reclaim) 993 { 994 struct mem_cgroup_reclaim_iter *iter; 995 struct cgroup_subsys_state *css = NULL; 996 struct mem_cgroup *memcg = NULL; 997 struct mem_cgroup *pos = NULL; 998 999 if (mem_cgroup_disabled()) 1000 return NULL; 1001 1002 if (!root) 1003 root = root_mem_cgroup; 1004 1005 if (prev && !reclaim) 1006 pos = prev; 1007 1008 rcu_read_lock(); 1009 1010 if (reclaim) { 1011 struct mem_cgroup_per_node *mz; 1012 1013 mz = root->nodeinfo[reclaim->pgdat->node_id]; 1014 iter = &mz->iter; 1015 1016 if (prev && reclaim->generation != iter->generation) 1017 goto out_unlock; 1018 1019 while (1) { 1020 pos = READ_ONCE(iter->position); 1021 if (!pos || css_tryget(&pos->css)) 1022 break; 1023 /* 1024 * css reference reached zero, so iter->position will 1025 * be cleared by ->css_released. However, we should not 1026 * rely on this happening soon, because ->css_released 1027 * is called from a work queue, and by busy-waiting we 1028 * might block it. So we clear iter->position right 1029 * away. 1030 */ 1031 (void)cmpxchg(&iter->position, pos, NULL); 1032 } 1033 } 1034 1035 if (pos) 1036 css = &pos->css; 1037 1038 for (;;) { 1039 css = css_next_descendant_pre(css, &root->css); 1040 if (!css) { 1041 /* 1042 * Reclaimers share the hierarchy walk, and a 1043 * new one might jump in right at the end of 1044 * the hierarchy - make sure they see at least 1045 * one group and restart from the beginning. 1046 */ 1047 if (!prev) 1048 continue; 1049 break; 1050 } 1051 1052 /* 1053 * Verify the css and acquire a reference. The root 1054 * is provided by the caller, so we know it's alive 1055 * and kicking, and don't take an extra reference. 1056 */ 1057 memcg = mem_cgroup_from_css(css); 1058 1059 if (css == &root->css) 1060 break; 1061 1062 if (css_tryget(css)) 1063 break; 1064 1065 memcg = NULL; 1066 } 1067 1068 if (reclaim) { 1069 /* 1070 * The position could have already been updated by a competing 1071 * thread, so check that the value hasn't changed since we read 1072 * it to avoid reclaiming from the same cgroup twice. 1073 */ 1074 (void)cmpxchg(&iter->position, pos, memcg); 1075 1076 if (pos) 1077 css_put(&pos->css); 1078 1079 if (!memcg) 1080 iter->generation++; 1081 else if (!prev) 1082 reclaim->generation = iter->generation; 1083 } 1084 1085 out_unlock: 1086 rcu_read_unlock(); 1087 if (prev && prev != root) 1088 css_put(&prev->css); 1089 1090 return memcg; 1091 } 1092 1093 /** 1094 * mem_cgroup_iter_break - abort a hierarchy walk prematurely 1095 * @root: hierarchy root 1096 * @prev: last visited hierarchy member as returned by mem_cgroup_iter() 1097 */ 1098 void mem_cgroup_iter_break(struct mem_cgroup *root, 1099 struct mem_cgroup *prev) 1100 { 1101 if (!root) 1102 root = root_mem_cgroup; 1103 if (prev && prev != root) 1104 css_put(&prev->css); 1105 } 1106 1107 static void __invalidate_reclaim_iterators(struct mem_cgroup *from, 1108 struct mem_cgroup *dead_memcg) 1109 { 1110 struct mem_cgroup_reclaim_iter *iter; 1111 struct mem_cgroup_per_node *mz; 1112 int nid; 1113 1114 for_each_node(nid) { 1115 mz = from->nodeinfo[nid]; 1116 iter = &mz->iter; 1117 cmpxchg(&iter->position, dead_memcg, NULL); 1118 } 1119 } 1120 1121 static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg) 1122 { 1123 struct mem_cgroup *memcg = dead_memcg; 1124 struct mem_cgroup *last; 1125 1126 do { 1127 __invalidate_reclaim_iterators(memcg, dead_memcg); 1128 last = memcg; 1129 } while ((memcg = parent_mem_cgroup(memcg))); 1130 1131 /* 1132 * When cgruop1 non-hierarchy mode is used, 1133 * parent_mem_cgroup() does not walk all the way up to the 1134 * cgroup root (root_mem_cgroup). So we have to handle 1135 * dead_memcg from cgroup root separately. 1136 */ 1137 if (last != root_mem_cgroup) 1138 __invalidate_reclaim_iterators(root_mem_cgroup, 1139 dead_memcg); 1140 } 1141 1142 /** 1143 * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy 1144 * @memcg: hierarchy root 1145 * @fn: function to call for each task 1146 * @arg: argument passed to @fn 1147 * 1148 * This function iterates over tasks attached to @memcg or to any of its 1149 * descendants and calls @fn for each task. If @fn returns a non-zero 1150 * value, the function breaks the iteration loop and returns the value. 1151 * Otherwise, it will iterate over all tasks and return 0. 1152 * 1153 * This function must not be called for the root memory cgroup. 1154 */ 1155 int mem_cgroup_scan_tasks(struct mem_cgroup *memcg, 1156 int (*fn)(struct task_struct *, void *), void *arg) 1157 { 1158 struct mem_cgroup *iter; 1159 int ret = 0; 1160 1161 BUG_ON(memcg == root_mem_cgroup); 1162 1163 for_each_mem_cgroup_tree(iter, memcg) { 1164 struct css_task_iter it; 1165 struct task_struct *task; 1166 1167 css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it); 1168 while (!ret && (task = css_task_iter_next(&it))) 1169 ret = fn(task, arg); 1170 css_task_iter_end(&it); 1171 if (ret) { 1172 mem_cgroup_iter_break(memcg, iter); 1173 break; 1174 } 1175 } 1176 return ret; 1177 } 1178 1179 #ifdef CONFIG_DEBUG_VM 1180 void lruvec_memcg_debug(struct lruvec *lruvec, struct folio *folio) 1181 { 1182 struct mem_cgroup *memcg; 1183 1184 if (mem_cgroup_disabled()) 1185 return; 1186 1187 memcg = folio_memcg(folio); 1188 1189 if (!memcg) 1190 VM_BUG_ON_FOLIO(lruvec_memcg(lruvec) != root_mem_cgroup, folio); 1191 else 1192 VM_BUG_ON_FOLIO(lruvec_memcg(lruvec) != memcg, folio); 1193 } 1194 #endif 1195 1196 /** 1197 * folio_lruvec_lock - Lock the lruvec for a folio. 1198 * @folio: Pointer to the folio. 1199 * 1200 * These functions are safe to use under any of the following conditions: 1201 * - folio locked 1202 * - folio_test_lru false 1203 * - folio_memcg_lock() 1204 * - folio frozen (refcount of 0) 1205 * 1206 * Return: The lruvec this folio is on with its lock held. 1207 */ 1208 struct lruvec *folio_lruvec_lock(struct folio *folio) 1209 { 1210 struct lruvec *lruvec = folio_lruvec(folio); 1211 1212 spin_lock(&lruvec->lru_lock); 1213 lruvec_memcg_debug(lruvec, folio); 1214 1215 return lruvec; 1216 } 1217 1218 /** 1219 * folio_lruvec_lock_irq - Lock the lruvec for a folio. 1220 * @folio: Pointer to the folio. 1221 * 1222 * These functions are safe to use under any of the following conditions: 1223 * - folio locked 1224 * - folio_test_lru false 1225 * - folio_memcg_lock() 1226 * - folio frozen (refcount of 0) 1227 * 1228 * Return: The lruvec this folio is on with its lock held and interrupts 1229 * disabled. 1230 */ 1231 struct lruvec *folio_lruvec_lock_irq(struct folio *folio) 1232 { 1233 struct lruvec *lruvec = folio_lruvec(folio); 1234 1235 spin_lock_irq(&lruvec->lru_lock); 1236 lruvec_memcg_debug(lruvec, folio); 1237 1238 return lruvec; 1239 } 1240 1241 /** 1242 * folio_lruvec_lock_irqsave - Lock the lruvec for a folio. 1243 * @folio: Pointer to the folio. 1244 * @flags: Pointer to irqsave flags. 1245 * 1246 * These functions are safe to use under any of the following conditions: 1247 * - folio locked 1248 * - folio_test_lru false 1249 * - folio_memcg_lock() 1250 * - folio frozen (refcount of 0) 1251 * 1252 * Return: The lruvec this folio is on with its lock held and interrupts 1253 * disabled. 1254 */ 1255 struct lruvec *folio_lruvec_lock_irqsave(struct folio *folio, 1256 unsigned long *flags) 1257 { 1258 struct lruvec *lruvec = folio_lruvec(folio); 1259 1260 spin_lock_irqsave(&lruvec->lru_lock, *flags); 1261 lruvec_memcg_debug(lruvec, folio); 1262 1263 return lruvec; 1264 } 1265 1266 /** 1267 * mem_cgroup_update_lru_size - account for adding or removing an lru page 1268 * @lruvec: mem_cgroup per zone lru vector 1269 * @lru: index of lru list the page is sitting on 1270 * @zid: zone id of the accounted pages 1271 * @nr_pages: positive when adding or negative when removing 1272 * 1273 * This function must be called under lru_lock, just before a page is added 1274 * to or just after a page is removed from an lru list (that ordering being 1275 * so as to allow it to check that lru_size 0 is consistent with list_empty). 1276 */ 1277 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru, 1278 int zid, int nr_pages) 1279 { 1280 struct mem_cgroup_per_node *mz; 1281 unsigned long *lru_size; 1282 long size; 1283 1284 if (mem_cgroup_disabled()) 1285 return; 1286 1287 mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec); 1288 lru_size = &mz->lru_zone_size[zid][lru]; 1289 1290 if (nr_pages < 0) 1291 *lru_size += nr_pages; 1292 1293 size = *lru_size; 1294 if (WARN_ONCE(size < 0, 1295 "%s(%p, %d, %d): lru_size %ld\n", 1296 __func__, lruvec, lru, nr_pages, size)) { 1297 VM_BUG_ON(1); 1298 *lru_size = 0; 1299 } 1300 1301 if (nr_pages > 0) 1302 *lru_size += nr_pages; 1303 } 1304 1305 /** 1306 * mem_cgroup_margin - calculate chargeable space of a memory cgroup 1307 * @memcg: the memory cgroup 1308 * 1309 * Returns the maximum amount of memory @mem can be charged with, in 1310 * pages. 1311 */ 1312 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg) 1313 { 1314 unsigned long margin = 0; 1315 unsigned long count; 1316 unsigned long limit; 1317 1318 count = page_counter_read(&memcg->memory); 1319 limit = READ_ONCE(memcg->memory.max); 1320 if (count < limit) 1321 margin = limit - count; 1322 1323 if (do_memsw_account()) { 1324 count = page_counter_read(&memcg->memsw); 1325 limit = READ_ONCE(memcg->memsw.max); 1326 if (count < limit) 1327 margin = min(margin, limit - count); 1328 else 1329 margin = 0; 1330 } 1331 1332 return margin; 1333 } 1334 1335 /* 1336 * A routine for checking "mem" is under move_account() or not. 1337 * 1338 * Checking a cgroup is mc.from or mc.to or under hierarchy of 1339 * moving cgroups. This is for waiting at high-memory pressure 1340 * caused by "move". 1341 */ 1342 static bool mem_cgroup_under_move(struct mem_cgroup *memcg) 1343 { 1344 struct mem_cgroup *from; 1345 struct mem_cgroup *to; 1346 bool ret = false; 1347 /* 1348 * Unlike task_move routines, we access mc.to, mc.from not under 1349 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead. 1350 */ 1351 spin_lock(&mc.lock); 1352 from = mc.from; 1353 to = mc.to; 1354 if (!from) 1355 goto unlock; 1356 1357 ret = mem_cgroup_is_descendant(from, memcg) || 1358 mem_cgroup_is_descendant(to, memcg); 1359 unlock: 1360 spin_unlock(&mc.lock); 1361 return ret; 1362 } 1363 1364 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg) 1365 { 1366 if (mc.moving_task && current != mc.moving_task) { 1367 if (mem_cgroup_under_move(memcg)) { 1368 DEFINE_WAIT(wait); 1369 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE); 1370 /* moving charge context might have finished. */ 1371 if (mc.moving_task) 1372 schedule(); 1373 finish_wait(&mc.waitq, &wait); 1374 return true; 1375 } 1376 } 1377 return false; 1378 } 1379 1380 struct memory_stat { 1381 const char *name; 1382 unsigned int idx; 1383 }; 1384 1385 static const struct memory_stat memory_stats[] = { 1386 { "anon", NR_ANON_MAPPED }, 1387 { "file", NR_FILE_PAGES }, 1388 { "kernel", MEMCG_KMEM }, 1389 { "kernel_stack", NR_KERNEL_STACK_KB }, 1390 { "pagetables", NR_PAGETABLE }, 1391 { "percpu", MEMCG_PERCPU_B }, 1392 { "sock", MEMCG_SOCK }, 1393 { "vmalloc", MEMCG_VMALLOC }, 1394 { "shmem", NR_SHMEM }, 1395 { "file_mapped", NR_FILE_MAPPED }, 1396 { "file_dirty", NR_FILE_DIRTY }, 1397 { "file_writeback", NR_WRITEBACK }, 1398 #ifdef CONFIG_SWAP 1399 { "swapcached", NR_SWAPCACHE }, 1400 #endif 1401 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 1402 { "anon_thp", NR_ANON_THPS }, 1403 { "file_thp", NR_FILE_THPS }, 1404 { "shmem_thp", NR_SHMEM_THPS }, 1405 #endif 1406 { "inactive_anon", NR_INACTIVE_ANON }, 1407 { "active_anon", NR_ACTIVE_ANON }, 1408 { "inactive_file", NR_INACTIVE_FILE }, 1409 { "active_file", NR_ACTIVE_FILE }, 1410 { "unevictable", NR_UNEVICTABLE }, 1411 { "slab_reclaimable", NR_SLAB_RECLAIMABLE_B }, 1412 { "slab_unreclaimable", NR_SLAB_UNRECLAIMABLE_B }, 1413 1414 /* The memory events */ 1415 { "workingset_refault_anon", WORKINGSET_REFAULT_ANON }, 1416 { "workingset_refault_file", WORKINGSET_REFAULT_FILE }, 1417 { "workingset_activate_anon", WORKINGSET_ACTIVATE_ANON }, 1418 { "workingset_activate_file", WORKINGSET_ACTIVATE_FILE }, 1419 { "workingset_restore_anon", WORKINGSET_RESTORE_ANON }, 1420 { "workingset_restore_file", WORKINGSET_RESTORE_FILE }, 1421 { "workingset_nodereclaim", WORKINGSET_NODERECLAIM }, 1422 }; 1423 1424 /* Translate stat items to the correct unit for memory.stat output */ 1425 static int memcg_page_state_unit(int item) 1426 { 1427 switch (item) { 1428 case MEMCG_PERCPU_B: 1429 case NR_SLAB_RECLAIMABLE_B: 1430 case NR_SLAB_UNRECLAIMABLE_B: 1431 case WORKINGSET_REFAULT_ANON: 1432 case WORKINGSET_REFAULT_FILE: 1433 case WORKINGSET_ACTIVATE_ANON: 1434 case WORKINGSET_ACTIVATE_FILE: 1435 case WORKINGSET_RESTORE_ANON: 1436 case WORKINGSET_RESTORE_FILE: 1437 case WORKINGSET_NODERECLAIM: 1438 return 1; 1439 case NR_KERNEL_STACK_KB: 1440 return SZ_1K; 1441 default: 1442 return PAGE_SIZE; 1443 } 1444 } 1445 1446 static inline unsigned long memcg_page_state_output(struct mem_cgroup *memcg, 1447 int item) 1448 { 1449 return memcg_page_state(memcg, item) * memcg_page_state_unit(item); 1450 } 1451 1452 static char *memory_stat_format(struct mem_cgroup *memcg) 1453 { 1454 struct seq_buf s; 1455 int i; 1456 1457 seq_buf_init(&s, kmalloc(PAGE_SIZE, GFP_KERNEL), PAGE_SIZE); 1458 if (!s.buffer) 1459 return NULL; 1460 1461 /* 1462 * Provide statistics on the state of the memory subsystem as 1463 * well as cumulative event counters that show past behavior. 1464 * 1465 * This list is ordered following a combination of these gradients: 1466 * 1) generic big picture -> specifics and details 1467 * 2) reflecting userspace activity -> reflecting kernel heuristics 1468 * 1469 * Current memory state: 1470 */ 1471 mem_cgroup_flush_stats(); 1472 1473 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) { 1474 u64 size; 1475 1476 size = memcg_page_state_output(memcg, memory_stats[i].idx); 1477 seq_buf_printf(&s, "%s %llu\n", memory_stats[i].name, size); 1478 1479 if (unlikely(memory_stats[i].idx == NR_SLAB_UNRECLAIMABLE_B)) { 1480 size += memcg_page_state_output(memcg, 1481 NR_SLAB_RECLAIMABLE_B); 1482 seq_buf_printf(&s, "slab %llu\n", size); 1483 } 1484 } 1485 1486 /* Accumulated memory events */ 1487 1488 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGFAULT), 1489 memcg_events(memcg, PGFAULT)); 1490 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGMAJFAULT), 1491 memcg_events(memcg, PGMAJFAULT)); 1492 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGREFILL), 1493 memcg_events(memcg, PGREFILL)); 1494 seq_buf_printf(&s, "pgscan %lu\n", 1495 memcg_events(memcg, PGSCAN_KSWAPD) + 1496 memcg_events(memcg, PGSCAN_DIRECT)); 1497 seq_buf_printf(&s, "pgsteal %lu\n", 1498 memcg_events(memcg, PGSTEAL_KSWAPD) + 1499 memcg_events(memcg, PGSTEAL_DIRECT)); 1500 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGACTIVATE), 1501 memcg_events(memcg, PGACTIVATE)); 1502 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGDEACTIVATE), 1503 memcg_events(memcg, PGDEACTIVATE)); 1504 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGLAZYFREE), 1505 memcg_events(memcg, PGLAZYFREE)); 1506 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGLAZYFREED), 1507 memcg_events(memcg, PGLAZYFREED)); 1508 1509 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 1510 seq_buf_printf(&s, "%s %lu\n", vm_event_name(THP_FAULT_ALLOC), 1511 memcg_events(memcg, THP_FAULT_ALLOC)); 1512 seq_buf_printf(&s, "%s %lu\n", vm_event_name(THP_COLLAPSE_ALLOC), 1513 memcg_events(memcg, THP_COLLAPSE_ALLOC)); 1514 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */ 1515 1516 /* The above should easily fit into one page */ 1517 WARN_ON_ONCE(seq_buf_has_overflowed(&s)); 1518 1519 return s.buffer; 1520 } 1521 1522 #define K(x) ((x) << (PAGE_SHIFT-10)) 1523 /** 1524 * mem_cgroup_print_oom_context: Print OOM information relevant to 1525 * memory controller. 1526 * @memcg: The memory cgroup that went over limit 1527 * @p: Task that is going to be killed 1528 * 1529 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is 1530 * enabled 1531 */ 1532 void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p) 1533 { 1534 rcu_read_lock(); 1535 1536 if (memcg) { 1537 pr_cont(",oom_memcg="); 1538 pr_cont_cgroup_path(memcg->css.cgroup); 1539 } else 1540 pr_cont(",global_oom"); 1541 if (p) { 1542 pr_cont(",task_memcg="); 1543 pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id)); 1544 } 1545 rcu_read_unlock(); 1546 } 1547 1548 /** 1549 * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to 1550 * memory controller. 1551 * @memcg: The memory cgroup that went over limit 1552 */ 1553 void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg) 1554 { 1555 char *buf; 1556 1557 pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n", 1558 K((u64)page_counter_read(&memcg->memory)), 1559 K((u64)READ_ONCE(memcg->memory.max)), memcg->memory.failcnt); 1560 if (cgroup_subsys_on_dfl(memory_cgrp_subsys)) 1561 pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n", 1562 K((u64)page_counter_read(&memcg->swap)), 1563 K((u64)READ_ONCE(memcg->swap.max)), memcg->swap.failcnt); 1564 else { 1565 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n", 1566 K((u64)page_counter_read(&memcg->memsw)), 1567 K((u64)memcg->memsw.max), memcg->memsw.failcnt); 1568 pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n", 1569 K((u64)page_counter_read(&memcg->kmem)), 1570 K((u64)memcg->kmem.max), memcg->kmem.failcnt); 1571 } 1572 1573 pr_info("Memory cgroup stats for "); 1574 pr_cont_cgroup_path(memcg->css.cgroup); 1575 pr_cont(":"); 1576 buf = memory_stat_format(memcg); 1577 if (!buf) 1578 return; 1579 pr_info("%s", buf); 1580 kfree(buf); 1581 } 1582 1583 /* 1584 * Return the memory (and swap, if configured) limit for a memcg. 1585 */ 1586 unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg) 1587 { 1588 unsigned long max = READ_ONCE(memcg->memory.max); 1589 1590 if (cgroup_subsys_on_dfl(memory_cgrp_subsys)) { 1591 if (mem_cgroup_swappiness(memcg)) 1592 max += min(READ_ONCE(memcg->swap.max), 1593 (unsigned long)total_swap_pages); 1594 } else { /* v1 */ 1595 if (mem_cgroup_swappiness(memcg)) { 1596 /* Calculate swap excess capacity from memsw limit */ 1597 unsigned long swap = READ_ONCE(memcg->memsw.max) - max; 1598 1599 max += min(swap, (unsigned long)total_swap_pages); 1600 } 1601 } 1602 return max; 1603 } 1604 1605 unsigned long mem_cgroup_size(struct mem_cgroup *memcg) 1606 { 1607 return page_counter_read(&memcg->memory); 1608 } 1609 1610 static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask, 1611 int order) 1612 { 1613 struct oom_control oc = { 1614 .zonelist = NULL, 1615 .nodemask = NULL, 1616 .memcg = memcg, 1617 .gfp_mask = gfp_mask, 1618 .order = order, 1619 }; 1620 bool ret = true; 1621 1622 if (mutex_lock_killable(&oom_lock)) 1623 return true; 1624 1625 if (mem_cgroup_margin(memcg) >= (1 << order)) 1626 goto unlock; 1627 1628 /* 1629 * A few threads which were not waiting at mutex_lock_killable() can 1630 * fail to bail out. Therefore, check again after holding oom_lock. 1631 */ 1632 ret = task_is_dying() || out_of_memory(&oc); 1633 1634 unlock: 1635 mutex_unlock(&oom_lock); 1636 return ret; 1637 } 1638 1639 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg, 1640 pg_data_t *pgdat, 1641 gfp_t gfp_mask, 1642 unsigned long *total_scanned) 1643 { 1644 struct mem_cgroup *victim = NULL; 1645 int total = 0; 1646 int loop = 0; 1647 unsigned long excess; 1648 unsigned long nr_scanned; 1649 struct mem_cgroup_reclaim_cookie reclaim = { 1650 .pgdat = pgdat, 1651 }; 1652 1653 excess = soft_limit_excess(root_memcg); 1654 1655 while (1) { 1656 victim = mem_cgroup_iter(root_memcg, victim, &reclaim); 1657 if (!victim) { 1658 loop++; 1659 if (loop >= 2) { 1660 /* 1661 * If we have not been able to reclaim 1662 * anything, it might because there are 1663 * no reclaimable pages under this hierarchy 1664 */ 1665 if (!total) 1666 break; 1667 /* 1668 * We want to do more targeted reclaim. 1669 * excess >> 2 is not to excessive so as to 1670 * reclaim too much, nor too less that we keep 1671 * coming back to reclaim from this cgroup 1672 */ 1673 if (total >= (excess >> 2) || 1674 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS)) 1675 break; 1676 } 1677 continue; 1678 } 1679 total += mem_cgroup_shrink_node(victim, gfp_mask, false, 1680 pgdat, &nr_scanned); 1681 *total_scanned += nr_scanned; 1682 if (!soft_limit_excess(root_memcg)) 1683 break; 1684 } 1685 mem_cgroup_iter_break(root_memcg, victim); 1686 return total; 1687 } 1688 1689 #ifdef CONFIG_LOCKDEP 1690 static struct lockdep_map memcg_oom_lock_dep_map = { 1691 .name = "memcg_oom_lock", 1692 }; 1693 #endif 1694 1695 static DEFINE_SPINLOCK(memcg_oom_lock); 1696 1697 /* 1698 * Check OOM-Killer is already running under our hierarchy. 1699 * If someone is running, return false. 1700 */ 1701 static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg) 1702 { 1703 struct mem_cgroup *iter, *failed = NULL; 1704 1705 spin_lock(&memcg_oom_lock); 1706 1707 for_each_mem_cgroup_tree(iter, memcg) { 1708 if (iter->oom_lock) { 1709 /* 1710 * this subtree of our hierarchy is already locked 1711 * so we cannot give a lock. 1712 */ 1713 failed = iter; 1714 mem_cgroup_iter_break(memcg, iter); 1715 break; 1716 } else 1717 iter->oom_lock = true; 1718 } 1719 1720 if (failed) { 1721 /* 1722 * OK, we failed to lock the whole subtree so we have 1723 * to clean up what we set up to the failing subtree 1724 */ 1725 for_each_mem_cgroup_tree(iter, memcg) { 1726 if (iter == failed) { 1727 mem_cgroup_iter_break(memcg, iter); 1728 break; 1729 } 1730 iter->oom_lock = false; 1731 } 1732 } else 1733 mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_); 1734 1735 spin_unlock(&memcg_oom_lock); 1736 1737 return !failed; 1738 } 1739 1740 static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg) 1741 { 1742 struct mem_cgroup *iter; 1743 1744 spin_lock(&memcg_oom_lock); 1745 mutex_release(&memcg_oom_lock_dep_map, _RET_IP_); 1746 for_each_mem_cgroup_tree(iter, memcg) 1747 iter->oom_lock = false; 1748 spin_unlock(&memcg_oom_lock); 1749 } 1750 1751 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg) 1752 { 1753 struct mem_cgroup *iter; 1754 1755 spin_lock(&memcg_oom_lock); 1756 for_each_mem_cgroup_tree(iter, memcg) 1757 iter->under_oom++; 1758 spin_unlock(&memcg_oom_lock); 1759 } 1760 1761 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg) 1762 { 1763 struct mem_cgroup *iter; 1764 1765 /* 1766 * Be careful about under_oom underflows because a child memcg 1767 * could have been added after mem_cgroup_mark_under_oom. 1768 */ 1769 spin_lock(&memcg_oom_lock); 1770 for_each_mem_cgroup_tree(iter, memcg) 1771 if (iter->under_oom > 0) 1772 iter->under_oom--; 1773 spin_unlock(&memcg_oom_lock); 1774 } 1775 1776 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq); 1777 1778 struct oom_wait_info { 1779 struct mem_cgroup *memcg; 1780 wait_queue_entry_t wait; 1781 }; 1782 1783 static int memcg_oom_wake_function(wait_queue_entry_t *wait, 1784 unsigned mode, int sync, void *arg) 1785 { 1786 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg; 1787 struct mem_cgroup *oom_wait_memcg; 1788 struct oom_wait_info *oom_wait_info; 1789 1790 oom_wait_info = container_of(wait, struct oom_wait_info, wait); 1791 oom_wait_memcg = oom_wait_info->memcg; 1792 1793 if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) && 1794 !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg)) 1795 return 0; 1796 return autoremove_wake_function(wait, mode, sync, arg); 1797 } 1798 1799 static void memcg_oom_recover(struct mem_cgroup *memcg) 1800 { 1801 /* 1802 * For the following lockless ->under_oom test, the only required 1803 * guarantee is that it must see the state asserted by an OOM when 1804 * this function is called as a result of userland actions 1805 * triggered by the notification of the OOM. This is trivially 1806 * achieved by invoking mem_cgroup_mark_under_oom() before 1807 * triggering notification. 1808 */ 1809 if (memcg && memcg->under_oom) 1810 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg); 1811 } 1812 1813 /* 1814 * Returns true if successfully killed one or more processes. Though in some 1815 * corner cases it can return true even without killing any process. 1816 */ 1817 static bool mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order) 1818 { 1819 bool locked, ret; 1820 1821 if (order > PAGE_ALLOC_COSTLY_ORDER) 1822 return false; 1823 1824 memcg_memory_event(memcg, MEMCG_OOM); 1825 1826 /* 1827 * We are in the middle of the charge context here, so we 1828 * don't want to block when potentially sitting on a callstack 1829 * that holds all kinds of filesystem and mm locks. 1830 * 1831 * cgroup1 allows disabling the OOM killer and waiting for outside 1832 * handling until the charge can succeed; remember the context and put 1833 * the task to sleep at the end of the page fault when all locks are 1834 * released. 1835 * 1836 * On the other hand, in-kernel OOM killer allows for an async victim 1837 * memory reclaim (oom_reaper) and that means that we are not solely 1838 * relying on the oom victim to make a forward progress and we can 1839 * invoke the oom killer here. 1840 * 1841 * Please note that mem_cgroup_out_of_memory might fail to find a 1842 * victim and then we have to bail out from the charge path. 1843 */ 1844 if (memcg->oom_kill_disable) { 1845 if (current->in_user_fault) { 1846 css_get(&memcg->css); 1847 current->memcg_in_oom = memcg; 1848 current->memcg_oom_gfp_mask = mask; 1849 current->memcg_oom_order = order; 1850 } 1851 return false; 1852 } 1853 1854 mem_cgroup_mark_under_oom(memcg); 1855 1856 locked = mem_cgroup_oom_trylock(memcg); 1857 1858 if (locked) 1859 mem_cgroup_oom_notify(memcg); 1860 1861 mem_cgroup_unmark_under_oom(memcg); 1862 ret = mem_cgroup_out_of_memory(memcg, mask, order); 1863 1864 if (locked) 1865 mem_cgroup_oom_unlock(memcg); 1866 1867 return ret; 1868 } 1869 1870 /** 1871 * mem_cgroup_oom_synchronize - complete memcg OOM handling 1872 * @handle: actually kill/wait or just clean up the OOM state 1873 * 1874 * This has to be called at the end of a page fault if the memcg OOM 1875 * handler was enabled. 1876 * 1877 * Memcg supports userspace OOM handling where failed allocations must 1878 * sleep on a waitqueue until the userspace task resolves the 1879 * situation. Sleeping directly in the charge context with all kinds 1880 * of locks held is not a good idea, instead we remember an OOM state 1881 * in the task and mem_cgroup_oom_synchronize() has to be called at 1882 * the end of the page fault to complete the OOM handling. 1883 * 1884 * Returns %true if an ongoing memcg OOM situation was detected and 1885 * completed, %false otherwise. 1886 */ 1887 bool mem_cgroup_oom_synchronize(bool handle) 1888 { 1889 struct mem_cgroup *memcg = current->memcg_in_oom; 1890 struct oom_wait_info owait; 1891 bool locked; 1892 1893 /* OOM is global, do not handle */ 1894 if (!memcg) 1895 return false; 1896 1897 if (!handle) 1898 goto cleanup; 1899 1900 owait.memcg = memcg; 1901 owait.wait.flags = 0; 1902 owait.wait.func = memcg_oom_wake_function; 1903 owait.wait.private = current; 1904 INIT_LIST_HEAD(&owait.wait.entry); 1905 1906 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE); 1907 mem_cgroup_mark_under_oom(memcg); 1908 1909 locked = mem_cgroup_oom_trylock(memcg); 1910 1911 if (locked) 1912 mem_cgroup_oom_notify(memcg); 1913 1914 if (locked && !memcg->oom_kill_disable) { 1915 mem_cgroup_unmark_under_oom(memcg); 1916 finish_wait(&memcg_oom_waitq, &owait.wait); 1917 mem_cgroup_out_of_memory(memcg, current->memcg_oom_gfp_mask, 1918 current->memcg_oom_order); 1919 } else { 1920 schedule(); 1921 mem_cgroup_unmark_under_oom(memcg); 1922 finish_wait(&memcg_oom_waitq, &owait.wait); 1923 } 1924 1925 if (locked) { 1926 mem_cgroup_oom_unlock(memcg); 1927 /* 1928 * There is no guarantee that an OOM-lock contender 1929 * sees the wakeups triggered by the OOM kill 1930 * uncharges. Wake any sleepers explicitly. 1931 */ 1932 memcg_oom_recover(memcg); 1933 } 1934 cleanup: 1935 current->memcg_in_oom = NULL; 1936 css_put(&memcg->css); 1937 return true; 1938 } 1939 1940 /** 1941 * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM 1942 * @victim: task to be killed by the OOM killer 1943 * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM 1944 * 1945 * Returns a pointer to a memory cgroup, which has to be cleaned up 1946 * by killing all belonging OOM-killable tasks. 1947 * 1948 * Caller has to call mem_cgroup_put() on the returned non-NULL memcg. 1949 */ 1950 struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim, 1951 struct mem_cgroup *oom_domain) 1952 { 1953 struct mem_cgroup *oom_group = NULL; 1954 struct mem_cgroup *memcg; 1955 1956 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) 1957 return NULL; 1958 1959 if (!oom_domain) 1960 oom_domain = root_mem_cgroup; 1961 1962 rcu_read_lock(); 1963 1964 memcg = mem_cgroup_from_task(victim); 1965 if (memcg == root_mem_cgroup) 1966 goto out; 1967 1968 /* 1969 * If the victim task has been asynchronously moved to a different 1970 * memory cgroup, we might end up killing tasks outside oom_domain. 1971 * In this case it's better to ignore memory.group.oom. 1972 */ 1973 if (unlikely(!mem_cgroup_is_descendant(memcg, oom_domain))) 1974 goto out; 1975 1976 /* 1977 * Traverse the memory cgroup hierarchy from the victim task's 1978 * cgroup up to the OOMing cgroup (or root) to find the 1979 * highest-level memory cgroup with oom.group set. 1980 */ 1981 for (; memcg; memcg = parent_mem_cgroup(memcg)) { 1982 if (memcg->oom_group) 1983 oom_group = memcg; 1984 1985 if (memcg == oom_domain) 1986 break; 1987 } 1988 1989 if (oom_group) 1990 css_get(&oom_group->css); 1991 out: 1992 rcu_read_unlock(); 1993 1994 return oom_group; 1995 } 1996 1997 void mem_cgroup_print_oom_group(struct mem_cgroup *memcg) 1998 { 1999 pr_info("Tasks in "); 2000 pr_cont_cgroup_path(memcg->css.cgroup); 2001 pr_cont(" are going to be killed due to memory.oom.group set\n"); 2002 } 2003 2004 /** 2005 * folio_memcg_lock - Bind a folio to its memcg. 2006 * @folio: The folio. 2007 * 2008 * This function prevents unlocked LRU folios from being moved to 2009 * another cgroup. 2010 * 2011 * It ensures lifetime of the bound memcg. The caller is responsible 2012 * for the lifetime of the folio. 2013 */ 2014 void folio_memcg_lock(struct folio *folio) 2015 { 2016 struct mem_cgroup *memcg; 2017 unsigned long flags; 2018 2019 /* 2020 * The RCU lock is held throughout the transaction. The fast 2021 * path can get away without acquiring the memcg->move_lock 2022 * because page moving starts with an RCU grace period. 2023 */ 2024 rcu_read_lock(); 2025 2026 if (mem_cgroup_disabled()) 2027 return; 2028 again: 2029 memcg = folio_memcg(folio); 2030 if (unlikely(!memcg)) 2031 return; 2032 2033 #ifdef CONFIG_PROVE_LOCKING 2034 local_irq_save(flags); 2035 might_lock(&memcg->move_lock); 2036 local_irq_restore(flags); 2037 #endif 2038 2039 if (atomic_read(&memcg->moving_account) <= 0) 2040 return; 2041 2042 spin_lock_irqsave(&memcg->move_lock, flags); 2043 if (memcg != folio_memcg(folio)) { 2044 spin_unlock_irqrestore(&memcg->move_lock, flags); 2045 goto again; 2046 } 2047 2048 /* 2049 * When charge migration first begins, we can have multiple 2050 * critical sections holding the fast-path RCU lock and one 2051 * holding the slowpath move_lock. Track the task who has the 2052 * move_lock for unlock_page_memcg(). 2053 */ 2054 memcg->move_lock_task = current; 2055 memcg->move_lock_flags = flags; 2056 } 2057 2058 void lock_page_memcg(struct page *page) 2059 { 2060 folio_memcg_lock(page_folio(page)); 2061 } 2062 2063 static void __folio_memcg_unlock(struct mem_cgroup *memcg) 2064 { 2065 if (memcg && memcg->move_lock_task == current) { 2066 unsigned long flags = memcg->move_lock_flags; 2067 2068 memcg->move_lock_task = NULL; 2069 memcg->move_lock_flags = 0; 2070 2071 spin_unlock_irqrestore(&memcg->move_lock, flags); 2072 } 2073 2074 rcu_read_unlock(); 2075 } 2076 2077 /** 2078 * folio_memcg_unlock - Release the binding between a folio and its memcg. 2079 * @folio: The folio. 2080 * 2081 * This releases the binding created by folio_memcg_lock(). This does 2082 * not change the accounting of this folio to its memcg, but it does 2083 * permit others to change it. 2084 */ 2085 void folio_memcg_unlock(struct folio *folio) 2086 { 2087 __folio_memcg_unlock(folio_memcg(folio)); 2088 } 2089 2090 void unlock_page_memcg(struct page *page) 2091 { 2092 folio_memcg_unlock(page_folio(page)); 2093 } 2094 2095 struct memcg_stock_pcp { 2096 local_lock_t stock_lock; 2097 struct mem_cgroup *cached; /* this never be root cgroup */ 2098 unsigned int nr_pages; 2099 2100 #ifdef CONFIG_MEMCG_KMEM 2101 struct obj_cgroup *cached_objcg; 2102 struct pglist_data *cached_pgdat; 2103 unsigned int nr_bytes; 2104 int nr_slab_reclaimable_b; 2105 int nr_slab_unreclaimable_b; 2106 #endif 2107 2108 struct work_struct work; 2109 unsigned long flags; 2110 #define FLUSHING_CACHED_CHARGE 0 2111 }; 2112 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock) = { 2113 .stock_lock = INIT_LOCAL_LOCK(stock_lock), 2114 }; 2115 static DEFINE_MUTEX(percpu_charge_mutex); 2116 2117 #ifdef CONFIG_MEMCG_KMEM 2118 static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock); 2119 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock, 2120 struct mem_cgroup *root_memcg); 2121 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages); 2122 2123 #else 2124 static inline struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock) 2125 { 2126 return NULL; 2127 } 2128 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock, 2129 struct mem_cgroup *root_memcg) 2130 { 2131 return false; 2132 } 2133 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages) 2134 { 2135 } 2136 #endif 2137 2138 /** 2139 * consume_stock: Try to consume stocked charge on this cpu. 2140 * @memcg: memcg to consume from. 2141 * @nr_pages: how many pages to charge. 2142 * 2143 * The charges will only happen if @memcg matches the current cpu's memcg 2144 * stock, and at least @nr_pages are available in that stock. Failure to 2145 * service an allocation will refill the stock. 2146 * 2147 * returns true if successful, false otherwise. 2148 */ 2149 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages) 2150 { 2151 struct memcg_stock_pcp *stock; 2152 unsigned long flags; 2153 bool ret = false; 2154 2155 if (nr_pages > MEMCG_CHARGE_BATCH) 2156 return ret; 2157 2158 local_lock_irqsave(&memcg_stock.stock_lock, flags); 2159 2160 stock = this_cpu_ptr(&memcg_stock); 2161 if (memcg == stock->cached && stock->nr_pages >= nr_pages) { 2162 stock->nr_pages -= nr_pages; 2163 ret = true; 2164 } 2165 2166 local_unlock_irqrestore(&memcg_stock.stock_lock, flags); 2167 2168 return ret; 2169 } 2170 2171 /* 2172 * Returns stocks cached in percpu and reset cached information. 2173 */ 2174 static void drain_stock(struct memcg_stock_pcp *stock) 2175 { 2176 struct mem_cgroup *old = stock->cached; 2177 2178 if (!old) 2179 return; 2180 2181 if (stock->nr_pages) { 2182 page_counter_uncharge(&old->memory, stock->nr_pages); 2183 if (do_memsw_account()) 2184 page_counter_uncharge(&old->memsw, stock->nr_pages); 2185 stock->nr_pages = 0; 2186 } 2187 2188 css_put(&old->css); 2189 stock->cached = NULL; 2190 } 2191 2192 static void drain_local_stock(struct work_struct *dummy) 2193 { 2194 struct memcg_stock_pcp *stock; 2195 struct obj_cgroup *old = NULL; 2196 unsigned long flags; 2197 2198 /* 2199 * The only protection from cpu hotplug (memcg_hotplug_cpu_dead) vs. 2200 * drain_stock races is that we always operate on local CPU stock 2201 * here with IRQ disabled 2202 */ 2203 local_lock_irqsave(&memcg_stock.stock_lock, flags); 2204 2205 stock = this_cpu_ptr(&memcg_stock); 2206 old = drain_obj_stock(stock); 2207 drain_stock(stock); 2208 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags); 2209 2210 local_unlock_irqrestore(&memcg_stock.stock_lock, flags); 2211 if (old) 2212 obj_cgroup_put(old); 2213 } 2214 2215 /* 2216 * Cache charges(val) to local per_cpu area. 2217 * This will be consumed by consume_stock() function, later. 2218 */ 2219 static void __refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages) 2220 { 2221 struct memcg_stock_pcp *stock; 2222 2223 stock = this_cpu_ptr(&memcg_stock); 2224 if (stock->cached != memcg) { /* reset if necessary */ 2225 drain_stock(stock); 2226 css_get(&memcg->css); 2227 stock->cached = memcg; 2228 } 2229 stock->nr_pages += nr_pages; 2230 2231 if (stock->nr_pages > MEMCG_CHARGE_BATCH) 2232 drain_stock(stock); 2233 } 2234 2235 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages) 2236 { 2237 unsigned long flags; 2238 2239 local_lock_irqsave(&memcg_stock.stock_lock, flags); 2240 __refill_stock(memcg, nr_pages); 2241 local_unlock_irqrestore(&memcg_stock.stock_lock, flags); 2242 } 2243 2244 /* 2245 * Drains all per-CPU charge caches for given root_memcg resp. subtree 2246 * of the hierarchy under it. 2247 */ 2248 static void drain_all_stock(struct mem_cgroup *root_memcg) 2249 { 2250 int cpu, curcpu; 2251 2252 /* If someone's already draining, avoid adding running more workers. */ 2253 if (!mutex_trylock(&percpu_charge_mutex)) 2254 return; 2255 /* 2256 * Notify other cpus that system-wide "drain" is running 2257 * We do not care about races with the cpu hotplug because cpu down 2258 * as well as workers from this path always operate on the local 2259 * per-cpu data. CPU up doesn't touch memcg_stock at all. 2260 */ 2261 migrate_disable(); 2262 curcpu = smp_processor_id(); 2263 for_each_online_cpu(cpu) { 2264 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu); 2265 struct mem_cgroup *memcg; 2266 bool flush = false; 2267 2268 rcu_read_lock(); 2269 memcg = stock->cached; 2270 if (memcg && stock->nr_pages && 2271 mem_cgroup_is_descendant(memcg, root_memcg)) 2272 flush = true; 2273 else if (obj_stock_flush_required(stock, root_memcg)) 2274 flush = true; 2275 rcu_read_unlock(); 2276 2277 if (flush && 2278 !test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) { 2279 if (cpu == curcpu) 2280 drain_local_stock(&stock->work); 2281 else 2282 schedule_work_on(cpu, &stock->work); 2283 } 2284 } 2285 migrate_enable(); 2286 mutex_unlock(&percpu_charge_mutex); 2287 } 2288 2289 static int memcg_hotplug_cpu_dead(unsigned int cpu) 2290 { 2291 struct memcg_stock_pcp *stock; 2292 2293 stock = &per_cpu(memcg_stock, cpu); 2294 drain_stock(stock); 2295 2296 return 0; 2297 } 2298 2299 static unsigned long reclaim_high(struct mem_cgroup *memcg, 2300 unsigned int nr_pages, 2301 gfp_t gfp_mask) 2302 { 2303 unsigned long nr_reclaimed = 0; 2304 2305 do { 2306 unsigned long pflags; 2307 2308 if (page_counter_read(&memcg->memory) <= 2309 READ_ONCE(memcg->memory.high)) 2310 continue; 2311 2312 memcg_memory_event(memcg, MEMCG_HIGH); 2313 2314 psi_memstall_enter(&pflags); 2315 nr_reclaimed += try_to_free_mem_cgroup_pages(memcg, nr_pages, 2316 gfp_mask, true); 2317 psi_memstall_leave(&pflags); 2318 } while ((memcg = parent_mem_cgroup(memcg)) && 2319 !mem_cgroup_is_root(memcg)); 2320 2321 return nr_reclaimed; 2322 } 2323 2324 static void high_work_func(struct work_struct *work) 2325 { 2326 struct mem_cgroup *memcg; 2327 2328 memcg = container_of(work, struct mem_cgroup, high_work); 2329 reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL); 2330 } 2331 2332 /* 2333 * Clamp the maximum sleep time per allocation batch to 2 seconds. This is 2334 * enough to still cause a significant slowdown in most cases, while still 2335 * allowing diagnostics and tracing to proceed without becoming stuck. 2336 */ 2337 #define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ) 2338 2339 /* 2340 * When calculating the delay, we use these either side of the exponentiation to 2341 * maintain precision and scale to a reasonable number of jiffies (see the table 2342 * below. 2343 * 2344 * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the 2345 * overage ratio to a delay. 2346 * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down the 2347 * proposed penalty in order to reduce to a reasonable number of jiffies, and 2348 * to produce a reasonable delay curve. 2349 * 2350 * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a 2351 * reasonable delay curve compared to precision-adjusted overage, not 2352 * penalising heavily at first, but still making sure that growth beyond the 2353 * limit penalises misbehaviour cgroups by slowing them down exponentially. For 2354 * example, with a high of 100 megabytes: 2355 * 2356 * +-------+------------------------+ 2357 * | usage | time to allocate in ms | 2358 * +-------+------------------------+ 2359 * | 100M | 0 | 2360 * | 101M | 6 | 2361 * | 102M | 25 | 2362 * | 103M | 57 | 2363 * | 104M | 102 | 2364 * | 105M | 159 | 2365 * | 106M | 230 | 2366 * | 107M | 313 | 2367 * | 108M | 409 | 2368 * | 109M | 518 | 2369 * | 110M | 639 | 2370 * | 111M | 774 | 2371 * | 112M | 921 | 2372 * | 113M | 1081 | 2373 * | 114M | 1254 | 2374 * | 115M | 1439 | 2375 * | 116M | 1638 | 2376 * | 117M | 1849 | 2377 * | 118M | 2000 | 2378 * | 119M | 2000 | 2379 * | 120M | 2000 | 2380 * +-------+------------------------+ 2381 */ 2382 #define MEMCG_DELAY_PRECISION_SHIFT 20 2383 #define MEMCG_DELAY_SCALING_SHIFT 14 2384 2385 static u64 calculate_overage(unsigned long usage, unsigned long high) 2386 { 2387 u64 overage; 2388 2389 if (usage <= high) 2390 return 0; 2391 2392 /* 2393 * Prevent division by 0 in overage calculation by acting as if 2394 * it was a threshold of 1 page 2395 */ 2396 high = max(high, 1UL); 2397 2398 overage = usage - high; 2399 overage <<= MEMCG_DELAY_PRECISION_SHIFT; 2400 return div64_u64(overage, high); 2401 } 2402 2403 static u64 mem_find_max_overage(struct mem_cgroup *memcg) 2404 { 2405 u64 overage, max_overage = 0; 2406 2407 do { 2408 overage = calculate_overage(page_counter_read(&memcg->memory), 2409 READ_ONCE(memcg->memory.high)); 2410 max_overage = max(overage, max_overage); 2411 } while ((memcg = parent_mem_cgroup(memcg)) && 2412 !mem_cgroup_is_root(memcg)); 2413 2414 return max_overage; 2415 } 2416 2417 static u64 swap_find_max_overage(struct mem_cgroup *memcg) 2418 { 2419 u64 overage, max_overage = 0; 2420 2421 do { 2422 overage = calculate_overage(page_counter_read(&memcg->swap), 2423 READ_ONCE(memcg->swap.high)); 2424 if (overage) 2425 memcg_memory_event(memcg, MEMCG_SWAP_HIGH); 2426 max_overage = max(overage, max_overage); 2427 } while ((memcg = parent_mem_cgroup(memcg)) && 2428 !mem_cgroup_is_root(memcg)); 2429 2430 return max_overage; 2431 } 2432 2433 /* 2434 * Get the number of jiffies that we should penalise a mischievous cgroup which 2435 * is exceeding its memory.high by checking both it and its ancestors. 2436 */ 2437 static unsigned long calculate_high_delay(struct mem_cgroup *memcg, 2438 unsigned int nr_pages, 2439 u64 max_overage) 2440 { 2441 unsigned long penalty_jiffies; 2442 2443 if (!max_overage) 2444 return 0; 2445 2446 /* 2447 * We use overage compared to memory.high to calculate the number of 2448 * jiffies to sleep (penalty_jiffies). Ideally this value should be 2449 * fairly lenient on small overages, and increasingly harsh when the 2450 * memcg in question makes it clear that it has no intention of stopping 2451 * its crazy behaviour, so we exponentially increase the delay based on 2452 * overage amount. 2453 */ 2454 penalty_jiffies = max_overage * max_overage * HZ; 2455 penalty_jiffies >>= MEMCG_DELAY_PRECISION_SHIFT; 2456 penalty_jiffies >>= MEMCG_DELAY_SCALING_SHIFT; 2457 2458 /* 2459 * Factor in the task's own contribution to the overage, such that four 2460 * N-sized allocations are throttled approximately the same as one 2461 * 4N-sized allocation. 2462 * 2463 * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or 2464 * larger the current charge patch is than that. 2465 */ 2466 return penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH; 2467 } 2468 2469 /* 2470 * Scheduled by try_charge() to be executed from the userland return path 2471 * and reclaims memory over the high limit. 2472 */ 2473 void mem_cgroup_handle_over_high(void) 2474 { 2475 unsigned long penalty_jiffies; 2476 unsigned long pflags; 2477 unsigned long nr_reclaimed; 2478 unsigned int nr_pages = current->memcg_nr_pages_over_high; 2479 int nr_retries = MAX_RECLAIM_RETRIES; 2480 struct mem_cgroup *memcg; 2481 bool in_retry = false; 2482 2483 if (likely(!nr_pages)) 2484 return; 2485 2486 memcg = get_mem_cgroup_from_mm(current->mm); 2487 current->memcg_nr_pages_over_high = 0; 2488 2489 retry_reclaim: 2490 /* 2491 * The allocating task should reclaim at least the batch size, but for 2492 * subsequent retries we only want to do what's necessary to prevent oom 2493 * or breaching resource isolation. 2494 * 2495 * This is distinct from memory.max or page allocator behaviour because 2496 * memory.high is currently batched, whereas memory.max and the page 2497 * allocator run every time an allocation is made. 2498 */ 2499 nr_reclaimed = reclaim_high(memcg, 2500 in_retry ? SWAP_CLUSTER_MAX : nr_pages, 2501 GFP_KERNEL); 2502 2503 /* 2504 * memory.high is breached and reclaim is unable to keep up. Throttle 2505 * allocators proactively to slow down excessive growth. 2506 */ 2507 penalty_jiffies = calculate_high_delay(memcg, nr_pages, 2508 mem_find_max_overage(memcg)); 2509 2510 penalty_jiffies += calculate_high_delay(memcg, nr_pages, 2511 swap_find_max_overage(memcg)); 2512 2513 /* 2514 * Clamp the max delay per usermode return so as to still keep the 2515 * application moving forwards and also permit diagnostics, albeit 2516 * extremely slowly. 2517 */ 2518 penalty_jiffies = min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES); 2519 2520 /* 2521 * Don't sleep if the amount of jiffies this memcg owes us is so low 2522 * that it's not even worth doing, in an attempt to be nice to those who 2523 * go only a small amount over their memory.high value and maybe haven't 2524 * been aggressively reclaimed enough yet. 2525 */ 2526 if (penalty_jiffies <= HZ / 100) 2527 goto out; 2528 2529 /* 2530 * If reclaim is making forward progress but we're still over 2531 * memory.high, we want to encourage that rather than doing allocator 2532 * throttling. 2533 */ 2534 if (nr_reclaimed || nr_retries--) { 2535 in_retry = true; 2536 goto retry_reclaim; 2537 } 2538 2539 /* 2540 * If we exit early, we're guaranteed to die (since 2541 * schedule_timeout_killable sets TASK_KILLABLE). This means we don't 2542 * need to account for any ill-begotten jiffies to pay them off later. 2543 */ 2544 psi_memstall_enter(&pflags); 2545 schedule_timeout_killable(penalty_jiffies); 2546 psi_memstall_leave(&pflags); 2547 2548 out: 2549 css_put(&memcg->css); 2550 } 2551 2552 static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask, 2553 unsigned int nr_pages) 2554 { 2555 unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages); 2556 int nr_retries = MAX_RECLAIM_RETRIES; 2557 struct mem_cgroup *mem_over_limit; 2558 struct page_counter *counter; 2559 unsigned long nr_reclaimed; 2560 bool passed_oom = false; 2561 bool may_swap = true; 2562 bool drained = false; 2563 unsigned long pflags; 2564 2565 retry: 2566 if (consume_stock(memcg, nr_pages)) 2567 return 0; 2568 2569 if (!do_memsw_account() || 2570 page_counter_try_charge(&memcg->memsw, batch, &counter)) { 2571 if (page_counter_try_charge(&memcg->memory, batch, &counter)) 2572 goto done_restock; 2573 if (do_memsw_account()) 2574 page_counter_uncharge(&memcg->memsw, batch); 2575 mem_over_limit = mem_cgroup_from_counter(counter, memory); 2576 } else { 2577 mem_over_limit = mem_cgroup_from_counter(counter, memsw); 2578 may_swap = false; 2579 } 2580 2581 if (batch > nr_pages) { 2582 batch = nr_pages; 2583 goto retry; 2584 } 2585 2586 /* 2587 * Prevent unbounded recursion when reclaim operations need to 2588 * allocate memory. This might exceed the limits temporarily, 2589 * but we prefer facilitating memory reclaim and getting back 2590 * under the limit over triggering OOM kills in these cases. 2591 */ 2592 if (unlikely(current->flags & PF_MEMALLOC)) 2593 goto force; 2594 2595 if (unlikely(task_in_memcg_oom(current))) 2596 goto nomem; 2597 2598 if (!gfpflags_allow_blocking(gfp_mask)) 2599 goto nomem; 2600 2601 memcg_memory_event(mem_over_limit, MEMCG_MAX); 2602 2603 psi_memstall_enter(&pflags); 2604 nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages, 2605 gfp_mask, may_swap); 2606 psi_memstall_leave(&pflags); 2607 2608 if (mem_cgroup_margin(mem_over_limit) >= nr_pages) 2609 goto retry; 2610 2611 if (!drained) { 2612 drain_all_stock(mem_over_limit); 2613 drained = true; 2614 goto retry; 2615 } 2616 2617 if (gfp_mask & __GFP_NORETRY) 2618 goto nomem; 2619 /* 2620 * Even though the limit is exceeded at this point, reclaim 2621 * may have been able to free some pages. Retry the charge 2622 * before killing the task. 2623 * 2624 * Only for regular pages, though: huge pages are rather 2625 * unlikely to succeed so close to the limit, and we fall back 2626 * to regular pages anyway in case of failure. 2627 */ 2628 if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER)) 2629 goto retry; 2630 /* 2631 * At task move, charge accounts can be doubly counted. So, it's 2632 * better to wait until the end of task_move if something is going on. 2633 */ 2634 if (mem_cgroup_wait_acct_move(mem_over_limit)) 2635 goto retry; 2636 2637 if (nr_retries--) 2638 goto retry; 2639 2640 if (gfp_mask & __GFP_RETRY_MAYFAIL) 2641 goto nomem; 2642 2643 /* Avoid endless loop for tasks bypassed by the oom killer */ 2644 if (passed_oom && task_is_dying()) 2645 goto nomem; 2646 2647 /* 2648 * keep retrying as long as the memcg oom killer is able to make 2649 * a forward progress or bypass the charge if the oom killer 2650 * couldn't make any progress. 2651 */ 2652 if (mem_cgroup_oom(mem_over_limit, gfp_mask, 2653 get_order(nr_pages * PAGE_SIZE))) { 2654 passed_oom = true; 2655 nr_retries = MAX_RECLAIM_RETRIES; 2656 goto retry; 2657 } 2658 nomem: 2659 /* 2660 * Memcg doesn't have a dedicated reserve for atomic 2661 * allocations. But like the global atomic pool, we need to 2662 * put the burden of reclaim on regular allocation requests 2663 * and let these go through as privileged allocations. 2664 */ 2665 if (!(gfp_mask & (__GFP_NOFAIL | __GFP_HIGH))) 2666 return -ENOMEM; 2667 force: 2668 /* 2669 * The allocation either can't fail or will lead to more memory 2670 * being freed very soon. Allow memory usage go over the limit 2671 * temporarily by force charging it. 2672 */ 2673 page_counter_charge(&memcg->memory, nr_pages); 2674 if (do_memsw_account()) 2675 page_counter_charge(&memcg->memsw, nr_pages); 2676 2677 return 0; 2678 2679 done_restock: 2680 if (batch > nr_pages) 2681 refill_stock(memcg, batch - nr_pages); 2682 2683 /* 2684 * If the hierarchy is above the normal consumption range, schedule 2685 * reclaim on returning to userland. We can perform reclaim here 2686 * if __GFP_RECLAIM but let's always punt for simplicity and so that 2687 * GFP_KERNEL can consistently be used during reclaim. @memcg is 2688 * not recorded as it most likely matches current's and won't 2689 * change in the meantime. As high limit is checked again before 2690 * reclaim, the cost of mismatch is negligible. 2691 */ 2692 do { 2693 bool mem_high, swap_high; 2694 2695 mem_high = page_counter_read(&memcg->memory) > 2696 READ_ONCE(memcg->memory.high); 2697 swap_high = page_counter_read(&memcg->swap) > 2698 READ_ONCE(memcg->swap.high); 2699 2700 /* Don't bother a random interrupted task */ 2701 if (!in_task()) { 2702 if (mem_high) { 2703 schedule_work(&memcg->high_work); 2704 break; 2705 } 2706 continue; 2707 } 2708 2709 if (mem_high || swap_high) { 2710 /* 2711 * The allocating tasks in this cgroup will need to do 2712 * reclaim or be throttled to prevent further growth 2713 * of the memory or swap footprints. 2714 * 2715 * Target some best-effort fairness between the tasks, 2716 * and distribute reclaim work and delay penalties 2717 * based on how much each task is actually allocating. 2718 */ 2719 current->memcg_nr_pages_over_high += batch; 2720 set_notify_resume(current); 2721 break; 2722 } 2723 } while ((memcg = parent_mem_cgroup(memcg))); 2724 2725 if (current->memcg_nr_pages_over_high > MEMCG_CHARGE_BATCH && 2726 !(current->flags & PF_MEMALLOC) && 2727 gfpflags_allow_blocking(gfp_mask)) { 2728 mem_cgroup_handle_over_high(); 2729 } 2730 return 0; 2731 } 2732 2733 static inline int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask, 2734 unsigned int nr_pages) 2735 { 2736 if (mem_cgroup_is_root(memcg)) 2737 return 0; 2738 2739 return try_charge_memcg(memcg, gfp_mask, nr_pages); 2740 } 2741 2742 static inline void cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages) 2743 { 2744 if (mem_cgroup_is_root(memcg)) 2745 return; 2746 2747 page_counter_uncharge(&memcg->memory, nr_pages); 2748 if (do_memsw_account()) 2749 page_counter_uncharge(&memcg->memsw, nr_pages); 2750 } 2751 2752 static void commit_charge(struct folio *folio, struct mem_cgroup *memcg) 2753 { 2754 VM_BUG_ON_FOLIO(folio_memcg(folio), folio); 2755 /* 2756 * Any of the following ensures page's memcg stability: 2757 * 2758 * - the page lock 2759 * - LRU isolation 2760 * - lock_page_memcg() 2761 * - exclusive reference 2762 */ 2763 folio->memcg_data = (unsigned long)memcg; 2764 } 2765 2766 #ifdef CONFIG_MEMCG_KMEM 2767 /* 2768 * The allocated objcg pointers array is not accounted directly. 2769 * Moreover, it should not come from DMA buffer and is not readily 2770 * reclaimable. So those GFP bits should be masked off. 2771 */ 2772 #define OBJCGS_CLEAR_MASK (__GFP_DMA | __GFP_RECLAIMABLE | __GFP_ACCOUNT) 2773 2774 /* 2775 * mod_objcg_mlstate() may be called with irq enabled, so 2776 * mod_memcg_lruvec_state() should be used. 2777 */ 2778 static inline void mod_objcg_mlstate(struct obj_cgroup *objcg, 2779 struct pglist_data *pgdat, 2780 enum node_stat_item idx, int nr) 2781 { 2782 struct mem_cgroup *memcg; 2783 struct lruvec *lruvec; 2784 2785 rcu_read_lock(); 2786 memcg = obj_cgroup_memcg(objcg); 2787 lruvec = mem_cgroup_lruvec(memcg, pgdat); 2788 mod_memcg_lruvec_state(lruvec, idx, nr); 2789 rcu_read_unlock(); 2790 } 2791 2792 int memcg_alloc_slab_cgroups(struct slab *slab, struct kmem_cache *s, 2793 gfp_t gfp, bool new_slab) 2794 { 2795 unsigned int objects = objs_per_slab(s, slab); 2796 unsigned long memcg_data; 2797 void *vec; 2798 2799 gfp &= ~OBJCGS_CLEAR_MASK; 2800 vec = kcalloc_node(objects, sizeof(struct obj_cgroup *), gfp, 2801 slab_nid(slab)); 2802 if (!vec) 2803 return -ENOMEM; 2804 2805 memcg_data = (unsigned long) vec | MEMCG_DATA_OBJCGS; 2806 if (new_slab) { 2807 /* 2808 * If the slab is brand new and nobody can yet access its 2809 * memcg_data, no synchronization is required and memcg_data can 2810 * be simply assigned. 2811 */ 2812 slab->memcg_data = memcg_data; 2813 } else if (cmpxchg(&slab->memcg_data, 0, memcg_data)) { 2814 /* 2815 * If the slab is already in use, somebody can allocate and 2816 * assign obj_cgroups in parallel. In this case the existing 2817 * objcg vector should be reused. 2818 */ 2819 kfree(vec); 2820 return 0; 2821 } 2822 2823 kmemleak_not_leak(vec); 2824 return 0; 2825 } 2826 2827 /* 2828 * Returns a pointer to the memory cgroup to which the kernel object is charged. 2829 * 2830 * A passed kernel object can be a slab object or a generic kernel page, so 2831 * different mechanisms for getting the memory cgroup pointer should be used. 2832 * In certain cases (e.g. kernel stacks or large kmallocs with SLUB) the caller 2833 * can not know for sure how the kernel object is implemented. 2834 * mem_cgroup_from_obj() can be safely used in such cases. 2835 * 2836 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(), 2837 * cgroup_mutex, etc. 2838 */ 2839 struct mem_cgroup *mem_cgroup_from_obj(void *p) 2840 { 2841 struct folio *folio; 2842 2843 if (mem_cgroup_disabled()) 2844 return NULL; 2845 2846 folio = virt_to_folio(p); 2847 2848 /* 2849 * Slab objects are accounted individually, not per-page. 2850 * Memcg membership data for each individual object is saved in 2851 * slab->memcg_data. 2852 */ 2853 if (folio_test_slab(folio)) { 2854 struct obj_cgroup **objcgs; 2855 struct slab *slab; 2856 unsigned int off; 2857 2858 slab = folio_slab(folio); 2859 objcgs = slab_objcgs(slab); 2860 if (!objcgs) 2861 return NULL; 2862 2863 off = obj_to_index(slab->slab_cache, slab, p); 2864 if (objcgs[off]) 2865 return obj_cgroup_memcg(objcgs[off]); 2866 2867 return NULL; 2868 } 2869 2870 /* 2871 * page_memcg_check() is used here, because in theory we can encounter 2872 * a folio where the slab flag has been cleared already, but 2873 * slab->memcg_data has not been freed yet 2874 * page_memcg_check(page) will guarantee that a proper memory 2875 * cgroup pointer or NULL will be returned. 2876 */ 2877 return page_memcg_check(folio_page(folio, 0)); 2878 } 2879 2880 __always_inline struct obj_cgroup *get_obj_cgroup_from_current(void) 2881 { 2882 struct obj_cgroup *objcg = NULL; 2883 struct mem_cgroup *memcg; 2884 2885 if (memcg_kmem_bypass()) 2886 return NULL; 2887 2888 rcu_read_lock(); 2889 if (unlikely(active_memcg())) 2890 memcg = active_memcg(); 2891 else 2892 memcg = mem_cgroup_from_task(current); 2893 2894 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg)) { 2895 objcg = rcu_dereference(memcg->objcg); 2896 if (objcg && obj_cgroup_tryget(objcg)) 2897 break; 2898 objcg = NULL; 2899 } 2900 rcu_read_unlock(); 2901 2902 return objcg; 2903 } 2904 2905 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages) 2906 { 2907 mod_memcg_state(memcg, MEMCG_KMEM, nr_pages); 2908 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) { 2909 if (nr_pages > 0) 2910 page_counter_charge(&memcg->kmem, nr_pages); 2911 else 2912 page_counter_uncharge(&memcg->kmem, -nr_pages); 2913 } 2914 } 2915 2916 2917 /* 2918 * obj_cgroup_uncharge_pages: uncharge a number of kernel pages from a objcg 2919 * @objcg: object cgroup to uncharge 2920 * @nr_pages: number of pages to uncharge 2921 */ 2922 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg, 2923 unsigned int nr_pages) 2924 { 2925 struct mem_cgroup *memcg; 2926 2927 memcg = get_mem_cgroup_from_objcg(objcg); 2928 2929 memcg_account_kmem(memcg, -nr_pages); 2930 refill_stock(memcg, nr_pages); 2931 2932 css_put(&memcg->css); 2933 } 2934 2935 /* 2936 * obj_cgroup_charge_pages: charge a number of kernel pages to a objcg 2937 * @objcg: object cgroup to charge 2938 * @gfp: reclaim mode 2939 * @nr_pages: number of pages to charge 2940 * 2941 * Returns 0 on success, an error code on failure. 2942 */ 2943 static int obj_cgroup_charge_pages(struct obj_cgroup *objcg, gfp_t gfp, 2944 unsigned int nr_pages) 2945 { 2946 struct mem_cgroup *memcg; 2947 int ret; 2948 2949 memcg = get_mem_cgroup_from_objcg(objcg); 2950 2951 ret = try_charge_memcg(memcg, gfp, nr_pages); 2952 if (ret) 2953 goto out; 2954 2955 memcg_account_kmem(memcg, nr_pages); 2956 out: 2957 css_put(&memcg->css); 2958 2959 return ret; 2960 } 2961 2962 /** 2963 * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup 2964 * @page: page to charge 2965 * @gfp: reclaim mode 2966 * @order: allocation order 2967 * 2968 * Returns 0 on success, an error code on failure. 2969 */ 2970 int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order) 2971 { 2972 struct obj_cgroup *objcg; 2973 int ret = 0; 2974 2975 objcg = get_obj_cgroup_from_current(); 2976 if (objcg) { 2977 ret = obj_cgroup_charge_pages(objcg, gfp, 1 << order); 2978 if (!ret) { 2979 page->memcg_data = (unsigned long)objcg | 2980 MEMCG_DATA_KMEM; 2981 return 0; 2982 } 2983 obj_cgroup_put(objcg); 2984 } 2985 return ret; 2986 } 2987 2988 /** 2989 * __memcg_kmem_uncharge_page: uncharge a kmem page 2990 * @page: page to uncharge 2991 * @order: allocation order 2992 */ 2993 void __memcg_kmem_uncharge_page(struct page *page, int order) 2994 { 2995 struct folio *folio = page_folio(page); 2996 struct obj_cgroup *objcg; 2997 unsigned int nr_pages = 1 << order; 2998 2999 if (!folio_memcg_kmem(folio)) 3000 return; 3001 3002 objcg = __folio_objcg(folio); 3003 obj_cgroup_uncharge_pages(objcg, nr_pages); 3004 folio->memcg_data = 0; 3005 obj_cgroup_put(objcg); 3006 } 3007 3008 void mod_objcg_state(struct obj_cgroup *objcg, struct pglist_data *pgdat, 3009 enum node_stat_item idx, int nr) 3010 { 3011 struct memcg_stock_pcp *stock; 3012 struct obj_cgroup *old = NULL; 3013 unsigned long flags; 3014 int *bytes; 3015 3016 local_lock_irqsave(&memcg_stock.stock_lock, flags); 3017 stock = this_cpu_ptr(&memcg_stock); 3018 3019 /* 3020 * Save vmstat data in stock and skip vmstat array update unless 3021 * accumulating over a page of vmstat data or when pgdat or idx 3022 * changes. 3023 */ 3024 if (stock->cached_objcg != objcg) { 3025 old = drain_obj_stock(stock); 3026 obj_cgroup_get(objcg); 3027 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes) 3028 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0; 3029 stock->cached_objcg = objcg; 3030 stock->cached_pgdat = pgdat; 3031 } else if (stock->cached_pgdat != pgdat) { 3032 /* Flush the existing cached vmstat data */ 3033 struct pglist_data *oldpg = stock->cached_pgdat; 3034 3035 if (stock->nr_slab_reclaimable_b) { 3036 mod_objcg_mlstate(objcg, oldpg, NR_SLAB_RECLAIMABLE_B, 3037 stock->nr_slab_reclaimable_b); 3038 stock->nr_slab_reclaimable_b = 0; 3039 } 3040 if (stock->nr_slab_unreclaimable_b) { 3041 mod_objcg_mlstate(objcg, oldpg, NR_SLAB_UNRECLAIMABLE_B, 3042 stock->nr_slab_unreclaimable_b); 3043 stock->nr_slab_unreclaimable_b = 0; 3044 } 3045 stock->cached_pgdat = pgdat; 3046 } 3047 3048 bytes = (idx == NR_SLAB_RECLAIMABLE_B) ? &stock->nr_slab_reclaimable_b 3049 : &stock->nr_slab_unreclaimable_b; 3050 /* 3051 * Even for large object >= PAGE_SIZE, the vmstat data will still be 3052 * cached locally at least once before pushing it out. 3053 */ 3054 if (!*bytes) { 3055 *bytes = nr; 3056 nr = 0; 3057 } else { 3058 *bytes += nr; 3059 if (abs(*bytes) > PAGE_SIZE) { 3060 nr = *bytes; 3061 *bytes = 0; 3062 } else { 3063 nr = 0; 3064 } 3065 } 3066 if (nr) 3067 mod_objcg_mlstate(objcg, pgdat, idx, nr); 3068 3069 local_unlock_irqrestore(&memcg_stock.stock_lock, flags); 3070 if (old) 3071 obj_cgroup_put(old); 3072 } 3073 3074 static bool consume_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes) 3075 { 3076 struct memcg_stock_pcp *stock; 3077 unsigned long flags; 3078 bool ret = false; 3079 3080 local_lock_irqsave(&memcg_stock.stock_lock, flags); 3081 3082 stock = this_cpu_ptr(&memcg_stock); 3083 if (objcg == stock->cached_objcg && stock->nr_bytes >= nr_bytes) { 3084 stock->nr_bytes -= nr_bytes; 3085 ret = true; 3086 } 3087 3088 local_unlock_irqrestore(&memcg_stock.stock_lock, flags); 3089 3090 return ret; 3091 } 3092 3093 static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock) 3094 { 3095 struct obj_cgroup *old = stock->cached_objcg; 3096 3097 if (!old) 3098 return NULL; 3099 3100 if (stock->nr_bytes) { 3101 unsigned int nr_pages = stock->nr_bytes >> PAGE_SHIFT; 3102 unsigned int nr_bytes = stock->nr_bytes & (PAGE_SIZE - 1); 3103 3104 if (nr_pages) { 3105 struct mem_cgroup *memcg; 3106 3107 memcg = get_mem_cgroup_from_objcg(old); 3108 3109 memcg_account_kmem(memcg, -nr_pages); 3110 __refill_stock(memcg, nr_pages); 3111 3112 css_put(&memcg->css); 3113 } 3114 3115 /* 3116 * The leftover is flushed to the centralized per-memcg value. 3117 * On the next attempt to refill obj stock it will be moved 3118 * to a per-cpu stock (probably, on an other CPU), see 3119 * refill_obj_stock(). 3120 * 3121 * How often it's flushed is a trade-off between the memory 3122 * limit enforcement accuracy and potential CPU contention, 3123 * so it might be changed in the future. 3124 */ 3125 atomic_add(nr_bytes, &old->nr_charged_bytes); 3126 stock->nr_bytes = 0; 3127 } 3128 3129 /* 3130 * Flush the vmstat data in current stock 3131 */ 3132 if (stock->nr_slab_reclaimable_b || stock->nr_slab_unreclaimable_b) { 3133 if (stock->nr_slab_reclaimable_b) { 3134 mod_objcg_mlstate(old, stock->cached_pgdat, 3135 NR_SLAB_RECLAIMABLE_B, 3136 stock->nr_slab_reclaimable_b); 3137 stock->nr_slab_reclaimable_b = 0; 3138 } 3139 if (stock->nr_slab_unreclaimable_b) { 3140 mod_objcg_mlstate(old, stock->cached_pgdat, 3141 NR_SLAB_UNRECLAIMABLE_B, 3142 stock->nr_slab_unreclaimable_b); 3143 stock->nr_slab_unreclaimable_b = 0; 3144 } 3145 stock->cached_pgdat = NULL; 3146 } 3147 3148 stock->cached_objcg = NULL; 3149 /* 3150 * The `old' objects needs to be released by the caller via 3151 * obj_cgroup_put() outside of memcg_stock_pcp::stock_lock. 3152 */ 3153 return old; 3154 } 3155 3156 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock, 3157 struct mem_cgroup *root_memcg) 3158 { 3159 struct mem_cgroup *memcg; 3160 3161 if (stock->cached_objcg) { 3162 memcg = obj_cgroup_memcg(stock->cached_objcg); 3163 if (memcg && mem_cgroup_is_descendant(memcg, root_memcg)) 3164 return true; 3165 } 3166 3167 return false; 3168 } 3169 3170 static void refill_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes, 3171 bool allow_uncharge) 3172 { 3173 struct memcg_stock_pcp *stock; 3174 struct obj_cgroup *old = NULL; 3175 unsigned long flags; 3176 unsigned int nr_pages = 0; 3177 3178 local_lock_irqsave(&memcg_stock.stock_lock, flags); 3179 3180 stock = this_cpu_ptr(&memcg_stock); 3181 if (stock->cached_objcg != objcg) { /* reset if necessary */ 3182 old = drain_obj_stock(stock); 3183 obj_cgroup_get(objcg); 3184 stock->cached_objcg = objcg; 3185 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes) 3186 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0; 3187 allow_uncharge = true; /* Allow uncharge when objcg changes */ 3188 } 3189 stock->nr_bytes += nr_bytes; 3190 3191 if (allow_uncharge && (stock->nr_bytes > PAGE_SIZE)) { 3192 nr_pages = stock->nr_bytes >> PAGE_SHIFT; 3193 stock->nr_bytes &= (PAGE_SIZE - 1); 3194 } 3195 3196 local_unlock_irqrestore(&memcg_stock.stock_lock, flags); 3197 if (old) 3198 obj_cgroup_put(old); 3199 3200 if (nr_pages) 3201 obj_cgroup_uncharge_pages(objcg, nr_pages); 3202 } 3203 3204 int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size) 3205 { 3206 unsigned int nr_pages, nr_bytes; 3207 int ret; 3208 3209 if (consume_obj_stock(objcg, size)) 3210 return 0; 3211 3212 /* 3213 * In theory, objcg->nr_charged_bytes can have enough 3214 * pre-charged bytes to satisfy the allocation. However, 3215 * flushing objcg->nr_charged_bytes requires two atomic 3216 * operations, and objcg->nr_charged_bytes can't be big. 3217 * The shared objcg->nr_charged_bytes can also become a 3218 * performance bottleneck if all tasks of the same memcg are 3219 * trying to update it. So it's better to ignore it and try 3220 * grab some new pages. The stock's nr_bytes will be flushed to 3221 * objcg->nr_charged_bytes later on when objcg changes. 3222 * 3223 * The stock's nr_bytes may contain enough pre-charged bytes 3224 * to allow one less page from being charged, but we can't rely 3225 * on the pre-charged bytes not being changed outside of 3226 * consume_obj_stock() or refill_obj_stock(). So ignore those 3227 * pre-charged bytes as well when charging pages. To avoid a 3228 * page uncharge right after a page charge, we set the 3229 * allow_uncharge flag to false when calling refill_obj_stock() 3230 * to temporarily allow the pre-charged bytes to exceed the page 3231 * size limit. The maximum reachable value of the pre-charged 3232 * bytes is (sizeof(object) + PAGE_SIZE - 2) if there is no data 3233 * race. 3234 */ 3235 nr_pages = size >> PAGE_SHIFT; 3236 nr_bytes = size & (PAGE_SIZE - 1); 3237 3238 if (nr_bytes) 3239 nr_pages += 1; 3240 3241 ret = obj_cgroup_charge_pages(objcg, gfp, nr_pages); 3242 if (!ret && nr_bytes) 3243 refill_obj_stock(objcg, PAGE_SIZE - nr_bytes, false); 3244 3245 return ret; 3246 } 3247 3248 void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size) 3249 { 3250 refill_obj_stock(objcg, size, true); 3251 } 3252 3253 #endif /* CONFIG_MEMCG_KMEM */ 3254 3255 /* 3256 * Because page_memcg(head) is not set on tails, set it now. 3257 */ 3258 void split_page_memcg(struct page *head, unsigned int nr) 3259 { 3260 struct folio *folio = page_folio(head); 3261 struct mem_cgroup *memcg = folio_memcg(folio); 3262 int i; 3263 3264 if (mem_cgroup_disabled() || !memcg) 3265 return; 3266 3267 for (i = 1; i < nr; i++) 3268 folio_page(folio, i)->memcg_data = folio->memcg_data; 3269 3270 if (folio_memcg_kmem(folio)) 3271 obj_cgroup_get_many(__folio_objcg(folio), nr - 1); 3272 else 3273 css_get_many(&memcg->css, nr - 1); 3274 } 3275 3276 #ifdef CONFIG_MEMCG_SWAP 3277 /** 3278 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record. 3279 * @entry: swap entry to be moved 3280 * @from: mem_cgroup which the entry is moved from 3281 * @to: mem_cgroup which the entry is moved to 3282 * 3283 * It succeeds only when the swap_cgroup's record for this entry is the same 3284 * as the mem_cgroup's id of @from. 3285 * 3286 * Returns 0 on success, -EINVAL on failure. 3287 * 3288 * The caller must have charged to @to, IOW, called page_counter_charge() about 3289 * both res and memsw, and called css_get(). 3290 */ 3291 static int mem_cgroup_move_swap_account(swp_entry_t entry, 3292 struct mem_cgroup *from, struct mem_cgroup *to) 3293 { 3294 unsigned short old_id, new_id; 3295 3296 old_id = mem_cgroup_id(from); 3297 new_id = mem_cgroup_id(to); 3298 3299 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) { 3300 mod_memcg_state(from, MEMCG_SWAP, -1); 3301 mod_memcg_state(to, MEMCG_SWAP, 1); 3302 return 0; 3303 } 3304 return -EINVAL; 3305 } 3306 #else 3307 static inline int mem_cgroup_move_swap_account(swp_entry_t entry, 3308 struct mem_cgroup *from, struct mem_cgroup *to) 3309 { 3310 return -EINVAL; 3311 } 3312 #endif 3313 3314 static DEFINE_MUTEX(memcg_max_mutex); 3315 3316 static int mem_cgroup_resize_max(struct mem_cgroup *memcg, 3317 unsigned long max, bool memsw) 3318 { 3319 bool enlarge = false; 3320 bool drained = false; 3321 int ret; 3322 bool limits_invariant; 3323 struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory; 3324 3325 do { 3326 if (signal_pending(current)) { 3327 ret = -EINTR; 3328 break; 3329 } 3330 3331 mutex_lock(&memcg_max_mutex); 3332 /* 3333 * Make sure that the new limit (memsw or memory limit) doesn't 3334 * break our basic invariant rule memory.max <= memsw.max. 3335 */ 3336 limits_invariant = memsw ? max >= READ_ONCE(memcg->memory.max) : 3337 max <= memcg->memsw.max; 3338 if (!limits_invariant) { 3339 mutex_unlock(&memcg_max_mutex); 3340 ret = -EINVAL; 3341 break; 3342 } 3343 if (max > counter->max) 3344 enlarge = true; 3345 ret = page_counter_set_max(counter, max); 3346 mutex_unlock(&memcg_max_mutex); 3347 3348 if (!ret) 3349 break; 3350 3351 if (!drained) { 3352 drain_all_stock(memcg); 3353 drained = true; 3354 continue; 3355 } 3356 3357 if (!try_to_free_mem_cgroup_pages(memcg, 1, 3358 GFP_KERNEL, !memsw)) { 3359 ret = -EBUSY; 3360 break; 3361 } 3362 } while (true); 3363 3364 if (!ret && enlarge) 3365 memcg_oom_recover(memcg); 3366 3367 return ret; 3368 } 3369 3370 unsigned long mem_cgroup_soft_limit_reclaim(pg_data_t *pgdat, int order, 3371 gfp_t gfp_mask, 3372 unsigned long *total_scanned) 3373 { 3374 unsigned long nr_reclaimed = 0; 3375 struct mem_cgroup_per_node *mz, *next_mz = NULL; 3376 unsigned long reclaimed; 3377 int loop = 0; 3378 struct mem_cgroup_tree_per_node *mctz; 3379 unsigned long excess; 3380 unsigned long nr_scanned; 3381 3382 if (order > 0) 3383 return 0; 3384 3385 mctz = soft_limit_tree.rb_tree_per_node[pgdat->node_id]; 3386 3387 /* 3388 * Do not even bother to check the largest node if the root 3389 * is empty. Do it lockless to prevent lock bouncing. Races 3390 * are acceptable as soft limit is best effort anyway. 3391 */ 3392 if (!mctz || RB_EMPTY_ROOT(&mctz->rb_root)) 3393 return 0; 3394 3395 /* 3396 * This loop can run a while, specially if mem_cgroup's continuously 3397 * keep exceeding their soft limit and putting the system under 3398 * pressure 3399 */ 3400 do { 3401 if (next_mz) 3402 mz = next_mz; 3403 else 3404 mz = mem_cgroup_largest_soft_limit_node(mctz); 3405 if (!mz) 3406 break; 3407 3408 nr_scanned = 0; 3409 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, pgdat, 3410 gfp_mask, &nr_scanned); 3411 nr_reclaimed += reclaimed; 3412 *total_scanned += nr_scanned; 3413 spin_lock_irq(&mctz->lock); 3414 __mem_cgroup_remove_exceeded(mz, mctz); 3415 3416 /* 3417 * If we failed to reclaim anything from this memory cgroup 3418 * it is time to move on to the next cgroup 3419 */ 3420 next_mz = NULL; 3421 if (!reclaimed) 3422 next_mz = __mem_cgroup_largest_soft_limit_node(mctz); 3423 3424 excess = soft_limit_excess(mz->memcg); 3425 /* 3426 * One school of thought says that we should not add 3427 * back the node to the tree if reclaim returns 0. 3428 * But our reclaim could return 0, simply because due 3429 * to priority we are exposing a smaller subset of 3430 * memory to reclaim from. Consider this as a longer 3431 * term TODO. 3432 */ 3433 /* If excess == 0, no tree ops */ 3434 __mem_cgroup_insert_exceeded(mz, mctz, excess); 3435 spin_unlock_irq(&mctz->lock); 3436 css_put(&mz->memcg->css); 3437 loop++; 3438 /* 3439 * Could not reclaim anything and there are no more 3440 * mem cgroups to try or we seem to be looping without 3441 * reclaiming anything. 3442 */ 3443 if (!nr_reclaimed && 3444 (next_mz == NULL || 3445 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS)) 3446 break; 3447 } while (!nr_reclaimed); 3448 if (next_mz) 3449 css_put(&next_mz->memcg->css); 3450 return nr_reclaimed; 3451 } 3452 3453 /* 3454 * Reclaims as many pages from the given memcg as possible. 3455 * 3456 * Caller is responsible for holding css reference for memcg. 3457 */ 3458 static int mem_cgroup_force_empty(struct mem_cgroup *memcg) 3459 { 3460 int nr_retries = MAX_RECLAIM_RETRIES; 3461 3462 /* we call try-to-free pages for make this cgroup empty */ 3463 lru_add_drain_all(); 3464 3465 drain_all_stock(memcg); 3466 3467 /* try to free all pages in this cgroup */ 3468 while (nr_retries && page_counter_read(&memcg->memory)) { 3469 if (signal_pending(current)) 3470 return -EINTR; 3471 3472 if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL, true)) 3473 nr_retries--; 3474 } 3475 3476 return 0; 3477 } 3478 3479 static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of, 3480 char *buf, size_t nbytes, 3481 loff_t off) 3482 { 3483 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 3484 3485 if (mem_cgroup_is_root(memcg)) 3486 return -EINVAL; 3487 return mem_cgroup_force_empty(memcg) ?: nbytes; 3488 } 3489 3490 static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css, 3491 struct cftype *cft) 3492 { 3493 return 1; 3494 } 3495 3496 static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css, 3497 struct cftype *cft, u64 val) 3498 { 3499 if (val == 1) 3500 return 0; 3501 3502 pr_warn_once("Non-hierarchical mode is deprecated. " 3503 "Please report your usecase to linux-mm@kvack.org if you " 3504 "depend on this functionality.\n"); 3505 3506 return -EINVAL; 3507 } 3508 3509 static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap) 3510 { 3511 unsigned long val; 3512 3513 if (mem_cgroup_is_root(memcg)) { 3514 mem_cgroup_flush_stats(); 3515 val = memcg_page_state(memcg, NR_FILE_PAGES) + 3516 memcg_page_state(memcg, NR_ANON_MAPPED); 3517 if (swap) 3518 val += memcg_page_state(memcg, MEMCG_SWAP); 3519 } else { 3520 if (!swap) 3521 val = page_counter_read(&memcg->memory); 3522 else 3523 val = page_counter_read(&memcg->memsw); 3524 } 3525 return val; 3526 } 3527 3528 enum { 3529 RES_USAGE, 3530 RES_LIMIT, 3531 RES_MAX_USAGE, 3532 RES_FAILCNT, 3533 RES_SOFT_LIMIT, 3534 }; 3535 3536 static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css, 3537 struct cftype *cft) 3538 { 3539 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 3540 struct page_counter *counter; 3541 3542 switch (MEMFILE_TYPE(cft->private)) { 3543 case _MEM: 3544 counter = &memcg->memory; 3545 break; 3546 case _MEMSWAP: 3547 counter = &memcg->memsw; 3548 break; 3549 case _KMEM: 3550 counter = &memcg->kmem; 3551 break; 3552 case _TCP: 3553 counter = &memcg->tcpmem; 3554 break; 3555 default: 3556 BUG(); 3557 } 3558 3559 switch (MEMFILE_ATTR(cft->private)) { 3560 case RES_USAGE: 3561 if (counter == &memcg->memory) 3562 return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE; 3563 if (counter == &memcg->memsw) 3564 return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE; 3565 return (u64)page_counter_read(counter) * PAGE_SIZE; 3566 case RES_LIMIT: 3567 return (u64)counter->max * PAGE_SIZE; 3568 case RES_MAX_USAGE: 3569 return (u64)counter->watermark * PAGE_SIZE; 3570 case RES_FAILCNT: 3571 return counter->failcnt; 3572 case RES_SOFT_LIMIT: 3573 return (u64)memcg->soft_limit * PAGE_SIZE; 3574 default: 3575 BUG(); 3576 } 3577 } 3578 3579 #ifdef CONFIG_MEMCG_KMEM 3580 static int memcg_online_kmem(struct mem_cgroup *memcg) 3581 { 3582 struct obj_cgroup *objcg; 3583 3584 if (cgroup_memory_nokmem) 3585 return 0; 3586 3587 if (unlikely(mem_cgroup_is_root(memcg))) 3588 return 0; 3589 3590 objcg = obj_cgroup_alloc(); 3591 if (!objcg) 3592 return -ENOMEM; 3593 3594 objcg->memcg = memcg; 3595 rcu_assign_pointer(memcg->objcg, objcg); 3596 3597 static_branch_enable(&memcg_kmem_enabled_key); 3598 3599 memcg->kmemcg_id = memcg->id.id; 3600 3601 return 0; 3602 } 3603 3604 static void memcg_offline_kmem(struct mem_cgroup *memcg) 3605 { 3606 struct mem_cgroup *parent; 3607 3608 if (cgroup_memory_nokmem) 3609 return; 3610 3611 if (unlikely(mem_cgroup_is_root(memcg))) 3612 return; 3613 3614 parent = parent_mem_cgroup(memcg); 3615 if (!parent) 3616 parent = root_mem_cgroup; 3617 3618 memcg_reparent_objcgs(memcg, parent); 3619 3620 /* 3621 * After we have finished memcg_reparent_objcgs(), all list_lrus 3622 * corresponding to this cgroup are guaranteed to remain empty. 3623 * The ordering is imposed by list_lru_node->lock taken by 3624 * memcg_reparent_list_lrus(). 3625 */ 3626 memcg_reparent_list_lrus(memcg, parent); 3627 } 3628 #else 3629 static int memcg_online_kmem(struct mem_cgroup *memcg) 3630 { 3631 return 0; 3632 } 3633 static void memcg_offline_kmem(struct mem_cgroup *memcg) 3634 { 3635 } 3636 #endif /* CONFIG_MEMCG_KMEM */ 3637 3638 static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max) 3639 { 3640 int ret; 3641 3642 mutex_lock(&memcg_max_mutex); 3643 3644 ret = page_counter_set_max(&memcg->tcpmem, max); 3645 if (ret) 3646 goto out; 3647 3648 if (!memcg->tcpmem_active) { 3649 /* 3650 * The active flag needs to be written after the static_key 3651 * update. This is what guarantees that the socket activation 3652 * function is the last one to run. See mem_cgroup_sk_alloc() 3653 * for details, and note that we don't mark any socket as 3654 * belonging to this memcg until that flag is up. 3655 * 3656 * We need to do this, because static_keys will span multiple 3657 * sites, but we can't control their order. If we mark a socket 3658 * as accounted, but the accounting functions are not patched in 3659 * yet, we'll lose accounting. 3660 * 3661 * We never race with the readers in mem_cgroup_sk_alloc(), 3662 * because when this value change, the code to process it is not 3663 * patched in yet. 3664 */ 3665 static_branch_inc(&memcg_sockets_enabled_key); 3666 memcg->tcpmem_active = true; 3667 } 3668 out: 3669 mutex_unlock(&memcg_max_mutex); 3670 return ret; 3671 } 3672 3673 /* 3674 * The user of this function is... 3675 * RES_LIMIT. 3676 */ 3677 static ssize_t mem_cgroup_write(struct kernfs_open_file *of, 3678 char *buf, size_t nbytes, loff_t off) 3679 { 3680 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 3681 unsigned long nr_pages; 3682 int ret; 3683 3684 buf = strstrip(buf); 3685 ret = page_counter_memparse(buf, "-1", &nr_pages); 3686 if (ret) 3687 return ret; 3688 3689 switch (MEMFILE_ATTR(of_cft(of)->private)) { 3690 case RES_LIMIT: 3691 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */ 3692 ret = -EINVAL; 3693 break; 3694 } 3695 switch (MEMFILE_TYPE(of_cft(of)->private)) { 3696 case _MEM: 3697 ret = mem_cgroup_resize_max(memcg, nr_pages, false); 3698 break; 3699 case _MEMSWAP: 3700 ret = mem_cgroup_resize_max(memcg, nr_pages, true); 3701 break; 3702 case _KMEM: 3703 /* kmem.limit_in_bytes is deprecated. */ 3704 ret = -EOPNOTSUPP; 3705 break; 3706 case _TCP: 3707 ret = memcg_update_tcp_max(memcg, nr_pages); 3708 break; 3709 } 3710 break; 3711 case RES_SOFT_LIMIT: 3712 if (IS_ENABLED(CONFIG_PREEMPT_RT)) { 3713 ret = -EOPNOTSUPP; 3714 } else { 3715 memcg->soft_limit = nr_pages; 3716 ret = 0; 3717 } 3718 break; 3719 } 3720 return ret ?: nbytes; 3721 } 3722 3723 static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf, 3724 size_t nbytes, loff_t off) 3725 { 3726 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 3727 struct page_counter *counter; 3728 3729 switch (MEMFILE_TYPE(of_cft(of)->private)) { 3730 case _MEM: 3731 counter = &memcg->memory; 3732 break; 3733 case _MEMSWAP: 3734 counter = &memcg->memsw; 3735 break; 3736 case _KMEM: 3737 counter = &memcg->kmem; 3738 break; 3739 case _TCP: 3740 counter = &memcg->tcpmem; 3741 break; 3742 default: 3743 BUG(); 3744 } 3745 3746 switch (MEMFILE_ATTR(of_cft(of)->private)) { 3747 case RES_MAX_USAGE: 3748 page_counter_reset_watermark(counter); 3749 break; 3750 case RES_FAILCNT: 3751 counter->failcnt = 0; 3752 break; 3753 default: 3754 BUG(); 3755 } 3756 3757 return nbytes; 3758 } 3759 3760 static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css, 3761 struct cftype *cft) 3762 { 3763 return mem_cgroup_from_css(css)->move_charge_at_immigrate; 3764 } 3765 3766 #ifdef CONFIG_MMU 3767 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css, 3768 struct cftype *cft, u64 val) 3769 { 3770 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 3771 3772 if (val & ~MOVE_MASK) 3773 return -EINVAL; 3774 3775 /* 3776 * No kind of locking is needed in here, because ->can_attach() will 3777 * check this value once in the beginning of the process, and then carry 3778 * on with stale data. This means that changes to this value will only 3779 * affect task migrations starting after the change. 3780 */ 3781 memcg->move_charge_at_immigrate = val; 3782 return 0; 3783 } 3784 #else 3785 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css, 3786 struct cftype *cft, u64 val) 3787 { 3788 return -ENOSYS; 3789 } 3790 #endif 3791 3792 #ifdef CONFIG_NUMA 3793 3794 #define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE)) 3795 #define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON)) 3796 #define LRU_ALL ((1 << NR_LRU_LISTS) - 1) 3797 3798 static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg, 3799 int nid, unsigned int lru_mask, bool tree) 3800 { 3801 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid)); 3802 unsigned long nr = 0; 3803 enum lru_list lru; 3804 3805 VM_BUG_ON((unsigned)nid >= nr_node_ids); 3806 3807 for_each_lru(lru) { 3808 if (!(BIT(lru) & lru_mask)) 3809 continue; 3810 if (tree) 3811 nr += lruvec_page_state(lruvec, NR_LRU_BASE + lru); 3812 else 3813 nr += lruvec_page_state_local(lruvec, NR_LRU_BASE + lru); 3814 } 3815 return nr; 3816 } 3817 3818 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg, 3819 unsigned int lru_mask, 3820 bool tree) 3821 { 3822 unsigned long nr = 0; 3823 enum lru_list lru; 3824 3825 for_each_lru(lru) { 3826 if (!(BIT(lru) & lru_mask)) 3827 continue; 3828 if (tree) 3829 nr += memcg_page_state(memcg, NR_LRU_BASE + lru); 3830 else 3831 nr += memcg_page_state_local(memcg, NR_LRU_BASE + lru); 3832 } 3833 return nr; 3834 } 3835 3836 static int memcg_numa_stat_show(struct seq_file *m, void *v) 3837 { 3838 struct numa_stat { 3839 const char *name; 3840 unsigned int lru_mask; 3841 }; 3842 3843 static const struct numa_stat stats[] = { 3844 { "total", LRU_ALL }, 3845 { "file", LRU_ALL_FILE }, 3846 { "anon", LRU_ALL_ANON }, 3847 { "unevictable", BIT(LRU_UNEVICTABLE) }, 3848 }; 3849 const struct numa_stat *stat; 3850 int nid; 3851 struct mem_cgroup *memcg = mem_cgroup_from_seq(m); 3852 3853 mem_cgroup_flush_stats(); 3854 3855 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) { 3856 seq_printf(m, "%s=%lu", stat->name, 3857 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask, 3858 false)); 3859 for_each_node_state(nid, N_MEMORY) 3860 seq_printf(m, " N%d=%lu", nid, 3861 mem_cgroup_node_nr_lru_pages(memcg, nid, 3862 stat->lru_mask, false)); 3863 seq_putc(m, '\n'); 3864 } 3865 3866 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) { 3867 3868 seq_printf(m, "hierarchical_%s=%lu", stat->name, 3869 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask, 3870 true)); 3871 for_each_node_state(nid, N_MEMORY) 3872 seq_printf(m, " N%d=%lu", nid, 3873 mem_cgroup_node_nr_lru_pages(memcg, nid, 3874 stat->lru_mask, true)); 3875 seq_putc(m, '\n'); 3876 } 3877 3878 return 0; 3879 } 3880 #endif /* CONFIG_NUMA */ 3881 3882 static const unsigned int memcg1_stats[] = { 3883 NR_FILE_PAGES, 3884 NR_ANON_MAPPED, 3885 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 3886 NR_ANON_THPS, 3887 #endif 3888 NR_SHMEM, 3889 NR_FILE_MAPPED, 3890 NR_FILE_DIRTY, 3891 NR_WRITEBACK, 3892 MEMCG_SWAP, 3893 }; 3894 3895 static const char *const memcg1_stat_names[] = { 3896 "cache", 3897 "rss", 3898 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 3899 "rss_huge", 3900 #endif 3901 "shmem", 3902 "mapped_file", 3903 "dirty", 3904 "writeback", 3905 "swap", 3906 }; 3907 3908 /* Universal VM events cgroup1 shows, original sort order */ 3909 static const unsigned int memcg1_events[] = { 3910 PGPGIN, 3911 PGPGOUT, 3912 PGFAULT, 3913 PGMAJFAULT, 3914 }; 3915 3916 static int memcg_stat_show(struct seq_file *m, void *v) 3917 { 3918 struct mem_cgroup *memcg = mem_cgroup_from_seq(m); 3919 unsigned long memory, memsw; 3920 struct mem_cgroup *mi; 3921 unsigned int i; 3922 3923 BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats)); 3924 3925 mem_cgroup_flush_stats(); 3926 3927 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) { 3928 unsigned long nr; 3929 3930 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account()) 3931 continue; 3932 nr = memcg_page_state_local(memcg, memcg1_stats[i]); 3933 seq_printf(m, "%s %lu\n", memcg1_stat_names[i], nr * PAGE_SIZE); 3934 } 3935 3936 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++) 3937 seq_printf(m, "%s %lu\n", vm_event_name(memcg1_events[i]), 3938 memcg_events_local(memcg, memcg1_events[i])); 3939 3940 for (i = 0; i < NR_LRU_LISTS; i++) 3941 seq_printf(m, "%s %lu\n", lru_list_name(i), 3942 memcg_page_state_local(memcg, NR_LRU_BASE + i) * 3943 PAGE_SIZE); 3944 3945 /* Hierarchical information */ 3946 memory = memsw = PAGE_COUNTER_MAX; 3947 for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) { 3948 memory = min(memory, READ_ONCE(mi->memory.max)); 3949 memsw = min(memsw, READ_ONCE(mi->memsw.max)); 3950 } 3951 seq_printf(m, "hierarchical_memory_limit %llu\n", 3952 (u64)memory * PAGE_SIZE); 3953 if (do_memsw_account()) 3954 seq_printf(m, "hierarchical_memsw_limit %llu\n", 3955 (u64)memsw * PAGE_SIZE); 3956 3957 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) { 3958 unsigned long nr; 3959 3960 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account()) 3961 continue; 3962 nr = memcg_page_state(memcg, memcg1_stats[i]); 3963 seq_printf(m, "total_%s %llu\n", memcg1_stat_names[i], 3964 (u64)nr * PAGE_SIZE); 3965 } 3966 3967 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++) 3968 seq_printf(m, "total_%s %llu\n", 3969 vm_event_name(memcg1_events[i]), 3970 (u64)memcg_events(memcg, memcg1_events[i])); 3971 3972 for (i = 0; i < NR_LRU_LISTS; i++) 3973 seq_printf(m, "total_%s %llu\n", lru_list_name(i), 3974 (u64)memcg_page_state(memcg, NR_LRU_BASE + i) * 3975 PAGE_SIZE); 3976 3977 #ifdef CONFIG_DEBUG_VM 3978 { 3979 pg_data_t *pgdat; 3980 struct mem_cgroup_per_node *mz; 3981 unsigned long anon_cost = 0; 3982 unsigned long file_cost = 0; 3983 3984 for_each_online_pgdat(pgdat) { 3985 mz = memcg->nodeinfo[pgdat->node_id]; 3986 3987 anon_cost += mz->lruvec.anon_cost; 3988 file_cost += mz->lruvec.file_cost; 3989 } 3990 seq_printf(m, "anon_cost %lu\n", anon_cost); 3991 seq_printf(m, "file_cost %lu\n", file_cost); 3992 } 3993 #endif 3994 3995 return 0; 3996 } 3997 3998 static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css, 3999 struct cftype *cft) 4000 { 4001 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 4002 4003 return mem_cgroup_swappiness(memcg); 4004 } 4005 4006 static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css, 4007 struct cftype *cft, u64 val) 4008 { 4009 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 4010 4011 if (val > 200) 4012 return -EINVAL; 4013 4014 if (!mem_cgroup_is_root(memcg)) 4015 memcg->swappiness = val; 4016 else 4017 vm_swappiness = val; 4018 4019 return 0; 4020 } 4021 4022 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap) 4023 { 4024 struct mem_cgroup_threshold_ary *t; 4025 unsigned long usage; 4026 int i; 4027 4028 rcu_read_lock(); 4029 if (!swap) 4030 t = rcu_dereference(memcg->thresholds.primary); 4031 else 4032 t = rcu_dereference(memcg->memsw_thresholds.primary); 4033 4034 if (!t) 4035 goto unlock; 4036 4037 usage = mem_cgroup_usage(memcg, swap); 4038 4039 /* 4040 * current_threshold points to threshold just below or equal to usage. 4041 * If it's not true, a threshold was crossed after last 4042 * call of __mem_cgroup_threshold(). 4043 */ 4044 i = t->current_threshold; 4045 4046 /* 4047 * Iterate backward over array of thresholds starting from 4048 * current_threshold and check if a threshold is crossed. 4049 * If none of thresholds below usage is crossed, we read 4050 * only one element of the array here. 4051 */ 4052 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--) 4053 eventfd_signal(t->entries[i].eventfd, 1); 4054 4055 /* i = current_threshold + 1 */ 4056 i++; 4057 4058 /* 4059 * Iterate forward over array of thresholds starting from 4060 * current_threshold+1 and check if a threshold is crossed. 4061 * If none of thresholds above usage is crossed, we read 4062 * only one element of the array here. 4063 */ 4064 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++) 4065 eventfd_signal(t->entries[i].eventfd, 1); 4066 4067 /* Update current_threshold */ 4068 t->current_threshold = i - 1; 4069 unlock: 4070 rcu_read_unlock(); 4071 } 4072 4073 static void mem_cgroup_threshold(struct mem_cgroup *memcg) 4074 { 4075 while (memcg) { 4076 __mem_cgroup_threshold(memcg, false); 4077 if (do_memsw_account()) 4078 __mem_cgroup_threshold(memcg, true); 4079 4080 memcg = parent_mem_cgroup(memcg); 4081 } 4082 } 4083 4084 static int compare_thresholds(const void *a, const void *b) 4085 { 4086 const struct mem_cgroup_threshold *_a = a; 4087 const struct mem_cgroup_threshold *_b = b; 4088 4089 if (_a->threshold > _b->threshold) 4090 return 1; 4091 4092 if (_a->threshold < _b->threshold) 4093 return -1; 4094 4095 return 0; 4096 } 4097 4098 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg) 4099 { 4100 struct mem_cgroup_eventfd_list *ev; 4101 4102 spin_lock(&memcg_oom_lock); 4103 4104 list_for_each_entry(ev, &memcg->oom_notify, list) 4105 eventfd_signal(ev->eventfd, 1); 4106 4107 spin_unlock(&memcg_oom_lock); 4108 return 0; 4109 } 4110 4111 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg) 4112 { 4113 struct mem_cgroup *iter; 4114 4115 for_each_mem_cgroup_tree(iter, memcg) 4116 mem_cgroup_oom_notify_cb(iter); 4117 } 4118 4119 static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg, 4120 struct eventfd_ctx *eventfd, const char *args, enum res_type type) 4121 { 4122 struct mem_cgroup_thresholds *thresholds; 4123 struct mem_cgroup_threshold_ary *new; 4124 unsigned long threshold; 4125 unsigned long usage; 4126 int i, size, ret; 4127 4128 ret = page_counter_memparse(args, "-1", &threshold); 4129 if (ret) 4130 return ret; 4131 4132 mutex_lock(&memcg->thresholds_lock); 4133 4134 if (type == _MEM) { 4135 thresholds = &memcg->thresholds; 4136 usage = mem_cgroup_usage(memcg, false); 4137 } else if (type == _MEMSWAP) { 4138 thresholds = &memcg->memsw_thresholds; 4139 usage = mem_cgroup_usage(memcg, true); 4140 } else 4141 BUG(); 4142 4143 /* Check if a threshold crossed before adding a new one */ 4144 if (thresholds->primary) 4145 __mem_cgroup_threshold(memcg, type == _MEMSWAP); 4146 4147 size = thresholds->primary ? thresholds->primary->size + 1 : 1; 4148 4149 /* Allocate memory for new array of thresholds */ 4150 new = kmalloc(struct_size(new, entries, size), GFP_KERNEL); 4151 if (!new) { 4152 ret = -ENOMEM; 4153 goto unlock; 4154 } 4155 new->size = size; 4156 4157 /* Copy thresholds (if any) to new array */ 4158 if (thresholds->primary) 4159 memcpy(new->entries, thresholds->primary->entries, 4160 flex_array_size(new, entries, size - 1)); 4161 4162 /* Add new threshold */ 4163 new->entries[size - 1].eventfd = eventfd; 4164 new->entries[size - 1].threshold = threshold; 4165 4166 /* Sort thresholds. Registering of new threshold isn't time-critical */ 4167 sort(new->entries, size, sizeof(*new->entries), 4168 compare_thresholds, NULL); 4169 4170 /* Find current threshold */ 4171 new->current_threshold = -1; 4172 for (i = 0; i < size; i++) { 4173 if (new->entries[i].threshold <= usage) { 4174 /* 4175 * new->current_threshold will not be used until 4176 * rcu_assign_pointer(), so it's safe to increment 4177 * it here. 4178 */ 4179 ++new->current_threshold; 4180 } else 4181 break; 4182 } 4183 4184 /* Free old spare buffer and save old primary buffer as spare */ 4185 kfree(thresholds->spare); 4186 thresholds->spare = thresholds->primary; 4187 4188 rcu_assign_pointer(thresholds->primary, new); 4189 4190 /* To be sure that nobody uses thresholds */ 4191 synchronize_rcu(); 4192 4193 unlock: 4194 mutex_unlock(&memcg->thresholds_lock); 4195 4196 return ret; 4197 } 4198 4199 static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg, 4200 struct eventfd_ctx *eventfd, const char *args) 4201 { 4202 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM); 4203 } 4204 4205 static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg, 4206 struct eventfd_ctx *eventfd, const char *args) 4207 { 4208 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP); 4209 } 4210 4211 static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg, 4212 struct eventfd_ctx *eventfd, enum res_type type) 4213 { 4214 struct mem_cgroup_thresholds *thresholds; 4215 struct mem_cgroup_threshold_ary *new; 4216 unsigned long usage; 4217 int i, j, size, entries; 4218 4219 mutex_lock(&memcg->thresholds_lock); 4220 4221 if (type == _MEM) { 4222 thresholds = &memcg->thresholds; 4223 usage = mem_cgroup_usage(memcg, false); 4224 } else if (type == _MEMSWAP) { 4225 thresholds = &memcg->memsw_thresholds; 4226 usage = mem_cgroup_usage(memcg, true); 4227 } else 4228 BUG(); 4229 4230 if (!thresholds->primary) 4231 goto unlock; 4232 4233 /* Check if a threshold crossed before removing */ 4234 __mem_cgroup_threshold(memcg, type == _MEMSWAP); 4235 4236 /* Calculate new number of threshold */ 4237 size = entries = 0; 4238 for (i = 0; i < thresholds->primary->size; i++) { 4239 if (thresholds->primary->entries[i].eventfd != eventfd) 4240 size++; 4241 else 4242 entries++; 4243 } 4244 4245 new = thresholds->spare; 4246 4247 /* If no items related to eventfd have been cleared, nothing to do */ 4248 if (!entries) 4249 goto unlock; 4250 4251 /* Set thresholds array to NULL if we don't have thresholds */ 4252 if (!size) { 4253 kfree(new); 4254 new = NULL; 4255 goto swap_buffers; 4256 } 4257 4258 new->size = size; 4259 4260 /* Copy thresholds and find current threshold */ 4261 new->current_threshold = -1; 4262 for (i = 0, j = 0; i < thresholds->primary->size; i++) { 4263 if (thresholds->primary->entries[i].eventfd == eventfd) 4264 continue; 4265 4266 new->entries[j] = thresholds->primary->entries[i]; 4267 if (new->entries[j].threshold <= usage) { 4268 /* 4269 * new->current_threshold will not be used 4270 * until rcu_assign_pointer(), so it's safe to increment 4271 * it here. 4272 */ 4273 ++new->current_threshold; 4274 } 4275 j++; 4276 } 4277 4278 swap_buffers: 4279 /* Swap primary and spare array */ 4280 thresholds->spare = thresholds->primary; 4281 4282 rcu_assign_pointer(thresholds->primary, new); 4283 4284 /* To be sure that nobody uses thresholds */ 4285 synchronize_rcu(); 4286 4287 /* If all events are unregistered, free the spare array */ 4288 if (!new) { 4289 kfree(thresholds->spare); 4290 thresholds->spare = NULL; 4291 } 4292 unlock: 4293 mutex_unlock(&memcg->thresholds_lock); 4294 } 4295 4296 static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg, 4297 struct eventfd_ctx *eventfd) 4298 { 4299 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM); 4300 } 4301 4302 static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg, 4303 struct eventfd_ctx *eventfd) 4304 { 4305 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP); 4306 } 4307 4308 static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg, 4309 struct eventfd_ctx *eventfd, const char *args) 4310 { 4311 struct mem_cgroup_eventfd_list *event; 4312 4313 event = kmalloc(sizeof(*event), GFP_KERNEL); 4314 if (!event) 4315 return -ENOMEM; 4316 4317 spin_lock(&memcg_oom_lock); 4318 4319 event->eventfd = eventfd; 4320 list_add(&event->list, &memcg->oom_notify); 4321 4322 /* already in OOM ? */ 4323 if (memcg->under_oom) 4324 eventfd_signal(eventfd, 1); 4325 spin_unlock(&memcg_oom_lock); 4326 4327 return 0; 4328 } 4329 4330 static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg, 4331 struct eventfd_ctx *eventfd) 4332 { 4333 struct mem_cgroup_eventfd_list *ev, *tmp; 4334 4335 spin_lock(&memcg_oom_lock); 4336 4337 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) { 4338 if (ev->eventfd == eventfd) { 4339 list_del(&ev->list); 4340 kfree(ev); 4341 } 4342 } 4343 4344 spin_unlock(&memcg_oom_lock); 4345 } 4346 4347 static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v) 4348 { 4349 struct mem_cgroup *memcg = mem_cgroup_from_seq(sf); 4350 4351 seq_printf(sf, "oom_kill_disable %d\n", memcg->oom_kill_disable); 4352 seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom); 4353 seq_printf(sf, "oom_kill %lu\n", 4354 atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL])); 4355 return 0; 4356 } 4357 4358 static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css, 4359 struct cftype *cft, u64 val) 4360 { 4361 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 4362 4363 /* cannot set to root cgroup and only 0 and 1 are allowed */ 4364 if (mem_cgroup_is_root(memcg) || !((val == 0) || (val == 1))) 4365 return -EINVAL; 4366 4367 memcg->oom_kill_disable = val; 4368 if (!val) 4369 memcg_oom_recover(memcg); 4370 4371 return 0; 4372 } 4373 4374 #ifdef CONFIG_CGROUP_WRITEBACK 4375 4376 #include <trace/events/writeback.h> 4377 4378 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp) 4379 { 4380 return wb_domain_init(&memcg->cgwb_domain, gfp); 4381 } 4382 4383 static void memcg_wb_domain_exit(struct mem_cgroup *memcg) 4384 { 4385 wb_domain_exit(&memcg->cgwb_domain); 4386 } 4387 4388 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg) 4389 { 4390 wb_domain_size_changed(&memcg->cgwb_domain); 4391 } 4392 4393 struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb) 4394 { 4395 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css); 4396 4397 if (!memcg->css.parent) 4398 return NULL; 4399 4400 return &memcg->cgwb_domain; 4401 } 4402 4403 /** 4404 * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg 4405 * @wb: bdi_writeback in question 4406 * @pfilepages: out parameter for number of file pages 4407 * @pheadroom: out parameter for number of allocatable pages according to memcg 4408 * @pdirty: out parameter for number of dirty pages 4409 * @pwriteback: out parameter for number of pages under writeback 4410 * 4411 * Determine the numbers of file, headroom, dirty, and writeback pages in 4412 * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom 4413 * is a bit more involved. 4414 * 4415 * A memcg's headroom is "min(max, high) - used". In the hierarchy, the 4416 * headroom is calculated as the lowest headroom of itself and the 4417 * ancestors. Note that this doesn't consider the actual amount of 4418 * available memory in the system. The caller should further cap 4419 * *@pheadroom accordingly. 4420 */ 4421 void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages, 4422 unsigned long *pheadroom, unsigned long *pdirty, 4423 unsigned long *pwriteback) 4424 { 4425 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css); 4426 struct mem_cgroup *parent; 4427 4428 mem_cgroup_flush_stats(); 4429 4430 *pdirty = memcg_page_state(memcg, NR_FILE_DIRTY); 4431 *pwriteback = memcg_page_state(memcg, NR_WRITEBACK); 4432 *pfilepages = memcg_page_state(memcg, NR_INACTIVE_FILE) + 4433 memcg_page_state(memcg, NR_ACTIVE_FILE); 4434 4435 *pheadroom = PAGE_COUNTER_MAX; 4436 while ((parent = parent_mem_cgroup(memcg))) { 4437 unsigned long ceiling = min(READ_ONCE(memcg->memory.max), 4438 READ_ONCE(memcg->memory.high)); 4439 unsigned long used = page_counter_read(&memcg->memory); 4440 4441 *pheadroom = min(*pheadroom, ceiling - min(ceiling, used)); 4442 memcg = parent; 4443 } 4444 } 4445 4446 /* 4447 * Foreign dirty flushing 4448 * 4449 * There's an inherent mismatch between memcg and writeback. The former 4450 * tracks ownership per-page while the latter per-inode. This was a 4451 * deliberate design decision because honoring per-page ownership in the 4452 * writeback path is complicated, may lead to higher CPU and IO overheads 4453 * and deemed unnecessary given that write-sharing an inode across 4454 * different cgroups isn't a common use-case. 4455 * 4456 * Combined with inode majority-writer ownership switching, this works well 4457 * enough in most cases but there are some pathological cases. For 4458 * example, let's say there are two cgroups A and B which keep writing to 4459 * different but confined parts of the same inode. B owns the inode and 4460 * A's memory is limited far below B's. A's dirty ratio can rise enough to 4461 * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid 4462 * triggering background writeback. A will be slowed down without a way to 4463 * make writeback of the dirty pages happen. 4464 * 4465 * Conditions like the above can lead to a cgroup getting repeatedly and 4466 * severely throttled after making some progress after each 4467 * dirty_expire_interval while the underlying IO device is almost 4468 * completely idle. 4469 * 4470 * Solving this problem completely requires matching the ownership tracking 4471 * granularities between memcg and writeback in either direction. However, 4472 * the more egregious behaviors can be avoided by simply remembering the 4473 * most recent foreign dirtying events and initiating remote flushes on 4474 * them when local writeback isn't enough to keep the memory clean enough. 4475 * 4476 * The following two functions implement such mechanism. When a foreign 4477 * page - a page whose memcg and writeback ownerships don't match - is 4478 * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning 4479 * bdi_writeback on the page owning memcg. When balance_dirty_pages() 4480 * decides that the memcg needs to sleep due to high dirty ratio, it calls 4481 * mem_cgroup_flush_foreign() which queues writeback on the recorded 4482 * foreign bdi_writebacks which haven't expired. Both the numbers of 4483 * recorded bdi_writebacks and concurrent in-flight foreign writebacks are 4484 * limited to MEMCG_CGWB_FRN_CNT. 4485 * 4486 * The mechanism only remembers IDs and doesn't hold any object references. 4487 * As being wrong occasionally doesn't matter, updates and accesses to the 4488 * records are lockless and racy. 4489 */ 4490 void mem_cgroup_track_foreign_dirty_slowpath(struct folio *folio, 4491 struct bdi_writeback *wb) 4492 { 4493 struct mem_cgroup *memcg = folio_memcg(folio); 4494 struct memcg_cgwb_frn *frn; 4495 u64 now = get_jiffies_64(); 4496 u64 oldest_at = now; 4497 int oldest = -1; 4498 int i; 4499 4500 trace_track_foreign_dirty(folio, wb); 4501 4502 /* 4503 * Pick the slot to use. If there is already a slot for @wb, keep 4504 * using it. If not replace the oldest one which isn't being 4505 * written out. 4506 */ 4507 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) { 4508 frn = &memcg->cgwb_frn[i]; 4509 if (frn->bdi_id == wb->bdi->id && 4510 frn->memcg_id == wb->memcg_css->id) 4511 break; 4512 if (time_before64(frn->at, oldest_at) && 4513 atomic_read(&frn->done.cnt) == 1) { 4514 oldest = i; 4515 oldest_at = frn->at; 4516 } 4517 } 4518 4519 if (i < MEMCG_CGWB_FRN_CNT) { 4520 /* 4521 * Re-using an existing one. Update timestamp lazily to 4522 * avoid making the cacheline hot. We want them to be 4523 * reasonably up-to-date and significantly shorter than 4524 * dirty_expire_interval as that's what expires the record. 4525 * Use the shorter of 1s and dirty_expire_interval / 8. 4526 */ 4527 unsigned long update_intv = 4528 min_t(unsigned long, HZ, 4529 msecs_to_jiffies(dirty_expire_interval * 10) / 8); 4530 4531 if (time_before64(frn->at, now - update_intv)) 4532 frn->at = now; 4533 } else if (oldest >= 0) { 4534 /* replace the oldest free one */ 4535 frn = &memcg->cgwb_frn[oldest]; 4536 frn->bdi_id = wb->bdi->id; 4537 frn->memcg_id = wb->memcg_css->id; 4538 frn->at = now; 4539 } 4540 } 4541 4542 /* issue foreign writeback flushes for recorded foreign dirtying events */ 4543 void mem_cgroup_flush_foreign(struct bdi_writeback *wb) 4544 { 4545 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css); 4546 unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10); 4547 u64 now = jiffies_64; 4548 int i; 4549 4550 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) { 4551 struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i]; 4552 4553 /* 4554 * If the record is older than dirty_expire_interval, 4555 * writeback on it has already started. No need to kick it 4556 * off again. Also, don't start a new one if there's 4557 * already one in flight. 4558 */ 4559 if (time_after64(frn->at, now - intv) && 4560 atomic_read(&frn->done.cnt) == 1) { 4561 frn->at = 0; 4562 trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id); 4563 cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id, 4564 WB_REASON_FOREIGN_FLUSH, 4565 &frn->done); 4566 } 4567 } 4568 } 4569 4570 #else /* CONFIG_CGROUP_WRITEBACK */ 4571 4572 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp) 4573 { 4574 return 0; 4575 } 4576 4577 static void memcg_wb_domain_exit(struct mem_cgroup *memcg) 4578 { 4579 } 4580 4581 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg) 4582 { 4583 } 4584 4585 #endif /* CONFIG_CGROUP_WRITEBACK */ 4586 4587 /* 4588 * DO NOT USE IN NEW FILES. 4589 * 4590 * "cgroup.event_control" implementation. 4591 * 4592 * This is way over-engineered. It tries to support fully configurable 4593 * events for each user. Such level of flexibility is completely 4594 * unnecessary especially in the light of the planned unified hierarchy. 4595 * 4596 * Please deprecate this and replace with something simpler if at all 4597 * possible. 4598 */ 4599 4600 /* 4601 * Unregister event and free resources. 4602 * 4603 * Gets called from workqueue. 4604 */ 4605 static void memcg_event_remove(struct work_struct *work) 4606 { 4607 struct mem_cgroup_event *event = 4608 container_of(work, struct mem_cgroup_event, remove); 4609 struct mem_cgroup *memcg = event->memcg; 4610 4611 remove_wait_queue(event->wqh, &event->wait); 4612 4613 event->unregister_event(memcg, event->eventfd); 4614 4615 /* Notify userspace the event is going away. */ 4616 eventfd_signal(event->eventfd, 1); 4617 4618 eventfd_ctx_put(event->eventfd); 4619 kfree(event); 4620 css_put(&memcg->css); 4621 } 4622 4623 /* 4624 * Gets called on EPOLLHUP on eventfd when user closes it. 4625 * 4626 * Called with wqh->lock held and interrupts disabled. 4627 */ 4628 static int memcg_event_wake(wait_queue_entry_t *wait, unsigned mode, 4629 int sync, void *key) 4630 { 4631 struct mem_cgroup_event *event = 4632 container_of(wait, struct mem_cgroup_event, wait); 4633 struct mem_cgroup *memcg = event->memcg; 4634 __poll_t flags = key_to_poll(key); 4635 4636 if (flags & EPOLLHUP) { 4637 /* 4638 * If the event has been detached at cgroup removal, we 4639 * can simply return knowing the other side will cleanup 4640 * for us. 4641 * 4642 * We can't race against event freeing since the other 4643 * side will require wqh->lock via remove_wait_queue(), 4644 * which we hold. 4645 */ 4646 spin_lock(&memcg->event_list_lock); 4647 if (!list_empty(&event->list)) { 4648 list_del_init(&event->list); 4649 /* 4650 * We are in atomic context, but cgroup_event_remove() 4651 * may sleep, so we have to call it in workqueue. 4652 */ 4653 schedule_work(&event->remove); 4654 } 4655 spin_unlock(&memcg->event_list_lock); 4656 } 4657 4658 return 0; 4659 } 4660 4661 static void memcg_event_ptable_queue_proc(struct file *file, 4662 wait_queue_head_t *wqh, poll_table *pt) 4663 { 4664 struct mem_cgroup_event *event = 4665 container_of(pt, struct mem_cgroup_event, pt); 4666 4667 event->wqh = wqh; 4668 add_wait_queue(wqh, &event->wait); 4669 } 4670 4671 /* 4672 * DO NOT USE IN NEW FILES. 4673 * 4674 * Parse input and register new cgroup event handler. 4675 * 4676 * Input must be in format '<event_fd> <control_fd> <args>'. 4677 * Interpretation of args is defined by control file implementation. 4678 */ 4679 static ssize_t memcg_write_event_control(struct kernfs_open_file *of, 4680 char *buf, size_t nbytes, loff_t off) 4681 { 4682 struct cgroup_subsys_state *css = of_css(of); 4683 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 4684 struct mem_cgroup_event *event; 4685 struct cgroup_subsys_state *cfile_css; 4686 unsigned int efd, cfd; 4687 struct fd efile; 4688 struct fd cfile; 4689 const char *name; 4690 char *endp; 4691 int ret; 4692 4693 if (IS_ENABLED(CONFIG_PREEMPT_RT)) 4694 return -EOPNOTSUPP; 4695 4696 buf = strstrip(buf); 4697 4698 efd = simple_strtoul(buf, &endp, 10); 4699 if (*endp != ' ') 4700 return -EINVAL; 4701 buf = endp + 1; 4702 4703 cfd = simple_strtoul(buf, &endp, 10); 4704 if ((*endp != ' ') && (*endp != '\0')) 4705 return -EINVAL; 4706 buf = endp + 1; 4707 4708 event = kzalloc(sizeof(*event), GFP_KERNEL); 4709 if (!event) 4710 return -ENOMEM; 4711 4712 event->memcg = memcg; 4713 INIT_LIST_HEAD(&event->list); 4714 init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc); 4715 init_waitqueue_func_entry(&event->wait, memcg_event_wake); 4716 INIT_WORK(&event->remove, memcg_event_remove); 4717 4718 efile = fdget(efd); 4719 if (!efile.file) { 4720 ret = -EBADF; 4721 goto out_kfree; 4722 } 4723 4724 event->eventfd = eventfd_ctx_fileget(efile.file); 4725 if (IS_ERR(event->eventfd)) { 4726 ret = PTR_ERR(event->eventfd); 4727 goto out_put_efile; 4728 } 4729 4730 cfile = fdget(cfd); 4731 if (!cfile.file) { 4732 ret = -EBADF; 4733 goto out_put_eventfd; 4734 } 4735 4736 /* the process need read permission on control file */ 4737 /* AV: shouldn't we check that it's been opened for read instead? */ 4738 ret = file_permission(cfile.file, MAY_READ); 4739 if (ret < 0) 4740 goto out_put_cfile; 4741 4742 /* 4743 * Determine the event callbacks and set them in @event. This used 4744 * to be done via struct cftype but cgroup core no longer knows 4745 * about these events. The following is crude but the whole thing 4746 * is for compatibility anyway. 4747 * 4748 * DO NOT ADD NEW FILES. 4749 */ 4750 name = cfile.file->f_path.dentry->d_name.name; 4751 4752 if (!strcmp(name, "memory.usage_in_bytes")) { 4753 event->register_event = mem_cgroup_usage_register_event; 4754 event->unregister_event = mem_cgroup_usage_unregister_event; 4755 } else if (!strcmp(name, "memory.oom_control")) { 4756 event->register_event = mem_cgroup_oom_register_event; 4757 event->unregister_event = mem_cgroup_oom_unregister_event; 4758 } else if (!strcmp(name, "memory.pressure_level")) { 4759 event->register_event = vmpressure_register_event; 4760 event->unregister_event = vmpressure_unregister_event; 4761 } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) { 4762 event->register_event = memsw_cgroup_usage_register_event; 4763 event->unregister_event = memsw_cgroup_usage_unregister_event; 4764 } else { 4765 ret = -EINVAL; 4766 goto out_put_cfile; 4767 } 4768 4769 /* 4770 * Verify @cfile should belong to @css. Also, remaining events are 4771 * automatically removed on cgroup destruction but the removal is 4772 * asynchronous, so take an extra ref on @css. 4773 */ 4774 cfile_css = css_tryget_online_from_dir(cfile.file->f_path.dentry->d_parent, 4775 &memory_cgrp_subsys); 4776 ret = -EINVAL; 4777 if (IS_ERR(cfile_css)) 4778 goto out_put_cfile; 4779 if (cfile_css != css) { 4780 css_put(cfile_css); 4781 goto out_put_cfile; 4782 } 4783 4784 ret = event->register_event(memcg, event->eventfd, buf); 4785 if (ret) 4786 goto out_put_css; 4787 4788 vfs_poll(efile.file, &event->pt); 4789 4790 spin_lock_irq(&memcg->event_list_lock); 4791 list_add(&event->list, &memcg->event_list); 4792 spin_unlock_irq(&memcg->event_list_lock); 4793 4794 fdput(cfile); 4795 fdput(efile); 4796 4797 return nbytes; 4798 4799 out_put_css: 4800 css_put(css); 4801 out_put_cfile: 4802 fdput(cfile); 4803 out_put_eventfd: 4804 eventfd_ctx_put(event->eventfd); 4805 out_put_efile: 4806 fdput(efile); 4807 out_kfree: 4808 kfree(event); 4809 4810 return ret; 4811 } 4812 4813 #if defined(CONFIG_MEMCG_KMEM) && (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG)) 4814 static int mem_cgroup_slab_show(struct seq_file *m, void *p) 4815 { 4816 /* 4817 * Deprecated. 4818 * Please, take a look at tools/cgroup/slabinfo.py . 4819 */ 4820 return 0; 4821 } 4822 #endif 4823 4824 static struct cftype mem_cgroup_legacy_files[] = { 4825 { 4826 .name = "usage_in_bytes", 4827 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE), 4828 .read_u64 = mem_cgroup_read_u64, 4829 }, 4830 { 4831 .name = "max_usage_in_bytes", 4832 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE), 4833 .write = mem_cgroup_reset, 4834 .read_u64 = mem_cgroup_read_u64, 4835 }, 4836 { 4837 .name = "limit_in_bytes", 4838 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT), 4839 .write = mem_cgroup_write, 4840 .read_u64 = mem_cgroup_read_u64, 4841 }, 4842 { 4843 .name = "soft_limit_in_bytes", 4844 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT), 4845 .write = mem_cgroup_write, 4846 .read_u64 = mem_cgroup_read_u64, 4847 }, 4848 { 4849 .name = "failcnt", 4850 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT), 4851 .write = mem_cgroup_reset, 4852 .read_u64 = mem_cgroup_read_u64, 4853 }, 4854 { 4855 .name = "stat", 4856 .seq_show = memcg_stat_show, 4857 }, 4858 { 4859 .name = "force_empty", 4860 .write = mem_cgroup_force_empty_write, 4861 }, 4862 { 4863 .name = "use_hierarchy", 4864 .write_u64 = mem_cgroup_hierarchy_write, 4865 .read_u64 = mem_cgroup_hierarchy_read, 4866 }, 4867 { 4868 .name = "cgroup.event_control", /* XXX: for compat */ 4869 .write = memcg_write_event_control, 4870 .flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE, 4871 }, 4872 { 4873 .name = "swappiness", 4874 .read_u64 = mem_cgroup_swappiness_read, 4875 .write_u64 = mem_cgroup_swappiness_write, 4876 }, 4877 { 4878 .name = "move_charge_at_immigrate", 4879 .read_u64 = mem_cgroup_move_charge_read, 4880 .write_u64 = mem_cgroup_move_charge_write, 4881 }, 4882 { 4883 .name = "oom_control", 4884 .seq_show = mem_cgroup_oom_control_read, 4885 .write_u64 = mem_cgroup_oom_control_write, 4886 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL), 4887 }, 4888 { 4889 .name = "pressure_level", 4890 }, 4891 #ifdef CONFIG_NUMA 4892 { 4893 .name = "numa_stat", 4894 .seq_show = memcg_numa_stat_show, 4895 }, 4896 #endif 4897 { 4898 .name = "kmem.limit_in_bytes", 4899 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT), 4900 .write = mem_cgroup_write, 4901 .read_u64 = mem_cgroup_read_u64, 4902 }, 4903 { 4904 .name = "kmem.usage_in_bytes", 4905 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE), 4906 .read_u64 = mem_cgroup_read_u64, 4907 }, 4908 { 4909 .name = "kmem.failcnt", 4910 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT), 4911 .write = mem_cgroup_reset, 4912 .read_u64 = mem_cgroup_read_u64, 4913 }, 4914 { 4915 .name = "kmem.max_usage_in_bytes", 4916 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE), 4917 .write = mem_cgroup_reset, 4918 .read_u64 = mem_cgroup_read_u64, 4919 }, 4920 #if defined(CONFIG_MEMCG_KMEM) && \ 4921 (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG)) 4922 { 4923 .name = "kmem.slabinfo", 4924 .seq_show = mem_cgroup_slab_show, 4925 }, 4926 #endif 4927 { 4928 .name = "kmem.tcp.limit_in_bytes", 4929 .private = MEMFILE_PRIVATE(_TCP, RES_LIMIT), 4930 .write = mem_cgroup_write, 4931 .read_u64 = mem_cgroup_read_u64, 4932 }, 4933 { 4934 .name = "kmem.tcp.usage_in_bytes", 4935 .private = MEMFILE_PRIVATE(_TCP, RES_USAGE), 4936 .read_u64 = mem_cgroup_read_u64, 4937 }, 4938 { 4939 .name = "kmem.tcp.failcnt", 4940 .private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT), 4941 .write = mem_cgroup_reset, 4942 .read_u64 = mem_cgroup_read_u64, 4943 }, 4944 { 4945 .name = "kmem.tcp.max_usage_in_bytes", 4946 .private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE), 4947 .write = mem_cgroup_reset, 4948 .read_u64 = mem_cgroup_read_u64, 4949 }, 4950 { }, /* terminate */ 4951 }; 4952 4953 /* 4954 * Private memory cgroup IDR 4955 * 4956 * Swap-out records and page cache shadow entries need to store memcg 4957 * references in constrained space, so we maintain an ID space that is 4958 * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of 4959 * memory-controlled cgroups to 64k. 4960 * 4961 * However, there usually are many references to the offline CSS after 4962 * the cgroup has been destroyed, such as page cache or reclaimable 4963 * slab objects, that don't need to hang on to the ID. We want to keep 4964 * those dead CSS from occupying IDs, or we might quickly exhaust the 4965 * relatively small ID space and prevent the creation of new cgroups 4966 * even when there are much fewer than 64k cgroups - possibly none. 4967 * 4968 * Maintain a private 16-bit ID space for memcg, and allow the ID to 4969 * be freed and recycled when it's no longer needed, which is usually 4970 * when the CSS is offlined. 4971 * 4972 * The only exception to that are records of swapped out tmpfs/shmem 4973 * pages that need to be attributed to live ancestors on swapin. But 4974 * those references are manageable from userspace. 4975 */ 4976 4977 static DEFINE_IDR(mem_cgroup_idr); 4978 4979 static void mem_cgroup_id_remove(struct mem_cgroup *memcg) 4980 { 4981 if (memcg->id.id > 0) { 4982 idr_remove(&mem_cgroup_idr, memcg->id.id); 4983 memcg->id.id = 0; 4984 } 4985 } 4986 4987 static void __maybe_unused mem_cgroup_id_get_many(struct mem_cgroup *memcg, 4988 unsigned int n) 4989 { 4990 refcount_add(n, &memcg->id.ref); 4991 } 4992 4993 static void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n) 4994 { 4995 if (refcount_sub_and_test(n, &memcg->id.ref)) { 4996 mem_cgroup_id_remove(memcg); 4997 4998 /* Memcg ID pins CSS */ 4999 css_put(&memcg->css); 5000 } 5001 } 5002 5003 static inline void mem_cgroup_id_put(struct mem_cgroup *memcg) 5004 { 5005 mem_cgroup_id_put_many(memcg, 1); 5006 } 5007 5008 /** 5009 * mem_cgroup_from_id - look up a memcg from a memcg id 5010 * @id: the memcg id to look up 5011 * 5012 * Caller must hold rcu_read_lock(). 5013 */ 5014 struct mem_cgroup *mem_cgroup_from_id(unsigned short id) 5015 { 5016 WARN_ON_ONCE(!rcu_read_lock_held()); 5017 return idr_find(&mem_cgroup_idr, id); 5018 } 5019 5020 static int alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node) 5021 { 5022 struct mem_cgroup_per_node *pn; 5023 int tmp = node; 5024 /* 5025 * This routine is called against possible nodes. 5026 * But it's BUG to call kmalloc() against offline node. 5027 * 5028 * TODO: this routine can waste much memory for nodes which will 5029 * never be onlined. It's better to use memory hotplug callback 5030 * function. 5031 */ 5032 if (!node_state(node, N_NORMAL_MEMORY)) 5033 tmp = -1; 5034 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp); 5035 if (!pn) 5036 return 1; 5037 5038 pn->lruvec_stats_percpu = alloc_percpu_gfp(struct lruvec_stats_percpu, 5039 GFP_KERNEL_ACCOUNT); 5040 if (!pn->lruvec_stats_percpu) { 5041 kfree(pn); 5042 return 1; 5043 } 5044 5045 lruvec_init(&pn->lruvec); 5046 pn->memcg = memcg; 5047 5048 memcg->nodeinfo[node] = pn; 5049 return 0; 5050 } 5051 5052 static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node) 5053 { 5054 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node]; 5055 5056 if (!pn) 5057 return; 5058 5059 free_percpu(pn->lruvec_stats_percpu); 5060 kfree(pn); 5061 } 5062 5063 static void __mem_cgroup_free(struct mem_cgroup *memcg) 5064 { 5065 int node; 5066 5067 for_each_node(node) 5068 free_mem_cgroup_per_node_info(memcg, node); 5069 free_percpu(memcg->vmstats_percpu); 5070 kfree(memcg); 5071 } 5072 5073 static void mem_cgroup_free(struct mem_cgroup *memcg) 5074 { 5075 memcg_wb_domain_exit(memcg); 5076 __mem_cgroup_free(memcg); 5077 } 5078 5079 static struct mem_cgroup *mem_cgroup_alloc(void) 5080 { 5081 struct mem_cgroup *memcg; 5082 int node; 5083 int __maybe_unused i; 5084 long error = -ENOMEM; 5085 5086 memcg = kzalloc(struct_size(memcg, nodeinfo, nr_node_ids), GFP_KERNEL); 5087 if (!memcg) 5088 return ERR_PTR(error); 5089 5090 memcg->id.id = idr_alloc(&mem_cgroup_idr, NULL, 5091 1, MEM_CGROUP_ID_MAX + 1, GFP_KERNEL); 5092 if (memcg->id.id < 0) { 5093 error = memcg->id.id; 5094 goto fail; 5095 } 5096 5097 memcg->vmstats_percpu = alloc_percpu_gfp(struct memcg_vmstats_percpu, 5098 GFP_KERNEL_ACCOUNT); 5099 if (!memcg->vmstats_percpu) 5100 goto fail; 5101 5102 for_each_node(node) 5103 if (alloc_mem_cgroup_per_node_info(memcg, node)) 5104 goto fail; 5105 5106 if (memcg_wb_domain_init(memcg, GFP_KERNEL)) 5107 goto fail; 5108 5109 INIT_WORK(&memcg->high_work, high_work_func); 5110 INIT_LIST_HEAD(&memcg->oom_notify); 5111 mutex_init(&memcg->thresholds_lock); 5112 spin_lock_init(&memcg->move_lock); 5113 vmpressure_init(&memcg->vmpressure); 5114 INIT_LIST_HEAD(&memcg->event_list); 5115 spin_lock_init(&memcg->event_list_lock); 5116 memcg->socket_pressure = jiffies; 5117 #ifdef CONFIG_MEMCG_KMEM 5118 memcg->kmemcg_id = -1; 5119 INIT_LIST_HEAD(&memcg->objcg_list); 5120 #endif 5121 #ifdef CONFIG_CGROUP_WRITEBACK 5122 INIT_LIST_HEAD(&memcg->cgwb_list); 5123 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) 5124 memcg->cgwb_frn[i].done = 5125 __WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq); 5126 #endif 5127 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 5128 spin_lock_init(&memcg->deferred_split_queue.split_queue_lock); 5129 INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue); 5130 memcg->deferred_split_queue.split_queue_len = 0; 5131 #endif 5132 idr_replace(&mem_cgroup_idr, memcg, memcg->id.id); 5133 return memcg; 5134 fail: 5135 mem_cgroup_id_remove(memcg); 5136 __mem_cgroup_free(memcg); 5137 return ERR_PTR(error); 5138 } 5139 5140 static struct cgroup_subsys_state * __ref 5141 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css) 5142 { 5143 struct mem_cgroup *parent = mem_cgroup_from_css(parent_css); 5144 struct mem_cgroup *memcg, *old_memcg; 5145 5146 old_memcg = set_active_memcg(parent); 5147 memcg = mem_cgroup_alloc(); 5148 set_active_memcg(old_memcg); 5149 if (IS_ERR(memcg)) 5150 return ERR_CAST(memcg); 5151 5152 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX); 5153 memcg->soft_limit = PAGE_COUNTER_MAX; 5154 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX); 5155 if (parent) { 5156 memcg->swappiness = mem_cgroup_swappiness(parent); 5157 memcg->oom_kill_disable = parent->oom_kill_disable; 5158 5159 page_counter_init(&memcg->memory, &parent->memory); 5160 page_counter_init(&memcg->swap, &parent->swap); 5161 page_counter_init(&memcg->kmem, &parent->kmem); 5162 page_counter_init(&memcg->tcpmem, &parent->tcpmem); 5163 } else { 5164 page_counter_init(&memcg->memory, NULL); 5165 page_counter_init(&memcg->swap, NULL); 5166 page_counter_init(&memcg->kmem, NULL); 5167 page_counter_init(&memcg->tcpmem, NULL); 5168 5169 root_mem_cgroup = memcg; 5170 return &memcg->css; 5171 } 5172 5173 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket) 5174 static_branch_inc(&memcg_sockets_enabled_key); 5175 5176 return &memcg->css; 5177 } 5178 5179 static int mem_cgroup_css_online(struct cgroup_subsys_state *css) 5180 { 5181 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 5182 5183 if (memcg_online_kmem(memcg)) 5184 goto remove_id; 5185 5186 /* 5187 * A memcg must be visible for expand_shrinker_info() 5188 * by the time the maps are allocated. So, we allocate maps 5189 * here, when for_each_mem_cgroup() can't skip it. 5190 */ 5191 if (alloc_shrinker_info(memcg)) 5192 goto offline_kmem; 5193 5194 /* Online state pins memcg ID, memcg ID pins CSS */ 5195 refcount_set(&memcg->id.ref, 1); 5196 css_get(css); 5197 5198 if (unlikely(mem_cgroup_is_root(memcg))) 5199 queue_delayed_work(system_unbound_wq, &stats_flush_dwork, 5200 2UL*HZ); 5201 return 0; 5202 offline_kmem: 5203 memcg_offline_kmem(memcg); 5204 remove_id: 5205 mem_cgroup_id_remove(memcg); 5206 return -ENOMEM; 5207 } 5208 5209 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css) 5210 { 5211 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 5212 struct mem_cgroup_event *event, *tmp; 5213 5214 /* 5215 * Unregister events and notify userspace. 5216 * Notify userspace about cgroup removing only after rmdir of cgroup 5217 * directory to avoid race between userspace and kernelspace. 5218 */ 5219 spin_lock_irq(&memcg->event_list_lock); 5220 list_for_each_entry_safe(event, tmp, &memcg->event_list, list) { 5221 list_del_init(&event->list); 5222 schedule_work(&event->remove); 5223 } 5224 spin_unlock_irq(&memcg->event_list_lock); 5225 5226 page_counter_set_min(&memcg->memory, 0); 5227 page_counter_set_low(&memcg->memory, 0); 5228 5229 memcg_offline_kmem(memcg); 5230 reparent_shrinker_deferred(memcg); 5231 wb_memcg_offline(memcg); 5232 5233 drain_all_stock(memcg); 5234 5235 mem_cgroup_id_put(memcg); 5236 } 5237 5238 static void mem_cgroup_css_released(struct cgroup_subsys_state *css) 5239 { 5240 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 5241 5242 invalidate_reclaim_iterators(memcg); 5243 } 5244 5245 static void mem_cgroup_css_free(struct cgroup_subsys_state *css) 5246 { 5247 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 5248 int __maybe_unused i; 5249 5250 #ifdef CONFIG_CGROUP_WRITEBACK 5251 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) 5252 wb_wait_for_completion(&memcg->cgwb_frn[i].done); 5253 #endif 5254 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket) 5255 static_branch_dec(&memcg_sockets_enabled_key); 5256 5257 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg->tcpmem_active) 5258 static_branch_dec(&memcg_sockets_enabled_key); 5259 5260 vmpressure_cleanup(&memcg->vmpressure); 5261 cancel_work_sync(&memcg->high_work); 5262 mem_cgroup_remove_from_trees(memcg); 5263 free_shrinker_info(memcg); 5264 mem_cgroup_free(memcg); 5265 } 5266 5267 /** 5268 * mem_cgroup_css_reset - reset the states of a mem_cgroup 5269 * @css: the target css 5270 * 5271 * Reset the states of the mem_cgroup associated with @css. This is 5272 * invoked when the userland requests disabling on the default hierarchy 5273 * but the memcg is pinned through dependency. The memcg should stop 5274 * applying policies and should revert to the vanilla state as it may be 5275 * made visible again. 5276 * 5277 * The current implementation only resets the essential configurations. 5278 * This needs to be expanded to cover all the visible parts. 5279 */ 5280 static void mem_cgroup_css_reset(struct cgroup_subsys_state *css) 5281 { 5282 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 5283 5284 page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX); 5285 page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX); 5286 page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX); 5287 page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX); 5288 page_counter_set_min(&memcg->memory, 0); 5289 page_counter_set_low(&memcg->memory, 0); 5290 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX); 5291 memcg->soft_limit = PAGE_COUNTER_MAX; 5292 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX); 5293 memcg_wb_domain_size_changed(memcg); 5294 } 5295 5296 static void mem_cgroup_css_rstat_flush(struct cgroup_subsys_state *css, int cpu) 5297 { 5298 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 5299 struct mem_cgroup *parent = parent_mem_cgroup(memcg); 5300 struct memcg_vmstats_percpu *statc; 5301 long delta, v; 5302 int i, nid; 5303 5304 statc = per_cpu_ptr(memcg->vmstats_percpu, cpu); 5305 5306 for (i = 0; i < MEMCG_NR_STAT; i++) { 5307 /* 5308 * Collect the aggregated propagation counts of groups 5309 * below us. We're in a per-cpu loop here and this is 5310 * a global counter, so the first cycle will get them. 5311 */ 5312 delta = memcg->vmstats.state_pending[i]; 5313 if (delta) 5314 memcg->vmstats.state_pending[i] = 0; 5315 5316 /* Add CPU changes on this level since the last flush */ 5317 v = READ_ONCE(statc->state[i]); 5318 if (v != statc->state_prev[i]) { 5319 delta += v - statc->state_prev[i]; 5320 statc->state_prev[i] = v; 5321 } 5322 5323 if (!delta) 5324 continue; 5325 5326 /* Aggregate counts on this level and propagate upwards */ 5327 memcg->vmstats.state[i] += delta; 5328 if (parent) 5329 parent->vmstats.state_pending[i] += delta; 5330 } 5331 5332 for (i = 0; i < NR_VM_EVENT_ITEMS; i++) { 5333 delta = memcg->vmstats.events_pending[i]; 5334 if (delta) 5335 memcg->vmstats.events_pending[i] = 0; 5336 5337 v = READ_ONCE(statc->events[i]); 5338 if (v != statc->events_prev[i]) { 5339 delta += v - statc->events_prev[i]; 5340 statc->events_prev[i] = v; 5341 } 5342 5343 if (!delta) 5344 continue; 5345 5346 memcg->vmstats.events[i] += delta; 5347 if (parent) 5348 parent->vmstats.events_pending[i] += delta; 5349 } 5350 5351 for_each_node_state(nid, N_MEMORY) { 5352 struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid]; 5353 struct mem_cgroup_per_node *ppn = NULL; 5354 struct lruvec_stats_percpu *lstatc; 5355 5356 if (parent) 5357 ppn = parent->nodeinfo[nid]; 5358 5359 lstatc = per_cpu_ptr(pn->lruvec_stats_percpu, cpu); 5360 5361 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++) { 5362 delta = pn->lruvec_stats.state_pending[i]; 5363 if (delta) 5364 pn->lruvec_stats.state_pending[i] = 0; 5365 5366 v = READ_ONCE(lstatc->state[i]); 5367 if (v != lstatc->state_prev[i]) { 5368 delta += v - lstatc->state_prev[i]; 5369 lstatc->state_prev[i] = v; 5370 } 5371 5372 if (!delta) 5373 continue; 5374 5375 pn->lruvec_stats.state[i] += delta; 5376 if (ppn) 5377 ppn->lruvec_stats.state_pending[i] += delta; 5378 } 5379 } 5380 } 5381 5382 #ifdef CONFIG_MMU 5383 /* Handlers for move charge at task migration. */ 5384 static int mem_cgroup_do_precharge(unsigned long count) 5385 { 5386 int ret; 5387 5388 /* Try a single bulk charge without reclaim first, kswapd may wake */ 5389 ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count); 5390 if (!ret) { 5391 mc.precharge += count; 5392 return ret; 5393 } 5394 5395 /* Try charges one by one with reclaim, but do not retry */ 5396 while (count--) { 5397 ret = try_charge(mc.to, GFP_KERNEL | __GFP_NORETRY, 1); 5398 if (ret) 5399 return ret; 5400 mc.precharge++; 5401 cond_resched(); 5402 } 5403 return 0; 5404 } 5405 5406 union mc_target { 5407 struct page *page; 5408 swp_entry_t ent; 5409 }; 5410 5411 enum mc_target_type { 5412 MC_TARGET_NONE = 0, 5413 MC_TARGET_PAGE, 5414 MC_TARGET_SWAP, 5415 MC_TARGET_DEVICE, 5416 }; 5417 5418 static struct page *mc_handle_present_pte(struct vm_area_struct *vma, 5419 unsigned long addr, pte_t ptent) 5420 { 5421 struct page *page = vm_normal_page(vma, addr, ptent); 5422 5423 if (!page || !page_mapped(page)) 5424 return NULL; 5425 if (PageAnon(page)) { 5426 if (!(mc.flags & MOVE_ANON)) 5427 return NULL; 5428 } else { 5429 if (!(mc.flags & MOVE_FILE)) 5430 return NULL; 5431 } 5432 if (!get_page_unless_zero(page)) 5433 return NULL; 5434 5435 return page; 5436 } 5437 5438 #if defined(CONFIG_SWAP) || defined(CONFIG_DEVICE_PRIVATE) 5439 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma, 5440 pte_t ptent, swp_entry_t *entry) 5441 { 5442 struct page *page = NULL; 5443 swp_entry_t ent = pte_to_swp_entry(ptent); 5444 5445 if (!(mc.flags & MOVE_ANON)) 5446 return NULL; 5447 5448 /* 5449 * Handle MEMORY_DEVICE_PRIVATE which are ZONE_DEVICE page belonging to 5450 * a device and because they are not accessible by CPU they are store 5451 * as special swap entry in the CPU page table. 5452 */ 5453 if (is_device_private_entry(ent)) { 5454 page = pfn_swap_entry_to_page(ent); 5455 /* 5456 * MEMORY_DEVICE_PRIVATE means ZONE_DEVICE page and which have 5457 * a refcount of 1 when free (unlike normal page) 5458 */ 5459 if (!page_ref_add_unless(page, 1, 1)) 5460 return NULL; 5461 return page; 5462 } 5463 5464 if (non_swap_entry(ent)) 5465 return NULL; 5466 5467 /* 5468 * Because lookup_swap_cache() updates some statistics counter, 5469 * we call find_get_page() with swapper_space directly. 5470 */ 5471 page = find_get_page(swap_address_space(ent), swp_offset(ent)); 5472 entry->val = ent.val; 5473 5474 return page; 5475 } 5476 #else 5477 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma, 5478 pte_t ptent, swp_entry_t *entry) 5479 { 5480 return NULL; 5481 } 5482 #endif 5483 5484 static struct page *mc_handle_file_pte(struct vm_area_struct *vma, 5485 unsigned long addr, pte_t ptent) 5486 { 5487 if (!vma->vm_file) /* anonymous vma */ 5488 return NULL; 5489 if (!(mc.flags & MOVE_FILE)) 5490 return NULL; 5491 5492 /* page is moved even if it's not RSS of this task(page-faulted). */ 5493 /* shmem/tmpfs may report page out on swap: account for that too. */ 5494 return find_get_incore_page(vma->vm_file->f_mapping, 5495 linear_page_index(vma, addr)); 5496 } 5497 5498 /** 5499 * mem_cgroup_move_account - move account of the page 5500 * @page: the page 5501 * @compound: charge the page as compound or small page 5502 * @from: mem_cgroup which the page is moved from. 5503 * @to: mem_cgroup which the page is moved to. @from != @to. 5504 * 5505 * The caller must make sure the page is not on LRU (isolate_page() is useful.) 5506 * 5507 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge" 5508 * from old cgroup. 5509 */ 5510 static int mem_cgroup_move_account(struct page *page, 5511 bool compound, 5512 struct mem_cgroup *from, 5513 struct mem_cgroup *to) 5514 { 5515 struct folio *folio = page_folio(page); 5516 struct lruvec *from_vec, *to_vec; 5517 struct pglist_data *pgdat; 5518 unsigned int nr_pages = compound ? folio_nr_pages(folio) : 1; 5519 int nid, ret; 5520 5521 VM_BUG_ON(from == to); 5522 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio); 5523 VM_BUG_ON(compound && !folio_test_large(folio)); 5524 5525 /* 5526 * Prevent mem_cgroup_migrate() from looking at 5527 * page's memory cgroup of its source page while we change it. 5528 */ 5529 ret = -EBUSY; 5530 if (!folio_trylock(folio)) 5531 goto out; 5532 5533 ret = -EINVAL; 5534 if (folio_memcg(folio) != from) 5535 goto out_unlock; 5536 5537 pgdat = folio_pgdat(folio); 5538 from_vec = mem_cgroup_lruvec(from, pgdat); 5539 to_vec = mem_cgroup_lruvec(to, pgdat); 5540 5541 folio_memcg_lock(folio); 5542 5543 if (folio_test_anon(folio)) { 5544 if (folio_mapped(folio)) { 5545 __mod_lruvec_state(from_vec, NR_ANON_MAPPED, -nr_pages); 5546 __mod_lruvec_state(to_vec, NR_ANON_MAPPED, nr_pages); 5547 if (folio_test_transhuge(folio)) { 5548 __mod_lruvec_state(from_vec, NR_ANON_THPS, 5549 -nr_pages); 5550 __mod_lruvec_state(to_vec, NR_ANON_THPS, 5551 nr_pages); 5552 } 5553 } 5554 } else { 5555 __mod_lruvec_state(from_vec, NR_FILE_PAGES, -nr_pages); 5556 __mod_lruvec_state(to_vec, NR_FILE_PAGES, nr_pages); 5557 5558 if (folio_test_swapbacked(folio)) { 5559 __mod_lruvec_state(from_vec, NR_SHMEM, -nr_pages); 5560 __mod_lruvec_state(to_vec, NR_SHMEM, nr_pages); 5561 } 5562 5563 if (folio_mapped(folio)) { 5564 __mod_lruvec_state(from_vec, NR_FILE_MAPPED, -nr_pages); 5565 __mod_lruvec_state(to_vec, NR_FILE_MAPPED, nr_pages); 5566 } 5567 5568 if (folio_test_dirty(folio)) { 5569 struct address_space *mapping = folio_mapping(folio); 5570 5571 if (mapping_can_writeback(mapping)) { 5572 __mod_lruvec_state(from_vec, NR_FILE_DIRTY, 5573 -nr_pages); 5574 __mod_lruvec_state(to_vec, NR_FILE_DIRTY, 5575 nr_pages); 5576 } 5577 } 5578 } 5579 5580 if (folio_test_writeback(folio)) { 5581 __mod_lruvec_state(from_vec, NR_WRITEBACK, -nr_pages); 5582 __mod_lruvec_state(to_vec, NR_WRITEBACK, nr_pages); 5583 } 5584 5585 /* 5586 * All state has been migrated, let's switch to the new memcg. 5587 * 5588 * It is safe to change page's memcg here because the page 5589 * is referenced, charged, isolated, and locked: we can't race 5590 * with (un)charging, migration, LRU putback, or anything else 5591 * that would rely on a stable page's memory cgroup. 5592 * 5593 * Note that lock_page_memcg is a memcg lock, not a page lock, 5594 * to save space. As soon as we switch page's memory cgroup to a 5595 * new memcg that isn't locked, the above state can change 5596 * concurrently again. Make sure we're truly done with it. 5597 */ 5598 smp_mb(); 5599 5600 css_get(&to->css); 5601 css_put(&from->css); 5602 5603 folio->memcg_data = (unsigned long)to; 5604 5605 __folio_memcg_unlock(from); 5606 5607 ret = 0; 5608 nid = folio_nid(folio); 5609 5610 local_irq_disable(); 5611 mem_cgroup_charge_statistics(to, nr_pages); 5612 memcg_check_events(to, nid); 5613 mem_cgroup_charge_statistics(from, -nr_pages); 5614 memcg_check_events(from, nid); 5615 local_irq_enable(); 5616 out_unlock: 5617 folio_unlock(folio); 5618 out: 5619 return ret; 5620 } 5621 5622 /** 5623 * get_mctgt_type - get target type of moving charge 5624 * @vma: the vma the pte to be checked belongs 5625 * @addr: the address corresponding to the pte to be checked 5626 * @ptent: the pte to be checked 5627 * @target: the pointer the target page or swap ent will be stored(can be NULL) 5628 * 5629 * Returns 5630 * 0(MC_TARGET_NONE): if the pte is not a target for move charge. 5631 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for 5632 * move charge. if @target is not NULL, the page is stored in target->page 5633 * with extra refcnt got(Callers should handle it). 5634 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a 5635 * target for charge migration. if @target is not NULL, the entry is stored 5636 * in target->ent. 5637 * 3(MC_TARGET_DEVICE): like MC_TARGET_PAGE but page is MEMORY_DEVICE_PRIVATE 5638 * (so ZONE_DEVICE page and thus not on the lru). 5639 * For now we such page is charge like a regular page would be as for all 5640 * intent and purposes it is just special memory taking the place of a 5641 * regular page. 5642 * 5643 * See Documentations/vm/hmm.txt and include/linux/hmm.h 5644 * 5645 * Called with pte lock held. 5646 */ 5647 5648 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma, 5649 unsigned long addr, pte_t ptent, union mc_target *target) 5650 { 5651 struct page *page = NULL; 5652 enum mc_target_type ret = MC_TARGET_NONE; 5653 swp_entry_t ent = { .val = 0 }; 5654 5655 if (pte_present(ptent)) 5656 page = mc_handle_present_pte(vma, addr, ptent); 5657 else if (is_swap_pte(ptent)) 5658 page = mc_handle_swap_pte(vma, ptent, &ent); 5659 else if (pte_none(ptent)) 5660 page = mc_handle_file_pte(vma, addr, ptent); 5661 5662 if (!page && !ent.val) 5663 return ret; 5664 if (page) { 5665 /* 5666 * Do only loose check w/o serialization. 5667 * mem_cgroup_move_account() checks the page is valid or 5668 * not under LRU exclusion. 5669 */ 5670 if (page_memcg(page) == mc.from) { 5671 ret = MC_TARGET_PAGE; 5672 if (is_device_private_page(page)) 5673 ret = MC_TARGET_DEVICE; 5674 if (target) 5675 target->page = page; 5676 } 5677 if (!ret || !target) 5678 put_page(page); 5679 } 5680 /* 5681 * There is a swap entry and a page doesn't exist or isn't charged. 5682 * But we cannot move a tail-page in a THP. 5683 */ 5684 if (ent.val && !ret && (!page || !PageTransCompound(page)) && 5685 mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) { 5686 ret = MC_TARGET_SWAP; 5687 if (target) 5688 target->ent = ent; 5689 } 5690 return ret; 5691 } 5692 5693 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 5694 /* 5695 * We don't consider PMD mapped swapping or file mapped pages because THP does 5696 * not support them for now. 5697 * Caller should make sure that pmd_trans_huge(pmd) is true. 5698 */ 5699 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma, 5700 unsigned long addr, pmd_t pmd, union mc_target *target) 5701 { 5702 struct page *page = NULL; 5703 enum mc_target_type ret = MC_TARGET_NONE; 5704 5705 if (unlikely(is_swap_pmd(pmd))) { 5706 VM_BUG_ON(thp_migration_supported() && 5707 !is_pmd_migration_entry(pmd)); 5708 return ret; 5709 } 5710 page = pmd_page(pmd); 5711 VM_BUG_ON_PAGE(!page || !PageHead(page), page); 5712 if (!(mc.flags & MOVE_ANON)) 5713 return ret; 5714 if (page_memcg(page) == mc.from) { 5715 ret = MC_TARGET_PAGE; 5716 if (target) { 5717 get_page(page); 5718 target->page = page; 5719 } 5720 } 5721 return ret; 5722 } 5723 #else 5724 static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma, 5725 unsigned long addr, pmd_t pmd, union mc_target *target) 5726 { 5727 return MC_TARGET_NONE; 5728 } 5729 #endif 5730 5731 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd, 5732 unsigned long addr, unsigned long end, 5733 struct mm_walk *walk) 5734 { 5735 struct vm_area_struct *vma = walk->vma; 5736 pte_t *pte; 5737 spinlock_t *ptl; 5738 5739 ptl = pmd_trans_huge_lock(pmd, vma); 5740 if (ptl) { 5741 /* 5742 * Note their can not be MC_TARGET_DEVICE for now as we do not 5743 * support transparent huge page with MEMORY_DEVICE_PRIVATE but 5744 * this might change. 5745 */ 5746 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE) 5747 mc.precharge += HPAGE_PMD_NR; 5748 spin_unlock(ptl); 5749 return 0; 5750 } 5751 5752 if (pmd_trans_unstable(pmd)) 5753 return 0; 5754 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl); 5755 for (; addr != end; pte++, addr += PAGE_SIZE) 5756 if (get_mctgt_type(vma, addr, *pte, NULL)) 5757 mc.precharge++; /* increment precharge temporarily */ 5758 pte_unmap_unlock(pte - 1, ptl); 5759 cond_resched(); 5760 5761 return 0; 5762 } 5763 5764 static const struct mm_walk_ops precharge_walk_ops = { 5765 .pmd_entry = mem_cgroup_count_precharge_pte_range, 5766 }; 5767 5768 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm) 5769 { 5770 unsigned long precharge; 5771 5772 mmap_read_lock(mm); 5773 walk_page_range(mm, 0, mm->highest_vm_end, &precharge_walk_ops, NULL); 5774 mmap_read_unlock(mm); 5775 5776 precharge = mc.precharge; 5777 mc.precharge = 0; 5778 5779 return precharge; 5780 } 5781 5782 static int mem_cgroup_precharge_mc(struct mm_struct *mm) 5783 { 5784 unsigned long precharge = mem_cgroup_count_precharge(mm); 5785 5786 VM_BUG_ON(mc.moving_task); 5787 mc.moving_task = current; 5788 return mem_cgroup_do_precharge(precharge); 5789 } 5790 5791 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */ 5792 static void __mem_cgroup_clear_mc(void) 5793 { 5794 struct mem_cgroup *from = mc.from; 5795 struct mem_cgroup *to = mc.to; 5796 5797 /* we must uncharge all the leftover precharges from mc.to */ 5798 if (mc.precharge) { 5799 cancel_charge(mc.to, mc.precharge); 5800 mc.precharge = 0; 5801 } 5802 /* 5803 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so 5804 * we must uncharge here. 5805 */ 5806 if (mc.moved_charge) { 5807 cancel_charge(mc.from, mc.moved_charge); 5808 mc.moved_charge = 0; 5809 } 5810 /* we must fixup refcnts and charges */ 5811 if (mc.moved_swap) { 5812 /* uncharge swap account from the old cgroup */ 5813 if (!mem_cgroup_is_root(mc.from)) 5814 page_counter_uncharge(&mc.from->memsw, mc.moved_swap); 5815 5816 mem_cgroup_id_put_many(mc.from, mc.moved_swap); 5817 5818 /* 5819 * we charged both to->memory and to->memsw, so we 5820 * should uncharge to->memory. 5821 */ 5822 if (!mem_cgroup_is_root(mc.to)) 5823 page_counter_uncharge(&mc.to->memory, mc.moved_swap); 5824 5825 mc.moved_swap = 0; 5826 } 5827 memcg_oom_recover(from); 5828 memcg_oom_recover(to); 5829 wake_up_all(&mc.waitq); 5830 } 5831 5832 static void mem_cgroup_clear_mc(void) 5833 { 5834 struct mm_struct *mm = mc.mm; 5835 5836 /* 5837 * we must clear moving_task before waking up waiters at the end of 5838 * task migration. 5839 */ 5840 mc.moving_task = NULL; 5841 __mem_cgroup_clear_mc(); 5842 spin_lock(&mc.lock); 5843 mc.from = NULL; 5844 mc.to = NULL; 5845 mc.mm = NULL; 5846 spin_unlock(&mc.lock); 5847 5848 mmput(mm); 5849 } 5850 5851 static int mem_cgroup_can_attach(struct cgroup_taskset *tset) 5852 { 5853 struct cgroup_subsys_state *css; 5854 struct mem_cgroup *memcg = NULL; /* unneeded init to make gcc happy */ 5855 struct mem_cgroup *from; 5856 struct task_struct *leader, *p; 5857 struct mm_struct *mm; 5858 unsigned long move_flags; 5859 int ret = 0; 5860 5861 /* charge immigration isn't supported on the default hierarchy */ 5862 if (cgroup_subsys_on_dfl(memory_cgrp_subsys)) 5863 return 0; 5864 5865 /* 5866 * Multi-process migrations only happen on the default hierarchy 5867 * where charge immigration is not used. Perform charge 5868 * immigration if @tset contains a leader and whine if there are 5869 * multiple. 5870 */ 5871 p = NULL; 5872 cgroup_taskset_for_each_leader(leader, css, tset) { 5873 WARN_ON_ONCE(p); 5874 p = leader; 5875 memcg = mem_cgroup_from_css(css); 5876 } 5877 if (!p) 5878 return 0; 5879 5880 /* 5881 * We are now committed to this value whatever it is. Changes in this 5882 * tunable will only affect upcoming migrations, not the current one. 5883 * So we need to save it, and keep it going. 5884 */ 5885 move_flags = READ_ONCE(memcg->move_charge_at_immigrate); 5886 if (!move_flags) 5887 return 0; 5888 5889 from = mem_cgroup_from_task(p); 5890 5891 VM_BUG_ON(from == memcg); 5892 5893 mm = get_task_mm(p); 5894 if (!mm) 5895 return 0; 5896 /* We move charges only when we move a owner of the mm */ 5897 if (mm->owner == p) { 5898 VM_BUG_ON(mc.from); 5899 VM_BUG_ON(mc.to); 5900 VM_BUG_ON(mc.precharge); 5901 VM_BUG_ON(mc.moved_charge); 5902 VM_BUG_ON(mc.moved_swap); 5903 5904 spin_lock(&mc.lock); 5905 mc.mm = mm; 5906 mc.from = from; 5907 mc.to = memcg; 5908 mc.flags = move_flags; 5909 spin_unlock(&mc.lock); 5910 /* We set mc.moving_task later */ 5911 5912 ret = mem_cgroup_precharge_mc(mm); 5913 if (ret) 5914 mem_cgroup_clear_mc(); 5915 } else { 5916 mmput(mm); 5917 } 5918 return ret; 5919 } 5920 5921 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset) 5922 { 5923 if (mc.to) 5924 mem_cgroup_clear_mc(); 5925 } 5926 5927 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd, 5928 unsigned long addr, unsigned long end, 5929 struct mm_walk *walk) 5930 { 5931 int ret = 0; 5932 struct vm_area_struct *vma = walk->vma; 5933 pte_t *pte; 5934 spinlock_t *ptl; 5935 enum mc_target_type target_type; 5936 union mc_target target; 5937 struct page *page; 5938 5939 ptl = pmd_trans_huge_lock(pmd, vma); 5940 if (ptl) { 5941 if (mc.precharge < HPAGE_PMD_NR) { 5942 spin_unlock(ptl); 5943 return 0; 5944 } 5945 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target); 5946 if (target_type == MC_TARGET_PAGE) { 5947 page = target.page; 5948 if (!isolate_lru_page(page)) { 5949 if (!mem_cgroup_move_account(page, true, 5950 mc.from, mc.to)) { 5951 mc.precharge -= HPAGE_PMD_NR; 5952 mc.moved_charge += HPAGE_PMD_NR; 5953 } 5954 putback_lru_page(page); 5955 } 5956 put_page(page); 5957 } else if (target_type == MC_TARGET_DEVICE) { 5958 page = target.page; 5959 if (!mem_cgroup_move_account(page, true, 5960 mc.from, mc.to)) { 5961 mc.precharge -= HPAGE_PMD_NR; 5962 mc.moved_charge += HPAGE_PMD_NR; 5963 } 5964 put_page(page); 5965 } 5966 spin_unlock(ptl); 5967 return 0; 5968 } 5969 5970 if (pmd_trans_unstable(pmd)) 5971 return 0; 5972 retry: 5973 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl); 5974 for (; addr != end; addr += PAGE_SIZE) { 5975 pte_t ptent = *(pte++); 5976 bool device = false; 5977 swp_entry_t ent; 5978 5979 if (!mc.precharge) 5980 break; 5981 5982 switch (get_mctgt_type(vma, addr, ptent, &target)) { 5983 case MC_TARGET_DEVICE: 5984 device = true; 5985 fallthrough; 5986 case MC_TARGET_PAGE: 5987 page = target.page; 5988 /* 5989 * We can have a part of the split pmd here. Moving it 5990 * can be done but it would be too convoluted so simply 5991 * ignore such a partial THP and keep it in original 5992 * memcg. There should be somebody mapping the head. 5993 */ 5994 if (PageTransCompound(page)) 5995 goto put; 5996 if (!device && isolate_lru_page(page)) 5997 goto put; 5998 if (!mem_cgroup_move_account(page, false, 5999 mc.from, mc.to)) { 6000 mc.precharge--; 6001 /* we uncharge from mc.from later. */ 6002 mc.moved_charge++; 6003 } 6004 if (!device) 6005 putback_lru_page(page); 6006 put: /* get_mctgt_type() gets the page */ 6007 put_page(page); 6008 break; 6009 case MC_TARGET_SWAP: 6010 ent = target.ent; 6011 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) { 6012 mc.precharge--; 6013 mem_cgroup_id_get_many(mc.to, 1); 6014 /* we fixup other refcnts and charges later. */ 6015 mc.moved_swap++; 6016 } 6017 break; 6018 default: 6019 break; 6020 } 6021 } 6022 pte_unmap_unlock(pte - 1, ptl); 6023 cond_resched(); 6024 6025 if (addr != end) { 6026 /* 6027 * We have consumed all precharges we got in can_attach(). 6028 * We try charge one by one, but don't do any additional 6029 * charges to mc.to if we have failed in charge once in attach() 6030 * phase. 6031 */ 6032 ret = mem_cgroup_do_precharge(1); 6033 if (!ret) 6034 goto retry; 6035 } 6036 6037 return ret; 6038 } 6039 6040 static const struct mm_walk_ops charge_walk_ops = { 6041 .pmd_entry = mem_cgroup_move_charge_pte_range, 6042 }; 6043 6044 static void mem_cgroup_move_charge(void) 6045 { 6046 lru_add_drain_all(); 6047 /* 6048 * Signal lock_page_memcg() to take the memcg's move_lock 6049 * while we're moving its pages to another memcg. Then wait 6050 * for already started RCU-only updates to finish. 6051 */ 6052 atomic_inc(&mc.from->moving_account); 6053 synchronize_rcu(); 6054 retry: 6055 if (unlikely(!mmap_read_trylock(mc.mm))) { 6056 /* 6057 * Someone who are holding the mmap_lock might be waiting in 6058 * waitq. So we cancel all extra charges, wake up all waiters, 6059 * and retry. Because we cancel precharges, we might not be able 6060 * to move enough charges, but moving charge is a best-effort 6061 * feature anyway, so it wouldn't be a big problem. 6062 */ 6063 __mem_cgroup_clear_mc(); 6064 cond_resched(); 6065 goto retry; 6066 } 6067 /* 6068 * When we have consumed all precharges and failed in doing 6069 * additional charge, the page walk just aborts. 6070 */ 6071 walk_page_range(mc.mm, 0, mc.mm->highest_vm_end, &charge_walk_ops, 6072 NULL); 6073 6074 mmap_read_unlock(mc.mm); 6075 atomic_dec(&mc.from->moving_account); 6076 } 6077 6078 static void mem_cgroup_move_task(void) 6079 { 6080 if (mc.to) { 6081 mem_cgroup_move_charge(); 6082 mem_cgroup_clear_mc(); 6083 } 6084 } 6085 #else /* !CONFIG_MMU */ 6086 static int mem_cgroup_can_attach(struct cgroup_taskset *tset) 6087 { 6088 return 0; 6089 } 6090 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset) 6091 { 6092 } 6093 static void mem_cgroup_move_task(void) 6094 { 6095 } 6096 #endif 6097 6098 static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value) 6099 { 6100 if (value == PAGE_COUNTER_MAX) 6101 seq_puts(m, "max\n"); 6102 else 6103 seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE); 6104 6105 return 0; 6106 } 6107 6108 static u64 memory_current_read(struct cgroup_subsys_state *css, 6109 struct cftype *cft) 6110 { 6111 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 6112 6113 return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE; 6114 } 6115 6116 static int memory_min_show(struct seq_file *m, void *v) 6117 { 6118 return seq_puts_memcg_tunable(m, 6119 READ_ONCE(mem_cgroup_from_seq(m)->memory.min)); 6120 } 6121 6122 static ssize_t memory_min_write(struct kernfs_open_file *of, 6123 char *buf, size_t nbytes, loff_t off) 6124 { 6125 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 6126 unsigned long min; 6127 int err; 6128 6129 buf = strstrip(buf); 6130 err = page_counter_memparse(buf, "max", &min); 6131 if (err) 6132 return err; 6133 6134 page_counter_set_min(&memcg->memory, min); 6135 6136 return nbytes; 6137 } 6138 6139 static int memory_low_show(struct seq_file *m, void *v) 6140 { 6141 return seq_puts_memcg_tunable(m, 6142 READ_ONCE(mem_cgroup_from_seq(m)->memory.low)); 6143 } 6144 6145 static ssize_t memory_low_write(struct kernfs_open_file *of, 6146 char *buf, size_t nbytes, loff_t off) 6147 { 6148 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 6149 unsigned long low; 6150 int err; 6151 6152 buf = strstrip(buf); 6153 err = page_counter_memparse(buf, "max", &low); 6154 if (err) 6155 return err; 6156 6157 page_counter_set_low(&memcg->memory, low); 6158 6159 return nbytes; 6160 } 6161 6162 static int memory_high_show(struct seq_file *m, void *v) 6163 { 6164 return seq_puts_memcg_tunable(m, 6165 READ_ONCE(mem_cgroup_from_seq(m)->memory.high)); 6166 } 6167 6168 static ssize_t memory_high_write(struct kernfs_open_file *of, 6169 char *buf, size_t nbytes, loff_t off) 6170 { 6171 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 6172 unsigned int nr_retries = MAX_RECLAIM_RETRIES; 6173 bool drained = false; 6174 unsigned long high; 6175 int err; 6176 6177 buf = strstrip(buf); 6178 err = page_counter_memparse(buf, "max", &high); 6179 if (err) 6180 return err; 6181 6182 page_counter_set_high(&memcg->memory, high); 6183 6184 for (;;) { 6185 unsigned long nr_pages = page_counter_read(&memcg->memory); 6186 unsigned long reclaimed; 6187 6188 if (nr_pages <= high) 6189 break; 6190 6191 if (signal_pending(current)) 6192 break; 6193 6194 if (!drained) { 6195 drain_all_stock(memcg); 6196 drained = true; 6197 continue; 6198 } 6199 6200 reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high, 6201 GFP_KERNEL, true); 6202 6203 if (!reclaimed && !nr_retries--) 6204 break; 6205 } 6206 6207 memcg_wb_domain_size_changed(memcg); 6208 return nbytes; 6209 } 6210 6211 static int memory_max_show(struct seq_file *m, void *v) 6212 { 6213 return seq_puts_memcg_tunable(m, 6214 READ_ONCE(mem_cgroup_from_seq(m)->memory.max)); 6215 } 6216 6217 static ssize_t memory_max_write(struct kernfs_open_file *of, 6218 char *buf, size_t nbytes, loff_t off) 6219 { 6220 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 6221 unsigned int nr_reclaims = MAX_RECLAIM_RETRIES; 6222 bool drained = false; 6223 unsigned long max; 6224 int err; 6225 6226 buf = strstrip(buf); 6227 err = page_counter_memparse(buf, "max", &max); 6228 if (err) 6229 return err; 6230 6231 xchg(&memcg->memory.max, max); 6232 6233 for (;;) { 6234 unsigned long nr_pages = page_counter_read(&memcg->memory); 6235 6236 if (nr_pages <= max) 6237 break; 6238 6239 if (signal_pending(current)) 6240 break; 6241 6242 if (!drained) { 6243 drain_all_stock(memcg); 6244 drained = true; 6245 continue; 6246 } 6247 6248 if (nr_reclaims) { 6249 if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max, 6250 GFP_KERNEL, true)) 6251 nr_reclaims--; 6252 continue; 6253 } 6254 6255 memcg_memory_event(memcg, MEMCG_OOM); 6256 if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0)) 6257 break; 6258 } 6259 6260 memcg_wb_domain_size_changed(memcg); 6261 return nbytes; 6262 } 6263 6264 static void __memory_events_show(struct seq_file *m, atomic_long_t *events) 6265 { 6266 seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW])); 6267 seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH])); 6268 seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX])); 6269 seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM])); 6270 seq_printf(m, "oom_kill %lu\n", 6271 atomic_long_read(&events[MEMCG_OOM_KILL])); 6272 seq_printf(m, "oom_group_kill %lu\n", 6273 atomic_long_read(&events[MEMCG_OOM_GROUP_KILL])); 6274 } 6275 6276 static int memory_events_show(struct seq_file *m, void *v) 6277 { 6278 struct mem_cgroup *memcg = mem_cgroup_from_seq(m); 6279 6280 __memory_events_show(m, memcg->memory_events); 6281 return 0; 6282 } 6283 6284 static int memory_events_local_show(struct seq_file *m, void *v) 6285 { 6286 struct mem_cgroup *memcg = mem_cgroup_from_seq(m); 6287 6288 __memory_events_show(m, memcg->memory_events_local); 6289 return 0; 6290 } 6291 6292 static int memory_stat_show(struct seq_file *m, void *v) 6293 { 6294 struct mem_cgroup *memcg = mem_cgroup_from_seq(m); 6295 char *buf; 6296 6297 buf = memory_stat_format(memcg); 6298 if (!buf) 6299 return -ENOMEM; 6300 seq_puts(m, buf); 6301 kfree(buf); 6302 return 0; 6303 } 6304 6305 #ifdef CONFIG_NUMA 6306 static inline unsigned long lruvec_page_state_output(struct lruvec *lruvec, 6307 int item) 6308 { 6309 return lruvec_page_state(lruvec, item) * memcg_page_state_unit(item); 6310 } 6311 6312 static int memory_numa_stat_show(struct seq_file *m, void *v) 6313 { 6314 int i; 6315 struct mem_cgroup *memcg = mem_cgroup_from_seq(m); 6316 6317 mem_cgroup_flush_stats(); 6318 6319 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) { 6320 int nid; 6321 6322 if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS) 6323 continue; 6324 6325 seq_printf(m, "%s", memory_stats[i].name); 6326 for_each_node_state(nid, N_MEMORY) { 6327 u64 size; 6328 struct lruvec *lruvec; 6329 6330 lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid)); 6331 size = lruvec_page_state_output(lruvec, 6332 memory_stats[i].idx); 6333 seq_printf(m, " N%d=%llu", nid, size); 6334 } 6335 seq_putc(m, '\n'); 6336 } 6337 6338 return 0; 6339 } 6340 #endif 6341 6342 static int memory_oom_group_show(struct seq_file *m, void *v) 6343 { 6344 struct mem_cgroup *memcg = mem_cgroup_from_seq(m); 6345 6346 seq_printf(m, "%d\n", memcg->oom_group); 6347 6348 return 0; 6349 } 6350 6351 static ssize_t memory_oom_group_write(struct kernfs_open_file *of, 6352 char *buf, size_t nbytes, loff_t off) 6353 { 6354 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 6355 int ret, oom_group; 6356 6357 buf = strstrip(buf); 6358 if (!buf) 6359 return -EINVAL; 6360 6361 ret = kstrtoint(buf, 0, &oom_group); 6362 if (ret) 6363 return ret; 6364 6365 if (oom_group != 0 && oom_group != 1) 6366 return -EINVAL; 6367 6368 memcg->oom_group = oom_group; 6369 6370 return nbytes; 6371 } 6372 6373 static struct cftype memory_files[] = { 6374 { 6375 .name = "current", 6376 .flags = CFTYPE_NOT_ON_ROOT, 6377 .read_u64 = memory_current_read, 6378 }, 6379 { 6380 .name = "min", 6381 .flags = CFTYPE_NOT_ON_ROOT, 6382 .seq_show = memory_min_show, 6383 .write = memory_min_write, 6384 }, 6385 { 6386 .name = "low", 6387 .flags = CFTYPE_NOT_ON_ROOT, 6388 .seq_show = memory_low_show, 6389 .write = memory_low_write, 6390 }, 6391 { 6392 .name = "high", 6393 .flags = CFTYPE_NOT_ON_ROOT, 6394 .seq_show = memory_high_show, 6395 .write = memory_high_write, 6396 }, 6397 { 6398 .name = "max", 6399 .flags = CFTYPE_NOT_ON_ROOT, 6400 .seq_show = memory_max_show, 6401 .write = memory_max_write, 6402 }, 6403 { 6404 .name = "events", 6405 .flags = CFTYPE_NOT_ON_ROOT, 6406 .file_offset = offsetof(struct mem_cgroup, events_file), 6407 .seq_show = memory_events_show, 6408 }, 6409 { 6410 .name = "events.local", 6411 .flags = CFTYPE_NOT_ON_ROOT, 6412 .file_offset = offsetof(struct mem_cgroup, events_local_file), 6413 .seq_show = memory_events_local_show, 6414 }, 6415 { 6416 .name = "stat", 6417 .seq_show = memory_stat_show, 6418 }, 6419 #ifdef CONFIG_NUMA 6420 { 6421 .name = "numa_stat", 6422 .seq_show = memory_numa_stat_show, 6423 }, 6424 #endif 6425 { 6426 .name = "oom.group", 6427 .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE, 6428 .seq_show = memory_oom_group_show, 6429 .write = memory_oom_group_write, 6430 }, 6431 { } /* terminate */ 6432 }; 6433 6434 struct cgroup_subsys memory_cgrp_subsys = { 6435 .css_alloc = mem_cgroup_css_alloc, 6436 .css_online = mem_cgroup_css_online, 6437 .css_offline = mem_cgroup_css_offline, 6438 .css_released = mem_cgroup_css_released, 6439 .css_free = mem_cgroup_css_free, 6440 .css_reset = mem_cgroup_css_reset, 6441 .css_rstat_flush = mem_cgroup_css_rstat_flush, 6442 .can_attach = mem_cgroup_can_attach, 6443 .cancel_attach = mem_cgroup_cancel_attach, 6444 .post_attach = mem_cgroup_move_task, 6445 .dfl_cftypes = memory_files, 6446 .legacy_cftypes = mem_cgroup_legacy_files, 6447 .early_init = 0, 6448 }; 6449 6450 /* 6451 * This function calculates an individual cgroup's effective 6452 * protection which is derived from its own memory.min/low, its 6453 * parent's and siblings' settings, as well as the actual memory 6454 * distribution in the tree. 6455 * 6456 * The following rules apply to the effective protection values: 6457 * 6458 * 1. At the first level of reclaim, effective protection is equal to 6459 * the declared protection in memory.min and memory.low. 6460 * 6461 * 2. To enable safe delegation of the protection configuration, at 6462 * subsequent levels the effective protection is capped to the 6463 * parent's effective protection. 6464 * 6465 * 3. To make complex and dynamic subtrees easier to configure, the 6466 * user is allowed to overcommit the declared protection at a given 6467 * level. If that is the case, the parent's effective protection is 6468 * distributed to the children in proportion to how much protection 6469 * they have declared and how much of it they are utilizing. 6470 * 6471 * This makes distribution proportional, but also work-conserving: 6472 * if one cgroup claims much more protection than it uses memory, 6473 * the unused remainder is available to its siblings. 6474 * 6475 * 4. Conversely, when the declared protection is undercommitted at a 6476 * given level, the distribution of the larger parental protection 6477 * budget is NOT proportional. A cgroup's protection from a sibling 6478 * is capped to its own memory.min/low setting. 6479 * 6480 * 5. However, to allow protecting recursive subtrees from each other 6481 * without having to declare each individual cgroup's fixed share 6482 * of the ancestor's claim to protection, any unutilized - 6483 * "floating" - protection from up the tree is distributed in 6484 * proportion to each cgroup's *usage*. This makes the protection 6485 * neutral wrt sibling cgroups and lets them compete freely over 6486 * the shared parental protection budget, but it protects the 6487 * subtree as a whole from neighboring subtrees. 6488 * 6489 * Note that 4. and 5. are not in conflict: 4. is about protecting 6490 * against immediate siblings whereas 5. is about protecting against 6491 * neighboring subtrees. 6492 */ 6493 static unsigned long effective_protection(unsigned long usage, 6494 unsigned long parent_usage, 6495 unsigned long setting, 6496 unsigned long parent_effective, 6497 unsigned long siblings_protected) 6498 { 6499 unsigned long protected; 6500 unsigned long ep; 6501 6502 protected = min(usage, setting); 6503 /* 6504 * If all cgroups at this level combined claim and use more 6505 * protection then what the parent affords them, distribute 6506 * shares in proportion to utilization. 6507 * 6508 * We are using actual utilization rather than the statically 6509 * claimed protection in order to be work-conserving: claimed 6510 * but unused protection is available to siblings that would 6511 * otherwise get a smaller chunk than what they claimed. 6512 */ 6513 if (siblings_protected > parent_effective) 6514 return protected * parent_effective / siblings_protected; 6515 6516 /* 6517 * Ok, utilized protection of all children is within what the 6518 * parent affords them, so we know whatever this child claims 6519 * and utilizes is effectively protected. 6520 * 6521 * If there is unprotected usage beyond this value, reclaim 6522 * will apply pressure in proportion to that amount. 6523 * 6524 * If there is unutilized protection, the cgroup will be fully 6525 * shielded from reclaim, but we do return a smaller value for 6526 * protection than what the group could enjoy in theory. This 6527 * is okay. With the overcommit distribution above, effective 6528 * protection is always dependent on how memory is actually 6529 * consumed among the siblings anyway. 6530 */ 6531 ep = protected; 6532 6533 /* 6534 * If the children aren't claiming (all of) the protection 6535 * afforded to them by the parent, distribute the remainder in 6536 * proportion to the (unprotected) memory of each cgroup. That 6537 * way, cgroups that aren't explicitly prioritized wrt each 6538 * other compete freely over the allowance, but they are 6539 * collectively protected from neighboring trees. 6540 * 6541 * We're using unprotected memory for the weight so that if 6542 * some cgroups DO claim explicit protection, we don't protect 6543 * the same bytes twice. 6544 * 6545 * Check both usage and parent_usage against the respective 6546 * protected values. One should imply the other, but they 6547 * aren't read atomically - make sure the division is sane. 6548 */ 6549 if (!(cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT)) 6550 return ep; 6551 if (parent_effective > siblings_protected && 6552 parent_usage > siblings_protected && 6553 usage > protected) { 6554 unsigned long unclaimed; 6555 6556 unclaimed = parent_effective - siblings_protected; 6557 unclaimed *= usage - protected; 6558 unclaimed /= parent_usage - siblings_protected; 6559 6560 ep += unclaimed; 6561 } 6562 6563 return ep; 6564 } 6565 6566 /** 6567 * mem_cgroup_calculate_protection - check if memory consumption is in the normal range 6568 * @root: the top ancestor of the sub-tree being checked 6569 * @memcg: the memory cgroup to check 6570 * 6571 * WARNING: This function is not stateless! It can only be used as part 6572 * of a top-down tree iteration, not for isolated queries. 6573 */ 6574 void mem_cgroup_calculate_protection(struct mem_cgroup *root, 6575 struct mem_cgroup *memcg) 6576 { 6577 unsigned long usage, parent_usage; 6578 struct mem_cgroup *parent; 6579 6580 if (mem_cgroup_disabled()) 6581 return; 6582 6583 if (!root) 6584 root = root_mem_cgroup; 6585 6586 /* 6587 * Effective values of the reclaim targets are ignored so they 6588 * can be stale. Have a look at mem_cgroup_protection for more 6589 * details. 6590 * TODO: calculation should be more robust so that we do not need 6591 * that special casing. 6592 */ 6593 if (memcg == root) 6594 return; 6595 6596 usage = page_counter_read(&memcg->memory); 6597 if (!usage) 6598 return; 6599 6600 parent = parent_mem_cgroup(memcg); 6601 /* No parent means a non-hierarchical mode on v1 memcg */ 6602 if (!parent) 6603 return; 6604 6605 if (parent == root) { 6606 memcg->memory.emin = READ_ONCE(memcg->memory.min); 6607 memcg->memory.elow = READ_ONCE(memcg->memory.low); 6608 return; 6609 } 6610 6611 parent_usage = page_counter_read(&parent->memory); 6612 6613 WRITE_ONCE(memcg->memory.emin, effective_protection(usage, parent_usage, 6614 READ_ONCE(memcg->memory.min), 6615 READ_ONCE(parent->memory.emin), 6616 atomic_long_read(&parent->memory.children_min_usage))); 6617 6618 WRITE_ONCE(memcg->memory.elow, effective_protection(usage, parent_usage, 6619 READ_ONCE(memcg->memory.low), 6620 READ_ONCE(parent->memory.elow), 6621 atomic_long_read(&parent->memory.children_low_usage))); 6622 } 6623 6624 static int charge_memcg(struct folio *folio, struct mem_cgroup *memcg, 6625 gfp_t gfp) 6626 { 6627 long nr_pages = folio_nr_pages(folio); 6628 int ret; 6629 6630 ret = try_charge(memcg, gfp, nr_pages); 6631 if (ret) 6632 goto out; 6633 6634 css_get(&memcg->css); 6635 commit_charge(folio, memcg); 6636 6637 local_irq_disable(); 6638 mem_cgroup_charge_statistics(memcg, nr_pages); 6639 memcg_check_events(memcg, folio_nid(folio)); 6640 local_irq_enable(); 6641 out: 6642 return ret; 6643 } 6644 6645 int __mem_cgroup_charge(struct folio *folio, struct mm_struct *mm, gfp_t gfp) 6646 { 6647 struct mem_cgroup *memcg; 6648 int ret; 6649 6650 memcg = get_mem_cgroup_from_mm(mm); 6651 ret = charge_memcg(folio, memcg, gfp); 6652 css_put(&memcg->css); 6653 6654 return ret; 6655 } 6656 6657 /** 6658 * mem_cgroup_swapin_charge_page - charge a newly allocated page for swapin 6659 * @page: page to charge 6660 * @mm: mm context of the victim 6661 * @gfp: reclaim mode 6662 * @entry: swap entry for which the page is allocated 6663 * 6664 * This function charges a page allocated for swapin. Please call this before 6665 * adding the page to the swapcache. 6666 * 6667 * Returns 0 on success. Otherwise, an error code is returned. 6668 */ 6669 int mem_cgroup_swapin_charge_page(struct page *page, struct mm_struct *mm, 6670 gfp_t gfp, swp_entry_t entry) 6671 { 6672 struct folio *folio = page_folio(page); 6673 struct mem_cgroup *memcg; 6674 unsigned short id; 6675 int ret; 6676 6677 if (mem_cgroup_disabled()) 6678 return 0; 6679 6680 id = lookup_swap_cgroup_id(entry); 6681 rcu_read_lock(); 6682 memcg = mem_cgroup_from_id(id); 6683 if (!memcg || !css_tryget_online(&memcg->css)) 6684 memcg = get_mem_cgroup_from_mm(mm); 6685 rcu_read_unlock(); 6686 6687 ret = charge_memcg(folio, memcg, gfp); 6688 6689 css_put(&memcg->css); 6690 return ret; 6691 } 6692 6693 /* 6694 * mem_cgroup_swapin_uncharge_swap - uncharge swap slot 6695 * @entry: swap entry for which the page is charged 6696 * 6697 * Call this function after successfully adding the charged page to swapcache. 6698 * 6699 * Note: This function assumes the page for which swap slot is being uncharged 6700 * is order 0 page. 6701 */ 6702 void mem_cgroup_swapin_uncharge_swap(swp_entry_t entry) 6703 { 6704 /* 6705 * Cgroup1's unified memory+swap counter has been charged with the 6706 * new swapcache page, finish the transfer by uncharging the swap 6707 * slot. The swap slot would also get uncharged when it dies, but 6708 * it can stick around indefinitely and we'd count the page twice 6709 * the entire time. 6710 * 6711 * Cgroup2 has separate resource counters for memory and swap, 6712 * so this is a non-issue here. Memory and swap charge lifetimes 6713 * correspond 1:1 to page and swap slot lifetimes: we charge the 6714 * page to memory here, and uncharge swap when the slot is freed. 6715 */ 6716 if (!mem_cgroup_disabled() && do_memsw_account()) { 6717 /* 6718 * The swap entry might not get freed for a long time, 6719 * let's not wait for it. The page already received a 6720 * memory+swap charge, drop the swap entry duplicate. 6721 */ 6722 mem_cgroup_uncharge_swap(entry, 1); 6723 } 6724 } 6725 6726 struct uncharge_gather { 6727 struct mem_cgroup *memcg; 6728 unsigned long nr_memory; 6729 unsigned long pgpgout; 6730 unsigned long nr_kmem; 6731 int nid; 6732 }; 6733 6734 static inline void uncharge_gather_clear(struct uncharge_gather *ug) 6735 { 6736 memset(ug, 0, sizeof(*ug)); 6737 } 6738 6739 static void uncharge_batch(const struct uncharge_gather *ug) 6740 { 6741 unsigned long flags; 6742 6743 if (ug->nr_memory) { 6744 page_counter_uncharge(&ug->memcg->memory, ug->nr_memory); 6745 if (do_memsw_account()) 6746 page_counter_uncharge(&ug->memcg->memsw, ug->nr_memory); 6747 if (ug->nr_kmem) 6748 memcg_account_kmem(ug->memcg, -ug->nr_kmem); 6749 memcg_oom_recover(ug->memcg); 6750 } 6751 6752 local_irq_save(flags); 6753 __count_memcg_events(ug->memcg, PGPGOUT, ug->pgpgout); 6754 __this_cpu_add(ug->memcg->vmstats_percpu->nr_page_events, ug->nr_memory); 6755 memcg_check_events(ug->memcg, ug->nid); 6756 local_irq_restore(flags); 6757 6758 /* drop reference from uncharge_folio */ 6759 css_put(&ug->memcg->css); 6760 } 6761 6762 static void uncharge_folio(struct folio *folio, struct uncharge_gather *ug) 6763 { 6764 long nr_pages; 6765 struct mem_cgroup *memcg; 6766 struct obj_cgroup *objcg; 6767 6768 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio); 6769 6770 /* 6771 * Nobody should be changing or seriously looking at 6772 * folio memcg or objcg at this point, we have fully 6773 * exclusive access to the folio. 6774 */ 6775 if (folio_memcg_kmem(folio)) { 6776 objcg = __folio_objcg(folio); 6777 /* 6778 * This get matches the put at the end of the function and 6779 * kmem pages do not hold memcg references anymore. 6780 */ 6781 memcg = get_mem_cgroup_from_objcg(objcg); 6782 } else { 6783 memcg = __folio_memcg(folio); 6784 } 6785 6786 if (!memcg) 6787 return; 6788 6789 if (ug->memcg != memcg) { 6790 if (ug->memcg) { 6791 uncharge_batch(ug); 6792 uncharge_gather_clear(ug); 6793 } 6794 ug->memcg = memcg; 6795 ug->nid = folio_nid(folio); 6796 6797 /* pairs with css_put in uncharge_batch */ 6798 css_get(&memcg->css); 6799 } 6800 6801 nr_pages = folio_nr_pages(folio); 6802 6803 if (folio_memcg_kmem(folio)) { 6804 ug->nr_memory += nr_pages; 6805 ug->nr_kmem += nr_pages; 6806 6807 folio->memcg_data = 0; 6808 obj_cgroup_put(objcg); 6809 } else { 6810 /* LRU pages aren't accounted at the root level */ 6811 if (!mem_cgroup_is_root(memcg)) 6812 ug->nr_memory += nr_pages; 6813 ug->pgpgout++; 6814 6815 folio->memcg_data = 0; 6816 } 6817 6818 css_put(&memcg->css); 6819 } 6820 6821 void __mem_cgroup_uncharge(struct folio *folio) 6822 { 6823 struct uncharge_gather ug; 6824 6825 /* Don't touch folio->lru of any random page, pre-check: */ 6826 if (!folio_memcg(folio)) 6827 return; 6828 6829 uncharge_gather_clear(&ug); 6830 uncharge_folio(folio, &ug); 6831 uncharge_batch(&ug); 6832 } 6833 6834 /** 6835 * __mem_cgroup_uncharge_list - uncharge a list of page 6836 * @page_list: list of pages to uncharge 6837 * 6838 * Uncharge a list of pages previously charged with 6839 * __mem_cgroup_charge(). 6840 */ 6841 void __mem_cgroup_uncharge_list(struct list_head *page_list) 6842 { 6843 struct uncharge_gather ug; 6844 struct folio *folio; 6845 6846 uncharge_gather_clear(&ug); 6847 list_for_each_entry(folio, page_list, lru) 6848 uncharge_folio(folio, &ug); 6849 if (ug.memcg) 6850 uncharge_batch(&ug); 6851 } 6852 6853 /** 6854 * mem_cgroup_migrate - Charge a folio's replacement. 6855 * @old: Currently circulating folio. 6856 * @new: Replacement folio. 6857 * 6858 * Charge @new as a replacement folio for @old. @old will 6859 * be uncharged upon free. 6860 * 6861 * Both folios must be locked, @new->mapping must be set up. 6862 */ 6863 void mem_cgroup_migrate(struct folio *old, struct folio *new) 6864 { 6865 struct mem_cgroup *memcg; 6866 long nr_pages = folio_nr_pages(new); 6867 unsigned long flags; 6868 6869 VM_BUG_ON_FOLIO(!folio_test_locked(old), old); 6870 VM_BUG_ON_FOLIO(!folio_test_locked(new), new); 6871 VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new); 6872 VM_BUG_ON_FOLIO(folio_nr_pages(old) != nr_pages, new); 6873 6874 if (mem_cgroup_disabled()) 6875 return; 6876 6877 /* Page cache replacement: new folio already charged? */ 6878 if (folio_memcg(new)) 6879 return; 6880 6881 memcg = folio_memcg(old); 6882 VM_WARN_ON_ONCE_FOLIO(!memcg, old); 6883 if (!memcg) 6884 return; 6885 6886 /* Force-charge the new page. The old one will be freed soon */ 6887 if (!mem_cgroup_is_root(memcg)) { 6888 page_counter_charge(&memcg->memory, nr_pages); 6889 if (do_memsw_account()) 6890 page_counter_charge(&memcg->memsw, nr_pages); 6891 } 6892 6893 css_get(&memcg->css); 6894 commit_charge(new, memcg); 6895 6896 local_irq_save(flags); 6897 mem_cgroup_charge_statistics(memcg, nr_pages); 6898 memcg_check_events(memcg, folio_nid(new)); 6899 local_irq_restore(flags); 6900 } 6901 6902 DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key); 6903 EXPORT_SYMBOL(memcg_sockets_enabled_key); 6904 6905 void mem_cgroup_sk_alloc(struct sock *sk) 6906 { 6907 struct mem_cgroup *memcg; 6908 6909 if (!mem_cgroup_sockets_enabled) 6910 return; 6911 6912 /* Do not associate the sock with unrelated interrupted task's memcg. */ 6913 if (!in_task()) 6914 return; 6915 6916 rcu_read_lock(); 6917 memcg = mem_cgroup_from_task(current); 6918 if (memcg == root_mem_cgroup) 6919 goto out; 6920 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg->tcpmem_active) 6921 goto out; 6922 if (css_tryget(&memcg->css)) 6923 sk->sk_memcg = memcg; 6924 out: 6925 rcu_read_unlock(); 6926 } 6927 6928 void mem_cgroup_sk_free(struct sock *sk) 6929 { 6930 if (sk->sk_memcg) 6931 css_put(&sk->sk_memcg->css); 6932 } 6933 6934 /** 6935 * mem_cgroup_charge_skmem - charge socket memory 6936 * @memcg: memcg to charge 6937 * @nr_pages: number of pages to charge 6938 * @gfp_mask: reclaim mode 6939 * 6940 * Charges @nr_pages to @memcg. Returns %true if the charge fit within 6941 * @memcg's configured limit, %false if it doesn't. 6942 */ 6943 bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages, 6944 gfp_t gfp_mask) 6945 { 6946 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) { 6947 struct page_counter *fail; 6948 6949 if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) { 6950 memcg->tcpmem_pressure = 0; 6951 return true; 6952 } 6953 memcg->tcpmem_pressure = 1; 6954 if (gfp_mask & __GFP_NOFAIL) { 6955 page_counter_charge(&memcg->tcpmem, nr_pages); 6956 return true; 6957 } 6958 return false; 6959 } 6960 6961 if (try_charge(memcg, gfp_mask, nr_pages) == 0) { 6962 mod_memcg_state(memcg, MEMCG_SOCK, nr_pages); 6963 return true; 6964 } 6965 6966 return false; 6967 } 6968 6969 /** 6970 * mem_cgroup_uncharge_skmem - uncharge socket memory 6971 * @memcg: memcg to uncharge 6972 * @nr_pages: number of pages to uncharge 6973 */ 6974 void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages) 6975 { 6976 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) { 6977 page_counter_uncharge(&memcg->tcpmem, nr_pages); 6978 return; 6979 } 6980 6981 mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages); 6982 6983 refill_stock(memcg, nr_pages); 6984 } 6985 6986 static int __init cgroup_memory(char *s) 6987 { 6988 char *token; 6989 6990 while ((token = strsep(&s, ",")) != NULL) { 6991 if (!*token) 6992 continue; 6993 if (!strcmp(token, "nosocket")) 6994 cgroup_memory_nosocket = true; 6995 if (!strcmp(token, "nokmem")) 6996 cgroup_memory_nokmem = true; 6997 } 6998 return 1; 6999 } 7000 __setup("cgroup.memory=", cgroup_memory); 7001 7002 /* 7003 * subsys_initcall() for memory controller. 7004 * 7005 * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this 7006 * context because of lock dependencies (cgroup_lock -> cpu hotplug) but 7007 * basically everything that doesn't depend on a specific mem_cgroup structure 7008 * should be initialized from here. 7009 */ 7010 static int __init mem_cgroup_init(void) 7011 { 7012 int cpu, node; 7013 7014 /* 7015 * Currently s32 type (can refer to struct batched_lruvec_stat) is 7016 * used for per-memcg-per-cpu caching of per-node statistics. In order 7017 * to work fine, we should make sure that the overfill threshold can't 7018 * exceed S32_MAX / PAGE_SIZE. 7019 */ 7020 BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE); 7021 7022 cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL, 7023 memcg_hotplug_cpu_dead); 7024 7025 for_each_possible_cpu(cpu) 7026 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work, 7027 drain_local_stock); 7028 7029 for_each_node(node) { 7030 struct mem_cgroup_tree_per_node *rtpn; 7031 7032 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, 7033 node_online(node) ? node : NUMA_NO_NODE); 7034 7035 rtpn->rb_root = RB_ROOT; 7036 rtpn->rb_rightmost = NULL; 7037 spin_lock_init(&rtpn->lock); 7038 soft_limit_tree.rb_tree_per_node[node] = rtpn; 7039 } 7040 7041 return 0; 7042 } 7043 subsys_initcall(mem_cgroup_init); 7044 7045 #ifdef CONFIG_MEMCG_SWAP 7046 static struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg) 7047 { 7048 while (!refcount_inc_not_zero(&memcg->id.ref)) { 7049 /* 7050 * The root cgroup cannot be destroyed, so it's refcount must 7051 * always be >= 1. 7052 */ 7053 if (WARN_ON_ONCE(memcg == root_mem_cgroup)) { 7054 VM_BUG_ON(1); 7055 break; 7056 } 7057 memcg = parent_mem_cgroup(memcg); 7058 if (!memcg) 7059 memcg = root_mem_cgroup; 7060 } 7061 return memcg; 7062 } 7063 7064 /** 7065 * mem_cgroup_swapout - transfer a memsw charge to swap 7066 * @page: page whose memsw charge to transfer 7067 * @entry: swap entry to move the charge to 7068 * 7069 * Transfer the memsw charge of @page to @entry. 7070 */ 7071 void mem_cgroup_swapout(struct page *page, swp_entry_t entry) 7072 { 7073 struct mem_cgroup *memcg, *swap_memcg; 7074 unsigned int nr_entries; 7075 unsigned short oldid; 7076 7077 VM_BUG_ON_PAGE(PageLRU(page), page); 7078 VM_BUG_ON_PAGE(page_count(page), page); 7079 7080 if (mem_cgroup_disabled()) 7081 return; 7082 7083 if (cgroup_subsys_on_dfl(memory_cgrp_subsys)) 7084 return; 7085 7086 memcg = page_memcg(page); 7087 7088 VM_WARN_ON_ONCE_PAGE(!memcg, page); 7089 if (!memcg) 7090 return; 7091 7092 /* 7093 * In case the memcg owning these pages has been offlined and doesn't 7094 * have an ID allocated to it anymore, charge the closest online 7095 * ancestor for the swap instead and transfer the memory+swap charge. 7096 */ 7097 swap_memcg = mem_cgroup_id_get_online(memcg); 7098 nr_entries = thp_nr_pages(page); 7099 /* Get references for the tail pages, too */ 7100 if (nr_entries > 1) 7101 mem_cgroup_id_get_many(swap_memcg, nr_entries - 1); 7102 oldid = swap_cgroup_record(entry, mem_cgroup_id(swap_memcg), 7103 nr_entries); 7104 VM_BUG_ON_PAGE(oldid, page); 7105 mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries); 7106 7107 page->memcg_data = 0; 7108 7109 if (!mem_cgroup_is_root(memcg)) 7110 page_counter_uncharge(&memcg->memory, nr_entries); 7111 7112 if (!cgroup_memory_noswap && memcg != swap_memcg) { 7113 if (!mem_cgroup_is_root(swap_memcg)) 7114 page_counter_charge(&swap_memcg->memsw, nr_entries); 7115 page_counter_uncharge(&memcg->memsw, nr_entries); 7116 } 7117 7118 /* 7119 * Interrupts should be disabled here because the caller holds the 7120 * i_pages lock which is taken with interrupts-off. It is 7121 * important here to have the interrupts disabled because it is the 7122 * only synchronisation we have for updating the per-CPU variables. 7123 */ 7124 memcg_stats_lock(); 7125 mem_cgroup_charge_statistics(memcg, -nr_entries); 7126 memcg_stats_unlock(); 7127 memcg_check_events(memcg, page_to_nid(page)); 7128 7129 css_put(&memcg->css); 7130 } 7131 7132 /** 7133 * __mem_cgroup_try_charge_swap - try charging swap space for a page 7134 * @page: page being added to swap 7135 * @entry: swap entry to charge 7136 * 7137 * Try to charge @page's memcg for the swap space at @entry. 7138 * 7139 * Returns 0 on success, -ENOMEM on failure. 7140 */ 7141 int __mem_cgroup_try_charge_swap(struct page *page, swp_entry_t entry) 7142 { 7143 unsigned int nr_pages = thp_nr_pages(page); 7144 struct page_counter *counter; 7145 struct mem_cgroup *memcg; 7146 unsigned short oldid; 7147 7148 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) 7149 return 0; 7150 7151 memcg = page_memcg(page); 7152 7153 VM_WARN_ON_ONCE_PAGE(!memcg, page); 7154 if (!memcg) 7155 return 0; 7156 7157 if (!entry.val) { 7158 memcg_memory_event(memcg, MEMCG_SWAP_FAIL); 7159 return 0; 7160 } 7161 7162 memcg = mem_cgroup_id_get_online(memcg); 7163 7164 if (!cgroup_memory_noswap && !mem_cgroup_is_root(memcg) && 7165 !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) { 7166 memcg_memory_event(memcg, MEMCG_SWAP_MAX); 7167 memcg_memory_event(memcg, MEMCG_SWAP_FAIL); 7168 mem_cgroup_id_put(memcg); 7169 return -ENOMEM; 7170 } 7171 7172 /* Get references for the tail pages, too */ 7173 if (nr_pages > 1) 7174 mem_cgroup_id_get_many(memcg, nr_pages - 1); 7175 oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg), nr_pages); 7176 VM_BUG_ON_PAGE(oldid, page); 7177 mod_memcg_state(memcg, MEMCG_SWAP, nr_pages); 7178 7179 return 0; 7180 } 7181 7182 /** 7183 * __mem_cgroup_uncharge_swap - uncharge swap space 7184 * @entry: swap entry to uncharge 7185 * @nr_pages: the amount of swap space to uncharge 7186 */ 7187 void __mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages) 7188 { 7189 struct mem_cgroup *memcg; 7190 unsigned short id; 7191 7192 id = swap_cgroup_record(entry, 0, nr_pages); 7193 rcu_read_lock(); 7194 memcg = mem_cgroup_from_id(id); 7195 if (memcg) { 7196 if (!cgroup_memory_noswap && !mem_cgroup_is_root(memcg)) { 7197 if (cgroup_subsys_on_dfl(memory_cgrp_subsys)) 7198 page_counter_uncharge(&memcg->swap, nr_pages); 7199 else 7200 page_counter_uncharge(&memcg->memsw, nr_pages); 7201 } 7202 mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages); 7203 mem_cgroup_id_put_many(memcg, nr_pages); 7204 } 7205 rcu_read_unlock(); 7206 } 7207 7208 long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg) 7209 { 7210 long nr_swap_pages = get_nr_swap_pages(); 7211 7212 if (cgroup_memory_noswap || !cgroup_subsys_on_dfl(memory_cgrp_subsys)) 7213 return nr_swap_pages; 7214 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg)) 7215 nr_swap_pages = min_t(long, nr_swap_pages, 7216 READ_ONCE(memcg->swap.max) - 7217 page_counter_read(&memcg->swap)); 7218 return nr_swap_pages; 7219 } 7220 7221 bool mem_cgroup_swap_full(struct page *page) 7222 { 7223 struct mem_cgroup *memcg; 7224 7225 VM_BUG_ON_PAGE(!PageLocked(page), page); 7226 7227 if (vm_swap_full()) 7228 return true; 7229 if (cgroup_memory_noswap || !cgroup_subsys_on_dfl(memory_cgrp_subsys)) 7230 return false; 7231 7232 memcg = page_memcg(page); 7233 if (!memcg) 7234 return false; 7235 7236 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg)) { 7237 unsigned long usage = page_counter_read(&memcg->swap); 7238 7239 if (usage * 2 >= READ_ONCE(memcg->swap.high) || 7240 usage * 2 >= READ_ONCE(memcg->swap.max)) 7241 return true; 7242 } 7243 7244 return false; 7245 } 7246 7247 static int __init setup_swap_account(char *s) 7248 { 7249 if (!strcmp(s, "1")) 7250 cgroup_memory_noswap = false; 7251 else if (!strcmp(s, "0")) 7252 cgroup_memory_noswap = true; 7253 return 1; 7254 } 7255 __setup("swapaccount=", setup_swap_account); 7256 7257 static u64 swap_current_read(struct cgroup_subsys_state *css, 7258 struct cftype *cft) 7259 { 7260 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 7261 7262 return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE; 7263 } 7264 7265 static int swap_high_show(struct seq_file *m, void *v) 7266 { 7267 return seq_puts_memcg_tunable(m, 7268 READ_ONCE(mem_cgroup_from_seq(m)->swap.high)); 7269 } 7270 7271 static ssize_t swap_high_write(struct kernfs_open_file *of, 7272 char *buf, size_t nbytes, loff_t off) 7273 { 7274 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 7275 unsigned long high; 7276 int err; 7277 7278 buf = strstrip(buf); 7279 err = page_counter_memparse(buf, "max", &high); 7280 if (err) 7281 return err; 7282 7283 page_counter_set_high(&memcg->swap, high); 7284 7285 return nbytes; 7286 } 7287 7288 static int swap_max_show(struct seq_file *m, void *v) 7289 { 7290 return seq_puts_memcg_tunable(m, 7291 READ_ONCE(mem_cgroup_from_seq(m)->swap.max)); 7292 } 7293 7294 static ssize_t swap_max_write(struct kernfs_open_file *of, 7295 char *buf, size_t nbytes, loff_t off) 7296 { 7297 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 7298 unsigned long max; 7299 int err; 7300 7301 buf = strstrip(buf); 7302 err = page_counter_memparse(buf, "max", &max); 7303 if (err) 7304 return err; 7305 7306 xchg(&memcg->swap.max, max); 7307 7308 return nbytes; 7309 } 7310 7311 static int swap_events_show(struct seq_file *m, void *v) 7312 { 7313 struct mem_cgroup *memcg = mem_cgroup_from_seq(m); 7314 7315 seq_printf(m, "high %lu\n", 7316 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH])); 7317 seq_printf(m, "max %lu\n", 7318 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX])); 7319 seq_printf(m, "fail %lu\n", 7320 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL])); 7321 7322 return 0; 7323 } 7324 7325 static struct cftype swap_files[] = { 7326 { 7327 .name = "swap.current", 7328 .flags = CFTYPE_NOT_ON_ROOT, 7329 .read_u64 = swap_current_read, 7330 }, 7331 { 7332 .name = "swap.high", 7333 .flags = CFTYPE_NOT_ON_ROOT, 7334 .seq_show = swap_high_show, 7335 .write = swap_high_write, 7336 }, 7337 { 7338 .name = "swap.max", 7339 .flags = CFTYPE_NOT_ON_ROOT, 7340 .seq_show = swap_max_show, 7341 .write = swap_max_write, 7342 }, 7343 { 7344 .name = "swap.events", 7345 .flags = CFTYPE_NOT_ON_ROOT, 7346 .file_offset = offsetof(struct mem_cgroup, swap_events_file), 7347 .seq_show = swap_events_show, 7348 }, 7349 { } /* terminate */ 7350 }; 7351 7352 static struct cftype memsw_files[] = { 7353 { 7354 .name = "memsw.usage_in_bytes", 7355 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE), 7356 .read_u64 = mem_cgroup_read_u64, 7357 }, 7358 { 7359 .name = "memsw.max_usage_in_bytes", 7360 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE), 7361 .write = mem_cgroup_reset, 7362 .read_u64 = mem_cgroup_read_u64, 7363 }, 7364 { 7365 .name = "memsw.limit_in_bytes", 7366 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT), 7367 .write = mem_cgroup_write, 7368 .read_u64 = mem_cgroup_read_u64, 7369 }, 7370 { 7371 .name = "memsw.failcnt", 7372 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT), 7373 .write = mem_cgroup_reset, 7374 .read_u64 = mem_cgroup_read_u64, 7375 }, 7376 { }, /* terminate */ 7377 }; 7378 7379 /* 7380 * If mem_cgroup_swap_init() is implemented as a subsys_initcall() 7381 * instead of a core_initcall(), this could mean cgroup_memory_noswap still 7382 * remains set to false even when memcg is disabled via "cgroup_disable=memory" 7383 * boot parameter. This may result in premature OOPS inside 7384 * mem_cgroup_get_nr_swap_pages() function in corner cases. 7385 */ 7386 static int __init mem_cgroup_swap_init(void) 7387 { 7388 /* No memory control -> no swap control */ 7389 if (mem_cgroup_disabled()) 7390 cgroup_memory_noswap = true; 7391 7392 if (cgroup_memory_noswap) 7393 return 0; 7394 7395 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files)); 7396 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files)); 7397 7398 return 0; 7399 } 7400 core_initcall(mem_cgroup_swap_init); 7401 7402 #endif /* CONFIG_MEMCG_SWAP */ 7403