1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* memcontrol.c - Memory Controller
4 * Copyright IBM Corporation, 2007
5 * Author Balbir Singh <balbir@linux.vnet.ibm.com>
7 * Copyright 2007 OpenVZ SWsoft Inc
8 * Author: Pavel Emelianov <xemul@openvz.org>
11 * Copyright (C) 2009 Nokia Corporation
12 * Author: Kirill A. Shutemov
14 * Kernel Memory Controller
15 * Copyright (C) 2012 Parallels Inc. and Google Inc.
16 * Authors: Glauber Costa and Suleiman Souhlal
19 * Charge lifetime sanitation
20 * Lockless page tracking & accounting
21 * Unified hierarchy configuration model
22 * Copyright (C) 2015 Red Hat, Inc., Johannes Weiner
24 * Per memcg lru locking
25 * Copyright (C) 2020 Alibaba, Inc, Alex Shi
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>
54 #include <linux/seq_file.h>
55 #include <linux/vmpressure.h>
56 #include <linux/memremap.h>
57 #include <linux/mm_inline.h>
58 #include <linux/swap_cgroup.h>
59 #include <linux/cpu.h>
60 #include <linux/oom.h>
61 #include <linux/lockdep.h>
62 #include <linux/file.h>
63 #include <linux/resume_user_mode.h>
64 #include <linux/psi.h>
65 #include <linux/seq_buf.h>
66 #include <linux/sched/isolation.h>
73 #include <linux/uaccess.h>
75 #include <trace/events/vmscan.h>
77 struct cgroup_subsys memory_cgrp_subsys __read_mostly;
78 EXPORT_SYMBOL(memory_cgrp_subsys);
80 struct mem_cgroup *root_mem_cgroup __read_mostly;
82 /* Active memory cgroup to use from an interrupt context */
83 DEFINE_PER_CPU(struct mem_cgroup *, int_active_memcg);
84 EXPORT_PER_CPU_SYMBOL_GPL(int_active_memcg);
86 /* Socket memory accounting disabled? */
87 static bool cgroup_memory_nosocket __ro_after_init;
89 /* Kernel memory accounting disabled? */
90 static bool cgroup_memory_nokmem __ro_after_init;
92 /* BPF memory accounting disabled? */
93 static bool cgroup_memory_nobpf __ro_after_init;
95 #ifdef CONFIG_CGROUP_WRITEBACK
96 static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq);
99 /* Whether legacy memory+swap accounting is active */
100 static bool do_memsw_account(void)
102 return !cgroup_subsys_on_dfl(memory_cgrp_subsys);
105 #define THRESHOLDS_EVENTS_TARGET 128
106 #define SOFTLIMIT_EVENTS_TARGET 1024
109 * Cgroups above their limits are maintained in a RB-Tree, independent of
110 * their hierarchy representation
113 struct mem_cgroup_tree_per_node {
114 struct rb_root rb_root;
115 struct rb_node *rb_rightmost;
119 struct mem_cgroup_tree {
120 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
123 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
126 struct mem_cgroup_eventfd_list {
127 struct list_head list;
128 struct eventfd_ctx *eventfd;
132 * cgroup_event represents events which userspace want to receive.
134 struct mem_cgroup_event {
136 * memcg which the event belongs to.
138 struct mem_cgroup *memcg;
140 * eventfd to signal userspace about the event.
142 struct eventfd_ctx *eventfd;
144 * Each of these stored in a list by the cgroup.
146 struct list_head list;
148 * register_event() callback will be used to add new userspace
149 * waiter for changes related to this event. Use eventfd_signal()
150 * on eventfd to send notification to userspace.
152 int (*register_event)(struct mem_cgroup *memcg,
153 struct eventfd_ctx *eventfd, const char *args);
155 * unregister_event() callback will be called when userspace closes
156 * the eventfd or on cgroup removing. This callback must be set,
157 * if you want provide notification functionality.
159 void (*unregister_event)(struct mem_cgroup *memcg,
160 struct eventfd_ctx *eventfd);
162 * All fields below needed to unregister event when
163 * userspace closes eventfd.
166 wait_queue_head_t *wqh;
167 wait_queue_entry_t wait;
168 struct work_struct remove;
171 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
172 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
174 /* Stuffs for move charges at task migration. */
176 * Types of charges to be moved.
178 #define MOVE_ANON 0x1U
179 #define MOVE_FILE 0x2U
180 #define MOVE_MASK (MOVE_ANON | MOVE_FILE)
182 /* "mc" and its members are protected by cgroup_mutex */
183 static struct move_charge_struct {
184 spinlock_t lock; /* for from, to */
185 struct mm_struct *mm;
186 struct mem_cgroup *from;
187 struct mem_cgroup *to;
189 unsigned long precharge;
190 unsigned long moved_charge;
191 unsigned long moved_swap;
192 struct task_struct *moving_task; /* a task moving charges */
193 wait_queue_head_t waitq; /* a waitq for other context */
195 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
196 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
200 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
201 * limit reclaim to prevent infinite loops, if they ever occur.
203 #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
204 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
206 /* for encoding cft->private value on file */
214 #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
215 #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
216 #define MEMFILE_ATTR(val) ((val) & 0xffff)
219 * Iteration constructs for visiting all cgroups (under a tree). If
220 * loops are exited prematurely (break), mem_cgroup_iter_break() must
221 * be used for reference counting.
223 #define for_each_mem_cgroup_tree(iter, root) \
224 for (iter = mem_cgroup_iter(root, NULL, NULL); \
226 iter = mem_cgroup_iter(root, iter, NULL))
228 #define for_each_mem_cgroup(iter) \
229 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
231 iter = mem_cgroup_iter(NULL, iter, NULL))
233 static inline bool task_is_dying(void)
235 return tsk_is_oom_victim(current) || fatal_signal_pending(current) ||
236 (current->flags & PF_EXITING);
239 /* Some nice accessors for the vmpressure. */
240 struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
243 memcg = root_mem_cgroup;
244 return &memcg->vmpressure;
247 struct mem_cgroup *vmpressure_to_memcg(struct vmpressure *vmpr)
249 return container_of(vmpr, struct mem_cgroup, vmpressure);
252 #ifdef CONFIG_MEMCG_KMEM
253 static DEFINE_SPINLOCK(objcg_lock);
255 bool mem_cgroup_kmem_disabled(void)
257 return cgroup_memory_nokmem;
260 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
261 unsigned int nr_pages);
263 static void obj_cgroup_release(struct percpu_ref *ref)
265 struct obj_cgroup *objcg = container_of(ref, struct obj_cgroup, refcnt);
266 unsigned int nr_bytes;
267 unsigned int nr_pages;
271 * At this point all allocated objects are freed, and
272 * objcg->nr_charged_bytes can't have an arbitrary byte value.
273 * However, it can be PAGE_SIZE or (x * PAGE_SIZE).
275 * The following sequence can lead to it:
276 * 1) CPU0: objcg == stock->cached_objcg
277 * 2) CPU1: we do a small allocation (e.g. 92 bytes),
278 * PAGE_SIZE bytes are charged
279 * 3) CPU1: a process from another memcg is allocating something,
280 * the stock if flushed,
281 * objcg->nr_charged_bytes = PAGE_SIZE - 92
282 * 5) CPU0: we do release this object,
283 * 92 bytes are added to stock->nr_bytes
284 * 6) CPU0: stock is flushed,
285 * 92 bytes are added to objcg->nr_charged_bytes
287 * In the result, nr_charged_bytes == PAGE_SIZE.
288 * This page will be uncharged in obj_cgroup_release().
290 nr_bytes = atomic_read(&objcg->nr_charged_bytes);
291 WARN_ON_ONCE(nr_bytes & (PAGE_SIZE - 1));
292 nr_pages = nr_bytes >> PAGE_SHIFT;
295 obj_cgroup_uncharge_pages(objcg, nr_pages);
297 spin_lock_irqsave(&objcg_lock, flags);
298 list_del(&objcg->list);
299 spin_unlock_irqrestore(&objcg_lock, flags);
301 percpu_ref_exit(ref);
302 kfree_rcu(objcg, rcu);
305 static struct obj_cgroup *obj_cgroup_alloc(void)
307 struct obj_cgroup *objcg;
310 objcg = kzalloc(sizeof(struct obj_cgroup), GFP_KERNEL);
314 ret = percpu_ref_init(&objcg->refcnt, obj_cgroup_release, 0,
320 INIT_LIST_HEAD(&objcg->list);
324 static void memcg_reparent_objcgs(struct mem_cgroup *memcg,
325 struct mem_cgroup *parent)
327 struct obj_cgroup *objcg, *iter;
329 objcg = rcu_replace_pointer(memcg->objcg, NULL, true);
331 spin_lock_irq(&objcg_lock);
333 /* 1) Ready to reparent active objcg. */
334 list_add(&objcg->list, &memcg->objcg_list);
335 /* 2) Reparent active objcg and already reparented objcgs to parent. */
336 list_for_each_entry(iter, &memcg->objcg_list, list)
337 WRITE_ONCE(iter->memcg, parent);
338 /* 3) Move already reparented objcgs to the parent's list */
339 list_splice(&memcg->objcg_list, &parent->objcg_list);
341 spin_unlock_irq(&objcg_lock);
343 percpu_ref_kill(&objcg->refcnt);
347 * A lot of the calls to the cache allocation functions are expected to be
348 * inlined by the compiler. Since the calls to memcg_slab_pre_alloc_hook() are
349 * conditional to this static branch, we'll have to allow modules that does
350 * kmem_cache_alloc and the such to see this symbol as well
352 DEFINE_STATIC_KEY_FALSE(memcg_kmem_online_key);
353 EXPORT_SYMBOL(memcg_kmem_online_key);
355 DEFINE_STATIC_KEY_FALSE(memcg_bpf_enabled_key);
356 EXPORT_SYMBOL(memcg_bpf_enabled_key);
360 * mem_cgroup_css_from_folio - css of the memcg associated with a folio
361 * @folio: folio of interest
363 * If memcg is bound to the default hierarchy, css of the memcg associated
364 * with @folio is returned. The returned css remains associated with @folio
365 * until it is released.
367 * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
370 struct cgroup_subsys_state *mem_cgroup_css_from_folio(struct folio *folio)
372 struct mem_cgroup *memcg = folio_memcg(folio);
374 if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
375 memcg = root_mem_cgroup;
381 * page_cgroup_ino - return inode number of the memcg a page is charged to
384 * Look up the closest online ancestor of the memory cgroup @page is charged to
385 * and return its inode number or 0 if @page is not charged to any cgroup. It
386 * is safe to call this function without holding a reference to @page.
388 * Note, this function is inherently racy, because there is nothing to prevent
389 * the cgroup inode from getting torn down and potentially reallocated a moment
390 * after page_cgroup_ino() returns, so it only should be used by callers that
391 * do not care (such as procfs interfaces).
393 ino_t page_cgroup_ino(struct page *page)
395 struct mem_cgroup *memcg;
396 unsigned long ino = 0;
399 /* page_folio() is racy here, but the entire function is racy anyway */
400 memcg = folio_memcg_check(page_folio(page));
402 while (memcg && !(memcg->css.flags & CSS_ONLINE))
403 memcg = parent_mem_cgroup(memcg);
405 ino = cgroup_ino(memcg->css.cgroup);
410 static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_node *mz,
411 struct mem_cgroup_tree_per_node *mctz,
412 unsigned long new_usage_in_excess)
414 struct rb_node **p = &mctz->rb_root.rb_node;
415 struct rb_node *parent = NULL;
416 struct mem_cgroup_per_node *mz_node;
417 bool rightmost = true;
422 mz->usage_in_excess = new_usage_in_excess;
423 if (!mz->usage_in_excess)
427 mz_node = rb_entry(parent, struct mem_cgroup_per_node,
429 if (mz->usage_in_excess < mz_node->usage_in_excess) {
438 mctz->rb_rightmost = &mz->tree_node;
440 rb_link_node(&mz->tree_node, parent, p);
441 rb_insert_color(&mz->tree_node, &mctz->rb_root);
445 static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
446 struct mem_cgroup_tree_per_node *mctz)
451 if (&mz->tree_node == mctz->rb_rightmost)
452 mctz->rb_rightmost = rb_prev(&mz->tree_node);
454 rb_erase(&mz->tree_node, &mctz->rb_root);
458 static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
459 struct mem_cgroup_tree_per_node *mctz)
463 spin_lock_irqsave(&mctz->lock, flags);
464 __mem_cgroup_remove_exceeded(mz, mctz);
465 spin_unlock_irqrestore(&mctz->lock, flags);
468 static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
470 unsigned long nr_pages = page_counter_read(&memcg->memory);
471 unsigned long soft_limit = READ_ONCE(memcg->soft_limit);
472 unsigned long excess = 0;
474 if (nr_pages > soft_limit)
475 excess = nr_pages - soft_limit;
480 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, int nid)
482 unsigned long excess;
483 struct mem_cgroup_per_node *mz;
484 struct mem_cgroup_tree_per_node *mctz;
486 if (lru_gen_enabled()) {
487 if (soft_limit_excess(memcg))
488 lru_gen_soft_reclaim(&memcg->nodeinfo[nid]->lruvec);
492 mctz = soft_limit_tree.rb_tree_per_node[nid];
496 * Necessary to update all ancestors when hierarchy is used.
497 * because their event counter is not touched.
499 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
500 mz = memcg->nodeinfo[nid];
501 excess = soft_limit_excess(memcg);
503 * We have to update the tree if mz is on RB-tree or
504 * mem is over its softlimit.
506 if (excess || mz->on_tree) {
509 spin_lock_irqsave(&mctz->lock, flags);
510 /* if on-tree, remove it */
512 __mem_cgroup_remove_exceeded(mz, mctz);
514 * Insert again. mz->usage_in_excess will be updated.
515 * If excess is 0, no tree ops.
517 __mem_cgroup_insert_exceeded(mz, mctz, excess);
518 spin_unlock_irqrestore(&mctz->lock, flags);
523 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
525 struct mem_cgroup_tree_per_node *mctz;
526 struct mem_cgroup_per_node *mz;
530 mz = memcg->nodeinfo[nid];
531 mctz = soft_limit_tree.rb_tree_per_node[nid];
533 mem_cgroup_remove_exceeded(mz, mctz);
537 static struct mem_cgroup_per_node *
538 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
540 struct mem_cgroup_per_node *mz;
544 if (!mctz->rb_rightmost)
545 goto done; /* Nothing to reclaim from */
547 mz = rb_entry(mctz->rb_rightmost,
548 struct mem_cgroup_per_node, tree_node);
550 * Remove the node now but someone else can add it back,
551 * we will to add it back at the end of reclaim to its correct
552 * position in the tree.
554 __mem_cgroup_remove_exceeded(mz, mctz);
555 if (!soft_limit_excess(mz->memcg) ||
556 !css_tryget(&mz->memcg->css))
562 static struct mem_cgroup_per_node *
563 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
565 struct mem_cgroup_per_node *mz;
567 spin_lock_irq(&mctz->lock);
568 mz = __mem_cgroup_largest_soft_limit_node(mctz);
569 spin_unlock_irq(&mctz->lock);
574 * memcg and lruvec stats flushing
576 * Many codepaths leading to stats update or read are performance sensitive and
577 * adding stats flushing in such codepaths is not desirable. So, to optimize the
578 * flushing the kernel does:
580 * 1) Periodically and asynchronously flush the stats every 2 seconds to not let
581 * rstat update tree grow unbounded.
583 * 2) Flush the stats synchronously on reader side only when there are more than
584 * (MEMCG_CHARGE_BATCH * nr_cpus) update events. Though this optimization
585 * will let stats be out of sync by atmost (MEMCG_CHARGE_BATCH * nr_cpus) but
586 * only for 2 seconds due to (1).
588 static void flush_memcg_stats_dwork(struct work_struct *w);
589 static DECLARE_DEFERRABLE_WORK(stats_flush_dwork, flush_memcg_stats_dwork);
590 static DEFINE_PER_CPU(unsigned int, stats_updates);
591 static atomic_t stats_flush_ongoing = ATOMIC_INIT(0);
592 static atomic_t stats_flush_threshold = ATOMIC_INIT(0);
593 static u64 flush_next_time;
595 #define FLUSH_TIME (2UL*HZ)
598 * Accessors to ensure that preemption is disabled on PREEMPT_RT because it can
599 * not rely on this as part of an acquired spinlock_t lock. These functions are
600 * never used in hardirq context on PREEMPT_RT and therefore disabling preemtion
603 static void memcg_stats_lock(void)
605 preempt_disable_nested();
606 VM_WARN_ON_IRQS_ENABLED();
609 static void __memcg_stats_lock(void)
611 preempt_disable_nested();
614 static void memcg_stats_unlock(void)
616 preempt_enable_nested();
619 static inline void memcg_rstat_updated(struct mem_cgroup *memcg, int val)
626 cgroup_rstat_updated(memcg->css.cgroup, smp_processor_id());
628 x = __this_cpu_add_return(stats_updates, abs(val));
629 if (x > MEMCG_CHARGE_BATCH) {
631 * If stats_flush_threshold exceeds the threshold
632 * (>num_online_cpus()), cgroup stats update will be triggered
633 * in __mem_cgroup_flush_stats(). Increasing this var further
634 * is redundant and simply adds overhead in atomic update.
636 if (atomic_read(&stats_flush_threshold) <= num_online_cpus())
637 atomic_add(x / MEMCG_CHARGE_BATCH, &stats_flush_threshold);
638 __this_cpu_write(stats_updates, 0);
642 static void do_flush_stats(bool atomic)
645 * We always flush the entire tree, so concurrent flushers can just
646 * skip. This avoids a thundering herd problem on the rstat global lock
647 * from memcg flushers (e.g. reclaim, refault, etc).
649 if (atomic_read(&stats_flush_ongoing) ||
650 atomic_xchg(&stats_flush_ongoing, 1))
653 WRITE_ONCE(flush_next_time, jiffies_64 + 2*FLUSH_TIME);
656 cgroup_rstat_flush_atomic(root_mem_cgroup->css.cgroup);
658 cgroup_rstat_flush(root_mem_cgroup->css.cgroup);
660 atomic_set(&stats_flush_threshold, 0);
661 atomic_set(&stats_flush_ongoing, 0);
664 static bool should_flush_stats(void)
666 return atomic_read(&stats_flush_threshold) > num_online_cpus();
669 void mem_cgroup_flush_stats(void)
671 if (should_flush_stats())
672 do_flush_stats(false);
675 void mem_cgroup_flush_stats_atomic(void)
677 if (should_flush_stats())
678 do_flush_stats(true);
681 void mem_cgroup_flush_stats_ratelimited(void)
683 if (time_after64(jiffies_64, READ_ONCE(flush_next_time)))
684 mem_cgroup_flush_stats();
687 static void flush_memcg_stats_dwork(struct work_struct *w)
690 * Always flush here so that flushing in latency-sensitive paths is
691 * as cheap as possible.
693 do_flush_stats(false);
694 queue_delayed_work(system_unbound_wq, &stats_flush_dwork, FLUSH_TIME);
697 /* Subset of vm_event_item to report for memcg event stats */
698 static const unsigned int memcg_vm_event_stat[] = {
714 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
718 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
724 #define NR_MEMCG_EVENTS ARRAY_SIZE(memcg_vm_event_stat)
725 static int mem_cgroup_events_index[NR_VM_EVENT_ITEMS] __read_mostly;
727 static void init_memcg_events(void)
731 for (i = 0; i < NR_MEMCG_EVENTS; ++i)
732 mem_cgroup_events_index[memcg_vm_event_stat[i]] = i + 1;
735 static inline int memcg_events_index(enum vm_event_item idx)
737 return mem_cgroup_events_index[idx] - 1;
740 struct memcg_vmstats_percpu {
741 /* Local (CPU and cgroup) page state & events */
742 long state[MEMCG_NR_STAT];
743 unsigned long events[NR_MEMCG_EVENTS];
745 /* Delta calculation for lockless upward propagation */
746 long state_prev[MEMCG_NR_STAT];
747 unsigned long events_prev[NR_MEMCG_EVENTS];
749 /* Cgroup1: threshold notifications & softlimit tree updates */
750 unsigned long nr_page_events;
751 unsigned long targets[MEM_CGROUP_NTARGETS];
754 struct memcg_vmstats {
755 /* Aggregated (CPU and subtree) page state & events */
756 long state[MEMCG_NR_STAT];
757 unsigned long events[NR_MEMCG_EVENTS];
759 /* Pending child counts during tree propagation */
760 long state_pending[MEMCG_NR_STAT];
761 unsigned long events_pending[NR_MEMCG_EVENTS];
764 unsigned long memcg_page_state(struct mem_cgroup *memcg, int idx)
766 long x = READ_ONCE(memcg->vmstats->state[idx]);
775 * __mod_memcg_state - update cgroup memory statistics
776 * @memcg: the memory cgroup
777 * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item
778 * @val: delta to add to the counter, can be negative
780 void __mod_memcg_state(struct mem_cgroup *memcg, int idx, int val)
782 if (mem_cgroup_disabled())
785 __this_cpu_add(memcg->vmstats_percpu->state[idx], val);
786 memcg_rstat_updated(memcg, val);
789 /* idx can be of type enum memcg_stat_item or node_stat_item. */
790 static unsigned long memcg_page_state_local(struct mem_cgroup *memcg, int idx)
795 for_each_possible_cpu(cpu)
796 x += per_cpu(memcg->vmstats_percpu->state[idx], cpu);
804 void __mod_memcg_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
807 struct mem_cgroup_per_node *pn;
808 struct mem_cgroup *memcg;
810 pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
814 * The caller from rmap relay on disabled preemption becase they never
815 * update their counter from in-interrupt context. For these two
816 * counters we check that the update is never performed from an
817 * interrupt context while other caller need to have disabled interrupt.
819 __memcg_stats_lock();
820 if (IS_ENABLED(CONFIG_DEBUG_VM)) {
825 case NR_SHMEM_PMDMAPPED:
826 case NR_FILE_PMDMAPPED:
827 WARN_ON_ONCE(!in_task());
830 VM_WARN_ON_IRQS_ENABLED();
835 __this_cpu_add(memcg->vmstats_percpu->state[idx], val);
838 __this_cpu_add(pn->lruvec_stats_percpu->state[idx], val);
840 memcg_rstat_updated(memcg, val);
841 memcg_stats_unlock();
845 * __mod_lruvec_state - update lruvec memory statistics
846 * @lruvec: the lruvec
847 * @idx: the stat item
848 * @val: delta to add to the counter, can be negative
850 * The lruvec is the intersection of the NUMA node and a cgroup. This
851 * function updates the all three counters that are affected by a
852 * change of state at this level: per-node, per-cgroup, per-lruvec.
854 void __mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
858 __mod_node_page_state(lruvec_pgdat(lruvec), idx, val);
860 /* Update memcg and lruvec */
861 if (!mem_cgroup_disabled())
862 __mod_memcg_lruvec_state(lruvec, idx, val);
865 void __mod_lruvec_page_state(struct page *page, enum node_stat_item idx,
868 struct page *head = compound_head(page); /* rmap on tail pages */
869 struct mem_cgroup *memcg;
870 pg_data_t *pgdat = page_pgdat(page);
871 struct lruvec *lruvec;
874 memcg = page_memcg(head);
875 /* Untracked pages have no memcg, no lruvec. Update only the node */
878 __mod_node_page_state(pgdat, idx, val);
882 lruvec = mem_cgroup_lruvec(memcg, pgdat);
883 __mod_lruvec_state(lruvec, idx, val);
886 EXPORT_SYMBOL(__mod_lruvec_page_state);
888 void __mod_lruvec_kmem_state(void *p, enum node_stat_item idx, int val)
890 pg_data_t *pgdat = page_pgdat(virt_to_page(p));
891 struct mem_cgroup *memcg;
892 struct lruvec *lruvec;
895 memcg = mem_cgroup_from_slab_obj(p);
898 * Untracked pages have no memcg, no lruvec. Update only the
899 * node. If we reparent the slab objects to the root memcg,
900 * when we free the slab object, we need to update the per-memcg
901 * vmstats to keep it correct for the root memcg.
904 __mod_node_page_state(pgdat, idx, val);
906 lruvec = mem_cgroup_lruvec(memcg, pgdat);
907 __mod_lruvec_state(lruvec, idx, val);
913 * __count_memcg_events - account VM events in a cgroup
914 * @memcg: the memory cgroup
915 * @idx: the event item
916 * @count: the number of events that occurred
918 void __count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx,
921 int index = memcg_events_index(idx);
923 if (mem_cgroup_disabled() || index < 0)
927 __this_cpu_add(memcg->vmstats_percpu->events[index], count);
928 memcg_rstat_updated(memcg, count);
929 memcg_stats_unlock();
932 static unsigned long memcg_events(struct mem_cgroup *memcg, int event)
934 int index = memcg_events_index(event);
938 return READ_ONCE(memcg->vmstats->events[index]);
941 static unsigned long memcg_events_local(struct mem_cgroup *memcg, int event)
945 int index = memcg_events_index(event);
950 for_each_possible_cpu(cpu)
951 x += per_cpu(memcg->vmstats_percpu->events[index], cpu);
955 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
958 /* pagein of a big page is an event. So, ignore page size */
960 __count_memcg_events(memcg, PGPGIN, 1);
962 __count_memcg_events(memcg, PGPGOUT, 1);
963 nr_pages = -nr_pages; /* for event */
966 __this_cpu_add(memcg->vmstats_percpu->nr_page_events, nr_pages);
969 static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
970 enum mem_cgroup_events_target target)
972 unsigned long val, next;
974 val = __this_cpu_read(memcg->vmstats_percpu->nr_page_events);
975 next = __this_cpu_read(memcg->vmstats_percpu->targets[target]);
976 /* from time_after() in jiffies.h */
977 if ((long)(next - val) < 0) {
979 case MEM_CGROUP_TARGET_THRESH:
980 next = val + THRESHOLDS_EVENTS_TARGET;
982 case MEM_CGROUP_TARGET_SOFTLIMIT:
983 next = val + SOFTLIMIT_EVENTS_TARGET;
988 __this_cpu_write(memcg->vmstats_percpu->targets[target], next);
995 * Check events in order.
998 static void memcg_check_events(struct mem_cgroup *memcg, int nid)
1000 if (IS_ENABLED(CONFIG_PREEMPT_RT))
1003 /* threshold event is triggered in finer grain than soft limit */
1004 if (unlikely(mem_cgroup_event_ratelimit(memcg,
1005 MEM_CGROUP_TARGET_THRESH))) {
1008 do_softlimit = mem_cgroup_event_ratelimit(memcg,
1009 MEM_CGROUP_TARGET_SOFTLIMIT);
1010 mem_cgroup_threshold(memcg);
1011 if (unlikely(do_softlimit))
1012 mem_cgroup_update_tree(memcg, nid);
1016 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
1019 * mm_update_next_owner() may clear mm->owner to NULL
1020 * if it races with swapoff, page migration, etc.
1021 * So this can be called with p == NULL.
1026 return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
1028 EXPORT_SYMBOL(mem_cgroup_from_task);
1030 static __always_inline struct mem_cgroup *active_memcg(void)
1033 return this_cpu_read(int_active_memcg);
1035 return current->active_memcg;
1039 * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
1040 * @mm: mm from which memcg should be extracted. It can be NULL.
1042 * Obtain a reference on mm->memcg and returns it if successful. If mm
1043 * is NULL, then the memcg is chosen as follows:
1044 * 1) The active memcg, if set.
1045 * 2) current->mm->memcg, if available
1047 * If mem_cgroup is disabled, NULL is returned.
1049 struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
1051 struct mem_cgroup *memcg;
1053 if (mem_cgroup_disabled())
1057 * Page cache insertions can happen without an
1058 * actual mm context, e.g. during disk probing
1059 * on boot, loopback IO, acct() writes etc.
1061 * No need to css_get on root memcg as the reference
1062 * counting is disabled on the root level in the
1063 * cgroup core. See CSS_NO_REF.
1065 if (unlikely(!mm)) {
1066 memcg = active_memcg();
1067 if (unlikely(memcg)) {
1068 /* remote memcg must hold a ref */
1069 css_get(&memcg->css);
1074 return root_mem_cgroup;
1079 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1080 if (unlikely(!memcg))
1081 memcg = root_mem_cgroup;
1082 } while (!css_tryget(&memcg->css));
1086 EXPORT_SYMBOL(get_mem_cgroup_from_mm);
1088 static __always_inline bool memcg_kmem_bypass(void)
1090 /* Allow remote memcg charging from any context. */
1091 if (unlikely(active_memcg()))
1094 /* Memcg to charge can't be determined. */
1095 if (!in_task() || !current->mm || (current->flags & PF_KTHREAD))
1102 * mem_cgroup_iter - iterate over memory cgroup hierarchy
1103 * @root: hierarchy root
1104 * @prev: previously returned memcg, NULL on first invocation
1105 * @reclaim: cookie for shared reclaim walks, NULL for full walks
1107 * Returns references to children of the hierarchy below @root, or
1108 * @root itself, or %NULL after a full round-trip.
1110 * Caller must pass the return value in @prev on subsequent
1111 * invocations for reference counting, or use mem_cgroup_iter_break()
1112 * to cancel a hierarchy walk before the round-trip is complete.
1114 * Reclaimers can specify a node in @reclaim to divide up the memcgs
1115 * in the hierarchy among all concurrent reclaimers operating on the
1118 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
1119 struct mem_cgroup *prev,
1120 struct mem_cgroup_reclaim_cookie *reclaim)
1122 struct mem_cgroup_reclaim_iter *iter;
1123 struct cgroup_subsys_state *css = NULL;
1124 struct mem_cgroup *memcg = NULL;
1125 struct mem_cgroup *pos = NULL;
1127 if (mem_cgroup_disabled())
1131 root = root_mem_cgroup;
1136 struct mem_cgroup_per_node *mz;
1138 mz = root->nodeinfo[reclaim->pgdat->node_id];
1142 * On start, join the current reclaim iteration cycle.
1143 * Exit when a concurrent walker completes it.
1146 reclaim->generation = iter->generation;
1147 else if (reclaim->generation != iter->generation)
1151 pos = READ_ONCE(iter->position);
1152 if (!pos || css_tryget(&pos->css))
1155 * css reference reached zero, so iter->position will
1156 * be cleared by ->css_released. However, we should not
1157 * rely on this happening soon, because ->css_released
1158 * is called from a work queue, and by busy-waiting we
1159 * might block it. So we clear iter->position right
1162 (void)cmpxchg(&iter->position, pos, NULL);
1172 css = css_next_descendant_pre(css, &root->css);
1175 * Reclaimers share the hierarchy walk, and a
1176 * new one might jump in right at the end of
1177 * the hierarchy - make sure they see at least
1178 * one group and restart from the beginning.
1186 * Verify the css and acquire a reference. The root
1187 * is provided by the caller, so we know it's alive
1188 * and kicking, and don't take an extra reference.
1190 if (css == &root->css || css_tryget(css)) {
1191 memcg = mem_cgroup_from_css(css);
1198 * The position could have already been updated by a competing
1199 * thread, so check that the value hasn't changed since we read
1200 * it to avoid reclaiming from the same cgroup twice.
1202 (void)cmpxchg(&iter->position, pos, memcg);
1213 if (prev && prev != root)
1214 css_put(&prev->css);
1220 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1221 * @root: hierarchy root
1222 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1224 void mem_cgroup_iter_break(struct mem_cgroup *root,
1225 struct mem_cgroup *prev)
1228 root = root_mem_cgroup;
1229 if (prev && prev != root)
1230 css_put(&prev->css);
1233 static void __invalidate_reclaim_iterators(struct mem_cgroup *from,
1234 struct mem_cgroup *dead_memcg)
1236 struct mem_cgroup_reclaim_iter *iter;
1237 struct mem_cgroup_per_node *mz;
1240 for_each_node(nid) {
1241 mz = from->nodeinfo[nid];
1243 cmpxchg(&iter->position, dead_memcg, NULL);
1247 static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
1249 struct mem_cgroup *memcg = dead_memcg;
1250 struct mem_cgroup *last;
1253 __invalidate_reclaim_iterators(memcg, dead_memcg);
1255 } while ((memcg = parent_mem_cgroup(memcg)));
1258 * When cgroup1 non-hierarchy mode is used,
1259 * parent_mem_cgroup() does not walk all the way up to the
1260 * cgroup root (root_mem_cgroup). So we have to handle
1261 * dead_memcg from cgroup root separately.
1263 if (!mem_cgroup_is_root(last))
1264 __invalidate_reclaim_iterators(root_mem_cgroup,
1269 * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
1270 * @memcg: hierarchy root
1271 * @fn: function to call for each task
1272 * @arg: argument passed to @fn
1274 * This function iterates over tasks attached to @memcg or to any of its
1275 * descendants and calls @fn for each task. If @fn returns a non-zero
1276 * value, the function breaks the iteration loop and returns the value.
1277 * Otherwise, it will iterate over all tasks and return 0.
1279 * This function must not be called for the root memory cgroup.
1281 int mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
1282 int (*fn)(struct task_struct *, void *), void *arg)
1284 struct mem_cgroup *iter;
1287 BUG_ON(mem_cgroup_is_root(memcg));
1289 for_each_mem_cgroup_tree(iter, memcg) {
1290 struct css_task_iter it;
1291 struct task_struct *task;
1293 css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it);
1294 while (!ret && (task = css_task_iter_next(&it)))
1295 ret = fn(task, arg);
1296 css_task_iter_end(&it);
1298 mem_cgroup_iter_break(memcg, iter);
1305 #ifdef CONFIG_DEBUG_VM
1306 void lruvec_memcg_debug(struct lruvec *lruvec, struct folio *folio)
1308 struct mem_cgroup *memcg;
1310 if (mem_cgroup_disabled())
1313 memcg = folio_memcg(folio);
1316 VM_BUG_ON_FOLIO(!mem_cgroup_is_root(lruvec_memcg(lruvec)), folio);
1318 VM_BUG_ON_FOLIO(lruvec_memcg(lruvec) != memcg, folio);
1323 * folio_lruvec_lock - Lock the lruvec for a folio.
1324 * @folio: Pointer to the folio.
1326 * These functions are safe to use under any of the following conditions:
1328 * - folio_test_lru false
1329 * - folio_memcg_lock()
1330 * - folio frozen (refcount of 0)
1332 * Return: The lruvec this folio is on with its lock held.
1334 struct lruvec *folio_lruvec_lock(struct folio *folio)
1336 struct lruvec *lruvec = folio_lruvec(folio);
1338 spin_lock(&lruvec->lru_lock);
1339 lruvec_memcg_debug(lruvec, folio);
1345 * folio_lruvec_lock_irq - Lock the lruvec for a folio.
1346 * @folio: Pointer to the folio.
1348 * These functions are safe to use under any of the following conditions:
1350 * - folio_test_lru false
1351 * - folio_memcg_lock()
1352 * - folio frozen (refcount of 0)
1354 * Return: The lruvec this folio is on with its lock held and interrupts
1357 struct lruvec *folio_lruvec_lock_irq(struct folio *folio)
1359 struct lruvec *lruvec = folio_lruvec(folio);
1361 spin_lock_irq(&lruvec->lru_lock);
1362 lruvec_memcg_debug(lruvec, folio);
1368 * folio_lruvec_lock_irqsave - Lock the lruvec for a folio.
1369 * @folio: Pointer to the folio.
1370 * @flags: Pointer to irqsave flags.
1372 * These functions are safe to use under any of the following conditions:
1374 * - folio_test_lru false
1375 * - folio_memcg_lock()
1376 * - folio frozen (refcount of 0)
1378 * Return: The lruvec this folio is on with its lock held and interrupts
1381 struct lruvec *folio_lruvec_lock_irqsave(struct folio *folio,
1382 unsigned long *flags)
1384 struct lruvec *lruvec = folio_lruvec(folio);
1386 spin_lock_irqsave(&lruvec->lru_lock, *flags);
1387 lruvec_memcg_debug(lruvec, folio);
1393 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1394 * @lruvec: mem_cgroup per zone lru vector
1395 * @lru: index of lru list the page is sitting on
1396 * @zid: zone id of the accounted pages
1397 * @nr_pages: positive when adding or negative when removing
1399 * This function must be called under lru_lock, just before a page is added
1400 * to or just after a page is removed from an lru list.
1402 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1403 int zid, int nr_pages)
1405 struct mem_cgroup_per_node *mz;
1406 unsigned long *lru_size;
1409 if (mem_cgroup_disabled())
1412 mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
1413 lru_size = &mz->lru_zone_size[zid][lru];
1416 *lru_size += nr_pages;
1419 if (WARN_ONCE(size < 0,
1420 "%s(%p, %d, %d): lru_size %ld\n",
1421 __func__, lruvec, lru, nr_pages, size)) {
1427 *lru_size += nr_pages;
1431 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1432 * @memcg: the memory cgroup
1434 * Returns the maximum amount of memory @mem can be charged with, in
1437 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1439 unsigned long margin = 0;
1440 unsigned long count;
1441 unsigned long limit;
1443 count = page_counter_read(&memcg->memory);
1444 limit = READ_ONCE(memcg->memory.max);
1446 margin = limit - count;
1448 if (do_memsw_account()) {
1449 count = page_counter_read(&memcg->memsw);
1450 limit = READ_ONCE(memcg->memsw.max);
1452 margin = min(margin, limit - count);
1461 * A routine for checking "mem" is under move_account() or not.
1463 * Checking a cgroup is mc.from or mc.to or under hierarchy of
1464 * moving cgroups. This is for waiting at high-memory pressure
1467 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1469 struct mem_cgroup *from;
1470 struct mem_cgroup *to;
1473 * Unlike task_move routines, we access mc.to, mc.from not under
1474 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1476 spin_lock(&mc.lock);
1482 ret = mem_cgroup_is_descendant(from, memcg) ||
1483 mem_cgroup_is_descendant(to, memcg);
1485 spin_unlock(&mc.lock);
1489 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1491 if (mc.moving_task && current != mc.moving_task) {
1492 if (mem_cgroup_under_move(memcg)) {
1494 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1495 /* moving charge context might have finished. */
1498 finish_wait(&mc.waitq, &wait);
1505 struct memory_stat {
1510 static const struct memory_stat memory_stats[] = {
1511 { "anon", NR_ANON_MAPPED },
1512 { "file", NR_FILE_PAGES },
1513 { "kernel", MEMCG_KMEM },
1514 { "kernel_stack", NR_KERNEL_STACK_KB },
1515 { "pagetables", NR_PAGETABLE },
1516 { "sec_pagetables", NR_SECONDARY_PAGETABLE },
1517 { "percpu", MEMCG_PERCPU_B },
1518 { "sock", MEMCG_SOCK },
1519 { "vmalloc", MEMCG_VMALLOC },
1520 { "shmem", NR_SHMEM },
1521 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
1522 { "zswap", MEMCG_ZSWAP_B },
1523 { "zswapped", MEMCG_ZSWAPPED },
1525 { "file_mapped", NR_FILE_MAPPED },
1526 { "file_dirty", NR_FILE_DIRTY },
1527 { "file_writeback", NR_WRITEBACK },
1529 { "swapcached", NR_SWAPCACHE },
1531 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1532 { "anon_thp", NR_ANON_THPS },
1533 { "file_thp", NR_FILE_THPS },
1534 { "shmem_thp", NR_SHMEM_THPS },
1536 { "inactive_anon", NR_INACTIVE_ANON },
1537 { "active_anon", NR_ACTIVE_ANON },
1538 { "inactive_file", NR_INACTIVE_FILE },
1539 { "active_file", NR_ACTIVE_FILE },
1540 { "unevictable", NR_UNEVICTABLE },
1541 { "slab_reclaimable", NR_SLAB_RECLAIMABLE_B },
1542 { "slab_unreclaimable", NR_SLAB_UNRECLAIMABLE_B },
1544 /* The memory events */
1545 { "workingset_refault_anon", WORKINGSET_REFAULT_ANON },
1546 { "workingset_refault_file", WORKINGSET_REFAULT_FILE },
1547 { "workingset_activate_anon", WORKINGSET_ACTIVATE_ANON },
1548 { "workingset_activate_file", WORKINGSET_ACTIVATE_FILE },
1549 { "workingset_restore_anon", WORKINGSET_RESTORE_ANON },
1550 { "workingset_restore_file", WORKINGSET_RESTORE_FILE },
1551 { "workingset_nodereclaim", WORKINGSET_NODERECLAIM },
1554 /* Translate stat items to the correct unit for memory.stat output */
1555 static int memcg_page_state_unit(int item)
1558 case MEMCG_PERCPU_B:
1560 case NR_SLAB_RECLAIMABLE_B:
1561 case NR_SLAB_UNRECLAIMABLE_B:
1562 case WORKINGSET_REFAULT_ANON:
1563 case WORKINGSET_REFAULT_FILE:
1564 case WORKINGSET_ACTIVATE_ANON:
1565 case WORKINGSET_ACTIVATE_FILE:
1566 case WORKINGSET_RESTORE_ANON:
1567 case WORKINGSET_RESTORE_FILE:
1568 case WORKINGSET_NODERECLAIM:
1570 case NR_KERNEL_STACK_KB:
1577 static inline unsigned long memcg_page_state_output(struct mem_cgroup *memcg,
1580 return memcg_page_state(memcg, item) * memcg_page_state_unit(item);
1583 static void memory_stat_format(struct mem_cgroup *memcg, char *buf, int bufsize)
1588 seq_buf_init(&s, buf, bufsize);
1591 * Provide statistics on the state of the memory subsystem as
1592 * well as cumulative event counters that show past behavior.
1594 * This list is ordered following a combination of these gradients:
1595 * 1) generic big picture -> specifics and details
1596 * 2) reflecting userspace activity -> reflecting kernel heuristics
1598 * Current memory state:
1600 mem_cgroup_flush_stats();
1602 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
1605 size = memcg_page_state_output(memcg, memory_stats[i].idx);
1606 seq_buf_printf(&s, "%s %llu\n", memory_stats[i].name, size);
1608 if (unlikely(memory_stats[i].idx == NR_SLAB_UNRECLAIMABLE_B)) {
1609 size += memcg_page_state_output(memcg,
1610 NR_SLAB_RECLAIMABLE_B);
1611 seq_buf_printf(&s, "slab %llu\n", size);
1615 /* Accumulated memory events */
1616 seq_buf_printf(&s, "pgscan %lu\n",
1617 memcg_events(memcg, PGSCAN_KSWAPD) +
1618 memcg_events(memcg, PGSCAN_DIRECT) +
1619 memcg_events(memcg, PGSCAN_KHUGEPAGED));
1620 seq_buf_printf(&s, "pgsteal %lu\n",
1621 memcg_events(memcg, PGSTEAL_KSWAPD) +
1622 memcg_events(memcg, PGSTEAL_DIRECT) +
1623 memcg_events(memcg, PGSTEAL_KHUGEPAGED));
1625 for (i = 0; i < ARRAY_SIZE(memcg_vm_event_stat); i++) {
1626 if (memcg_vm_event_stat[i] == PGPGIN ||
1627 memcg_vm_event_stat[i] == PGPGOUT)
1630 seq_buf_printf(&s, "%s %lu\n",
1631 vm_event_name(memcg_vm_event_stat[i]),
1632 memcg_events(memcg, memcg_vm_event_stat[i]));
1635 /* The above should easily fit into one page */
1636 WARN_ON_ONCE(seq_buf_has_overflowed(&s));
1639 #define K(x) ((x) << (PAGE_SHIFT-10))
1641 * mem_cgroup_print_oom_context: Print OOM information relevant to
1642 * memory controller.
1643 * @memcg: The memory cgroup that went over limit
1644 * @p: Task that is going to be killed
1646 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1649 void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p)
1654 pr_cont(",oom_memcg=");
1655 pr_cont_cgroup_path(memcg->css.cgroup);
1657 pr_cont(",global_oom");
1659 pr_cont(",task_memcg=");
1660 pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
1666 * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
1667 * memory controller.
1668 * @memcg: The memory cgroup that went over limit
1670 void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
1672 /* Use static buffer, for the caller is holding oom_lock. */
1673 static char buf[PAGE_SIZE];
1675 lockdep_assert_held(&oom_lock);
1677 pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1678 K((u64)page_counter_read(&memcg->memory)),
1679 K((u64)READ_ONCE(memcg->memory.max)), memcg->memory.failcnt);
1680 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1681 pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n",
1682 K((u64)page_counter_read(&memcg->swap)),
1683 K((u64)READ_ONCE(memcg->swap.max)), memcg->swap.failcnt);
1685 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1686 K((u64)page_counter_read(&memcg->memsw)),
1687 K((u64)memcg->memsw.max), memcg->memsw.failcnt);
1688 pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1689 K((u64)page_counter_read(&memcg->kmem)),
1690 K((u64)memcg->kmem.max), memcg->kmem.failcnt);
1693 pr_info("Memory cgroup stats for ");
1694 pr_cont_cgroup_path(memcg->css.cgroup);
1696 memory_stat_format(memcg, buf, sizeof(buf));
1701 * Return the memory (and swap, if configured) limit for a memcg.
1703 unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg)
1705 unsigned long max = READ_ONCE(memcg->memory.max);
1707 if (do_memsw_account()) {
1708 if (mem_cgroup_swappiness(memcg)) {
1709 /* Calculate swap excess capacity from memsw limit */
1710 unsigned long swap = READ_ONCE(memcg->memsw.max) - max;
1712 max += min(swap, (unsigned long)total_swap_pages);
1715 if (mem_cgroup_swappiness(memcg))
1716 max += min(READ_ONCE(memcg->swap.max),
1717 (unsigned long)total_swap_pages);
1722 unsigned long mem_cgroup_size(struct mem_cgroup *memcg)
1724 return page_counter_read(&memcg->memory);
1727 static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1730 struct oom_control oc = {
1734 .gfp_mask = gfp_mask,
1739 if (mutex_lock_killable(&oom_lock))
1742 if (mem_cgroup_margin(memcg) >= (1 << order))
1746 * A few threads which were not waiting at mutex_lock_killable() can
1747 * fail to bail out. Therefore, check again after holding oom_lock.
1749 ret = task_is_dying() || out_of_memory(&oc);
1752 mutex_unlock(&oom_lock);
1756 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
1759 unsigned long *total_scanned)
1761 struct mem_cgroup *victim = NULL;
1764 unsigned long excess;
1765 unsigned long nr_scanned;
1766 struct mem_cgroup_reclaim_cookie reclaim = {
1770 excess = soft_limit_excess(root_memcg);
1773 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1778 * If we have not been able to reclaim
1779 * anything, it might because there are
1780 * no reclaimable pages under this hierarchy
1785 * We want to do more targeted reclaim.
1786 * excess >> 2 is not to excessive so as to
1787 * reclaim too much, nor too less that we keep
1788 * coming back to reclaim from this cgroup
1790 if (total >= (excess >> 2) ||
1791 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1796 total += mem_cgroup_shrink_node(victim, gfp_mask, false,
1797 pgdat, &nr_scanned);
1798 *total_scanned += nr_scanned;
1799 if (!soft_limit_excess(root_memcg))
1802 mem_cgroup_iter_break(root_memcg, victim);
1806 #ifdef CONFIG_LOCKDEP
1807 static struct lockdep_map memcg_oom_lock_dep_map = {
1808 .name = "memcg_oom_lock",
1812 static DEFINE_SPINLOCK(memcg_oom_lock);
1815 * Check OOM-Killer is already running under our hierarchy.
1816 * If someone is running, return false.
1818 static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
1820 struct mem_cgroup *iter, *failed = NULL;
1822 spin_lock(&memcg_oom_lock);
1824 for_each_mem_cgroup_tree(iter, memcg) {
1825 if (iter->oom_lock) {
1827 * this subtree of our hierarchy is already locked
1828 * so we cannot give a lock.
1831 mem_cgroup_iter_break(memcg, iter);
1834 iter->oom_lock = true;
1839 * OK, we failed to lock the whole subtree so we have
1840 * to clean up what we set up to the failing subtree
1842 for_each_mem_cgroup_tree(iter, memcg) {
1843 if (iter == failed) {
1844 mem_cgroup_iter_break(memcg, iter);
1847 iter->oom_lock = false;
1850 mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
1852 spin_unlock(&memcg_oom_lock);
1857 static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1859 struct mem_cgroup *iter;
1861 spin_lock(&memcg_oom_lock);
1862 mutex_release(&memcg_oom_lock_dep_map, _RET_IP_);
1863 for_each_mem_cgroup_tree(iter, memcg)
1864 iter->oom_lock = false;
1865 spin_unlock(&memcg_oom_lock);
1868 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1870 struct mem_cgroup *iter;
1872 spin_lock(&memcg_oom_lock);
1873 for_each_mem_cgroup_tree(iter, memcg)
1875 spin_unlock(&memcg_oom_lock);
1878 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1880 struct mem_cgroup *iter;
1883 * Be careful about under_oom underflows because a child memcg
1884 * could have been added after mem_cgroup_mark_under_oom.
1886 spin_lock(&memcg_oom_lock);
1887 for_each_mem_cgroup_tree(iter, memcg)
1888 if (iter->under_oom > 0)
1890 spin_unlock(&memcg_oom_lock);
1893 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1895 struct oom_wait_info {
1896 struct mem_cgroup *memcg;
1897 wait_queue_entry_t wait;
1900 static int memcg_oom_wake_function(wait_queue_entry_t *wait,
1901 unsigned mode, int sync, void *arg)
1903 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
1904 struct mem_cgroup *oom_wait_memcg;
1905 struct oom_wait_info *oom_wait_info;
1907 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1908 oom_wait_memcg = oom_wait_info->memcg;
1910 if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
1911 !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
1913 return autoremove_wake_function(wait, mode, sync, arg);
1916 static void memcg_oom_recover(struct mem_cgroup *memcg)
1919 * For the following lockless ->under_oom test, the only required
1920 * guarantee is that it must see the state asserted by an OOM when
1921 * this function is called as a result of userland actions
1922 * triggered by the notification of the OOM. This is trivially
1923 * achieved by invoking mem_cgroup_mark_under_oom() before
1924 * triggering notification.
1926 if (memcg && memcg->under_oom)
1927 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
1931 * Returns true if successfully killed one or more processes. Though in some
1932 * corner cases it can return true even without killing any process.
1934 static bool mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
1938 if (order > PAGE_ALLOC_COSTLY_ORDER)
1941 memcg_memory_event(memcg, MEMCG_OOM);
1944 * We are in the middle of the charge context here, so we
1945 * don't want to block when potentially sitting on a callstack
1946 * that holds all kinds of filesystem and mm locks.
1948 * cgroup1 allows disabling the OOM killer and waiting for outside
1949 * handling until the charge can succeed; remember the context and put
1950 * the task to sleep at the end of the page fault when all locks are
1953 * On the other hand, in-kernel OOM killer allows for an async victim
1954 * memory reclaim (oom_reaper) and that means that we are not solely
1955 * relying on the oom victim to make a forward progress and we can
1956 * invoke the oom killer here.
1958 * Please note that mem_cgroup_out_of_memory might fail to find a
1959 * victim and then we have to bail out from the charge path.
1961 if (READ_ONCE(memcg->oom_kill_disable)) {
1962 if (current->in_user_fault) {
1963 css_get(&memcg->css);
1964 current->memcg_in_oom = memcg;
1965 current->memcg_oom_gfp_mask = mask;
1966 current->memcg_oom_order = order;
1971 mem_cgroup_mark_under_oom(memcg);
1973 locked = mem_cgroup_oom_trylock(memcg);
1976 mem_cgroup_oom_notify(memcg);
1978 mem_cgroup_unmark_under_oom(memcg);
1979 ret = mem_cgroup_out_of_memory(memcg, mask, order);
1982 mem_cgroup_oom_unlock(memcg);
1988 * mem_cgroup_oom_synchronize - complete memcg OOM handling
1989 * @handle: actually kill/wait or just clean up the OOM state
1991 * This has to be called at the end of a page fault if the memcg OOM
1992 * handler was enabled.
1994 * Memcg supports userspace OOM handling where failed allocations must
1995 * sleep on a waitqueue until the userspace task resolves the
1996 * situation. Sleeping directly in the charge context with all kinds
1997 * of locks held is not a good idea, instead we remember an OOM state
1998 * in the task and mem_cgroup_oom_synchronize() has to be called at
1999 * the end of the page fault to complete the OOM handling.
2001 * Returns %true if an ongoing memcg OOM situation was detected and
2002 * completed, %false otherwise.
2004 bool mem_cgroup_oom_synchronize(bool handle)
2006 struct mem_cgroup *memcg = current->memcg_in_oom;
2007 struct oom_wait_info owait;
2010 /* OOM is global, do not handle */
2017 owait.memcg = memcg;
2018 owait.wait.flags = 0;
2019 owait.wait.func = memcg_oom_wake_function;
2020 owait.wait.private = current;
2021 INIT_LIST_HEAD(&owait.wait.entry);
2023 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
2024 mem_cgroup_mark_under_oom(memcg);
2026 locked = mem_cgroup_oom_trylock(memcg);
2029 mem_cgroup_oom_notify(memcg);
2031 if (locked && !READ_ONCE(memcg->oom_kill_disable)) {
2032 mem_cgroup_unmark_under_oom(memcg);
2033 finish_wait(&memcg_oom_waitq, &owait.wait);
2034 mem_cgroup_out_of_memory(memcg, current->memcg_oom_gfp_mask,
2035 current->memcg_oom_order);
2038 mem_cgroup_unmark_under_oom(memcg);
2039 finish_wait(&memcg_oom_waitq, &owait.wait);
2043 mem_cgroup_oom_unlock(memcg);
2045 * There is no guarantee that an OOM-lock contender
2046 * sees the wakeups triggered by the OOM kill
2047 * uncharges. Wake any sleepers explicitly.
2049 memcg_oom_recover(memcg);
2052 current->memcg_in_oom = NULL;
2053 css_put(&memcg->css);
2058 * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
2059 * @victim: task to be killed by the OOM killer
2060 * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
2062 * Returns a pointer to a memory cgroup, which has to be cleaned up
2063 * by killing all belonging OOM-killable tasks.
2065 * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
2067 struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim,
2068 struct mem_cgroup *oom_domain)
2070 struct mem_cgroup *oom_group = NULL;
2071 struct mem_cgroup *memcg;
2073 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
2077 oom_domain = root_mem_cgroup;
2081 memcg = mem_cgroup_from_task(victim);
2082 if (mem_cgroup_is_root(memcg))
2086 * If the victim task has been asynchronously moved to a different
2087 * memory cgroup, we might end up killing tasks outside oom_domain.
2088 * In this case it's better to ignore memory.group.oom.
2090 if (unlikely(!mem_cgroup_is_descendant(memcg, oom_domain)))
2094 * Traverse the memory cgroup hierarchy from the victim task's
2095 * cgroup up to the OOMing cgroup (or root) to find the
2096 * highest-level memory cgroup with oom.group set.
2098 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
2099 if (READ_ONCE(memcg->oom_group))
2102 if (memcg == oom_domain)
2107 css_get(&oom_group->css);
2114 void mem_cgroup_print_oom_group(struct mem_cgroup *memcg)
2116 pr_info("Tasks in ");
2117 pr_cont_cgroup_path(memcg->css.cgroup);
2118 pr_cont(" are going to be killed due to memory.oom.group set\n");
2122 * folio_memcg_lock - Bind a folio to its memcg.
2123 * @folio: The folio.
2125 * This function prevents unlocked LRU folios from being moved to
2128 * It ensures lifetime of the bound memcg. The caller is responsible
2129 * for the lifetime of the folio.
2131 void folio_memcg_lock(struct folio *folio)
2133 struct mem_cgroup *memcg;
2134 unsigned long flags;
2137 * The RCU lock is held throughout the transaction. The fast
2138 * path can get away without acquiring the memcg->move_lock
2139 * because page moving starts with an RCU grace period.
2143 if (mem_cgroup_disabled())
2146 memcg = folio_memcg(folio);
2147 if (unlikely(!memcg))
2150 #ifdef CONFIG_PROVE_LOCKING
2151 local_irq_save(flags);
2152 might_lock(&memcg->move_lock);
2153 local_irq_restore(flags);
2156 if (atomic_read(&memcg->moving_account) <= 0)
2159 spin_lock_irqsave(&memcg->move_lock, flags);
2160 if (memcg != folio_memcg(folio)) {
2161 spin_unlock_irqrestore(&memcg->move_lock, flags);
2166 * When charge migration first begins, we can have multiple
2167 * critical sections holding the fast-path RCU lock and one
2168 * holding the slowpath move_lock. Track the task who has the
2169 * move_lock for unlock_page_memcg().
2171 memcg->move_lock_task = current;
2172 memcg->move_lock_flags = flags;
2175 void lock_page_memcg(struct page *page)
2177 folio_memcg_lock(page_folio(page));
2180 static void __folio_memcg_unlock(struct mem_cgroup *memcg)
2182 if (memcg && memcg->move_lock_task == current) {
2183 unsigned long flags = memcg->move_lock_flags;
2185 memcg->move_lock_task = NULL;
2186 memcg->move_lock_flags = 0;
2188 spin_unlock_irqrestore(&memcg->move_lock, flags);
2195 * folio_memcg_unlock - Release the binding between a folio and its memcg.
2196 * @folio: The folio.
2198 * This releases the binding created by folio_memcg_lock(). This does
2199 * not change the accounting of this folio to its memcg, but it does
2200 * permit others to change it.
2202 void folio_memcg_unlock(struct folio *folio)
2204 __folio_memcg_unlock(folio_memcg(folio));
2207 void unlock_page_memcg(struct page *page)
2209 folio_memcg_unlock(page_folio(page));
2212 struct memcg_stock_pcp {
2213 local_lock_t stock_lock;
2214 struct mem_cgroup *cached; /* this never be root cgroup */
2215 unsigned int nr_pages;
2217 #ifdef CONFIG_MEMCG_KMEM
2218 struct obj_cgroup *cached_objcg;
2219 struct pglist_data *cached_pgdat;
2220 unsigned int nr_bytes;
2221 int nr_slab_reclaimable_b;
2222 int nr_slab_unreclaimable_b;
2225 struct work_struct work;
2226 unsigned long flags;
2227 #define FLUSHING_CACHED_CHARGE 0
2229 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock) = {
2230 .stock_lock = INIT_LOCAL_LOCK(stock_lock),
2232 static DEFINE_MUTEX(percpu_charge_mutex);
2234 #ifdef CONFIG_MEMCG_KMEM
2235 static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock);
2236 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2237 struct mem_cgroup *root_memcg);
2238 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages);
2241 static inline struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock)
2245 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2246 struct mem_cgroup *root_memcg)
2250 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages)
2256 * consume_stock: Try to consume stocked charge on this cpu.
2257 * @memcg: memcg to consume from.
2258 * @nr_pages: how many pages to charge.
2260 * The charges will only happen if @memcg matches the current cpu's memcg
2261 * stock, and at least @nr_pages are available in that stock. Failure to
2262 * service an allocation will refill the stock.
2264 * returns true if successful, false otherwise.
2266 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2268 struct memcg_stock_pcp *stock;
2269 unsigned long flags;
2272 if (nr_pages > MEMCG_CHARGE_BATCH)
2275 local_lock_irqsave(&memcg_stock.stock_lock, flags);
2277 stock = this_cpu_ptr(&memcg_stock);
2278 if (memcg == stock->cached && stock->nr_pages >= nr_pages) {
2279 stock->nr_pages -= nr_pages;
2283 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2289 * Returns stocks cached in percpu and reset cached information.
2291 static void drain_stock(struct memcg_stock_pcp *stock)
2293 struct mem_cgroup *old = stock->cached;
2298 if (stock->nr_pages) {
2299 page_counter_uncharge(&old->memory, stock->nr_pages);
2300 if (do_memsw_account())
2301 page_counter_uncharge(&old->memsw, stock->nr_pages);
2302 stock->nr_pages = 0;
2306 stock->cached = NULL;
2309 static void drain_local_stock(struct work_struct *dummy)
2311 struct memcg_stock_pcp *stock;
2312 struct obj_cgroup *old = NULL;
2313 unsigned long flags;
2316 * The only protection from cpu hotplug (memcg_hotplug_cpu_dead) vs.
2317 * drain_stock races is that we always operate on local CPU stock
2318 * here with IRQ disabled
2320 local_lock_irqsave(&memcg_stock.stock_lock, flags);
2322 stock = this_cpu_ptr(&memcg_stock);
2323 old = drain_obj_stock(stock);
2325 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2327 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2329 obj_cgroup_put(old);
2333 * Cache charges(val) to local per_cpu area.
2334 * This will be consumed by consume_stock() function, later.
2336 static void __refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2338 struct memcg_stock_pcp *stock;
2340 stock = this_cpu_ptr(&memcg_stock);
2341 if (stock->cached != memcg) { /* reset if necessary */
2343 css_get(&memcg->css);
2344 stock->cached = memcg;
2346 stock->nr_pages += nr_pages;
2348 if (stock->nr_pages > MEMCG_CHARGE_BATCH)
2352 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2354 unsigned long flags;
2356 local_lock_irqsave(&memcg_stock.stock_lock, flags);
2357 __refill_stock(memcg, nr_pages);
2358 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2362 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2363 * of the hierarchy under it.
2365 static void drain_all_stock(struct mem_cgroup *root_memcg)
2369 /* If someone's already draining, avoid adding running more workers. */
2370 if (!mutex_trylock(&percpu_charge_mutex))
2373 * Notify other cpus that system-wide "drain" is running
2374 * We do not care about races with the cpu hotplug because cpu down
2375 * as well as workers from this path always operate on the local
2376 * per-cpu data. CPU up doesn't touch memcg_stock at all.
2379 curcpu = smp_processor_id();
2380 for_each_online_cpu(cpu) {
2381 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2382 struct mem_cgroup *memcg;
2386 memcg = stock->cached;
2387 if (memcg && stock->nr_pages &&
2388 mem_cgroup_is_descendant(memcg, root_memcg))
2390 else if (obj_stock_flush_required(stock, root_memcg))
2395 !test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2397 drain_local_stock(&stock->work);
2398 else if (!cpu_is_isolated(cpu))
2399 schedule_work_on(cpu, &stock->work);
2403 mutex_unlock(&percpu_charge_mutex);
2406 static int memcg_hotplug_cpu_dead(unsigned int cpu)
2408 struct memcg_stock_pcp *stock;
2410 stock = &per_cpu(memcg_stock, cpu);
2416 static unsigned long reclaim_high(struct mem_cgroup *memcg,
2417 unsigned int nr_pages,
2420 unsigned long nr_reclaimed = 0;
2423 unsigned long pflags;
2425 if (page_counter_read(&memcg->memory) <=
2426 READ_ONCE(memcg->memory.high))
2429 memcg_memory_event(memcg, MEMCG_HIGH);
2431 psi_memstall_enter(&pflags);
2432 nr_reclaimed += try_to_free_mem_cgroup_pages(memcg, nr_pages,
2434 MEMCG_RECLAIM_MAY_SWAP);
2435 psi_memstall_leave(&pflags);
2436 } while ((memcg = parent_mem_cgroup(memcg)) &&
2437 !mem_cgroup_is_root(memcg));
2439 return nr_reclaimed;
2442 static void high_work_func(struct work_struct *work)
2444 struct mem_cgroup *memcg;
2446 memcg = container_of(work, struct mem_cgroup, high_work);
2447 reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
2451 * Clamp the maximum sleep time per allocation batch to 2 seconds. This is
2452 * enough to still cause a significant slowdown in most cases, while still
2453 * allowing diagnostics and tracing to proceed without becoming stuck.
2455 #define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ)
2458 * When calculating the delay, we use these either side of the exponentiation to
2459 * maintain precision and scale to a reasonable number of jiffies (see the table
2462 * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the
2463 * overage ratio to a delay.
2464 * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down the
2465 * proposed penalty in order to reduce to a reasonable number of jiffies, and
2466 * to produce a reasonable delay curve.
2468 * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a
2469 * reasonable delay curve compared to precision-adjusted overage, not
2470 * penalising heavily at first, but still making sure that growth beyond the
2471 * limit penalises misbehaviour cgroups by slowing them down exponentially. For
2472 * example, with a high of 100 megabytes:
2474 * +-------+------------------------+
2475 * | usage | time to allocate in ms |
2476 * +-------+------------------------+
2498 * +-------+------------------------+
2500 #define MEMCG_DELAY_PRECISION_SHIFT 20
2501 #define MEMCG_DELAY_SCALING_SHIFT 14
2503 static u64 calculate_overage(unsigned long usage, unsigned long high)
2511 * Prevent division by 0 in overage calculation by acting as if
2512 * it was a threshold of 1 page
2514 high = max(high, 1UL);
2516 overage = usage - high;
2517 overage <<= MEMCG_DELAY_PRECISION_SHIFT;
2518 return div64_u64(overage, high);
2521 static u64 mem_find_max_overage(struct mem_cgroup *memcg)
2523 u64 overage, max_overage = 0;
2526 overage = calculate_overage(page_counter_read(&memcg->memory),
2527 READ_ONCE(memcg->memory.high));
2528 max_overage = max(overage, max_overage);
2529 } while ((memcg = parent_mem_cgroup(memcg)) &&
2530 !mem_cgroup_is_root(memcg));
2535 static u64 swap_find_max_overage(struct mem_cgroup *memcg)
2537 u64 overage, max_overage = 0;
2540 overage = calculate_overage(page_counter_read(&memcg->swap),
2541 READ_ONCE(memcg->swap.high));
2543 memcg_memory_event(memcg, MEMCG_SWAP_HIGH);
2544 max_overage = max(overage, max_overage);
2545 } while ((memcg = parent_mem_cgroup(memcg)) &&
2546 !mem_cgroup_is_root(memcg));
2552 * Get the number of jiffies that we should penalise a mischievous cgroup which
2553 * is exceeding its memory.high by checking both it and its ancestors.
2555 static unsigned long calculate_high_delay(struct mem_cgroup *memcg,
2556 unsigned int nr_pages,
2559 unsigned long penalty_jiffies;
2565 * We use overage compared to memory.high to calculate the number of
2566 * jiffies to sleep (penalty_jiffies). Ideally this value should be
2567 * fairly lenient on small overages, and increasingly harsh when the
2568 * memcg in question makes it clear that it has no intention of stopping
2569 * its crazy behaviour, so we exponentially increase the delay based on
2572 penalty_jiffies = max_overage * max_overage * HZ;
2573 penalty_jiffies >>= MEMCG_DELAY_PRECISION_SHIFT;
2574 penalty_jiffies >>= MEMCG_DELAY_SCALING_SHIFT;
2577 * Factor in the task's own contribution to the overage, such that four
2578 * N-sized allocations are throttled approximately the same as one
2579 * 4N-sized allocation.
2581 * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or
2582 * larger the current charge patch is than that.
2584 return penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH;
2588 * Scheduled by try_charge() to be executed from the userland return path
2589 * and reclaims memory over the high limit.
2591 void mem_cgroup_handle_over_high(void)
2593 unsigned long penalty_jiffies;
2594 unsigned long pflags;
2595 unsigned long nr_reclaimed;
2596 unsigned int nr_pages = current->memcg_nr_pages_over_high;
2597 int nr_retries = MAX_RECLAIM_RETRIES;
2598 struct mem_cgroup *memcg;
2599 bool in_retry = false;
2601 if (likely(!nr_pages))
2604 memcg = get_mem_cgroup_from_mm(current->mm);
2605 current->memcg_nr_pages_over_high = 0;
2609 * The allocating task should reclaim at least the batch size, but for
2610 * subsequent retries we only want to do what's necessary to prevent oom
2611 * or breaching resource isolation.
2613 * This is distinct from memory.max or page allocator behaviour because
2614 * memory.high is currently batched, whereas memory.max and the page
2615 * allocator run every time an allocation is made.
2617 nr_reclaimed = reclaim_high(memcg,
2618 in_retry ? SWAP_CLUSTER_MAX : nr_pages,
2622 * memory.high is breached and reclaim is unable to keep up. Throttle
2623 * allocators proactively to slow down excessive growth.
2625 penalty_jiffies = calculate_high_delay(memcg, nr_pages,
2626 mem_find_max_overage(memcg));
2628 penalty_jiffies += calculate_high_delay(memcg, nr_pages,
2629 swap_find_max_overage(memcg));
2632 * Clamp the max delay per usermode return so as to still keep the
2633 * application moving forwards and also permit diagnostics, albeit
2636 penalty_jiffies = min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES);
2639 * Don't sleep if the amount of jiffies this memcg owes us is so low
2640 * that it's not even worth doing, in an attempt to be nice to those who
2641 * go only a small amount over their memory.high value and maybe haven't
2642 * been aggressively reclaimed enough yet.
2644 if (penalty_jiffies <= HZ / 100)
2648 * If reclaim is making forward progress but we're still over
2649 * memory.high, we want to encourage that rather than doing allocator
2652 if (nr_reclaimed || nr_retries--) {
2658 * If we exit early, we're guaranteed to die (since
2659 * schedule_timeout_killable sets TASK_KILLABLE). This means we don't
2660 * need to account for any ill-begotten jiffies to pay them off later.
2662 psi_memstall_enter(&pflags);
2663 schedule_timeout_killable(penalty_jiffies);
2664 psi_memstall_leave(&pflags);
2667 css_put(&memcg->css);
2670 static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask,
2671 unsigned int nr_pages)
2673 unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
2674 int nr_retries = MAX_RECLAIM_RETRIES;
2675 struct mem_cgroup *mem_over_limit;
2676 struct page_counter *counter;
2677 unsigned long nr_reclaimed;
2678 bool passed_oom = false;
2679 unsigned int reclaim_options = MEMCG_RECLAIM_MAY_SWAP;
2680 bool drained = false;
2681 bool raised_max_event = false;
2682 unsigned long pflags;
2685 if (consume_stock(memcg, nr_pages))
2688 if (!do_memsw_account() ||
2689 page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2690 if (page_counter_try_charge(&memcg->memory, batch, &counter))
2692 if (do_memsw_account())
2693 page_counter_uncharge(&memcg->memsw, batch);
2694 mem_over_limit = mem_cgroup_from_counter(counter, memory);
2696 mem_over_limit = mem_cgroup_from_counter(counter, memsw);
2697 reclaim_options &= ~MEMCG_RECLAIM_MAY_SWAP;
2700 if (batch > nr_pages) {
2706 * Prevent unbounded recursion when reclaim operations need to
2707 * allocate memory. This might exceed the limits temporarily,
2708 * but we prefer facilitating memory reclaim and getting back
2709 * under the limit over triggering OOM kills in these cases.
2711 if (unlikely(current->flags & PF_MEMALLOC))
2714 if (unlikely(task_in_memcg_oom(current)))
2717 if (!gfpflags_allow_blocking(gfp_mask))
2720 memcg_memory_event(mem_over_limit, MEMCG_MAX);
2721 raised_max_event = true;
2723 psi_memstall_enter(&pflags);
2724 nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
2725 gfp_mask, reclaim_options);
2726 psi_memstall_leave(&pflags);
2728 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2732 drain_all_stock(mem_over_limit);
2737 if (gfp_mask & __GFP_NORETRY)
2740 * Even though the limit is exceeded at this point, reclaim
2741 * may have been able to free some pages. Retry the charge
2742 * before killing the task.
2744 * Only for regular pages, though: huge pages are rather
2745 * unlikely to succeed so close to the limit, and we fall back
2746 * to regular pages anyway in case of failure.
2748 if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
2751 * At task move, charge accounts can be doubly counted. So, it's
2752 * better to wait until the end of task_move if something is going on.
2754 if (mem_cgroup_wait_acct_move(mem_over_limit))
2760 if (gfp_mask & __GFP_RETRY_MAYFAIL)
2763 /* Avoid endless loop for tasks bypassed by the oom killer */
2764 if (passed_oom && task_is_dying())
2768 * keep retrying as long as the memcg oom killer is able to make
2769 * a forward progress or bypass the charge if the oom killer
2770 * couldn't make any progress.
2772 if (mem_cgroup_oom(mem_over_limit, gfp_mask,
2773 get_order(nr_pages * PAGE_SIZE))) {
2775 nr_retries = MAX_RECLAIM_RETRIES;
2780 * Memcg doesn't have a dedicated reserve for atomic
2781 * allocations. But like the global atomic pool, we need to
2782 * put the burden of reclaim on regular allocation requests
2783 * and let these go through as privileged allocations.
2785 if (!(gfp_mask & (__GFP_NOFAIL | __GFP_HIGH)))
2789 * If the allocation has to be enforced, don't forget to raise
2790 * a MEMCG_MAX event.
2792 if (!raised_max_event)
2793 memcg_memory_event(mem_over_limit, MEMCG_MAX);
2796 * The allocation either can't fail or will lead to more memory
2797 * being freed very soon. Allow memory usage go over the limit
2798 * temporarily by force charging it.
2800 page_counter_charge(&memcg->memory, nr_pages);
2801 if (do_memsw_account())
2802 page_counter_charge(&memcg->memsw, nr_pages);
2807 if (batch > nr_pages)
2808 refill_stock(memcg, batch - nr_pages);
2811 * If the hierarchy is above the normal consumption range, schedule
2812 * reclaim on returning to userland. We can perform reclaim here
2813 * if __GFP_RECLAIM but let's always punt for simplicity and so that
2814 * GFP_KERNEL can consistently be used during reclaim. @memcg is
2815 * not recorded as it most likely matches current's and won't
2816 * change in the meantime. As high limit is checked again before
2817 * reclaim, the cost of mismatch is negligible.
2820 bool mem_high, swap_high;
2822 mem_high = page_counter_read(&memcg->memory) >
2823 READ_ONCE(memcg->memory.high);
2824 swap_high = page_counter_read(&memcg->swap) >
2825 READ_ONCE(memcg->swap.high);
2827 /* Don't bother a random interrupted task */
2830 schedule_work(&memcg->high_work);
2836 if (mem_high || swap_high) {
2838 * The allocating tasks in this cgroup will need to do
2839 * reclaim or be throttled to prevent further growth
2840 * of the memory or swap footprints.
2842 * Target some best-effort fairness between the tasks,
2843 * and distribute reclaim work and delay penalties
2844 * based on how much each task is actually allocating.
2846 current->memcg_nr_pages_over_high += batch;
2847 set_notify_resume(current);
2850 } while ((memcg = parent_mem_cgroup(memcg)));
2852 if (current->memcg_nr_pages_over_high > MEMCG_CHARGE_BATCH &&
2853 !(current->flags & PF_MEMALLOC) &&
2854 gfpflags_allow_blocking(gfp_mask)) {
2855 mem_cgroup_handle_over_high();
2860 static inline int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2861 unsigned int nr_pages)
2863 if (mem_cgroup_is_root(memcg))
2866 return try_charge_memcg(memcg, gfp_mask, nr_pages);
2869 static inline void cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
2871 if (mem_cgroup_is_root(memcg))
2874 page_counter_uncharge(&memcg->memory, nr_pages);
2875 if (do_memsw_account())
2876 page_counter_uncharge(&memcg->memsw, nr_pages);
2879 static void commit_charge(struct folio *folio, struct mem_cgroup *memcg)
2881 VM_BUG_ON_FOLIO(folio_memcg(folio), folio);
2883 * Any of the following ensures page's memcg stability:
2887 * - lock_page_memcg()
2888 * - exclusive reference
2889 * - mem_cgroup_trylock_pages()
2891 folio->memcg_data = (unsigned long)memcg;
2894 #ifdef CONFIG_MEMCG_KMEM
2896 * The allocated objcg pointers array is not accounted directly.
2897 * Moreover, it should not come from DMA buffer and is not readily
2898 * reclaimable. So those GFP bits should be masked off.
2900 #define OBJCGS_CLEAR_MASK (__GFP_DMA | __GFP_RECLAIMABLE | __GFP_ACCOUNT)
2903 * mod_objcg_mlstate() may be called with irq enabled, so
2904 * mod_memcg_lruvec_state() should be used.
2906 static inline void mod_objcg_mlstate(struct obj_cgroup *objcg,
2907 struct pglist_data *pgdat,
2908 enum node_stat_item idx, int nr)
2910 struct mem_cgroup *memcg;
2911 struct lruvec *lruvec;
2914 memcg = obj_cgroup_memcg(objcg);
2915 lruvec = mem_cgroup_lruvec(memcg, pgdat);
2916 mod_memcg_lruvec_state(lruvec, idx, nr);
2920 int memcg_alloc_slab_cgroups(struct slab *slab, struct kmem_cache *s,
2921 gfp_t gfp, bool new_slab)
2923 unsigned int objects = objs_per_slab(s, slab);
2924 unsigned long memcg_data;
2927 gfp &= ~OBJCGS_CLEAR_MASK;
2928 vec = kcalloc_node(objects, sizeof(struct obj_cgroup *), gfp,
2933 memcg_data = (unsigned long) vec | MEMCG_DATA_OBJCGS;
2936 * If the slab is brand new and nobody can yet access its
2937 * memcg_data, no synchronization is required and memcg_data can
2938 * be simply assigned.
2940 slab->memcg_data = memcg_data;
2941 } else if (cmpxchg(&slab->memcg_data, 0, memcg_data)) {
2943 * If the slab is already in use, somebody can allocate and
2944 * assign obj_cgroups in parallel. In this case the existing
2945 * objcg vector should be reused.
2951 kmemleak_not_leak(vec);
2955 static __always_inline
2956 struct mem_cgroup *mem_cgroup_from_obj_folio(struct folio *folio, void *p)
2959 * Slab objects are accounted individually, not per-page.
2960 * Memcg membership data for each individual object is saved in
2963 if (folio_test_slab(folio)) {
2964 struct obj_cgroup **objcgs;
2968 slab = folio_slab(folio);
2969 objcgs = slab_objcgs(slab);
2973 off = obj_to_index(slab->slab_cache, slab, p);
2975 return obj_cgroup_memcg(objcgs[off]);
2981 * folio_memcg_check() is used here, because in theory we can encounter
2982 * a folio where the slab flag has been cleared already, but
2983 * slab->memcg_data has not been freed yet
2984 * folio_memcg_check() will guarantee that a proper memory
2985 * cgroup pointer or NULL will be returned.
2987 return folio_memcg_check(folio);
2991 * Returns a pointer to the memory cgroup to which the kernel object is charged.
2993 * A passed kernel object can be a slab object, vmalloc object or a generic
2994 * kernel page, so different mechanisms for getting the memory cgroup pointer
2997 * In certain cases (e.g. kernel stacks or large kmallocs with SLUB) the caller
2998 * can not know for sure how the kernel object is implemented.
2999 * mem_cgroup_from_obj() can be safely used in such cases.
3001 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
3002 * cgroup_mutex, etc.
3004 struct mem_cgroup *mem_cgroup_from_obj(void *p)
3006 struct folio *folio;
3008 if (mem_cgroup_disabled())
3011 if (unlikely(is_vmalloc_addr(p)))
3012 folio = page_folio(vmalloc_to_page(p));
3014 folio = virt_to_folio(p);
3016 return mem_cgroup_from_obj_folio(folio, p);
3020 * Returns a pointer to the memory cgroup to which the kernel object is charged.
3021 * Similar to mem_cgroup_from_obj(), but faster and not suitable for objects,
3022 * allocated using vmalloc().
3024 * A passed kernel object must be a slab object or a generic kernel page.
3026 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
3027 * cgroup_mutex, etc.
3029 struct mem_cgroup *mem_cgroup_from_slab_obj(void *p)
3031 if (mem_cgroup_disabled())
3034 return mem_cgroup_from_obj_folio(virt_to_folio(p), p);
3037 static struct obj_cgroup *__get_obj_cgroup_from_memcg(struct mem_cgroup *memcg)
3039 struct obj_cgroup *objcg = NULL;
3041 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
3042 objcg = rcu_dereference(memcg->objcg);
3043 if (objcg && obj_cgroup_tryget(objcg))
3050 __always_inline struct obj_cgroup *get_obj_cgroup_from_current(void)
3052 struct obj_cgroup *objcg = NULL;
3053 struct mem_cgroup *memcg;
3055 if (memcg_kmem_bypass())
3059 if (unlikely(active_memcg()))
3060 memcg = active_memcg();
3062 memcg = mem_cgroup_from_task(current);
3063 objcg = __get_obj_cgroup_from_memcg(memcg);
3068 struct obj_cgroup *get_obj_cgroup_from_page(struct page *page)
3070 struct obj_cgroup *objcg;
3072 if (!memcg_kmem_online())
3075 if (PageMemcgKmem(page)) {
3076 objcg = __folio_objcg(page_folio(page));
3077 obj_cgroup_get(objcg);
3079 struct mem_cgroup *memcg;
3082 memcg = __folio_memcg(page_folio(page));
3084 objcg = __get_obj_cgroup_from_memcg(memcg);
3092 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages)
3094 mod_memcg_state(memcg, MEMCG_KMEM, nr_pages);
3095 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
3097 page_counter_charge(&memcg->kmem, nr_pages);
3099 page_counter_uncharge(&memcg->kmem, -nr_pages);
3105 * obj_cgroup_uncharge_pages: uncharge a number of kernel pages from a objcg
3106 * @objcg: object cgroup to uncharge
3107 * @nr_pages: number of pages to uncharge
3109 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
3110 unsigned int nr_pages)
3112 struct mem_cgroup *memcg;
3114 memcg = get_mem_cgroup_from_objcg(objcg);
3116 memcg_account_kmem(memcg, -nr_pages);
3117 refill_stock(memcg, nr_pages);
3119 css_put(&memcg->css);
3123 * obj_cgroup_charge_pages: charge a number of kernel pages to a objcg
3124 * @objcg: object cgroup to charge
3125 * @gfp: reclaim mode
3126 * @nr_pages: number of pages to charge
3128 * Returns 0 on success, an error code on failure.
3130 static int obj_cgroup_charge_pages(struct obj_cgroup *objcg, gfp_t gfp,
3131 unsigned int nr_pages)
3133 struct mem_cgroup *memcg;
3136 memcg = get_mem_cgroup_from_objcg(objcg);
3138 ret = try_charge_memcg(memcg, gfp, nr_pages);
3142 memcg_account_kmem(memcg, nr_pages);
3144 css_put(&memcg->css);
3150 * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup
3151 * @page: page to charge
3152 * @gfp: reclaim mode
3153 * @order: allocation order
3155 * Returns 0 on success, an error code on failure.
3157 int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
3159 struct obj_cgroup *objcg;
3162 objcg = get_obj_cgroup_from_current();
3164 ret = obj_cgroup_charge_pages(objcg, gfp, 1 << order);
3166 page->memcg_data = (unsigned long)objcg |
3170 obj_cgroup_put(objcg);
3176 * __memcg_kmem_uncharge_page: uncharge a kmem page
3177 * @page: page to uncharge
3178 * @order: allocation order
3180 void __memcg_kmem_uncharge_page(struct page *page, int order)
3182 struct folio *folio = page_folio(page);
3183 struct obj_cgroup *objcg;
3184 unsigned int nr_pages = 1 << order;
3186 if (!folio_memcg_kmem(folio))
3189 objcg = __folio_objcg(folio);
3190 obj_cgroup_uncharge_pages(objcg, nr_pages);
3191 folio->memcg_data = 0;
3192 obj_cgroup_put(objcg);
3195 void mod_objcg_state(struct obj_cgroup *objcg, struct pglist_data *pgdat,
3196 enum node_stat_item idx, int nr)
3198 struct memcg_stock_pcp *stock;
3199 struct obj_cgroup *old = NULL;
3200 unsigned long flags;
3203 local_lock_irqsave(&memcg_stock.stock_lock, flags);
3204 stock = this_cpu_ptr(&memcg_stock);
3207 * Save vmstat data in stock and skip vmstat array update unless
3208 * accumulating over a page of vmstat data or when pgdat or idx
3211 if (READ_ONCE(stock->cached_objcg) != objcg) {
3212 old = drain_obj_stock(stock);
3213 obj_cgroup_get(objcg);
3214 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3215 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3216 WRITE_ONCE(stock->cached_objcg, objcg);
3217 stock->cached_pgdat = pgdat;
3218 } else if (stock->cached_pgdat != pgdat) {
3219 /* Flush the existing cached vmstat data */
3220 struct pglist_data *oldpg = stock->cached_pgdat;
3222 if (stock->nr_slab_reclaimable_b) {
3223 mod_objcg_mlstate(objcg, oldpg, NR_SLAB_RECLAIMABLE_B,
3224 stock->nr_slab_reclaimable_b);
3225 stock->nr_slab_reclaimable_b = 0;
3227 if (stock->nr_slab_unreclaimable_b) {
3228 mod_objcg_mlstate(objcg, oldpg, NR_SLAB_UNRECLAIMABLE_B,
3229 stock->nr_slab_unreclaimable_b);
3230 stock->nr_slab_unreclaimable_b = 0;
3232 stock->cached_pgdat = pgdat;
3235 bytes = (idx == NR_SLAB_RECLAIMABLE_B) ? &stock->nr_slab_reclaimable_b
3236 : &stock->nr_slab_unreclaimable_b;
3238 * Even for large object >= PAGE_SIZE, the vmstat data will still be
3239 * cached locally at least once before pushing it out.
3246 if (abs(*bytes) > PAGE_SIZE) {
3254 mod_objcg_mlstate(objcg, pgdat, idx, nr);
3256 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3258 obj_cgroup_put(old);
3261 static bool consume_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes)
3263 struct memcg_stock_pcp *stock;
3264 unsigned long flags;
3267 local_lock_irqsave(&memcg_stock.stock_lock, flags);
3269 stock = this_cpu_ptr(&memcg_stock);
3270 if (objcg == READ_ONCE(stock->cached_objcg) && stock->nr_bytes >= nr_bytes) {
3271 stock->nr_bytes -= nr_bytes;
3275 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3280 static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock)
3282 struct obj_cgroup *old = READ_ONCE(stock->cached_objcg);
3287 if (stock->nr_bytes) {
3288 unsigned int nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3289 unsigned int nr_bytes = stock->nr_bytes & (PAGE_SIZE - 1);
3292 struct mem_cgroup *memcg;
3294 memcg = get_mem_cgroup_from_objcg(old);
3296 memcg_account_kmem(memcg, -nr_pages);
3297 __refill_stock(memcg, nr_pages);
3299 css_put(&memcg->css);
3303 * The leftover is flushed to the centralized per-memcg value.
3304 * On the next attempt to refill obj stock it will be moved
3305 * to a per-cpu stock (probably, on an other CPU), see
3306 * refill_obj_stock().
3308 * How often it's flushed is a trade-off between the memory
3309 * limit enforcement accuracy and potential CPU contention,
3310 * so it might be changed in the future.
3312 atomic_add(nr_bytes, &old->nr_charged_bytes);
3313 stock->nr_bytes = 0;
3317 * Flush the vmstat data in current stock
3319 if (stock->nr_slab_reclaimable_b || stock->nr_slab_unreclaimable_b) {
3320 if (stock->nr_slab_reclaimable_b) {
3321 mod_objcg_mlstate(old, stock->cached_pgdat,
3322 NR_SLAB_RECLAIMABLE_B,
3323 stock->nr_slab_reclaimable_b);
3324 stock->nr_slab_reclaimable_b = 0;
3326 if (stock->nr_slab_unreclaimable_b) {
3327 mod_objcg_mlstate(old, stock->cached_pgdat,
3328 NR_SLAB_UNRECLAIMABLE_B,
3329 stock->nr_slab_unreclaimable_b);
3330 stock->nr_slab_unreclaimable_b = 0;
3332 stock->cached_pgdat = NULL;
3335 WRITE_ONCE(stock->cached_objcg, NULL);
3337 * The `old' objects needs to be released by the caller via
3338 * obj_cgroup_put() outside of memcg_stock_pcp::stock_lock.
3343 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
3344 struct mem_cgroup *root_memcg)
3346 struct obj_cgroup *objcg = READ_ONCE(stock->cached_objcg);
3347 struct mem_cgroup *memcg;
3350 memcg = obj_cgroup_memcg(objcg);
3351 if (memcg && mem_cgroup_is_descendant(memcg, root_memcg))
3358 static void refill_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes,
3359 bool allow_uncharge)
3361 struct memcg_stock_pcp *stock;
3362 struct obj_cgroup *old = NULL;
3363 unsigned long flags;
3364 unsigned int nr_pages = 0;
3366 local_lock_irqsave(&memcg_stock.stock_lock, flags);
3368 stock = this_cpu_ptr(&memcg_stock);
3369 if (READ_ONCE(stock->cached_objcg) != objcg) { /* reset if necessary */
3370 old = drain_obj_stock(stock);
3371 obj_cgroup_get(objcg);
3372 WRITE_ONCE(stock->cached_objcg, objcg);
3373 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3374 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3375 allow_uncharge = true; /* Allow uncharge when objcg changes */
3377 stock->nr_bytes += nr_bytes;
3379 if (allow_uncharge && (stock->nr_bytes > PAGE_SIZE)) {
3380 nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3381 stock->nr_bytes &= (PAGE_SIZE - 1);
3384 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3386 obj_cgroup_put(old);
3389 obj_cgroup_uncharge_pages(objcg, nr_pages);
3392 int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size)
3394 unsigned int nr_pages, nr_bytes;
3397 if (consume_obj_stock(objcg, size))
3401 * In theory, objcg->nr_charged_bytes can have enough
3402 * pre-charged bytes to satisfy the allocation. However,
3403 * flushing objcg->nr_charged_bytes requires two atomic
3404 * operations, and objcg->nr_charged_bytes can't be big.
3405 * The shared objcg->nr_charged_bytes can also become a
3406 * performance bottleneck if all tasks of the same memcg are
3407 * trying to update it. So it's better to ignore it and try
3408 * grab some new pages. The stock's nr_bytes will be flushed to
3409 * objcg->nr_charged_bytes later on when objcg changes.
3411 * The stock's nr_bytes may contain enough pre-charged bytes
3412 * to allow one less page from being charged, but we can't rely
3413 * on the pre-charged bytes not being changed outside of
3414 * consume_obj_stock() or refill_obj_stock(). So ignore those
3415 * pre-charged bytes as well when charging pages. To avoid a
3416 * page uncharge right after a page charge, we set the
3417 * allow_uncharge flag to false when calling refill_obj_stock()
3418 * to temporarily allow the pre-charged bytes to exceed the page
3419 * size limit. The maximum reachable value of the pre-charged
3420 * bytes is (sizeof(object) + PAGE_SIZE - 2) if there is no data
3423 nr_pages = size >> PAGE_SHIFT;
3424 nr_bytes = size & (PAGE_SIZE - 1);
3429 ret = obj_cgroup_charge_pages(objcg, gfp, nr_pages);
3430 if (!ret && nr_bytes)
3431 refill_obj_stock(objcg, PAGE_SIZE - nr_bytes, false);
3436 void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size)
3438 refill_obj_stock(objcg, size, true);
3441 #endif /* CONFIG_MEMCG_KMEM */
3444 * Because page_memcg(head) is not set on tails, set it now.
3446 void split_page_memcg(struct page *head, unsigned int nr)
3448 struct folio *folio = page_folio(head);
3449 struct mem_cgroup *memcg = folio_memcg(folio);
3452 if (mem_cgroup_disabled() || !memcg)
3455 for (i = 1; i < nr; i++)
3456 folio_page(folio, i)->memcg_data = folio->memcg_data;
3458 if (folio_memcg_kmem(folio))
3459 obj_cgroup_get_many(__folio_objcg(folio), nr - 1);
3461 css_get_many(&memcg->css, nr - 1);
3466 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3467 * @entry: swap entry to be moved
3468 * @from: mem_cgroup which the entry is moved from
3469 * @to: mem_cgroup which the entry is moved to
3471 * It succeeds only when the swap_cgroup's record for this entry is the same
3472 * as the mem_cgroup's id of @from.
3474 * Returns 0 on success, -EINVAL on failure.
3476 * The caller must have charged to @to, IOW, called page_counter_charge() about
3477 * both res and memsw, and called css_get().
3479 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3480 struct mem_cgroup *from, struct mem_cgroup *to)
3482 unsigned short old_id, new_id;
3484 old_id = mem_cgroup_id(from);
3485 new_id = mem_cgroup_id(to);
3487 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3488 mod_memcg_state(from, MEMCG_SWAP, -1);
3489 mod_memcg_state(to, MEMCG_SWAP, 1);
3495 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3496 struct mem_cgroup *from, struct mem_cgroup *to)
3502 static DEFINE_MUTEX(memcg_max_mutex);
3504 static int mem_cgroup_resize_max(struct mem_cgroup *memcg,
3505 unsigned long max, bool memsw)
3507 bool enlarge = false;
3508 bool drained = false;
3510 bool limits_invariant;
3511 struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory;
3514 if (signal_pending(current)) {
3519 mutex_lock(&memcg_max_mutex);
3521 * Make sure that the new limit (memsw or memory limit) doesn't
3522 * break our basic invariant rule memory.max <= memsw.max.
3524 limits_invariant = memsw ? max >= READ_ONCE(memcg->memory.max) :
3525 max <= memcg->memsw.max;
3526 if (!limits_invariant) {
3527 mutex_unlock(&memcg_max_mutex);
3531 if (max > counter->max)
3533 ret = page_counter_set_max(counter, max);
3534 mutex_unlock(&memcg_max_mutex);
3540 drain_all_stock(memcg);
3545 if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,
3546 memsw ? 0 : MEMCG_RECLAIM_MAY_SWAP)) {
3552 if (!ret && enlarge)
3553 memcg_oom_recover(memcg);
3558 unsigned long mem_cgroup_soft_limit_reclaim(pg_data_t *pgdat, int order,
3560 unsigned long *total_scanned)
3562 unsigned long nr_reclaimed = 0;
3563 struct mem_cgroup_per_node *mz, *next_mz = NULL;
3564 unsigned long reclaimed;
3566 struct mem_cgroup_tree_per_node *mctz;
3567 unsigned long excess;
3569 if (lru_gen_enabled())
3575 mctz = soft_limit_tree.rb_tree_per_node[pgdat->node_id];
3578 * Do not even bother to check the largest node if the root
3579 * is empty. Do it lockless to prevent lock bouncing. Races
3580 * are acceptable as soft limit is best effort anyway.
3582 if (!mctz || RB_EMPTY_ROOT(&mctz->rb_root))
3586 * This loop can run a while, specially if mem_cgroup's continuously
3587 * keep exceeding their soft limit and putting the system under
3594 mz = mem_cgroup_largest_soft_limit_node(mctz);
3598 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, pgdat,
3599 gfp_mask, total_scanned);
3600 nr_reclaimed += reclaimed;
3601 spin_lock_irq(&mctz->lock);
3604 * If we failed to reclaim anything from this memory cgroup
3605 * it is time to move on to the next cgroup
3609 next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
3611 excess = soft_limit_excess(mz->memcg);
3613 * One school of thought says that we should not add
3614 * back the node to the tree if reclaim returns 0.
3615 * But our reclaim could return 0, simply because due
3616 * to priority we are exposing a smaller subset of
3617 * memory to reclaim from. Consider this as a longer
3620 /* If excess == 0, no tree ops */
3621 __mem_cgroup_insert_exceeded(mz, mctz, excess);
3622 spin_unlock_irq(&mctz->lock);
3623 css_put(&mz->memcg->css);
3626 * Could not reclaim anything and there are no more
3627 * mem cgroups to try or we seem to be looping without
3628 * reclaiming anything.
3630 if (!nr_reclaimed &&
3632 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3634 } while (!nr_reclaimed);
3636 css_put(&next_mz->memcg->css);
3637 return nr_reclaimed;
3641 * Reclaims as many pages from the given memcg as possible.
3643 * Caller is responsible for holding css reference for memcg.
3645 static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
3647 int nr_retries = MAX_RECLAIM_RETRIES;
3649 /* we call try-to-free pages for make this cgroup empty */
3650 lru_add_drain_all();
3652 drain_all_stock(memcg);
3654 /* try to free all pages in this cgroup */
3655 while (nr_retries && page_counter_read(&memcg->memory)) {
3656 if (signal_pending(current))
3659 if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,
3660 MEMCG_RECLAIM_MAY_SWAP))
3667 static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
3668 char *buf, size_t nbytes,
3671 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3673 if (mem_cgroup_is_root(memcg))
3675 return mem_cgroup_force_empty(memcg) ?: nbytes;
3678 static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
3684 static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
3685 struct cftype *cft, u64 val)
3690 pr_warn_once("Non-hierarchical mode is deprecated. "
3691 "Please report your usecase to linux-mm@kvack.org if you "
3692 "depend on this functionality.\n");
3697 static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3701 if (mem_cgroup_is_root(memcg)) {
3703 * We can reach here from irq context through:
3705 * |--memcg_check_events()
3706 * |--mem_cgroup_threshold()
3707 * |--__mem_cgroup_threshold()
3708 * |--mem_cgroup_usage
3710 * rstat flushing is an expensive operation that should not be
3711 * done from irq context; use stale stats in this case.
3712 * Arguably, usage threshold events are not reliable on the root
3713 * memcg anyway since its usage is ill-defined.
3715 * Additionally, other call paths through memcg_check_events()
3716 * disable irqs, so make sure we are flushing stats atomically.
3719 mem_cgroup_flush_stats_atomic();
3720 val = memcg_page_state(memcg, NR_FILE_PAGES) +
3721 memcg_page_state(memcg, NR_ANON_MAPPED);
3723 val += memcg_page_state(memcg, MEMCG_SWAP);
3726 val = page_counter_read(&memcg->memory);
3728 val = page_counter_read(&memcg->memsw);
3741 static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
3744 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3745 struct page_counter *counter;
3747 switch (MEMFILE_TYPE(cft->private)) {
3749 counter = &memcg->memory;
3752 counter = &memcg->memsw;
3755 counter = &memcg->kmem;
3758 counter = &memcg->tcpmem;
3764 switch (MEMFILE_ATTR(cft->private)) {
3766 if (counter == &memcg->memory)
3767 return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
3768 if (counter == &memcg->memsw)
3769 return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
3770 return (u64)page_counter_read(counter) * PAGE_SIZE;
3772 return (u64)counter->max * PAGE_SIZE;
3774 return (u64)counter->watermark * PAGE_SIZE;
3776 return counter->failcnt;
3777 case RES_SOFT_LIMIT:
3778 return (u64)READ_ONCE(memcg->soft_limit) * PAGE_SIZE;
3785 * This function doesn't do anything useful. Its only job is to provide a read
3786 * handler for a file so that cgroup_file_mode() will add read permissions.
3788 static int mem_cgroup_dummy_seq_show(__always_unused struct seq_file *m,
3789 __always_unused void *v)
3794 #ifdef CONFIG_MEMCG_KMEM
3795 static int memcg_online_kmem(struct mem_cgroup *memcg)
3797 struct obj_cgroup *objcg;
3799 if (mem_cgroup_kmem_disabled())
3802 if (unlikely(mem_cgroup_is_root(memcg)))
3805 objcg = obj_cgroup_alloc();
3809 objcg->memcg = memcg;
3810 rcu_assign_pointer(memcg->objcg, objcg);
3812 static_branch_enable(&memcg_kmem_online_key);
3814 memcg->kmemcg_id = memcg->id.id;
3819 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3821 struct mem_cgroup *parent;
3823 if (mem_cgroup_kmem_disabled())
3826 if (unlikely(mem_cgroup_is_root(memcg)))
3829 parent = parent_mem_cgroup(memcg);
3831 parent = root_mem_cgroup;
3833 memcg_reparent_objcgs(memcg, parent);
3836 * After we have finished memcg_reparent_objcgs(), all list_lrus
3837 * corresponding to this cgroup are guaranteed to remain empty.
3838 * The ordering is imposed by list_lru_node->lock taken by
3839 * memcg_reparent_list_lrus().
3841 memcg_reparent_list_lrus(memcg, parent);
3844 static int memcg_online_kmem(struct mem_cgroup *memcg)
3848 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3851 #endif /* CONFIG_MEMCG_KMEM */
3853 static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max)
3857 mutex_lock(&memcg_max_mutex);
3859 ret = page_counter_set_max(&memcg->tcpmem, max);
3863 if (!memcg->tcpmem_active) {
3865 * The active flag needs to be written after the static_key
3866 * update. This is what guarantees that the socket activation
3867 * function is the last one to run. See mem_cgroup_sk_alloc()
3868 * for details, and note that we don't mark any socket as
3869 * belonging to this memcg until that flag is up.
3871 * We need to do this, because static_keys will span multiple
3872 * sites, but we can't control their order. If we mark a socket
3873 * as accounted, but the accounting functions are not patched in
3874 * yet, we'll lose accounting.
3876 * We never race with the readers in mem_cgroup_sk_alloc(),
3877 * because when this value change, the code to process it is not
3880 static_branch_inc(&memcg_sockets_enabled_key);
3881 memcg->tcpmem_active = true;
3884 mutex_unlock(&memcg_max_mutex);
3889 * The user of this function is...
3892 static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
3893 char *buf, size_t nbytes, loff_t off)
3895 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3896 unsigned long nr_pages;
3899 buf = strstrip(buf);
3900 ret = page_counter_memparse(buf, "-1", &nr_pages);
3904 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3906 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3910 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3912 ret = mem_cgroup_resize_max(memcg, nr_pages, false);
3915 ret = mem_cgroup_resize_max(memcg, nr_pages, true);
3918 /* kmem.limit_in_bytes is deprecated. */
3922 ret = memcg_update_tcp_max(memcg, nr_pages);
3926 case RES_SOFT_LIMIT:
3927 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
3930 WRITE_ONCE(memcg->soft_limit, nr_pages);
3935 return ret ?: nbytes;
3938 static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
3939 size_t nbytes, loff_t off)
3941 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3942 struct page_counter *counter;
3944 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3946 counter = &memcg->memory;
3949 counter = &memcg->memsw;
3952 counter = &memcg->kmem;
3955 counter = &memcg->tcpmem;
3961 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3963 page_counter_reset_watermark(counter);
3966 counter->failcnt = 0;
3975 static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
3978 return mem_cgroup_from_css(css)->move_charge_at_immigrate;
3982 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3983 struct cftype *cft, u64 val)
3985 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3987 pr_warn_once("Cgroup memory moving (move_charge_at_immigrate) is deprecated. "
3988 "Please report your usecase to linux-mm@kvack.org if you "
3989 "depend on this functionality.\n");
3991 if (val & ~MOVE_MASK)
3995 * No kind of locking is needed in here, because ->can_attach() will
3996 * check this value once in the beginning of the process, and then carry
3997 * on with stale data. This means that changes to this value will only
3998 * affect task migrations starting after the change.
4000 memcg->move_charge_at_immigrate = val;
4004 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
4005 struct cftype *cft, u64 val)
4013 #define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE))
4014 #define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON))
4015 #define LRU_ALL ((1 << NR_LRU_LISTS) - 1)
4017 static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
4018 int nid, unsigned int lru_mask, bool tree)
4020 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
4021 unsigned long nr = 0;
4024 VM_BUG_ON((unsigned)nid >= nr_node_ids);
4027 if (!(BIT(lru) & lru_mask))
4030 nr += lruvec_page_state(lruvec, NR_LRU_BASE + lru);
4032 nr += lruvec_page_state_local(lruvec, NR_LRU_BASE + lru);
4037 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
4038 unsigned int lru_mask,
4041 unsigned long nr = 0;
4045 if (!(BIT(lru) & lru_mask))
4048 nr += memcg_page_state(memcg, NR_LRU_BASE + lru);
4050 nr += memcg_page_state_local(memcg, NR_LRU_BASE + lru);
4055 static int memcg_numa_stat_show(struct seq_file *m, void *v)
4059 unsigned int lru_mask;
4062 static const struct numa_stat stats[] = {
4063 { "total", LRU_ALL },
4064 { "file", LRU_ALL_FILE },
4065 { "anon", LRU_ALL_ANON },
4066 { "unevictable", BIT(LRU_UNEVICTABLE) },
4068 const struct numa_stat *stat;
4070 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
4072 mem_cgroup_flush_stats();
4074 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
4075 seq_printf(m, "%s=%lu", stat->name,
4076 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
4078 for_each_node_state(nid, N_MEMORY)
4079 seq_printf(m, " N%d=%lu", nid,
4080 mem_cgroup_node_nr_lru_pages(memcg, nid,
4081 stat->lru_mask, false));
4085 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
4087 seq_printf(m, "hierarchical_%s=%lu", stat->name,
4088 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
4090 for_each_node_state(nid, N_MEMORY)
4091 seq_printf(m, " N%d=%lu", nid,
4092 mem_cgroup_node_nr_lru_pages(memcg, nid,
4093 stat->lru_mask, true));
4099 #endif /* CONFIG_NUMA */
4101 static const unsigned int memcg1_stats[] = {
4104 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4111 WORKINGSET_REFAULT_ANON,
4112 WORKINGSET_REFAULT_FILE,
4116 static const char *const memcg1_stat_names[] = {
4119 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4126 "workingset_refault_anon",
4127 "workingset_refault_file",
4131 /* Universal VM events cgroup1 shows, original sort order */
4132 static const unsigned int memcg1_events[] = {
4139 static int memcg_stat_show(struct seq_file *m, void *v)
4141 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
4142 unsigned long memory, memsw;
4143 struct mem_cgroup *mi;
4146 BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats));
4148 mem_cgroup_flush_stats();
4150 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
4153 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
4155 nr = memcg_page_state_local(memcg, memcg1_stats[i]);
4156 seq_printf(m, "%s %lu\n", memcg1_stat_names[i],
4157 nr * memcg_page_state_unit(memcg1_stats[i]));
4160 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
4161 seq_printf(m, "%s %lu\n", vm_event_name(memcg1_events[i]),
4162 memcg_events_local(memcg, memcg1_events[i]));
4164 for (i = 0; i < NR_LRU_LISTS; i++)
4165 seq_printf(m, "%s %lu\n", lru_list_name(i),
4166 memcg_page_state_local(memcg, NR_LRU_BASE + i) *
4169 /* Hierarchical information */
4170 memory = memsw = PAGE_COUNTER_MAX;
4171 for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
4172 memory = min(memory, READ_ONCE(mi->memory.max));
4173 memsw = min(memsw, READ_ONCE(mi->memsw.max));
4175 seq_printf(m, "hierarchical_memory_limit %llu\n",
4176 (u64)memory * PAGE_SIZE);
4177 if (do_memsw_account())
4178 seq_printf(m, "hierarchical_memsw_limit %llu\n",
4179 (u64)memsw * PAGE_SIZE);
4181 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
4184 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
4186 nr = memcg_page_state(memcg, memcg1_stats[i]);
4187 seq_printf(m, "total_%s %llu\n", memcg1_stat_names[i],
4188 (u64)nr * memcg_page_state_unit(memcg1_stats[i]));
4191 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
4192 seq_printf(m, "total_%s %llu\n",
4193 vm_event_name(memcg1_events[i]),
4194 (u64)memcg_events(memcg, memcg1_events[i]));
4196 for (i = 0; i < NR_LRU_LISTS; i++)
4197 seq_printf(m, "total_%s %llu\n", lru_list_name(i),
4198 (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
4201 #ifdef CONFIG_DEBUG_VM
4204 struct mem_cgroup_per_node *mz;
4205 unsigned long anon_cost = 0;
4206 unsigned long file_cost = 0;
4208 for_each_online_pgdat(pgdat) {
4209 mz = memcg->nodeinfo[pgdat->node_id];
4211 anon_cost += mz->lruvec.anon_cost;
4212 file_cost += mz->lruvec.file_cost;
4214 seq_printf(m, "anon_cost %lu\n", anon_cost);
4215 seq_printf(m, "file_cost %lu\n", file_cost);
4222 static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
4225 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4227 return mem_cgroup_swappiness(memcg);
4230 static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
4231 struct cftype *cft, u64 val)
4233 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4238 if (!mem_cgroup_is_root(memcg))
4239 WRITE_ONCE(memcg->swappiness, val);
4241 WRITE_ONCE(vm_swappiness, val);
4246 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4248 struct mem_cgroup_threshold_ary *t;
4249 unsigned long usage;
4254 t = rcu_dereference(memcg->thresholds.primary);
4256 t = rcu_dereference(memcg->memsw_thresholds.primary);
4261 usage = mem_cgroup_usage(memcg, swap);
4264 * current_threshold points to threshold just below or equal to usage.
4265 * If it's not true, a threshold was crossed after last
4266 * call of __mem_cgroup_threshold().
4268 i = t->current_threshold;
4271 * Iterate backward over array of thresholds starting from
4272 * current_threshold and check if a threshold is crossed.
4273 * If none of thresholds below usage is crossed, we read
4274 * only one element of the array here.
4276 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4277 eventfd_signal(t->entries[i].eventfd, 1);
4279 /* i = current_threshold + 1 */
4283 * Iterate forward over array of thresholds starting from
4284 * current_threshold+1 and check if a threshold is crossed.
4285 * If none of thresholds above usage is crossed, we read
4286 * only one element of the array here.
4288 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4289 eventfd_signal(t->entries[i].eventfd, 1);
4291 /* Update current_threshold */
4292 t->current_threshold = i - 1;
4297 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4300 __mem_cgroup_threshold(memcg, false);
4301 if (do_memsw_account())
4302 __mem_cgroup_threshold(memcg, true);
4304 memcg = parent_mem_cgroup(memcg);
4308 static int compare_thresholds(const void *a, const void *b)
4310 const struct mem_cgroup_threshold *_a = a;
4311 const struct mem_cgroup_threshold *_b = b;
4313 if (_a->threshold > _b->threshold)
4316 if (_a->threshold < _b->threshold)
4322 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
4324 struct mem_cgroup_eventfd_list *ev;
4326 spin_lock(&memcg_oom_lock);
4328 list_for_each_entry(ev, &memcg->oom_notify, list)
4329 eventfd_signal(ev->eventfd, 1);
4331 spin_unlock(&memcg_oom_lock);
4335 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
4337 struct mem_cgroup *iter;
4339 for_each_mem_cgroup_tree(iter, memcg)
4340 mem_cgroup_oom_notify_cb(iter);
4343 static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4344 struct eventfd_ctx *eventfd, const char *args, enum res_type type)
4346 struct mem_cgroup_thresholds *thresholds;
4347 struct mem_cgroup_threshold_ary *new;
4348 unsigned long threshold;
4349 unsigned long usage;
4352 ret = page_counter_memparse(args, "-1", &threshold);
4356 mutex_lock(&memcg->thresholds_lock);
4359 thresholds = &memcg->thresholds;
4360 usage = mem_cgroup_usage(memcg, false);
4361 } else if (type == _MEMSWAP) {
4362 thresholds = &memcg->memsw_thresholds;
4363 usage = mem_cgroup_usage(memcg, true);
4367 /* Check if a threshold crossed before adding a new one */
4368 if (thresholds->primary)
4369 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4371 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4373 /* Allocate memory for new array of thresholds */
4374 new = kmalloc(struct_size(new, entries, size), GFP_KERNEL);
4381 /* Copy thresholds (if any) to new array */
4382 if (thresholds->primary)
4383 memcpy(new->entries, thresholds->primary->entries,
4384 flex_array_size(new, entries, size - 1));
4386 /* Add new threshold */
4387 new->entries[size - 1].eventfd = eventfd;
4388 new->entries[size - 1].threshold = threshold;
4390 /* Sort thresholds. Registering of new threshold isn't time-critical */
4391 sort(new->entries, size, sizeof(*new->entries),
4392 compare_thresholds, NULL);
4394 /* Find current threshold */
4395 new->current_threshold = -1;
4396 for (i = 0; i < size; i++) {
4397 if (new->entries[i].threshold <= usage) {
4399 * new->current_threshold will not be used until
4400 * rcu_assign_pointer(), so it's safe to increment
4403 ++new->current_threshold;
4408 /* Free old spare buffer and save old primary buffer as spare */
4409 kfree(thresholds->spare);
4410 thresholds->spare = thresholds->primary;
4412 rcu_assign_pointer(thresholds->primary, new);
4414 /* To be sure that nobody uses thresholds */
4418 mutex_unlock(&memcg->thresholds_lock);
4423 static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4424 struct eventfd_ctx *eventfd, const char *args)
4426 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
4429 static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
4430 struct eventfd_ctx *eventfd, const char *args)
4432 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
4435 static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4436 struct eventfd_ctx *eventfd, enum res_type type)
4438 struct mem_cgroup_thresholds *thresholds;
4439 struct mem_cgroup_threshold_ary *new;
4440 unsigned long usage;
4441 int i, j, size, entries;
4443 mutex_lock(&memcg->thresholds_lock);
4446 thresholds = &memcg->thresholds;
4447 usage = mem_cgroup_usage(memcg, false);
4448 } else if (type == _MEMSWAP) {
4449 thresholds = &memcg->memsw_thresholds;
4450 usage = mem_cgroup_usage(memcg, true);
4454 if (!thresholds->primary)
4457 /* Check if a threshold crossed before removing */
4458 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4460 /* Calculate new number of threshold */
4462 for (i = 0; i < thresholds->primary->size; i++) {
4463 if (thresholds->primary->entries[i].eventfd != eventfd)
4469 new = thresholds->spare;
4471 /* If no items related to eventfd have been cleared, nothing to do */
4475 /* Set thresholds array to NULL if we don't have thresholds */
4484 /* Copy thresholds and find current threshold */
4485 new->current_threshold = -1;
4486 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4487 if (thresholds->primary->entries[i].eventfd == eventfd)
4490 new->entries[j] = thresholds->primary->entries[i];
4491 if (new->entries[j].threshold <= usage) {
4493 * new->current_threshold will not be used
4494 * until rcu_assign_pointer(), so it's safe to increment
4497 ++new->current_threshold;
4503 /* Swap primary and spare array */
4504 thresholds->spare = thresholds->primary;
4506 rcu_assign_pointer(thresholds->primary, new);
4508 /* To be sure that nobody uses thresholds */
4511 /* If all events are unregistered, free the spare array */
4513 kfree(thresholds->spare);
4514 thresholds->spare = NULL;
4517 mutex_unlock(&memcg->thresholds_lock);
4520 static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4521 struct eventfd_ctx *eventfd)
4523 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
4526 static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4527 struct eventfd_ctx *eventfd)
4529 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
4532 static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
4533 struct eventfd_ctx *eventfd, const char *args)
4535 struct mem_cgroup_eventfd_list *event;
4537 event = kmalloc(sizeof(*event), GFP_KERNEL);
4541 spin_lock(&memcg_oom_lock);
4543 event->eventfd = eventfd;
4544 list_add(&event->list, &memcg->oom_notify);
4546 /* already in OOM ? */
4547 if (memcg->under_oom)
4548 eventfd_signal(eventfd, 1);
4549 spin_unlock(&memcg_oom_lock);
4554 static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
4555 struct eventfd_ctx *eventfd)
4557 struct mem_cgroup_eventfd_list *ev, *tmp;
4559 spin_lock(&memcg_oom_lock);
4561 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
4562 if (ev->eventfd == eventfd) {
4563 list_del(&ev->list);
4568 spin_unlock(&memcg_oom_lock);
4571 static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
4573 struct mem_cgroup *memcg = mem_cgroup_from_seq(sf);
4575 seq_printf(sf, "oom_kill_disable %d\n", READ_ONCE(memcg->oom_kill_disable));
4576 seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
4577 seq_printf(sf, "oom_kill %lu\n",
4578 atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
4582 static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
4583 struct cftype *cft, u64 val)
4585 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4587 /* cannot set to root cgroup and only 0 and 1 are allowed */
4588 if (mem_cgroup_is_root(memcg) || !((val == 0) || (val == 1)))
4591 WRITE_ONCE(memcg->oom_kill_disable, val);
4593 memcg_oom_recover(memcg);
4598 #ifdef CONFIG_CGROUP_WRITEBACK
4600 #include <trace/events/writeback.h>
4602 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4604 return wb_domain_init(&memcg->cgwb_domain, gfp);
4607 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4609 wb_domain_exit(&memcg->cgwb_domain);
4612 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4614 wb_domain_size_changed(&memcg->cgwb_domain);
4617 struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
4619 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4621 if (!memcg->css.parent)
4624 return &memcg->cgwb_domain;
4628 * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
4629 * @wb: bdi_writeback in question
4630 * @pfilepages: out parameter for number of file pages
4631 * @pheadroom: out parameter for number of allocatable pages according to memcg
4632 * @pdirty: out parameter for number of dirty pages
4633 * @pwriteback: out parameter for number of pages under writeback
4635 * Determine the numbers of file, headroom, dirty, and writeback pages in
4636 * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom
4637 * is a bit more involved.
4639 * A memcg's headroom is "min(max, high) - used". In the hierarchy, the
4640 * headroom is calculated as the lowest headroom of itself and the
4641 * ancestors. Note that this doesn't consider the actual amount of
4642 * available memory in the system. The caller should further cap
4643 * *@pheadroom accordingly.
4645 void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
4646 unsigned long *pheadroom, unsigned long *pdirty,
4647 unsigned long *pwriteback)
4649 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4650 struct mem_cgroup *parent;
4653 * wb_writeback() takes a spinlock and calls
4654 * wb_over_bg_thresh()->mem_cgroup_wb_stats(). Do not sleep.
4656 mem_cgroup_flush_stats_atomic();
4658 *pdirty = memcg_page_state(memcg, NR_FILE_DIRTY);
4659 *pwriteback = memcg_page_state(memcg, NR_WRITEBACK);
4660 *pfilepages = memcg_page_state(memcg, NR_INACTIVE_FILE) +
4661 memcg_page_state(memcg, NR_ACTIVE_FILE);
4663 *pheadroom = PAGE_COUNTER_MAX;
4664 while ((parent = parent_mem_cgroup(memcg))) {
4665 unsigned long ceiling = min(READ_ONCE(memcg->memory.max),
4666 READ_ONCE(memcg->memory.high));
4667 unsigned long used = page_counter_read(&memcg->memory);
4669 *pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
4675 * Foreign dirty flushing
4677 * There's an inherent mismatch between memcg and writeback. The former
4678 * tracks ownership per-page while the latter per-inode. This was a
4679 * deliberate design decision because honoring per-page ownership in the
4680 * writeback path is complicated, may lead to higher CPU and IO overheads
4681 * and deemed unnecessary given that write-sharing an inode across
4682 * different cgroups isn't a common use-case.
4684 * Combined with inode majority-writer ownership switching, this works well
4685 * enough in most cases but there are some pathological cases. For
4686 * example, let's say there are two cgroups A and B which keep writing to
4687 * different but confined parts of the same inode. B owns the inode and
4688 * A's memory is limited far below B's. A's dirty ratio can rise enough to
4689 * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
4690 * triggering background writeback. A will be slowed down without a way to
4691 * make writeback of the dirty pages happen.
4693 * Conditions like the above can lead to a cgroup getting repeatedly and
4694 * severely throttled after making some progress after each
4695 * dirty_expire_interval while the underlying IO device is almost
4698 * Solving this problem completely requires matching the ownership tracking
4699 * granularities between memcg and writeback in either direction. However,
4700 * the more egregious behaviors can be avoided by simply remembering the
4701 * most recent foreign dirtying events and initiating remote flushes on
4702 * them when local writeback isn't enough to keep the memory clean enough.
4704 * The following two functions implement such mechanism. When a foreign
4705 * page - a page whose memcg and writeback ownerships don't match - is
4706 * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
4707 * bdi_writeback on the page owning memcg. When balance_dirty_pages()
4708 * decides that the memcg needs to sleep due to high dirty ratio, it calls
4709 * mem_cgroup_flush_foreign() which queues writeback on the recorded
4710 * foreign bdi_writebacks which haven't expired. Both the numbers of
4711 * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
4712 * limited to MEMCG_CGWB_FRN_CNT.
4714 * The mechanism only remembers IDs and doesn't hold any object references.
4715 * As being wrong occasionally doesn't matter, updates and accesses to the
4716 * records are lockless and racy.
4718 void mem_cgroup_track_foreign_dirty_slowpath(struct folio *folio,
4719 struct bdi_writeback *wb)
4721 struct mem_cgroup *memcg = folio_memcg(folio);
4722 struct memcg_cgwb_frn *frn;
4723 u64 now = get_jiffies_64();
4724 u64 oldest_at = now;
4728 trace_track_foreign_dirty(folio, wb);
4731 * Pick the slot to use. If there is already a slot for @wb, keep
4732 * using it. If not replace the oldest one which isn't being
4735 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4736 frn = &memcg->cgwb_frn[i];
4737 if (frn->bdi_id == wb->bdi->id &&
4738 frn->memcg_id == wb->memcg_css->id)
4740 if (time_before64(frn->at, oldest_at) &&
4741 atomic_read(&frn->done.cnt) == 1) {
4743 oldest_at = frn->at;
4747 if (i < MEMCG_CGWB_FRN_CNT) {
4749 * Re-using an existing one. Update timestamp lazily to
4750 * avoid making the cacheline hot. We want them to be
4751 * reasonably up-to-date and significantly shorter than
4752 * dirty_expire_interval as that's what expires the record.
4753 * Use the shorter of 1s and dirty_expire_interval / 8.
4755 unsigned long update_intv =
4756 min_t(unsigned long, HZ,
4757 msecs_to_jiffies(dirty_expire_interval * 10) / 8);
4759 if (time_before64(frn->at, now - update_intv))
4761 } else if (oldest >= 0) {
4762 /* replace the oldest free one */
4763 frn = &memcg->cgwb_frn[oldest];
4764 frn->bdi_id = wb->bdi->id;
4765 frn->memcg_id = wb->memcg_css->id;
4770 /* issue foreign writeback flushes for recorded foreign dirtying events */
4771 void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
4773 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4774 unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
4775 u64 now = jiffies_64;
4778 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4779 struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
4782 * If the record is older than dirty_expire_interval,
4783 * writeback on it has already started. No need to kick it
4784 * off again. Also, don't start a new one if there's
4785 * already one in flight.
4787 if (time_after64(frn->at, now - intv) &&
4788 atomic_read(&frn->done.cnt) == 1) {
4790 trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
4791 cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id,
4792 WB_REASON_FOREIGN_FLUSH,
4798 #else /* CONFIG_CGROUP_WRITEBACK */
4800 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4805 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4809 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4813 #endif /* CONFIG_CGROUP_WRITEBACK */
4816 * DO NOT USE IN NEW FILES.
4818 * "cgroup.event_control" implementation.
4820 * This is way over-engineered. It tries to support fully configurable
4821 * events for each user. Such level of flexibility is completely
4822 * unnecessary especially in the light of the planned unified hierarchy.
4824 * Please deprecate this and replace with something simpler if at all
4829 * Unregister event and free resources.
4831 * Gets called from workqueue.
4833 static void memcg_event_remove(struct work_struct *work)
4835 struct mem_cgroup_event *event =
4836 container_of(work, struct mem_cgroup_event, remove);
4837 struct mem_cgroup *memcg = event->memcg;
4839 remove_wait_queue(event->wqh, &event->wait);
4841 event->unregister_event(memcg, event->eventfd);
4843 /* Notify userspace the event is going away. */
4844 eventfd_signal(event->eventfd, 1);
4846 eventfd_ctx_put(event->eventfd);
4848 css_put(&memcg->css);
4852 * Gets called on EPOLLHUP on eventfd when user closes it.
4854 * Called with wqh->lock held and interrupts disabled.
4856 static int memcg_event_wake(wait_queue_entry_t *wait, unsigned mode,
4857 int sync, void *key)
4859 struct mem_cgroup_event *event =
4860 container_of(wait, struct mem_cgroup_event, wait);
4861 struct mem_cgroup *memcg = event->memcg;
4862 __poll_t flags = key_to_poll(key);
4864 if (flags & EPOLLHUP) {
4866 * If the event has been detached at cgroup removal, we
4867 * can simply return knowing the other side will cleanup
4870 * We can't race against event freeing since the other
4871 * side will require wqh->lock via remove_wait_queue(),
4874 spin_lock(&memcg->event_list_lock);
4875 if (!list_empty(&event->list)) {
4876 list_del_init(&event->list);
4878 * We are in atomic context, but cgroup_event_remove()
4879 * may sleep, so we have to call it in workqueue.
4881 schedule_work(&event->remove);
4883 spin_unlock(&memcg->event_list_lock);
4889 static void memcg_event_ptable_queue_proc(struct file *file,
4890 wait_queue_head_t *wqh, poll_table *pt)
4892 struct mem_cgroup_event *event =
4893 container_of(pt, struct mem_cgroup_event, pt);
4896 add_wait_queue(wqh, &event->wait);
4900 * DO NOT USE IN NEW FILES.
4902 * Parse input and register new cgroup event handler.
4904 * Input must be in format '<event_fd> <control_fd> <args>'.
4905 * Interpretation of args is defined by control file implementation.
4907 static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
4908 char *buf, size_t nbytes, loff_t off)
4910 struct cgroup_subsys_state *css = of_css(of);
4911 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4912 struct mem_cgroup_event *event;
4913 struct cgroup_subsys_state *cfile_css;
4914 unsigned int efd, cfd;
4917 struct dentry *cdentry;
4922 if (IS_ENABLED(CONFIG_PREEMPT_RT))
4925 buf = strstrip(buf);
4927 efd = simple_strtoul(buf, &endp, 10);
4932 cfd = simple_strtoul(buf, &endp, 10);
4933 if ((*endp != ' ') && (*endp != '\0'))
4937 event = kzalloc(sizeof(*event), GFP_KERNEL);
4941 event->memcg = memcg;
4942 INIT_LIST_HEAD(&event->list);
4943 init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
4944 init_waitqueue_func_entry(&event->wait, memcg_event_wake);
4945 INIT_WORK(&event->remove, memcg_event_remove);
4953 event->eventfd = eventfd_ctx_fileget(efile.file);
4954 if (IS_ERR(event->eventfd)) {
4955 ret = PTR_ERR(event->eventfd);
4962 goto out_put_eventfd;
4965 /* the process need read permission on control file */
4966 /* AV: shouldn't we check that it's been opened for read instead? */
4967 ret = file_permission(cfile.file, MAY_READ);
4972 * The control file must be a regular cgroup1 file. As a regular cgroup
4973 * file can't be renamed, it's safe to access its name afterwards.
4975 cdentry = cfile.file->f_path.dentry;
4976 if (cdentry->d_sb->s_type != &cgroup_fs_type || !d_is_reg(cdentry)) {
4982 * Determine the event callbacks and set them in @event. This used
4983 * to be done via struct cftype but cgroup core no longer knows
4984 * about these events. The following is crude but the whole thing
4985 * is for compatibility anyway.
4987 * DO NOT ADD NEW FILES.
4989 name = cdentry->d_name.name;
4991 if (!strcmp(name, "memory.usage_in_bytes")) {
4992 event->register_event = mem_cgroup_usage_register_event;
4993 event->unregister_event = mem_cgroup_usage_unregister_event;
4994 } else if (!strcmp(name, "memory.oom_control")) {
4995 event->register_event = mem_cgroup_oom_register_event;
4996 event->unregister_event = mem_cgroup_oom_unregister_event;
4997 } else if (!strcmp(name, "memory.pressure_level")) {
4998 event->register_event = vmpressure_register_event;
4999 event->unregister_event = vmpressure_unregister_event;
5000 } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
5001 event->register_event = memsw_cgroup_usage_register_event;
5002 event->unregister_event = memsw_cgroup_usage_unregister_event;
5009 * Verify @cfile should belong to @css. Also, remaining events are
5010 * automatically removed on cgroup destruction but the removal is
5011 * asynchronous, so take an extra ref on @css.
5013 cfile_css = css_tryget_online_from_dir(cdentry->d_parent,
5014 &memory_cgrp_subsys);
5016 if (IS_ERR(cfile_css))
5018 if (cfile_css != css) {
5023 ret = event->register_event(memcg, event->eventfd, buf);
5027 vfs_poll(efile.file, &event->pt);
5029 spin_lock_irq(&memcg->event_list_lock);
5030 list_add(&event->list, &memcg->event_list);
5031 spin_unlock_irq(&memcg->event_list_lock);
5043 eventfd_ctx_put(event->eventfd);
5052 #if defined(CONFIG_MEMCG_KMEM) && (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG))
5053 static int mem_cgroup_slab_show(struct seq_file *m, void *p)
5057 * Please, take a look at tools/cgroup/memcg_slabinfo.py .
5063 static struct cftype mem_cgroup_legacy_files[] = {
5065 .name = "usage_in_bytes",
5066 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
5067 .read_u64 = mem_cgroup_read_u64,
5070 .name = "max_usage_in_bytes",
5071 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
5072 .write = mem_cgroup_reset,
5073 .read_u64 = mem_cgroup_read_u64,
5076 .name = "limit_in_bytes",
5077 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
5078 .write = mem_cgroup_write,
5079 .read_u64 = mem_cgroup_read_u64,
5082 .name = "soft_limit_in_bytes",
5083 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
5084 .write = mem_cgroup_write,
5085 .read_u64 = mem_cgroup_read_u64,
5089 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
5090 .write = mem_cgroup_reset,
5091 .read_u64 = mem_cgroup_read_u64,
5095 .seq_show = memcg_stat_show,
5098 .name = "force_empty",
5099 .write = mem_cgroup_force_empty_write,
5102 .name = "use_hierarchy",
5103 .write_u64 = mem_cgroup_hierarchy_write,
5104 .read_u64 = mem_cgroup_hierarchy_read,
5107 .name = "cgroup.event_control", /* XXX: for compat */
5108 .write = memcg_write_event_control,
5109 .flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE,
5112 .name = "swappiness",
5113 .read_u64 = mem_cgroup_swappiness_read,
5114 .write_u64 = mem_cgroup_swappiness_write,
5117 .name = "move_charge_at_immigrate",
5118 .read_u64 = mem_cgroup_move_charge_read,
5119 .write_u64 = mem_cgroup_move_charge_write,
5122 .name = "oom_control",
5123 .seq_show = mem_cgroup_oom_control_read,
5124 .write_u64 = mem_cgroup_oom_control_write,
5127 .name = "pressure_level",
5128 .seq_show = mem_cgroup_dummy_seq_show,
5132 .name = "numa_stat",
5133 .seq_show = memcg_numa_stat_show,
5137 .name = "kmem.limit_in_bytes",
5138 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
5139 .write = mem_cgroup_write,
5140 .read_u64 = mem_cgroup_read_u64,
5143 .name = "kmem.usage_in_bytes",
5144 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
5145 .read_u64 = mem_cgroup_read_u64,
5148 .name = "kmem.failcnt",
5149 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
5150 .write = mem_cgroup_reset,
5151 .read_u64 = mem_cgroup_read_u64,
5154 .name = "kmem.max_usage_in_bytes",
5155 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
5156 .write = mem_cgroup_reset,
5157 .read_u64 = mem_cgroup_read_u64,
5159 #if defined(CONFIG_MEMCG_KMEM) && \
5160 (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG))
5162 .name = "kmem.slabinfo",
5163 .seq_show = mem_cgroup_slab_show,
5167 .name = "kmem.tcp.limit_in_bytes",
5168 .private = MEMFILE_PRIVATE(_TCP, RES_LIMIT),
5169 .write = mem_cgroup_write,
5170 .read_u64 = mem_cgroup_read_u64,
5173 .name = "kmem.tcp.usage_in_bytes",
5174 .private = MEMFILE_PRIVATE(_TCP, RES_USAGE),
5175 .read_u64 = mem_cgroup_read_u64,
5178 .name = "kmem.tcp.failcnt",
5179 .private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT),
5180 .write = mem_cgroup_reset,
5181 .read_u64 = mem_cgroup_read_u64,
5184 .name = "kmem.tcp.max_usage_in_bytes",
5185 .private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE),
5186 .write = mem_cgroup_reset,
5187 .read_u64 = mem_cgroup_read_u64,
5189 { }, /* terminate */
5193 * Private memory cgroup IDR
5195 * Swap-out records and page cache shadow entries need to store memcg
5196 * references in constrained space, so we maintain an ID space that is
5197 * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
5198 * memory-controlled cgroups to 64k.
5200 * However, there usually are many references to the offline CSS after
5201 * the cgroup has been destroyed, such as page cache or reclaimable
5202 * slab objects, that don't need to hang on to the ID. We want to keep
5203 * those dead CSS from occupying IDs, or we might quickly exhaust the
5204 * relatively small ID space and prevent the creation of new cgroups
5205 * even when there are much fewer than 64k cgroups - possibly none.
5207 * Maintain a private 16-bit ID space for memcg, and allow the ID to
5208 * be freed and recycled when it's no longer needed, which is usually
5209 * when the CSS is offlined.
5211 * The only exception to that are records of swapped out tmpfs/shmem
5212 * pages that need to be attributed to live ancestors on swapin. But
5213 * those references are manageable from userspace.
5216 static DEFINE_IDR(mem_cgroup_idr);
5218 static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
5220 if (memcg->id.id > 0) {
5221 idr_remove(&mem_cgroup_idr, memcg->id.id);
5226 static void __maybe_unused mem_cgroup_id_get_many(struct mem_cgroup *memcg,
5229 refcount_add(n, &memcg->id.ref);
5232 static void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
5234 if (refcount_sub_and_test(n, &memcg->id.ref)) {
5235 mem_cgroup_id_remove(memcg);
5237 /* Memcg ID pins CSS */
5238 css_put(&memcg->css);
5242 static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
5244 mem_cgroup_id_put_many(memcg, 1);
5248 * mem_cgroup_from_id - look up a memcg from a memcg id
5249 * @id: the memcg id to look up
5251 * Caller must hold rcu_read_lock().
5253 struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
5255 WARN_ON_ONCE(!rcu_read_lock_held());
5256 return idr_find(&mem_cgroup_idr, id);
5259 #ifdef CONFIG_SHRINKER_DEBUG
5260 struct mem_cgroup *mem_cgroup_get_from_ino(unsigned long ino)
5262 struct cgroup *cgrp;
5263 struct cgroup_subsys_state *css;
5264 struct mem_cgroup *memcg;
5266 cgrp = cgroup_get_from_id(ino);
5268 return ERR_CAST(cgrp);
5270 css = cgroup_get_e_css(cgrp, &memory_cgrp_subsys);
5272 memcg = container_of(css, struct mem_cgroup, css);
5274 memcg = ERR_PTR(-ENOENT);
5282 static int alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5284 struct mem_cgroup_per_node *pn;
5286 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, node);
5290 pn->lruvec_stats_percpu = alloc_percpu_gfp(struct lruvec_stats_percpu,
5291 GFP_KERNEL_ACCOUNT);
5292 if (!pn->lruvec_stats_percpu) {
5297 lruvec_init(&pn->lruvec);
5300 memcg->nodeinfo[node] = pn;
5304 static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5306 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
5311 free_percpu(pn->lruvec_stats_percpu);
5315 static void __mem_cgroup_free(struct mem_cgroup *memcg)
5320 free_mem_cgroup_per_node_info(memcg, node);
5321 kfree(memcg->vmstats);
5322 free_percpu(memcg->vmstats_percpu);
5326 static void mem_cgroup_free(struct mem_cgroup *memcg)
5328 lru_gen_exit_memcg(memcg);
5329 memcg_wb_domain_exit(memcg);
5330 __mem_cgroup_free(memcg);
5333 static struct mem_cgroup *mem_cgroup_alloc(void)
5335 struct mem_cgroup *memcg;
5337 int __maybe_unused i;
5338 long error = -ENOMEM;
5340 memcg = kzalloc(struct_size(memcg, nodeinfo, nr_node_ids), GFP_KERNEL);
5342 return ERR_PTR(error);
5344 memcg->id.id = idr_alloc(&mem_cgroup_idr, NULL,
5345 1, MEM_CGROUP_ID_MAX + 1, GFP_KERNEL);
5346 if (memcg->id.id < 0) {
5347 error = memcg->id.id;
5351 memcg->vmstats = kzalloc(sizeof(struct memcg_vmstats), GFP_KERNEL);
5352 if (!memcg->vmstats)
5355 memcg->vmstats_percpu = alloc_percpu_gfp(struct memcg_vmstats_percpu,
5356 GFP_KERNEL_ACCOUNT);
5357 if (!memcg->vmstats_percpu)
5361 if (alloc_mem_cgroup_per_node_info(memcg, node))
5364 if (memcg_wb_domain_init(memcg, GFP_KERNEL))
5367 INIT_WORK(&memcg->high_work, high_work_func);
5368 INIT_LIST_HEAD(&memcg->oom_notify);
5369 mutex_init(&memcg->thresholds_lock);
5370 spin_lock_init(&memcg->move_lock);
5371 vmpressure_init(&memcg->vmpressure);
5372 INIT_LIST_HEAD(&memcg->event_list);
5373 spin_lock_init(&memcg->event_list_lock);
5374 memcg->socket_pressure = jiffies;
5375 #ifdef CONFIG_MEMCG_KMEM
5376 memcg->kmemcg_id = -1;
5377 INIT_LIST_HEAD(&memcg->objcg_list);
5379 #ifdef CONFIG_CGROUP_WRITEBACK
5380 INIT_LIST_HEAD(&memcg->cgwb_list);
5381 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5382 memcg->cgwb_frn[i].done =
5383 __WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
5385 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5386 spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
5387 INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
5388 memcg->deferred_split_queue.split_queue_len = 0;
5390 idr_replace(&mem_cgroup_idr, memcg, memcg->id.id);
5391 lru_gen_init_memcg(memcg);
5394 mem_cgroup_id_remove(memcg);
5395 __mem_cgroup_free(memcg);
5396 return ERR_PTR(error);
5399 static struct cgroup_subsys_state * __ref
5400 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
5402 struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
5403 struct mem_cgroup *memcg, *old_memcg;
5405 old_memcg = set_active_memcg(parent);
5406 memcg = mem_cgroup_alloc();
5407 set_active_memcg(old_memcg);
5409 return ERR_CAST(memcg);
5411 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5412 WRITE_ONCE(memcg->soft_limit, PAGE_COUNTER_MAX);
5413 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
5414 memcg->zswap_max = PAGE_COUNTER_MAX;
5416 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5418 WRITE_ONCE(memcg->swappiness, mem_cgroup_swappiness(parent));
5419 WRITE_ONCE(memcg->oom_kill_disable, READ_ONCE(parent->oom_kill_disable));
5421 page_counter_init(&memcg->memory, &parent->memory);
5422 page_counter_init(&memcg->swap, &parent->swap);
5423 page_counter_init(&memcg->kmem, &parent->kmem);
5424 page_counter_init(&memcg->tcpmem, &parent->tcpmem);
5426 init_memcg_events();
5427 page_counter_init(&memcg->memory, NULL);
5428 page_counter_init(&memcg->swap, NULL);
5429 page_counter_init(&memcg->kmem, NULL);
5430 page_counter_init(&memcg->tcpmem, NULL);
5432 root_mem_cgroup = memcg;
5436 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5437 static_branch_inc(&memcg_sockets_enabled_key);
5439 #if defined(CONFIG_MEMCG_KMEM)
5440 if (!cgroup_memory_nobpf)
5441 static_branch_inc(&memcg_bpf_enabled_key);
5447 static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
5449 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5451 if (memcg_online_kmem(memcg))
5455 * A memcg must be visible for expand_shrinker_info()
5456 * by the time the maps are allocated. So, we allocate maps
5457 * here, when for_each_mem_cgroup() can't skip it.
5459 if (alloc_shrinker_info(memcg))
5462 /* Online state pins memcg ID, memcg ID pins CSS */
5463 refcount_set(&memcg->id.ref, 1);
5466 if (unlikely(mem_cgroup_is_root(memcg)))
5467 queue_delayed_work(system_unbound_wq, &stats_flush_dwork,
5469 lru_gen_online_memcg(memcg);
5472 memcg_offline_kmem(memcg);
5474 mem_cgroup_id_remove(memcg);
5478 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
5480 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5481 struct mem_cgroup_event *event, *tmp;
5484 * Unregister events and notify userspace.
5485 * Notify userspace about cgroup removing only after rmdir of cgroup
5486 * directory to avoid race between userspace and kernelspace.
5488 spin_lock_irq(&memcg->event_list_lock);
5489 list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
5490 list_del_init(&event->list);
5491 schedule_work(&event->remove);
5493 spin_unlock_irq(&memcg->event_list_lock);
5495 page_counter_set_min(&memcg->memory, 0);
5496 page_counter_set_low(&memcg->memory, 0);
5498 memcg_offline_kmem(memcg);
5499 reparent_shrinker_deferred(memcg);
5500 wb_memcg_offline(memcg);
5501 lru_gen_offline_memcg(memcg);
5503 drain_all_stock(memcg);
5505 mem_cgroup_id_put(memcg);
5508 static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
5510 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5512 invalidate_reclaim_iterators(memcg);
5513 lru_gen_release_memcg(memcg);
5516 static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
5518 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5519 int __maybe_unused i;
5521 #ifdef CONFIG_CGROUP_WRITEBACK
5522 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5523 wb_wait_for_completion(&memcg->cgwb_frn[i].done);
5525 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5526 static_branch_dec(&memcg_sockets_enabled_key);
5528 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg->tcpmem_active)
5529 static_branch_dec(&memcg_sockets_enabled_key);
5531 #if defined(CONFIG_MEMCG_KMEM)
5532 if (!cgroup_memory_nobpf)
5533 static_branch_dec(&memcg_bpf_enabled_key);
5536 vmpressure_cleanup(&memcg->vmpressure);
5537 cancel_work_sync(&memcg->high_work);
5538 mem_cgroup_remove_from_trees(memcg);
5539 free_shrinker_info(memcg);
5540 mem_cgroup_free(memcg);
5544 * mem_cgroup_css_reset - reset the states of a mem_cgroup
5545 * @css: the target css
5547 * Reset the states of the mem_cgroup associated with @css. This is
5548 * invoked when the userland requests disabling on the default hierarchy
5549 * but the memcg is pinned through dependency. The memcg should stop
5550 * applying policies and should revert to the vanilla state as it may be
5551 * made visible again.
5553 * The current implementation only resets the essential configurations.
5554 * This needs to be expanded to cover all the visible parts.
5556 static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
5558 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5560 page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
5561 page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
5562 page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
5563 page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
5564 page_counter_set_min(&memcg->memory, 0);
5565 page_counter_set_low(&memcg->memory, 0);
5566 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5567 WRITE_ONCE(memcg->soft_limit, PAGE_COUNTER_MAX);
5568 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5569 memcg_wb_domain_size_changed(memcg);
5572 static void mem_cgroup_css_rstat_flush(struct cgroup_subsys_state *css, int cpu)
5574 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5575 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
5576 struct memcg_vmstats_percpu *statc;
5580 statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
5582 for (i = 0; i < MEMCG_NR_STAT; i++) {
5584 * Collect the aggregated propagation counts of groups
5585 * below us. We're in a per-cpu loop here and this is
5586 * a global counter, so the first cycle will get them.
5588 delta = memcg->vmstats->state_pending[i];
5590 memcg->vmstats->state_pending[i] = 0;
5592 /* Add CPU changes on this level since the last flush */
5593 v = READ_ONCE(statc->state[i]);
5594 if (v != statc->state_prev[i]) {
5595 delta += v - statc->state_prev[i];
5596 statc->state_prev[i] = v;
5602 /* Aggregate counts on this level and propagate upwards */
5603 memcg->vmstats->state[i] += delta;
5605 parent->vmstats->state_pending[i] += delta;
5608 for (i = 0; i < NR_MEMCG_EVENTS; i++) {
5609 delta = memcg->vmstats->events_pending[i];
5611 memcg->vmstats->events_pending[i] = 0;
5613 v = READ_ONCE(statc->events[i]);
5614 if (v != statc->events_prev[i]) {
5615 delta += v - statc->events_prev[i];
5616 statc->events_prev[i] = v;
5622 memcg->vmstats->events[i] += delta;
5624 parent->vmstats->events_pending[i] += delta;
5627 for_each_node_state(nid, N_MEMORY) {
5628 struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
5629 struct mem_cgroup_per_node *ppn = NULL;
5630 struct lruvec_stats_percpu *lstatc;
5633 ppn = parent->nodeinfo[nid];
5635 lstatc = per_cpu_ptr(pn->lruvec_stats_percpu, cpu);
5637 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++) {
5638 delta = pn->lruvec_stats.state_pending[i];
5640 pn->lruvec_stats.state_pending[i] = 0;
5642 v = READ_ONCE(lstatc->state[i]);
5643 if (v != lstatc->state_prev[i]) {
5644 delta += v - lstatc->state_prev[i];
5645 lstatc->state_prev[i] = v;
5651 pn->lruvec_stats.state[i] += delta;
5653 ppn->lruvec_stats.state_pending[i] += delta;
5659 /* Handlers for move charge at task migration. */
5660 static int mem_cgroup_do_precharge(unsigned long count)
5664 /* Try a single bulk charge without reclaim first, kswapd may wake */
5665 ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count);
5667 mc.precharge += count;
5671 /* Try charges one by one with reclaim, but do not retry */
5673 ret = try_charge(mc.to, GFP_KERNEL | __GFP_NORETRY, 1);
5687 enum mc_target_type {
5694 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5695 unsigned long addr, pte_t ptent)
5697 struct page *page = vm_normal_page(vma, addr, ptent);
5699 if (!page || !page_mapped(page))
5701 if (PageAnon(page)) {
5702 if (!(mc.flags & MOVE_ANON))
5705 if (!(mc.flags & MOVE_FILE))
5708 if (!get_page_unless_zero(page))
5714 #if defined(CONFIG_SWAP) || defined(CONFIG_DEVICE_PRIVATE)
5715 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5716 pte_t ptent, swp_entry_t *entry)
5718 struct page *page = NULL;
5719 swp_entry_t ent = pte_to_swp_entry(ptent);
5721 if (!(mc.flags & MOVE_ANON))
5725 * Handle device private pages that are not accessible by the CPU, but
5726 * stored as special swap entries in the page table.
5728 if (is_device_private_entry(ent)) {
5729 page = pfn_swap_entry_to_page(ent);
5730 if (!get_page_unless_zero(page))
5735 if (non_swap_entry(ent))
5739 * Because swap_cache_get_folio() updates some statistics counter,
5740 * we call find_get_page() with swapper_space directly.
5742 page = find_get_page(swap_address_space(ent), swp_offset(ent));
5743 entry->val = ent.val;
5748 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5749 pte_t ptent, swp_entry_t *entry)
5755 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5756 unsigned long addr, pte_t ptent)
5758 unsigned long index;
5759 struct folio *folio;
5761 if (!vma->vm_file) /* anonymous vma */
5763 if (!(mc.flags & MOVE_FILE))
5766 /* folio is moved even if it's not RSS of this task(page-faulted). */
5767 /* shmem/tmpfs may report page out on swap: account for that too. */
5768 index = linear_page_index(vma, addr);
5769 folio = filemap_get_incore_folio(vma->vm_file->f_mapping, index);
5772 return folio_file_page(folio, index);
5776 * mem_cgroup_move_account - move account of the page
5778 * @compound: charge the page as compound or small page
5779 * @from: mem_cgroup which the page is moved from.
5780 * @to: mem_cgroup which the page is moved to. @from != @to.
5782 * The page must be locked and not on the LRU.
5784 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
5787 static int mem_cgroup_move_account(struct page *page,
5789 struct mem_cgroup *from,
5790 struct mem_cgroup *to)
5792 struct folio *folio = page_folio(page);
5793 struct lruvec *from_vec, *to_vec;
5794 struct pglist_data *pgdat;
5795 unsigned int nr_pages = compound ? folio_nr_pages(folio) : 1;
5798 VM_BUG_ON(from == to);
5799 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
5800 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
5801 VM_BUG_ON(compound && !folio_test_large(folio));
5804 if (folio_memcg(folio) != from)
5807 pgdat = folio_pgdat(folio);
5808 from_vec = mem_cgroup_lruvec(from, pgdat);
5809 to_vec = mem_cgroup_lruvec(to, pgdat);
5811 folio_memcg_lock(folio);
5813 if (folio_test_anon(folio)) {
5814 if (folio_mapped(folio)) {
5815 __mod_lruvec_state(from_vec, NR_ANON_MAPPED, -nr_pages);
5816 __mod_lruvec_state(to_vec, NR_ANON_MAPPED, nr_pages);
5817 if (folio_test_transhuge(folio)) {
5818 __mod_lruvec_state(from_vec, NR_ANON_THPS,
5820 __mod_lruvec_state(to_vec, NR_ANON_THPS,
5825 __mod_lruvec_state(from_vec, NR_FILE_PAGES, -nr_pages);
5826 __mod_lruvec_state(to_vec, NR_FILE_PAGES, nr_pages);
5828 if (folio_test_swapbacked(folio)) {
5829 __mod_lruvec_state(from_vec, NR_SHMEM, -nr_pages);
5830 __mod_lruvec_state(to_vec, NR_SHMEM, nr_pages);
5833 if (folio_mapped(folio)) {
5834 __mod_lruvec_state(from_vec, NR_FILE_MAPPED, -nr_pages);
5835 __mod_lruvec_state(to_vec, NR_FILE_MAPPED, nr_pages);
5838 if (folio_test_dirty(folio)) {
5839 struct address_space *mapping = folio_mapping(folio);
5841 if (mapping_can_writeback(mapping)) {
5842 __mod_lruvec_state(from_vec, NR_FILE_DIRTY,
5844 __mod_lruvec_state(to_vec, NR_FILE_DIRTY,
5851 if (folio_test_swapcache(folio)) {
5852 __mod_lruvec_state(from_vec, NR_SWAPCACHE, -nr_pages);
5853 __mod_lruvec_state(to_vec, NR_SWAPCACHE, nr_pages);
5856 if (folio_test_writeback(folio)) {
5857 __mod_lruvec_state(from_vec, NR_WRITEBACK, -nr_pages);
5858 __mod_lruvec_state(to_vec, NR_WRITEBACK, nr_pages);
5862 * All state has been migrated, let's switch to the new memcg.
5864 * It is safe to change page's memcg here because the page
5865 * is referenced, charged, isolated, and locked: we can't race
5866 * with (un)charging, migration, LRU putback, or anything else
5867 * that would rely on a stable page's memory cgroup.
5869 * Note that lock_page_memcg is a memcg lock, not a page lock,
5870 * to save space. As soon as we switch page's memory cgroup to a
5871 * new memcg that isn't locked, the above state can change
5872 * concurrently again. Make sure we're truly done with it.
5877 css_put(&from->css);
5879 folio->memcg_data = (unsigned long)to;
5881 __folio_memcg_unlock(from);
5884 nid = folio_nid(folio);
5886 local_irq_disable();
5887 mem_cgroup_charge_statistics(to, nr_pages);
5888 memcg_check_events(to, nid);
5889 mem_cgroup_charge_statistics(from, -nr_pages);
5890 memcg_check_events(from, nid);
5897 * get_mctgt_type - get target type of moving charge
5898 * @vma: the vma the pte to be checked belongs
5899 * @addr: the address corresponding to the pte to be checked
5900 * @ptent: the pte to be checked
5901 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5904 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5905 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5906 * move charge. if @target is not NULL, the page is stored in target->page
5907 * with extra refcnt got(Callers should handle it).
5908 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5909 * target for charge migration. if @target is not NULL, the entry is stored
5911 * 3(MC_TARGET_DEVICE): like MC_TARGET_PAGE but page is device memory and
5912 * thus not on the lru.
5913 * For now we such page is charge like a regular page would be as for all
5914 * intent and purposes it is just special memory taking the place of a
5917 * See Documentations/vm/hmm.txt and include/linux/hmm.h
5919 * Called with pte lock held.
5922 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
5923 unsigned long addr, pte_t ptent, union mc_target *target)
5925 struct page *page = NULL;
5926 enum mc_target_type ret = MC_TARGET_NONE;
5927 swp_entry_t ent = { .val = 0 };
5929 if (pte_present(ptent))
5930 page = mc_handle_present_pte(vma, addr, ptent);
5931 else if (pte_none_mostly(ptent))
5933 * PTE markers should be treated as a none pte here, separated
5934 * from other swap handling below.
5936 page = mc_handle_file_pte(vma, addr, ptent);
5937 else if (is_swap_pte(ptent))
5938 page = mc_handle_swap_pte(vma, ptent, &ent);
5940 if (target && page) {
5941 if (!trylock_page(page)) {
5946 * page_mapped() must be stable during the move. This
5947 * pte is locked, so if it's present, the page cannot
5948 * become unmapped. If it isn't, we have only partial
5949 * control over the mapped state: the page lock will
5950 * prevent new faults against pagecache and swapcache,
5951 * so an unmapped page cannot become mapped. However,
5952 * if the page is already mapped elsewhere, it can
5953 * unmap, and there is nothing we can do about it.
5954 * Alas, skip moving the page in this case.
5956 if (!pte_present(ptent) && page_mapped(page)) {
5963 if (!page && !ent.val)
5967 * Do only loose check w/o serialization.
5968 * mem_cgroup_move_account() checks the page is valid or
5969 * not under LRU exclusion.
5971 if (page_memcg(page) == mc.from) {
5972 ret = MC_TARGET_PAGE;
5973 if (is_device_private_page(page) ||
5974 is_device_coherent_page(page))
5975 ret = MC_TARGET_DEVICE;
5977 target->page = page;
5979 if (!ret || !target) {
5986 * There is a swap entry and a page doesn't exist or isn't charged.
5987 * But we cannot move a tail-page in a THP.
5989 if (ent.val && !ret && (!page || !PageTransCompound(page)) &&
5990 mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
5991 ret = MC_TARGET_SWAP;
5998 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
6000 * We don't consider PMD mapped swapping or file mapped pages because THP does
6001 * not support them for now.
6002 * Caller should make sure that pmd_trans_huge(pmd) is true.
6004 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
6005 unsigned long addr, pmd_t pmd, union mc_target *target)
6007 struct page *page = NULL;
6008 enum mc_target_type ret = MC_TARGET_NONE;
6010 if (unlikely(is_swap_pmd(pmd))) {
6011 VM_BUG_ON(thp_migration_supported() &&
6012 !is_pmd_migration_entry(pmd));
6015 page = pmd_page(pmd);
6016 VM_BUG_ON_PAGE(!page || !PageHead(page), page);
6017 if (!(mc.flags & MOVE_ANON))
6019 if (page_memcg(page) == mc.from) {
6020 ret = MC_TARGET_PAGE;
6023 if (!trylock_page(page)) {
6025 return MC_TARGET_NONE;
6027 target->page = page;
6033 static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
6034 unsigned long addr, pmd_t pmd, union mc_target *target)
6036 return MC_TARGET_NONE;
6040 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
6041 unsigned long addr, unsigned long end,
6042 struct mm_walk *walk)
6044 struct vm_area_struct *vma = walk->vma;
6048 ptl = pmd_trans_huge_lock(pmd, vma);
6051 * Note their can not be MC_TARGET_DEVICE for now as we do not
6052 * support transparent huge page with MEMORY_DEVICE_PRIVATE but
6053 * this might change.
6055 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
6056 mc.precharge += HPAGE_PMD_NR;
6061 if (pmd_trans_unstable(pmd))
6063 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6064 for (; addr != end; pte++, addr += PAGE_SIZE)
6065 if (get_mctgt_type(vma, addr, *pte, NULL))
6066 mc.precharge++; /* increment precharge temporarily */
6067 pte_unmap_unlock(pte - 1, ptl);
6073 static const struct mm_walk_ops precharge_walk_ops = {
6074 .pmd_entry = mem_cgroup_count_precharge_pte_range,
6075 .walk_lock = PGWALK_RDLOCK,
6078 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
6080 unsigned long precharge;
6083 walk_page_range(mm, 0, ULONG_MAX, &precharge_walk_ops, NULL);
6084 mmap_read_unlock(mm);
6086 precharge = mc.precharge;
6092 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
6094 unsigned long precharge = mem_cgroup_count_precharge(mm);
6096 VM_BUG_ON(mc.moving_task);
6097 mc.moving_task = current;
6098 return mem_cgroup_do_precharge(precharge);
6101 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
6102 static void __mem_cgroup_clear_mc(void)
6104 struct mem_cgroup *from = mc.from;
6105 struct mem_cgroup *to = mc.to;
6107 /* we must uncharge all the leftover precharges from mc.to */
6109 cancel_charge(mc.to, mc.precharge);
6113 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
6114 * we must uncharge here.
6116 if (mc.moved_charge) {
6117 cancel_charge(mc.from, mc.moved_charge);
6118 mc.moved_charge = 0;
6120 /* we must fixup refcnts and charges */
6121 if (mc.moved_swap) {
6122 /* uncharge swap account from the old cgroup */
6123 if (!mem_cgroup_is_root(mc.from))
6124 page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
6126 mem_cgroup_id_put_many(mc.from, mc.moved_swap);
6129 * we charged both to->memory and to->memsw, so we
6130 * should uncharge to->memory.
6132 if (!mem_cgroup_is_root(mc.to))
6133 page_counter_uncharge(&mc.to->memory, mc.moved_swap);
6137 memcg_oom_recover(from);
6138 memcg_oom_recover(to);
6139 wake_up_all(&mc.waitq);
6142 static void mem_cgroup_clear_mc(void)
6144 struct mm_struct *mm = mc.mm;
6147 * we must clear moving_task before waking up waiters at the end of
6150 mc.moving_task = NULL;
6151 __mem_cgroup_clear_mc();
6152 spin_lock(&mc.lock);
6156 spin_unlock(&mc.lock);
6161 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
6163 struct cgroup_subsys_state *css;
6164 struct mem_cgroup *memcg = NULL; /* unneeded init to make gcc happy */
6165 struct mem_cgroup *from;
6166 struct task_struct *leader, *p;
6167 struct mm_struct *mm;
6168 unsigned long move_flags;
6171 /* charge immigration isn't supported on the default hierarchy */
6172 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
6176 * Multi-process migrations only happen on the default hierarchy
6177 * where charge immigration is not used. Perform charge
6178 * immigration if @tset contains a leader and whine if there are
6182 cgroup_taskset_for_each_leader(leader, css, tset) {
6185 memcg = mem_cgroup_from_css(css);
6191 * We are now committed to this value whatever it is. Changes in this
6192 * tunable will only affect upcoming migrations, not the current one.
6193 * So we need to save it, and keep it going.
6195 move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
6199 from = mem_cgroup_from_task(p);
6201 VM_BUG_ON(from == memcg);
6203 mm = get_task_mm(p);
6206 /* We move charges only when we move a owner of the mm */
6207 if (mm->owner == p) {
6210 VM_BUG_ON(mc.precharge);
6211 VM_BUG_ON(mc.moved_charge);
6212 VM_BUG_ON(mc.moved_swap);
6214 spin_lock(&mc.lock);
6218 mc.flags = move_flags;
6219 spin_unlock(&mc.lock);
6220 /* We set mc.moving_task later */
6222 ret = mem_cgroup_precharge_mc(mm);
6224 mem_cgroup_clear_mc();
6231 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6234 mem_cgroup_clear_mc();
6237 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
6238 unsigned long addr, unsigned long end,
6239 struct mm_walk *walk)
6242 struct vm_area_struct *vma = walk->vma;
6245 enum mc_target_type target_type;
6246 union mc_target target;
6249 ptl = pmd_trans_huge_lock(pmd, vma);
6251 if (mc.precharge < HPAGE_PMD_NR) {
6255 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
6256 if (target_type == MC_TARGET_PAGE) {
6258 if (isolate_lru_page(page)) {
6259 if (!mem_cgroup_move_account(page, true,
6261 mc.precharge -= HPAGE_PMD_NR;
6262 mc.moved_charge += HPAGE_PMD_NR;
6264 putback_lru_page(page);
6268 } else if (target_type == MC_TARGET_DEVICE) {
6270 if (!mem_cgroup_move_account(page, true,
6272 mc.precharge -= HPAGE_PMD_NR;
6273 mc.moved_charge += HPAGE_PMD_NR;
6282 if (pmd_trans_unstable(pmd))
6285 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6286 for (; addr != end; addr += PAGE_SIZE) {
6287 pte_t ptent = *(pte++);
6288 bool device = false;
6294 switch (get_mctgt_type(vma, addr, ptent, &target)) {
6295 case MC_TARGET_DEVICE:
6298 case MC_TARGET_PAGE:
6301 * We can have a part of the split pmd here. Moving it
6302 * can be done but it would be too convoluted so simply
6303 * ignore such a partial THP and keep it in original
6304 * memcg. There should be somebody mapping the head.
6306 if (PageTransCompound(page))
6308 if (!device && !isolate_lru_page(page))
6310 if (!mem_cgroup_move_account(page, false,
6313 /* we uncharge from mc.from later. */
6317 putback_lru_page(page);
6318 put: /* get_mctgt_type() gets & locks the page */
6322 case MC_TARGET_SWAP:
6324 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
6326 mem_cgroup_id_get_many(mc.to, 1);
6327 /* we fixup other refcnts and charges later. */
6335 pte_unmap_unlock(pte - 1, ptl);
6340 * We have consumed all precharges we got in can_attach().
6341 * We try charge one by one, but don't do any additional
6342 * charges to mc.to if we have failed in charge once in attach()
6345 ret = mem_cgroup_do_precharge(1);
6353 static const struct mm_walk_ops charge_walk_ops = {
6354 .pmd_entry = mem_cgroup_move_charge_pte_range,
6355 .walk_lock = PGWALK_RDLOCK,
6358 static void mem_cgroup_move_charge(void)
6360 lru_add_drain_all();
6362 * Signal lock_page_memcg() to take the memcg's move_lock
6363 * while we're moving its pages to another memcg. Then wait
6364 * for already started RCU-only updates to finish.
6366 atomic_inc(&mc.from->moving_account);
6369 if (unlikely(!mmap_read_trylock(mc.mm))) {
6371 * Someone who are holding the mmap_lock might be waiting in
6372 * waitq. So we cancel all extra charges, wake up all waiters,
6373 * and retry. Because we cancel precharges, we might not be able
6374 * to move enough charges, but moving charge is a best-effort
6375 * feature anyway, so it wouldn't be a big problem.
6377 __mem_cgroup_clear_mc();
6382 * When we have consumed all precharges and failed in doing
6383 * additional charge, the page walk just aborts.
6385 walk_page_range(mc.mm, 0, ULONG_MAX, &charge_walk_ops, NULL);
6386 mmap_read_unlock(mc.mm);
6387 atomic_dec(&mc.from->moving_account);
6390 static void mem_cgroup_move_task(void)
6393 mem_cgroup_move_charge();
6394 mem_cgroup_clear_mc();
6397 #else /* !CONFIG_MMU */
6398 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
6402 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6405 static void mem_cgroup_move_task(void)
6410 #ifdef CONFIG_LRU_GEN
6411 static void mem_cgroup_attach(struct cgroup_taskset *tset)
6413 struct task_struct *task;
6414 struct cgroup_subsys_state *css;
6416 /* find the first leader if there is any */
6417 cgroup_taskset_for_each_leader(task, css, tset)
6424 if (task->mm && READ_ONCE(task->mm->owner) == task)
6425 lru_gen_migrate_mm(task->mm);
6429 static void mem_cgroup_attach(struct cgroup_taskset *tset)
6432 #endif /* CONFIG_LRU_GEN */
6434 static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
6436 if (value == PAGE_COUNTER_MAX)
6437 seq_puts(m, "max\n");
6439 seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
6444 static u64 memory_current_read(struct cgroup_subsys_state *css,
6447 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6449 return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
6452 static u64 memory_peak_read(struct cgroup_subsys_state *css,
6455 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6457 return (u64)memcg->memory.watermark * PAGE_SIZE;
6460 static int memory_min_show(struct seq_file *m, void *v)
6462 return seq_puts_memcg_tunable(m,
6463 READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
6466 static ssize_t memory_min_write(struct kernfs_open_file *of,
6467 char *buf, size_t nbytes, loff_t off)
6469 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6473 buf = strstrip(buf);
6474 err = page_counter_memparse(buf, "max", &min);
6478 page_counter_set_min(&memcg->memory, min);
6483 static int memory_low_show(struct seq_file *m, void *v)
6485 return seq_puts_memcg_tunable(m,
6486 READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
6489 static ssize_t memory_low_write(struct kernfs_open_file *of,
6490 char *buf, size_t nbytes, loff_t off)
6492 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6496 buf = strstrip(buf);
6497 err = page_counter_memparse(buf, "max", &low);
6501 page_counter_set_low(&memcg->memory, low);
6506 static int memory_high_show(struct seq_file *m, void *v)
6508 return seq_puts_memcg_tunable(m,
6509 READ_ONCE(mem_cgroup_from_seq(m)->memory.high));
6512 static ssize_t memory_high_write(struct kernfs_open_file *of,
6513 char *buf, size_t nbytes, loff_t off)
6515 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6516 unsigned int nr_retries = MAX_RECLAIM_RETRIES;
6517 bool drained = false;
6521 buf = strstrip(buf);
6522 err = page_counter_memparse(buf, "max", &high);
6526 page_counter_set_high(&memcg->memory, high);
6529 unsigned long nr_pages = page_counter_read(&memcg->memory);
6530 unsigned long reclaimed;
6532 if (nr_pages <= high)
6535 if (signal_pending(current))
6539 drain_all_stock(memcg);
6544 reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
6545 GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP);
6547 if (!reclaimed && !nr_retries--)
6551 memcg_wb_domain_size_changed(memcg);
6555 static int memory_max_show(struct seq_file *m, void *v)
6557 return seq_puts_memcg_tunable(m,
6558 READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
6561 static ssize_t memory_max_write(struct kernfs_open_file *of,
6562 char *buf, size_t nbytes, loff_t off)
6564 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6565 unsigned int nr_reclaims = MAX_RECLAIM_RETRIES;
6566 bool drained = false;
6570 buf = strstrip(buf);
6571 err = page_counter_memparse(buf, "max", &max);
6575 xchg(&memcg->memory.max, max);
6578 unsigned long nr_pages = page_counter_read(&memcg->memory);
6580 if (nr_pages <= max)
6583 if (signal_pending(current))
6587 drain_all_stock(memcg);
6593 if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
6594 GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP))
6599 memcg_memory_event(memcg, MEMCG_OOM);
6600 if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
6604 memcg_wb_domain_size_changed(memcg);
6608 static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
6610 seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
6611 seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
6612 seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
6613 seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
6614 seq_printf(m, "oom_kill %lu\n",
6615 atomic_long_read(&events[MEMCG_OOM_KILL]));
6616 seq_printf(m, "oom_group_kill %lu\n",
6617 atomic_long_read(&events[MEMCG_OOM_GROUP_KILL]));
6620 static int memory_events_show(struct seq_file *m, void *v)
6622 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6624 __memory_events_show(m, memcg->memory_events);
6628 static int memory_events_local_show(struct seq_file *m, void *v)
6630 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6632 __memory_events_show(m, memcg->memory_events_local);
6636 static int memory_stat_show(struct seq_file *m, void *v)
6638 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6639 char *buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
6643 memory_stat_format(memcg, buf, PAGE_SIZE);
6650 static inline unsigned long lruvec_page_state_output(struct lruvec *lruvec,
6653 return lruvec_page_state(lruvec, item) * memcg_page_state_unit(item);
6656 static int memory_numa_stat_show(struct seq_file *m, void *v)
6659 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6661 mem_cgroup_flush_stats();
6663 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
6666 if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS)
6669 seq_printf(m, "%s", memory_stats[i].name);
6670 for_each_node_state(nid, N_MEMORY) {
6672 struct lruvec *lruvec;
6674 lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
6675 size = lruvec_page_state_output(lruvec,
6676 memory_stats[i].idx);
6677 seq_printf(m, " N%d=%llu", nid, size);
6686 static int memory_oom_group_show(struct seq_file *m, void *v)
6688 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6690 seq_printf(m, "%d\n", READ_ONCE(memcg->oom_group));
6695 static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
6696 char *buf, size_t nbytes, loff_t off)
6698 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6701 buf = strstrip(buf);
6705 ret = kstrtoint(buf, 0, &oom_group);
6709 if (oom_group != 0 && oom_group != 1)
6712 WRITE_ONCE(memcg->oom_group, oom_group);
6717 static ssize_t memory_reclaim(struct kernfs_open_file *of, char *buf,
6718 size_t nbytes, loff_t off)
6720 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6721 unsigned int nr_retries = MAX_RECLAIM_RETRIES;
6722 unsigned long nr_to_reclaim, nr_reclaimed = 0;
6723 unsigned int reclaim_options;
6726 buf = strstrip(buf);
6727 err = page_counter_memparse(buf, "", &nr_to_reclaim);
6731 reclaim_options = MEMCG_RECLAIM_MAY_SWAP | MEMCG_RECLAIM_PROACTIVE;
6732 while (nr_reclaimed < nr_to_reclaim) {
6733 unsigned long reclaimed;
6735 if (signal_pending(current))
6739 * This is the final attempt, drain percpu lru caches in the
6740 * hope of introducing more evictable pages for
6741 * try_to_free_mem_cgroup_pages().
6744 lru_add_drain_all();
6746 reclaimed = try_to_free_mem_cgroup_pages(memcg,
6747 nr_to_reclaim - nr_reclaimed,
6748 GFP_KERNEL, reclaim_options);
6750 if (!reclaimed && !nr_retries--)
6753 nr_reclaimed += reclaimed;
6759 static struct cftype memory_files[] = {
6762 .flags = CFTYPE_NOT_ON_ROOT,
6763 .read_u64 = memory_current_read,
6767 .flags = CFTYPE_NOT_ON_ROOT,
6768 .read_u64 = memory_peak_read,
6772 .flags = CFTYPE_NOT_ON_ROOT,
6773 .seq_show = memory_min_show,
6774 .write = memory_min_write,
6778 .flags = CFTYPE_NOT_ON_ROOT,
6779 .seq_show = memory_low_show,
6780 .write = memory_low_write,
6784 .flags = CFTYPE_NOT_ON_ROOT,
6785 .seq_show = memory_high_show,
6786 .write = memory_high_write,
6790 .flags = CFTYPE_NOT_ON_ROOT,
6791 .seq_show = memory_max_show,
6792 .write = memory_max_write,
6796 .flags = CFTYPE_NOT_ON_ROOT,
6797 .file_offset = offsetof(struct mem_cgroup, events_file),
6798 .seq_show = memory_events_show,
6801 .name = "events.local",
6802 .flags = CFTYPE_NOT_ON_ROOT,
6803 .file_offset = offsetof(struct mem_cgroup, events_local_file),
6804 .seq_show = memory_events_local_show,
6808 .seq_show = memory_stat_show,
6812 .name = "numa_stat",
6813 .seq_show = memory_numa_stat_show,
6817 .name = "oom.group",
6818 .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
6819 .seq_show = memory_oom_group_show,
6820 .write = memory_oom_group_write,
6824 .flags = CFTYPE_NS_DELEGATABLE,
6825 .write = memory_reclaim,
6830 struct cgroup_subsys memory_cgrp_subsys = {
6831 .css_alloc = mem_cgroup_css_alloc,
6832 .css_online = mem_cgroup_css_online,
6833 .css_offline = mem_cgroup_css_offline,
6834 .css_released = mem_cgroup_css_released,
6835 .css_free = mem_cgroup_css_free,
6836 .css_reset = mem_cgroup_css_reset,
6837 .css_rstat_flush = mem_cgroup_css_rstat_flush,
6838 .can_attach = mem_cgroup_can_attach,
6839 .attach = mem_cgroup_attach,
6840 .cancel_attach = mem_cgroup_cancel_attach,
6841 .post_attach = mem_cgroup_move_task,
6842 .dfl_cftypes = memory_files,
6843 .legacy_cftypes = mem_cgroup_legacy_files,
6848 * This function calculates an individual cgroup's effective
6849 * protection which is derived from its own memory.min/low, its
6850 * parent's and siblings' settings, as well as the actual memory
6851 * distribution in the tree.
6853 * The following rules apply to the effective protection values:
6855 * 1. At the first level of reclaim, effective protection is equal to
6856 * the declared protection in memory.min and memory.low.
6858 * 2. To enable safe delegation of the protection configuration, at
6859 * subsequent levels the effective protection is capped to the
6860 * parent's effective protection.
6862 * 3. To make complex and dynamic subtrees easier to configure, the
6863 * user is allowed to overcommit the declared protection at a given
6864 * level. If that is the case, the parent's effective protection is
6865 * distributed to the children in proportion to how much protection
6866 * they have declared and how much of it they are utilizing.
6868 * This makes distribution proportional, but also work-conserving:
6869 * if one cgroup claims much more protection than it uses memory,
6870 * the unused remainder is available to its siblings.
6872 * 4. Conversely, when the declared protection is undercommitted at a
6873 * given level, the distribution of the larger parental protection
6874 * budget is NOT proportional. A cgroup's protection from a sibling
6875 * is capped to its own memory.min/low setting.
6877 * 5. However, to allow protecting recursive subtrees from each other
6878 * without having to declare each individual cgroup's fixed share
6879 * of the ancestor's claim to protection, any unutilized -
6880 * "floating" - protection from up the tree is distributed in
6881 * proportion to each cgroup's *usage*. This makes the protection
6882 * neutral wrt sibling cgroups and lets them compete freely over
6883 * the shared parental protection budget, but it protects the
6884 * subtree as a whole from neighboring subtrees.
6886 * Note that 4. and 5. are not in conflict: 4. is about protecting
6887 * against immediate siblings whereas 5. is about protecting against
6888 * neighboring subtrees.
6890 static unsigned long effective_protection(unsigned long usage,
6891 unsigned long parent_usage,
6892 unsigned long setting,
6893 unsigned long parent_effective,
6894 unsigned long siblings_protected)
6896 unsigned long protected;
6899 protected = min(usage, setting);
6901 * If all cgroups at this level combined claim and use more
6902 * protection then what the parent affords them, distribute
6903 * shares in proportion to utilization.
6905 * We are using actual utilization rather than the statically
6906 * claimed protection in order to be work-conserving: claimed
6907 * but unused protection is available to siblings that would
6908 * otherwise get a smaller chunk than what they claimed.
6910 if (siblings_protected > parent_effective)
6911 return protected * parent_effective / siblings_protected;
6914 * Ok, utilized protection of all children is within what the
6915 * parent affords them, so we know whatever this child claims
6916 * and utilizes is effectively protected.
6918 * If there is unprotected usage beyond this value, reclaim
6919 * will apply pressure in proportion to that amount.
6921 * If there is unutilized protection, the cgroup will be fully
6922 * shielded from reclaim, but we do return a smaller value for
6923 * protection than what the group could enjoy in theory. This
6924 * is okay. With the overcommit distribution above, effective
6925 * protection is always dependent on how memory is actually
6926 * consumed among the siblings anyway.
6931 * If the children aren't claiming (all of) the protection
6932 * afforded to them by the parent, distribute the remainder in
6933 * proportion to the (unprotected) memory of each cgroup. That
6934 * way, cgroups that aren't explicitly prioritized wrt each
6935 * other compete freely over the allowance, but they are
6936 * collectively protected from neighboring trees.
6938 * We're using unprotected memory for the weight so that if
6939 * some cgroups DO claim explicit protection, we don't protect
6940 * the same bytes twice.
6942 * Check both usage and parent_usage against the respective
6943 * protected values. One should imply the other, but they
6944 * aren't read atomically - make sure the division is sane.
6946 if (!(cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT))
6948 if (parent_effective > siblings_protected &&
6949 parent_usage > siblings_protected &&
6950 usage > protected) {
6951 unsigned long unclaimed;
6953 unclaimed = parent_effective - siblings_protected;
6954 unclaimed *= usage - protected;
6955 unclaimed /= parent_usage - siblings_protected;
6964 * mem_cgroup_calculate_protection - check if memory consumption is in the normal range
6965 * @root: the top ancestor of the sub-tree being checked
6966 * @memcg: the memory cgroup to check
6968 * WARNING: This function is not stateless! It can only be used as part
6969 * of a top-down tree iteration, not for isolated queries.
6971 void mem_cgroup_calculate_protection(struct mem_cgroup *root,
6972 struct mem_cgroup *memcg)
6974 unsigned long usage, parent_usage;
6975 struct mem_cgroup *parent;
6977 if (mem_cgroup_disabled())
6981 root = root_mem_cgroup;
6984 * Effective values of the reclaim targets are ignored so they
6985 * can be stale. Have a look at mem_cgroup_protection for more
6987 * TODO: calculation should be more robust so that we do not need
6988 * that special casing.
6993 usage = page_counter_read(&memcg->memory);
6997 parent = parent_mem_cgroup(memcg);
6999 if (parent == root) {
7000 memcg->memory.emin = READ_ONCE(memcg->memory.min);
7001 memcg->memory.elow = READ_ONCE(memcg->memory.low);
7005 parent_usage = page_counter_read(&parent->memory);
7007 WRITE_ONCE(memcg->memory.emin, effective_protection(usage, parent_usage,
7008 READ_ONCE(memcg->memory.min),
7009 READ_ONCE(parent->memory.emin),
7010 atomic_long_read(&parent->memory.children_min_usage)));
7012 WRITE_ONCE(memcg->memory.elow, effective_protection(usage, parent_usage,
7013 READ_ONCE(memcg->memory.low),
7014 READ_ONCE(parent->memory.elow),
7015 atomic_long_read(&parent->memory.children_low_usage)));
7018 static int charge_memcg(struct folio *folio, struct mem_cgroup *memcg,
7021 long nr_pages = folio_nr_pages(folio);
7024 ret = try_charge(memcg, gfp, nr_pages);
7028 css_get(&memcg->css);
7029 commit_charge(folio, memcg);
7031 local_irq_disable();
7032 mem_cgroup_charge_statistics(memcg, nr_pages);
7033 memcg_check_events(memcg, folio_nid(folio));
7039 int __mem_cgroup_charge(struct folio *folio, struct mm_struct *mm, gfp_t gfp)
7041 struct mem_cgroup *memcg;
7044 memcg = get_mem_cgroup_from_mm(mm);
7045 ret = charge_memcg(folio, memcg, gfp);
7046 css_put(&memcg->css);
7052 * mem_cgroup_swapin_charge_folio - Charge a newly allocated folio for swapin.
7053 * @folio: folio to charge.
7054 * @mm: mm context of the victim
7055 * @gfp: reclaim mode
7056 * @entry: swap entry for which the folio is allocated
7058 * This function charges a folio allocated for swapin. Please call this before
7059 * adding the folio to the swapcache.
7061 * Returns 0 on success. Otherwise, an error code is returned.
7063 int mem_cgroup_swapin_charge_folio(struct folio *folio, struct mm_struct *mm,
7064 gfp_t gfp, swp_entry_t entry)
7066 struct mem_cgroup *memcg;
7070 if (mem_cgroup_disabled())
7073 id = lookup_swap_cgroup_id(entry);
7075 memcg = mem_cgroup_from_id(id);
7076 if (!memcg || !css_tryget_online(&memcg->css))
7077 memcg = get_mem_cgroup_from_mm(mm);
7080 ret = charge_memcg(folio, memcg, gfp);
7082 css_put(&memcg->css);
7087 * mem_cgroup_swapin_uncharge_swap - uncharge swap slot
7088 * @entry: swap entry for which the page is charged
7090 * Call this function after successfully adding the charged page to swapcache.
7092 * Note: This function assumes the page for which swap slot is being uncharged
7095 void mem_cgroup_swapin_uncharge_swap(swp_entry_t entry)
7098 * Cgroup1's unified memory+swap counter has been charged with the
7099 * new swapcache page, finish the transfer by uncharging the swap
7100 * slot. The swap slot would also get uncharged when it dies, but
7101 * it can stick around indefinitely and we'd count the page twice
7104 * Cgroup2 has separate resource counters for memory and swap,
7105 * so this is a non-issue here. Memory and swap charge lifetimes
7106 * correspond 1:1 to page and swap slot lifetimes: we charge the
7107 * page to memory here, and uncharge swap when the slot is freed.
7109 if (!mem_cgroup_disabled() && do_memsw_account()) {
7111 * The swap entry might not get freed for a long time,
7112 * let's not wait for it. The page already received a
7113 * memory+swap charge, drop the swap entry duplicate.
7115 mem_cgroup_uncharge_swap(entry, 1);
7119 struct uncharge_gather {
7120 struct mem_cgroup *memcg;
7121 unsigned long nr_memory;
7122 unsigned long pgpgout;
7123 unsigned long nr_kmem;
7127 static inline void uncharge_gather_clear(struct uncharge_gather *ug)
7129 memset(ug, 0, sizeof(*ug));
7132 static void uncharge_batch(const struct uncharge_gather *ug)
7134 unsigned long flags;
7136 if (ug->nr_memory) {
7137 page_counter_uncharge(&ug->memcg->memory, ug->nr_memory);
7138 if (do_memsw_account())
7139 page_counter_uncharge(&ug->memcg->memsw, ug->nr_memory);
7141 memcg_account_kmem(ug->memcg, -ug->nr_kmem);
7142 memcg_oom_recover(ug->memcg);
7145 local_irq_save(flags);
7146 __count_memcg_events(ug->memcg, PGPGOUT, ug->pgpgout);
7147 __this_cpu_add(ug->memcg->vmstats_percpu->nr_page_events, ug->nr_memory);
7148 memcg_check_events(ug->memcg, ug->nid);
7149 local_irq_restore(flags);
7151 /* drop reference from uncharge_folio */
7152 css_put(&ug->memcg->css);
7155 static void uncharge_folio(struct folio *folio, struct uncharge_gather *ug)
7158 struct mem_cgroup *memcg;
7159 struct obj_cgroup *objcg;
7161 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
7164 * Nobody should be changing or seriously looking at
7165 * folio memcg or objcg at this point, we have fully
7166 * exclusive access to the folio.
7168 if (folio_memcg_kmem(folio)) {
7169 objcg = __folio_objcg(folio);
7171 * This get matches the put at the end of the function and
7172 * kmem pages do not hold memcg references anymore.
7174 memcg = get_mem_cgroup_from_objcg(objcg);
7176 memcg = __folio_memcg(folio);
7182 if (ug->memcg != memcg) {
7185 uncharge_gather_clear(ug);
7188 ug->nid = folio_nid(folio);
7190 /* pairs with css_put in uncharge_batch */
7191 css_get(&memcg->css);
7194 nr_pages = folio_nr_pages(folio);
7196 if (folio_memcg_kmem(folio)) {
7197 ug->nr_memory += nr_pages;
7198 ug->nr_kmem += nr_pages;
7200 folio->memcg_data = 0;
7201 obj_cgroup_put(objcg);
7203 /* LRU pages aren't accounted at the root level */
7204 if (!mem_cgroup_is_root(memcg))
7205 ug->nr_memory += nr_pages;
7208 folio->memcg_data = 0;
7211 css_put(&memcg->css);
7214 void __mem_cgroup_uncharge(struct folio *folio)
7216 struct uncharge_gather ug;
7218 /* Don't touch folio->lru of any random page, pre-check: */
7219 if (!folio_memcg(folio))
7222 uncharge_gather_clear(&ug);
7223 uncharge_folio(folio, &ug);
7224 uncharge_batch(&ug);
7228 * __mem_cgroup_uncharge_list - uncharge a list of page
7229 * @page_list: list of pages to uncharge
7231 * Uncharge a list of pages previously charged with
7232 * __mem_cgroup_charge().
7234 void __mem_cgroup_uncharge_list(struct list_head *page_list)
7236 struct uncharge_gather ug;
7237 struct folio *folio;
7239 uncharge_gather_clear(&ug);
7240 list_for_each_entry(folio, page_list, lru)
7241 uncharge_folio(folio, &ug);
7243 uncharge_batch(&ug);
7247 * mem_cgroup_migrate - Charge a folio's replacement.
7248 * @old: Currently circulating folio.
7249 * @new: Replacement folio.
7251 * Charge @new as a replacement folio for @old. @old will
7252 * be uncharged upon free.
7254 * Both folios must be locked, @new->mapping must be set up.
7256 void mem_cgroup_migrate(struct folio *old, struct folio *new)
7258 struct mem_cgroup *memcg;
7259 long nr_pages = folio_nr_pages(new);
7260 unsigned long flags;
7262 VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
7263 VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
7264 VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
7265 VM_BUG_ON_FOLIO(folio_nr_pages(old) != nr_pages, new);
7267 if (mem_cgroup_disabled())
7270 /* Page cache replacement: new folio already charged? */
7271 if (folio_memcg(new))
7274 memcg = folio_memcg(old);
7275 VM_WARN_ON_ONCE_FOLIO(!memcg, old);
7279 /* Force-charge the new page. The old one will be freed soon */
7280 if (!mem_cgroup_is_root(memcg)) {
7281 page_counter_charge(&memcg->memory, nr_pages);
7282 if (do_memsw_account())
7283 page_counter_charge(&memcg->memsw, nr_pages);
7286 css_get(&memcg->css);
7287 commit_charge(new, memcg);
7289 local_irq_save(flags);
7290 mem_cgroup_charge_statistics(memcg, nr_pages);
7291 memcg_check_events(memcg, folio_nid(new));
7292 local_irq_restore(flags);
7295 DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
7296 EXPORT_SYMBOL(memcg_sockets_enabled_key);
7298 void mem_cgroup_sk_alloc(struct sock *sk)
7300 struct mem_cgroup *memcg;
7302 if (!mem_cgroup_sockets_enabled)
7305 /* Do not associate the sock with unrelated interrupted task's memcg. */
7310 memcg = mem_cgroup_from_task(current);
7311 if (mem_cgroup_is_root(memcg))
7313 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg->tcpmem_active)
7315 if (css_tryget(&memcg->css))
7316 sk->sk_memcg = memcg;
7321 void mem_cgroup_sk_free(struct sock *sk)
7324 css_put(&sk->sk_memcg->css);
7328 * mem_cgroup_charge_skmem - charge socket memory
7329 * @memcg: memcg to charge
7330 * @nr_pages: number of pages to charge
7331 * @gfp_mask: reclaim mode
7333 * Charges @nr_pages to @memcg. Returns %true if the charge fit within
7334 * @memcg's configured limit, %false if it doesn't.
7336 bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages,
7339 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
7340 struct page_counter *fail;
7342 if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) {
7343 memcg->tcpmem_pressure = 0;
7346 memcg->tcpmem_pressure = 1;
7347 if (gfp_mask & __GFP_NOFAIL) {
7348 page_counter_charge(&memcg->tcpmem, nr_pages);
7354 if (try_charge(memcg, gfp_mask, nr_pages) == 0) {
7355 mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
7363 * mem_cgroup_uncharge_skmem - uncharge socket memory
7364 * @memcg: memcg to uncharge
7365 * @nr_pages: number of pages to uncharge
7367 void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
7369 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
7370 page_counter_uncharge(&memcg->tcpmem, nr_pages);
7374 mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
7376 refill_stock(memcg, nr_pages);
7379 static int __init cgroup_memory(char *s)
7383 while ((token = strsep(&s, ",")) != NULL) {
7386 if (!strcmp(token, "nosocket"))
7387 cgroup_memory_nosocket = true;
7388 if (!strcmp(token, "nokmem"))
7389 cgroup_memory_nokmem = true;
7390 if (!strcmp(token, "nobpf"))
7391 cgroup_memory_nobpf = true;
7395 __setup("cgroup.memory=", cgroup_memory);
7398 * subsys_initcall() for memory controller.
7400 * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
7401 * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
7402 * basically everything that doesn't depend on a specific mem_cgroup structure
7403 * should be initialized from here.
7405 static int __init mem_cgroup_init(void)
7410 * Currently s32 type (can refer to struct batched_lruvec_stat) is
7411 * used for per-memcg-per-cpu caching of per-node statistics. In order
7412 * to work fine, we should make sure that the overfill threshold can't
7413 * exceed S32_MAX / PAGE_SIZE.
7415 BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE);
7417 cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
7418 memcg_hotplug_cpu_dead);
7420 for_each_possible_cpu(cpu)
7421 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
7424 for_each_node(node) {
7425 struct mem_cgroup_tree_per_node *rtpn;
7427 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL,
7428 node_online(node) ? node : NUMA_NO_NODE);
7430 rtpn->rb_root = RB_ROOT;
7431 rtpn->rb_rightmost = NULL;
7432 spin_lock_init(&rtpn->lock);
7433 soft_limit_tree.rb_tree_per_node[node] = rtpn;
7438 subsys_initcall(mem_cgroup_init);
7441 static struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
7443 while (!refcount_inc_not_zero(&memcg->id.ref)) {
7445 * The root cgroup cannot be destroyed, so it's refcount must
7448 if (WARN_ON_ONCE(mem_cgroup_is_root(memcg))) {
7452 memcg = parent_mem_cgroup(memcg);
7454 memcg = root_mem_cgroup;
7460 * mem_cgroup_swapout - transfer a memsw charge to swap
7461 * @folio: folio whose memsw charge to transfer
7462 * @entry: swap entry to move the charge to
7464 * Transfer the memsw charge of @folio to @entry.
7466 void mem_cgroup_swapout(struct folio *folio, swp_entry_t entry)
7468 struct mem_cgroup *memcg, *swap_memcg;
7469 unsigned int nr_entries;
7470 unsigned short oldid;
7472 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
7473 VM_BUG_ON_FOLIO(folio_ref_count(folio), folio);
7475 if (mem_cgroup_disabled())
7478 if (!do_memsw_account())
7481 memcg = folio_memcg(folio);
7483 VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
7488 * In case the memcg owning these pages has been offlined and doesn't
7489 * have an ID allocated to it anymore, charge the closest online
7490 * ancestor for the swap instead and transfer the memory+swap charge.
7492 swap_memcg = mem_cgroup_id_get_online(memcg);
7493 nr_entries = folio_nr_pages(folio);
7494 /* Get references for the tail pages, too */
7496 mem_cgroup_id_get_many(swap_memcg, nr_entries - 1);
7497 oldid = swap_cgroup_record(entry, mem_cgroup_id(swap_memcg),
7499 VM_BUG_ON_FOLIO(oldid, folio);
7500 mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries);
7502 folio->memcg_data = 0;
7504 if (!mem_cgroup_is_root(memcg))
7505 page_counter_uncharge(&memcg->memory, nr_entries);
7507 if (memcg != swap_memcg) {
7508 if (!mem_cgroup_is_root(swap_memcg))
7509 page_counter_charge(&swap_memcg->memsw, nr_entries);
7510 page_counter_uncharge(&memcg->memsw, nr_entries);
7514 * Interrupts should be disabled here because the caller holds the
7515 * i_pages lock which is taken with interrupts-off. It is
7516 * important here to have the interrupts disabled because it is the
7517 * only synchronisation we have for updating the per-CPU variables.
7520 mem_cgroup_charge_statistics(memcg, -nr_entries);
7521 memcg_stats_unlock();
7522 memcg_check_events(memcg, folio_nid(folio));
7524 css_put(&memcg->css);
7528 * __mem_cgroup_try_charge_swap - try charging swap space for a folio
7529 * @folio: folio being added to swap
7530 * @entry: swap entry to charge
7532 * Try to charge @folio's memcg for the swap space at @entry.
7534 * Returns 0 on success, -ENOMEM on failure.
7536 int __mem_cgroup_try_charge_swap(struct folio *folio, swp_entry_t entry)
7538 unsigned int nr_pages = folio_nr_pages(folio);
7539 struct page_counter *counter;
7540 struct mem_cgroup *memcg;
7541 unsigned short oldid;
7543 if (do_memsw_account())
7546 memcg = folio_memcg(folio);
7548 VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
7553 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7557 memcg = mem_cgroup_id_get_online(memcg);
7559 if (!mem_cgroup_is_root(memcg) &&
7560 !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
7561 memcg_memory_event(memcg, MEMCG_SWAP_MAX);
7562 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7563 mem_cgroup_id_put(memcg);
7567 /* Get references for the tail pages, too */
7569 mem_cgroup_id_get_many(memcg, nr_pages - 1);
7570 oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg), nr_pages);
7571 VM_BUG_ON_FOLIO(oldid, folio);
7572 mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
7578 * __mem_cgroup_uncharge_swap - uncharge swap space
7579 * @entry: swap entry to uncharge
7580 * @nr_pages: the amount of swap space to uncharge
7582 void __mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
7584 struct mem_cgroup *memcg;
7587 if (mem_cgroup_disabled())
7590 id = swap_cgroup_record(entry, 0, nr_pages);
7592 memcg = mem_cgroup_from_id(id);
7594 if (!mem_cgroup_is_root(memcg)) {
7595 if (do_memsw_account())
7596 page_counter_uncharge(&memcg->memsw, nr_pages);
7598 page_counter_uncharge(&memcg->swap, nr_pages);
7600 mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
7601 mem_cgroup_id_put_many(memcg, nr_pages);
7606 long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
7608 long nr_swap_pages = get_nr_swap_pages();
7610 if (mem_cgroup_disabled() || do_memsw_account())
7611 return nr_swap_pages;
7612 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg))
7613 nr_swap_pages = min_t(long, nr_swap_pages,
7614 READ_ONCE(memcg->swap.max) -
7615 page_counter_read(&memcg->swap));
7616 return nr_swap_pages;
7619 bool mem_cgroup_swap_full(struct folio *folio)
7621 struct mem_cgroup *memcg;
7623 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
7627 if (do_memsw_account())
7630 memcg = folio_memcg(folio);
7634 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
7635 unsigned long usage = page_counter_read(&memcg->swap);
7637 if (usage * 2 >= READ_ONCE(memcg->swap.high) ||
7638 usage * 2 >= READ_ONCE(memcg->swap.max))
7645 static int __init setup_swap_account(char *s)
7647 pr_warn_once("The swapaccount= commandline option is deprecated. "
7648 "Please report your usecase to linux-mm@kvack.org if you "
7649 "depend on this functionality.\n");
7652 __setup("swapaccount=", setup_swap_account);
7654 static u64 swap_current_read(struct cgroup_subsys_state *css,
7657 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7659 return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
7662 static int swap_high_show(struct seq_file *m, void *v)
7664 return seq_puts_memcg_tunable(m,
7665 READ_ONCE(mem_cgroup_from_seq(m)->swap.high));
7668 static ssize_t swap_high_write(struct kernfs_open_file *of,
7669 char *buf, size_t nbytes, loff_t off)
7671 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7675 buf = strstrip(buf);
7676 err = page_counter_memparse(buf, "max", &high);
7680 page_counter_set_high(&memcg->swap, high);
7685 static int swap_max_show(struct seq_file *m, void *v)
7687 return seq_puts_memcg_tunable(m,
7688 READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
7691 static ssize_t swap_max_write(struct kernfs_open_file *of,
7692 char *buf, size_t nbytes, loff_t off)
7694 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7698 buf = strstrip(buf);
7699 err = page_counter_memparse(buf, "max", &max);
7703 xchg(&memcg->swap.max, max);
7708 static int swap_events_show(struct seq_file *m, void *v)
7710 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
7712 seq_printf(m, "high %lu\n",
7713 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH]));
7714 seq_printf(m, "max %lu\n",
7715 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
7716 seq_printf(m, "fail %lu\n",
7717 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
7722 static struct cftype swap_files[] = {
7724 .name = "swap.current",
7725 .flags = CFTYPE_NOT_ON_ROOT,
7726 .read_u64 = swap_current_read,
7729 .name = "swap.high",
7730 .flags = CFTYPE_NOT_ON_ROOT,
7731 .seq_show = swap_high_show,
7732 .write = swap_high_write,
7736 .flags = CFTYPE_NOT_ON_ROOT,
7737 .seq_show = swap_max_show,
7738 .write = swap_max_write,
7741 .name = "swap.events",
7742 .flags = CFTYPE_NOT_ON_ROOT,
7743 .file_offset = offsetof(struct mem_cgroup, swap_events_file),
7744 .seq_show = swap_events_show,
7749 static struct cftype memsw_files[] = {
7751 .name = "memsw.usage_in_bytes",
7752 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
7753 .read_u64 = mem_cgroup_read_u64,
7756 .name = "memsw.max_usage_in_bytes",
7757 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
7758 .write = mem_cgroup_reset,
7759 .read_u64 = mem_cgroup_read_u64,
7762 .name = "memsw.limit_in_bytes",
7763 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
7764 .write = mem_cgroup_write,
7765 .read_u64 = mem_cgroup_read_u64,
7768 .name = "memsw.failcnt",
7769 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
7770 .write = mem_cgroup_reset,
7771 .read_u64 = mem_cgroup_read_u64,
7773 { }, /* terminate */
7776 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
7778 * obj_cgroup_may_zswap - check if this cgroup can zswap
7779 * @objcg: the object cgroup
7781 * Check if the hierarchical zswap limit has been reached.
7783 * This doesn't check for specific headroom, and it is not atomic
7784 * either. But with zswap, the size of the allocation is only known
7785 * once compression has occured, and this optimistic pre-check avoids
7786 * spending cycles on compression when there is already no room left
7787 * or zswap is disabled altogether somewhere in the hierarchy.
7789 bool obj_cgroup_may_zswap(struct obj_cgroup *objcg)
7791 struct mem_cgroup *memcg, *original_memcg;
7794 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
7797 original_memcg = get_mem_cgroup_from_objcg(objcg);
7798 for (memcg = original_memcg; !mem_cgroup_is_root(memcg);
7799 memcg = parent_mem_cgroup(memcg)) {
7800 unsigned long max = READ_ONCE(memcg->zswap_max);
7801 unsigned long pages;
7803 if (max == PAGE_COUNTER_MAX)
7810 cgroup_rstat_flush(memcg->css.cgroup);
7811 pages = memcg_page_state(memcg, MEMCG_ZSWAP_B) / PAGE_SIZE;
7817 mem_cgroup_put(original_memcg);
7822 * obj_cgroup_charge_zswap - charge compression backend memory
7823 * @objcg: the object cgroup
7824 * @size: size of compressed object
7826 * This forces the charge after obj_cgroup_may_swap() allowed
7827 * compression and storage in zwap for this cgroup to go ahead.
7829 void obj_cgroup_charge_zswap(struct obj_cgroup *objcg, size_t size)
7831 struct mem_cgroup *memcg;
7833 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
7836 VM_WARN_ON_ONCE(!(current->flags & PF_MEMALLOC));
7838 /* PF_MEMALLOC context, charging must succeed */
7839 if (obj_cgroup_charge(objcg, GFP_KERNEL, size))
7843 memcg = obj_cgroup_memcg(objcg);
7844 mod_memcg_state(memcg, MEMCG_ZSWAP_B, size);
7845 mod_memcg_state(memcg, MEMCG_ZSWAPPED, 1);
7850 * obj_cgroup_uncharge_zswap - uncharge compression backend memory
7851 * @objcg: the object cgroup
7852 * @size: size of compressed object
7854 * Uncharges zswap memory on page in.
7856 void obj_cgroup_uncharge_zswap(struct obj_cgroup *objcg, size_t size)
7858 struct mem_cgroup *memcg;
7860 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
7863 obj_cgroup_uncharge(objcg, size);
7866 memcg = obj_cgroup_memcg(objcg);
7867 mod_memcg_state(memcg, MEMCG_ZSWAP_B, -size);
7868 mod_memcg_state(memcg, MEMCG_ZSWAPPED, -1);
7872 static u64 zswap_current_read(struct cgroup_subsys_state *css,
7875 cgroup_rstat_flush(css->cgroup);
7876 return memcg_page_state(mem_cgroup_from_css(css), MEMCG_ZSWAP_B);
7879 static int zswap_max_show(struct seq_file *m, void *v)
7881 return seq_puts_memcg_tunable(m,
7882 READ_ONCE(mem_cgroup_from_seq(m)->zswap_max));
7885 static ssize_t zswap_max_write(struct kernfs_open_file *of,
7886 char *buf, size_t nbytes, loff_t off)
7888 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7892 buf = strstrip(buf);
7893 err = page_counter_memparse(buf, "max", &max);
7897 xchg(&memcg->zswap_max, max);
7902 static struct cftype zswap_files[] = {
7904 .name = "zswap.current",
7905 .flags = CFTYPE_NOT_ON_ROOT,
7906 .read_u64 = zswap_current_read,
7909 .name = "zswap.max",
7910 .flags = CFTYPE_NOT_ON_ROOT,
7911 .seq_show = zswap_max_show,
7912 .write = zswap_max_write,
7916 #endif /* CONFIG_MEMCG_KMEM && CONFIG_ZSWAP */
7918 static int __init mem_cgroup_swap_init(void)
7920 if (mem_cgroup_disabled())
7923 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files));
7924 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files));
7925 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
7926 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, zswap_files));
7930 subsys_initcall(mem_cgroup_swap_init);
7932 #endif /* CONFIG_SWAP */