1 // SPDX-License-Identifier: GPL-2.0-or-later 2 3 #include <linux/memcontrol.h> 4 #include <linux/swap.h> 5 #include <linux/mm_inline.h> 6 #include <linux/pagewalk.h> 7 #include <linux/backing-dev.h> 8 #include <linux/eventfd.h> 9 #include <linux/log2.h> 10 #include <linux/poll.h> 11 #include <linux/sort.h> 12 #include <linux/file.h> 13 #include <linux/seq_buf.h> 14 15 #include "internal.h" 16 #include "swap.h" 17 #include "swap_table.h" 18 #include "memcontrol-v1.h" 19 20 /* 21 * Cgroups above their limits are maintained in a RB-Tree, independent of 22 * their hierarchy representation 23 */ 24 25 struct mem_cgroup_tree_per_node { 26 struct rb_root rb_root; 27 struct rb_node *rb_rightmost; 28 spinlock_t lock; 29 }; 30 31 struct mem_cgroup_tree { 32 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES]; 33 }; 34 35 static struct mem_cgroup_tree soft_limit_tree __read_mostly; 36 37 /* 38 * Maximum loops in mem_cgroup_soft_reclaim(), used for soft 39 * limit reclaim to prevent infinite loops, if they ever occur. 40 */ 41 #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100 42 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2 43 44 /* for OOM */ 45 struct mem_cgroup_eventfd_list { 46 struct list_head list; 47 struct eventfd_ctx *eventfd; 48 }; 49 50 /* 51 * cgroup_event represents events which userspace want to receive. 52 */ 53 struct mem_cgroup_event { 54 /* 55 * memcg which the event belongs to. 56 */ 57 struct mem_cgroup *memcg; 58 /* 59 * eventfd to signal userspace about the event. 60 */ 61 struct eventfd_ctx *eventfd; 62 /* 63 * Each of these stored in a list by the cgroup. 64 */ 65 struct list_head list; 66 /* 67 * register_event() callback will be used to add new userspace 68 * waiter for changes related to this event. Use eventfd_signal() 69 * on eventfd to send notification to userspace. 70 */ 71 int (*register_event)(struct mem_cgroup *memcg, 72 struct eventfd_ctx *eventfd, const char *args); 73 /* 74 * unregister_event() callback will be called when userspace closes 75 * the eventfd or on cgroup removing. This callback must be set, 76 * if you want provide notification functionality. 77 */ 78 void (*unregister_event)(struct mem_cgroup *memcg, 79 struct eventfd_ctx *eventfd); 80 /* 81 * All fields below needed to unregister event when 82 * userspace closes eventfd. 83 */ 84 poll_table pt; 85 wait_queue_head_t *wqh; 86 wait_queue_entry_t wait; 87 struct work_struct remove; 88 }; 89 90 #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val)) 91 #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff) 92 #define MEMFILE_ATTR(val) ((val) & 0xffff) 93 94 enum { 95 RES_USAGE, 96 RES_LIMIT, 97 RES_MAX_USAGE, 98 RES_FAILCNT, 99 }; 100 101 #ifdef CONFIG_LOCKDEP 102 static struct lockdep_map memcg_oom_lock_dep_map = { 103 .name = "memcg_oom_lock", 104 }; 105 #endif 106 107 DEFINE_SPINLOCK(memcg_oom_lock); 108 109 static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_node *mz, 110 struct mem_cgroup_tree_per_node *mctz, 111 unsigned long new_usage_in_excess) 112 { 113 struct rb_node **p = &mctz->rb_root.rb_node; 114 struct rb_node *parent = NULL; 115 struct mem_cgroup_per_node *mz_node; 116 bool rightmost = true; 117 118 if (mz->on_tree) 119 return; 120 121 mz->usage_in_excess = new_usage_in_excess; 122 if (!mz->usage_in_excess) 123 return; 124 while (*p) { 125 parent = *p; 126 mz_node = rb_entry(parent, struct mem_cgroup_per_node, 127 tree_node); 128 if (mz->usage_in_excess < mz_node->usage_in_excess) { 129 p = &(*p)->rb_left; 130 rightmost = false; 131 } else { 132 p = &(*p)->rb_right; 133 } 134 } 135 136 if (rightmost) 137 mctz->rb_rightmost = &mz->tree_node; 138 139 rb_link_node(&mz->tree_node, parent, p); 140 rb_insert_color(&mz->tree_node, &mctz->rb_root); 141 mz->on_tree = true; 142 } 143 144 static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz, 145 struct mem_cgroup_tree_per_node *mctz) 146 { 147 if (!mz->on_tree) 148 return; 149 150 if (&mz->tree_node == mctz->rb_rightmost) 151 mctz->rb_rightmost = rb_prev(&mz->tree_node); 152 153 rb_erase(&mz->tree_node, &mctz->rb_root); 154 mz->on_tree = false; 155 } 156 157 static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz, 158 struct mem_cgroup_tree_per_node *mctz) 159 { 160 unsigned long flags; 161 162 spin_lock_irqsave(&mctz->lock, flags); 163 __mem_cgroup_remove_exceeded(mz, mctz); 164 spin_unlock_irqrestore(&mctz->lock, flags); 165 } 166 167 static unsigned long soft_limit_excess(struct mem_cgroup *memcg) 168 { 169 unsigned long nr_pages = page_counter_read(&memcg->memory); 170 unsigned long soft_limit = READ_ONCE(memcg->soft_limit); 171 unsigned long excess = 0; 172 173 if (nr_pages > soft_limit) 174 excess = nr_pages - soft_limit; 175 176 return excess; 177 } 178 179 static void memcg1_update_tree(struct mem_cgroup *memcg, int nid) 180 { 181 unsigned long excess; 182 struct mem_cgroup_per_node *mz; 183 struct mem_cgroup_tree_per_node *mctz; 184 185 if (lru_gen_enabled()) { 186 if (soft_limit_excess(memcg)) 187 lru_gen_soft_reclaim(memcg, nid); 188 return; 189 } 190 191 mctz = soft_limit_tree.rb_tree_per_node[nid]; 192 if (!mctz) 193 return; 194 /* 195 * Necessary to update all ancestors when hierarchy is used. 196 * because their event counter is not touched. 197 */ 198 for (; memcg; memcg = parent_mem_cgroup(memcg)) { 199 mz = memcg->nodeinfo[nid]; 200 excess = soft_limit_excess(memcg); 201 /* 202 * We have to update the tree if mz is on RB-tree or 203 * mem is over its softlimit. 204 */ 205 if (excess || mz->on_tree) { 206 unsigned long flags; 207 208 spin_lock_irqsave(&mctz->lock, flags); 209 /* if on-tree, remove it */ 210 if (mz->on_tree) 211 __mem_cgroup_remove_exceeded(mz, mctz); 212 /* 213 * Insert again. mz->usage_in_excess will be updated. 214 * If excess is 0, no tree ops. 215 */ 216 __mem_cgroup_insert_exceeded(mz, mctz, excess); 217 spin_unlock_irqrestore(&mctz->lock, flags); 218 } 219 } 220 } 221 222 void memcg1_remove_from_trees(struct mem_cgroup *memcg) 223 { 224 struct mem_cgroup_tree_per_node *mctz; 225 struct mem_cgroup_per_node *mz; 226 int nid; 227 228 for_each_node(nid) { 229 mz = memcg->nodeinfo[nid]; 230 mctz = soft_limit_tree.rb_tree_per_node[nid]; 231 if (mctz) 232 mem_cgroup_remove_exceeded(mz, mctz); 233 } 234 } 235 236 static struct mem_cgroup_per_node * 237 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz) 238 { 239 struct mem_cgroup_per_node *mz; 240 241 retry: 242 mz = NULL; 243 if (!mctz->rb_rightmost) 244 goto done; /* Nothing to reclaim from */ 245 246 mz = rb_entry(mctz->rb_rightmost, 247 struct mem_cgroup_per_node, tree_node); 248 /* 249 * Remove the node now but someone else can add it back, 250 * we will to add it back at the end of reclaim to its correct 251 * position in the tree. 252 */ 253 __mem_cgroup_remove_exceeded(mz, mctz); 254 if (!soft_limit_excess(mz->memcg) || 255 !css_tryget(&mz->memcg->css)) 256 goto retry; 257 done: 258 return mz; 259 } 260 261 static struct mem_cgroup_per_node * 262 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz) 263 { 264 struct mem_cgroup_per_node *mz; 265 266 spin_lock_irq(&mctz->lock); 267 mz = __mem_cgroup_largest_soft_limit_node(mctz); 268 spin_unlock_irq(&mctz->lock); 269 return mz; 270 } 271 272 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg, 273 pg_data_t *pgdat, 274 gfp_t gfp_mask, 275 unsigned long *total_scanned) 276 { 277 struct mem_cgroup *victim = NULL; 278 int total = 0; 279 int loop = 0; 280 unsigned long excess; 281 unsigned long nr_scanned; 282 struct mem_cgroup_reclaim_cookie reclaim = { 283 .pgdat = pgdat, 284 }; 285 286 excess = soft_limit_excess(root_memcg); 287 288 while (1) { 289 victim = mem_cgroup_iter(root_memcg, victim, &reclaim); 290 if (!victim) { 291 loop++; 292 if (loop >= 2) { 293 /* 294 * If we have not been able to reclaim 295 * anything, it might because there are 296 * no reclaimable pages under this hierarchy 297 */ 298 if (!total) 299 break; 300 /* 301 * We want to do more targeted reclaim. 302 * excess >> 2 is not to excessive so as to 303 * reclaim too much, nor too less that we keep 304 * coming back to reclaim from this cgroup 305 */ 306 if (total >= (excess >> 2) || 307 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS)) 308 break; 309 } 310 continue; 311 } 312 total += mem_cgroup_shrink_node(victim, gfp_mask, false, 313 pgdat, &nr_scanned); 314 *total_scanned += nr_scanned; 315 if (!soft_limit_excess(root_memcg)) 316 break; 317 } 318 mem_cgroup_iter_break(root_memcg, victim); 319 return total; 320 } 321 322 unsigned long memcg1_soft_limit_reclaim(pg_data_t *pgdat, int order, 323 gfp_t gfp_mask, 324 unsigned long *total_scanned) 325 { 326 unsigned long nr_reclaimed = 0; 327 struct mem_cgroup_per_node *mz, *next_mz = NULL; 328 unsigned long reclaimed; 329 int loop = 0; 330 struct mem_cgroup_tree_per_node *mctz; 331 unsigned long excess; 332 333 if (lru_gen_enabled()) 334 return 0; 335 336 if (order > 0) 337 return 0; 338 339 mctz = soft_limit_tree.rb_tree_per_node[pgdat->node_id]; 340 341 /* 342 * Do not even bother to check the largest node if the root 343 * is empty. Do it lockless to prevent lock bouncing. Races 344 * are acceptable as soft limit is best effort anyway. 345 */ 346 if (!mctz || RB_EMPTY_ROOT(&mctz->rb_root)) 347 return 0; 348 349 /* 350 * This loop can run a while, specially if mem_cgroup's continuously 351 * keep exceeding their soft limit and putting the system under 352 * pressure 353 */ 354 do { 355 if (next_mz) 356 mz = next_mz; 357 else 358 mz = mem_cgroup_largest_soft_limit_node(mctz); 359 if (!mz) 360 break; 361 362 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, pgdat, 363 gfp_mask, total_scanned); 364 nr_reclaimed += reclaimed; 365 spin_lock_irq(&mctz->lock); 366 367 /* 368 * If we failed to reclaim anything from this memory cgroup 369 * it is time to move on to the next cgroup 370 */ 371 next_mz = NULL; 372 if (!reclaimed) 373 next_mz = __mem_cgroup_largest_soft_limit_node(mctz); 374 375 excess = soft_limit_excess(mz->memcg); 376 /* 377 * One school of thought says that we should not add 378 * back the node to the tree if reclaim returns 0. 379 * But our reclaim could return 0, simply because due 380 * to priority we are exposing a smaller subset of 381 * memory to reclaim from. Consider this as a longer 382 * term TODO. 383 */ 384 /* If excess == 0, no tree ops */ 385 __mem_cgroup_insert_exceeded(mz, mctz, excess); 386 spin_unlock_irq(&mctz->lock); 387 css_put(&mz->memcg->css); 388 loop++; 389 /* 390 * Could not reclaim anything and there are no more 391 * mem cgroups to try or we seem to be looping without 392 * reclaiming anything. 393 */ 394 if (!nr_reclaimed && 395 (next_mz == NULL || 396 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS)) 397 break; 398 } while (!nr_reclaimed); 399 if (next_mz) 400 css_put(&next_mz->memcg->css); 401 return nr_reclaimed; 402 } 403 404 static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css, 405 struct cftype *cft) 406 { 407 return 0; 408 } 409 410 #ifdef CONFIG_MMU 411 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css, 412 struct cftype *cft, u64 val) 413 { 414 pr_warn_once("Cgroup memory moving (move_charge_at_immigrate) is deprecated. " 415 "Please report your usecase to linux-mm@kvack.org if you " 416 "depend on this functionality.\n"); 417 418 if (val != 0) 419 return -EINVAL; 420 return 0; 421 } 422 #else 423 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css, 424 struct cftype *cft, u64 val) 425 { 426 return -ENOSYS; 427 } 428 #endif 429 430 static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap) 431 { 432 unsigned long val; 433 434 if (mem_cgroup_is_root(memcg)) { 435 /* 436 * Approximate root's usage from global state. This isn't 437 * perfect, but the root usage was always an approximation. 438 */ 439 val = global_node_page_state(NR_FILE_PAGES) + 440 global_node_page_state(NR_ANON_MAPPED); 441 if (swap) 442 val += total_swap_pages - get_nr_swap_pages(); 443 } else { 444 if (!swap) 445 val = page_counter_read(&memcg->memory); 446 else 447 val = page_counter_read(&memcg->memsw); 448 } 449 return val; 450 } 451 452 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap) 453 { 454 struct mem_cgroup_threshold_ary *t; 455 unsigned long usage; 456 int i; 457 458 rcu_read_lock(); 459 if (!swap) 460 t = rcu_dereference(memcg->thresholds.primary); 461 else 462 t = rcu_dereference(memcg->memsw_thresholds.primary); 463 464 if (!t) 465 goto unlock; 466 467 usage = mem_cgroup_usage(memcg, swap); 468 469 /* 470 * current_threshold points to threshold just below or equal to usage. 471 * If it's not true, a threshold was crossed after last 472 * call of __mem_cgroup_threshold(). 473 */ 474 i = t->current_threshold; 475 476 /* 477 * Iterate backward over array of thresholds starting from 478 * current_threshold and check if a threshold is crossed. 479 * If none of thresholds below usage is crossed, we read 480 * only one element of the array here. 481 */ 482 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--) 483 eventfd_signal(t->entries[i].eventfd); 484 485 /* i = current_threshold + 1 */ 486 i++; 487 488 /* 489 * Iterate forward over array of thresholds starting from 490 * current_threshold+1 and check if a threshold is crossed. 491 * If none of thresholds above usage is crossed, we read 492 * only one element of the array here. 493 */ 494 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++) 495 eventfd_signal(t->entries[i].eventfd); 496 497 /* Update current_threshold */ 498 t->current_threshold = i - 1; 499 unlock: 500 rcu_read_unlock(); 501 } 502 503 static void mem_cgroup_threshold(struct mem_cgroup *memcg) 504 { 505 while (memcg) { 506 __mem_cgroup_threshold(memcg, false); 507 if (do_memsw_account()) 508 __mem_cgroup_threshold(memcg, true); 509 510 memcg = parent_mem_cgroup(memcg); 511 } 512 } 513 514 /* Cgroup1: threshold notifications & softlimit tree updates */ 515 516 /* 517 * Per memcg event counter is incremented at every pagein/pageout. With THP, 518 * it will be incremented by the number of pages. This counter is used 519 * to trigger some periodic events. This is straightforward and better 520 * than using jiffies etc. to handle periodic memcg event. 521 */ 522 enum mem_cgroup_events_target { 523 MEM_CGROUP_TARGET_THRESH, 524 MEM_CGROUP_TARGET_SOFTLIMIT, 525 MEM_CGROUP_NTARGETS, 526 }; 527 528 struct memcg1_events_percpu { 529 unsigned long nr_page_events; 530 unsigned long targets[MEM_CGROUP_NTARGETS]; 531 }; 532 533 static void memcg1_charge_statistics(struct mem_cgroup *memcg, int nr_pages) 534 { 535 /* pagein of a big page is an event. So, ignore page size */ 536 if (nr_pages > 0) 537 count_memcg_events(memcg, PGPGIN, 1); 538 else { 539 count_memcg_events(memcg, PGPGOUT, 1); 540 nr_pages = -nr_pages; /* for event */ 541 } 542 543 __this_cpu_add(memcg->events_percpu->nr_page_events, nr_pages); 544 } 545 546 #define THRESHOLDS_EVENTS_TARGET 128 547 #define SOFTLIMIT_EVENTS_TARGET 1024 548 549 static bool memcg1_event_ratelimit(struct mem_cgroup *memcg, 550 enum mem_cgroup_events_target target) 551 { 552 unsigned long val, next; 553 554 val = __this_cpu_read(memcg->events_percpu->nr_page_events); 555 next = __this_cpu_read(memcg->events_percpu->targets[target]); 556 /* from time_after() in jiffies.h */ 557 if ((long)(next - val) < 0) { 558 switch (target) { 559 case MEM_CGROUP_TARGET_THRESH: 560 next = val + THRESHOLDS_EVENTS_TARGET; 561 break; 562 case MEM_CGROUP_TARGET_SOFTLIMIT: 563 next = val + SOFTLIMIT_EVENTS_TARGET; 564 break; 565 default: 566 break; 567 } 568 __this_cpu_write(memcg->events_percpu->targets[target], next); 569 return true; 570 } 571 return false; 572 } 573 574 /* 575 * Check events in order. 576 * 577 */ 578 static void memcg1_check_events(struct mem_cgroup *memcg, int nid) 579 { 580 if (IS_ENABLED(CONFIG_PREEMPT_RT)) 581 return; 582 583 /* threshold event is triggered in finer grain than soft limit */ 584 if (unlikely(memcg1_event_ratelimit(memcg, 585 MEM_CGROUP_TARGET_THRESH))) { 586 bool do_softlimit; 587 588 do_softlimit = memcg1_event_ratelimit(memcg, 589 MEM_CGROUP_TARGET_SOFTLIMIT); 590 mem_cgroup_threshold(memcg); 591 if (unlikely(do_softlimit)) 592 memcg1_update_tree(memcg, nid); 593 } 594 } 595 596 void memcg1_commit_charge(struct folio *folio, struct mem_cgroup *memcg) 597 { 598 unsigned long flags; 599 600 local_irq_save(flags); 601 memcg1_charge_statistics(memcg, folio_nr_pages(folio)); 602 memcg1_check_events(memcg, folio_nid(folio)); 603 local_irq_restore(flags); 604 } 605 606 #ifdef CONFIG_SWAP 607 /** 608 * __memcg1_swapout - transfer a memsw charge to swap 609 * @folio: folio whose memsw charge to transfer 610 * @ci: the locked swap cluster holding the swap entries 611 * 612 * Transfer the memsw charge of @folio to the swap entry stored in 613 * folio->swap. 614 * 615 * Context: folio must be isolated, unmapped, locked and is just about to 616 * be freed, and caller must disable IRQs and hold the swap cluster lock. 617 */ 618 void __memcg1_swapout(struct folio *folio, struct swap_cluster_info *ci) 619 { 620 struct mem_cgroup *memcg, *swap_memcg; 621 struct obj_cgroup *objcg; 622 unsigned int nr_entries; 623 624 VM_WARN_ON_ONCE_FOLIO(!folio_test_swapcache(folio), folio); 625 VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio); 626 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio); 627 VM_BUG_ON_FOLIO(folio_ref_count(folio), folio); 628 629 if (mem_cgroup_disabled()) 630 return; 631 632 if (!do_memsw_account()) 633 return; 634 635 objcg = folio_objcg(folio); 636 VM_WARN_ON_ONCE_FOLIO(!objcg, folio); 637 if (!objcg) 638 return; 639 640 rcu_read_lock(); 641 memcg = obj_cgroup_memcg(objcg); 642 /* 643 * In case the memcg owning these pages has been offlined and doesn't 644 * have an ID allocated to it anymore, charge the closest online 645 * ancestor for the swap instead and transfer the memory+swap charge. 646 */ 647 nr_entries = folio_nr_pages(folio); 648 swap_memcg = mem_cgroup_private_id_get_online(memcg, nr_entries); 649 mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries); 650 651 __swap_cgroup_set(ci, swp_cluster_offset(folio->swap), nr_entries, 652 mem_cgroup_private_id(swap_memcg)); 653 654 folio_unqueue_deferred_split(folio); 655 folio->memcg_data = 0; 656 657 if (!obj_cgroup_is_root(objcg)) 658 page_counter_uncharge(&memcg->memory, nr_entries); 659 660 if (memcg != swap_memcg) { 661 if (!mem_cgroup_is_root(swap_memcg)) 662 page_counter_charge(&swap_memcg->memsw, nr_entries); 663 page_counter_uncharge(&memcg->memsw, nr_entries); 664 } 665 666 /* 667 * The caller must hold the swap cluster lock with IRQ off. It is 668 * important here to have the interrupts disabled because it is the 669 * only synchronisation we have for updating the per-CPU variables. 670 */ 671 preempt_disable_nested(); 672 VM_WARN_ON_IRQS_ENABLED(); 673 memcg1_charge_statistics(memcg, -folio_nr_pages(folio)); 674 preempt_enable_nested(); 675 memcg1_check_events(memcg, folio_nid(folio)); 676 677 rcu_read_unlock(); 678 obj_cgroup_put(objcg); 679 } 680 681 /** 682 * memcg1_swapin - uncharge swap slot on swapin 683 * @folio: folio being swapped in 684 * 685 * Call this function after successfully adding the charged 686 * folio to swapcache. 687 * 688 * Context: The folio has to be in swap cache and locked. 689 */ 690 void memcg1_swapin(struct folio *folio) 691 { 692 struct swap_cluster_info *ci; 693 unsigned long nr_pages; 694 unsigned short id; 695 696 VM_WARN_ON_ONCE_FOLIO(!folio_test_swapcache(folio), folio); 697 VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio); 698 699 /* 700 * Cgroup1's unified memory+swap counter has been charged with the 701 * new swapcache page, finish the transfer by uncharging the swap 702 * slot. The swap slot would also get uncharged when it dies, but 703 * it can stick around indefinitely and we'd count the page twice 704 * the entire time. 705 * 706 * Cgroup2 has separate resource counters for memory and swap, 707 * so this is a non-issue here. Memory and swap charge lifetimes 708 * correspond 1:1 to page and swap slot lifetimes: we charge the 709 * page to memory here, and uncharge swap when the slot is freed. 710 */ 711 if (!do_memsw_account()) 712 return; 713 714 /* 715 * The swap entry might not get freed for a long time, 716 * let's not wait for it. The page already received a 717 * memory+swap charge, drop the swap entry duplicate. 718 */ 719 nr_pages = folio_nr_pages(folio); 720 ci = swap_cluster_get_and_lock(folio); 721 id = __swap_cgroup_clear(ci, swp_cluster_offset(folio->swap), 722 nr_pages); 723 swap_cluster_unlock(ci); 724 mem_cgroup_uncharge_swap(id, nr_pages); 725 } 726 #endif 727 728 void memcg1_uncharge_batch(struct mem_cgroup *memcg, unsigned long pgpgout, 729 unsigned long nr_memory, int nid) 730 { 731 unsigned long flags; 732 733 local_irq_save(flags); 734 count_memcg_events(memcg, PGPGOUT, pgpgout); 735 __this_cpu_add(memcg->events_percpu->nr_page_events, nr_memory); 736 memcg1_check_events(memcg, nid); 737 local_irq_restore(flags); 738 } 739 740 static int compare_thresholds(const void *a, const void *b) 741 { 742 const struct mem_cgroup_threshold *_a = a; 743 const struct mem_cgroup_threshold *_b = b; 744 745 if (_a->threshold > _b->threshold) 746 return 1; 747 748 if (_a->threshold < _b->threshold) 749 return -1; 750 751 return 0; 752 } 753 754 static void mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg) 755 { 756 struct mem_cgroup_eventfd_list *ev; 757 758 spin_lock(&memcg_oom_lock); 759 760 list_for_each_entry(ev, &memcg->oom_notify, list) 761 eventfd_signal(ev->eventfd); 762 763 spin_unlock(&memcg_oom_lock); 764 } 765 766 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg) 767 { 768 struct mem_cgroup *iter; 769 770 for_each_mem_cgroup_tree(iter, memcg) 771 mem_cgroup_oom_notify_cb(iter); 772 } 773 774 static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg, 775 struct eventfd_ctx *eventfd, const char *args, enum res_type type) 776 { 777 struct mem_cgroup_thresholds *thresholds; 778 struct mem_cgroup_threshold_ary *new; 779 unsigned long threshold; 780 unsigned long usage; 781 int i, size, ret; 782 783 ret = page_counter_memparse(args, "-1", &threshold); 784 if (ret) 785 return ret; 786 787 mutex_lock(&memcg->thresholds_lock); 788 789 if (type == _MEM) { 790 thresholds = &memcg->thresholds; 791 usage = mem_cgroup_usage(memcg, false); 792 } else if (type == _MEMSWAP) { 793 thresholds = &memcg->memsw_thresholds; 794 usage = mem_cgroup_usage(memcg, true); 795 } else 796 BUG(); 797 798 /* Check if a threshold crossed before adding a new one */ 799 if (thresholds->primary) 800 __mem_cgroup_threshold(memcg, type == _MEMSWAP); 801 802 size = thresholds->primary ? thresholds->primary->size + 1 : 1; 803 804 /* Allocate memory for new array of thresholds */ 805 new = kmalloc_flex(*new, entries, size, GFP_KERNEL_ACCOUNT); 806 if (!new) { 807 ret = -ENOMEM; 808 goto unlock; 809 } 810 new->size = size; 811 812 /* Copy thresholds (if any) to new array */ 813 if (thresholds->primary) 814 memcpy(new->entries, thresholds->primary->entries, 815 flex_array_size(new, entries, size - 1)); 816 817 /* Add new threshold */ 818 new->entries[size - 1].eventfd = eventfd; 819 new->entries[size - 1].threshold = threshold; 820 821 /* Sort thresholds. Registering of new threshold isn't time-critical */ 822 sort(new->entries, size, sizeof(*new->entries), 823 compare_thresholds, NULL); 824 825 /* Find current threshold */ 826 new->current_threshold = -1; 827 for (i = 0; i < size; i++) { 828 if (new->entries[i].threshold <= usage) { 829 /* 830 * new->current_threshold will not be used until 831 * rcu_assign_pointer(), so it's safe to increment 832 * it here. 833 */ 834 ++new->current_threshold; 835 } else 836 break; 837 } 838 839 /* Free old spare buffer and save old primary buffer as spare */ 840 kfree(thresholds->spare); 841 thresholds->spare = thresholds->primary; 842 843 rcu_assign_pointer(thresholds->primary, new); 844 845 /* To be sure that nobody uses thresholds */ 846 synchronize_rcu(); 847 848 unlock: 849 mutex_unlock(&memcg->thresholds_lock); 850 851 return ret; 852 } 853 854 static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg, 855 struct eventfd_ctx *eventfd, const char *args) 856 { 857 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM); 858 } 859 860 static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg, 861 struct eventfd_ctx *eventfd, const char *args) 862 { 863 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP); 864 } 865 866 static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg, 867 struct eventfd_ctx *eventfd, enum res_type type) 868 { 869 struct mem_cgroup_thresholds *thresholds; 870 struct mem_cgroup_threshold_ary *new; 871 unsigned long usage; 872 int i, j, size, entries; 873 874 mutex_lock(&memcg->thresholds_lock); 875 876 if (type == _MEM) { 877 thresholds = &memcg->thresholds; 878 usage = mem_cgroup_usage(memcg, false); 879 } else if (type == _MEMSWAP) { 880 thresholds = &memcg->memsw_thresholds; 881 usage = mem_cgroup_usage(memcg, true); 882 } else 883 BUG(); 884 885 if (!thresholds->primary) 886 goto unlock; 887 888 /* Check if a threshold crossed before removing */ 889 __mem_cgroup_threshold(memcg, type == _MEMSWAP); 890 891 /* Calculate new number of threshold */ 892 size = entries = 0; 893 for (i = 0; i < thresholds->primary->size; i++) { 894 if (thresholds->primary->entries[i].eventfd != eventfd) 895 size++; 896 else 897 entries++; 898 } 899 900 new = thresholds->spare; 901 902 /* If no items related to eventfd have been cleared, nothing to do */ 903 if (!entries) 904 goto unlock; 905 906 /* Set thresholds array to NULL if we don't have thresholds */ 907 if (!size) { 908 kfree(new); 909 new = NULL; 910 goto swap_buffers; 911 } 912 913 new->size = size; 914 915 /* Copy thresholds and find current threshold */ 916 new->current_threshold = -1; 917 for (i = 0, j = 0; i < thresholds->primary->size; i++) { 918 if (thresholds->primary->entries[i].eventfd == eventfd) 919 continue; 920 921 new->entries[j] = thresholds->primary->entries[i]; 922 if (new->entries[j].threshold <= usage) { 923 /* 924 * new->current_threshold will not be used 925 * until rcu_assign_pointer(), so it's safe to increment 926 * it here. 927 */ 928 ++new->current_threshold; 929 } 930 j++; 931 } 932 933 swap_buffers: 934 /* Swap primary and spare array */ 935 thresholds->spare = thresholds->primary; 936 937 rcu_assign_pointer(thresholds->primary, new); 938 939 /* To be sure that nobody uses thresholds */ 940 synchronize_rcu(); 941 942 /* If all events are unregistered, free the spare array */ 943 if (!new) { 944 kfree(thresholds->spare); 945 thresholds->spare = NULL; 946 } 947 unlock: 948 mutex_unlock(&memcg->thresholds_lock); 949 } 950 951 static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg, 952 struct eventfd_ctx *eventfd) 953 { 954 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM); 955 } 956 957 static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg, 958 struct eventfd_ctx *eventfd) 959 { 960 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP); 961 } 962 963 static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg, 964 struct eventfd_ctx *eventfd, const char *args) 965 { 966 struct mem_cgroup_eventfd_list *event; 967 968 event = kmalloc_obj(*event, GFP_KERNEL_ACCOUNT); 969 if (!event) 970 return -ENOMEM; 971 972 spin_lock(&memcg_oom_lock); 973 974 event->eventfd = eventfd; 975 list_add(&event->list, &memcg->oom_notify); 976 977 /* already in OOM ? */ 978 if (memcg->under_oom) 979 eventfd_signal(eventfd); 980 spin_unlock(&memcg_oom_lock); 981 982 return 0; 983 } 984 985 static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg, 986 struct eventfd_ctx *eventfd) 987 { 988 struct mem_cgroup_eventfd_list *ev, *tmp; 989 990 spin_lock(&memcg_oom_lock); 991 992 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) { 993 if (ev->eventfd == eventfd) { 994 list_del(&ev->list); 995 kfree(ev); 996 } 997 } 998 999 spin_unlock(&memcg_oom_lock); 1000 } 1001 1002 /* 1003 * DO NOT USE IN NEW FILES. 1004 * 1005 * "cgroup.event_control" implementation. 1006 * 1007 * This is way over-engineered. It tries to support fully configurable 1008 * events for each user. Such level of flexibility is completely 1009 * unnecessary especially in the light of the planned unified hierarchy. 1010 * 1011 * Please deprecate this and replace with something simpler if at all 1012 * possible. 1013 */ 1014 1015 /* 1016 * Unregister event and free resources. 1017 * 1018 * Gets called from workqueue. 1019 */ 1020 static void memcg_event_remove(struct work_struct *work) 1021 { 1022 struct mem_cgroup_event *event = 1023 container_of(work, struct mem_cgroup_event, remove); 1024 struct mem_cgroup *memcg = event->memcg; 1025 1026 remove_wait_queue(event->wqh, &event->wait); 1027 1028 event->unregister_event(memcg, event->eventfd); 1029 1030 /* Notify userspace the event is going away. */ 1031 eventfd_signal(event->eventfd); 1032 1033 eventfd_ctx_put(event->eventfd); 1034 kfree(event); 1035 css_put(&memcg->css); 1036 } 1037 1038 /* 1039 * Gets called on EPOLLHUP on eventfd when user closes it. 1040 * 1041 * Called with wqh->lock held and interrupts disabled. 1042 */ 1043 static int memcg_event_wake(wait_queue_entry_t *wait, unsigned int mode, 1044 int sync, void *key) 1045 { 1046 struct mem_cgroup_event *event = 1047 container_of(wait, struct mem_cgroup_event, wait); 1048 struct mem_cgroup *memcg = event->memcg; 1049 __poll_t flags = key_to_poll(key); 1050 1051 if (flags & EPOLLHUP) { 1052 /* 1053 * If the event has been detached at cgroup removal, we 1054 * can simply return knowing the other side will cleanup 1055 * for us. 1056 * 1057 * We can't race against event freeing since the other 1058 * side will require wqh->lock via remove_wait_queue(), 1059 * which we hold. 1060 */ 1061 spin_lock(&memcg->event_list_lock); 1062 if (!list_empty(&event->list)) { 1063 list_del_init(&event->list); 1064 /* 1065 * We are in atomic context, but cgroup_event_remove() 1066 * may sleep, so we have to call it in workqueue. 1067 */ 1068 schedule_work(&event->remove); 1069 } 1070 spin_unlock(&memcg->event_list_lock); 1071 } 1072 1073 return 0; 1074 } 1075 1076 static void memcg_event_ptable_queue_proc(struct file *file, 1077 wait_queue_head_t *wqh, poll_table *pt) 1078 { 1079 struct mem_cgroup_event *event = 1080 container_of(pt, struct mem_cgroup_event, pt); 1081 1082 event->wqh = wqh; 1083 add_wait_queue(wqh, &event->wait); 1084 } 1085 1086 /* 1087 * DO NOT USE IN NEW FILES. 1088 * 1089 * Parse input and register new cgroup event handler. 1090 * 1091 * Input must be in format '<event_fd> <control_fd> <args>'. 1092 * Interpretation of args is defined by control file implementation. 1093 */ 1094 static ssize_t memcg_write_event_control(struct kernfs_open_file *of, 1095 char *buf, size_t nbytes, loff_t off) 1096 { 1097 struct cgroup_subsys_state *css = of_css(of); 1098 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 1099 struct mem_cgroup_event *event; 1100 struct cgroup_subsys_state *cfile_css; 1101 unsigned int efd, cfd; 1102 struct dentry *cdentry; 1103 const char *name; 1104 char *endp; 1105 int ret; 1106 1107 if (IS_ENABLED(CONFIG_PREEMPT_RT)) 1108 return -EOPNOTSUPP; 1109 1110 buf = strstrip(buf); 1111 1112 efd = simple_strtoul(buf, &endp, 10); 1113 if (*endp != ' ') 1114 return -EINVAL; 1115 buf = endp + 1; 1116 1117 cfd = simple_strtoul(buf, &endp, 10); 1118 if (*endp == '\0') 1119 buf = endp; 1120 else if (*endp == ' ') 1121 buf = endp + 1; 1122 else 1123 return -EINVAL; 1124 1125 CLASS(fd, efile)(efd); 1126 if (fd_empty(efile)) 1127 return -EBADF; 1128 1129 CLASS(fd, cfile)(cfd); 1130 1131 event = kzalloc_obj(*event, GFP_KERNEL_ACCOUNT); 1132 if (!event) 1133 return -ENOMEM; 1134 1135 event->memcg = memcg; 1136 INIT_LIST_HEAD(&event->list); 1137 init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc); 1138 init_waitqueue_func_entry(&event->wait, memcg_event_wake); 1139 INIT_WORK(&event->remove, memcg_event_remove); 1140 1141 event->eventfd = eventfd_ctx_fileget(fd_file(efile)); 1142 if (IS_ERR(event->eventfd)) { 1143 ret = PTR_ERR(event->eventfd); 1144 goto out_kfree; 1145 } 1146 1147 if (fd_empty(cfile)) { 1148 ret = -EBADF; 1149 goto out_put_eventfd; 1150 } 1151 1152 /* the process need read permission on control file */ 1153 /* AV: shouldn't we check that it's been opened for read instead? */ 1154 ret = file_permission(fd_file(cfile), MAY_READ); 1155 if (ret < 0) 1156 goto out_put_eventfd; 1157 1158 /* 1159 * The control file must be a regular cgroup1 file. As a regular cgroup 1160 * file can't be renamed, it's safe to access its name afterwards. 1161 */ 1162 cdentry = fd_file(cfile)->f_path.dentry; 1163 if (cdentry->d_sb->s_type != &cgroup_fs_type || !d_is_reg(cdentry)) { 1164 ret = -EINVAL; 1165 goto out_put_eventfd; 1166 } 1167 1168 /* 1169 * Determine the event callbacks and set them in @event. This used 1170 * to be done via struct cftype but cgroup core no longer knows 1171 * about these events. The following is crude but the whole thing 1172 * is for compatibility anyway. 1173 * 1174 * DO NOT ADD NEW FILES. 1175 */ 1176 name = cdentry->d_name.name; 1177 1178 if (!strcmp(name, "memory.usage_in_bytes")) { 1179 event->register_event = mem_cgroup_usage_register_event; 1180 event->unregister_event = mem_cgroup_usage_unregister_event; 1181 } else if (!strcmp(name, "memory.oom_control")) { 1182 pr_warn_once("oom_control is deprecated and will be removed. " 1183 "Please report your usecase to linux-mm@kvack.org" 1184 " if you depend on this functionality.\n"); 1185 event->register_event = mem_cgroup_oom_register_event; 1186 event->unregister_event = mem_cgroup_oom_unregister_event; 1187 } else if (!strcmp(name, "memory.pressure_level")) { 1188 pr_warn_once("pressure_level is deprecated and will be removed. " 1189 "Please report your usecase to linux-mm@kvack.org " 1190 "if you depend on this functionality.\n"); 1191 event->register_event = vmpressure_register_event; 1192 event->unregister_event = vmpressure_unregister_event; 1193 } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) { 1194 event->register_event = memsw_cgroup_usage_register_event; 1195 event->unregister_event = memsw_cgroup_usage_unregister_event; 1196 } else { 1197 ret = -EINVAL; 1198 goto out_put_eventfd; 1199 } 1200 1201 /* 1202 * Verify @cfile should belong to @css. Also, remaining events are 1203 * automatically removed on cgroup destruction but the removal is 1204 * asynchronous, so take an extra ref on @css. 1205 */ 1206 cfile_css = css_tryget_online_from_dir(cdentry->d_parent, 1207 &memory_cgrp_subsys); 1208 ret = -EINVAL; 1209 if (IS_ERR(cfile_css)) 1210 goto out_put_eventfd; 1211 if (cfile_css != css) 1212 goto out_put_css; 1213 1214 ret = event->register_event(memcg, event->eventfd, buf); 1215 if (ret) 1216 goto out_put_css; 1217 1218 vfs_poll(fd_file(efile), &event->pt); 1219 1220 spin_lock_irq(&memcg->event_list_lock); 1221 list_add(&event->list, &memcg->event_list); 1222 spin_unlock_irq(&memcg->event_list_lock); 1223 return nbytes; 1224 1225 out_put_css: 1226 css_put(cfile_css); 1227 out_put_eventfd: 1228 eventfd_ctx_put(event->eventfd); 1229 out_kfree: 1230 kfree(event); 1231 return ret; 1232 } 1233 1234 void memcg1_memcg_init(struct mem_cgroup *memcg) 1235 { 1236 INIT_LIST_HEAD(&memcg->oom_notify); 1237 mutex_init(&memcg->thresholds_lock); 1238 INIT_LIST_HEAD(&memcg->event_list); 1239 spin_lock_init(&memcg->event_list_lock); 1240 } 1241 1242 void memcg1_css_offline(struct mem_cgroup *memcg) 1243 { 1244 struct mem_cgroup_event *event, *tmp; 1245 1246 /* 1247 * Unregister events and notify userspace. 1248 * Notify userspace about cgroup removing only after rmdir of cgroup 1249 * directory to avoid race between userspace and kernelspace. 1250 */ 1251 spin_lock_irq(&memcg->event_list_lock); 1252 list_for_each_entry_safe(event, tmp, &memcg->event_list, list) { 1253 list_del_init(&event->list); 1254 schedule_work(&event->remove); 1255 } 1256 spin_unlock_irq(&memcg->event_list_lock); 1257 } 1258 1259 /* 1260 * Check OOM-Killer is already running under our hierarchy. 1261 * If someone is running, return false. 1262 */ 1263 static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg) 1264 { 1265 struct mem_cgroup *iter, *failed = NULL; 1266 1267 spin_lock(&memcg_oom_lock); 1268 1269 for_each_mem_cgroup_tree(iter, memcg) { 1270 if (iter->oom_lock) { 1271 /* 1272 * this subtree of our hierarchy is already locked 1273 * so we cannot give a lock. 1274 */ 1275 failed = iter; 1276 mem_cgroup_iter_break(memcg, iter); 1277 break; 1278 } 1279 iter->oom_lock = true; 1280 } 1281 1282 if (failed) { 1283 /* 1284 * OK, we failed to lock the whole subtree so we have 1285 * to clean up what we set up to the failing subtree 1286 */ 1287 for_each_mem_cgroup_tree(iter, memcg) { 1288 if (iter == failed) { 1289 mem_cgroup_iter_break(memcg, iter); 1290 break; 1291 } 1292 iter->oom_lock = false; 1293 } 1294 } else 1295 mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_); 1296 1297 spin_unlock(&memcg_oom_lock); 1298 1299 return !failed; 1300 } 1301 1302 static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg) 1303 { 1304 struct mem_cgroup *iter; 1305 1306 spin_lock(&memcg_oom_lock); 1307 mutex_release(&memcg_oom_lock_dep_map, _RET_IP_); 1308 for_each_mem_cgroup_tree(iter, memcg) 1309 iter->oom_lock = false; 1310 spin_unlock(&memcg_oom_lock); 1311 } 1312 1313 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg) 1314 { 1315 struct mem_cgroup *iter; 1316 1317 spin_lock(&memcg_oom_lock); 1318 for_each_mem_cgroup_tree(iter, memcg) 1319 iter->under_oom++; 1320 spin_unlock(&memcg_oom_lock); 1321 } 1322 1323 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg) 1324 { 1325 struct mem_cgroup *iter; 1326 1327 /* 1328 * Be careful about under_oom underflows because a child memcg 1329 * could have been added after mem_cgroup_mark_under_oom. 1330 */ 1331 spin_lock(&memcg_oom_lock); 1332 for_each_mem_cgroup_tree(iter, memcg) 1333 if (iter->under_oom > 0) 1334 iter->under_oom--; 1335 spin_unlock(&memcg_oom_lock); 1336 } 1337 1338 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq); 1339 1340 struct oom_wait_info { 1341 struct mem_cgroup *memcg; 1342 wait_queue_entry_t wait; 1343 }; 1344 1345 static int memcg_oom_wake_function(wait_queue_entry_t *wait, 1346 unsigned int mode, int sync, void *arg) 1347 { 1348 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg; 1349 struct mem_cgroup *oom_wait_memcg; 1350 struct oom_wait_info *oom_wait_info; 1351 1352 oom_wait_info = container_of(wait, struct oom_wait_info, wait); 1353 oom_wait_memcg = oom_wait_info->memcg; 1354 1355 if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) && 1356 !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg)) 1357 return 0; 1358 return autoremove_wake_function(wait, mode, sync, arg); 1359 } 1360 1361 void memcg1_oom_recover(struct mem_cgroup *memcg) 1362 { 1363 /* 1364 * For the following lockless ->under_oom test, the only required 1365 * guarantee is that it must see the state asserted by an OOM when 1366 * this function is called as a result of userland actions 1367 * triggered by the notification of the OOM. This is trivially 1368 * achieved by invoking mem_cgroup_mark_under_oom() before 1369 * triggering notification. 1370 */ 1371 if (memcg && memcg->under_oom) 1372 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg); 1373 } 1374 1375 /** 1376 * mem_cgroup_oom_synchronize - complete memcg OOM handling 1377 * @handle: actually kill/wait or just clean up the OOM state 1378 * 1379 * This has to be called at the end of a page fault if the memcg OOM 1380 * handler was enabled. 1381 * 1382 * Memcg supports userspace OOM handling where failed allocations must 1383 * sleep on a waitqueue until the userspace task resolves the 1384 * situation. Sleeping directly in the charge context with all kinds 1385 * of locks held is not a good idea, instead we remember an OOM state 1386 * in the task and mem_cgroup_oom_synchronize() has to be called at 1387 * the end of the page fault to complete the OOM handling. 1388 * 1389 * Returns %true if an ongoing memcg OOM situation was detected and 1390 * completed, %false otherwise. 1391 */ 1392 bool mem_cgroup_oom_synchronize(bool handle) 1393 { 1394 struct mem_cgroup *memcg = current->memcg_in_oom; 1395 struct oom_wait_info owait; 1396 bool locked; 1397 1398 /* OOM is global, do not handle */ 1399 if (!memcg) 1400 return false; 1401 1402 if (!handle) 1403 goto cleanup; 1404 1405 owait.memcg = memcg; 1406 owait.wait.flags = 0; 1407 owait.wait.func = memcg_oom_wake_function; 1408 owait.wait.private = current; 1409 INIT_LIST_HEAD(&owait.wait.entry); 1410 1411 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE); 1412 mem_cgroup_mark_under_oom(memcg); 1413 1414 locked = mem_cgroup_oom_trylock(memcg); 1415 1416 if (locked) 1417 mem_cgroup_oom_notify(memcg); 1418 1419 schedule(); 1420 mem_cgroup_unmark_under_oom(memcg); 1421 finish_wait(&memcg_oom_waitq, &owait.wait); 1422 1423 if (locked) 1424 mem_cgroup_oom_unlock(memcg); 1425 cleanup: 1426 current->memcg_in_oom = NULL; 1427 css_put(&memcg->css); 1428 return true; 1429 } 1430 1431 1432 bool memcg1_oom_prepare(struct mem_cgroup *memcg, bool *locked) 1433 { 1434 /* 1435 * We are in the middle of the charge context here, so we 1436 * don't want to block when potentially sitting on a callstack 1437 * that holds all kinds of filesystem and mm locks. 1438 * 1439 * cgroup1 allows disabling the OOM killer and waiting for outside 1440 * handling until the charge can succeed; remember the context and put 1441 * the task to sleep at the end of the page fault when all locks are 1442 * released. 1443 * 1444 * On the other hand, in-kernel OOM killer allows for an async victim 1445 * memory reclaim (oom_reaper) and that means that we are not solely 1446 * relying on the oom victim to make a forward progress and we can 1447 * invoke the oom killer here. 1448 * 1449 * Please note that mem_cgroup_out_of_memory might fail to find a 1450 * victim and then we have to bail out from the charge path. 1451 */ 1452 if (READ_ONCE(memcg->oom_kill_disable)) { 1453 if (current->in_user_fault) { 1454 css_get(&memcg->css); 1455 current->memcg_in_oom = memcg; 1456 } 1457 return false; 1458 } 1459 1460 mem_cgroup_mark_under_oom(memcg); 1461 1462 *locked = mem_cgroup_oom_trylock(memcg); 1463 1464 if (*locked) 1465 mem_cgroup_oom_notify(memcg); 1466 1467 mem_cgroup_unmark_under_oom(memcg); 1468 1469 return true; 1470 } 1471 1472 void memcg1_oom_finish(struct mem_cgroup *memcg, bool locked) 1473 { 1474 if (locked) 1475 mem_cgroup_oom_unlock(memcg); 1476 } 1477 1478 /* 1479 * cgroup v1 userspace vmpressure interface (memory.pressure_level / 1480 * cgroup.event_control). Kept here so v2-only kernels (CONFIG_MEMCG_V1=n) 1481 * drop the whole eventfd accumulator, its work item, and the per-memcg 1482 * state it requires. 1483 * 1484 * When there are too little pages left to scan, vmpressure() may miss the 1485 * critical pressure as number of pages will be less than "window size". 1486 * However, in that case the vmscan priority will raise fast as the 1487 * reclaimer will try to scan LRUs more deeply. 1488 * 1489 * The vmscan logic considers these special priorities: 1490 * 1491 * prio == DEF_PRIORITY (12): reclaimer starts with that value 1492 * prio <= DEF_PRIORITY - 2 : kswapd becomes somewhat overwhelmed 1493 * prio == 0 : close to OOM, kernel scans every page in an lru 1494 * 1495 * Any value in this range is acceptable for this tunable (i.e. from 12 to 1496 * 0). Current value for the vmpressure_level_critical_prio is chosen 1497 * empirically, but the number, in essence, means that we consider 1498 * critical level when scanning depth is ~10% of the lru size (vmscan 1499 * scans 'lru_size >> prio' pages, so it is actually 12.5%, or one 1500 * eights). 1501 */ 1502 static const unsigned int vmpressure_level_critical_prio = ilog2(100 / 10); 1503 1504 enum vmpressure_modes { 1505 VMPRESSURE_NO_PASSTHROUGH = 0, 1506 VMPRESSURE_HIERARCHY, 1507 VMPRESSURE_LOCAL, 1508 VMPRESSURE_NUM_MODES, 1509 }; 1510 1511 static const char * const vmpressure_str_levels[] = { 1512 [VMPRESSURE_LOW] = "low", 1513 [VMPRESSURE_MEDIUM] = "medium", 1514 [VMPRESSURE_CRITICAL] = "critical", 1515 }; 1516 1517 static const char * const vmpressure_str_modes[] = { 1518 [VMPRESSURE_NO_PASSTHROUGH] = "default", 1519 [VMPRESSURE_HIERARCHY] = "hierarchy", 1520 [VMPRESSURE_LOCAL] = "local", 1521 }; 1522 1523 struct vmpressure_event { 1524 struct eventfd_ctx *efd; 1525 enum vmpressure_levels level; 1526 enum vmpressure_modes mode; 1527 struct list_head node; 1528 }; 1529 1530 static struct vmpressure *work_to_vmpressure(struct work_struct *work) 1531 { 1532 return container_of(work, struct vmpressure, work); 1533 } 1534 1535 static struct vmpressure *vmpressure_parent(struct vmpressure *vmpr) 1536 { 1537 struct mem_cgroup *memcg = vmpressure_to_memcg(vmpr); 1538 1539 memcg = parent_mem_cgroup(memcg); 1540 if (!memcg) 1541 return NULL; 1542 return memcg_to_vmpressure(memcg); 1543 } 1544 1545 static bool vmpressure_event(struct vmpressure *vmpr, 1546 const enum vmpressure_levels level, 1547 bool ancestor, bool signalled) 1548 { 1549 struct vmpressure_event *ev; 1550 bool ret = false; 1551 1552 mutex_lock(&vmpr->events_lock); 1553 list_for_each_entry(ev, &vmpr->events, node) { 1554 if (ancestor && ev->mode == VMPRESSURE_LOCAL) 1555 continue; 1556 if (signalled && ev->mode == VMPRESSURE_NO_PASSTHROUGH) 1557 continue; 1558 if (level < ev->level) 1559 continue; 1560 eventfd_signal(ev->efd); 1561 ret = true; 1562 } 1563 mutex_unlock(&vmpr->events_lock); 1564 1565 return ret; 1566 } 1567 1568 static void vmpressure_work_fn(struct work_struct *work) 1569 { 1570 struct vmpressure *vmpr = work_to_vmpressure(work); 1571 unsigned long scanned; 1572 unsigned long reclaimed; 1573 enum vmpressure_levels level; 1574 bool ancestor = false; 1575 bool signalled = false; 1576 1577 spin_lock(&vmpr->sr_lock); 1578 /* 1579 * Several contexts might be calling vmpressure(), so it is 1580 * possible that the work was rescheduled again before the old 1581 * work context cleared the counters. In that case we will run 1582 * just after the old work returns, but then scanned might be zero 1583 * here. No need for any locks here since we don't care if 1584 * vmpr->reclaimed is in sync. 1585 */ 1586 scanned = vmpr->tree_scanned; 1587 if (!scanned) { 1588 spin_unlock(&vmpr->sr_lock); 1589 return; 1590 } 1591 1592 reclaimed = vmpr->tree_reclaimed; 1593 vmpr->tree_scanned = 0; 1594 vmpr->tree_reclaimed = 0; 1595 spin_unlock(&vmpr->sr_lock); 1596 1597 level = vmpressure_calc_level(scanned, reclaimed); 1598 1599 do { 1600 if (vmpressure_event(vmpr, level, ancestor, signalled)) 1601 signalled = true; 1602 ancestor = true; 1603 } while ((vmpr = vmpressure_parent(vmpr))); 1604 } 1605 1606 /* 1607 * Tree-mode accumulator: accumulate per-memcg scanned/reclaimed and 1608 * schedule the work that walks the parent chain and signals registered 1609 * eventfd listeners once we cross the window threshold. 1610 */ 1611 void vmpressure_v1_account_tree(struct vmpressure *vmpr, 1612 unsigned long scanned, 1613 unsigned long reclaimed) 1614 { 1615 spin_lock(&vmpr->sr_lock); 1616 scanned = vmpr->tree_scanned += scanned; 1617 vmpr->tree_reclaimed += reclaimed; 1618 spin_unlock(&vmpr->sr_lock); 1619 1620 if (scanned < vmpressure_win) 1621 return; 1622 schedule_work(&vmpr->work); 1623 } 1624 1625 void vmpressure_v1_init(struct vmpressure *vmpr) 1626 { 1627 mutex_init(&vmpr->events_lock); 1628 INIT_LIST_HEAD(&vmpr->events); 1629 INIT_WORK(&vmpr->work, vmpressure_work_fn); 1630 } 1631 1632 void vmpressure_v1_cleanup(struct vmpressure *vmpr) 1633 { 1634 /* 1635 * Make sure there is no pending work before eventfd infrastructure 1636 * goes away. 1637 */ 1638 flush_work(&vmpr->work); 1639 } 1640 1641 /** 1642 * vmpressure_prio() - Account memory pressure through reclaimer priority level 1643 * @gfp: reclaimer's gfp mask 1644 * @memcg: cgroup memory controller handle 1645 * @prio: reclaimer's priority 1646 * 1647 * This function should be called from the reclaim path every time when 1648 * the vmscan's reclaiming priority (scanning depth) changes. 1649 * 1650 * This function does not return any value. 1651 */ 1652 void vmpressure_prio(gfp_t gfp, struct mem_cgroup *memcg, int prio) 1653 { 1654 /* 1655 * We only use prio for accounting critical level. For more info 1656 * see comment for vmpressure_level_critical_prio variable above. 1657 */ 1658 if (prio > vmpressure_level_critical_prio) 1659 return; 1660 1661 /* 1662 * OK, the prio is below the threshold, updating vmpressure 1663 * information before shrinker dives into long shrinking of long 1664 * range vmscan. Passing scanned = vmpressure_win, reclaimed = 0 1665 * to the vmpressure() basically means that we signal 'critical' 1666 * level. 1667 */ 1668 vmpressure(gfp, 0, memcg, true, vmpressure_win, 0); 1669 } 1670 1671 #define MAX_VMPRESSURE_ARGS_LEN (strlen("critical") + strlen("hierarchy") + 2) 1672 1673 /** 1674 * vmpressure_register_event() - Bind vmpressure notifications to an eventfd 1675 * @memcg: memcg that is interested in vmpressure notifications 1676 * @eventfd: eventfd context to link notifications with 1677 * @args: event arguments (pressure level threshold, optional mode) 1678 * 1679 * This function associates eventfd context with the vmpressure 1680 * infrastructure, so that the notifications will be delivered to the 1681 * @eventfd. The @args parameter is a comma-delimited string that denotes a 1682 * pressure level threshold (one of vmpressure_str_levels, i.e. "low", "medium", 1683 * or "critical") and an optional mode (one of vmpressure_str_modes, i.e. 1684 * "hierarchy" or "local"). 1685 * 1686 * To be used as memcg event method. 1687 * 1688 * Return: 0 on success, -ENOMEM on memory failure or -EINVAL if @args could 1689 * not be parsed. 1690 */ 1691 int vmpressure_register_event(struct mem_cgroup *memcg, 1692 struct eventfd_ctx *eventfd, const char *args) 1693 { 1694 struct vmpressure *vmpr = memcg_to_vmpressure(memcg); 1695 struct vmpressure_event *ev; 1696 enum vmpressure_modes mode = VMPRESSURE_NO_PASSTHROUGH; 1697 enum vmpressure_levels level; 1698 char *spec, *spec_orig; 1699 char *token; 1700 int ret = 0; 1701 1702 spec_orig = spec = kstrndup(args, MAX_VMPRESSURE_ARGS_LEN, GFP_KERNEL); 1703 if (!spec) 1704 return -ENOMEM; 1705 1706 /* Find required level */ 1707 token = strsep(&spec, ","); 1708 ret = match_string(vmpressure_str_levels, VMPRESSURE_NUM_LEVELS, token); 1709 if (ret < 0) 1710 goto out; 1711 level = ret; 1712 1713 /* Find optional mode */ 1714 token = strsep(&spec, ","); 1715 if (token) { 1716 ret = match_string(vmpressure_str_modes, VMPRESSURE_NUM_MODES, token); 1717 if (ret < 0) 1718 goto out; 1719 mode = ret; 1720 } 1721 1722 ev = kzalloc_obj(*ev, GFP_KERNEL_ACCOUNT); 1723 if (!ev) { 1724 ret = -ENOMEM; 1725 goto out; 1726 } 1727 1728 ev->efd = eventfd; 1729 ev->level = level; 1730 ev->mode = mode; 1731 1732 mutex_lock(&vmpr->events_lock); 1733 list_add(&ev->node, &vmpr->events); 1734 mutex_unlock(&vmpr->events_lock); 1735 ret = 0; 1736 out: 1737 kfree(spec_orig); 1738 return ret; 1739 } 1740 1741 /** 1742 * vmpressure_unregister_event() - Unbind eventfd from vmpressure 1743 * @memcg: memcg handle 1744 * @eventfd: eventfd context that was used to link vmpressure with the @cg 1745 * 1746 * This function does internal manipulations to detach the @eventfd from 1747 * the vmpressure notifications, and then frees internal resources 1748 * associated with the @eventfd (but the @eventfd itself is not freed). 1749 * 1750 * To be used as memcg event method. 1751 */ 1752 void vmpressure_unregister_event(struct mem_cgroup *memcg, 1753 struct eventfd_ctx *eventfd) 1754 { 1755 struct vmpressure *vmpr = memcg_to_vmpressure(memcg); 1756 struct vmpressure_event *ev; 1757 1758 mutex_lock(&vmpr->events_lock); 1759 list_for_each_entry(ev, &vmpr->events, node) { 1760 if (ev->efd != eventfd) 1761 continue; 1762 list_del(&ev->node); 1763 kfree(ev); 1764 break; 1765 } 1766 mutex_unlock(&vmpr->events_lock); 1767 } 1768 1769 static DEFINE_MUTEX(memcg_max_mutex); 1770 1771 static int mem_cgroup_resize_max(struct mem_cgroup *memcg, 1772 unsigned long max, bool memsw) 1773 { 1774 bool enlarge = false; 1775 bool drained = false; 1776 int ret; 1777 bool limits_invariant; 1778 struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory; 1779 1780 do { 1781 if (signal_pending(current)) { 1782 ret = -EINTR; 1783 break; 1784 } 1785 1786 mutex_lock(&memcg_max_mutex); 1787 /* 1788 * Make sure that the new limit (memsw or memory limit) doesn't 1789 * break our basic invariant rule memory.max <= memsw.max. 1790 */ 1791 limits_invariant = memsw ? max >= READ_ONCE(memcg->memory.max) : 1792 max <= memcg->memsw.max; 1793 if (!limits_invariant) { 1794 mutex_unlock(&memcg_max_mutex); 1795 ret = -EINVAL; 1796 break; 1797 } 1798 if (max > counter->max) 1799 enlarge = true; 1800 ret = page_counter_set_max(counter, max); 1801 mutex_unlock(&memcg_max_mutex); 1802 1803 if (!ret) 1804 break; 1805 1806 /* cgroup_rmdir() waits for us with cgroup_mutex held. */ 1807 if (memcg_is_dying(memcg)) 1808 break; 1809 1810 if (!drained) { 1811 drain_all_stock(memcg); 1812 drained = true; 1813 continue; 1814 } 1815 1816 if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL, 1817 memsw ? 0 : MEMCG_RECLAIM_MAY_SWAP, NULL)) { 1818 ret = -EBUSY; 1819 break; 1820 } 1821 } while (true); 1822 1823 if (!ret && enlarge) 1824 memcg1_oom_recover(memcg); 1825 1826 return ret; 1827 } 1828 1829 /* 1830 * Reclaims as many pages from the given memcg as possible. 1831 * 1832 * Caller is responsible for holding css reference for memcg. 1833 */ 1834 static int mem_cgroup_force_empty(struct mem_cgroup *memcg) 1835 { 1836 int nr_retries = MAX_RECLAIM_RETRIES; 1837 1838 /* we call try-to-free pages for make this cgroup empty */ 1839 lru_add_drain_all(); 1840 1841 drain_all_stock(memcg); 1842 1843 /* try to free all pages in this cgroup */ 1844 while (nr_retries && page_counter_read(&memcg->memory)) { 1845 if (signal_pending(current)) 1846 return -EINTR; 1847 1848 /* cgroup_rmdir() waits for us with cgroup_mutex held. */ 1849 if (memcg_is_dying(memcg)) 1850 break; 1851 1852 if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL, 1853 MEMCG_RECLAIM_MAY_SWAP, NULL)) 1854 nr_retries--; 1855 } 1856 1857 return 0; 1858 } 1859 1860 static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of, 1861 char *buf, size_t nbytes, 1862 loff_t off) 1863 { 1864 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 1865 1866 if (mem_cgroup_is_root(memcg)) 1867 return -EINVAL; 1868 return mem_cgroup_force_empty(memcg) ?: nbytes; 1869 } 1870 1871 static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css, 1872 struct cftype *cft) 1873 { 1874 return 1; 1875 } 1876 1877 static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css, 1878 struct cftype *cft, u64 val) 1879 { 1880 if (val == 1) 1881 return 0; 1882 1883 pr_warn_once("Non-hierarchical mode is deprecated. " 1884 "Please report your usecase to linux-mm@kvack.org if you " 1885 "depend on this functionality.\n"); 1886 1887 return -EINVAL; 1888 } 1889 1890 static u64 mem_cgroup_soft_limit_read(struct cgroup_subsys_state *css, 1891 struct cftype *cft) 1892 { 1893 return (u64)PAGE_COUNTER_MAX * PAGE_SIZE; 1894 } 1895 1896 static ssize_t mem_cgroup_soft_limit_write(struct kernfs_open_file *of, 1897 char *buf, size_t nbytes, loff_t off) 1898 { 1899 unsigned long nr_pages; 1900 int ret; 1901 1902 ret = page_counter_memparse(strstrip(buf), "-1", &nr_pages); 1903 if (ret) 1904 return ret; 1905 1906 pr_warn_once("soft_limit_in_bytes is deprecated and will be removed. " 1907 "Writing any value to this file has no effect. " 1908 "Please report your usecase to linux-mm@kvack.org if you " 1909 "depend on this functionality.\n"); 1910 1911 return nbytes; 1912 } 1913 1914 static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css, 1915 struct cftype *cft) 1916 { 1917 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 1918 struct page_counter *counter; 1919 1920 switch (MEMFILE_TYPE(cft->private)) { 1921 case _MEM: 1922 counter = &memcg->memory; 1923 break; 1924 case _MEMSWAP: 1925 counter = &memcg->memsw; 1926 break; 1927 case _KMEM: 1928 counter = &memcg->kmem; 1929 break; 1930 case _TCP: 1931 counter = &memcg->tcpmem; 1932 break; 1933 default: 1934 BUG(); 1935 } 1936 1937 switch (MEMFILE_ATTR(cft->private)) { 1938 case RES_USAGE: 1939 if (counter == &memcg->memory) 1940 return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE; 1941 if (counter == &memcg->memsw) 1942 return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE; 1943 return (u64)page_counter_read(counter) * PAGE_SIZE; 1944 case RES_LIMIT: 1945 return (u64)counter->max * PAGE_SIZE; 1946 case RES_MAX_USAGE: 1947 return (u64)counter->watermark * PAGE_SIZE; 1948 case RES_FAILCNT: 1949 return counter->failcnt; 1950 default: 1951 BUG(); 1952 } 1953 } 1954 1955 /* 1956 * This function doesn't do anything useful. Its only job is to provide a read 1957 * handler for a file so that cgroup_file_mode() will add read permissions. 1958 */ 1959 static int mem_cgroup_dummy_seq_show(__always_unused struct seq_file *m, 1960 __always_unused void *v) 1961 { 1962 return -EINVAL; 1963 } 1964 1965 static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max) 1966 { 1967 int ret; 1968 1969 mutex_lock(&memcg_max_mutex); 1970 1971 ret = page_counter_set_max(&memcg->tcpmem, max); 1972 if (ret) 1973 goto out; 1974 1975 if (!memcg->tcpmem_active) { 1976 /* 1977 * The active flag needs to be written after the static_key 1978 * update. This is what guarantees that the socket activation 1979 * function is the last one to run. See mem_cgroup_sk_alloc() 1980 * for details, and note that we don't mark any socket as 1981 * belonging to this memcg until that flag is up. 1982 * 1983 * We need to do this, because static_keys will span multiple 1984 * sites, but we can't control their order. If we mark a socket 1985 * as accounted, but the accounting functions are not patched in 1986 * yet, we'll lose accounting. 1987 * 1988 * We never race with the readers in mem_cgroup_sk_alloc(), 1989 * because when this value change, the code to process it is not 1990 * patched in yet. 1991 */ 1992 static_branch_inc(&memcg_sockets_enabled_key); 1993 memcg->tcpmem_active = true; 1994 } 1995 out: 1996 mutex_unlock(&memcg_max_mutex); 1997 return ret; 1998 } 1999 2000 /* 2001 * The user of this function is... 2002 * RES_LIMIT. 2003 */ 2004 static ssize_t mem_cgroup_write(struct kernfs_open_file *of, 2005 char *buf, size_t nbytes, loff_t off) 2006 { 2007 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 2008 unsigned long nr_pages; 2009 int ret; 2010 2011 buf = strstrip(buf); 2012 ret = page_counter_memparse(buf, "-1", &nr_pages); 2013 if (ret) 2014 return ret; 2015 2016 switch (MEMFILE_ATTR(of_cft(of)->private)) { 2017 case RES_LIMIT: 2018 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */ 2019 ret = -EINVAL; 2020 break; 2021 } 2022 switch (MEMFILE_TYPE(of_cft(of)->private)) { 2023 case _MEM: 2024 ret = mem_cgroup_resize_max(memcg, nr_pages, false); 2025 break; 2026 case _MEMSWAP: 2027 ret = mem_cgroup_resize_max(memcg, nr_pages, true); 2028 break; 2029 case _KMEM: 2030 pr_warn_once("kmem.limit_in_bytes is deprecated and will be removed. " 2031 "Writing any value to this file has no effect. " 2032 "Please report your usecase to linux-mm@kvack.org if you " 2033 "depend on this functionality.\n"); 2034 ret = 0; 2035 break; 2036 case _TCP: 2037 pr_warn_once("kmem.tcp.limit_in_bytes is deprecated and will be removed. " 2038 "Please report your usecase to linux-mm@kvack.org if you " 2039 "depend on this functionality.\n"); 2040 ret = memcg_update_tcp_max(memcg, nr_pages); 2041 break; 2042 } 2043 break; 2044 } 2045 return ret ?: nbytes; 2046 } 2047 2048 static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf, 2049 size_t nbytes, loff_t off) 2050 { 2051 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of)); 2052 struct page_counter *counter; 2053 2054 switch (MEMFILE_TYPE(of_cft(of)->private)) { 2055 case _MEM: 2056 counter = &memcg->memory; 2057 break; 2058 case _MEMSWAP: 2059 counter = &memcg->memsw; 2060 break; 2061 case _KMEM: 2062 counter = &memcg->kmem; 2063 break; 2064 case _TCP: 2065 counter = &memcg->tcpmem; 2066 break; 2067 default: 2068 BUG(); 2069 } 2070 2071 switch (MEMFILE_ATTR(of_cft(of)->private)) { 2072 case RES_MAX_USAGE: 2073 page_counter_reset_watermark(counter); 2074 break; 2075 case RES_FAILCNT: 2076 counter->failcnt = 0; 2077 break; 2078 default: 2079 BUG(); 2080 } 2081 2082 return nbytes; 2083 } 2084 2085 #ifdef CONFIG_NUMA 2086 2087 #define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE)) 2088 #define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON)) 2089 #define LRU_ALL ((1 << NR_LRU_LISTS) - 1) 2090 2091 static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg, 2092 int nid, unsigned int lru_mask, bool tree) 2093 { 2094 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid)); 2095 unsigned long nr = 0; 2096 enum lru_list lru; 2097 2098 VM_BUG_ON((unsigned int)nid >= nr_node_ids); 2099 2100 for_each_lru(lru) { 2101 if (!(BIT(lru) & lru_mask)) 2102 continue; 2103 if (tree) 2104 nr += lruvec_page_state(lruvec, NR_LRU_BASE + lru); 2105 else 2106 nr += lruvec_page_state_local(lruvec, NR_LRU_BASE + lru); 2107 } 2108 return nr; 2109 } 2110 2111 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg, 2112 unsigned int lru_mask, 2113 bool tree) 2114 { 2115 unsigned long nr = 0; 2116 enum lru_list lru; 2117 2118 for_each_lru(lru) { 2119 if (!(BIT(lru) & lru_mask)) 2120 continue; 2121 if (tree) 2122 nr += memcg_page_state(memcg, NR_LRU_BASE + lru); 2123 else 2124 nr += memcg_page_state_local(memcg, NR_LRU_BASE + lru); 2125 } 2126 return nr; 2127 } 2128 2129 static int memcg_numa_stat_show(struct seq_file *m, void *v) 2130 { 2131 struct numa_stat { 2132 const char *name; 2133 unsigned int lru_mask; 2134 }; 2135 2136 static const struct numa_stat stats[] = { 2137 { "total", LRU_ALL }, 2138 { "file", LRU_ALL_FILE }, 2139 { "anon", LRU_ALL_ANON }, 2140 { "unevictable", BIT(LRU_UNEVICTABLE) }, 2141 }; 2142 const struct numa_stat *stat; 2143 int nid; 2144 struct mem_cgroup *memcg = mem_cgroup_from_seq(m); 2145 2146 mem_cgroup_flush_stats(memcg); 2147 2148 for (stat = stats; stat < ARRAY_END(stats); stat++) { 2149 seq_printf(m, "%s=%lu", stat->name, 2150 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask, 2151 false)); 2152 for_each_node_state(nid, N_MEMORY) 2153 seq_printf(m, " N%d=%lu", nid, 2154 mem_cgroup_node_nr_lru_pages(memcg, nid, 2155 stat->lru_mask, false)); 2156 seq_putc(m, '\n'); 2157 } 2158 2159 for (stat = stats; stat < ARRAY_END(stats); stat++) { 2160 2161 seq_printf(m, "hierarchical_%s=%lu", stat->name, 2162 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask, 2163 true)); 2164 for_each_node_state(nid, N_MEMORY) 2165 seq_printf(m, " N%d=%lu", nid, 2166 mem_cgroup_node_nr_lru_pages(memcg, nid, 2167 stat->lru_mask, true)); 2168 seq_putc(m, '\n'); 2169 } 2170 2171 return 0; 2172 } 2173 #endif /* CONFIG_NUMA */ 2174 2175 static const unsigned int memcg1_stats[] = { 2176 NR_FILE_PAGES, 2177 NR_ANON_MAPPED, 2178 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 2179 NR_ANON_THPS, 2180 #endif 2181 NR_SHMEM, 2182 NR_FILE_MAPPED, 2183 NR_FILE_DIRTY, 2184 NR_WRITEBACK, 2185 WORKINGSET_REFAULT_ANON, 2186 WORKINGSET_REFAULT_FILE, 2187 #ifdef CONFIG_SWAP 2188 MEMCG_SWAP, 2189 NR_SWAPCACHE, 2190 #endif 2191 }; 2192 2193 static const char *const memcg1_stat_names[] = { 2194 "cache", 2195 "rss", 2196 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 2197 "rss_huge", 2198 #endif 2199 "shmem", 2200 "mapped_file", 2201 "dirty", 2202 "writeback", 2203 "workingset_refault_anon", 2204 "workingset_refault_file", 2205 #ifdef CONFIG_SWAP 2206 "swap", 2207 "swapcached", 2208 #endif 2209 }; 2210 2211 /* Universal VM events cgroup1 shows, original sort order */ 2212 static const unsigned int memcg1_events[] = { 2213 PGPGIN, 2214 PGPGOUT, 2215 PGFAULT, 2216 PGMAJFAULT, 2217 }; 2218 2219 void reparent_memcg1_state_local(struct mem_cgroup *memcg, struct mem_cgroup *parent) 2220 { 2221 int i; 2222 2223 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) 2224 reparent_memcg_state_local(memcg, parent, memcg1_stats[i]); 2225 } 2226 2227 void reparent_memcg1_lruvec_state_local(struct mem_cgroup *memcg, struct mem_cgroup *parent) 2228 { 2229 int i; 2230 2231 for (i = 0; i < NR_LRU_LISTS; i++) 2232 reparent_memcg_lruvec_state_local(memcg, parent, i); 2233 } 2234 2235 void memcg1_stat_format(struct mem_cgroup *memcg, struct seq_buf *s) 2236 { 2237 unsigned long memory, memsw; 2238 struct mem_cgroup *mi; 2239 unsigned int i; 2240 2241 BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats)); 2242 2243 mem_cgroup_flush_stats(memcg); 2244 2245 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) { 2246 unsigned long nr; 2247 2248 nr = memcg_page_state_local_output(memcg, memcg1_stats[i]); 2249 seq_buf_printf(s, "%s %lu\n", memcg1_stat_names[i], nr); 2250 } 2251 2252 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++) 2253 seq_buf_printf(s, "%s %lu\n", vm_event_name(memcg1_events[i]), 2254 memcg_events_local(memcg, memcg1_events[i])); 2255 2256 for (i = 0; i < NR_LRU_LISTS; i++) 2257 seq_buf_printf(s, "%s %lu\n", lru_list_name(i), 2258 memcg_page_state_local(memcg, NR_LRU_BASE + i) * 2259 PAGE_SIZE); 2260 2261 /* Hierarchical information */ 2262 memory = memsw = PAGE_COUNTER_MAX; 2263 for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) { 2264 memory = min(memory, READ_ONCE(mi->memory.max)); 2265 memsw = min(memsw, READ_ONCE(mi->memsw.max)); 2266 } 2267 seq_buf_printf(s, "hierarchical_memory_limit %llu\n", 2268 (u64)memory * PAGE_SIZE); 2269 seq_buf_printf(s, "hierarchical_memsw_limit %llu\n", 2270 (u64)memsw * PAGE_SIZE); 2271 2272 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) { 2273 unsigned long nr; 2274 2275 nr = memcg_page_state_output(memcg, memcg1_stats[i]); 2276 seq_buf_printf(s, "total_%s %llu\n", memcg1_stat_names[i], 2277 (u64)nr); 2278 } 2279 2280 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++) 2281 seq_buf_printf(s, "total_%s %llu\n", 2282 vm_event_name(memcg1_events[i]), 2283 (u64)memcg_events(memcg, memcg1_events[i])); 2284 2285 for (i = 0; i < NR_LRU_LISTS; i++) 2286 seq_buf_printf(s, "total_%s %llu\n", lru_list_name(i), 2287 (u64)memcg_page_state(memcg, NR_LRU_BASE + i) * 2288 PAGE_SIZE); 2289 2290 #ifdef CONFIG_DEBUG_VM 2291 { 2292 pg_data_t *pgdat; 2293 struct mem_cgroup_per_node *mz; 2294 unsigned long anon_cost = 0; 2295 unsigned long file_cost = 0; 2296 2297 for_each_online_pgdat(pgdat) { 2298 mz = memcg->nodeinfo[pgdat->node_id]; 2299 2300 anon_cost += mz->lruvec.cost[WORKINGSET_ANON].count; 2301 file_cost += mz->lruvec.cost[WORKINGSET_FILE].count; 2302 } 2303 seq_buf_printf(s, "anon_cost %lu\n", anon_cost); 2304 seq_buf_printf(s, "file_cost %lu\n", file_cost); 2305 } 2306 #endif 2307 } 2308 2309 static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css, 2310 struct cftype *cft) 2311 { 2312 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 2313 2314 return mem_cgroup_swappiness(memcg); 2315 } 2316 2317 static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css, 2318 struct cftype *cft, u64 val) 2319 { 2320 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 2321 2322 if (val > MAX_SWAPPINESS) 2323 return -EINVAL; 2324 2325 if (!mem_cgroup_is_root(memcg)) { 2326 pr_info_once("Per memcg swappiness does not exist in cgroup v2. " 2327 "See memory.reclaim or memory.swap.max there\n "); 2328 WRITE_ONCE(memcg->swappiness, val); 2329 } else 2330 WRITE_ONCE(vm_swappiness, val); 2331 2332 return 0; 2333 } 2334 2335 static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v) 2336 { 2337 struct mem_cgroup *memcg = mem_cgroup_from_seq(sf); 2338 2339 seq_printf(sf, "oom_kill_disable %d\n", READ_ONCE(memcg->oom_kill_disable)); 2340 seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom); 2341 seq_printf(sf, "oom_kill %lu\n", 2342 atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL])); 2343 return 0; 2344 } 2345 2346 static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css, 2347 struct cftype *cft, u64 val) 2348 { 2349 struct mem_cgroup *memcg = mem_cgroup_from_css(css); 2350 2351 pr_warn_once("oom_control is deprecated and will be removed. " 2352 "Please report your usecase to linux-mm@kvack.org if you " 2353 "depend on this functionality.\n"); 2354 2355 /* cannot set to root cgroup and only 0 and 1 are allowed */ 2356 if (mem_cgroup_is_root(memcg) || !((val == 0) || (val == 1))) 2357 return -EINVAL; 2358 2359 WRITE_ONCE(memcg->oom_kill_disable, val); 2360 if (!val) 2361 memcg1_oom_recover(memcg); 2362 2363 return 0; 2364 } 2365 2366 #ifdef CONFIG_SLUB_DEBUG 2367 static int mem_cgroup_slab_show(struct seq_file *m, void *p) 2368 { 2369 /* 2370 * Deprecated. 2371 * Please, take a look at tools/cgroup/memcg_slabinfo.py . 2372 */ 2373 return 0; 2374 } 2375 #endif 2376 2377 struct cftype mem_cgroup_legacy_files[] = { 2378 { 2379 .name = "usage_in_bytes", 2380 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE), 2381 .read_u64 = mem_cgroup_read_u64, 2382 }, 2383 { 2384 .name = "max_usage_in_bytes", 2385 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE), 2386 .write = mem_cgroup_reset, 2387 .read_u64 = mem_cgroup_read_u64, 2388 }, 2389 { 2390 .name = "limit_in_bytes", 2391 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT), 2392 .write = mem_cgroup_write, 2393 .read_u64 = mem_cgroup_read_u64, 2394 }, 2395 { 2396 .name = "soft_limit_in_bytes", 2397 .write = mem_cgroup_soft_limit_write, 2398 .read_u64 = mem_cgroup_soft_limit_read, 2399 }, 2400 { 2401 .name = "failcnt", 2402 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT), 2403 .write = mem_cgroup_reset, 2404 .read_u64 = mem_cgroup_read_u64, 2405 }, 2406 { 2407 .name = "stat", 2408 .seq_show = memory_stat_show, 2409 }, 2410 { 2411 .name = "force_empty", 2412 .write = mem_cgroup_force_empty_write, 2413 }, 2414 { 2415 .name = "use_hierarchy", 2416 .write_u64 = mem_cgroup_hierarchy_write, 2417 .read_u64 = mem_cgroup_hierarchy_read, 2418 }, 2419 { 2420 .name = "cgroup.event_control", /* XXX: for compat */ 2421 .write = memcg_write_event_control, 2422 .flags = CFTYPE_NO_PREFIX, 2423 }, 2424 { 2425 .name = "swappiness", 2426 .read_u64 = mem_cgroup_swappiness_read, 2427 .write_u64 = mem_cgroup_swappiness_write, 2428 }, 2429 { 2430 .name = "move_charge_at_immigrate", 2431 .read_u64 = mem_cgroup_move_charge_read, 2432 .write_u64 = mem_cgroup_move_charge_write, 2433 }, 2434 { 2435 .name = "oom_control", 2436 .seq_show = mem_cgroup_oom_control_read, 2437 .write_u64 = mem_cgroup_oom_control_write, 2438 }, 2439 { 2440 .name = "pressure_level", 2441 .seq_show = mem_cgroup_dummy_seq_show, 2442 }, 2443 #ifdef CONFIG_NUMA 2444 { 2445 .name = "numa_stat", 2446 .seq_show = memcg_numa_stat_show, 2447 }, 2448 #endif 2449 { 2450 .name = "kmem.limit_in_bytes", 2451 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT), 2452 .write = mem_cgroup_write, 2453 .read_u64 = mem_cgroup_read_u64, 2454 }, 2455 { 2456 .name = "kmem.usage_in_bytes", 2457 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE), 2458 .read_u64 = mem_cgroup_read_u64, 2459 }, 2460 { 2461 .name = "kmem.failcnt", 2462 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT), 2463 .write = mem_cgroup_reset, 2464 .read_u64 = mem_cgroup_read_u64, 2465 }, 2466 { 2467 .name = "kmem.max_usage_in_bytes", 2468 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE), 2469 .write = mem_cgroup_reset, 2470 .read_u64 = mem_cgroup_read_u64, 2471 }, 2472 #ifdef CONFIG_SLUB_DEBUG 2473 { 2474 .name = "kmem.slabinfo", 2475 .seq_show = mem_cgroup_slab_show, 2476 }, 2477 #endif 2478 { 2479 .name = "kmem.tcp.limit_in_bytes", 2480 .private = MEMFILE_PRIVATE(_TCP, RES_LIMIT), 2481 .write = mem_cgroup_write, 2482 .read_u64 = mem_cgroup_read_u64, 2483 }, 2484 { 2485 .name = "kmem.tcp.usage_in_bytes", 2486 .private = MEMFILE_PRIVATE(_TCP, RES_USAGE), 2487 .read_u64 = mem_cgroup_read_u64, 2488 }, 2489 { 2490 .name = "kmem.tcp.failcnt", 2491 .private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT), 2492 .write = mem_cgroup_reset, 2493 .read_u64 = mem_cgroup_read_u64, 2494 }, 2495 { 2496 .name = "kmem.tcp.max_usage_in_bytes", 2497 .private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE), 2498 .write = mem_cgroup_reset, 2499 .read_u64 = mem_cgroup_read_u64, 2500 }, 2501 { }, /* terminate */ 2502 }; 2503 2504 struct cftype memsw_files[] = { 2505 { 2506 .name = "memsw.usage_in_bytes", 2507 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE), 2508 .read_u64 = mem_cgroup_read_u64, 2509 }, 2510 { 2511 .name = "memsw.max_usage_in_bytes", 2512 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE), 2513 .write = mem_cgroup_reset, 2514 .read_u64 = mem_cgroup_read_u64, 2515 }, 2516 { 2517 .name = "memsw.limit_in_bytes", 2518 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT), 2519 .write = mem_cgroup_write, 2520 .read_u64 = mem_cgroup_read_u64, 2521 }, 2522 { 2523 .name = "memsw.failcnt", 2524 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT), 2525 .write = mem_cgroup_reset, 2526 .read_u64 = mem_cgroup_read_u64, 2527 }, 2528 { }, /* terminate */ 2529 }; 2530 2531 void memcg1_account_kmem(struct mem_cgroup *memcg, int nr_pages) 2532 { 2533 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) { 2534 if (nr_pages > 0) 2535 page_counter_charge(&memcg->kmem, nr_pages); 2536 else 2537 page_counter_uncharge(&memcg->kmem, -nr_pages); 2538 } 2539 } 2540 2541 bool memcg1_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages, 2542 gfp_t gfp_mask) 2543 { 2544 struct page_counter *fail; 2545 2546 if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) { 2547 memcg->tcpmem_pressure = 0; 2548 return true; 2549 } 2550 memcg->tcpmem_pressure = 1; 2551 if (gfp_mask & __GFP_NOFAIL) { 2552 page_counter_charge(&memcg->tcpmem, nr_pages); 2553 return true; 2554 } 2555 return false; 2556 } 2557 2558 bool memcg1_alloc_events(struct mem_cgroup *memcg) 2559 { 2560 memcg->events_percpu = alloc_percpu_gfp(struct memcg1_events_percpu, 2561 GFP_KERNEL_ACCOUNT); 2562 return !!memcg->events_percpu; 2563 } 2564 2565 void memcg1_free_events(struct mem_cgroup *memcg) 2566 { 2567 free_percpu(memcg->events_percpu); 2568 } 2569 2570 static int __init memcg1_init(void) 2571 { 2572 int node; 2573 2574 for_each_node(node) { 2575 struct mem_cgroup_tree_per_node *rtpn; 2576 2577 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, node); 2578 2579 rtpn->rb_root = RB_ROOT; 2580 rtpn->rb_rightmost = NULL; 2581 spin_lock_init(&rtpn->lock); 2582 soft_limit_tree.rb_tree_per_node[node] = rtpn; 2583 } 2584 2585 return 0; 2586 } 2587 subsys_initcall(memcg1_init); 2588