1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* memcontrol.c - Memory Controller
4 * Copyright IBM Corporation, 2007
7 * Copyright 2007 OpenVZ SWsoft Inc
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/pagevec.h>
37 #include <linux/vm_event_item.h>
38 #include <linux/smp.h>
39 #include <linux/page-flags.h>
40 #include <linux/backing-dev.h>
41 #include <linux/bit_spinlock.h>
42 #include <linux/rcupdate.h>
43 #include <linux/limits.h>
44 #include <linux/export.h>
45 #include <linux/mutex.h>
46 #include <linux/rbtree.h>
47 #include <linux/slab.h>
48 #include <linux/swap.h>
49 #include <linux/swapops.h>
50 #include <linux/spinlock.h>
51 #include <linux/eventfd.h>
52 #include <linux/poll.h>
53 #include <linux/sort.h>
55 #include <linux/seq_file.h>
56 #include <linux/vmpressure.h>
57 #include <linux/memremap.h>
58 #include <linux/mm_inline.h>
59 #include <linux/swap_cgroup.h>
60 #include <linux/cpu.h>
61 #include <linux/oom.h>
62 #include <linux/lockdep.h>
63 #include <linux/file.h>
64 #include <linux/resume_user_mode.h>
65 #include <linux/psi.h>
66 #include <linux/seq_buf.h>
67 #include <linux/sched/isolation.h>
68 #include <linux/kmemleak.h>
75 #include <linux/uaccess.h>
77 #include <trace/events/vmscan.h>
79 struct cgroup_subsys memory_cgrp_subsys __read_mostly;
80 EXPORT_SYMBOL(memory_cgrp_subsys);
82 struct mem_cgroup *root_mem_cgroup __read_mostly;
84 /* Active memory cgroup to use from an interrupt context */
85 DEFINE_PER_CPU(struct mem_cgroup *, int_active_memcg);
86 EXPORT_PER_CPU_SYMBOL_GPL(int_active_memcg);
88 /* Socket memory accounting disabled? */
89 static bool cgroup_memory_nosocket __ro_after_init;
91 /* Kernel memory accounting disabled? */
92 static bool cgroup_memory_nokmem __ro_after_init;
94 /* BPF memory accounting disabled? */
95 static bool cgroup_memory_nobpf __ro_after_init;
97 #ifdef CONFIG_CGROUP_WRITEBACK
98 static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq);
101 /* Whether legacy memory+swap accounting is active */
102 static bool do_memsw_account(void)
104 return !cgroup_subsys_on_dfl(memory_cgrp_subsys);
107 #define THRESHOLDS_EVENTS_TARGET 128
108 #define SOFTLIMIT_EVENTS_TARGET 1024
111 * Cgroups above their limits are maintained in a RB-Tree, independent of
112 * their hierarchy representation
115 struct mem_cgroup_tree_per_node {
116 struct rb_root rb_root;
117 struct rb_node *rb_rightmost;
121 struct mem_cgroup_tree {
122 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
125 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
128 struct mem_cgroup_eventfd_list {
129 struct list_head list;
130 struct eventfd_ctx *eventfd;
134 * cgroup_event represents events which userspace want to receive.
136 struct mem_cgroup_event {
138 * memcg which the event belongs to.
140 struct mem_cgroup *memcg;
142 * eventfd to signal userspace about the event.
144 struct eventfd_ctx *eventfd;
146 * Each of these stored in a list by the cgroup.
148 struct list_head list;
150 * register_event() callback will be used to add new userspace
151 * waiter for changes related to this event. Use eventfd_signal()
152 * on eventfd to send notification to userspace.
154 int (*register_event)(struct mem_cgroup *memcg,
155 struct eventfd_ctx *eventfd, const char *args);
157 * unregister_event() callback will be called when userspace closes
158 * the eventfd or on cgroup removing. This callback must be set,
159 * if you want provide notification functionality.
161 void (*unregister_event)(struct mem_cgroup *memcg,
162 struct eventfd_ctx *eventfd);
164 * All fields below needed to unregister event when
165 * userspace closes eventfd.
168 wait_queue_head_t *wqh;
169 wait_queue_entry_t wait;
170 struct work_struct remove;
173 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
174 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
176 /* Stuffs for move charges at task migration. */
178 * Types of charges to be moved.
180 #define MOVE_ANON 0x1U
181 #define MOVE_FILE 0x2U
182 #define MOVE_MASK (MOVE_ANON | MOVE_FILE)
184 /* "mc" and its members are protected by cgroup_mutex */
185 static struct move_charge_struct {
186 spinlock_t lock; /* for from, to */
187 struct mm_struct *mm;
188 struct mem_cgroup *from;
189 struct mem_cgroup *to;
191 unsigned long precharge;
192 unsigned long moved_charge;
193 unsigned long moved_swap;
194 struct task_struct *moving_task; /* a task moving charges */
195 wait_queue_head_t waitq; /* a waitq for other context */
197 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
198 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
202 * Maximum loops in mem_cgroup_soft_reclaim(), used for soft
203 * limit reclaim to prevent infinite loops, if they ever occur.
205 #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
206 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
208 /* for encoding cft->private value on file */
216 #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
217 #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
218 #define MEMFILE_ATTR(val) ((val) & 0xffff)
221 * Iteration constructs for visiting all cgroups (under a tree). If
222 * loops are exited prematurely (break), mem_cgroup_iter_break() must
223 * be used for reference counting.
225 #define for_each_mem_cgroup_tree(iter, root) \
226 for (iter = mem_cgroup_iter(root, NULL, NULL); \
228 iter = mem_cgroup_iter(root, iter, NULL))
230 #define for_each_mem_cgroup(iter) \
231 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
233 iter = mem_cgroup_iter(NULL, iter, NULL))
235 static inline bool task_is_dying(void)
237 return tsk_is_oom_victim(current) || fatal_signal_pending(current) ||
238 (current->flags & PF_EXITING);
241 /* Some nice accessors for the vmpressure. */
242 struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
245 memcg = root_mem_cgroup;
246 return &memcg->vmpressure;
249 struct mem_cgroup *vmpressure_to_memcg(struct vmpressure *vmpr)
251 return container_of(vmpr, struct mem_cgroup, vmpressure);
254 #define CURRENT_OBJCG_UPDATE_BIT 0
255 #define CURRENT_OBJCG_UPDATE_FLAG (1UL << CURRENT_OBJCG_UPDATE_BIT)
257 #ifdef CONFIG_MEMCG_KMEM
258 static DEFINE_SPINLOCK(objcg_lock);
260 bool mem_cgroup_kmem_disabled(void)
262 return cgroup_memory_nokmem;
265 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
266 unsigned int nr_pages);
268 static void obj_cgroup_release(struct percpu_ref *ref)
270 struct obj_cgroup *objcg = container_of(ref, struct obj_cgroup, refcnt);
271 unsigned int nr_bytes;
272 unsigned int nr_pages;
276 * At this point all allocated objects are freed, and
277 * objcg->nr_charged_bytes can't have an arbitrary byte value.
278 * However, it can be PAGE_SIZE or (x * PAGE_SIZE).
280 * The following sequence can lead to it:
281 * 1) CPU0: objcg == stock->cached_objcg
282 * 2) CPU1: we do a small allocation (e.g. 92 bytes),
283 * PAGE_SIZE bytes are charged
284 * 3) CPU1: a process from another memcg is allocating something,
285 * the stock if flushed,
286 * objcg->nr_charged_bytes = PAGE_SIZE - 92
287 * 5) CPU0: we do release this object,
288 * 92 bytes are added to stock->nr_bytes
289 * 6) CPU0: stock is flushed,
290 * 92 bytes are added to objcg->nr_charged_bytes
292 * In the result, nr_charged_bytes == PAGE_SIZE.
293 * This page will be uncharged in obj_cgroup_release().
295 nr_bytes = atomic_read(&objcg->nr_charged_bytes);
296 WARN_ON_ONCE(nr_bytes & (PAGE_SIZE - 1));
297 nr_pages = nr_bytes >> PAGE_SHIFT;
300 obj_cgroup_uncharge_pages(objcg, nr_pages);
302 spin_lock_irqsave(&objcg_lock, flags);
303 list_del(&objcg->list);
304 spin_unlock_irqrestore(&objcg_lock, flags);
306 percpu_ref_exit(ref);
307 kfree_rcu(objcg, rcu);
310 static struct obj_cgroup *obj_cgroup_alloc(void)
312 struct obj_cgroup *objcg;
315 objcg = kzalloc(sizeof(struct obj_cgroup), GFP_KERNEL);
319 ret = percpu_ref_init(&objcg->refcnt, obj_cgroup_release, 0,
325 INIT_LIST_HEAD(&objcg->list);
329 static void memcg_reparent_objcgs(struct mem_cgroup *memcg,
330 struct mem_cgroup *parent)
332 struct obj_cgroup *objcg, *iter;
334 objcg = rcu_replace_pointer(memcg->objcg, NULL, true);
336 spin_lock_irq(&objcg_lock);
338 /* 1) Ready to reparent active objcg. */
339 list_add(&objcg->list, &memcg->objcg_list);
340 /* 2) Reparent active objcg and already reparented objcgs to parent. */
341 list_for_each_entry(iter, &memcg->objcg_list, list)
342 WRITE_ONCE(iter->memcg, parent);
343 /* 3) Move already reparented objcgs to the parent's list */
344 list_splice(&memcg->objcg_list, &parent->objcg_list);
346 spin_unlock_irq(&objcg_lock);
348 percpu_ref_kill(&objcg->refcnt);
352 * A lot of the calls to the cache allocation functions are expected to be
353 * inlined by the compiler. Since the calls to memcg_slab_post_alloc_hook() are
354 * conditional to this static branch, we'll have to allow modules that does
355 * kmem_cache_alloc and the such to see this symbol as well
357 DEFINE_STATIC_KEY_FALSE(memcg_kmem_online_key);
358 EXPORT_SYMBOL(memcg_kmem_online_key);
360 DEFINE_STATIC_KEY_FALSE(memcg_bpf_enabled_key);
361 EXPORT_SYMBOL(memcg_bpf_enabled_key);
365 * mem_cgroup_css_from_folio - css of the memcg associated with a folio
366 * @folio: folio of interest
368 * If memcg is bound to the default hierarchy, css of the memcg associated
369 * with @folio is returned. The returned css remains associated with @folio
370 * until it is released.
372 * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
375 struct cgroup_subsys_state *mem_cgroup_css_from_folio(struct folio *folio)
377 struct mem_cgroup *memcg = folio_memcg(folio);
379 if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
380 memcg = root_mem_cgroup;
386 * page_cgroup_ino - return inode number of the memcg a page is charged to
389 * Look up the closest online ancestor of the memory cgroup @page is charged to
390 * and return its inode number or 0 if @page is not charged to any cgroup. It
391 * is safe to call this function without holding a reference to @page.
393 * Note, this function is inherently racy, because there is nothing to prevent
394 * the cgroup inode from getting torn down and potentially reallocated a moment
395 * after page_cgroup_ino() returns, so it only should be used by callers that
396 * do not care (such as procfs interfaces).
398 ino_t page_cgroup_ino(struct page *page)
400 struct mem_cgroup *memcg;
401 unsigned long ino = 0;
404 /* page_folio() is racy here, but the entire function is racy anyway */
405 memcg = folio_memcg_check(page_folio(page));
407 while (memcg && !(memcg->css.flags & CSS_ONLINE))
408 memcg = parent_mem_cgroup(memcg);
410 ino = cgroup_ino(memcg->css.cgroup);
415 static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_node *mz,
416 struct mem_cgroup_tree_per_node *mctz,
417 unsigned long new_usage_in_excess)
419 struct rb_node **p = &mctz->rb_root.rb_node;
420 struct rb_node *parent = NULL;
421 struct mem_cgroup_per_node *mz_node;
422 bool rightmost = true;
427 mz->usage_in_excess = new_usage_in_excess;
428 if (!mz->usage_in_excess)
432 mz_node = rb_entry(parent, struct mem_cgroup_per_node,
434 if (mz->usage_in_excess < mz_node->usage_in_excess) {
443 mctz->rb_rightmost = &mz->tree_node;
445 rb_link_node(&mz->tree_node, parent, p);
446 rb_insert_color(&mz->tree_node, &mctz->rb_root);
450 static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
451 struct mem_cgroup_tree_per_node *mctz)
456 if (&mz->tree_node == mctz->rb_rightmost)
457 mctz->rb_rightmost = rb_prev(&mz->tree_node);
459 rb_erase(&mz->tree_node, &mctz->rb_root);
463 static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
464 struct mem_cgroup_tree_per_node *mctz)
468 spin_lock_irqsave(&mctz->lock, flags);
469 __mem_cgroup_remove_exceeded(mz, mctz);
470 spin_unlock_irqrestore(&mctz->lock, flags);
473 static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
475 unsigned long nr_pages = page_counter_read(&memcg->memory);
476 unsigned long soft_limit = READ_ONCE(memcg->soft_limit);
477 unsigned long excess = 0;
479 if (nr_pages > soft_limit)
480 excess = nr_pages - soft_limit;
485 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, int nid)
487 unsigned long excess;
488 struct mem_cgroup_per_node *mz;
489 struct mem_cgroup_tree_per_node *mctz;
491 if (lru_gen_enabled()) {
492 if (soft_limit_excess(memcg))
493 lru_gen_soft_reclaim(memcg, nid);
497 mctz = soft_limit_tree.rb_tree_per_node[nid];
501 * Necessary to update all ancestors when hierarchy is used.
502 * because their event counter is not touched.
504 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
505 mz = memcg->nodeinfo[nid];
506 excess = soft_limit_excess(memcg);
508 * We have to update the tree if mz is on RB-tree or
509 * mem is over its softlimit.
511 if (excess || mz->on_tree) {
514 spin_lock_irqsave(&mctz->lock, flags);
515 /* if on-tree, remove it */
517 __mem_cgroup_remove_exceeded(mz, mctz);
519 * Insert again. mz->usage_in_excess will be updated.
520 * If excess is 0, no tree ops.
522 __mem_cgroup_insert_exceeded(mz, mctz, excess);
523 spin_unlock_irqrestore(&mctz->lock, flags);
528 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
530 struct mem_cgroup_tree_per_node *mctz;
531 struct mem_cgroup_per_node *mz;
535 mz = memcg->nodeinfo[nid];
536 mctz = soft_limit_tree.rb_tree_per_node[nid];
538 mem_cgroup_remove_exceeded(mz, mctz);
542 static struct mem_cgroup_per_node *
543 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
545 struct mem_cgroup_per_node *mz;
549 if (!mctz->rb_rightmost)
550 goto done; /* Nothing to reclaim from */
552 mz = rb_entry(mctz->rb_rightmost,
553 struct mem_cgroup_per_node, tree_node);
555 * Remove the node now but someone else can add it back,
556 * we will to add it back at the end of reclaim to its correct
557 * position in the tree.
559 __mem_cgroup_remove_exceeded(mz, mctz);
560 if (!soft_limit_excess(mz->memcg) ||
561 !css_tryget(&mz->memcg->css))
567 static struct mem_cgroup_per_node *
568 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
570 struct mem_cgroup_per_node *mz;
572 spin_lock_irq(&mctz->lock);
573 mz = __mem_cgroup_largest_soft_limit_node(mctz);
574 spin_unlock_irq(&mctz->lock);
578 /* Subset of node_stat_item for memcg stats */
579 static const unsigned int memcg_node_stat_items[] = {
585 NR_SLAB_RECLAIMABLE_B,
586 NR_SLAB_UNRECLAIMABLE_B,
587 WORKINGSET_REFAULT_ANON,
588 WORKINGSET_REFAULT_FILE,
589 WORKINGSET_ACTIVATE_ANON,
590 WORKINGSET_ACTIVATE_FILE,
591 WORKINGSET_RESTORE_ANON,
592 WORKINGSET_RESTORE_FILE,
593 WORKINGSET_NODERECLAIM,
605 NR_SECONDARY_PAGETABLE,
611 static const unsigned int memcg_stat_items[] = {
621 #define NR_MEMCG_NODE_STAT_ITEMS ARRAY_SIZE(memcg_node_stat_items)
622 #define MEMCG_VMSTAT_SIZE (NR_MEMCG_NODE_STAT_ITEMS + \
623 ARRAY_SIZE(memcg_stat_items))
624 static int8_t mem_cgroup_stats_index[MEMCG_NR_STAT] __read_mostly;
626 static void init_memcg_stats(void)
630 BUILD_BUG_ON(MEMCG_NR_STAT >= S8_MAX);
632 for (i = 0; i < NR_MEMCG_NODE_STAT_ITEMS; ++i)
633 mem_cgroup_stats_index[memcg_node_stat_items[i]] = ++j;
635 for (i = 0; i < ARRAY_SIZE(memcg_stat_items); ++i)
636 mem_cgroup_stats_index[memcg_stat_items[i]] = ++j;
639 static inline int memcg_stats_index(int idx)
641 return mem_cgroup_stats_index[idx] - 1;
644 struct lruvec_stats_percpu {
645 /* Local (CPU and cgroup) state */
646 long state[NR_MEMCG_NODE_STAT_ITEMS];
648 /* Delta calculation for lockless upward propagation */
649 long state_prev[NR_MEMCG_NODE_STAT_ITEMS];
652 struct lruvec_stats {
653 /* Aggregated (CPU and subtree) state */
654 long state[NR_MEMCG_NODE_STAT_ITEMS];
656 /* Non-hierarchical (CPU aggregated) state */
657 long state_local[NR_MEMCG_NODE_STAT_ITEMS];
659 /* Pending child counts during tree propagation */
660 long state_pending[NR_MEMCG_NODE_STAT_ITEMS];
663 unsigned long lruvec_page_state(struct lruvec *lruvec, enum node_stat_item idx)
665 struct mem_cgroup_per_node *pn;
669 if (mem_cgroup_disabled())
670 return node_page_state(lruvec_pgdat(lruvec), idx);
672 i = memcg_stats_index(idx);
673 if (WARN_ONCE(i < 0, "%s: missing stat item %d\n", __func__, idx))
676 pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
677 x = READ_ONCE(pn->lruvec_stats->state[i]);
685 unsigned long lruvec_page_state_local(struct lruvec *lruvec,
686 enum node_stat_item idx)
688 struct mem_cgroup_per_node *pn;
692 if (mem_cgroup_disabled())
693 return node_page_state(lruvec_pgdat(lruvec), idx);
695 i = memcg_stats_index(idx);
696 if (WARN_ONCE(i < 0, "%s: missing stat item %d\n", __func__, idx))
699 pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
700 x = READ_ONCE(pn->lruvec_stats->state_local[i]);
708 /* Subset of vm_event_item to report for memcg event stats */
709 static const unsigned int memcg_vm_event_stat[] = {
725 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
730 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
738 #define NR_MEMCG_EVENTS ARRAY_SIZE(memcg_vm_event_stat)
739 static int8_t mem_cgroup_events_index[NR_VM_EVENT_ITEMS] __read_mostly;
741 static void init_memcg_events(void)
745 BUILD_BUG_ON(NR_VM_EVENT_ITEMS >= S8_MAX);
747 for (i = 0; i < NR_MEMCG_EVENTS; ++i)
748 mem_cgroup_events_index[memcg_vm_event_stat[i]] = i + 1;
751 static inline int memcg_events_index(enum vm_event_item idx)
753 return mem_cgroup_events_index[idx] - 1;
756 struct memcg_vmstats_percpu {
757 /* Stats updates since the last flush */
758 unsigned int stats_updates;
760 /* Cached pointers for fast iteration in memcg_rstat_updated() */
761 struct memcg_vmstats_percpu *parent;
762 struct memcg_vmstats *vmstats;
764 /* The above should fit a single cacheline for memcg_rstat_updated() */
766 /* Local (CPU and cgroup) page state & events */
767 long state[MEMCG_VMSTAT_SIZE];
768 unsigned long events[NR_MEMCG_EVENTS];
770 /* Delta calculation for lockless upward propagation */
771 long state_prev[MEMCG_VMSTAT_SIZE];
772 unsigned long events_prev[NR_MEMCG_EVENTS];
774 /* Cgroup1: threshold notifications & softlimit tree updates */
775 unsigned long nr_page_events;
776 unsigned long targets[MEM_CGROUP_NTARGETS];
777 } ____cacheline_aligned;
779 struct memcg_vmstats {
780 /* Aggregated (CPU and subtree) page state & events */
781 long state[MEMCG_VMSTAT_SIZE];
782 unsigned long events[NR_MEMCG_EVENTS];
784 /* Non-hierarchical (CPU aggregated) page state & events */
785 long state_local[MEMCG_VMSTAT_SIZE];
786 unsigned long events_local[NR_MEMCG_EVENTS];
788 /* Pending child counts during tree propagation */
789 long state_pending[MEMCG_VMSTAT_SIZE];
790 unsigned long events_pending[NR_MEMCG_EVENTS];
792 /* Stats updates since the last flush */
793 atomic64_t stats_updates;
797 * memcg and lruvec stats flushing
799 * Many codepaths leading to stats update or read are performance sensitive and
800 * adding stats flushing in such codepaths is not desirable. So, to optimize the
801 * flushing the kernel does:
803 * 1) Periodically and asynchronously flush the stats every 2 seconds to not let
804 * rstat update tree grow unbounded.
806 * 2) Flush the stats synchronously on reader side only when there are more than
807 * (MEMCG_CHARGE_BATCH * nr_cpus) update events. Though this optimization
808 * will let stats be out of sync by atmost (MEMCG_CHARGE_BATCH * nr_cpus) but
809 * only for 2 seconds due to (1).
811 static void flush_memcg_stats_dwork(struct work_struct *w);
812 static DECLARE_DEFERRABLE_WORK(stats_flush_dwork, flush_memcg_stats_dwork);
813 static u64 flush_last_time;
815 #define FLUSH_TIME (2UL*HZ)
818 * Accessors to ensure that preemption is disabled on PREEMPT_RT because it can
819 * not rely on this as part of an acquired spinlock_t lock. These functions are
820 * never used in hardirq context on PREEMPT_RT and therefore disabling preemtion
823 static void memcg_stats_lock(void)
825 preempt_disable_nested();
826 VM_WARN_ON_IRQS_ENABLED();
829 static void __memcg_stats_lock(void)
831 preempt_disable_nested();
834 static void memcg_stats_unlock(void)
836 preempt_enable_nested();
840 static bool memcg_vmstats_needs_flush(struct memcg_vmstats *vmstats)
842 return atomic64_read(&vmstats->stats_updates) >
843 MEMCG_CHARGE_BATCH * num_online_cpus();
846 static inline void memcg_rstat_updated(struct mem_cgroup *memcg, int val)
848 struct memcg_vmstats_percpu *statc;
849 int cpu = smp_processor_id();
850 unsigned int stats_updates;
855 cgroup_rstat_updated(memcg->css.cgroup, cpu);
856 statc = this_cpu_ptr(memcg->vmstats_percpu);
857 for (; statc; statc = statc->parent) {
858 stats_updates = READ_ONCE(statc->stats_updates) + abs(val);
859 WRITE_ONCE(statc->stats_updates, stats_updates);
860 if (stats_updates < MEMCG_CHARGE_BATCH)
864 * If @memcg is already flush-able, increasing stats_updates is
865 * redundant. Avoid the overhead of the atomic update.
867 if (!memcg_vmstats_needs_flush(statc->vmstats))
868 atomic64_add(stats_updates,
869 &statc->vmstats->stats_updates);
870 WRITE_ONCE(statc->stats_updates, 0);
874 static void do_flush_stats(struct mem_cgroup *memcg)
876 if (mem_cgroup_is_root(memcg))
877 WRITE_ONCE(flush_last_time, jiffies_64);
879 cgroup_rstat_flush(memcg->css.cgroup);
883 * mem_cgroup_flush_stats - flush the stats of a memory cgroup subtree
884 * @memcg: root of the subtree to flush
886 * Flushing is serialized by the underlying global rstat lock. There is also a
887 * minimum amount of work to be done even if there are no stat updates to flush.
888 * Hence, we only flush the stats if the updates delta exceeds a threshold. This
889 * avoids unnecessary work and contention on the underlying lock.
891 void mem_cgroup_flush_stats(struct mem_cgroup *memcg)
893 if (mem_cgroup_disabled())
897 memcg = root_mem_cgroup;
899 if (memcg_vmstats_needs_flush(memcg->vmstats))
900 do_flush_stats(memcg);
903 void mem_cgroup_flush_stats_ratelimited(struct mem_cgroup *memcg)
905 /* Only flush if the periodic flusher is one full cycle late */
906 if (time_after64(jiffies_64, READ_ONCE(flush_last_time) + 2*FLUSH_TIME))
907 mem_cgroup_flush_stats(memcg);
910 static void flush_memcg_stats_dwork(struct work_struct *w)
913 * Deliberately ignore memcg_vmstats_needs_flush() here so that flushing
914 * in latency-sensitive paths is as cheap as possible.
916 do_flush_stats(root_mem_cgroup);
917 queue_delayed_work(system_unbound_wq, &stats_flush_dwork, FLUSH_TIME);
920 unsigned long memcg_page_state(struct mem_cgroup *memcg, int idx)
923 int i = memcg_stats_index(idx);
925 if (WARN_ONCE(i < 0, "%s: missing stat item %d\n", __func__, idx))
928 x = READ_ONCE(memcg->vmstats->state[i]);
936 static int memcg_page_state_unit(int item);
939 * Normalize the value passed into memcg_rstat_updated() to be in pages. Round
940 * up non-zero sub-page updates to 1 page as zero page updates are ignored.
942 static int memcg_state_val_in_pages(int idx, int val)
944 int unit = memcg_page_state_unit(idx);
946 if (!val || unit == PAGE_SIZE)
949 return max(val * unit / PAGE_SIZE, 1UL);
953 * __mod_memcg_state - update cgroup memory statistics
954 * @memcg: the memory cgroup
955 * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item
956 * @val: delta to add to the counter, can be negative
958 void __mod_memcg_state(struct mem_cgroup *memcg, enum memcg_stat_item idx,
961 int i = memcg_stats_index(idx);
963 if (mem_cgroup_disabled())
966 if (WARN_ONCE(i < 0, "%s: missing stat item %d\n", __func__, idx))
969 __this_cpu_add(memcg->vmstats_percpu->state[i], val);
970 memcg_rstat_updated(memcg, memcg_state_val_in_pages(idx, val));
973 /* idx can be of type enum memcg_stat_item or node_stat_item. */
974 static unsigned long memcg_page_state_local(struct mem_cgroup *memcg, int idx)
977 int i = memcg_stats_index(idx);
979 if (WARN_ONCE(i < 0, "%s: missing stat item %d\n", __func__, idx))
982 x = READ_ONCE(memcg->vmstats->state_local[i]);
990 static void __mod_memcg_lruvec_state(struct lruvec *lruvec,
991 enum node_stat_item idx,
994 struct mem_cgroup_per_node *pn;
995 struct mem_cgroup *memcg;
996 int i = memcg_stats_index(idx);
998 if (WARN_ONCE(i < 0, "%s: missing stat item %d\n", __func__, idx))
1001 pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
1005 * The caller from rmap relies on disabled preemption because they never
1006 * update their counter from in-interrupt context. For these two
1007 * counters we check that the update is never performed from an
1008 * interrupt context while other caller need to have disabled interrupt.
1010 __memcg_stats_lock();
1011 if (IS_ENABLED(CONFIG_DEBUG_VM)) {
1013 case NR_ANON_MAPPED:
1014 case NR_FILE_MAPPED:
1016 WARN_ON_ONCE(!in_task());
1019 VM_WARN_ON_IRQS_ENABLED();
1024 __this_cpu_add(memcg->vmstats_percpu->state[i], val);
1027 __this_cpu_add(pn->lruvec_stats_percpu->state[i], val);
1029 memcg_rstat_updated(memcg, memcg_state_val_in_pages(idx, val));
1030 memcg_stats_unlock();
1034 * __mod_lruvec_state - update lruvec memory statistics
1035 * @lruvec: the lruvec
1036 * @idx: the stat item
1037 * @val: delta to add to the counter, can be negative
1039 * The lruvec is the intersection of the NUMA node and a cgroup. This
1040 * function updates the all three counters that are affected by a
1041 * change of state at this level: per-node, per-cgroup, per-lruvec.
1043 void __mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
1047 __mod_node_page_state(lruvec_pgdat(lruvec), idx, val);
1049 /* Update memcg and lruvec */
1050 if (!mem_cgroup_disabled())
1051 __mod_memcg_lruvec_state(lruvec, idx, val);
1054 void __lruvec_stat_mod_folio(struct folio *folio, enum node_stat_item idx,
1057 struct mem_cgroup *memcg;
1058 pg_data_t *pgdat = folio_pgdat(folio);
1059 struct lruvec *lruvec;
1062 memcg = folio_memcg(folio);
1063 /* Untracked pages have no memcg, no lruvec. Update only the node */
1066 __mod_node_page_state(pgdat, idx, val);
1070 lruvec = mem_cgroup_lruvec(memcg, pgdat);
1071 __mod_lruvec_state(lruvec, idx, val);
1074 EXPORT_SYMBOL(__lruvec_stat_mod_folio);
1076 void __mod_lruvec_kmem_state(void *p, enum node_stat_item idx, int val)
1078 pg_data_t *pgdat = page_pgdat(virt_to_page(p));
1079 struct mem_cgroup *memcg;
1080 struct lruvec *lruvec;
1083 memcg = mem_cgroup_from_slab_obj(p);
1086 * Untracked pages have no memcg, no lruvec. Update only the
1087 * node. If we reparent the slab objects to the root memcg,
1088 * when we free the slab object, we need to update the per-memcg
1089 * vmstats to keep it correct for the root memcg.
1092 __mod_node_page_state(pgdat, idx, val);
1094 lruvec = mem_cgroup_lruvec(memcg, pgdat);
1095 __mod_lruvec_state(lruvec, idx, val);
1101 * __count_memcg_events - account VM events in a cgroup
1102 * @memcg: the memory cgroup
1103 * @idx: the event item
1104 * @count: the number of events that occurred
1106 void __count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx,
1107 unsigned long count)
1109 int i = memcg_events_index(idx);
1111 if (mem_cgroup_disabled())
1114 if (WARN_ONCE(i < 0, "%s: missing stat item %d\n", __func__, idx))
1118 __this_cpu_add(memcg->vmstats_percpu->events[i], count);
1119 memcg_rstat_updated(memcg, count);
1120 memcg_stats_unlock();
1123 static unsigned long memcg_events(struct mem_cgroup *memcg, int event)
1125 int i = memcg_events_index(event);
1127 if (WARN_ONCE(i < 0, "%s: missing stat item %d\n", __func__, event))
1130 return READ_ONCE(memcg->vmstats->events[i]);
1133 static unsigned long memcg_events_local(struct mem_cgroup *memcg, int event)
1135 int i = memcg_events_index(event);
1137 if (WARN_ONCE(i < 0, "%s: missing stat item %d\n", __func__, event))
1140 return READ_ONCE(memcg->vmstats->events_local[i]);
1143 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
1146 /* pagein of a big page is an event. So, ignore page size */
1148 __count_memcg_events(memcg, PGPGIN, 1);
1150 __count_memcg_events(memcg, PGPGOUT, 1);
1151 nr_pages = -nr_pages; /* for event */
1154 __this_cpu_add(memcg->vmstats_percpu->nr_page_events, nr_pages);
1157 static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
1158 enum mem_cgroup_events_target target)
1160 unsigned long val, next;
1162 val = __this_cpu_read(memcg->vmstats_percpu->nr_page_events);
1163 next = __this_cpu_read(memcg->vmstats_percpu->targets[target]);
1164 /* from time_after() in jiffies.h */
1165 if ((long)(next - val) < 0) {
1167 case MEM_CGROUP_TARGET_THRESH:
1168 next = val + THRESHOLDS_EVENTS_TARGET;
1170 case MEM_CGROUP_TARGET_SOFTLIMIT:
1171 next = val + SOFTLIMIT_EVENTS_TARGET;
1176 __this_cpu_write(memcg->vmstats_percpu->targets[target], next);
1183 * Check events in order.
1186 static void memcg_check_events(struct mem_cgroup *memcg, int nid)
1188 if (IS_ENABLED(CONFIG_PREEMPT_RT))
1191 /* threshold event is triggered in finer grain than soft limit */
1192 if (unlikely(mem_cgroup_event_ratelimit(memcg,
1193 MEM_CGROUP_TARGET_THRESH))) {
1196 do_softlimit = mem_cgroup_event_ratelimit(memcg,
1197 MEM_CGROUP_TARGET_SOFTLIMIT);
1198 mem_cgroup_threshold(memcg);
1199 if (unlikely(do_softlimit))
1200 mem_cgroup_update_tree(memcg, nid);
1204 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
1207 * mm_update_next_owner() may clear mm->owner to NULL
1208 * if it races with swapoff, page migration, etc.
1209 * So this can be called with p == NULL.
1214 return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
1216 EXPORT_SYMBOL(mem_cgroup_from_task);
1218 static __always_inline struct mem_cgroup *active_memcg(void)
1221 return this_cpu_read(int_active_memcg);
1223 return current->active_memcg;
1227 * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
1228 * @mm: mm from which memcg should be extracted. It can be NULL.
1230 * Obtain a reference on mm->memcg and returns it if successful. If mm
1231 * is NULL, then the memcg is chosen as follows:
1232 * 1) The active memcg, if set.
1233 * 2) current->mm->memcg, if available
1235 * If mem_cgroup is disabled, NULL is returned.
1237 struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
1239 struct mem_cgroup *memcg;
1241 if (mem_cgroup_disabled())
1245 * Page cache insertions can happen without an
1246 * actual mm context, e.g. during disk probing
1247 * on boot, loopback IO, acct() writes etc.
1249 * No need to css_get on root memcg as the reference
1250 * counting is disabled on the root level in the
1251 * cgroup core. See CSS_NO_REF.
1253 if (unlikely(!mm)) {
1254 memcg = active_memcg();
1255 if (unlikely(memcg)) {
1256 /* remote memcg must hold a ref */
1257 css_get(&memcg->css);
1262 return root_mem_cgroup;
1267 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1268 if (unlikely(!memcg))
1269 memcg = root_mem_cgroup;
1270 } while (!css_tryget(&memcg->css));
1274 EXPORT_SYMBOL(get_mem_cgroup_from_mm);
1277 * get_mem_cgroup_from_current - Obtain a reference on current task's memcg.
1279 struct mem_cgroup *get_mem_cgroup_from_current(void)
1281 struct mem_cgroup *memcg;
1283 if (mem_cgroup_disabled())
1288 memcg = mem_cgroup_from_task(current);
1289 if (!css_tryget(&memcg->css)) {
1298 * mem_cgroup_iter - iterate over memory cgroup hierarchy
1299 * @root: hierarchy root
1300 * @prev: previously returned memcg, NULL on first invocation
1301 * @reclaim: cookie for shared reclaim walks, NULL for full walks
1303 * Returns references to children of the hierarchy below @root, or
1304 * @root itself, or %NULL after a full round-trip.
1306 * Caller must pass the return value in @prev on subsequent
1307 * invocations for reference counting, or use mem_cgroup_iter_break()
1308 * to cancel a hierarchy walk before the round-trip is complete.
1310 * Reclaimers can specify a node in @reclaim to divide up the memcgs
1311 * in the hierarchy among all concurrent reclaimers operating on the
1314 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
1315 struct mem_cgroup *prev,
1316 struct mem_cgroup_reclaim_cookie *reclaim)
1318 struct mem_cgroup_reclaim_iter *iter;
1319 struct cgroup_subsys_state *css = NULL;
1320 struct mem_cgroup *memcg = NULL;
1321 struct mem_cgroup *pos = NULL;
1323 if (mem_cgroup_disabled())
1327 root = root_mem_cgroup;
1332 struct mem_cgroup_per_node *mz;
1334 mz = root->nodeinfo[reclaim->pgdat->node_id];
1338 * On start, join the current reclaim iteration cycle.
1339 * Exit when a concurrent walker completes it.
1342 reclaim->generation = iter->generation;
1343 else if (reclaim->generation != iter->generation)
1347 pos = READ_ONCE(iter->position);
1348 if (!pos || css_tryget(&pos->css))
1351 * css reference reached zero, so iter->position will
1352 * be cleared by ->css_released. However, we should not
1353 * rely on this happening soon, because ->css_released
1354 * is called from a work queue, and by busy-waiting we
1355 * might block it. So we clear iter->position right
1358 (void)cmpxchg(&iter->position, pos, NULL);
1368 css = css_next_descendant_pre(css, &root->css);
1371 * Reclaimers share the hierarchy walk, and a
1372 * new one might jump in right at the end of
1373 * the hierarchy - make sure they see at least
1374 * one group and restart from the beginning.
1382 * Verify the css and acquire a reference. The root
1383 * is provided by the caller, so we know it's alive
1384 * and kicking, and don't take an extra reference.
1386 if (css == &root->css || css_tryget(css)) {
1387 memcg = mem_cgroup_from_css(css);
1394 * The position could have already been updated by a competing
1395 * thread, so check that the value hasn't changed since we read
1396 * it to avoid reclaiming from the same cgroup twice.
1398 (void)cmpxchg(&iter->position, pos, memcg);
1409 if (prev && prev != root)
1410 css_put(&prev->css);
1416 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1417 * @root: hierarchy root
1418 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1420 void mem_cgroup_iter_break(struct mem_cgroup *root,
1421 struct mem_cgroup *prev)
1424 root = root_mem_cgroup;
1425 if (prev && prev != root)
1426 css_put(&prev->css);
1429 static void __invalidate_reclaim_iterators(struct mem_cgroup *from,
1430 struct mem_cgroup *dead_memcg)
1432 struct mem_cgroup_reclaim_iter *iter;
1433 struct mem_cgroup_per_node *mz;
1436 for_each_node(nid) {
1437 mz = from->nodeinfo[nid];
1439 cmpxchg(&iter->position, dead_memcg, NULL);
1443 static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
1445 struct mem_cgroup *memcg = dead_memcg;
1446 struct mem_cgroup *last;
1449 __invalidate_reclaim_iterators(memcg, dead_memcg);
1451 } while ((memcg = parent_mem_cgroup(memcg)));
1454 * When cgroup1 non-hierarchy mode is used,
1455 * parent_mem_cgroup() does not walk all the way up to the
1456 * cgroup root (root_mem_cgroup). So we have to handle
1457 * dead_memcg from cgroup root separately.
1459 if (!mem_cgroup_is_root(last))
1460 __invalidate_reclaim_iterators(root_mem_cgroup,
1465 * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
1466 * @memcg: hierarchy root
1467 * @fn: function to call for each task
1468 * @arg: argument passed to @fn
1470 * This function iterates over tasks attached to @memcg or to any of its
1471 * descendants and calls @fn for each task. If @fn returns a non-zero
1472 * value, the function breaks the iteration loop. Otherwise, it will iterate
1473 * over all tasks and return 0.
1475 * This function must not be called for the root memory cgroup.
1477 void mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
1478 int (*fn)(struct task_struct *, void *), void *arg)
1480 struct mem_cgroup *iter;
1483 BUG_ON(mem_cgroup_is_root(memcg));
1485 for_each_mem_cgroup_tree(iter, memcg) {
1486 struct css_task_iter it;
1487 struct task_struct *task;
1489 css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it);
1490 while (!ret && (task = css_task_iter_next(&it)))
1491 ret = fn(task, arg);
1492 css_task_iter_end(&it);
1494 mem_cgroup_iter_break(memcg, iter);
1500 #ifdef CONFIG_DEBUG_VM
1501 void lruvec_memcg_debug(struct lruvec *lruvec, struct folio *folio)
1503 struct mem_cgroup *memcg;
1505 if (mem_cgroup_disabled())
1508 memcg = folio_memcg(folio);
1511 VM_BUG_ON_FOLIO(!mem_cgroup_is_root(lruvec_memcg(lruvec)), folio);
1513 VM_BUG_ON_FOLIO(lruvec_memcg(lruvec) != memcg, folio);
1518 * folio_lruvec_lock - Lock the lruvec for a folio.
1519 * @folio: Pointer to the folio.
1521 * These functions are safe to use under any of the following conditions:
1523 * - folio_test_lru false
1524 * - folio_memcg_lock()
1525 * - folio frozen (refcount of 0)
1527 * Return: The lruvec this folio is on with its lock held.
1529 struct lruvec *folio_lruvec_lock(struct folio *folio)
1531 struct lruvec *lruvec = folio_lruvec(folio);
1533 spin_lock(&lruvec->lru_lock);
1534 lruvec_memcg_debug(lruvec, folio);
1540 * folio_lruvec_lock_irq - Lock the lruvec for a folio.
1541 * @folio: Pointer to the folio.
1543 * These functions are safe to use under any of the following conditions:
1545 * - folio_test_lru false
1546 * - folio_memcg_lock()
1547 * - folio frozen (refcount of 0)
1549 * Return: The lruvec this folio is on with its lock held and interrupts
1552 struct lruvec *folio_lruvec_lock_irq(struct folio *folio)
1554 struct lruvec *lruvec = folio_lruvec(folio);
1556 spin_lock_irq(&lruvec->lru_lock);
1557 lruvec_memcg_debug(lruvec, folio);
1563 * folio_lruvec_lock_irqsave - Lock the lruvec for a folio.
1564 * @folio: Pointer to the folio.
1565 * @flags: Pointer to irqsave flags.
1567 * These functions are safe to use under any of the following conditions:
1569 * - folio_test_lru false
1570 * - folio_memcg_lock()
1571 * - folio frozen (refcount of 0)
1573 * Return: The lruvec this folio is on with its lock held and interrupts
1576 struct lruvec *folio_lruvec_lock_irqsave(struct folio *folio,
1577 unsigned long *flags)
1579 struct lruvec *lruvec = folio_lruvec(folio);
1581 spin_lock_irqsave(&lruvec->lru_lock, *flags);
1582 lruvec_memcg_debug(lruvec, folio);
1588 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1589 * @lruvec: mem_cgroup per zone lru vector
1590 * @lru: index of lru list the page is sitting on
1591 * @zid: zone id of the accounted pages
1592 * @nr_pages: positive when adding or negative when removing
1594 * This function must be called under lru_lock, just before a page is added
1595 * to or just after a page is removed from an lru list.
1597 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1598 int zid, int nr_pages)
1600 struct mem_cgroup_per_node *mz;
1601 unsigned long *lru_size;
1604 if (mem_cgroup_disabled())
1607 mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
1608 lru_size = &mz->lru_zone_size[zid][lru];
1611 *lru_size += nr_pages;
1614 if (WARN_ONCE(size < 0,
1615 "%s(%p, %d, %d): lru_size %ld\n",
1616 __func__, lruvec, lru, nr_pages, size)) {
1622 *lru_size += nr_pages;
1626 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1627 * @memcg: the memory cgroup
1629 * Returns the maximum amount of memory @mem can be charged with, in
1632 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1634 unsigned long margin = 0;
1635 unsigned long count;
1636 unsigned long limit;
1638 count = page_counter_read(&memcg->memory);
1639 limit = READ_ONCE(memcg->memory.max);
1641 margin = limit - count;
1643 if (do_memsw_account()) {
1644 count = page_counter_read(&memcg->memsw);
1645 limit = READ_ONCE(memcg->memsw.max);
1647 margin = min(margin, limit - count);
1656 * A routine for checking "mem" is under move_account() or not.
1658 * Checking a cgroup is mc.from or mc.to or under hierarchy of
1659 * moving cgroups. This is for waiting at high-memory pressure
1662 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1664 struct mem_cgroup *from;
1665 struct mem_cgroup *to;
1668 * Unlike task_move routines, we access mc.to, mc.from not under
1669 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1671 spin_lock(&mc.lock);
1677 ret = mem_cgroup_is_descendant(from, memcg) ||
1678 mem_cgroup_is_descendant(to, memcg);
1680 spin_unlock(&mc.lock);
1684 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1686 if (mc.moving_task && current != mc.moving_task) {
1687 if (mem_cgroup_under_move(memcg)) {
1689 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1690 /* moving charge context might have finished. */
1693 finish_wait(&mc.waitq, &wait);
1700 struct memory_stat {
1705 static const struct memory_stat memory_stats[] = {
1706 { "anon", NR_ANON_MAPPED },
1707 { "file", NR_FILE_PAGES },
1708 { "kernel", MEMCG_KMEM },
1709 { "kernel_stack", NR_KERNEL_STACK_KB },
1710 { "pagetables", NR_PAGETABLE },
1711 { "sec_pagetables", NR_SECONDARY_PAGETABLE },
1712 { "percpu", MEMCG_PERCPU_B },
1713 { "sock", MEMCG_SOCK },
1714 { "vmalloc", MEMCG_VMALLOC },
1715 { "shmem", NR_SHMEM },
1716 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
1717 { "zswap", MEMCG_ZSWAP_B },
1718 { "zswapped", MEMCG_ZSWAPPED },
1720 { "file_mapped", NR_FILE_MAPPED },
1721 { "file_dirty", NR_FILE_DIRTY },
1722 { "file_writeback", NR_WRITEBACK },
1724 { "swapcached", NR_SWAPCACHE },
1726 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1727 { "anon_thp", NR_ANON_THPS },
1728 { "file_thp", NR_FILE_THPS },
1729 { "shmem_thp", NR_SHMEM_THPS },
1731 { "inactive_anon", NR_INACTIVE_ANON },
1732 { "active_anon", NR_ACTIVE_ANON },
1733 { "inactive_file", NR_INACTIVE_FILE },
1734 { "active_file", NR_ACTIVE_FILE },
1735 { "unevictable", NR_UNEVICTABLE },
1736 { "slab_reclaimable", NR_SLAB_RECLAIMABLE_B },
1737 { "slab_unreclaimable", NR_SLAB_UNRECLAIMABLE_B },
1739 /* The memory events */
1740 { "workingset_refault_anon", WORKINGSET_REFAULT_ANON },
1741 { "workingset_refault_file", WORKINGSET_REFAULT_FILE },
1742 { "workingset_activate_anon", WORKINGSET_ACTIVATE_ANON },
1743 { "workingset_activate_file", WORKINGSET_ACTIVATE_FILE },
1744 { "workingset_restore_anon", WORKINGSET_RESTORE_ANON },
1745 { "workingset_restore_file", WORKINGSET_RESTORE_FILE },
1746 { "workingset_nodereclaim", WORKINGSET_NODERECLAIM },
1749 /* The actual unit of the state item, not the same as the output unit */
1750 static int memcg_page_state_unit(int item)
1753 case MEMCG_PERCPU_B:
1755 case NR_SLAB_RECLAIMABLE_B:
1756 case NR_SLAB_UNRECLAIMABLE_B:
1758 case NR_KERNEL_STACK_KB:
1765 /* Translate stat items to the correct unit for memory.stat output */
1766 static int memcg_page_state_output_unit(int item)
1769 * Workingset state is actually in pages, but we export it to userspace
1770 * as a scalar count of events, so special case it here.
1773 case WORKINGSET_REFAULT_ANON:
1774 case WORKINGSET_REFAULT_FILE:
1775 case WORKINGSET_ACTIVATE_ANON:
1776 case WORKINGSET_ACTIVATE_FILE:
1777 case WORKINGSET_RESTORE_ANON:
1778 case WORKINGSET_RESTORE_FILE:
1779 case WORKINGSET_NODERECLAIM:
1782 return memcg_page_state_unit(item);
1786 static inline unsigned long memcg_page_state_output(struct mem_cgroup *memcg,
1789 return memcg_page_state(memcg, item) *
1790 memcg_page_state_output_unit(item);
1793 static inline unsigned long memcg_page_state_local_output(
1794 struct mem_cgroup *memcg, int item)
1796 return memcg_page_state_local(memcg, item) *
1797 memcg_page_state_output_unit(item);
1800 static void memcg_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
1805 * Provide statistics on the state of the memory subsystem as
1806 * well as cumulative event counters that show past behavior.
1808 * This list is ordered following a combination of these gradients:
1809 * 1) generic big picture -> specifics and details
1810 * 2) reflecting userspace activity -> reflecting kernel heuristics
1812 * Current memory state:
1814 mem_cgroup_flush_stats(memcg);
1816 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
1819 size = memcg_page_state_output(memcg, memory_stats[i].idx);
1820 seq_buf_printf(s, "%s %llu\n", memory_stats[i].name, size);
1822 if (unlikely(memory_stats[i].idx == NR_SLAB_UNRECLAIMABLE_B)) {
1823 size += memcg_page_state_output(memcg,
1824 NR_SLAB_RECLAIMABLE_B);
1825 seq_buf_printf(s, "slab %llu\n", size);
1829 /* Accumulated memory events */
1830 seq_buf_printf(s, "pgscan %lu\n",
1831 memcg_events(memcg, PGSCAN_KSWAPD) +
1832 memcg_events(memcg, PGSCAN_DIRECT) +
1833 memcg_events(memcg, PGSCAN_KHUGEPAGED));
1834 seq_buf_printf(s, "pgsteal %lu\n",
1835 memcg_events(memcg, PGSTEAL_KSWAPD) +
1836 memcg_events(memcg, PGSTEAL_DIRECT) +
1837 memcg_events(memcg, PGSTEAL_KHUGEPAGED));
1839 for (i = 0; i < ARRAY_SIZE(memcg_vm_event_stat); i++) {
1840 if (memcg_vm_event_stat[i] == PGPGIN ||
1841 memcg_vm_event_stat[i] == PGPGOUT)
1844 seq_buf_printf(s, "%s %lu\n",
1845 vm_event_name(memcg_vm_event_stat[i]),
1846 memcg_events(memcg, memcg_vm_event_stat[i]));
1849 /* The above should easily fit into one page */
1850 WARN_ON_ONCE(seq_buf_has_overflowed(s));
1853 static void memcg1_stat_format(struct mem_cgroup *memcg, struct seq_buf *s);
1855 static void memory_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
1857 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1858 memcg_stat_format(memcg, s);
1860 memcg1_stat_format(memcg, s);
1861 WARN_ON_ONCE(seq_buf_has_overflowed(s));
1865 * mem_cgroup_print_oom_context: Print OOM information relevant to
1866 * memory controller.
1867 * @memcg: The memory cgroup that went over limit
1868 * @p: Task that is going to be killed
1870 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1873 void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p)
1878 pr_cont(",oom_memcg=");
1879 pr_cont_cgroup_path(memcg->css.cgroup);
1881 pr_cont(",global_oom");
1883 pr_cont(",task_memcg=");
1884 pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
1890 * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
1891 * memory controller.
1892 * @memcg: The memory cgroup that went over limit
1894 void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
1896 /* Use static buffer, for the caller is holding oom_lock. */
1897 static char buf[PAGE_SIZE];
1900 lockdep_assert_held(&oom_lock);
1902 pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1903 K((u64)page_counter_read(&memcg->memory)),
1904 K((u64)READ_ONCE(memcg->memory.max)), memcg->memory.failcnt);
1905 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1906 pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n",
1907 K((u64)page_counter_read(&memcg->swap)),
1908 K((u64)READ_ONCE(memcg->swap.max)), memcg->swap.failcnt);
1910 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1911 K((u64)page_counter_read(&memcg->memsw)),
1912 K((u64)memcg->memsw.max), memcg->memsw.failcnt);
1913 pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1914 K((u64)page_counter_read(&memcg->kmem)),
1915 K((u64)memcg->kmem.max), memcg->kmem.failcnt);
1918 pr_info("Memory cgroup stats for ");
1919 pr_cont_cgroup_path(memcg->css.cgroup);
1921 seq_buf_init(&s, buf, sizeof(buf));
1922 memory_stat_format(memcg, &s);
1923 seq_buf_do_printk(&s, KERN_INFO);
1927 * Return the memory (and swap, if configured) limit for a memcg.
1929 unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg)
1931 unsigned long max = READ_ONCE(memcg->memory.max);
1933 if (do_memsw_account()) {
1934 if (mem_cgroup_swappiness(memcg)) {
1935 /* Calculate swap excess capacity from memsw limit */
1936 unsigned long swap = READ_ONCE(memcg->memsw.max) - max;
1938 max += min(swap, (unsigned long)total_swap_pages);
1941 if (mem_cgroup_swappiness(memcg))
1942 max += min(READ_ONCE(memcg->swap.max),
1943 (unsigned long)total_swap_pages);
1948 unsigned long mem_cgroup_size(struct mem_cgroup *memcg)
1950 return page_counter_read(&memcg->memory);
1953 static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1956 struct oom_control oc = {
1960 .gfp_mask = gfp_mask,
1965 if (mutex_lock_killable(&oom_lock))
1968 if (mem_cgroup_margin(memcg) >= (1 << order))
1972 * A few threads which were not waiting at mutex_lock_killable() can
1973 * fail to bail out. Therefore, check again after holding oom_lock.
1975 ret = task_is_dying() || out_of_memory(&oc);
1978 mutex_unlock(&oom_lock);
1982 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
1985 unsigned long *total_scanned)
1987 struct mem_cgroup *victim = NULL;
1990 unsigned long excess;
1991 unsigned long nr_scanned;
1992 struct mem_cgroup_reclaim_cookie reclaim = {
1996 excess = soft_limit_excess(root_memcg);
1999 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
2004 * If we have not been able to reclaim
2005 * anything, it might because there are
2006 * no reclaimable pages under this hierarchy
2011 * We want to do more targeted reclaim.
2012 * excess >> 2 is not to excessive so as to
2013 * reclaim too much, nor too less that we keep
2014 * coming back to reclaim from this cgroup
2016 if (total >= (excess >> 2) ||
2017 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
2022 total += mem_cgroup_shrink_node(victim, gfp_mask, false,
2023 pgdat, &nr_scanned);
2024 *total_scanned += nr_scanned;
2025 if (!soft_limit_excess(root_memcg))
2028 mem_cgroup_iter_break(root_memcg, victim);
2032 #ifdef CONFIG_LOCKDEP
2033 static struct lockdep_map memcg_oom_lock_dep_map = {
2034 .name = "memcg_oom_lock",
2038 static DEFINE_SPINLOCK(memcg_oom_lock);
2041 * Check OOM-Killer is already running under our hierarchy.
2042 * If someone is running, return false.
2044 static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
2046 struct mem_cgroup *iter, *failed = NULL;
2048 spin_lock(&memcg_oom_lock);
2050 for_each_mem_cgroup_tree(iter, memcg) {
2051 if (iter->oom_lock) {
2053 * this subtree of our hierarchy is already locked
2054 * so we cannot give a lock.
2057 mem_cgroup_iter_break(memcg, iter);
2060 iter->oom_lock = true;
2065 * OK, we failed to lock the whole subtree so we have
2066 * to clean up what we set up to the failing subtree
2068 for_each_mem_cgroup_tree(iter, memcg) {
2069 if (iter == failed) {
2070 mem_cgroup_iter_break(memcg, iter);
2073 iter->oom_lock = false;
2076 mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
2078 spin_unlock(&memcg_oom_lock);
2083 static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
2085 struct mem_cgroup *iter;
2087 spin_lock(&memcg_oom_lock);
2088 mutex_release(&memcg_oom_lock_dep_map, _RET_IP_);
2089 for_each_mem_cgroup_tree(iter, memcg)
2090 iter->oom_lock = false;
2091 spin_unlock(&memcg_oom_lock);
2094 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
2096 struct mem_cgroup *iter;
2098 spin_lock(&memcg_oom_lock);
2099 for_each_mem_cgroup_tree(iter, memcg)
2101 spin_unlock(&memcg_oom_lock);
2104 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
2106 struct mem_cgroup *iter;
2109 * Be careful about under_oom underflows because a child memcg
2110 * could have been added after mem_cgroup_mark_under_oom.
2112 spin_lock(&memcg_oom_lock);
2113 for_each_mem_cgroup_tree(iter, memcg)
2114 if (iter->under_oom > 0)
2116 spin_unlock(&memcg_oom_lock);
2119 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
2121 struct oom_wait_info {
2122 struct mem_cgroup *memcg;
2123 wait_queue_entry_t wait;
2126 static int memcg_oom_wake_function(wait_queue_entry_t *wait,
2127 unsigned mode, int sync, void *arg)
2129 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
2130 struct mem_cgroup *oom_wait_memcg;
2131 struct oom_wait_info *oom_wait_info;
2133 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
2134 oom_wait_memcg = oom_wait_info->memcg;
2136 if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
2137 !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
2139 return autoremove_wake_function(wait, mode, sync, arg);
2142 static void memcg_oom_recover(struct mem_cgroup *memcg)
2145 * For the following lockless ->under_oom test, the only required
2146 * guarantee is that it must see the state asserted by an OOM when
2147 * this function is called as a result of userland actions
2148 * triggered by the notification of the OOM. This is trivially
2149 * achieved by invoking mem_cgroup_mark_under_oom() before
2150 * triggering notification.
2152 if (memcg && memcg->under_oom)
2153 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
2157 * Returns true if successfully killed one or more processes. Though in some
2158 * corner cases it can return true even without killing any process.
2160 static bool mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
2164 if (order > PAGE_ALLOC_COSTLY_ORDER)
2167 memcg_memory_event(memcg, MEMCG_OOM);
2170 * We are in the middle of the charge context here, so we
2171 * don't want to block when potentially sitting on a callstack
2172 * that holds all kinds of filesystem and mm locks.
2174 * cgroup1 allows disabling the OOM killer and waiting for outside
2175 * handling until the charge can succeed; remember the context and put
2176 * the task to sleep at the end of the page fault when all locks are
2179 * On the other hand, in-kernel OOM killer allows for an async victim
2180 * memory reclaim (oom_reaper) and that means that we are not solely
2181 * relying on the oom victim to make a forward progress and we can
2182 * invoke the oom killer here.
2184 * Please note that mem_cgroup_out_of_memory might fail to find a
2185 * victim and then we have to bail out from the charge path.
2187 if (READ_ONCE(memcg->oom_kill_disable)) {
2188 if (current->in_user_fault) {
2189 css_get(&memcg->css);
2190 current->memcg_in_oom = memcg;
2195 mem_cgroup_mark_under_oom(memcg);
2197 locked = mem_cgroup_oom_trylock(memcg);
2200 mem_cgroup_oom_notify(memcg);
2202 mem_cgroup_unmark_under_oom(memcg);
2203 ret = mem_cgroup_out_of_memory(memcg, mask, order);
2206 mem_cgroup_oom_unlock(memcg);
2212 * mem_cgroup_oom_synchronize - complete memcg OOM handling
2213 * @handle: actually kill/wait or just clean up the OOM state
2215 * This has to be called at the end of a page fault if the memcg OOM
2216 * handler was enabled.
2218 * Memcg supports userspace OOM handling where failed allocations must
2219 * sleep on a waitqueue until the userspace task resolves the
2220 * situation. Sleeping directly in the charge context with all kinds
2221 * of locks held is not a good idea, instead we remember an OOM state
2222 * in the task and mem_cgroup_oom_synchronize() has to be called at
2223 * the end of the page fault to complete the OOM handling.
2225 * Returns %true if an ongoing memcg OOM situation was detected and
2226 * completed, %false otherwise.
2228 bool mem_cgroup_oom_synchronize(bool handle)
2230 struct mem_cgroup *memcg = current->memcg_in_oom;
2231 struct oom_wait_info owait;
2234 /* OOM is global, do not handle */
2241 owait.memcg = memcg;
2242 owait.wait.flags = 0;
2243 owait.wait.func = memcg_oom_wake_function;
2244 owait.wait.private = current;
2245 INIT_LIST_HEAD(&owait.wait.entry);
2247 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
2248 mem_cgroup_mark_under_oom(memcg);
2250 locked = mem_cgroup_oom_trylock(memcg);
2253 mem_cgroup_oom_notify(memcg);
2256 mem_cgroup_unmark_under_oom(memcg);
2257 finish_wait(&memcg_oom_waitq, &owait.wait);
2260 mem_cgroup_oom_unlock(memcg);
2262 current->memcg_in_oom = NULL;
2263 css_put(&memcg->css);
2268 * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
2269 * @victim: task to be killed by the OOM killer
2270 * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
2272 * Returns a pointer to a memory cgroup, which has to be cleaned up
2273 * by killing all belonging OOM-killable tasks.
2275 * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
2277 struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim,
2278 struct mem_cgroup *oom_domain)
2280 struct mem_cgroup *oom_group = NULL;
2281 struct mem_cgroup *memcg;
2283 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
2287 oom_domain = root_mem_cgroup;
2291 memcg = mem_cgroup_from_task(victim);
2292 if (mem_cgroup_is_root(memcg))
2296 * If the victim task has been asynchronously moved to a different
2297 * memory cgroup, we might end up killing tasks outside oom_domain.
2298 * In this case it's better to ignore memory.group.oom.
2300 if (unlikely(!mem_cgroup_is_descendant(memcg, oom_domain)))
2304 * Traverse the memory cgroup hierarchy from the victim task's
2305 * cgroup up to the OOMing cgroup (or root) to find the
2306 * highest-level memory cgroup with oom.group set.
2308 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
2309 if (READ_ONCE(memcg->oom_group))
2312 if (memcg == oom_domain)
2317 css_get(&oom_group->css);
2324 void mem_cgroup_print_oom_group(struct mem_cgroup *memcg)
2326 pr_info("Tasks in ");
2327 pr_cont_cgroup_path(memcg->css.cgroup);
2328 pr_cont(" are going to be killed due to memory.oom.group set\n");
2332 * folio_memcg_lock - Bind a folio to its memcg.
2333 * @folio: The folio.
2335 * This function prevents unlocked LRU folios from being moved to
2338 * It ensures lifetime of the bound memcg. The caller is responsible
2339 * for the lifetime of the folio.
2341 void folio_memcg_lock(struct folio *folio)
2343 struct mem_cgroup *memcg;
2344 unsigned long flags;
2347 * The RCU lock is held throughout the transaction. The fast
2348 * path can get away without acquiring the memcg->move_lock
2349 * because page moving starts with an RCU grace period.
2353 if (mem_cgroup_disabled())
2356 memcg = folio_memcg(folio);
2357 if (unlikely(!memcg))
2360 #ifdef CONFIG_PROVE_LOCKING
2361 local_irq_save(flags);
2362 might_lock(&memcg->move_lock);
2363 local_irq_restore(flags);
2366 if (atomic_read(&memcg->moving_account) <= 0)
2369 spin_lock_irqsave(&memcg->move_lock, flags);
2370 if (memcg != folio_memcg(folio)) {
2371 spin_unlock_irqrestore(&memcg->move_lock, flags);
2376 * When charge migration first begins, we can have multiple
2377 * critical sections holding the fast-path RCU lock and one
2378 * holding the slowpath move_lock. Track the task who has the
2379 * move_lock for folio_memcg_unlock().
2381 memcg->move_lock_task = current;
2382 memcg->move_lock_flags = flags;
2385 static void __folio_memcg_unlock(struct mem_cgroup *memcg)
2387 if (memcg && memcg->move_lock_task == current) {
2388 unsigned long flags = memcg->move_lock_flags;
2390 memcg->move_lock_task = NULL;
2391 memcg->move_lock_flags = 0;
2393 spin_unlock_irqrestore(&memcg->move_lock, flags);
2400 * folio_memcg_unlock - Release the binding between a folio and its memcg.
2401 * @folio: The folio.
2403 * This releases the binding created by folio_memcg_lock(). This does
2404 * not change the accounting of this folio to its memcg, but it does
2405 * permit others to change it.
2407 void folio_memcg_unlock(struct folio *folio)
2409 __folio_memcg_unlock(folio_memcg(folio));
2412 struct memcg_stock_pcp {
2413 local_lock_t stock_lock;
2414 struct mem_cgroup *cached; /* this never be root cgroup */
2415 unsigned int nr_pages;
2417 #ifdef CONFIG_MEMCG_KMEM
2418 struct obj_cgroup *cached_objcg;
2419 struct pglist_data *cached_pgdat;
2420 unsigned int nr_bytes;
2421 int nr_slab_reclaimable_b;
2422 int nr_slab_unreclaimable_b;
2425 struct work_struct work;
2426 unsigned long flags;
2427 #define FLUSHING_CACHED_CHARGE 0
2429 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock) = {
2430 .stock_lock = INIT_LOCAL_LOCK(stock_lock),
2432 static DEFINE_MUTEX(percpu_charge_mutex);
2434 #ifdef CONFIG_MEMCG_KMEM
2435 static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock);
2436 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2437 struct mem_cgroup *root_memcg);
2438 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages);
2441 static inline struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock)
2445 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2446 struct mem_cgroup *root_memcg)
2450 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages)
2456 * consume_stock: Try to consume stocked charge on this cpu.
2457 * @memcg: memcg to consume from.
2458 * @nr_pages: how many pages to charge.
2460 * The charges will only happen if @memcg matches the current cpu's memcg
2461 * stock, and at least @nr_pages are available in that stock. Failure to
2462 * service an allocation will refill the stock.
2464 * returns true if successful, false otherwise.
2466 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2468 struct memcg_stock_pcp *stock;
2469 unsigned int stock_pages;
2470 unsigned long flags;
2473 if (nr_pages > MEMCG_CHARGE_BATCH)
2476 local_lock_irqsave(&memcg_stock.stock_lock, flags);
2478 stock = this_cpu_ptr(&memcg_stock);
2479 stock_pages = READ_ONCE(stock->nr_pages);
2480 if (memcg == READ_ONCE(stock->cached) && stock_pages >= nr_pages) {
2481 WRITE_ONCE(stock->nr_pages, stock_pages - nr_pages);
2485 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2491 * Returns stocks cached in percpu and reset cached information.
2493 static void drain_stock(struct memcg_stock_pcp *stock)
2495 unsigned int stock_pages = READ_ONCE(stock->nr_pages);
2496 struct mem_cgroup *old = READ_ONCE(stock->cached);
2502 page_counter_uncharge(&old->memory, stock_pages);
2503 if (do_memsw_account())
2504 page_counter_uncharge(&old->memsw, stock_pages);
2506 WRITE_ONCE(stock->nr_pages, 0);
2510 WRITE_ONCE(stock->cached, NULL);
2513 static void drain_local_stock(struct work_struct *dummy)
2515 struct memcg_stock_pcp *stock;
2516 struct obj_cgroup *old = NULL;
2517 unsigned long flags;
2520 * The only protection from cpu hotplug (memcg_hotplug_cpu_dead) vs.
2521 * drain_stock races is that we always operate on local CPU stock
2522 * here with IRQ disabled
2524 local_lock_irqsave(&memcg_stock.stock_lock, flags);
2526 stock = this_cpu_ptr(&memcg_stock);
2527 old = drain_obj_stock(stock);
2529 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2531 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2532 obj_cgroup_put(old);
2536 * Cache charges(val) to local per_cpu area.
2537 * This will be consumed by consume_stock() function, later.
2539 static void __refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2541 struct memcg_stock_pcp *stock;
2542 unsigned int stock_pages;
2544 stock = this_cpu_ptr(&memcg_stock);
2545 if (READ_ONCE(stock->cached) != memcg) { /* reset if necessary */
2547 css_get(&memcg->css);
2548 WRITE_ONCE(stock->cached, memcg);
2550 stock_pages = READ_ONCE(stock->nr_pages) + nr_pages;
2551 WRITE_ONCE(stock->nr_pages, stock_pages);
2553 if (stock_pages > MEMCG_CHARGE_BATCH)
2557 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2559 unsigned long flags;
2561 local_lock_irqsave(&memcg_stock.stock_lock, flags);
2562 __refill_stock(memcg, nr_pages);
2563 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2567 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2568 * of the hierarchy under it.
2570 static void drain_all_stock(struct mem_cgroup *root_memcg)
2574 /* If someone's already draining, avoid adding running more workers. */
2575 if (!mutex_trylock(&percpu_charge_mutex))
2578 * Notify other cpus that system-wide "drain" is running
2579 * We do not care about races with the cpu hotplug because cpu down
2580 * as well as workers from this path always operate on the local
2581 * per-cpu data. CPU up doesn't touch memcg_stock at all.
2584 curcpu = smp_processor_id();
2585 for_each_online_cpu(cpu) {
2586 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2587 struct mem_cgroup *memcg;
2591 memcg = READ_ONCE(stock->cached);
2592 if (memcg && READ_ONCE(stock->nr_pages) &&
2593 mem_cgroup_is_descendant(memcg, root_memcg))
2595 else if (obj_stock_flush_required(stock, root_memcg))
2600 !test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2602 drain_local_stock(&stock->work);
2603 else if (!cpu_is_isolated(cpu))
2604 schedule_work_on(cpu, &stock->work);
2608 mutex_unlock(&percpu_charge_mutex);
2611 static int memcg_hotplug_cpu_dead(unsigned int cpu)
2613 struct memcg_stock_pcp *stock;
2615 stock = &per_cpu(memcg_stock, cpu);
2621 static unsigned long reclaim_high(struct mem_cgroup *memcg,
2622 unsigned int nr_pages,
2625 unsigned long nr_reclaimed = 0;
2628 unsigned long pflags;
2630 if (page_counter_read(&memcg->memory) <=
2631 READ_ONCE(memcg->memory.high))
2634 memcg_memory_event(memcg, MEMCG_HIGH);
2636 psi_memstall_enter(&pflags);
2637 nr_reclaimed += try_to_free_mem_cgroup_pages(memcg, nr_pages,
2639 MEMCG_RECLAIM_MAY_SWAP);
2640 psi_memstall_leave(&pflags);
2641 } while ((memcg = parent_mem_cgroup(memcg)) &&
2642 !mem_cgroup_is_root(memcg));
2644 return nr_reclaimed;
2647 static void high_work_func(struct work_struct *work)
2649 struct mem_cgroup *memcg;
2651 memcg = container_of(work, struct mem_cgroup, high_work);
2652 reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
2656 * Clamp the maximum sleep time per allocation batch to 2 seconds. This is
2657 * enough to still cause a significant slowdown in most cases, while still
2658 * allowing diagnostics and tracing to proceed without becoming stuck.
2660 #define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ)
2663 * When calculating the delay, we use these either side of the exponentiation to
2664 * maintain precision and scale to a reasonable number of jiffies (see the table
2667 * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the
2668 * overage ratio to a delay.
2669 * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down the
2670 * proposed penalty in order to reduce to a reasonable number of jiffies, and
2671 * to produce a reasonable delay curve.
2673 * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a
2674 * reasonable delay curve compared to precision-adjusted overage, not
2675 * penalising heavily at first, but still making sure that growth beyond the
2676 * limit penalises misbehaviour cgroups by slowing them down exponentially. For
2677 * example, with a high of 100 megabytes:
2679 * +-------+------------------------+
2680 * | usage | time to allocate in ms |
2681 * +-------+------------------------+
2703 * +-------+------------------------+
2705 #define MEMCG_DELAY_PRECISION_SHIFT 20
2706 #define MEMCG_DELAY_SCALING_SHIFT 14
2708 static u64 calculate_overage(unsigned long usage, unsigned long high)
2716 * Prevent division by 0 in overage calculation by acting as if
2717 * it was a threshold of 1 page
2719 high = max(high, 1UL);
2721 overage = usage - high;
2722 overage <<= MEMCG_DELAY_PRECISION_SHIFT;
2723 return div64_u64(overage, high);
2726 static u64 mem_find_max_overage(struct mem_cgroup *memcg)
2728 u64 overage, max_overage = 0;
2731 overage = calculate_overage(page_counter_read(&memcg->memory),
2732 READ_ONCE(memcg->memory.high));
2733 max_overage = max(overage, max_overage);
2734 } while ((memcg = parent_mem_cgroup(memcg)) &&
2735 !mem_cgroup_is_root(memcg));
2740 static u64 swap_find_max_overage(struct mem_cgroup *memcg)
2742 u64 overage, max_overage = 0;
2745 overage = calculate_overage(page_counter_read(&memcg->swap),
2746 READ_ONCE(memcg->swap.high));
2748 memcg_memory_event(memcg, MEMCG_SWAP_HIGH);
2749 max_overage = max(overage, max_overage);
2750 } while ((memcg = parent_mem_cgroup(memcg)) &&
2751 !mem_cgroup_is_root(memcg));
2757 * Get the number of jiffies that we should penalise a mischievous cgroup which
2758 * is exceeding its memory.high by checking both it and its ancestors.
2760 static unsigned long calculate_high_delay(struct mem_cgroup *memcg,
2761 unsigned int nr_pages,
2764 unsigned long penalty_jiffies;
2770 * We use overage compared to memory.high to calculate the number of
2771 * jiffies to sleep (penalty_jiffies). Ideally this value should be
2772 * fairly lenient on small overages, and increasingly harsh when the
2773 * memcg in question makes it clear that it has no intention of stopping
2774 * its crazy behaviour, so we exponentially increase the delay based on
2777 penalty_jiffies = max_overage * max_overage * HZ;
2778 penalty_jiffies >>= MEMCG_DELAY_PRECISION_SHIFT;
2779 penalty_jiffies >>= MEMCG_DELAY_SCALING_SHIFT;
2782 * Factor in the task's own contribution to the overage, such that four
2783 * N-sized allocations are throttled approximately the same as one
2784 * 4N-sized allocation.
2786 * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or
2787 * larger the current charge patch is than that.
2789 return penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH;
2793 * Reclaims memory over the high limit. Called directly from
2794 * try_charge() (context permitting), as well as from the userland
2795 * return path where reclaim is always able to block.
2797 void mem_cgroup_handle_over_high(gfp_t gfp_mask)
2799 unsigned long penalty_jiffies;
2800 unsigned long pflags;
2801 unsigned long nr_reclaimed;
2802 unsigned int nr_pages = current->memcg_nr_pages_over_high;
2803 int nr_retries = MAX_RECLAIM_RETRIES;
2804 struct mem_cgroup *memcg;
2805 bool in_retry = false;
2807 if (likely(!nr_pages))
2810 memcg = get_mem_cgroup_from_mm(current->mm);
2811 current->memcg_nr_pages_over_high = 0;
2815 * Bail if the task is already exiting. Unlike memory.max,
2816 * memory.high enforcement isn't as strict, and there is no
2817 * OOM killer involved, which means the excess could already
2818 * be much bigger (and still growing) than it could for
2819 * memory.max; the dying task could get stuck in fruitless
2820 * reclaim for a long time, which isn't desirable.
2822 if (task_is_dying())
2826 * The allocating task should reclaim at least the batch size, but for
2827 * subsequent retries we only want to do what's necessary to prevent oom
2828 * or breaching resource isolation.
2830 * This is distinct from memory.max or page allocator behaviour because
2831 * memory.high is currently batched, whereas memory.max and the page
2832 * allocator run every time an allocation is made.
2834 nr_reclaimed = reclaim_high(memcg,
2835 in_retry ? SWAP_CLUSTER_MAX : nr_pages,
2839 * memory.high is breached and reclaim is unable to keep up. Throttle
2840 * allocators proactively to slow down excessive growth.
2842 penalty_jiffies = calculate_high_delay(memcg, nr_pages,
2843 mem_find_max_overage(memcg));
2845 penalty_jiffies += calculate_high_delay(memcg, nr_pages,
2846 swap_find_max_overage(memcg));
2849 * Clamp the max delay per usermode return so as to still keep the
2850 * application moving forwards and also permit diagnostics, albeit
2853 penalty_jiffies = min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES);
2856 * Don't sleep if the amount of jiffies this memcg owes us is so low
2857 * that it's not even worth doing, in an attempt to be nice to those who
2858 * go only a small amount over their memory.high value and maybe haven't
2859 * been aggressively reclaimed enough yet.
2861 if (penalty_jiffies <= HZ / 100)
2865 * If reclaim is making forward progress but we're still over
2866 * memory.high, we want to encourage that rather than doing allocator
2869 if (nr_reclaimed || nr_retries--) {
2875 * Reclaim didn't manage to push usage below the limit, slow
2876 * this allocating task down.
2878 * If we exit early, we're guaranteed to die (since
2879 * schedule_timeout_killable sets TASK_KILLABLE). This means we don't
2880 * need to account for any ill-begotten jiffies to pay them off later.
2882 psi_memstall_enter(&pflags);
2883 schedule_timeout_killable(penalty_jiffies);
2884 psi_memstall_leave(&pflags);
2887 css_put(&memcg->css);
2890 static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask,
2891 unsigned int nr_pages)
2893 unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
2894 int nr_retries = MAX_RECLAIM_RETRIES;
2895 struct mem_cgroup *mem_over_limit;
2896 struct page_counter *counter;
2897 unsigned long nr_reclaimed;
2898 bool passed_oom = false;
2899 unsigned int reclaim_options = MEMCG_RECLAIM_MAY_SWAP;
2900 bool drained = false;
2901 bool raised_max_event = false;
2902 unsigned long pflags;
2905 if (consume_stock(memcg, nr_pages))
2908 if (!do_memsw_account() ||
2909 page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2910 if (page_counter_try_charge(&memcg->memory, batch, &counter))
2912 if (do_memsw_account())
2913 page_counter_uncharge(&memcg->memsw, batch);
2914 mem_over_limit = mem_cgroup_from_counter(counter, memory);
2916 mem_over_limit = mem_cgroup_from_counter(counter, memsw);
2917 reclaim_options &= ~MEMCG_RECLAIM_MAY_SWAP;
2920 if (batch > nr_pages) {
2926 * Prevent unbounded recursion when reclaim operations need to
2927 * allocate memory. This might exceed the limits temporarily,
2928 * but we prefer facilitating memory reclaim and getting back
2929 * under the limit over triggering OOM kills in these cases.
2931 if (unlikely(current->flags & PF_MEMALLOC))
2934 if (unlikely(task_in_memcg_oom(current)))
2937 if (!gfpflags_allow_blocking(gfp_mask))
2940 memcg_memory_event(mem_over_limit, MEMCG_MAX);
2941 raised_max_event = true;
2943 psi_memstall_enter(&pflags);
2944 nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
2945 gfp_mask, reclaim_options);
2946 psi_memstall_leave(&pflags);
2948 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2952 drain_all_stock(mem_over_limit);
2957 if (gfp_mask & __GFP_NORETRY)
2960 * Even though the limit is exceeded at this point, reclaim
2961 * may have been able to free some pages. Retry the charge
2962 * before killing the task.
2964 * Only for regular pages, though: huge pages are rather
2965 * unlikely to succeed so close to the limit, and we fall back
2966 * to regular pages anyway in case of failure.
2968 if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
2971 * At task move, charge accounts can be doubly counted. So, it's
2972 * better to wait until the end of task_move if something is going on.
2974 if (mem_cgroup_wait_acct_move(mem_over_limit))
2980 if (gfp_mask & __GFP_RETRY_MAYFAIL)
2983 /* Avoid endless loop for tasks bypassed by the oom killer */
2984 if (passed_oom && task_is_dying())
2988 * keep retrying as long as the memcg oom killer is able to make
2989 * a forward progress or bypass the charge if the oom killer
2990 * couldn't make any progress.
2992 if (mem_cgroup_oom(mem_over_limit, gfp_mask,
2993 get_order(nr_pages * PAGE_SIZE))) {
2995 nr_retries = MAX_RECLAIM_RETRIES;
3000 * Memcg doesn't have a dedicated reserve for atomic
3001 * allocations. But like the global atomic pool, we need to
3002 * put the burden of reclaim on regular allocation requests
3003 * and let these go through as privileged allocations.
3005 if (!(gfp_mask & (__GFP_NOFAIL | __GFP_HIGH)))
3009 * If the allocation has to be enforced, don't forget to raise
3010 * a MEMCG_MAX event.
3012 if (!raised_max_event)
3013 memcg_memory_event(mem_over_limit, MEMCG_MAX);
3016 * The allocation either can't fail or will lead to more memory
3017 * being freed very soon. Allow memory usage go over the limit
3018 * temporarily by force charging it.
3020 page_counter_charge(&memcg->memory, nr_pages);
3021 if (do_memsw_account())
3022 page_counter_charge(&memcg->memsw, nr_pages);
3027 if (batch > nr_pages)
3028 refill_stock(memcg, batch - nr_pages);
3031 * If the hierarchy is above the normal consumption range, schedule
3032 * reclaim on returning to userland. We can perform reclaim here
3033 * if __GFP_RECLAIM but let's always punt for simplicity and so that
3034 * GFP_KERNEL can consistently be used during reclaim. @memcg is
3035 * not recorded as it most likely matches current's and won't
3036 * change in the meantime. As high limit is checked again before
3037 * reclaim, the cost of mismatch is negligible.
3040 bool mem_high, swap_high;
3042 mem_high = page_counter_read(&memcg->memory) >
3043 READ_ONCE(memcg->memory.high);
3044 swap_high = page_counter_read(&memcg->swap) >
3045 READ_ONCE(memcg->swap.high);
3047 /* Don't bother a random interrupted task */
3050 schedule_work(&memcg->high_work);
3056 if (mem_high || swap_high) {
3058 * The allocating tasks in this cgroup will need to do
3059 * reclaim or be throttled to prevent further growth
3060 * of the memory or swap footprints.
3062 * Target some best-effort fairness between the tasks,
3063 * and distribute reclaim work and delay penalties
3064 * based on how much each task is actually allocating.
3066 current->memcg_nr_pages_over_high += batch;
3067 set_notify_resume(current);
3070 } while ((memcg = parent_mem_cgroup(memcg)));
3073 * Reclaim is set up above to be called from the userland
3074 * return path. But also attempt synchronous reclaim to avoid
3075 * excessive overrun while the task is still inside the
3076 * kernel. If this is successful, the return path will see it
3077 * when it rechecks the overage and simply bail out.
3079 if (current->memcg_nr_pages_over_high > MEMCG_CHARGE_BATCH &&
3080 !(current->flags & PF_MEMALLOC) &&
3081 gfpflags_allow_blocking(gfp_mask))
3082 mem_cgroup_handle_over_high(gfp_mask);
3086 static inline int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
3087 unsigned int nr_pages)
3089 if (mem_cgroup_is_root(memcg))
3092 return try_charge_memcg(memcg, gfp_mask, nr_pages);
3096 * mem_cgroup_cancel_charge() - cancel an uncommitted try_charge() call.
3097 * @memcg: memcg previously charged.
3098 * @nr_pages: number of pages previously charged.
3100 void mem_cgroup_cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
3102 if (mem_cgroup_is_root(memcg))
3105 page_counter_uncharge(&memcg->memory, nr_pages);
3106 if (do_memsw_account())
3107 page_counter_uncharge(&memcg->memsw, nr_pages);
3110 static void commit_charge(struct folio *folio, struct mem_cgroup *memcg)
3112 VM_BUG_ON_FOLIO(folio_memcg(folio), folio);
3114 * Any of the following ensures page's memcg stability:
3118 * - folio_memcg_lock()
3119 * - exclusive reference
3120 * - mem_cgroup_trylock_pages()
3122 folio->memcg_data = (unsigned long)memcg;
3126 * mem_cgroup_commit_charge - commit a previously successful try_charge().
3127 * @folio: folio to commit the charge to.
3128 * @memcg: memcg previously charged.
3130 void mem_cgroup_commit_charge(struct folio *folio, struct mem_cgroup *memcg)
3132 css_get(&memcg->css);
3133 commit_charge(folio, memcg);
3135 local_irq_disable();
3136 mem_cgroup_charge_statistics(memcg, folio_nr_pages(folio));
3137 memcg_check_events(memcg, folio_nid(folio));
3141 #ifdef CONFIG_MEMCG_KMEM
3143 static inline void __mod_objcg_mlstate(struct obj_cgroup *objcg,
3144 struct pglist_data *pgdat,
3145 enum node_stat_item idx, int nr)
3147 struct mem_cgroup *memcg;
3148 struct lruvec *lruvec;
3150 lockdep_assert_irqs_disabled();
3153 memcg = obj_cgroup_memcg(objcg);
3154 lruvec = mem_cgroup_lruvec(memcg, pgdat);
3155 __mod_memcg_lruvec_state(lruvec, idx, nr);
3159 static __always_inline
3160 struct mem_cgroup *mem_cgroup_from_obj_folio(struct folio *folio, void *p)
3163 * Slab objects are accounted individually, not per-page.
3164 * Memcg membership data for each individual object is saved in
3167 if (folio_test_slab(folio)) {
3168 struct slabobj_ext *obj_exts;
3172 slab = folio_slab(folio);
3173 obj_exts = slab_obj_exts(slab);
3177 off = obj_to_index(slab->slab_cache, slab, p);
3178 if (obj_exts[off].objcg)
3179 return obj_cgroup_memcg(obj_exts[off].objcg);
3185 * folio_memcg_check() is used here, because in theory we can encounter
3186 * a folio where the slab flag has been cleared already, but
3187 * slab->obj_exts has not been freed yet
3188 * folio_memcg_check() will guarantee that a proper memory
3189 * cgroup pointer or NULL will be returned.
3191 return folio_memcg_check(folio);
3195 * Returns a pointer to the memory cgroup to which the kernel object is charged.
3197 * A passed kernel object can be a slab object, vmalloc object or a generic
3198 * kernel page, so different mechanisms for getting the memory cgroup pointer
3201 * In certain cases (e.g. kernel stacks or large kmallocs with SLUB) the caller
3202 * can not know for sure how the kernel object is implemented.
3203 * mem_cgroup_from_obj() can be safely used in such cases.
3205 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
3206 * cgroup_mutex, etc.
3208 struct mem_cgroup *mem_cgroup_from_obj(void *p)
3210 struct folio *folio;
3212 if (mem_cgroup_disabled())
3215 if (unlikely(is_vmalloc_addr(p)))
3216 folio = page_folio(vmalloc_to_page(p));
3218 folio = virt_to_folio(p);
3220 return mem_cgroup_from_obj_folio(folio, p);
3224 * Returns a pointer to the memory cgroup to which the kernel object is charged.
3225 * Similar to mem_cgroup_from_obj(), but faster and not suitable for objects,
3226 * allocated using vmalloc().
3228 * A passed kernel object must be a slab object or a generic kernel page.
3230 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
3231 * cgroup_mutex, etc.
3233 struct mem_cgroup *mem_cgroup_from_slab_obj(void *p)
3235 if (mem_cgroup_disabled())
3238 return mem_cgroup_from_obj_folio(virt_to_folio(p), p);
3241 static struct obj_cgroup *__get_obj_cgroup_from_memcg(struct mem_cgroup *memcg)
3243 struct obj_cgroup *objcg = NULL;
3245 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
3246 objcg = rcu_dereference(memcg->objcg);
3247 if (likely(objcg && obj_cgroup_tryget(objcg)))
3254 static struct obj_cgroup *current_objcg_update(void)
3256 struct mem_cgroup *memcg;
3257 struct obj_cgroup *old, *objcg = NULL;
3260 /* Atomically drop the update bit. */
3261 old = xchg(¤t->objcg, NULL);
3263 old = (struct obj_cgroup *)
3264 ((unsigned long)old & ~CURRENT_OBJCG_UPDATE_FLAG);
3265 obj_cgroup_put(old);
3270 /* If new objcg is NULL, no reason for the second atomic update. */
3271 if (!current->mm || (current->flags & PF_KTHREAD))
3275 * Release the objcg pointer from the previous iteration,
3276 * if try_cmpxcg() below fails.
3278 if (unlikely(objcg)) {
3279 obj_cgroup_put(objcg);
3284 * Obtain the new objcg pointer. The current task can be
3285 * asynchronously moved to another memcg and the previous
3286 * memcg can be offlined. So let's get the memcg pointer
3287 * and try get a reference to objcg under a rcu read lock.
3291 memcg = mem_cgroup_from_task(current);
3292 objcg = __get_obj_cgroup_from_memcg(memcg);
3296 * Try set up a new objcg pointer atomically. If it
3297 * fails, it means the update flag was set concurrently, so
3298 * the whole procedure should be repeated.
3300 } while (!try_cmpxchg(¤t->objcg, &old, objcg));
3305 __always_inline struct obj_cgroup *current_obj_cgroup(void)
3307 struct mem_cgroup *memcg;
3308 struct obj_cgroup *objcg;
3311 memcg = current->active_memcg;
3312 if (unlikely(memcg))
3315 objcg = READ_ONCE(current->objcg);
3316 if (unlikely((unsigned long)objcg & CURRENT_OBJCG_UPDATE_FLAG))
3317 objcg = current_objcg_update();
3319 * Objcg reference is kept by the task, so it's safe
3320 * to use the objcg by the current task.
3325 memcg = this_cpu_read(int_active_memcg);
3326 if (unlikely(memcg))
3333 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
3335 * Memcg pointer is protected by scope (see set_active_memcg())
3336 * and is pinning the corresponding objcg, so objcg can't go
3337 * away and can be used within the scope without any additional
3340 objcg = rcu_dereference_check(memcg->objcg, 1);
3348 struct obj_cgroup *get_obj_cgroup_from_folio(struct folio *folio)
3350 struct obj_cgroup *objcg;
3352 if (!memcg_kmem_online())
3355 if (folio_memcg_kmem(folio)) {
3356 objcg = __folio_objcg(folio);
3357 obj_cgroup_get(objcg);
3359 struct mem_cgroup *memcg;
3362 memcg = __folio_memcg(folio);
3364 objcg = __get_obj_cgroup_from_memcg(memcg);
3372 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages)
3374 mod_memcg_state(memcg, MEMCG_KMEM, nr_pages);
3375 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
3377 page_counter_charge(&memcg->kmem, nr_pages);
3379 page_counter_uncharge(&memcg->kmem, -nr_pages);
3385 * obj_cgroup_uncharge_pages: uncharge a number of kernel pages from a objcg
3386 * @objcg: object cgroup to uncharge
3387 * @nr_pages: number of pages to uncharge
3389 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
3390 unsigned int nr_pages)
3392 struct mem_cgroup *memcg;
3394 memcg = get_mem_cgroup_from_objcg(objcg);
3396 memcg_account_kmem(memcg, -nr_pages);
3397 refill_stock(memcg, nr_pages);
3399 css_put(&memcg->css);
3403 * obj_cgroup_charge_pages: charge a number of kernel pages to a objcg
3404 * @objcg: object cgroup to charge
3405 * @gfp: reclaim mode
3406 * @nr_pages: number of pages to charge
3408 * Returns 0 on success, an error code on failure.
3410 static int obj_cgroup_charge_pages(struct obj_cgroup *objcg, gfp_t gfp,
3411 unsigned int nr_pages)
3413 struct mem_cgroup *memcg;
3416 memcg = get_mem_cgroup_from_objcg(objcg);
3418 ret = try_charge_memcg(memcg, gfp, nr_pages);
3422 memcg_account_kmem(memcg, nr_pages);
3424 css_put(&memcg->css);
3430 * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup
3431 * @page: page to charge
3432 * @gfp: reclaim mode
3433 * @order: allocation order
3435 * Returns 0 on success, an error code on failure.
3437 int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
3439 struct obj_cgroup *objcg;
3442 objcg = current_obj_cgroup();
3444 ret = obj_cgroup_charge_pages(objcg, gfp, 1 << order);
3446 obj_cgroup_get(objcg);
3447 page->memcg_data = (unsigned long)objcg |
3456 * __memcg_kmem_uncharge_page: uncharge a kmem page
3457 * @page: page to uncharge
3458 * @order: allocation order
3460 void __memcg_kmem_uncharge_page(struct page *page, int order)
3462 struct folio *folio = page_folio(page);
3463 struct obj_cgroup *objcg;
3464 unsigned int nr_pages = 1 << order;
3466 if (!folio_memcg_kmem(folio))
3469 objcg = __folio_objcg(folio);
3470 obj_cgroup_uncharge_pages(objcg, nr_pages);
3471 folio->memcg_data = 0;
3472 obj_cgroup_put(objcg);
3475 static void mod_objcg_state(struct obj_cgroup *objcg, struct pglist_data *pgdat,
3476 enum node_stat_item idx, int nr)
3478 struct memcg_stock_pcp *stock;
3479 struct obj_cgroup *old = NULL;
3480 unsigned long flags;
3483 local_lock_irqsave(&memcg_stock.stock_lock, flags);
3484 stock = this_cpu_ptr(&memcg_stock);
3487 * Save vmstat data in stock and skip vmstat array update unless
3488 * accumulating over a page of vmstat data or when pgdat or idx
3491 if (READ_ONCE(stock->cached_objcg) != objcg) {
3492 old = drain_obj_stock(stock);
3493 obj_cgroup_get(objcg);
3494 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3495 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3496 WRITE_ONCE(stock->cached_objcg, objcg);
3497 stock->cached_pgdat = pgdat;
3498 } else if (stock->cached_pgdat != pgdat) {
3499 /* Flush the existing cached vmstat data */
3500 struct pglist_data *oldpg = stock->cached_pgdat;
3502 if (stock->nr_slab_reclaimable_b) {
3503 __mod_objcg_mlstate(objcg, oldpg, NR_SLAB_RECLAIMABLE_B,
3504 stock->nr_slab_reclaimable_b);
3505 stock->nr_slab_reclaimable_b = 0;
3507 if (stock->nr_slab_unreclaimable_b) {
3508 __mod_objcg_mlstate(objcg, oldpg, NR_SLAB_UNRECLAIMABLE_B,
3509 stock->nr_slab_unreclaimable_b);
3510 stock->nr_slab_unreclaimable_b = 0;
3512 stock->cached_pgdat = pgdat;
3515 bytes = (idx == NR_SLAB_RECLAIMABLE_B) ? &stock->nr_slab_reclaimable_b
3516 : &stock->nr_slab_unreclaimable_b;
3518 * Even for large object >= PAGE_SIZE, the vmstat data will still be
3519 * cached locally at least once before pushing it out.
3526 if (abs(*bytes) > PAGE_SIZE) {
3534 __mod_objcg_mlstate(objcg, pgdat, idx, nr);
3536 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3537 obj_cgroup_put(old);
3540 static bool consume_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes)
3542 struct memcg_stock_pcp *stock;
3543 unsigned long flags;
3546 local_lock_irqsave(&memcg_stock.stock_lock, flags);
3548 stock = this_cpu_ptr(&memcg_stock);
3549 if (objcg == READ_ONCE(stock->cached_objcg) && stock->nr_bytes >= nr_bytes) {
3550 stock->nr_bytes -= nr_bytes;
3554 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3559 static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock)
3561 struct obj_cgroup *old = READ_ONCE(stock->cached_objcg);
3566 if (stock->nr_bytes) {
3567 unsigned int nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3568 unsigned int nr_bytes = stock->nr_bytes & (PAGE_SIZE - 1);
3571 struct mem_cgroup *memcg;
3573 memcg = get_mem_cgroup_from_objcg(old);
3575 memcg_account_kmem(memcg, -nr_pages);
3576 __refill_stock(memcg, nr_pages);
3578 css_put(&memcg->css);
3582 * The leftover is flushed to the centralized per-memcg value.
3583 * On the next attempt to refill obj stock it will be moved
3584 * to a per-cpu stock (probably, on an other CPU), see
3585 * refill_obj_stock().
3587 * How often it's flushed is a trade-off between the memory
3588 * limit enforcement accuracy and potential CPU contention,
3589 * so it might be changed in the future.
3591 atomic_add(nr_bytes, &old->nr_charged_bytes);
3592 stock->nr_bytes = 0;
3596 * Flush the vmstat data in current stock
3598 if (stock->nr_slab_reclaimable_b || stock->nr_slab_unreclaimable_b) {
3599 if (stock->nr_slab_reclaimable_b) {
3600 __mod_objcg_mlstate(old, stock->cached_pgdat,
3601 NR_SLAB_RECLAIMABLE_B,
3602 stock->nr_slab_reclaimable_b);
3603 stock->nr_slab_reclaimable_b = 0;
3605 if (stock->nr_slab_unreclaimable_b) {
3606 __mod_objcg_mlstate(old, stock->cached_pgdat,
3607 NR_SLAB_UNRECLAIMABLE_B,
3608 stock->nr_slab_unreclaimable_b);
3609 stock->nr_slab_unreclaimable_b = 0;
3611 stock->cached_pgdat = NULL;
3614 WRITE_ONCE(stock->cached_objcg, NULL);
3616 * The `old' objects needs to be released by the caller via
3617 * obj_cgroup_put() outside of memcg_stock_pcp::stock_lock.
3622 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
3623 struct mem_cgroup *root_memcg)
3625 struct obj_cgroup *objcg = READ_ONCE(stock->cached_objcg);
3626 struct mem_cgroup *memcg;
3629 memcg = obj_cgroup_memcg(objcg);
3630 if (memcg && mem_cgroup_is_descendant(memcg, root_memcg))
3637 static void refill_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes,
3638 bool allow_uncharge)
3640 struct memcg_stock_pcp *stock;
3641 struct obj_cgroup *old = NULL;
3642 unsigned long flags;
3643 unsigned int nr_pages = 0;
3645 local_lock_irqsave(&memcg_stock.stock_lock, flags);
3647 stock = this_cpu_ptr(&memcg_stock);
3648 if (READ_ONCE(stock->cached_objcg) != objcg) { /* reset if necessary */
3649 old = drain_obj_stock(stock);
3650 obj_cgroup_get(objcg);
3651 WRITE_ONCE(stock->cached_objcg, objcg);
3652 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3653 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3654 allow_uncharge = true; /* Allow uncharge when objcg changes */
3656 stock->nr_bytes += nr_bytes;
3658 if (allow_uncharge && (stock->nr_bytes > PAGE_SIZE)) {
3659 nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3660 stock->nr_bytes &= (PAGE_SIZE - 1);
3663 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3664 obj_cgroup_put(old);
3667 obj_cgroup_uncharge_pages(objcg, nr_pages);
3670 int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size)
3672 unsigned int nr_pages, nr_bytes;
3675 if (consume_obj_stock(objcg, size))
3679 * In theory, objcg->nr_charged_bytes can have enough
3680 * pre-charged bytes to satisfy the allocation. However,
3681 * flushing objcg->nr_charged_bytes requires two atomic
3682 * operations, and objcg->nr_charged_bytes can't be big.
3683 * The shared objcg->nr_charged_bytes can also become a
3684 * performance bottleneck if all tasks of the same memcg are
3685 * trying to update it. So it's better to ignore it and try
3686 * grab some new pages. The stock's nr_bytes will be flushed to
3687 * objcg->nr_charged_bytes later on when objcg changes.
3689 * The stock's nr_bytes may contain enough pre-charged bytes
3690 * to allow one less page from being charged, but we can't rely
3691 * on the pre-charged bytes not being changed outside of
3692 * consume_obj_stock() or refill_obj_stock(). So ignore those
3693 * pre-charged bytes as well when charging pages. To avoid a
3694 * page uncharge right after a page charge, we set the
3695 * allow_uncharge flag to false when calling refill_obj_stock()
3696 * to temporarily allow the pre-charged bytes to exceed the page
3697 * size limit. The maximum reachable value of the pre-charged
3698 * bytes is (sizeof(object) + PAGE_SIZE - 2) if there is no data
3701 nr_pages = size >> PAGE_SHIFT;
3702 nr_bytes = size & (PAGE_SIZE - 1);
3707 ret = obj_cgroup_charge_pages(objcg, gfp, nr_pages);
3708 if (!ret && nr_bytes)
3709 refill_obj_stock(objcg, PAGE_SIZE - nr_bytes, false);
3714 void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size)
3716 refill_obj_stock(objcg, size, true);
3719 static inline size_t obj_full_size(struct kmem_cache *s)
3722 * For each accounted object there is an extra space which is used
3723 * to store obj_cgroup membership. Charge it too.
3725 return s->size + sizeof(struct obj_cgroup *);
3728 bool __memcg_slab_post_alloc_hook(struct kmem_cache *s, struct list_lru *lru,
3729 gfp_t flags, size_t size, void **p)
3731 struct obj_cgroup *objcg;
3737 * The obtained objcg pointer is safe to use within the current scope,
3738 * defined by current task or set_active_memcg() pair.
3739 * obj_cgroup_get() is used to get a permanent reference.
3741 objcg = current_obj_cgroup();
3746 * slab_alloc_node() avoids the NULL check, so we might be called with a
3747 * single NULL object. kmem_cache_alloc_bulk() aborts if it can't fill
3748 * the whole requested size.
3749 * return success as there's nothing to free back
3751 if (unlikely(*p == NULL))
3754 flags &= gfp_allowed_mask;
3758 struct mem_cgroup *memcg;
3760 memcg = get_mem_cgroup_from_objcg(objcg);
3761 ret = memcg_list_lru_alloc(memcg, lru, flags);
3762 css_put(&memcg->css);
3768 if (obj_cgroup_charge(objcg, flags, size * obj_full_size(s)))
3771 for (i = 0; i < size; i++) {
3772 slab = virt_to_slab(p[i]);
3774 if (!slab_obj_exts(slab) &&
3775 alloc_slab_obj_exts(slab, s, flags, false)) {
3776 obj_cgroup_uncharge(objcg, obj_full_size(s));
3780 off = obj_to_index(s, slab, p[i]);
3781 obj_cgroup_get(objcg);
3782 slab_obj_exts(slab)[off].objcg = objcg;
3783 mod_objcg_state(objcg, slab_pgdat(slab),
3784 cache_vmstat_idx(s), obj_full_size(s));
3790 void __memcg_slab_free_hook(struct kmem_cache *s, struct slab *slab,
3791 void **p, int objects, struct slabobj_ext *obj_exts)
3793 for (int i = 0; i < objects; i++) {
3794 struct obj_cgroup *objcg;
3797 off = obj_to_index(s, slab, p[i]);
3798 objcg = obj_exts[off].objcg;
3802 obj_exts[off].objcg = NULL;
3803 obj_cgroup_uncharge(objcg, obj_full_size(s));
3804 mod_objcg_state(objcg, slab_pgdat(slab), cache_vmstat_idx(s),
3806 obj_cgroup_put(objcg);
3809 #endif /* CONFIG_MEMCG_KMEM */
3812 * Because page_memcg(head) is not set on tails, set it now.
3814 void split_page_memcg(struct page *head, int old_order, int new_order)
3816 struct folio *folio = page_folio(head);
3817 struct mem_cgroup *memcg = folio_memcg(folio);
3819 unsigned int old_nr = 1 << old_order;
3820 unsigned int new_nr = 1 << new_order;
3822 if (mem_cgroup_disabled() || !memcg)
3825 for (i = new_nr; i < old_nr; i += new_nr)
3826 folio_page(folio, i)->memcg_data = folio->memcg_data;
3828 if (folio_memcg_kmem(folio))
3829 obj_cgroup_get_many(__folio_objcg(folio), old_nr / new_nr - 1);
3831 css_get_many(&memcg->css, old_nr / new_nr - 1);
3836 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3837 * @entry: swap entry to be moved
3838 * @from: mem_cgroup which the entry is moved from
3839 * @to: mem_cgroup which the entry is moved to
3841 * It succeeds only when the swap_cgroup's record for this entry is the same
3842 * as the mem_cgroup's id of @from.
3844 * Returns 0 on success, -EINVAL on failure.
3846 * The caller must have charged to @to, IOW, called page_counter_charge() about
3847 * both res and memsw, and called css_get().
3849 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3850 struct mem_cgroup *from, struct mem_cgroup *to)
3852 unsigned short old_id, new_id;
3854 old_id = mem_cgroup_id(from);
3855 new_id = mem_cgroup_id(to);
3857 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3858 mod_memcg_state(from, MEMCG_SWAP, -1);
3859 mod_memcg_state(to, MEMCG_SWAP, 1);
3865 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3866 struct mem_cgroup *from, struct mem_cgroup *to)
3872 static DEFINE_MUTEX(memcg_max_mutex);
3874 static int mem_cgroup_resize_max(struct mem_cgroup *memcg,
3875 unsigned long max, bool memsw)
3877 bool enlarge = false;
3878 bool drained = false;
3880 bool limits_invariant;
3881 struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory;
3884 if (signal_pending(current)) {
3889 mutex_lock(&memcg_max_mutex);
3891 * Make sure that the new limit (memsw or memory limit) doesn't
3892 * break our basic invariant rule memory.max <= memsw.max.
3894 limits_invariant = memsw ? max >= READ_ONCE(memcg->memory.max) :
3895 max <= memcg->memsw.max;
3896 if (!limits_invariant) {
3897 mutex_unlock(&memcg_max_mutex);
3901 if (max > counter->max)
3903 ret = page_counter_set_max(counter, max);
3904 mutex_unlock(&memcg_max_mutex);
3910 drain_all_stock(memcg);
3915 if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,
3916 memsw ? 0 : MEMCG_RECLAIM_MAY_SWAP)) {
3922 if (!ret && enlarge)
3923 memcg_oom_recover(memcg);
3928 unsigned long mem_cgroup_soft_limit_reclaim(pg_data_t *pgdat, int order,
3930 unsigned long *total_scanned)
3932 unsigned long nr_reclaimed = 0;
3933 struct mem_cgroup_per_node *mz, *next_mz = NULL;
3934 unsigned long reclaimed;
3936 struct mem_cgroup_tree_per_node *mctz;
3937 unsigned long excess;
3939 if (lru_gen_enabled())
3945 mctz = soft_limit_tree.rb_tree_per_node[pgdat->node_id];
3948 * Do not even bother to check the largest node if the root
3949 * is empty. Do it lockless to prevent lock bouncing. Races
3950 * are acceptable as soft limit is best effort anyway.
3952 if (!mctz || RB_EMPTY_ROOT(&mctz->rb_root))
3956 * This loop can run a while, specially if mem_cgroup's continuously
3957 * keep exceeding their soft limit and putting the system under
3964 mz = mem_cgroup_largest_soft_limit_node(mctz);
3968 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, pgdat,
3969 gfp_mask, total_scanned);
3970 nr_reclaimed += reclaimed;
3971 spin_lock_irq(&mctz->lock);
3974 * If we failed to reclaim anything from this memory cgroup
3975 * it is time to move on to the next cgroup
3979 next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
3981 excess = soft_limit_excess(mz->memcg);
3983 * One school of thought says that we should not add
3984 * back the node to the tree if reclaim returns 0.
3985 * But our reclaim could return 0, simply because due
3986 * to priority we are exposing a smaller subset of
3987 * memory to reclaim from. Consider this as a longer
3990 /* If excess == 0, no tree ops */
3991 __mem_cgroup_insert_exceeded(mz, mctz, excess);
3992 spin_unlock_irq(&mctz->lock);
3993 css_put(&mz->memcg->css);
3996 * Could not reclaim anything and there are no more
3997 * mem cgroups to try or we seem to be looping without
3998 * reclaiming anything.
4000 if (!nr_reclaimed &&
4002 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
4004 } while (!nr_reclaimed);
4006 css_put(&next_mz->memcg->css);
4007 return nr_reclaimed;
4011 * Reclaims as many pages from the given memcg as possible.
4013 * Caller is responsible for holding css reference for memcg.
4015 static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
4017 int nr_retries = MAX_RECLAIM_RETRIES;
4019 /* we call try-to-free pages for make this cgroup empty */
4020 lru_add_drain_all();
4022 drain_all_stock(memcg);
4024 /* try to free all pages in this cgroup */
4025 while (nr_retries && page_counter_read(&memcg->memory)) {
4026 if (signal_pending(current))
4029 if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,
4030 MEMCG_RECLAIM_MAY_SWAP))
4037 static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
4038 char *buf, size_t nbytes,
4041 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4043 if (mem_cgroup_is_root(memcg))
4045 return mem_cgroup_force_empty(memcg) ?: nbytes;
4048 static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
4054 static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
4055 struct cftype *cft, u64 val)
4060 pr_warn_once("Non-hierarchical mode is deprecated. "
4062 "depend on this functionality.\n");
4067 static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
4071 if (mem_cgroup_is_root(memcg)) {
4073 * Approximate root's usage from global state. This isn't
4074 * perfect, but the root usage was always an approximation.
4076 val = global_node_page_state(NR_FILE_PAGES) +
4077 global_node_page_state(NR_ANON_MAPPED);
4079 val += total_swap_pages - get_nr_swap_pages();
4082 val = page_counter_read(&memcg->memory);
4084 val = page_counter_read(&memcg->memsw);
4097 static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
4100 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4101 struct page_counter *counter;
4103 switch (MEMFILE_TYPE(cft->private)) {
4105 counter = &memcg->memory;
4108 counter = &memcg->memsw;
4111 counter = &memcg->kmem;
4114 counter = &memcg->tcpmem;
4120 switch (MEMFILE_ATTR(cft->private)) {
4122 if (counter == &memcg->memory)
4123 return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
4124 if (counter == &memcg->memsw)
4125 return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
4126 return (u64)page_counter_read(counter) * PAGE_SIZE;
4128 return (u64)counter->max * PAGE_SIZE;
4130 return (u64)counter->watermark * PAGE_SIZE;
4132 return counter->failcnt;
4133 case RES_SOFT_LIMIT:
4134 return (u64)READ_ONCE(memcg->soft_limit) * PAGE_SIZE;
4141 * This function doesn't do anything useful. Its only job is to provide a read
4142 * handler for a file so that cgroup_file_mode() will add read permissions.
4144 static int mem_cgroup_dummy_seq_show(__always_unused struct seq_file *m,
4145 __always_unused void *v)
4150 #ifdef CONFIG_MEMCG_KMEM
4151 static int memcg_online_kmem(struct mem_cgroup *memcg)
4153 struct obj_cgroup *objcg;
4155 if (mem_cgroup_kmem_disabled())
4158 if (unlikely(mem_cgroup_is_root(memcg)))
4161 objcg = obj_cgroup_alloc();
4165 objcg->memcg = memcg;
4166 rcu_assign_pointer(memcg->objcg, objcg);
4167 obj_cgroup_get(objcg);
4168 memcg->orig_objcg = objcg;
4170 static_branch_enable(&memcg_kmem_online_key);
4172 memcg->kmemcg_id = memcg->id.id;
4177 static void memcg_offline_kmem(struct mem_cgroup *memcg)
4179 struct mem_cgroup *parent;
4181 if (mem_cgroup_kmem_disabled())
4184 if (unlikely(mem_cgroup_is_root(memcg)))
4187 parent = parent_mem_cgroup(memcg);
4189 parent = root_mem_cgroup;
4191 memcg_reparent_objcgs(memcg, parent);
4194 * After we have finished memcg_reparent_objcgs(), all list_lrus
4195 * corresponding to this cgroup are guaranteed to remain empty.
4196 * The ordering is imposed by list_lru_node->lock taken by
4197 * memcg_reparent_list_lrus().
4199 memcg_reparent_list_lrus(memcg, parent);
4202 static int memcg_online_kmem(struct mem_cgroup *memcg)
4206 static void memcg_offline_kmem(struct mem_cgroup *memcg)
4209 #endif /* CONFIG_MEMCG_KMEM */
4211 static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max)
4215 mutex_lock(&memcg_max_mutex);
4217 ret = page_counter_set_max(&memcg->tcpmem, max);
4221 if (!memcg->tcpmem_active) {
4223 * The active flag needs to be written after the static_key
4224 * update. This is what guarantees that the socket activation
4225 * function is the last one to run. See mem_cgroup_sk_alloc()
4226 * for details, and note that we don't mark any socket as
4227 * belonging to this memcg until that flag is up.
4229 * We need to do this, because static_keys will span multiple
4230 * sites, but we can't control their order. If we mark a socket
4231 * as accounted, but the accounting functions are not patched in
4232 * yet, we'll lose accounting.
4234 * We never race with the readers in mem_cgroup_sk_alloc(),
4235 * because when this value change, the code to process it is not
4238 static_branch_inc(&memcg_sockets_enabled_key);
4239 memcg->tcpmem_active = true;
4242 mutex_unlock(&memcg_max_mutex);
4247 * The user of this function is...
4250 static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
4251 char *buf, size_t nbytes, loff_t off)
4253 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4254 unsigned long nr_pages;
4257 buf = strstrip(buf);
4258 ret = page_counter_memparse(buf, "-1", &nr_pages);
4262 switch (MEMFILE_ATTR(of_cft(of)->private)) {
4264 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
4268 switch (MEMFILE_TYPE(of_cft(of)->private)) {
4270 ret = mem_cgroup_resize_max(memcg, nr_pages, false);
4273 ret = mem_cgroup_resize_max(memcg, nr_pages, true);
4276 pr_warn_once("kmem.limit_in_bytes is deprecated and will be removed. "
4277 "Writing any value to this file has no effect. "
4279 "depend on this functionality.\n");
4283 ret = memcg_update_tcp_max(memcg, nr_pages);
4287 case RES_SOFT_LIMIT:
4288 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
4291 WRITE_ONCE(memcg->soft_limit, nr_pages);
4296 return ret ?: nbytes;
4299 static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
4300 size_t nbytes, loff_t off)
4302 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4303 struct page_counter *counter;
4305 switch (MEMFILE_TYPE(of_cft(of)->private)) {
4307 counter = &memcg->memory;
4310 counter = &memcg->memsw;
4313 counter = &memcg->kmem;
4316 counter = &memcg->tcpmem;
4322 switch (MEMFILE_ATTR(of_cft(of)->private)) {
4324 page_counter_reset_watermark(counter);
4327 counter->failcnt = 0;
4336 static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
4339 return mem_cgroup_from_css(css)->move_charge_at_immigrate;
4343 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
4344 struct cftype *cft, u64 val)
4346 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4348 pr_warn_once("Cgroup memory moving (move_charge_at_immigrate) is deprecated. "
4350 "depend on this functionality.\n");
4352 if (val & ~MOVE_MASK)
4356 * No kind of locking is needed in here, because ->can_attach() will
4357 * check this value once in the beginning of the process, and then carry
4358 * on with stale data. This means that changes to this value will only
4359 * affect task migrations starting after the change.
4361 memcg->move_charge_at_immigrate = val;
4365 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
4366 struct cftype *cft, u64 val)
4374 #define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE))
4375 #define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON))
4376 #define LRU_ALL ((1 << NR_LRU_LISTS) - 1)
4378 static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
4379 int nid, unsigned int lru_mask, bool tree)
4381 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
4382 unsigned long nr = 0;
4385 VM_BUG_ON((unsigned)nid >= nr_node_ids);
4388 if (!(BIT(lru) & lru_mask))
4391 nr += lruvec_page_state(lruvec, NR_LRU_BASE + lru);
4393 nr += lruvec_page_state_local(lruvec, NR_LRU_BASE + lru);
4398 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
4399 unsigned int lru_mask,
4402 unsigned long nr = 0;
4406 if (!(BIT(lru) & lru_mask))
4409 nr += memcg_page_state(memcg, NR_LRU_BASE + lru);
4411 nr += memcg_page_state_local(memcg, NR_LRU_BASE + lru);
4416 static int memcg_numa_stat_show(struct seq_file *m, void *v)
4420 unsigned int lru_mask;
4423 static const struct numa_stat stats[] = {
4424 { "total", LRU_ALL },
4425 { "file", LRU_ALL_FILE },
4426 { "anon", LRU_ALL_ANON },
4427 { "unevictable", BIT(LRU_UNEVICTABLE) },
4429 const struct numa_stat *stat;
4431 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
4433 mem_cgroup_flush_stats(memcg);
4435 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
4436 seq_printf(m, "%s=%lu", stat->name,
4437 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
4439 for_each_node_state(nid, N_MEMORY)
4440 seq_printf(m, " N%d=%lu", nid,
4441 mem_cgroup_node_nr_lru_pages(memcg, nid,
4442 stat->lru_mask, false));
4446 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
4448 seq_printf(m, "hierarchical_%s=%lu", stat->name,
4449 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
4451 for_each_node_state(nid, N_MEMORY)
4452 seq_printf(m, " N%d=%lu", nid,
4453 mem_cgroup_node_nr_lru_pages(memcg, nid,
4454 stat->lru_mask, true));
4460 #endif /* CONFIG_NUMA */
4462 static const unsigned int memcg1_stats[] = {
4465 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4472 WORKINGSET_REFAULT_ANON,
4473 WORKINGSET_REFAULT_FILE,
4480 static const char *const memcg1_stat_names[] = {
4483 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4490 "workingset_refault_anon",
4491 "workingset_refault_file",
4498 /* Universal VM events cgroup1 shows, original sort order */
4499 static const unsigned int memcg1_events[] = {
4506 static void memcg1_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
4508 unsigned long memory, memsw;
4509 struct mem_cgroup *mi;
4512 BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats));
4514 mem_cgroup_flush_stats(memcg);
4516 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
4519 nr = memcg_page_state_local_output(memcg, memcg1_stats[i]);
4520 seq_buf_printf(s, "%s %lu\n", memcg1_stat_names[i], nr);
4523 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
4524 seq_buf_printf(s, "%s %lu\n", vm_event_name(memcg1_events[i]),
4525 memcg_events_local(memcg, memcg1_events[i]));
4527 for (i = 0; i < NR_LRU_LISTS; i++)
4528 seq_buf_printf(s, "%s %lu\n", lru_list_name(i),
4529 memcg_page_state_local(memcg, NR_LRU_BASE + i) *
4532 /* Hierarchical information */
4533 memory = memsw = PAGE_COUNTER_MAX;
4534 for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
4535 memory = min(memory, READ_ONCE(mi->memory.max));
4536 memsw = min(memsw, READ_ONCE(mi->memsw.max));
4538 seq_buf_printf(s, "hierarchical_memory_limit %llu\n",
4539 (u64)memory * PAGE_SIZE);
4540 seq_buf_printf(s, "hierarchical_memsw_limit %llu\n",
4541 (u64)memsw * PAGE_SIZE);
4543 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
4546 nr = memcg_page_state_output(memcg, memcg1_stats[i]);
4547 seq_buf_printf(s, "total_%s %llu\n", memcg1_stat_names[i],
4551 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
4552 seq_buf_printf(s, "total_%s %llu\n",
4553 vm_event_name(memcg1_events[i]),
4554 (u64)memcg_events(memcg, memcg1_events[i]));
4556 for (i = 0; i < NR_LRU_LISTS; i++)
4557 seq_buf_printf(s, "total_%s %llu\n", lru_list_name(i),
4558 (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
4561 #ifdef CONFIG_DEBUG_VM
4564 struct mem_cgroup_per_node *mz;
4565 unsigned long anon_cost = 0;
4566 unsigned long file_cost = 0;
4568 for_each_online_pgdat(pgdat) {
4569 mz = memcg->nodeinfo[pgdat->node_id];
4571 anon_cost += mz->lruvec.anon_cost;
4572 file_cost += mz->lruvec.file_cost;
4574 seq_buf_printf(s, "anon_cost %lu\n", anon_cost);
4575 seq_buf_printf(s, "file_cost %lu\n", file_cost);
4580 static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
4583 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4585 return mem_cgroup_swappiness(memcg);
4588 static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
4589 struct cftype *cft, u64 val)
4591 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4596 if (!mem_cgroup_is_root(memcg))
4597 WRITE_ONCE(memcg->swappiness, val);
4599 WRITE_ONCE(vm_swappiness, val);
4604 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4606 struct mem_cgroup_threshold_ary *t;
4607 unsigned long usage;
4612 t = rcu_dereference(memcg->thresholds.primary);
4614 t = rcu_dereference(memcg->memsw_thresholds.primary);
4619 usage = mem_cgroup_usage(memcg, swap);
4622 * current_threshold points to threshold just below or equal to usage.
4623 * If it's not true, a threshold was crossed after last
4624 * call of __mem_cgroup_threshold().
4626 i = t->current_threshold;
4629 * Iterate backward over array of thresholds starting from
4630 * current_threshold and check if a threshold is crossed.
4631 * If none of thresholds below usage is crossed, we read
4632 * only one element of the array here.
4634 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4635 eventfd_signal(t->entries[i].eventfd);
4637 /* i = current_threshold + 1 */
4641 * Iterate forward over array of thresholds starting from
4642 * current_threshold+1 and check if a threshold is crossed.
4643 * If none of thresholds above usage is crossed, we read
4644 * only one element of the array here.
4646 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4647 eventfd_signal(t->entries[i].eventfd);
4649 /* Update current_threshold */
4650 t->current_threshold = i - 1;
4655 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4658 __mem_cgroup_threshold(memcg, false);
4659 if (do_memsw_account())
4660 __mem_cgroup_threshold(memcg, true);
4662 memcg = parent_mem_cgroup(memcg);
4666 static int compare_thresholds(const void *a, const void *b)
4668 const struct mem_cgroup_threshold *_a = a;
4669 const struct mem_cgroup_threshold *_b = b;
4671 if (_a->threshold > _b->threshold)
4674 if (_a->threshold < _b->threshold)
4680 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
4682 struct mem_cgroup_eventfd_list *ev;
4684 spin_lock(&memcg_oom_lock);
4686 list_for_each_entry(ev, &memcg->oom_notify, list)
4687 eventfd_signal(ev->eventfd);
4689 spin_unlock(&memcg_oom_lock);
4693 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
4695 struct mem_cgroup *iter;
4697 for_each_mem_cgroup_tree(iter, memcg)
4698 mem_cgroup_oom_notify_cb(iter);
4701 static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4702 struct eventfd_ctx *eventfd, const char *args, enum res_type type)
4704 struct mem_cgroup_thresholds *thresholds;
4705 struct mem_cgroup_threshold_ary *new;
4706 unsigned long threshold;
4707 unsigned long usage;
4710 ret = page_counter_memparse(args, "-1", &threshold);
4714 mutex_lock(&memcg->thresholds_lock);
4717 thresholds = &memcg->thresholds;
4718 usage = mem_cgroup_usage(memcg, false);
4719 } else if (type == _MEMSWAP) {
4720 thresholds = &memcg->memsw_thresholds;
4721 usage = mem_cgroup_usage(memcg, true);
4725 /* Check if a threshold crossed before adding a new one */
4726 if (thresholds->primary)
4727 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4729 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4731 /* Allocate memory for new array of thresholds */
4732 new = kmalloc(struct_size(new, entries, size), GFP_KERNEL);
4739 /* Copy thresholds (if any) to new array */
4740 if (thresholds->primary)
4741 memcpy(new->entries, thresholds->primary->entries,
4742 flex_array_size(new, entries, size - 1));
4744 /* Add new threshold */
4745 new->entries[size - 1].eventfd = eventfd;
4746 new->entries[size - 1].threshold = threshold;
4748 /* Sort thresholds. Registering of new threshold isn't time-critical */
4749 sort(new->entries, size, sizeof(*new->entries),
4750 compare_thresholds, NULL);
4752 /* Find current threshold */
4753 new->current_threshold = -1;
4754 for (i = 0; i < size; i++) {
4755 if (new->entries[i].threshold <= usage) {
4757 * new->current_threshold will not be used until
4758 * rcu_assign_pointer(), so it's safe to increment
4761 ++new->current_threshold;
4766 /* Free old spare buffer and save old primary buffer as spare */
4767 kfree(thresholds->spare);
4768 thresholds->spare = thresholds->primary;
4770 rcu_assign_pointer(thresholds->primary, new);
4772 /* To be sure that nobody uses thresholds */
4776 mutex_unlock(&memcg->thresholds_lock);
4781 static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4782 struct eventfd_ctx *eventfd, const char *args)
4784 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
4787 static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
4788 struct eventfd_ctx *eventfd, const char *args)
4790 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
4793 static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4794 struct eventfd_ctx *eventfd, enum res_type type)
4796 struct mem_cgroup_thresholds *thresholds;
4797 struct mem_cgroup_threshold_ary *new;
4798 unsigned long usage;
4799 int i, j, size, entries;
4801 mutex_lock(&memcg->thresholds_lock);
4804 thresholds = &memcg->thresholds;
4805 usage = mem_cgroup_usage(memcg, false);
4806 } else if (type == _MEMSWAP) {
4807 thresholds = &memcg->memsw_thresholds;
4808 usage = mem_cgroup_usage(memcg, true);
4812 if (!thresholds->primary)
4815 /* Check if a threshold crossed before removing */
4816 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4818 /* Calculate new number of threshold */
4820 for (i = 0; i < thresholds->primary->size; i++) {
4821 if (thresholds->primary->entries[i].eventfd != eventfd)
4827 new = thresholds->spare;
4829 /* If no items related to eventfd have been cleared, nothing to do */
4833 /* Set thresholds array to NULL if we don't have thresholds */
4842 /* Copy thresholds and find current threshold */
4843 new->current_threshold = -1;
4844 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4845 if (thresholds->primary->entries[i].eventfd == eventfd)
4848 new->entries[j] = thresholds->primary->entries[i];
4849 if (new->entries[j].threshold <= usage) {
4851 * new->current_threshold will not be used
4852 * until rcu_assign_pointer(), so it's safe to increment
4855 ++new->current_threshold;
4861 /* Swap primary and spare array */
4862 thresholds->spare = thresholds->primary;
4864 rcu_assign_pointer(thresholds->primary, new);
4866 /* To be sure that nobody uses thresholds */
4869 /* If all events are unregistered, free the spare array */
4871 kfree(thresholds->spare);
4872 thresholds->spare = NULL;
4875 mutex_unlock(&memcg->thresholds_lock);
4878 static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4879 struct eventfd_ctx *eventfd)
4881 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
4884 static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4885 struct eventfd_ctx *eventfd)
4887 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
4890 static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
4891 struct eventfd_ctx *eventfd, const char *args)
4893 struct mem_cgroup_eventfd_list *event;
4895 event = kmalloc(sizeof(*event), GFP_KERNEL);
4899 spin_lock(&memcg_oom_lock);
4901 event->eventfd = eventfd;
4902 list_add(&event->list, &memcg->oom_notify);
4904 /* already in OOM ? */
4905 if (memcg->under_oom)
4906 eventfd_signal(eventfd);
4907 spin_unlock(&memcg_oom_lock);
4912 static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
4913 struct eventfd_ctx *eventfd)
4915 struct mem_cgroup_eventfd_list *ev, *tmp;
4917 spin_lock(&memcg_oom_lock);
4919 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
4920 if (ev->eventfd == eventfd) {
4921 list_del(&ev->list);
4926 spin_unlock(&memcg_oom_lock);
4929 static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
4931 struct mem_cgroup *memcg = mem_cgroup_from_seq(sf);
4933 seq_printf(sf, "oom_kill_disable %d\n", READ_ONCE(memcg->oom_kill_disable));
4934 seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
4935 seq_printf(sf, "oom_kill %lu\n",
4936 atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
4940 static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
4941 struct cftype *cft, u64 val)
4943 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4945 /* cannot set to root cgroup and only 0 and 1 are allowed */
4946 if (mem_cgroup_is_root(memcg) || !((val == 0) || (val == 1)))
4949 WRITE_ONCE(memcg->oom_kill_disable, val);
4951 memcg_oom_recover(memcg);
4956 #ifdef CONFIG_CGROUP_WRITEBACK
4958 #include <trace/events/writeback.h>
4960 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4962 return wb_domain_init(&memcg->cgwb_domain, gfp);
4965 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4967 wb_domain_exit(&memcg->cgwb_domain);
4970 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4972 wb_domain_size_changed(&memcg->cgwb_domain);
4975 struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
4977 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4979 if (!memcg->css.parent)
4982 return &memcg->cgwb_domain;
4986 * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
4987 * @wb: bdi_writeback in question
4988 * @pfilepages: out parameter for number of file pages
4989 * @pheadroom: out parameter for number of allocatable pages according to memcg
4990 * @pdirty: out parameter for number of dirty pages
4991 * @pwriteback: out parameter for number of pages under writeback
4993 * Determine the numbers of file, headroom, dirty, and writeback pages in
4994 * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom
4995 * is a bit more involved.
4997 * A memcg's headroom is "min(max, high) - used". In the hierarchy, the
4998 * headroom is calculated as the lowest headroom of itself and the
4999 * ancestors. Note that this doesn't consider the actual amount of
5000 * available memory in the system. The caller should further cap
5001 * *@pheadroom accordingly.
5003 void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
5004 unsigned long *pheadroom, unsigned long *pdirty,
5005 unsigned long *pwriteback)
5007 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
5008 struct mem_cgroup *parent;
5010 mem_cgroup_flush_stats_ratelimited(memcg);
5012 *pdirty = memcg_page_state(memcg, NR_FILE_DIRTY);
5013 *pwriteback = memcg_page_state(memcg, NR_WRITEBACK);
5014 *pfilepages = memcg_page_state(memcg, NR_INACTIVE_FILE) +
5015 memcg_page_state(memcg, NR_ACTIVE_FILE);
5017 *pheadroom = PAGE_COUNTER_MAX;
5018 while ((parent = parent_mem_cgroup(memcg))) {
5019 unsigned long ceiling = min(READ_ONCE(memcg->memory.max),
5020 READ_ONCE(memcg->memory.high));
5021 unsigned long used = page_counter_read(&memcg->memory);
5023 *pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
5029 * Foreign dirty flushing
5031 * There's an inherent mismatch between memcg and writeback. The former
5032 * tracks ownership per-page while the latter per-inode. This was a
5033 * deliberate design decision because honoring per-page ownership in the
5034 * writeback path is complicated, may lead to higher CPU and IO overheads
5035 * and deemed unnecessary given that write-sharing an inode across
5036 * different cgroups isn't a common use-case.
5038 * Combined with inode majority-writer ownership switching, this works well
5039 * enough in most cases but there are some pathological cases. For
5040 * example, let's say there are two cgroups A and B which keep writing to
5041 * different but confined parts of the same inode. B owns the inode and
5042 * A's memory is limited far below B's. A's dirty ratio can rise enough to
5043 * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
5044 * triggering background writeback. A will be slowed down without a way to
5045 * make writeback of the dirty pages happen.
5047 * Conditions like the above can lead to a cgroup getting repeatedly and
5048 * severely throttled after making some progress after each
5049 * dirty_expire_interval while the underlying IO device is almost
5052 * Solving this problem completely requires matching the ownership tracking
5053 * granularities between memcg and writeback in either direction. However,
5054 * the more egregious behaviors can be avoided by simply remembering the
5055 * most recent foreign dirtying events and initiating remote flushes on
5056 * them when local writeback isn't enough to keep the memory clean enough.
5058 * The following two functions implement such mechanism. When a foreign
5059 * page - a page whose memcg and writeback ownerships don't match - is
5060 * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
5061 * bdi_writeback on the page owning memcg. When balance_dirty_pages()
5062 * decides that the memcg needs to sleep due to high dirty ratio, it calls
5063 * mem_cgroup_flush_foreign() which queues writeback on the recorded
5064 * foreign bdi_writebacks which haven't expired. Both the numbers of
5065 * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
5066 * limited to MEMCG_CGWB_FRN_CNT.
5068 * The mechanism only remembers IDs and doesn't hold any object references.
5069 * As being wrong occasionally doesn't matter, updates and accesses to the
5070 * records are lockless and racy.
5072 void mem_cgroup_track_foreign_dirty_slowpath(struct folio *folio,
5073 struct bdi_writeback *wb)
5075 struct mem_cgroup *memcg = folio_memcg(folio);
5076 struct memcg_cgwb_frn *frn;
5077 u64 now = get_jiffies_64();
5078 u64 oldest_at = now;
5082 trace_track_foreign_dirty(folio, wb);
5085 * Pick the slot to use. If there is already a slot for @wb, keep
5086 * using it. If not replace the oldest one which isn't being
5089 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
5090 frn = &memcg->cgwb_frn[i];
5091 if (frn->bdi_id == wb->bdi->id &&
5092 frn->memcg_id == wb->memcg_css->id)
5094 if (time_before64(frn->at, oldest_at) &&
5095 atomic_read(&frn->done.cnt) == 1) {
5097 oldest_at = frn->at;
5101 if (i < MEMCG_CGWB_FRN_CNT) {
5103 * Re-using an existing one. Update timestamp lazily to
5104 * avoid making the cacheline hot. We want them to be
5105 * reasonably up-to-date and significantly shorter than
5106 * dirty_expire_interval as that's what expires the record.
5107 * Use the shorter of 1s and dirty_expire_interval / 8.
5109 unsigned long update_intv =
5110 min_t(unsigned long, HZ,
5111 msecs_to_jiffies(dirty_expire_interval * 10) / 8);
5113 if (time_before64(frn->at, now - update_intv))
5115 } else if (oldest >= 0) {
5116 /* replace the oldest free one */
5117 frn = &memcg->cgwb_frn[oldest];
5118 frn->bdi_id = wb->bdi->id;
5119 frn->memcg_id = wb->memcg_css->id;
5124 /* issue foreign writeback flushes for recorded foreign dirtying events */
5125 void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
5127 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
5128 unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
5129 u64 now = jiffies_64;
5132 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
5133 struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
5136 * If the record is older than dirty_expire_interval,
5137 * writeback on it has already started. No need to kick it
5138 * off again. Also, don't start a new one if there's
5139 * already one in flight.
5141 if (time_after64(frn->at, now - intv) &&
5142 atomic_read(&frn->done.cnt) == 1) {
5144 trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
5145 cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id,
5146 WB_REASON_FOREIGN_FLUSH,
5152 #else /* CONFIG_CGROUP_WRITEBACK */
5154 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
5159 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
5163 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
5167 #endif /* CONFIG_CGROUP_WRITEBACK */
5170 * DO NOT USE IN NEW FILES.
5172 * "cgroup.event_control" implementation.
5174 * This is way over-engineered. It tries to support fully configurable
5175 * events for each user. Such level of flexibility is completely
5176 * unnecessary especially in the light of the planned unified hierarchy.
5178 * Please deprecate this and replace with something simpler if at all
5183 * Unregister event and free resources.
5185 * Gets called from workqueue.
5187 static void memcg_event_remove(struct work_struct *work)
5189 struct mem_cgroup_event *event =
5190 container_of(work, struct mem_cgroup_event, remove);
5191 struct mem_cgroup *memcg = event->memcg;
5193 remove_wait_queue(event->wqh, &event->wait);
5195 event->unregister_event(memcg, event->eventfd);
5197 /* Notify userspace the event is going away. */
5198 eventfd_signal(event->eventfd);
5200 eventfd_ctx_put(event->eventfd);
5202 css_put(&memcg->css);
5206 * Gets called on EPOLLHUP on eventfd when user closes it.
5208 * Called with wqh->lock held and interrupts disabled.
5210 static int memcg_event_wake(wait_queue_entry_t *wait, unsigned mode,
5211 int sync, void *key)
5213 struct mem_cgroup_event *event =
5214 container_of(wait, struct mem_cgroup_event, wait);
5215 struct mem_cgroup *memcg = event->memcg;
5216 __poll_t flags = key_to_poll(key);
5218 if (flags & EPOLLHUP) {
5220 * If the event has been detached at cgroup removal, we
5221 * can simply return knowing the other side will cleanup
5224 * We can't race against event freeing since the other
5225 * side will require wqh->lock via remove_wait_queue(),
5228 spin_lock(&memcg->event_list_lock);
5229 if (!list_empty(&event->list)) {
5230 list_del_init(&event->list);
5232 * We are in atomic context, but cgroup_event_remove()
5233 * may sleep, so we have to call it in workqueue.
5235 schedule_work(&event->remove);
5237 spin_unlock(&memcg->event_list_lock);
5243 static void memcg_event_ptable_queue_proc(struct file *file,
5244 wait_queue_head_t *wqh, poll_table *pt)
5246 struct mem_cgroup_event *event =
5247 container_of(pt, struct mem_cgroup_event, pt);
5250 add_wait_queue(wqh, &event->wait);
5254 * DO NOT USE IN NEW FILES.
5256 * Parse input and register new cgroup event handler.
5258 * Input must be in format '<event_fd> <control_fd> <args>'.
5259 * Interpretation of args is defined by control file implementation.
5261 static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
5262 char *buf, size_t nbytes, loff_t off)
5264 struct cgroup_subsys_state *css = of_css(of);
5265 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5266 struct mem_cgroup_event *event;
5267 struct cgroup_subsys_state *cfile_css;
5268 unsigned int efd, cfd;
5271 struct dentry *cdentry;
5276 if (IS_ENABLED(CONFIG_PREEMPT_RT))
5279 buf = strstrip(buf);
5281 efd = simple_strtoul(buf, &endp, 10);
5286 cfd = simple_strtoul(buf, &endp, 10);
5287 if ((*endp != ' ') && (*endp != '\0'))
5291 event = kzalloc(sizeof(*event), GFP_KERNEL);
5295 event->memcg = memcg;
5296 INIT_LIST_HEAD(&event->list);
5297 init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
5298 init_waitqueue_func_entry(&event->wait, memcg_event_wake);
5299 INIT_WORK(&event->remove, memcg_event_remove);
5307 event->eventfd = eventfd_ctx_fileget(efile.file);
5308 if (IS_ERR(event->eventfd)) {
5309 ret = PTR_ERR(event->eventfd);
5316 goto out_put_eventfd;
5319 /* the process need read permission on control file */
5320 /* AV: shouldn't we check that it's been opened for read instead? */
5321 ret = file_permission(cfile.file, MAY_READ);
5326 * The control file must be a regular cgroup1 file. As a regular cgroup
5327 * file can't be renamed, it's safe to access its name afterwards.
5329 cdentry = cfile.file->f_path.dentry;
5330 if (cdentry->d_sb->s_type != &cgroup_fs_type || !d_is_reg(cdentry)) {
5336 * Determine the event callbacks and set them in @event. This used
5337 * to be done via struct cftype but cgroup core no longer knows
5338 * about these events. The following is crude but the whole thing
5339 * is for compatibility anyway.
5341 * DO NOT ADD NEW FILES.
5343 name = cdentry->d_name.name;
5345 if (!strcmp(name, "memory.usage_in_bytes")) {
5346 event->register_event = mem_cgroup_usage_register_event;
5347 event->unregister_event = mem_cgroup_usage_unregister_event;
5348 } else if (!strcmp(name, "memory.oom_control")) {
5349 event->register_event = mem_cgroup_oom_register_event;
5350 event->unregister_event = mem_cgroup_oom_unregister_event;
5351 } else if (!strcmp(name, "memory.pressure_level")) {
5352 event->register_event = vmpressure_register_event;
5353 event->unregister_event = vmpressure_unregister_event;
5354 } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
5355 event->register_event = memsw_cgroup_usage_register_event;
5356 event->unregister_event = memsw_cgroup_usage_unregister_event;
5363 * Verify @cfile should belong to @css. Also, remaining events are
5364 * automatically removed on cgroup destruction but the removal is
5365 * asynchronous, so take an extra ref on @css.
5367 cfile_css = css_tryget_online_from_dir(cdentry->d_parent,
5368 &memory_cgrp_subsys);
5370 if (IS_ERR(cfile_css))
5372 if (cfile_css != css) {
5377 ret = event->register_event(memcg, event->eventfd, buf);
5381 vfs_poll(efile.file, &event->pt);
5383 spin_lock_irq(&memcg->event_list_lock);
5384 list_add(&event->list, &memcg->event_list);
5385 spin_unlock_irq(&memcg->event_list_lock);
5397 eventfd_ctx_put(event->eventfd);
5406 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_SLUB_DEBUG)
5407 static int mem_cgroup_slab_show(struct seq_file *m, void *p)
5411 * Please, take a look at tools/cgroup/memcg_slabinfo.py .
5417 static int memory_stat_show(struct seq_file *m, void *v);
5419 static struct cftype mem_cgroup_legacy_files[] = {
5421 .name = "usage_in_bytes",
5422 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
5423 .read_u64 = mem_cgroup_read_u64,
5426 .name = "max_usage_in_bytes",
5427 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
5428 .write = mem_cgroup_reset,
5429 .read_u64 = mem_cgroup_read_u64,
5432 .name = "limit_in_bytes",
5433 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
5434 .write = mem_cgroup_write,
5435 .read_u64 = mem_cgroup_read_u64,
5438 .name = "soft_limit_in_bytes",
5439 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
5440 .write = mem_cgroup_write,
5441 .read_u64 = mem_cgroup_read_u64,
5445 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
5446 .write = mem_cgroup_reset,
5447 .read_u64 = mem_cgroup_read_u64,
5451 .seq_show = memory_stat_show,
5454 .name = "force_empty",
5455 .write = mem_cgroup_force_empty_write,
5458 .name = "use_hierarchy",
5459 .write_u64 = mem_cgroup_hierarchy_write,
5460 .read_u64 = mem_cgroup_hierarchy_read,
5463 .name = "cgroup.event_control", /* XXX: for compat */
5464 .write = memcg_write_event_control,
5465 .flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE,
5468 .name = "swappiness",
5469 .read_u64 = mem_cgroup_swappiness_read,
5470 .write_u64 = mem_cgroup_swappiness_write,
5473 .name = "move_charge_at_immigrate",
5474 .read_u64 = mem_cgroup_move_charge_read,
5475 .write_u64 = mem_cgroup_move_charge_write,
5478 .name = "oom_control",
5479 .seq_show = mem_cgroup_oom_control_read,
5480 .write_u64 = mem_cgroup_oom_control_write,
5483 .name = "pressure_level",
5484 .seq_show = mem_cgroup_dummy_seq_show,
5488 .name = "numa_stat",
5489 .seq_show = memcg_numa_stat_show,
5493 .name = "kmem.limit_in_bytes",
5494 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
5495 .write = mem_cgroup_write,
5496 .read_u64 = mem_cgroup_read_u64,
5499 .name = "kmem.usage_in_bytes",
5500 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
5501 .read_u64 = mem_cgroup_read_u64,
5504 .name = "kmem.failcnt",
5505 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
5506 .write = mem_cgroup_reset,
5507 .read_u64 = mem_cgroup_read_u64,
5510 .name = "kmem.max_usage_in_bytes",
5511 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
5512 .write = mem_cgroup_reset,
5513 .read_u64 = mem_cgroup_read_u64,
5515 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_SLUB_DEBUG)
5517 .name = "kmem.slabinfo",
5518 .seq_show = mem_cgroup_slab_show,
5522 .name = "kmem.tcp.limit_in_bytes",
5523 .private = MEMFILE_PRIVATE(_TCP, RES_LIMIT),
5524 .write = mem_cgroup_write,
5525 .read_u64 = mem_cgroup_read_u64,
5528 .name = "kmem.tcp.usage_in_bytes",
5529 .private = MEMFILE_PRIVATE(_TCP, RES_USAGE),
5530 .read_u64 = mem_cgroup_read_u64,
5533 .name = "kmem.tcp.failcnt",
5534 .private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT),
5535 .write = mem_cgroup_reset,
5536 .read_u64 = mem_cgroup_read_u64,
5539 .name = "kmem.tcp.max_usage_in_bytes",
5540 .private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE),
5541 .write = mem_cgroup_reset,
5542 .read_u64 = mem_cgroup_read_u64,
5544 { }, /* terminate */
5548 * Private memory cgroup IDR
5550 * Swap-out records and page cache shadow entries need to store memcg
5551 * references in constrained space, so we maintain an ID space that is
5552 * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
5553 * memory-controlled cgroups to 64k.
5555 * However, there usually are many references to the offline CSS after
5556 * the cgroup has been destroyed, such as page cache or reclaimable
5557 * slab objects, that don't need to hang on to the ID. We want to keep
5558 * those dead CSS from occupying IDs, or we might quickly exhaust the
5559 * relatively small ID space and prevent the creation of new cgroups
5560 * even when there are much fewer than 64k cgroups - possibly none.
5562 * Maintain a private 16-bit ID space for memcg, and allow the ID to
5563 * be freed and recycled when it's no longer needed, which is usually
5564 * when the CSS is offlined.
5566 * The only exception to that are records of swapped out tmpfs/shmem
5567 * pages that need to be attributed to live ancestors on swapin. But
5568 * those references are manageable from userspace.
5571 #define MEM_CGROUP_ID_MAX ((1UL << MEM_CGROUP_ID_SHIFT) - 1)
5572 static DEFINE_IDR(mem_cgroup_idr);
5574 static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
5576 if (memcg->id.id > 0) {
5577 idr_remove(&mem_cgroup_idr, memcg->id.id);
5582 static void __maybe_unused mem_cgroup_id_get_many(struct mem_cgroup *memcg,
5585 refcount_add(n, &memcg->id.ref);
5588 static void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
5590 if (refcount_sub_and_test(n, &memcg->id.ref)) {
5591 mem_cgroup_id_remove(memcg);
5593 /* Memcg ID pins CSS */
5594 css_put(&memcg->css);
5598 static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
5600 mem_cgroup_id_put_many(memcg, 1);
5604 * mem_cgroup_from_id - look up a memcg from a memcg id
5605 * @id: the memcg id to look up
5607 * Caller must hold rcu_read_lock().
5609 struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
5611 WARN_ON_ONCE(!rcu_read_lock_held());
5612 return idr_find(&mem_cgroup_idr, id);
5615 #ifdef CONFIG_SHRINKER_DEBUG
5616 struct mem_cgroup *mem_cgroup_get_from_ino(unsigned long ino)
5618 struct cgroup *cgrp;
5619 struct cgroup_subsys_state *css;
5620 struct mem_cgroup *memcg;
5622 cgrp = cgroup_get_from_id(ino);
5624 return ERR_CAST(cgrp);
5626 css = cgroup_get_e_css(cgrp, &memory_cgrp_subsys);
5628 memcg = container_of(css, struct mem_cgroup, css);
5630 memcg = ERR_PTR(-ENOENT);
5638 static bool alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5640 struct mem_cgroup_per_node *pn;
5642 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, node);
5646 pn->lruvec_stats = kzalloc_node(sizeof(struct lruvec_stats),
5647 GFP_KERNEL_ACCOUNT, node);
5648 if (!pn->lruvec_stats)
5651 pn->lruvec_stats_percpu = alloc_percpu_gfp(struct lruvec_stats_percpu,
5652 GFP_KERNEL_ACCOUNT);
5653 if (!pn->lruvec_stats_percpu)
5656 lruvec_init(&pn->lruvec);
5659 memcg->nodeinfo[node] = pn;
5662 kfree(pn->lruvec_stats);
5667 static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5669 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
5674 free_percpu(pn->lruvec_stats_percpu);
5675 kfree(pn->lruvec_stats);
5679 static void __mem_cgroup_free(struct mem_cgroup *memcg)
5683 obj_cgroup_put(memcg->orig_objcg);
5686 free_mem_cgroup_per_node_info(memcg, node);
5687 kfree(memcg->vmstats);
5688 free_percpu(memcg->vmstats_percpu);
5692 static void mem_cgroup_free(struct mem_cgroup *memcg)
5694 lru_gen_exit_memcg(memcg);
5695 memcg_wb_domain_exit(memcg);
5696 __mem_cgroup_free(memcg);
5699 static struct mem_cgroup *mem_cgroup_alloc(struct mem_cgroup *parent)
5701 struct memcg_vmstats_percpu *statc, *pstatc;
5702 struct mem_cgroup *memcg;
5704 int __maybe_unused i;
5705 long error = -ENOMEM;
5707 memcg = kzalloc(struct_size(memcg, nodeinfo, nr_node_ids), GFP_KERNEL);
5709 return ERR_PTR(error);
5711 memcg->id.id = idr_alloc(&mem_cgroup_idr, NULL,
5712 1, MEM_CGROUP_ID_MAX + 1, GFP_KERNEL);
5713 if (memcg->id.id < 0) {
5714 error = memcg->id.id;
5718 memcg->vmstats = kzalloc(sizeof(struct memcg_vmstats),
5719 GFP_KERNEL_ACCOUNT);
5720 if (!memcg->vmstats)
5723 memcg->vmstats_percpu = alloc_percpu_gfp(struct memcg_vmstats_percpu,
5724 GFP_KERNEL_ACCOUNT);
5725 if (!memcg->vmstats_percpu)
5728 for_each_possible_cpu(cpu) {
5730 pstatc = per_cpu_ptr(parent->vmstats_percpu, cpu);
5731 statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
5732 statc->parent = parent ? pstatc : NULL;
5733 statc->vmstats = memcg->vmstats;
5737 if (!alloc_mem_cgroup_per_node_info(memcg, node))
5740 if (memcg_wb_domain_init(memcg, GFP_KERNEL))
5743 INIT_WORK(&memcg->high_work, high_work_func);
5744 INIT_LIST_HEAD(&memcg->oom_notify);
5745 mutex_init(&memcg->thresholds_lock);
5746 spin_lock_init(&memcg->move_lock);
5747 vmpressure_init(&memcg->vmpressure);
5748 INIT_LIST_HEAD(&memcg->event_list);
5749 spin_lock_init(&memcg->event_list_lock);
5750 memcg->socket_pressure = jiffies;
5751 #ifdef CONFIG_MEMCG_KMEM
5752 memcg->kmemcg_id = -1;
5753 INIT_LIST_HEAD(&memcg->objcg_list);
5755 #ifdef CONFIG_CGROUP_WRITEBACK
5756 INIT_LIST_HEAD(&memcg->cgwb_list);
5757 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5758 memcg->cgwb_frn[i].done =
5759 __WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
5761 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5762 spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
5763 INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
5764 memcg->deferred_split_queue.split_queue_len = 0;
5766 lru_gen_init_memcg(memcg);
5769 mem_cgroup_id_remove(memcg);
5770 __mem_cgroup_free(memcg);
5771 return ERR_PTR(error);
5774 static struct cgroup_subsys_state * __ref
5775 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
5777 struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
5778 struct mem_cgroup *memcg, *old_memcg;
5780 old_memcg = set_active_memcg(parent);
5781 memcg = mem_cgroup_alloc(parent);
5782 set_active_memcg(old_memcg);
5784 return ERR_CAST(memcg);
5786 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5787 WRITE_ONCE(memcg->soft_limit, PAGE_COUNTER_MAX);
5788 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
5789 memcg->zswap_max = PAGE_COUNTER_MAX;
5790 WRITE_ONCE(memcg->zswap_writeback,
5791 !parent || READ_ONCE(parent->zswap_writeback));
5793 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5795 WRITE_ONCE(memcg->swappiness, mem_cgroup_swappiness(parent));
5796 WRITE_ONCE(memcg->oom_kill_disable, READ_ONCE(parent->oom_kill_disable));
5798 page_counter_init(&memcg->memory, &parent->memory);
5799 page_counter_init(&memcg->swap, &parent->swap);
5800 page_counter_init(&memcg->kmem, &parent->kmem);
5801 page_counter_init(&memcg->tcpmem, &parent->tcpmem);
5804 init_memcg_events();
5805 page_counter_init(&memcg->memory, NULL);
5806 page_counter_init(&memcg->swap, NULL);
5807 page_counter_init(&memcg->kmem, NULL);
5808 page_counter_init(&memcg->tcpmem, NULL);
5810 root_mem_cgroup = memcg;
5814 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5815 static_branch_inc(&memcg_sockets_enabled_key);
5817 #if defined(CONFIG_MEMCG_KMEM)
5818 if (!cgroup_memory_nobpf)
5819 static_branch_inc(&memcg_bpf_enabled_key);
5825 static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
5827 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5829 if (memcg_online_kmem(memcg))
5833 * A memcg must be visible for expand_shrinker_info()
5834 * by the time the maps are allocated. So, we allocate maps
5835 * here, when for_each_mem_cgroup() can't skip it.
5837 if (alloc_shrinker_info(memcg))
5840 if (unlikely(mem_cgroup_is_root(memcg)) && !mem_cgroup_disabled())
5841 queue_delayed_work(system_unbound_wq, &stats_flush_dwork,
5843 lru_gen_online_memcg(memcg);
5845 /* Online state pins memcg ID, memcg ID pins CSS */
5846 refcount_set(&memcg->id.ref, 1);
5850 * Ensure mem_cgroup_from_id() works once we're fully online.
5852 * We could do this earlier and require callers to filter with
5853 * css_tryget_online(). But right now there are no users that
5854 * need earlier access, and the workingset code relies on the
5855 * cgroup tree linkage (mem_cgroup_get_nr_swap_pages()). So
5856 * publish it here at the end of onlining. This matches the
5857 * regular ID destruction during offlining.
5859 idr_replace(&mem_cgroup_idr, memcg, memcg->id.id);
5863 memcg_offline_kmem(memcg);
5865 mem_cgroup_id_remove(memcg);
5869 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
5871 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5872 struct mem_cgroup_event *event, *tmp;
5875 * Unregister events and notify userspace.
5876 * Notify userspace about cgroup removing only after rmdir of cgroup
5877 * directory to avoid race between userspace and kernelspace.
5879 spin_lock_irq(&memcg->event_list_lock);
5880 list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
5881 list_del_init(&event->list);
5882 schedule_work(&event->remove);
5884 spin_unlock_irq(&memcg->event_list_lock);
5886 page_counter_set_min(&memcg->memory, 0);
5887 page_counter_set_low(&memcg->memory, 0);
5889 zswap_memcg_offline_cleanup(memcg);
5891 memcg_offline_kmem(memcg);
5892 reparent_shrinker_deferred(memcg);
5893 wb_memcg_offline(memcg);
5894 lru_gen_offline_memcg(memcg);
5896 drain_all_stock(memcg);
5898 mem_cgroup_id_put(memcg);
5901 static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
5903 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5905 invalidate_reclaim_iterators(memcg);
5906 lru_gen_release_memcg(memcg);
5909 static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
5911 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5912 int __maybe_unused i;
5914 #ifdef CONFIG_CGROUP_WRITEBACK
5915 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5916 wb_wait_for_completion(&memcg->cgwb_frn[i].done);
5918 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5919 static_branch_dec(&memcg_sockets_enabled_key);
5921 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg->tcpmem_active)
5922 static_branch_dec(&memcg_sockets_enabled_key);
5924 #if defined(CONFIG_MEMCG_KMEM)
5925 if (!cgroup_memory_nobpf)
5926 static_branch_dec(&memcg_bpf_enabled_key);
5929 vmpressure_cleanup(&memcg->vmpressure);
5930 cancel_work_sync(&memcg->high_work);
5931 mem_cgroup_remove_from_trees(memcg);
5932 free_shrinker_info(memcg);
5933 mem_cgroup_free(memcg);
5937 * mem_cgroup_css_reset - reset the states of a mem_cgroup
5938 * @css: the target css
5940 * Reset the states of the mem_cgroup associated with @css. This is
5941 * invoked when the userland requests disabling on the default hierarchy
5942 * but the memcg is pinned through dependency. The memcg should stop
5943 * applying policies and should revert to the vanilla state as it may be
5944 * made visible again.
5946 * The current implementation only resets the essential configurations.
5947 * This needs to be expanded to cover all the visible parts.
5949 static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
5951 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5953 page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
5954 page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
5955 page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
5956 page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
5957 page_counter_set_min(&memcg->memory, 0);
5958 page_counter_set_low(&memcg->memory, 0);
5959 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5960 WRITE_ONCE(memcg->soft_limit, PAGE_COUNTER_MAX);
5961 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5962 memcg_wb_domain_size_changed(memcg);
5965 static void mem_cgroup_css_rstat_flush(struct cgroup_subsys_state *css, int cpu)
5967 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5968 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
5969 struct memcg_vmstats_percpu *statc;
5970 long delta, delta_cpu, v;
5973 statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
5975 for (i = 0; i < MEMCG_VMSTAT_SIZE; i++) {
5977 * Collect the aggregated propagation counts of groups
5978 * below us. We're in a per-cpu loop here and this is
5979 * a global counter, so the first cycle will get them.
5981 delta = memcg->vmstats->state_pending[i];
5983 memcg->vmstats->state_pending[i] = 0;
5985 /* Add CPU changes on this level since the last flush */
5987 v = READ_ONCE(statc->state[i]);
5988 if (v != statc->state_prev[i]) {
5989 delta_cpu = v - statc->state_prev[i];
5991 statc->state_prev[i] = v;
5994 /* Aggregate counts on this level and propagate upwards */
5996 memcg->vmstats->state_local[i] += delta_cpu;
5999 memcg->vmstats->state[i] += delta;
6001 parent->vmstats->state_pending[i] += delta;
6005 for (i = 0; i < NR_MEMCG_EVENTS; i++) {
6006 delta = memcg->vmstats->events_pending[i];
6008 memcg->vmstats->events_pending[i] = 0;
6011 v = READ_ONCE(statc->events[i]);
6012 if (v != statc->events_prev[i]) {
6013 delta_cpu = v - statc->events_prev[i];
6015 statc->events_prev[i] = v;
6019 memcg->vmstats->events_local[i] += delta_cpu;
6022 memcg->vmstats->events[i] += delta;
6024 parent->vmstats->events_pending[i] += delta;
6028 for_each_node_state(nid, N_MEMORY) {
6029 struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
6030 struct lruvec_stats *lstats = pn->lruvec_stats;
6031 struct lruvec_stats *plstats = NULL;
6032 struct lruvec_stats_percpu *lstatc;
6035 plstats = parent->nodeinfo[nid]->lruvec_stats;
6037 lstatc = per_cpu_ptr(pn->lruvec_stats_percpu, cpu);
6039 for (i = 0; i < NR_MEMCG_NODE_STAT_ITEMS; i++) {
6040 delta = lstats->state_pending[i];
6042 lstats->state_pending[i] = 0;
6045 v = READ_ONCE(lstatc->state[i]);
6046 if (v != lstatc->state_prev[i]) {
6047 delta_cpu = v - lstatc->state_prev[i];
6049 lstatc->state_prev[i] = v;
6053 lstats->state_local[i] += delta_cpu;
6056 lstats->state[i] += delta;
6058 plstats->state_pending[i] += delta;
6062 WRITE_ONCE(statc->stats_updates, 0);
6063 /* We are in a per-cpu loop here, only do the atomic write once */
6064 if (atomic64_read(&memcg->vmstats->stats_updates))
6065 atomic64_set(&memcg->vmstats->stats_updates, 0);
6069 /* Handlers for move charge at task migration. */
6070 static int mem_cgroup_do_precharge(unsigned long count)
6074 /* Try a single bulk charge without reclaim first, kswapd may wake */
6075 ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count);
6077 mc.precharge += count;
6081 /* Try charges one by one with reclaim, but do not retry */
6083 ret = try_charge(mc.to, GFP_KERNEL | __GFP_NORETRY, 1);
6093 struct folio *folio;
6097 enum mc_target_type {
6104 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
6105 unsigned long addr, pte_t ptent)
6107 struct page *page = vm_normal_page(vma, addr, ptent);
6111 if (PageAnon(page)) {
6112 if (!(mc.flags & MOVE_ANON))
6115 if (!(mc.flags & MOVE_FILE))
6123 #if defined(CONFIG_SWAP) || defined(CONFIG_DEVICE_PRIVATE)
6124 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
6125 pte_t ptent, swp_entry_t *entry)
6127 struct page *page = NULL;
6128 swp_entry_t ent = pte_to_swp_entry(ptent);
6130 if (!(mc.flags & MOVE_ANON))
6134 * Handle device private pages that are not accessible by the CPU, but
6135 * stored as special swap entries in the page table.
6137 if (is_device_private_entry(ent)) {
6138 page = pfn_swap_entry_to_page(ent);
6139 if (!get_page_unless_zero(page))
6144 if (non_swap_entry(ent))
6148 * Because swap_cache_get_folio() updates some statistics counter,
6149 * we call find_get_page() with swapper_space directly.
6151 page = find_get_page(swap_address_space(ent), swp_offset(ent));
6152 entry->val = ent.val;
6157 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
6158 pte_t ptent, swp_entry_t *entry)
6164 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
6165 unsigned long addr, pte_t ptent)
6167 unsigned long index;
6168 struct folio *folio;
6170 if (!vma->vm_file) /* anonymous vma */
6172 if (!(mc.flags & MOVE_FILE))
6175 /* folio is moved even if it's not RSS of this task(page-faulted). */
6176 /* shmem/tmpfs may report page out on swap: account for that too. */
6177 index = linear_page_index(vma, addr);
6178 folio = filemap_get_incore_folio(vma->vm_file->f_mapping, index);
6181 return folio_file_page(folio, index);
6185 * mem_cgroup_move_account - move account of the folio
6186 * @folio: The folio.
6187 * @compound: charge the page as compound or small page
6188 * @from: mem_cgroup which the folio is moved from.
6189 * @to: mem_cgroup which the folio is moved to. @from != @to.
6191 * The folio must be locked and not on the LRU.
6193 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
6196 static int mem_cgroup_move_account(struct folio *folio,
6198 struct mem_cgroup *from,
6199 struct mem_cgroup *to)
6201 struct lruvec *from_vec, *to_vec;
6202 struct pglist_data *pgdat;
6203 unsigned int nr_pages = compound ? folio_nr_pages(folio) : 1;
6206 VM_BUG_ON(from == to);
6207 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
6208 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
6209 VM_BUG_ON(compound && !folio_test_large(folio));
6212 if (folio_memcg(folio) != from)
6215 pgdat = folio_pgdat(folio);
6216 from_vec = mem_cgroup_lruvec(from, pgdat);
6217 to_vec = mem_cgroup_lruvec(to, pgdat);
6219 folio_memcg_lock(folio);
6221 if (folio_test_anon(folio)) {
6222 if (folio_mapped(folio)) {
6223 __mod_lruvec_state(from_vec, NR_ANON_MAPPED, -nr_pages);
6224 __mod_lruvec_state(to_vec, NR_ANON_MAPPED, nr_pages);
6225 if (folio_test_pmd_mappable(folio)) {
6226 __mod_lruvec_state(from_vec, NR_ANON_THPS,
6228 __mod_lruvec_state(to_vec, NR_ANON_THPS,
6233 __mod_lruvec_state(from_vec, NR_FILE_PAGES, -nr_pages);
6234 __mod_lruvec_state(to_vec, NR_FILE_PAGES, nr_pages);
6236 if (folio_test_swapbacked(folio)) {
6237 __mod_lruvec_state(from_vec, NR_SHMEM, -nr_pages);
6238 __mod_lruvec_state(to_vec, NR_SHMEM, nr_pages);
6241 if (folio_mapped(folio)) {
6242 __mod_lruvec_state(from_vec, NR_FILE_MAPPED, -nr_pages);
6243 __mod_lruvec_state(to_vec, NR_FILE_MAPPED, nr_pages);
6246 if (folio_test_dirty(folio)) {
6247 struct address_space *mapping = folio_mapping(folio);
6249 if (mapping_can_writeback(mapping)) {
6250 __mod_lruvec_state(from_vec, NR_FILE_DIRTY,
6252 __mod_lruvec_state(to_vec, NR_FILE_DIRTY,
6259 if (folio_test_swapcache(folio)) {
6260 __mod_lruvec_state(from_vec, NR_SWAPCACHE, -nr_pages);
6261 __mod_lruvec_state(to_vec, NR_SWAPCACHE, nr_pages);
6264 if (folio_test_writeback(folio)) {
6265 __mod_lruvec_state(from_vec, NR_WRITEBACK, -nr_pages);
6266 __mod_lruvec_state(to_vec, NR_WRITEBACK, nr_pages);
6270 * All state has been migrated, let's switch to the new memcg.
6272 * It is safe to change page's memcg here because the page
6273 * is referenced, charged, isolated, and locked: we can't race
6274 * with (un)charging, migration, LRU putback, or anything else
6275 * that would rely on a stable page's memory cgroup.
6277 * Note that folio_memcg_lock is a memcg lock, not a page lock,
6278 * to save space. As soon as we switch page's memory cgroup to a
6279 * new memcg that isn't locked, the above state can change
6280 * concurrently again. Make sure we're truly done with it.
6285 css_put(&from->css);
6287 folio->memcg_data = (unsigned long)to;
6289 __folio_memcg_unlock(from);
6292 nid = folio_nid(folio);
6294 local_irq_disable();
6295 mem_cgroup_charge_statistics(to, nr_pages);
6296 memcg_check_events(to, nid);
6297 mem_cgroup_charge_statistics(from, -nr_pages);
6298 memcg_check_events(from, nid);
6305 * get_mctgt_type - get target type of moving charge
6306 * @vma: the vma the pte to be checked belongs
6307 * @addr: the address corresponding to the pte to be checked
6308 * @ptent: the pte to be checked
6309 * @target: the pointer the target page or swap ent will be stored(can be NULL)
6311 * Context: Called with pte lock held.
6313 * * MC_TARGET_NONE - If the pte is not a target for move charge.
6314 * * MC_TARGET_PAGE - If the page corresponding to this pte is a target for
6315 * move charge. If @target is not NULL, the folio is stored in target->folio
6316 * with extra refcnt taken (Caller should release it).
6317 * * MC_TARGET_SWAP - If the swap entry corresponding to this pte is a
6318 * target for charge migration. If @target is not NULL, the entry is
6319 * stored in target->ent.
6320 * * MC_TARGET_DEVICE - Like MC_TARGET_PAGE but page is device memory and
6321 * thus not on the lru. For now such page is charged like a regular page
6322 * would be as it is just special memory taking the place of a regular page.
6323 * See Documentations/vm/hmm.txt and include/linux/hmm.h
6325 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
6326 unsigned long addr, pte_t ptent, union mc_target *target)
6328 struct page *page = NULL;
6329 struct folio *folio;
6330 enum mc_target_type ret = MC_TARGET_NONE;
6331 swp_entry_t ent = { .val = 0 };
6333 if (pte_present(ptent))
6334 page = mc_handle_present_pte(vma, addr, ptent);
6335 else if (pte_none_mostly(ptent))
6337 * PTE markers should be treated as a none pte here, separated
6338 * from other swap handling below.
6340 page = mc_handle_file_pte(vma, addr, ptent);
6341 else if (is_swap_pte(ptent))
6342 page = mc_handle_swap_pte(vma, ptent, &ent);
6345 folio = page_folio(page);
6346 if (target && page) {
6347 if (!folio_trylock(folio)) {
6352 * page_mapped() must be stable during the move. This
6353 * pte is locked, so if it's present, the page cannot
6354 * become unmapped. If it isn't, we have only partial
6355 * control over the mapped state: the page lock will
6356 * prevent new faults against pagecache and swapcache,
6357 * so an unmapped page cannot become mapped. However,
6358 * if the page is already mapped elsewhere, it can
6359 * unmap, and there is nothing we can do about it.
6360 * Alas, skip moving the page in this case.
6362 if (!pte_present(ptent) && page_mapped(page)) {
6363 folio_unlock(folio);
6369 if (!page && !ent.val)
6373 * Do only loose check w/o serialization.
6374 * mem_cgroup_move_account() checks the page is valid or
6375 * not under LRU exclusion.
6377 if (folio_memcg(folio) == mc.from) {
6378 ret = MC_TARGET_PAGE;
6379 if (folio_is_device_private(folio) ||
6380 folio_is_device_coherent(folio))
6381 ret = MC_TARGET_DEVICE;
6383 target->folio = folio;
6385 if (!ret || !target) {
6387 folio_unlock(folio);
6392 * There is a swap entry and a page doesn't exist or isn't charged.
6393 * But we cannot move a tail-page in a THP.
6395 if (ent.val && !ret && (!page || !PageTransCompound(page)) &&
6396 mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
6397 ret = MC_TARGET_SWAP;
6404 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
6406 * We don't consider PMD mapped swapping or file mapped pages because THP does
6407 * not support them for now.
6408 * Caller should make sure that pmd_trans_huge(pmd) is true.
6410 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
6411 unsigned long addr, pmd_t pmd, union mc_target *target)
6413 struct page *page = NULL;
6414 struct folio *folio;
6415 enum mc_target_type ret = MC_TARGET_NONE;
6417 if (unlikely(is_swap_pmd(pmd))) {
6418 VM_BUG_ON(thp_migration_supported() &&
6419 !is_pmd_migration_entry(pmd));
6422 page = pmd_page(pmd);
6423 VM_BUG_ON_PAGE(!page || !PageHead(page), page);
6424 folio = page_folio(page);
6425 if (!(mc.flags & MOVE_ANON))
6427 if (folio_memcg(folio) == mc.from) {
6428 ret = MC_TARGET_PAGE;
6431 if (!folio_trylock(folio)) {
6433 return MC_TARGET_NONE;
6435 target->folio = folio;
6441 static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
6442 unsigned long addr, pmd_t pmd, union mc_target *target)
6444 return MC_TARGET_NONE;
6448 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
6449 unsigned long addr, unsigned long end,
6450 struct mm_walk *walk)
6452 struct vm_area_struct *vma = walk->vma;
6456 ptl = pmd_trans_huge_lock(pmd, vma);
6459 * Note their can not be MC_TARGET_DEVICE for now as we do not
6460 * support transparent huge page with MEMORY_DEVICE_PRIVATE but
6461 * this might change.
6463 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
6464 mc.precharge += HPAGE_PMD_NR;
6469 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6472 for (; addr != end; pte++, addr += PAGE_SIZE)
6473 if (get_mctgt_type(vma, addr, ptep_get(pte), NULL))
6474 mc.precharge++; /* increment precharge temporarily */
6475 pte_unmap_unlock(pte - 1, ptl);
6481 static const struct mm_walk_ops precharge_walk_ops = {
6482 .pmd_entry = mem_cgroup_count_precharge_pte_range,
6483 .walk_lock = PGWALK_RDLOCK,
6486 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
6488 unsigned long precharge;
6491 walk_page_range(mm, 0, ULONG_MAX, &precharge_walk_ops, NULL);
6492 mmap_read_unlock(mm);
6494 precharge = mc.precharge;
6500 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
6502 unsigned long precharge = mem_cgroup_count_precharge(mm);
6504 VM_BUG_ON(mc.moving_task);
6505 mc.moving_task = current;
6506 return mem_cgroup_do_precharge(precharge);
6509 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
6510 static void __mem_cgroup_clear_mc(void)
6512 struct mem_cgroup *from = mc.from;
6513 struct mem_cgroup *to = mc.to;
6515 /* we must uncharge all the leftover precharges from mc.to */
6517 mem_cgroup_cancel_charge(mc.to, mc.precharge);
6521 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
6522 * we must uncharge here.
6524 if (mc.moved_charge) {
6525 mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
6526 mc.moved_charge = 0;
6528 /* we must fixup refcnts and charges */
6529 if (mc.moved_swap) {
6530 /* uncharge swap account from the old cgroup */
6531 if (!mem_cgroup_is_root(mc.from))
6532 page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
6534 mem_cgroup_id_put_many(mc.from, mc.moved_swap);
6537 * we charged both to->memory and to->memsw, so we
6538 * should uncharge to->memory.
6540 if (!mem_cgroup_is_root(mc.to))
6541 page_counter_uncharge(&mc.to->memory, mc.moved_swap);
6545 memcg_oom_recover(from);
6546 memcg_oom_recover(to);
6547 wake_up_all(&mc.waitq);
6550 static void mem_cgroup_clear_mc(void)
6552 struct mm_struct *mm = mc.mm;
6555 * we must clear moving_task before waking up waiters at the end of
6558 mc.moving_task = NULL;
6559 __mem_cgroup_clear_mc();
6560 spin_lock(&mc.lock);
6564 spin_unlock(&mc.lock);
6569 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
6571 struct cgroup_subsys_state *css;
6572 struct mem_cgroup *memcg = NULL; /* unneeded init to make gcc happy */
6573 struct mem_cgroup *from;
6574 struct task_struct *leader, *p;
6575 struct mm_struct *mm;
6576 unsigned long move_flags;
6579 /* charge immigration isn't supported on the default hierarchy */
6580 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
6584 * Multi-process migrations only happen on the default hierarchy
6585 * where charge immigration is not used. Perform charge
6586 * immigration if @tset contains a leader and whine if there are
6590 cgroup_taskset_for_each_leader(leader, css, tset) {
6593 memcg = mem_cgroup_from_css(css);
6599 * We are now committed to this value whatever it is. Changes in this
6600 * tunable will only affect upcoming migrations, not the current one.
6601 * So we need to save it, and keep it going.
6603 move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
6607 from = mem_cgroup_from_task(p);
6609 VM_BUG_ON(from == memcg);
6611 mm = get_task_mm(p);
6614 /* We move charges only when we move a owner of the mm */
6615 if (mm->owner == p) {
6618 VM_BUG_ON(mc.precharge);
6619 VM_BUG_ON(mc.moved_charge);
6620 VM_BUG_ON(mc.moved_swap);
6622 spin_lock(&mc.lock);
6626 mc.flags = move_flags;
6627 spin_unlock(&mc.lock);
6628 /* We set mc.moving_task later */
6630 ret = mem_cgroup_precharge_mc(mm);
6632 mem_cgroup_clear_mc();
6639 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6642 mem_cgroup_clear_mc();
6645 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
6646 unsigned long addr, unsigned long end,
6647 struct mm_walk *walk)
6650 struct vm_area_struct *vma = walk->vma;
6653 enum mc_target_type target_type;
6654 union mc_target target;
6655 struct folio *folio;
6657 ptl = pmd_trans_huge_lock(pmd, vma);
6659 if (mc.precharge < HPAGE_PMD_NR) {
6663 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
6664 if (target_type == MC_TARGET_PAGE) {
6665 folio = target.folio;
6666 if (folio_isolate_lru(folio)) {
6667 if (!mem_cgroup_move_account(folio, true,
6669 mc.precharge -= HPAGE_PMD_NR;
6670 mc.moved_charge += HPAGE_PMD_NR;
6672 folio_putback_lru(folio);
6674 folio_unlock(folio);
6676 } else if (target_type == MC_TARGET_DEVICE) {
6677 folio = target.folio;
6678 if (!mem_cgroup_move_account(folio, true,
6680 mc.precharge -= HPAGE_PMD_NR;
6681 mc.moved_charge += HPAGE_PMD_NR;
6683 folio_unlock(folio);
6691 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6694 for (; addr != end; addr += PAGE_SIZE) {
6695 pte_t ptent = ptep_get(pte++);
6696 bool device = false;
6702 switch (get_mctgt_type(vma, addr, ptent, &target)) {
6703 case MC_TARGET_DEVICE:
6706 case MC_TARGET_PAGE:
6707 folio = target.folio;
6709 * We can have a part of the split pmd here. Moving it
6710 * can be done but it would be too convoluted so simply
6711 * ignore such a partial THP and keep it in original
6712 * memcg. There should be somebody mapping the head.
6714 if (folio_test_large(folio))
6716 if (!device && !folio_isolate_lru(folio))
6718 if (!mem_cgroup_move_account(folio, false,
6721 /* we uncharge from mc.from later. */
6725 folio_putback_lru(folio);
6726 put: /* get_mctgt_type() gets & locks the page */
6727 folio_unlock(folio);
6730 case MC_TARGET_SWAP:
6732 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
6734 mem_cgroup_id_get_many(mc.to, 1);
6735 /* we fixup other refcnts and charges later. */
6743 pte_unmap_unlock(pte - 1, ptl);
6748 * We have consumed all precharges we got in can_attach().
6749 * We try charge one by one, but don't do any additional
6750 * charges to mc.to if we have failed in charge once in attach()
6753 ret = mem_cgroup_do_precharge(1);
6761 static const struct mm_walk_ops charge_walk_ops = {
6762 .pmd_entry = mem_cgroup_move_charge_pte_range,
6763 .walk_lock = PGWALK_RDLOCK,
6766 static void mem_cgroup_move_charge(void)
6768 lru_add_drain_all();
6770 * Signal folio_memcg_lock() to take the memcg's move_lock
6771 * while we're moving its pages to another memcg. Then wait
6772 * for already started RCU-only updates to finish.
6774 atomic_inc(&mc.from->moving_account);
6777 if (unlikely(!mmap_read_trylock(mc.mm))) {
6779 * Someone who are holding the mmap_lock might be waiting in
6780 * waitq. So we cancel all extra charges, wake up all waiters,
6781 * and retry. Because we cancel precharges, we might not be able
6782 * to move enough charges, but moving charge is a best-effort
6783 * feature anyway, so it wouldn't be a big problem.
6785 __mem_cgroup_clear_mc();
6790 * When we have consumed all precharges and failed in doing
6791 * additional charge, the page walk just aborts.
6793 walk_page_range(mc.mm, 0, ULONG_MAX, &charge_walk_ops, NULL);
6794 mmap_read_unlock(mc.mm);
6795 atomic_dec(&mc.from->moving_account);
6798 static void mem_cgroup_move_task(void)
6801 mem_cgroup_move_charge();
6802 mem_cgroup_clear_mc();
6806 #else /* !CONFIG_MMU */
6807 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
6811 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6814 static void mem_cgroup_move_task(void)
6819 #ifdef CONFIG_MEMCG_KMEM
6820 static void mem_cgroup_fork(struct task_struct *task)
6823 * Set the update flag to cause task->objcg to be initialized lazily
6824 * on the first allocation. It can be done without any synchronization
6825 * because it's always performed on the current task, so does
6826 * current_objcg_update().
6828 task->objcg = (struct obj_cgroup *)CURRENT_OBJCG_UPDATE_FLAG;
6831 static void mem_cgroup_exit(struct task_struct *task)
6833 struct obj_cgroup *objcg = task->objcg;
6835 objcg = (struct obj_cgroup *)
6836 ((unsigned long)objcg & ~CURRENT_OBJCG_UPDATE_FLAG);
6837 obj_cgroup_put(objcg);
6840 * Some kernel allocations can happen after this point,
6841 * but let's ignore them. It can be done without any synchronization
6842 * because it's always performed on the current task, so does
6843 * current_objcg_update().
6849 #ifdef CONFIG_LRU_GEN
6850 static void mem_cgroup_lru_gen_attach(struct cgroup_taskset *tset)
6852 struct task_struct *task;
6853 struct cgroup_subsys_state *css;
6855 /* find the first leader if there is any */
6856 cgroup_taskset_for_each_leader(task, css, tset)
6863 if (task->mm && READ_ONCE(task->mm->owner) == task)
6864 lru_gen_migrate_mm(task->mm);
6868 static void mem_cgroup_lru_gen_attach(struct cgroup_taskset *tset) {}
6869 #endif /* CONFIG_LRU_GEN */
6871 #ifdef CONFIG_MEMCG_KMEM
6872 static void mem_cgroup_kmem_attach(struct cgroup_taskset *tset)
6874 struct task_struct *task;
6875 struct cgroup_subsys_state *css;
6877 cgroup_taskset_for_each(task, css, tset) {
6878 /* atomically set the update bit */
6879 set_bit(CURRENT_OBJCG_UPDATE_BIT, (unsigned long *)&task->objcg);
6883 static void mem_cgroup_kmem_attach(struct cgroup_taskset *tset) {}
6884 #endif /* CONFIG_MEMCG_KMEM */
6886 #if defined(CONFIG_LRU_GEN) || defined(CONFIG_MEMCG_KMEM)
6887 static void mem_cgroup_attach(struct cgroup_taskset *tset)
6889 mem_cgroup_lru_gen_attach(tset);
6890 mem_cgroup_kmem_attach(tset);
6894 static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
6896 if (value == PAGE_COUNTER_MAX)
6897 seq_puts(m, "max\n");
6899 seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
6904 static u64 memory_current_read(struct cgroup_subsys_state *css,
6907 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6909 return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
6912 static u64 memory_peak_read(struct cgroup_subsys_state *css,
6915 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6917 return (u64)memcg->memory.watermark * PAGE_SIZE;
6920 static int memory_min_show(struct seq_file *m, void *v)
6922 return seq_puts_memcg_tunable(m,
6923 READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
6926 static ssize_t memory_min_write(struct kernfs_open_file *of,
6927 char *buf, size_t nbytes, loff_t off)
6929 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6933 buf = strstrip(buf);
6934 err = page_counter_memparse(buf, "max", &min);
6938 page_counter_set_min(&memcg->memory, min);
6943 static int memory_low_show(struct seq_file *m, void *v)
6945 return seq_puts_memcg_tunable(m,
6946 READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
6949 static ssize_t memory_low_write(struct kernfs_open_file *of,
6950 char *buf, size_t nbytes, loff_t off)
6952 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6956 buf = strstrip(buf);
6957 err = page_counter_memparse(buf, "max", &low);
6961 page_counter_set_low(&memcg->memory, low);
6966 static int memory_high_show(struct seq_file *m, void *v)
6968 return seq_puts_memcg_tunable(m,
6969 READ_ONCE(mem_cgroup_from_seq(m)->memory.high));
6972 static ssize_t memory_high_write(struct kernfs_open_file *of,
6973 char *buf, size_t nbytes, loff_t off)
6975 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6976 unsigned int nr_retries = MAX_RECLAIM_RETRIES;
6977 bool drained = false;
6981 buf = strstrip(buf);
6982 err = page_counter_memparse(buf, "max", &high);
6986 page_counter_set_high(&memcg->memory, high);
6989 unsigned long nr_pages = page_counter_read(&memcg->memory);
6990 unsigned long reclaimed;
6992 if (nr_pages <= high)
6995 if (signal_pending(current))
6999 drain_all_stock(memcg);
7004 reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
7005 GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP);
7007 if (!reclaimed && !nr_retries--)
7011 memcg_wb_domain_size_changed(memcg);
7015 static int memory_max_show(struct seq_file *m, void *v)
7017 return seq_puts_memcg_tunable(m,
7018 READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
7021 static ssize_t memory_max_write(struct kernfs_open_file *of,
7022 char *buf, size_t nbytes, loff_t off)
7024 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7025 unsigned int nr_reclaims = MAX_RECLAIM_RETRIES;
7026 bool drained = false;
7030 buf = strstrip(buf);
7031 err = page_counter_memparse(buf, "max", &max);
7035 xchg(&memcg->memory.max, max);
7038 unsigned long nr_pages = page_counter_read(&memcg->memory);
7040 if (nr_pages <= max)
7043 if (signal_pending(current))
7047 drain_all_stock(memcg);
7053 if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
7054 GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP))
7059 memcg_memory_event(memcg, MEMCG_OOM);
7060 if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
7064 memcg_wb_domain_size_changed(memcg);
7069 * Note: don't forget to update the 'samples/cgroup/memcg_event_listener'
7070 * if any new events become available.
7072 static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
7074 seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
7075 seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
7076 seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
7077 seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
7078 seq_printf(m, "oom_kill %lu\n",
7079 atomic_long_read(&events[MEMCG_OOM_KILL]));
7080 seq_printf(m, "oom_group_kill %lu\n",
7081 atomic_long_read(&events[MEMCG_OOM_GROUP_KILL]));
7084 static int memory_events_show(struct seq_file *m, void *v)
7086 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
7088 __memory_events_show(m, memcg->memory_events);
7092 static int memory_events_local_show(struct seq_file *m, void *v)
7094 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
7096 __memory_events_show(m, memcg->memory_events_local);
7100 static int memory_stat_show(struct seq_file *m, void *v)
7102 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
7103 char *buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
7108 seq_buf_init(&s, buf, PAGE_SIZE);
7109 memory_stat_format(memcg, &s);
7116 static inline unsigned long lruvec_page_state_output(struct lruvec *lruvec,
7119 return lruvec_page_state(lruvec, item) *
7120 memcg_page_state_output_unit(item);
7123 static int memory_numa_stat_show(struct seq_file *m, void *v)
7126 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
7128 mem_cgroup_flush_stats(memcg);
7130 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
7133 if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS)
7136 seq_printf(m, "%s", memory_stats[i].name);
7137 for_each_node_state(nid, N_MEMORY) {
7139 struct lruvec *lruvec;
7141 lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
7142 size = lruvec_page_state_output(lruvec,
7143 memory_stats[i].idx);
7144 seq_printf(m, " N%d=%llu", nid, size);
7153 static int memory_oom_group_show(struct seq_file *m, void *v)
7155 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
7157 seq_printf(m, "%d\n", READ_ONCE(memcg->oom_group));
7162 static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
7163 char *buf, size_t nbytes, loff_t off)
7165 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7168 buf = strstrip(buf);
7172 ret = kstrtoint(buf, 0, &oom_group);
7176 if (oom_group != 0 && oom_group != 1)
7179 WRITE_ONCE(memcg->oom_group, oom_group);
7184 static ssize_t memory_reclaim(struct kernfs_open_file *of, char *buf,
7185 size_t nbytes, loff_t off)
7187 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7188 unsigned int nr_retries = MAX_RECLAIM_RETRIES;
7189 unsigned long nr_to_reclaim, nr_reclaimed = 0;
7190 unsigned int reclaim_options;
7193 buf = strstrip(buf);
7194 err = page_counter_memparse(buf, "", &nr_to_reclaim);
7198 reclaim_options = MEMCG_RECLAIM_MAY_SWAP | MEMCG_RECLAIM_PROACTIVE;
7199 while (nr_reclaimed < nr_to_reclaim) {
7200 /* Will converge on zero, but reclaim enforces a minimum */
7201 unsigned long batch_size = (nr_to_reclaim - nr_reclaimed) / 4;
7202 unsigned long reclaimed;
7204 if (signal_pending(current))
7208 * This is the final attempt, drain percpu lru caches in the
7209 * hope of introducing more evictable pages for
7210 * try_to_free_mem_cgroup_pages().
7213 lru_add_drain_all();
7215 reclaimed = try_to_free_mem_cgroup_pages(memcg,
7216 batch_size, GFP_KERNEL, reclaim_options);
7218 if (!reclaimed && !nr_retries--)
7221 nr_reclaimed += reclaimed;
7227 static struct cftype memory_files[] = {
7230 .flags = CFTYPE_NOT_ON_ROOT,
7231 .read_u64 = memory_current_read,
7235 .flags = CFTYPE_NOT_ON_ROOT,
7236 .read_u64 = memory_peak_read,
7240 .flags = CFTYPE_NOT_ON_ROOT,
7241 .seq_show = memory_min_show,
7242 .write = memory_min_write,
7246 .flags = CFTYPE_NOT_ON_ROOT,
7247 .seq_show = memory_low_show,
7248 .write = memory_low_write,
7252 .flags = CFTYPE_NOT_ON_ROOT,
7253 .seq_show = memory_high_show,
7254 .write = memory_high_write,
7258 .flags = CFTYPE_NOT_ON_ROOT,
7259 .seq_show = memory_max_show,
7260 .write = memory_max_write,
7264 .flags = CFTYPE_NOT_ON_ROOT,
7265 .file_offset = offsetof(struct mem_cgroup, events_file),
7266 .seq_show = memory_events_show,
7269 .name = "events.local",
7270 .flags = CFTYPE_NOT_ON_ROOT,
7271 .file_offset = offsetof(struct mem_cgroup, events_local_file),
7272 .seq_show = memory_events_local_show,
7276 .seq_show = memory_stat_show,
7280 .name = "numa_stat",
7281 .seq_show = memory_numa_stat_show,
7285 .name = "oom.group",
7286 .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
7287 .seq_show = memory_oom_group_show,
7288 .write = memory_oom_group_write,
7292 .flags = CFTYPE_NS_DELEGATABLE,
7293 .write = memory_reclaim,
7298 struct cgroup_subsys memory_cgrp_subsys = {
7299 .css_alloc = mem_cgroup_css_alloc,
7300 .css_online = mem_cgroup_css_online,
7301 .css_offline = mem_cgroup_css_offline,
7302 .css_released = mem_cgroup_css_released,
7303 .css_free = mem_cgroup_css_free,
7304 .css_reset = mem_cgroup_css_reset,
7305 .css_rstat_flush = mem_cgroup_css_rstat_flush,
7306 .can_attach = mem_cgroup_can_attach,
7307 #if defined(CONFIG_LRU_GEN) || defined(CONFIG_MEMCG_KMEM)
7308 .attach = mem_cgroup_attach,
7310 .cancel_attach = mem_cgroup_cancel_attach,
7311 .post_attach = mem_cgroup_move_task,
7312 #ifdef CONFIG_MEMCG_KMEM
7313 .fork = mem_cgroup_fork,
7314 .exit = mem_cgroup_exit,
7316 .dfl_cftypes = memory_files,
7317 .legacy_cftypes = mem_cgroup_legacy_files,
7322 * This function calculates an individual cgroup's effective
7323 * protection which is derived from its own memory.min/low, its
7324 * parent's and siblings' settings, as well as the actual memory
7325 * distribution in the tree.
7327 * The following rules apply to the effective protection values:
7329 * 1. At the first level of reclaim, effective protection is equal to
7330 * the declared protection in memory.min and memory.low.
7332 * 2. To enable safe delegation of the protection configuration, at
7333 * subsequent levels the effective protection is capped to the
7334 * parent's effective protection.
7336 * 3. To make complex and dynamic subtrees easier to configure, the
7337 * user is allowed to overcommit the declared protection at a given
7338 * level. If that is the case, the parent's effective protection is
7339 * distributed to the children in proportion to how much protection
7340 * they have declared and how much of it they are utilizing.
7342 * This makes distribution proportional, but also work-conserving:
7343 * if one cgroup claims much more protection than it uses memory,
7344 * the unused remainder is available to its siblings.
7346 * 4. Conversely, when the declared protection is undercommitted at a
7347 * given level, the distribution of the larger parental protection
7348 * budget is NOT proportional. A cgroup's protection from a sibling
7349 * is capped to its own memory.min/low setting.
7351 * 5. However, to allow protecting recursive subtrees from each other
7352 * without having to declare each individual cgroup's fixed share
7353 * of the ancestor's claim to protection, any unutilized -
7354 * "floating" - protection from up the tree is distributed in
7355 * proportion to each cgroup's *usage*. This makes the protection
7356 * neutral wrt sibling cgroups and lets them compete freely over
7357 * the shared parental protection budget, but it protects the
7358 * subtree as a whole from neighboring subtrees.
7360 * Note that 4. and 5. are not in conflict: 4. is about protecting
7361 * against immediate siblings whereas 5. is about protecting against
7362 * neighboring subtrees.
7364 static unsigned long effective_protection(unsigned long usage,
7365 unsigned long parent_usage,
7366 unsigned long setting,
7367 unsigned long parent_effective,
7368 unsigned long siblings_protected)
7370 unsigned long protected;
7373 protected = min(usage, setting);
7375 * If all cgroups at this level combined claim and use more
7376 * protection than what the parent affords them, distribute
7377 * shares in proportion to utilization.
7379 * We are using actual utilization rather than the statically
7380 * claimed protection in order to be work-conserving: claimed
7381 * but unused protection is available to siblings that would
7382 * otherwise get a smaller chunk than what they claimed.
7384 if (siblings_protected > parent_effective)
7385 return protected * parent_effective / siblings_protected;
7388 * Ok, utilized protection of all children is within what the
7389 * parent affords them, so we know whatever this child claims
7390 * and utilizes is effectively protected.
7392 * If there is unprotected usage beyond this value, reclaim
7393 * will apply pressure in proportion to that amount.
7395 * If there is unutilized protection, the cgroup will be fully
7396 * shielded from reclaim, but we do return a smaller value for
7397 * protection than what the group could enjoy in theory. This
7398 * is okay. With the overcommit distribution above, effective
7399 * protection is always dependent on how memory is actually
7400 * consumed among the siblings anyway.
7405 * If the children aren't claiming (all of) the protection
7406 * afforded to them by the parent, distribute the remainder in
7407 * proportion to the (unprotected) memory of each cgroup. That
7408 * way, cgroups that aren't explicitly prioritized wrt each
7409 * other compete freely over the allowance, but they are
7410 * collectively protected from neighboring trees.
7412 * We're using unprotected memory for the weight so that if
7413 * some cgroups DO claim explicit protection, we don't protect
7414 * the same bytes twice.
7416 * Check both usage and parent_usage against the respective
7417 * protected values. One should imply the other, but they
7418 * aren't read atomically - make sure the division is sane.
7420 if (!(cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT))
7422 if (parent_effective > siblings_protected &&
7423 parent_usage > siblings_protected &&
7424 usage > protected) {
7425 unsigned long unclaimed;
7427 unclaimed = parent_effective - siblings_protected;
7428 unclaimed *= usage - protected;
7429 unclaimed /= parent_usage - siblings_protected;
7438 * mem_cgroup_calculate_protection - check if memory consumption is in the normal range
7439 * @root: the top ancestor of the sub-tree being checked
7440 * @memcg: the memory cgroup to check
7442 * WARNING: This function is not stateless! It can only be used as part
7443 * of a top-down tree iteration, not for isolated queries.
7445 void mem_cgroup_calculate_protection(struct mem_cgroup *root,
7446 struct mem_cgroup *memcg)
7448 unsigned long usage, parent_usage;
7449 struct mem_cgroup *parent;
7451 if (mem_cgroup_disabled())
7455 root = root_mem_cgroup;
7458 * Effective values of the reclaim targets are ignored so they
7459 * can be stale. Have a look at mem_cgroup_protection for more
7461 * TODO: calculation should be more robust so that we do not need
7462 * that special casing.
7467 usage = page_counter_read(&memcg->memory);
7471 parent = parent_mem_cgroup(memcg);
7473 if (parent == root) {
7474 memcg->memory.emin = READ_ONCE(memcg->memory.min);
7475 memcg->memory.elow = READ_ONCE(memcg->memory.low);
7479 parent_usage = page_counter_read(&parent->memory);
7481 WRITE_ONCE(memcg->memory.emin, effective_protection(usage, parent_usage,
7482 READ_ONCE(memcg->memory.min),
7483 READ_ONCE(parent->memory.emin),
7484 atomic_long_read(&parent->memory.children_min_usage)));
7486 WRITE_ONCE(memcg->memory.elow, effective_protection(usage, parent_usage,
7487 READ_ONCE(memcg->memory.low),
7488 READ_ONCE(parent->memory.elow),
7489 atomic_long_read(&parent->memory.children_low_usage)));
7492 static int charge_memcg(struct folio *folio, struct mem_cgroup *memcg,
7497 ret = try_charge(memcg, gfp, folio_nr_pages(folio));
7501 mem_cgroup_commit_charge(folio, memcg);
7506 int __mem_cgroup_charge(struct folio *folio, struct mm_struct *mm, gfp_t gfp)
7508 struct mem_cgroup *memcg;
7511 memcg = get_mem_cgroup_from_mm(mm);
7512 ret = charge_memcg(folio, memcg, gfp);
7513 css_put(&memcg->css);
7519 * mem_cgroup_hugetlb_try_charge - try to charge the memcg for a hugetlb folio
7520 * @memcg: memcg to charge.
7521 * @gfp: reclaim mode.
7522 * @nr_pages: number of pages to charge.
7524 * This function is called when allocating a huge page folio to determine if
7525 * the memcg has the capacity for it. It does not commit the charge yet,
7526 * as the hugetlb folio itself has not been obtained from the hugetlb pool.
7528 * Once we have obtained the hugetlb folio, we can call
7529 * mem_cgroup_commit_charge() to commit the charge. If we fail to obtain the
7530 * folio, we should instead call mem_cgroup_cancel_charge() to undo the effect
7533 * Returns 0 on success. Otherwise, an error code is returned.
7535 int mem_cgroup_hugetlb_try_charge(struct mem_cgroup *memcg, gfp_t gfp,
7539 * If hugetlb memcg charging is not enabled, do not fail hugetlb allocation,
7540 * but do not attempt to commit charge later (or cancel on error) either.
7542 if (mem_cgroup_disabled() || !memcg ||
7543 !cgroup_subsys_on_dfl(memory_cgrp_subsys) ||
7544 !(cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_HUGETLB_ACCOUNTING))
7547 if (try_charge(memcg, gfp, nr_pages))
7554 * mem_cgroup_swapin_charge_folio - Charge a newly allocated folio for swapin.
7555 * @folio: folio to charge.
7556 * @mm: mm context of the victim
7557 * @gfp: reclaim mode
7558 * @entry: swap entry for which the folio is allocated
7560 * This function charges a folio allocated for swapin. Please call this before
7561 * adding the folio to the swapcache.
7563 * Returns 0 on success. Otherwise, an error code is returned.
7565 int mem_cgroup_swapin_charge_folio(struct folio *folio, struct mm_struct *mm,
7566 gfp_t gfp, swp_entry_t entry)
7568 struct mem_cgroup *memcg;
7572 if (mem_cgroup_disabled())
7575 id = lookup_swap_cgroup_id(entry);
7577 memcg = mem_cgroup_from_id(id);
7578 if (!memcg || !css_tryget_online(&memcg->css))
7579 memcg = get_mem_cgroup_from_mm(mm);
7582 ret = charge_memcg(folio, memcg, gfp);
7584 css_put(&memcg->css);
7589 * mem_cgroup_swapin_uncharge_swap - uncharge swap slot
7590 * @entry: swap entry for which the page is charged
7592 * Call this function after successfully adding the charged page to swapcache.
7594 * Note: This function assumes the page for which swap slot is being uncharged
7597 void mem_cgroup_swapin_uncharge_swap(swp_entry_t entry)
7600 * Cgroup1's unified memory+swap counter has been charged with the
7601 * new swapcache page, finish the transfer by uncharging the swap
7602 * slot. The swap slot would also get uncharged when it dies, but
7603 * it can stick around indefinitely and we'd count the page twice
7606 * Cgroup2 has separate resource counters for memory and swap,
7607 * so this is a non-issue here. Memory and swap charge lifetimes
7608 * correspond 1:1 to page and swap slot lifetimes: we charge the
7609 * page to memory here, and uncharge swap when the slot is freed.
7611 if (!mem_cgroup_disabled() && do_memsw_account()) {
7613 * The swap entry might not get freed for a long time,
7614 * let's not wait for it. The page already received a
7615 * memory+swap charge, drop the swap entry duplicate.
7617 mem_cgroup_uncharge_swap(entry, 1);
7621 struct uncharge_gather {
7622 struct mem_cgroup *memcg;
7623 unsigned long nr_memory;
7624 unsigned long pgpgout;
7625 unsigned long nr_kmem;
7629 static inline void uncharge_gather_clear(struct uncharge_gather *ug)
7631 memset(ug, 0, sizeof(*ug));
7634 static void uncharge_batch(const struct uncharge_gather *ug)
7636 unsigned long flags;
7638 if (ug->nr_memory) {
7639 page_counter_uncharge(&ug->memcg->memory, ug->nr_memory);
7640 if (do_memsw_account())
7641 page_counter_uncharge(&ug->memcg->memsw, ug->nr_memory);
7643 memcg_account_kmem(ug->memcg, -ug->nr_kmem);
7644 memcg_oom_recover(ug->memcg);
7647 local_irq_save(flags);
7648 __count_memcg_events(ug->memcg, PGPGOUT, ug->pgpgout);
7649 __this_cpu_add(ug->memcg->vmstats_percpu->nr_page_events, ug->nr_memory);
7650 memcg_check_events(ug->memcg, ug->nid);
7651 local_irq_restore(flags);
7653 /* drop reference from uncharge_folio */
7654 css_put(&ug->memcg->css);
7657 static void uncharge_folio(struct folio *folio, struct uncharge_gather *ug)
7660 struct mem_cgroup *memcg;
7661 struct obj_cgroup *objcg;
7663 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
7664 VM_BUG_ON_FOLIO(folio_order(folio) > 1 &&
7665 !folio_test_hugetlb(folio) &&
7666 !list_empty(&folio->_deferred_list), folio);
7669 * Nobody should be changing or seriously looking at
7670 * folio memcg or objcg at this point, we have fully
7671 * exclusive access to the folio.
7673 if (folio_memcg_kmem(folio)) {
7674 objcg = __folio_objcg(folio);
7676 * This get matches the put at the end of the function and
7677 * kmem pages do not hold memcg references anymore.
7679 memcg = get_mem_cgroup_from_objcg(objcg);
7681 memcg = __folio_memcg(folio);
7687 if (ug->memcg != memcg) {
7690 uncharge_gather_clear(ug);
7693 ug->nid = folio_nid(folio);
7695 /* pairs with css_put in uncharge_batch */
7696 css_get(&memcg->css);
7699 nr_pages = folio_nr_pages(folio);
7701 if (folio_memcg_kmem(folio)) {
7702 ug->nr_memory += nr_pages;
7703 ug->nr_kmem += nr_pages;
7705 folio->memcg_data = 0;
7706 obj_cgroup_put(objcg);
7708 /* LRU pages aren't accounted at the root level */
7709 if (!mem_cgroup_is_root(memcg))
7710 ug->nr_memory += nr_pages;
7713 folio->memcg_data = 0;
7716 css_put(&memcg->css);
7719 void __mem_cgroup_uncharge(struct folio *folio)
7721 struct uncharge_gather ug;
7723 /* Don't touch folio->lru of any random page, pre-check: */
7724 if (!folio_memcg(folio))
7727 uncharge_gather_clear(&ug);
7728 uncharge_folio(folio, &ug);
7729 uncharge_batch(&ug);
7732 void __mem_cgroup_uncharge_folios(struct folio_batch *folios)
7734 struct uncharge_gather ug;
7737 uncharge_gather_clear(&ug);
7738 for (i = 0; i < folios->nr; i++)
7739 uncharge_folio(folios->folios[i], &ug);
7741 uncharge_batch(&ug);
7745 * mem_cgroup_replace_folio - Charge a folio's replacement.
7746 * @old: Currently circulating folio.
7747 * @new: Replacement folio.
7749 * Charge @new as a replacement folio for @old. @old will
7750 * be uncharged upon free. This is only used by the page cache
7751 * (in replace_page_cache_folio()).
7753 * Both folios must be locked, @new->mapping must be set up.
7755 void mem_cgroup_replace_folio(struct folio *old, struct folio *new)
7757 struct mem_cgroup *memcg;
7758 long nr_pages = folio_nr_pages(new);
7759 unsigned long flags;
7761 VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
7762 VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
7763 VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
7764 VM_BUG_ON_FOLIO(folio_nr_pages(old) != nr_pages, new);
7766 if (mem_cgroup_disabled())
7769 /* Page cache replacement: new folio already charged? */
7770 if (folio_memcg(new))
7773 memcg = folio_memcg(old);
7774 VM_WARN_ON_ONCE_FOLIO(!memcg, old);
7778 /* Force-charge the new page. The old one will be freed soon */
7779 if (!mem_cgroup_is_root(memcg)) {
7780 page_counter_charge(&memcg->memory, nr_pages);
7781 if (do_memsw_account())
7782 page_counter_charge(&memcg->memsw, nr_pages);
7785 css_get(&memcg->css);
7786 commit_charge(new, memcg);
7788 local_irq_save(flags);
7789 mem_cgroup_charge_statistics(memcg, nr_pages);
7790 memcg_check_events(memcg, folio_nid(new));
7791 local_irq_restore(flags);
7795 * mem_cgroup_migrate - Transfer the memcg data from the old to the new folio.
7796 * @old: Currently circulating folio.
7797 * @new: Replacement folio.
7799 * Transfer the memcg data from the old folio to the new folio for migration.
7800 * The old folio's data info will be cleared. Note that the memory counters
7801 * will remain unchanged throughout the process.
7803 * Both folios must be locked, @new->mapping must be set up.
7805 void mem_cgroup_migrate(struct folio *old, struct folio *new)
7807 struct mem_cgroup *memcg;
7809 VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
7810 VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
7811 VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
7812 VM_BUG_ON_FOLIO(folio_nr_pages(old) != folio_nr_pages(new), new);
7814 if (mem_cgroup_disabled())
7817 memcg = folio_memcg(old);
7819 * Note that it is normal to see !memcg for a hugetlb folio.
7820 * For e.g, itt could have been allocated when memory_hugetlb_accounting
7823 VM_WARN_ON_ONCE_FOLIO(!folio_test_hugetlb(old) && !memcg, old);
7827 /* Transfer the charge and the css ref */
7828 commit_charge(new, memcg);
7830 * If the old folio is a large folio and is in the split queue, it needs
7831 * to be removed from the split queue now, in case getting an incorrect
7832 * split queue in destroy_large_folio() after the memcg of the old folio
7835 * In addition, the old folio is about to be freed after migration, so
7836 * removing from the split queue a bit earlier seems reasonable.
7838 if (folio_test_large(old) && folio_test_large_rmappable(old))
7839 folio_undo_large_rmappable(old);
7840 old->memcg_data = 0;
7843 DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
7844 EXPORT_SYMBOL(memcg_sockets_enabled_key);
7846 void mem_cgroup_sk_alloc(struct sock *sk)
7848 struct mem_cgroup *memcg;
7850 if (!mem_cgroup_sockets_enabled)
7853 /* Do not associate the sock with unrelated interrupted task's memcg. */
7858 memcg = mem_cgroup_from_task(current);
7859 if (mem_cgroup_is_root(memcg))
7861 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg->tcpmem_active)
7863 if (css_tryget(&memcg->css))
7864 sk->sk_memcg = memcg;
7869 void mem_cgroup_sk_free(struct sock *sk)
7872 css_put(&sk->sk_memcg->css);
7876 * mem_cgroup_charge_skmem - charge socket memory
7877 * @memcg: memcg to charge
7878 * @nr_pages: number of pages to charge
7879 * @gfp_mask: reclaim mode
7881 * Charges @nr_pages to @memcg. Returns %true if the charge fit within
7882 * @memcg's configured limit, %false if it doesn't.
7884 bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages,
7887 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
7888 struct page_counter *fail;
7890 if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) {
7891 memcg->tcpmem_pressure = 0;
7894 memcg->tcpmem_pressure = 1;
7895 if (gfp_mask & __GFP_NOFAIL) {
7896 page_counter_charge(&memcg->tcpmem, nr_pages);
7902 if (try_charge(memcg, gfp_mask, nr_pages) == 0) {
7903 mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
7911 * mem_cgroup_uncharge_skmem - uncharge socket memory
7912 * @memcg: memcg to uncharge
7913 * @nr_pages: number of pages to uncharge
7915 void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
7917 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
7918 page_counter_uncharge(&memcg->tcpmem, nr_pages);
7922 mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
7924 refill_stock(memcg, nr_pages);
7927 static int __init cgroup_memory(char *s)
7931 while ((token = strsep(&s, ",")) != NULL) {
7934 if (!strcmp(token, "nosocket"))
7935 cgroup_memory_nosocket = true;
7936 if (!strcmp(token, "nokmem"))
7937 cgroup_memory_nokmem = true;
7938 if (!strcmp(token, "nobpf"))
7939 cgroup_memory_nobpf = true;
7943 __setup("cgroup.memory=", cgroup_memory);
7946 * subsys_initcall() for memory controller.
7948 * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
7949 * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
7950 * basically everything that doesn't depend on a specific mem_cgroup structure
7951 * should be initialized from here.
7953 static int __init mem_cgroup_init(void)
7958 * Currently s32 type (can refer to struct batched_lruvec_stat) is
7959 * used for per-memcg-per-cpu caching of per-node statistics. In order
7960 * to work fine, we should make sure that the overfill threshold can't
7961 * exceed S32_MAX / PAGE_SIZE.
7963 BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE);
7965 cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
7966 memcg_hotplug_cpu_dead);
7968 for_each_possible_cpu(cpu)
7969 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
7972 for_each_node(node) {
7973 struct mem_cgroup_tree_per_node *rtpn;
7975 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, node);
7977 rtpn->rb_root = RB_ROOT;
7978 rtpn->rb_rightmost = NULL;
7979 spin_lock_init(&rtpn->lock);
7980 soft_limit_tree.rb_tree_per_node[node] = rtpn;
7985 subsys_initcall(mem_cgroup_init);
7988 static struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
7990 while (!refcount_inc_not_zero(&memcg->id.ref)) {
7992 * The root cgroup cannot be destroyed, so it's refcount must
7995 if (WARN_ON_ONCE(mem_cgroup_is_root(memcg))) {
7999 memcg = parent_mem_cgroup(memcg);
8001 memcg = root_mem_cgroup;
8007 * mem_cgroup_swapout - transfer a memsw charge to swap
8008 * @folio: folio whose memsw charge to transfer
8009 * @entry: swap entry to move the charge to
8011 * Transfer the memsw charge of @folio to @entry.
8013 void mem_cgroup_swapout(struct folio *folio, swp_entry_t entry)
8015 struct mem_cgroup *memcg, *swap_memcg;
8016 unsigned int nr_entries;
8017 unsigned short oldid;
8019 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
8020 VM_BUG_ON_FOLIO(folio_ref_count(folio), folio);
8022 if (mem_cgroup_disabled())
8025 if (!do_memsw_account())
8028 memcg = folio_memcg(folio);
8030 VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
8035 * In case the memcg owning these pages has been offlined and doesn't
8036 * have an ID allocated to it anymore, charge the closest online
8037 * ancestor for the swap instead and transfer the memory+swap charge.
8039 swap_memcg = mem_cgroup_id_get_online(memcg);
8040 nr_entries = folio_nr_pages(folio);
8041 /* Get references for the tail pages, too */
8043 mem_cgroup_id_get_many(swap_memcg, nr_entries - 1);
8044 oldid = swap_cgroup_record(entry, mem_cgroup_id(swap_memcg),
8046 VM_BUG_ON_FOLIO(oldid, folio);
8047 mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries);
8049 folio->memcg_data = 0;
8051 if (!mem_cgroup_is_root(memcg))
8052 page_counter_uncharge(&memcg->memory, nr_entries);
8054 if (memcg != swap_memcg) {
8055 if (!mem_cgroup_is_root(swap_memcg))
8056 page_counter_charge(&swap_memcg->memsw, nr_entries);
8057 page_counter_uncharge(&memcg->memsw, nr_entries);
8061 * Interrupts should be disabled here because the caller holds the
8062 * i_pages lock which is taken with interrupts-off. It is
8063 * important here to have the interrupts disabled because it is the
8064 * only synchronisation we have for updating the per-CPU variables.
8067 mem_cgroup_charge_statistics(memcg, -nr_entries);
8068 memcg_stats_unlock();
8069 memcg_check_events(memcg, folio_nid(folio));
8071 css_put(&memcg->css);
8075 * __mem_cgroup_try_charge_swap - try charging swap space for a folio
8076 * @folio: folio being added to swap
8077 * @entry: swap entry to charge
8079 * Try to charge @folio's memcg for the swap space at @entry.
8081 * Returns 0 on success, -ENOMEM on failure.
8083 int __mem_cgroup_try_charge_swap(struct folio *folio, swp_entry_t entry)
8085 unsigned int nr_pages = folio_nr_pages(folio);
8086 struct page_counter *counter;
8087 struct mem_cgroup *memcg;
8088 unsigned short oldid;
8090 if (do_memsw_account())
8093 memcg = folio_memcg(folio);
8095 VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
8100 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
8104 memcg = mem_cgroup_id_get_online(memcg);
8106 if (!mem_cgroup_is_root(memcg) &&
8107 !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
8108 memcg_memory_event(memcg, MEMCG_SWAP_MAX);
8109 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
8110 mem_cgroup_id_put(memcg);
8114 /* Get references for the tail pages, too */
8116 mem_cgroup_id_get_many(memcg, nr_pages - 1);
8117 oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg), nr_pages);
8118 VM_BUG_ON_FOLIO(oldid, folio);
8119 mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
8125 * __mem_cgroup_uncharge_swap - uncharge swap space
8126 * @entry: swap entry to uncharge
8127 * @nr_pages: the amount of swap space to uncharge
8129 void __mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
8131 struct mem_cgroup *memcg;
8134 id = swap_cgroup_record(entry, 0, nr_pages);
8136 memcg = mem_cgroup_from_id(id);
8138 if (!mem_cgroup_is_root(memcg)) {
8139 if (do_memsw_account())
8140 page_counter_uncharge(&memcg->memsw, nr_pages);
8142 page_counter_uncharge(&memcg->swap, nr_pages);
8144 mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
8145 mem_cgroup_id_put_many(memcg, nr_pages);
8150 long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
8152 long nr_swap_pages = get_nr_swap_pages();
8154 if (mem_cgroup_disabled() || do_memsw_account())
8155 return nr_swap_pages;
8156 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg))
8157 nr_swap_pages = min_t(long, nr_swap_pages,
8158 READ_ONCE(memcg->swap.max) -
8159 page_counter_read(&memcg->swap));
8160 return nr_swap_pages;
8163 bool mem_cgroup_swap_full(struct folio *folio)
8165 struct mem_cgroup *memcg;
8167 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
8171 if (do_memsw_account())
8174 memcg = folio_memcg(folio);
8178 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
8179 unsigned long usage = page_counter_read(&memcg->swap);
8181 if (usage * 2 >= READ_ONCE(memcg->swap.high) ||
8182 usage * 2 >= READ_ONCE(memcg->swap.max))
8189 static int __init setup_swap_account(char *s)
8193 if (!kstrtobool(s, &res) && !res)
8194 pr_warn_once("The swapaccount=0 commandline option is deprecated "
8195 "in favor of configuring swap control via cgroupfs. "
8197 "depend on this functionality.\n");
8200 __setup("swapaccount=", setup_swap_account);
8202 static u64 swap_current_read(struct cgroup_subsys_state *css,
8205 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
8207 return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
8210 static u64 swap_peak_read(struct cgroup_subsys_state *css,
8213 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
8215 return (u64)memcg->swap.watermark * PAGE_SIZE;
8218 static int swap_high_show(struct seq_file *m, void *v)
8220 return seq_puts_memcg_tunable(m,
8221 READ_ONCE(mem_cgroup_from_seq(m)->swap.high));
8224 static ssize_t swap_high_write(struct kernfs_open_file *of,
8225 char *buf, size_t nbytes, loff_t off)
8227 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
8231 buf = strstrip(buf);
8232 err = page_counter_memparse(buf, "max", &high);
8236 page_counter_set_high(&memcg->swap, high);
8241 static int swap_max_show(struct seq_file *m, void *v)
8243 return seq_puts_memcg_tunable(m,
8244 READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
8247 static ssize_t swap_max_write(struct kernfs_open_file *of,
8248 char *buf, size_t nbytes, loff_t off)
8250 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
8254 buf = strstrip(buf);
8255 err = page_counter_memparse(buf, "max", &max);
8259 xchg(&memcg->swap.max, max);
8264 static int swap_events_show(struct seq_file *m, void *v)
8266 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
8268 seq_printf(m, "high %lu\n",
8269 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH]));
8270 seq_printf(m, "max %lu\n",
8271 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
8272 seq_printf(m, "fail %lu\n",
8273 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
8278 static struct cftype swap_files[] = {
8280 .name = "swap.current",
8281 .flags = CFTYPE_NOT_ON_ROOT,
8282 .read_u64 = swap_current_read,
8285 .name = "swap.high",
8286 .flags = CFTYPE_NOT_ON_ROOT,
8287 .seq_show = swap_high_show,
8288 .write = swap_high_write,
8292 .flags = CFTYPE_NOT_ON_ROOT,
8293 .seq_show = swap_max_show,
8294 .write = swap_max_write,
8297 .name = "swap.peak",
8298 .flags = CFTYPE_NOT_ON_ROOT,
8299 .read_u64 = swap_peak_read,
8302 .name = "swap.events",
8303 .flags = CFTYPE_NOT_ON_ROOT,
8304 .file_offset = offsetof(struct mem_cgroup, swap_events_file),
8305 .seq_show = swap_events_show,
8310 static struct cftype memsw_files[] = {
8312 .name = "memsw.usage_in_bytes",
8313 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
8314 .read_u64 = mem_cgroup_read_u64,
8317 .name = "memsw.max_usage_in_bytes",
8318 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
8319 .write = mem_cgroup_reset,
8320 .read_u64 = mem_cgroup_read_u64,
8323 .name = "memsw.limit_in_bytes",
8324 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
8325 .write = mem_cgroup_write,
8326 .read_u64 = mem_cgroup_read_u64,
8329 .name = "memsw.failcnt",
8330 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
8331 .write = mem_cgroup_reset,
8332 .read_u64 = mem_cgroup_read_u64,
8334 { }, /* terminate */
8337 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
8339 * obj_cgroup_may_zswap - check if this cgroup can zswap
8340 * @objcg: the object cgroup
8342 * Check if the hierarchical zswap limit has been reached.
8344 * This doesn't check for specific headroom, and it is not atomic
8345 * either. But with zswap, the size of the allocation is only known
8346 * once compression has occurred, and this optimistic pre-check avoids
8347 * spending cycles on compression when there is already no room left
8348 * or zswap is disabled altogether somewhere in the hierarchy.
8350 bool obj_cgroup_may_zswap(struct obj_cgroup *objcg)
8352 struct mem_cgroup *memcg, *original_memcg;
8355 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
8358 original_memcg = get_mem_cgroup_from_objcg(objcg);
8359 for (memcg = original_memcg; !mem_cgroup_is_root(memcg);
8360 memcg = parent_mem_cgroup(memcg)) {
8361 unsigned long max = READ_ONCE(memcg->zswap_max);
8362 unsigned long pages;
8364 if (max == PAGE_COUNTER_MAX)
8372 * mem_cgroup_flush_stats() ignores small changes. Use
8373 * do_flush_stats() directly to get accurate stats for charging.
8375 do_flush_stats(memcg);
8376 pages = memcg_page_state(memcg, MEMCG_ZSWAP_B) / PAGE_SIZE;
8382 mem_cgroup_put(original_memcg);
8387 * obj_cgroup_charge_zswap - charge compression backend memory
8388 * @objcg: the object cgroup
8389 * @size: size of compressed object
8391 * This forces the charge after obj_cgroup_may_zswap() allowed
8392 * compression and storage in zwap for this cgroup to go ahead.
8394 void obj_cgroup_charge_zswap(struct obj_cgroup *objcg, size_t size)
8396 struct mem_cgroup *memcg;
8398 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
8401 VM_WARN_ON_ONCE(!(current->flags & PF_MEMALLOC));
8403 /* PF_MEMALLOC context, charging must succeed */
8404 if (obj_cgroup_charge(objcg, GFP_KERNEL, size))
8408 memcg = obj_cgroup_memcg(objcg);
8409 mod_memcg_state(memcg, MEMCG_ZSWAP_B, size);
8410 mod_memcg_state(memcg, MEMCG_ZSWAPPED, 1);
8415 * obj_cgroup_uncharge_zswap - uncharge compression backend memory
8416 * @objcg: the object cgroup
8417 * @size: size of compressed object
8419 * Uncharges zswap memory on page in.
8421 void obj_cgroup_uncharge_zswap(struct obj_cgroup *objcg, size_t size)
8423 struct mem_cgroup *memcg;
8425 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
8428 obj_cgroup_uncharge(objcg, size);
8431 memcg = obj_cgroup_memcg(objcg);
8432 mod_memcg_state(memcg, MEMCG_ZSWAP_B, -size);
8433 mod_memcg_state(memcg, MEMCG_ZSWAPPED, -1);
8437 bool mem_cgroup_zswap_writeback_enabled(struct mem_cgroup *memcg)
8439 /* if zswap is disabled, do not block pages going to the swapping device */
8440 return !is_zswap_enabled() || !memcg || READ_ONCE(memcg->zswap_writeback);
8443 static u64 zswap_current_read(struct cgroup_subsys_state *css,
8446 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
8448 mem_cgroup_flush_stats(memcg);
8449 return memcg_page_state(memcg, MEMCG_ZSWAP_B);
8452 static int zswap_max_show(struct seq_file *m, void *v)
8454 return seq_puts_memcg_tunable(m,
8455 READ_ONCE(mem_cgroup_from_seq(m)->zswap_max));
8458 static ssize_t zswap_max_write(struct kernfs_open_file *of,
8459 char *buf, size_t nbytes, loff_t off)
8461 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
8465 buf = strstrip(buf);
8466 err = page_counter_memparse(buf, "max", &max);
8470 xchg(&memcg->zswap_max, max);
8475 static int zswap_writeback_show(struct seq_file *m, void *v)
8477 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
8479 seq_printf(m, "%d\n", READ_ONCE(memcg->zswap_writeback));
8483 static ssize_t zswap_writeback_write(struct kernfs_open_file *of,
8484 char *buf, size_t nbytes, loff_t off)
8486 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
8487 int zswap_writeback;
8488 ssize_t parse_ret = kstrtoint(strstrip(buf), 0, &zswap_writeback);
8493 if (zswap_writeback != 0 && zswap_writeback != 1)
8496 WRITE_ONCE(memcg->zswap_writeback, zswap_writeback);
8500 static struct cftype zswap_files[] = {
8502 .name = "zswap.current",
8503 .flags = CFTYPE_NOT_ON_ROOT,
8504 .read_u64 = zswap_current_read,
8507 .name = "zswap.max",
8508 .flags = CFTYPE_NOT_ON_ROOT,
8509 .seq_show = zswap_max_show,
8510 .write = zswap_max_write,
8513 .name = "zswap.writeback",
8514 .seq_show = zswap_writeback_show,
8515 .write = zswap_writeback_write,
8519 #endif /* CONFIG_MEMCG_KMEM && CONFIG_ZSWAP */
8521 static int __init mem_cgroup_swap_init(void)
8523 if (mem_cgroup_disabled())
8526 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files));
8527 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files));
8528 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
8529 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, zswap_files));
8533 subsys_initcall(mem_cgroup_swap_init);
8535 #endif /* CONFIG_SWAP */