1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* memcontrol.c - Memory Controller
4 * Copyright IBM Corporation, 2007
5 * Author Balbir Singh <balbir@linux.vnet.ibm.com>
7 * Copyright 2007 OpenVZ SWsoft Inc
8 * Author: Pavel Emelianov <xemul@openvz.org>
11 * Copyright (C) 2009 Nokia Corporation
12 * Author: Kirill A. Shutemov
14 * Kernel Memory Controller
15 * Copyright (C) 2012 Parallels Inc. and Google Inc.
16 * Authors: Glauber Costa and Suleiman Souhlal
19 * Charge lifetime sanitation
20 * Lockless page tracking & accounting
21 * Unified hierarchy configuration model
22 * Copyright (C) 2015 Red Hat, Inc., Johannes Weiner
24 * Per memcg lru locking
25 * Copyright (C) 2020 Alibaba, Inc, Alex Shi
28 #include <linux/page_counter.h>
29 #include <linux/memcontrol.h>
30 #include <linux/cgroup.h>
31 #include <linux/pagewalk.h>
32 #include <linux/sched/mm.h>
33 #include <linux/shmem_fs.h>
34 #include <linux/hugetlb.h>
35 #include <linux/pagemap.h>
36 #include <linux/vm_event_item.h>
37 #include <linux/smp.h>
38 #include <linux/page-flags.h>
39 #include <linux/backing-dev.h>
40 #include <linux/bit_spinlock.h>
41 #include <linux/rcupdate.h>
42 #include <linux/limits.h>
43 #include <linux/export.h>
44 #include <linux/mutex.h>
45 #include <linux/rbtree.h>
46 #include <linux/slab.h>
47 #include <linux/swap.h>
48 #include <linux/swapops.h>
49 #include <linux/spinlock.h>
50 #include <linux/eventfd.h>
51 #include <linux/poll.h>
52 #include <linux/sort.h>
54 #include <linux/seq_file.h>
55 #include <linux/vmpressure.h>
56 #include <linux/memremap.h>
57 #include <linux/mm_inline.h>
58 #include <linux/swap_cgroup.h>
59 #include <linux/cpu.h>
60 #include <linux/oom.h>
61 #include <linux/lockdep.h>
62 #include <linux/file.h>
63 #include <linux/resume_user_mode.h>
64 #include <linux/psi.h>
65 #include <linux/seq_buf.h>
66 #include <linux/sched/isolation.h>
73 #include <linux/uaccess.h>
75 #include <trace/events/vmscan.h>
77 struct cgroup_subsys memory_cgrp_subsys __read_mostly;
78 EXPORT_SYMBOL(memory_cgrp_subsys);
80 struct mem_cgroup *root_mem_cgroup __read_mostly;
82 /* Active memory cgroup to use from an interrupt context */
83 DEFINE_PER_CPU(struct mem_cgroup *, int_active_memcg);
84 EXPORT_PER_CPU_SYMBOL_GPL(int_active_memcg);
86 /* Socket memory accounting disabled? */
87 static bool cgroup_memory_nosocket __ro_after_init;
89 /* Kernel memory accounting disabled? */
90 static bool cgroup_memory_nokmem __ro_after_init;
92 /* BPF memory accounting disabled? */
93 static bool cgroup_memory_nobpf __ro_after_init;
95 #ifdef CONFIG_CGROUP_WRITEBACK
96 static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq);
99 /* Whether legacy memory+swap accounting is active */
100 static bool do_memsw_account(void)
102 return !cgroup_subsys_on_dfl(memory_cgrp_subsys);
105 #define THRESHOLDS_EVENTS_TARGET 128
106 #define SOFTLIMIT_EVENTS_TARGET 1024
109 * Cgroups above their limits are maintained in a RB-Tree, independent of
110 * their hierarchy representation
113 struct mem_cgroup_tree_per_node {
114 struct rb_root rb_root;
115 struct rb_node *rb_rightmost;
119 struct mem_cgroup_tree {
120 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
123 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
126 struct mem_cgroup_eventfd_list {
127 struct list_head list;
128 struct eventfd_ctx *eventfd;
132 * cgroup_event represents events which userspace want to receive.
134 struct mem_cgroup_event {
136 * memcg which the event belongs to.
138 struct mem_cgroup *memcg;
140 * eventfd to signal userspace about the event.
142 struct eventfd_ctx *eventfd;
144 * Each of these stored in a list by the cgroup.
146 struct list_head list;
148 * register_event() callback will be used to add new userspace
149 * waiter for changes related to this event. Use eventfd_signal()
150 * on eventfd to send notification to userspace.
152 int (*register_event)(struct mem_cgroup *memcg,
153 struct eventfd_ctx *eventfd, const char *args);
155 * unregister_event() callback will be called when userspace closes
156 * the eventfd or on cgroup removing. This callback must be set,
157 * if you want provide notification functionality.
159 void (*unregister_event)(struct mem_cgroup *memcg,
160 struct eventfd_ctx *eventfd);
162 * All fields below needed to unregister event when
163 * userspace closes eventfd.
166 wait_queue_head_t *wqh;
167 wait_queue_entry_t wait;
168 struct work_struct remove;
171 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
172 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
174 /* Stuffs for move charges at task migration. */
176 * Types of charges to be moved.
178 #define MOVE_ANON 0x1U
179 #define MOVE_FILE 0x2U
180 #define MOVE_MASK (MOVE_ANON | MOVE_FILE)
182 /* "mc" and its members are protected by cgroup_mutex */
183 static struct move_charge_struct {
184 spinlock_t lock; /* for from, to */
185 struct mm_struct *mm;
186 struct mem_cgroup *from;
187 struct mem_cgroup *to;
189 unsigned long precharge;
190 unsigned long moved_charge;
191 unsigned long moved_swap;
192 struct task_struct *moving_task; /* a task moving charges */
193 wait_queue_head_t waitq; /* a waitq for other context */
195 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
196 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
200 * Maximum loops in mem_cgroup_soft_reclaim(), used for soft
201 * limit reclaim to prevent infinite loops, if they ever occur.
203 #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
204 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
206 /* for encoding cft->private value on file */
214 #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
215 #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
216 #define MEMFILE_ATTR(val) ((val) & 0xffff)
219 * Iteration constructs for visiting all cgroups (under a tree). If
220 * loops are exited prematurely (break), mem_cgroup_iter_break() must
221 * be used for reference counting.
223 #define for_each_mem_cgroup_tree(iter, root) \
224 for (iter = mem_cgroup_iter(root, NULL, NULL); \
226 iter = mem_cgroup_iter(root, iter, NULL))
228 #define for_each_mem_cgroup(iter) \
229 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
231 iter = mem_cgroup_iter(NULL, iter, NULL))
233 static inline bool task_is_dying(void)
235 return tsk_is_oom_victim(current) || fatal_signal_pending(current) ||
236 (current->flags & PF_EXITING);
239 /* Some nice accessors for the vmpressure. */
240 struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
243 memcg = root_mem_cgroup;
244 return &memcg->vmpressure;
247 struct mem_cgroup *vmpressure_to_memcg(struct vmpressure *vmpr)
249 return container_of(vmpr, struct mem_cgroup, vmpressure);
252 #define CURRENT_OBJCG_UPDATE_BIT 0
253 #define CURRENT_OBJCG_UPDATE_FLAG (1UL << CURRENT_OBJCG_UPDATE_BIT)
255 #ifdef CONFIG_MEMCG_KMEM
256 static DEFINE_SPINLOCK(objcg_lock);
258 bool mem_cgroup_kmem_disabled(void)
260 return cgroup_memory_nokmem;
263 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
264 unsigned int nr_pages);
266 static void obj_cgroup_release(struct percpu_ref *ref)
268 struct obj_cgroup *objcg = container_of(ref, struct obj_cgroup, refcnt);
269 unsigned int nr_bytes;
270 unsigned int nr_pages;
274 * At this point all allocated objects are freed, and
275 * objcg->nr_charged_bytes can't have an arbitrary byte value.
276 * However, it can be PAGE_SIZE or (x * PAGE_SIZE).
278 * The following sequence can lead to it:
279 * 1) CPU0: objcg == stock->cached_objcg
280 * 2) CPU1: we do a small allocation (e.g. 92 bytes),
281 * PAGE_SIZE bytes are charged
282 * 3) CPU1: a process from another memcg is allocating something,
283 * the stock if flushed,
284 * objcg->nr_charged_bytes = PAGE_SIZE - 92
285 * 5) CPU0: we do release this object,
286 * 92 bytes are added to stock->nr_bytes
287 * 6) CPU0: stock is flushed,
288 * 92 bytes are added to objcg->nr_charged_bytes
290 * In the result, nr_charged_bytes == PAGE_SIZE.
291 * This page will be uncharged in obj_cgroup_release().
293 nr_bytes = atomic_read(&objcg->nr_charged_bytes);
294 WARN_ON_ONCE(nr_bytes & (PAGE_SIZE - 1));
295 nr_pages = nr_bytes >> PAGE_SHIFT;
298 obj_cgroup_uncharge_pages(objcg, nr_pages);
300 spin_lock_irqsave(&objcg_lock, flags);
301 list_del(&objcg->list);
302 spin_unlock_irqrestore(&objcg_lock, flags);
304 percpu_ref_exit(ref);
305 kfree_rcu(objcg, rcu);
308 static struct obj_cgroup *obj_cgroup_alloc(void)
310 struct obj_cgroup *objcg;
313 objcg = kzalloc(sizeof(struct obj_cgroup), GFP_KERNEL);
317 ret = percpu_ref_init(&objcg->refcnt, obj_cgroup_release, 0,
323 INIT_LIST_HEAD(&objcg->list);
327 static void memcg_reparent_objcgs(struct mem_cgroup *memcg,
328 struct mem_cgroup *parent)
330 struct obj_cgroup *objcg, *iter;
332 objcg = rcu_replace_pointer(memcg->objcg, NULL, true);
334 spin_lock_irq(&objcg_lock);
336 /* 1) Ready to reparent active objcg. */
337 list_add(&objcg->list, &memcg->objcg_list);
338 /* 2) Reparent active objcg and already reparented objcgs to parent. */
339 list_for_each_entry(iter, &memcg->objcg_list, list)
340 WRITE_ONCE(iter->memcg, parent);
341 /* 3) Move already reparented objcgs to the parent's list */
342 list_splice(&memcg->objcg_list, &parent->objcg_list);
344 spin_unlock_irq(&objcg_lock);
346 percpu_ref_kill(&objcg->refcnt);
350 * A lot of the calls to the cache allocation functions are expected to be
351 * inlined by the compiler. Since the calls to memcg_slab_pre_alloc_hook() are
352 * conditional to this static branch, we'll have to allow modules that does
353 * kmem_cache_alloc and the such to see this symbol as well
355 DEFINE_STATIC_KEY_FALSE(memcg_kmem_online_key);
356 EXPORT_SYMBOL(memcg_kmem_online_key);
358 DEFINE_STATIC_KEY_FALSE(memcg_bpf_enabled_key);
359 EXPORT_SYMBOL(memcg_bpf_enabled_key);
363 * mem_cgroup_css_from_folio - css of the memcg associated with a folio
364 * @folio: folio of interest
366 * If memcg is bound to the default hierarchy, css of the memcg associated
367 * with @folio is returned. The returned css remains associated with @folio
368 * until it is released.
370 * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
373 struct cgroup_subsys_state *mem_cgroup_css_from_folio(struct folio *folio)
375 struct mem_cgroup *memcg = folio_memcg(folio);
377 if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
378 memcg = root_mem_cgroup;
384 * page_cgroup_ino - return inode number of the memcg a page is charged to
387 * Look up the closest online ancestor of the memory cgroup @page is charged to
388 * and return its inode number or 0 if @page is not charged to any cgroup. It
389 * is safe to call this function without holding a reference to @page.
391 * Note, this function is inherently racy, because there is nothing to prevent
392 * the cgroup inode from getting torn down and potentially reallocated a moment
393 * after page_cgroup_ino() returns, so it only should be used by callers that
394 * do not care (such as procfs interfaces).
396 ino_t page_cgroup_ino(struct page *page)
398 struct mem_cgroup *memcg;
399 unsigned long ino = 0;
402 /* page_folio() is racy here, but the entire function is racy anyway */
403 memcg = folio_memcg_check(page_folio(page));
405 while (memcg && !(memcg->css.flags & CSS_ONLINE))
406 memcg = parent_mem_cgroup(memcg);
408 ino = cgroup_ino(memcg->css.cgroup);
413 static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_node *mz,
414 struct mem_cgroup_tree_per_node *mctz,
415 unsigned long new_usage_in_excess)
417 struct rb_node **p = &mctz->rb_root.rb_node;
418 struct rb_node *parent = NULL;
419 struct mem_cgroup_per_node *mz_node;
420 bool rightmost = true;
425 mz->usage_in_excess = new_usage_in_excess;
426 if (!mz->usage_in_excess)
430 mz_node = rb_entry(parent, struct mem_cgroup_per_node,
432 if (mz->usage_in_excess < mz_node->usage_in_excess) {
441 mctz->rb_rightmost = &mz->tree_node;
443 rb_link_node(&mz->tree_node, parent, p);
444 rb_insert_color(&mz->tree_node, &mctz->rb_root);
448 static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
449 struct mem_cgroup_tree_per_node *mctz)
454 if (&mz->tree_node == mctz->rb_rightmost)
455 mctz->rb_rightmost = rb_prev(&mz->tree_node);
457 rb_erase(&mz->tree_node, &mctz->rb_root);
461 static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
462 struct mem_cgroup_tree_per_node *mctz)
466 spin_lock_irqsave(&mctz->lock, flags);
467 __mem_cgroup_remove_exceeded(mz, mctz);
468 spin_unlock_irqrestore(&mctz->lock, flags);
471 static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
473 unsigned long nr_pages = page_counter_read(&memcg->memory);
474 unsigned long soft_limit = READ_ONCE(memcg->soft_limit);
475 unsigned long excess = 0;
477 if (nr_pages > soft_limit)
478 excess = nr_pages - soft_limit;
483 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, int nid)
485 unsigned long excess;
486 struct mem_cgroup_per_node *mz;
487 struct mem_cgroup_tree_per_node *mctz;
489 if (lru_gen_enabled()) {
490 if (soft_limit_excess(memcg))
491 lru_gen_soft_reclaim(memcg, nid);
495 mctz = soft_limit_tree.rb_tree_per_node[nid];
499 * Necessary to update all ancestors when hierarchy is used.
500 * because their event counter is not touched.
502 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
503 mz = memcg->nodeinfo[nid];
504 excess = soft_limit_excess(memcg);
506 * We have to update the tree if mz is on RB-tree or
507 * mem is over its softlimit.
509 if (excess || mz->on_tree) {
512 spin_lock_irqsave(&mctz->lock, flags);
513 /* if on-tree, remove it */
515 __mem_cgroup_remove_exceeded(mz, mctz);
517 * Insert again. mz->usage_in_excess will be updated.
518 * If excess is 0, no tree ops.
520 __mem_cgroup_insert_exceeded(mz, mctz, excess);
521 spin_unlock_irqrestore(&mctz->lock, flags);
526 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
528 struct mem_cgroup_tree_per_node *mctz;
529 struct mem_cgroup_per_node *mz;
533 mz = memcg->nodeinfo[nid];
534 mctz = soft_limit_tree.rb_tree_per_node[nid];
536 mem_cgroup_remove_exceeded(mz, mctz);
540 static struct mem_cgroup_per_node *
541 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
543 struct mem_cgroup_per_node *mz;
547 if (!mctz->rb_rightmost)
548 goto done; /* Nothing to reclaim from */
550 mz = rb_entry(mctz->rb_rightmost,
551 struct mem_cgroup_per_node, tree_node);
553 * Remove the node now but someone else can add it back,
554 * we will to add it back at the end of reclaim to its correct
555 * position in the tree.
557 __mem_cgroup_remove_exceeded(mz, mctz);
558 if (!soft_limit_excess(mz->memcg) ||
559 !css_tryget(&mz->memcg->css))
565 static struct mem_cgroup_per_node *
566 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
568 struct mem_cgroup_per_node *mz;
570 spin_lock_irq(&mctz->lock);
571 mz = __mem_cgroup_largest_soft_limit_node(mctz);
572 spin_unlock_irq(&mctz->lock);
577 * memcg and lruvec stats flushing
579 * Many codepaths leading to stats update or read are performance sensitive and
580 * adding stats flushing in such codepaths is not desirable. So, to optimize the
581 * flushing the kernel does:
583 * 1) Periodically and asynchronously flush the stats every 2 seconds to not let
584 * rstat update tree grow unbounded.
586 * 2) Flush the stats synchronously on reader side only when there are more than
587 * (MEMCG_CHARGE_BATCH * nr_cpus) update events. Though this optimization
588 * will let stats be out of sync by atmost (MEMCG_CHARGE_BATCH * nr_cpus) but
589 * only for 2 seconds due to (1).
591 static void flush_memcg_stats_dwork(struct work_struct *w);
592 static DECLARE_DEFERRABLE_WORK(stats_flush_dwork, flush_memcg_stats_dwork);
593 static DEFINE_PER_CPU(unsigned int, stats_updates);
594 static atomic_t stats_flush_ongoing = ATOMIC_INIT(0);
595 static atomic_t stats_flush_threshold = ATOMIC_INIT(0);
596 static u64 flush_next_time;
598 #define FLUSH_TIME (2UL*HZ)
601 * Accessors to ensure that preemption is disabled on PREEMPT_RT because it can
602 * not rely on this as part of an acquired spinlock_t lock. These functions are
603 * never used in hardirq context on PREEMPT_RT and therefore disabling preemtion
606 static void memcg_stats_lock(void)
608 preempt_disable_nested();
609 VM_WARN_ON_IRQS_ENABLED();
612 static void __memcg_stats_lock(void)
614 preempt_disable_nested();
617 static void memcg_stats_unlock(void)
619 preempt_enable_nested();
622 static inline void memcg_rstat_updated(struct mem_cgroup *memcg, int val)
629 cgroup_rstat_updated(memcg->css.cgroup, smp_processor_id());
631 x = __this_cpu_add_return(stats_updates, abs(val));
632 if (x > MEMCG_CHARGE_BATCH) {
634 * If stats_flush_threshold exceeds the threshold
635 * (>num_online_cpus()), cgroup stats update will be triggered
636 * in __mem_cgroup_flush_stats(). Increasing this var further
637 * is redundant and simply adds overhead in atomic update.
639 if (atomic_read(&stats_flush_threshold) <= num_online_cpus())
640 atomic_add(x / MEMCG_CHARGE_BATCH, &stats_flush_threshold);
641 __this_cpu_write(stats_updates, 0);
645 static void do_flush_stats(void)
648 * We always flush the entire tree, so concurrent flushers can just
649 * skip. This avoids a thundering herd problem on the rstat global lock
650 * from memcg flushers (e.g. reclaim, refault, etc).
652 if (atomic_read(&stats_flush_ongoing) ||
653 atomic_xchg(&stats_flush_ongoing, 1))
656 WRITE_ONCE(flush_next_time, jiffies_64 + 2*FLUSH_TIME);
658 cgroup_rstat_flush(root_mem_cgroup->css.cgroup);
660 atomic_set(&stats_flush_threshold, 0);
661 atomic_set(&stats_flush_ongoing, 0);
664 void mem_cgroup_flush_stats(void)
666 if (atomic_read(&stats_flush_threshold) > num_online_cpus())
670 void mem_cgroup_flush_stats_ratelimited(void)
672 if (time_after64(jiffies_64, READ_ONCE(flush_next_time)))
673 mem_cgroup_flush_stats();
676 static void flush_memcg_stats_dwork(struct work_struct *w)
679 * Always flush here so that flushing in latency-sensitive paths is
680 * as cheap as possible.
683 queue_delayed_work(system_unbound_wq, &stats_flush_dwork, FLUSH_TIME);
686 /* Subset of vm_event_item to report for memcg event stats */
687 static const unsigned int memcg_vm_event_stat[] = {
703 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
707 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
715 #define NR_MEMCG_EVENTS ARRAY_SIZE(memcg_vm_event_stat)
716 static int mem_cgroup_events_index[NR_VM_EVENT_ITEMS] __read_mostly;
718 static void init_memcg_events(void)
722 for (i = 0; i < NR_MEMCG_EVENTS; ++i)
723 mem_cgroup_events_index[memcg_vm_event_stat[i]] = i + 1;
726 static inline int memcg_events_index(enum vm_event_item idx)
728 return mem_cgroup_events_index[idx] - 1;
731 struct memcg_vmstats_percpu {
732 /* Local (CPU and cgroup) page state & events */
733 long state[MEMCG_NR_STAT];
734 unsigned long events[NR_MEMCG_EVENTS];
736 /* Delta calculation for lockless upward propagation */
737 long state_prev[MEMCG_NR_STAT];
738 unsigned long events_prev[NR_MEMCG_EVENTS];
740 /* Cgroup1: threshold notifications & softlimit tree updates */
741 unsigned long nr_page_events;
742 unsigned long targets[MEM_CGROUP_NTARGETS];
745 struct memcg_vmstats {
746 /* Aggregated (CPU and subtree) page state & events */
747 long state[MEMCG_NR_STAT];
748 unsigned long events[NR_MEMCG_EVENTS];
750 /* Non-hierarchical (CPU aggregated) page state & events */
751 long state_local[MEMCG_NR_STAT];
752 unsigned long events_local[NR_MEMCG_EVENTS];
754 /* Pending child counts during tree propagation */
755 long state_pending[MEMCG_NR_STAT];
756 unsigned long events_pending[NR_MEMCG_EVENTS];
759 unsigned long memcg_page_state(struct mem_cgroup *memcg, int idx)
761 long x = READ_ONCE(memcg->vmstats->state[idx]);
769 static int memcg_page_state_unit(int item);
772 * Normalize the value passed into memcg_rstat_updated() to be in pages. Round
773 * up non-zero sub-page updates to 1 page as zero page updates are ignored.
775 static int memcg_state_val_in_pages(int idx, int val)
777 int unit = memcg_page_state_unit(idx);
779 if (!val || unit == PAGE_SIZE)
782 return max(val * unit / PAGE_SIZE, 1UL);
786 * __mod_memcg_state - update cgroup memory statistics
787 * @memcg: the memory cgroup
788 * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item
789 * @val: delta to add to the counter, can be negative
791 void __mod_memcg_state(struct mem_cgroup *memcg, int idx, int val)
793 if (mem_cgroup_disabled())
796 __this_cpu_add(memcg->vmstats_percpu->state[idx], val);
797 memcg_rstat_updated(memcg, memcg_state_val_in_pages(idx, val));
800 /* idx can be of type enum memcg_stat_item or node_stat_item. */
801 static unsigned long memcg_page_state_local(struct mem_cgroup *memcg, int idx)
803 long x = READ_ONCE(memcg->vmstats->state_local[idx]);
812 void __mod_memcg_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
815 struct mem_cgroup_per_node *pn;
816 struct mem_cgroup *memcg;
818 pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
822 * The caller from rmap relies on disabled preemption because they never
823 * update their counter from in-interrupt context. For these two
824 * counters we check that the update is never performed from an
825 * interrupt context while other caller need to have disabled interrupt.
827 __memcg_stats_lock();
828 if (IS_ENABLED(CONFIG_DEBUG_VM)) {
833 case NR_SHMEM_PMDMAPPED:
834 case NR_FILE_PMDMAPPED:
835 WARN_ON_ONCE(!in_task());
838 VM_WARN_ON_IRQS_ENABLED();
843 __this_cpu_add(memcg->vmstats_percpu->state[idx], val);
846 __this_cpu_add(pn->lruvec_stats_percpu->state[idx], val);
848 memcg_rstat_updated(memcg, memcg_state_val_in_pages(idx, val));
849 memcg_stats_unlock();
853 * __mod_lruvec_state - update lruvec memory statistics
854 * @lruvec: the lruvec
855 * @idx: the stat item
856 * @val: delta to add to the counter, can be negative
858 * The lruvec is the intersection of the NUMA node and a cgroup. This
859 * function updates the all three counters that are affected by a
860 * change of state at this level: per-node, per-cgroup, per-lruvec.
862 void __mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
866 __mod_node_page_state(lruvec_pgdat(lruvec), idx, val);
868 /* Update memcg and lruvec */
869 if (!mem_cgroup_disabled())
870 __mod_memcg_lruvec_state(lruvec, idx, val);
873 void __mod_lruvec_page_state(struct page *page, enum node_stat_item idx,
876 struct page *head = compound_head(page); /* rmap on tail pages */
877 struct mem_cgroup *memcg;
878 pg_data_t *pgdat = page_pgdat(page);
879 struct lruvec *lruvec;
882 memcg = page_memcg(head);
883 /* Untracked pages have no memcg, no lruvec. Update only the node */
886 __mod_node_page_state(pgdat, idx, val);
890 lruvec = mem_cgroup_lruvec(memcg, pgdat);
891 __mod_lruvec_state(lruvec, idx, val);
894 EXPORT_SYMBOL(__mod_lruvec_page_state);
896 void __mod_lruvec_kmem_state(void *p, enum node_stat_item idx, int val)
898 pg_data_t *pgdat = page_pgdat(virt_to_page(p));
899 struct mem_cgroup *memcg;
900 struct lruvec *lruvec;
903 memcg = mem_cgroup_from_slab_obj(p);
906 * Untracked pages have no memcg, no lruvec. Update only the
907 * node. If we reparent the slab objects to the root memcg,
908 * when we free the slab object, we need to update the per-memcg
909 * vmstats to keep it correct for the root memcg.
912 __mod_node_page_state(pgdat, idx, val);
914 lruvec = mem_cgroup_lruvec(memcg, pgdat);
915 __mod_lruvec_state(lruvec, idx, val);
921 * __count_memcg_events - account VM events in a cgroup
922 * @memcg: the memory cgroup
923 * @idx: the event item
924 * @count: the number of events that occurred
926 void __count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx,
929 int index = memcg_events_index(idx);
931 if (mem_cgroup_disabled() || index < 0)
935 __this_cpu_add(memcg->vmstats_percpu->events[index], count);
936 memcg_rstat_updated(memcg, count);
937 memcg_stats_unlock();
940 static unsigned long memcg_events(struct mem_cgroup *memcg, int event)
942 int index = memcg_events_index(event);
946 return READ_ONCE(memcg->vmstats->events[index]);
949 static unsigned long memcg_events_local(struct mem_cgroup *memcg, int event)
951 int index = memcg_events_index(event);
956 return READ_ONCE(memcg->vmstats->events_local[index]);
959 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
962 /* pagein of a big page is an event. So, ignore page size */
964 __count_memcg_events(memcg, PGPGIN, 1);
966 __count_memcg_events(memcg, PGPGOUT, 1);
967 nr_pages = -nr_pages; /* for event */
970 __this_cpu_add(memcg->vmstats_percpu->nr_page_events, nr_pages);
973 static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
974 enum mem_cgroup_events_target target)
976 unsigned long val, next;
978 val = __this_cpu_read(memcg->vmstats_percpu->nr_page_events);
979 next = __this_cpu_read(memcg->vmstats_percpu->targets[target]);
980 /* from time_after() in jiffies.h */
981 if ((long)(next - val) < 0) {
983 case MEM_CGROUP_TARGET_THRESH:
984 next = val + THRESHOLDS_EVENTS_TARGET;
986 case MEM_CGROUP_TARGET_SOFTLIMIT:
987 next = val + SOFTLIMIT_EVENTS_TARGET;
992 __this_cpu_write(memcg->vmstats_percpu->targets[target], next);
999 * Check events in order.
1002 static void memcg_check_events(struct mem_cgroup *memcg, int nid)
1004 if (IS_ENABLED(CONFIG_PREEMPT_RT))
1007 /* threshold event is triggered in finer grain than soft limit */
1008 if (unlikely(mem_cgroup_event_ratelimit(memcg,
1009 MEM_CGROUP_TARGET_THRESH))) {
1012 do_softlimit = mem_cgroup_event_ratelimit(memcg,
1013 MEM_CGROUP_TARGET_SOFTLIMIT);
1014 mem_cgroup_threshold(memcg);
1015 if (unlikely(do_softlimit))
1016 mem_cgroup_update_tree(memcg, nid);
1020 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
1023 * mm_update_next_owner() may clear mm->owner to NULL
1024 * if it races with swapoff, page migration, etc.
1025 * So this can be called with p == NULL.
1030 return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
1032 EXPORT_SYMBOL(mem_cgroup_from_task);
1034 static __always_inline struct mem_cgroup *active_memcg(void)
1037 return this_cpu_read(int_active_memcg);
1039 return current->active_memcg;
1043 * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
1044 * @mm: mm from which memcg should be extracted. It can be NULL.
1046 * Obtain a reference on mm->memcg and returns it if successful. If mm
1047 * is NULL, then the memcg is chosen as follows:
1048 * 1) The active memcg, if set.
1049 * 2) current->mm->memcg, if available
1051 * If mem_cgroup is disabled, NULL is returned.
1053 struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
1055 struct mem_cgroup *memcg;
1057 if (mem_cgroup_disabled())
1061 * Page cache insertions can happen without an
1062 * actual mm context, e.g. during disk probing
1063 * on boot, loopback IO, acct() writes etc.
1065 * No need to css_get on root memcg as the reference
1066 * counting is disabled on the root level in the
1067 * cgroup core. See CSS_NO_REF.
1069 if (unlikely(!mm)) {
1070 memcg = active_memcg();
1071 if (unlikely(memcg)) {
1072 /* remote memcg must hold a ref */
1073 css_get(&memcg->css);
1078 return root_mem_cgroup;
1083 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1084 if (unlikely(!memcg))
1085 memcg = root_mem_cgroup;
1086 } while (!css_tryget(&memcg->css));
1090 EXPORT_SYMBOL(get_mem_cgroup_from_mm);
1093 * get_mem_cgroup_from_current - Obtain a reference on current task's memcg.
1095 struct mem_cgroup *get_mem_cgroup_from_current(void)
1097 struct mem_cgroup *memcg;
1099 if (mem_cgroup_disabled())
1104 memcg = mem_cgroup_from_task(current);
1105 if (!css_tryget(&memcg->css)) {
1114 * mem_cgroup_iter - iterate over memory cgroup hierarchy
1115 * @root: hierarchy root
1116 * @prev: previously returned memcg, NULL on first invocation
1117 * @reclaim: cookie for shared reclaim walks, NULL for full walks
1119 * Returns references to children of the hierarchy below @root, or
1120 * @root itself, or %NULL after a full round-trip.
1122 * Caller must pass the return value in @prev on subsequent
1123 * invocations for reference counting, or use mem_cgroup_iter_break()
1124 * to cancel a hierarchy walk before the round-trip is complete.
1126 * Reclaimers can specify a node in @reclaim to divide up the memcgs
1127 * in the hierarchy among all concurrent reclaimers operating on the
1130 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
1131 struct mem_cgroup *prev,
1132 struct mem_cgroup_reclaim_cookie *reclaim)
1134 struct mem_cgroup_reclaim_iter *iter;
1135 struct cgroup_subsys_state *css = NULL;
1136 struct mem_cgroup *memcg = NULL;
1137 struct mem_cgroup *pos = NULL;
1139 if (mem_cgroup_disabled())
1143 root = root_mem_cgroup;
1148 struct mem_cgroup_per_node *mz;
1150 mz = root->nodeinfo[reclaim->pgdat->node_id];
1154 * On start, join the current reclaim iteration cycle.
1155 * Exit when a concurrent walker completes it.
1158 reclaim->generation = iter->generation;
1159 else if (reclaim->generation != iter->generation)
1163 pos = READ_ONCE(iter->position);
1164 if (!pos || css_tryget(&pos->css))
1167 * css reference reached zero, so iter->position will
1168 * be cleared by ->css_released. However, we should not
1169 * rely on this happening soon, because ->css_released
1170 * is called from a work queue, and by busy-waiting we
1171 * might block it. So we clear iter->position right
1174 (void)cmpxchg(&iter->position, pos, NULL);
1184 css = css_next_descendant_pre(css, &root->css);
1187 * Reclaimers share the hierarchy walk, and a
1188 * new one might jump in right at the end of
1189 * the hierarchy - make sure they see at least
1190 * one group and restart from the beginning.
1198 * Verify the css and acquire a reference. The root
1199 * is provided by the caller, so we know it's alive
1200 * and kicking, and don't take an extra reference.
1202 if (css == &root->css || css_tryget(css)) {
1203 memcg = mem_cgroup_from_css(css);
1210 * The position could have already been updated by a competing
1211 * thread, so check that the value hasn't changed since we read
1212 * it to avoid reclaiming from the same cgroup twice.
1214 (void)cmpxchg(&iter->position, pos, memcg);
1225 if (prev && prev != root)
1226 css_put(&prev->css);
1232 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1233 * @root: hierarchy root
1234 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1236 void mem_cgroup_iter_break(struct mem_cgroup *root,
1237 struct mem_cgroup *prev)
1240 root = root_mem_cgroup;
1241 if (prev && prev != root)
1242 css_put(&prev->css);
1245 static void __invalidate_reclaim_iterators(struct mem_cgroup *from,
1246 struct mem_cgroup *dead_memcg)
1248 struct mem_cgroup_reclaim_iter *iter;
1249 struct mem_cgroup_per_node *mz;
1252 for_each_node(nid) {
1253 mz = from->nodeinfo[nid];
1255 cmpxchg(&iter->position, dead_memcg, NULL);
1259 static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
1261 struct mem_cgroup *memcg = dead_memcg;
1262 struct mem_cgroup *last;
1265 __invalidate_reclaim_iterators(memcg, dead_memcg);
1267 } while ((memcg = parent_mem_cgroup(memcg)));
1270 * When cgroup1 non-hierarchy mode is used,
1271 * parent_mem_cgroup() does not walk all the way up to the
1272 * cgroup root (root_mem_cgroup). So we have to handle
1273 * dead_memcg from cgroup root separately.
1275 if (!mem_cgroup_is_root(last))
1276 __invalidate_reclaim_iterators(root_mem_cgroup,
1281 * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
1282 * @memcg: hierarchy root
1283 * @fn: function to call for each task
1284 * @arg: argument passed to @fn
1286 * This function iterates over tasks attached to @memcg or to any of its
1287 * descendants and calls @fn for each task. If @fn returns a non-zero
1288 * value, the function breaks the iteration loop. Otherwise, it will iterate
1289 * over all tasks and return 0.
1291 * This function must not be called for the root memory cgroup.
1293 void mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
1294 int (*fn)(struct task_struct *, void *), void *arg)
1296 struct mem_cgroup *iter;
1299 BUG_ON(mem_cgroup_is_root(memcg));
1301 for_each_mem_cgroup_tree(iter, memcg) {
1302 struct css_task_iter it;
1303 struct task_struct *task;
1305 css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it);
1306 while (!ret && (task = css_task_iter_next(&it)))
1307 ret = fn(task, arg);
1308 css_task_iter_end(&it);
1310 mem_cgroup_iter_break(memcg, iter);
1316 #ifdef CONFIG_DEBUG_VM
1317 void lruvec_memcg_debug(struct lruvec *lruvec, struct folio *folio)
1319 struct mem_cgroup *memcg;
1321 if (mem_cgroup_disabled())
1324 memcg = folio_memcg(folio);
1327 VM_BUG_ON_FOLIO(!mem_cgroup_is_root(lruvec_memcg(lruvec)), folio);
1329 VM_BUG_ON_FOLIO(lruvec_memcg(lruvec) != memcg, folio);
1334 * folio_lruvec_lock - Lock the lruvec for a folio.
1335 * @folio: Pointer to the folio.
1337 * These functions are safe to use under any of the following conditions:
1339 * - folio_test_lru false
1340 * - folio_memcg_lock()
1341 * - folio frozen (refcount of 0)
1343 * Return: The lruvec this folio is on with its lock held.
1345 struct lruvec *folio_lruvec_lock(struct folio *folio)
1347 struct lruvec *lruvec = folio_lruvec(folio);
1349 spin_lock(&lruvec->lru_lock);
1350 lruvec_memcg_debug(lruvec, folio);
1356 * folio_lruvec_lock_irq - Lock the lruvec for a folio.
1357 * @folio: Pointer to the folio.
1359 * These functions are safe to use under any of the following conditions:
1361 * - folio_test_lru false
1362 * - folio_memcg_lock()
1363 * - folio frozen (refcount of 0)
1365 * Return: The lruvec this folio is on with its lock held and interrupts
1368 struct lruvec *folio_lruvec_lock_irq(struct folio *folio)
1370 struct lruvec *lruvec = folio_lruvec(folio);
1372 spin_lock_irq(&lruvec->lru_lock);
1373 lruvec_memcg_debug(lruvec, folio);
1379 * folio_lruvec_lock_irqsave - Lock the lruvec for a folio.
1380 * @folio: Pointer to the folio.
1381 * @flags: Pointer to irqsave flags.
1383 * These functions are safe to use under any of the following conditions:
1385 * - folio_test_lru false
1386 * - folio_memcg_lock()
1387 * - folio frozen (refcount of 0)
1389 * Return: The lruvec this folio is on with its lock held and interrupts
1392 struct lruvec *folio_lruvec_lock_irqsave(struct folio *folio,
1393 unsigned long *flags)
1395 struct lruvec *lruvec = folio_lruvec(folio);
1397 spin_lock_irqsave(&lruvec->lru_lock, *flags);
1398 lruvec_memcg_debug(lruvec, folio);
1404 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1405 * @lruvec: mem_cgroup per zone lru vector
1406 * @lru: index of lru list the page is sitting on
1407 * @zid: zone id of the accounted pages
1408 * @nr_pages: positive when adding or negative when removing
1410 * This function must be called under lru_lock, just before a page is added
1411 * to or just after a page is removed from an lru list.
1413 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1414 int zid, int nr_pages)
1416 struct mem_cgroup_per_node *mz;
1417 unsigned long *lru_size;
1420 if (mem_cgroup_disabled())
1423 mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
1424 lru_size = &mz->lru_zone_size[zid][lru];
1427 *lru_size += nr_pages;
1430 if (WARN_ONCE(size < 0,
1431 "%s(%p, %d, %d): lru_size %ld\n",
1432 __func__, lruvec, lru, nr_pages, size)) {
1438 *lru_size += nr_pages;
1442 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1443 * @memcg: the memory cgroup
1445 * Returns the maximum amount of memory @mem can be charged with, in
1448 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1450 unsigned long margin = 0;
1451 unsigned long count;
1452 unsigned long limit;
1454 count = page_counter_read(&memcg->memory);
1455 limit = READ_ONCE(memcg->memory.max);
1457 margin = limit - count;
1459 if (do_memsw_account()) {
1460 count = page_counter_read(&memcg->memsw);
1461 limit = READ_ONCE(memcg->memsw.max);
1463 margin = min(margin, limit - count);
1472 * A routine for checking "mem" is under move_account() or not.
1474 * Checking a cgroup is mc.from or mc.to or under hierarchy of
1475 * moving cgroups. This is for waiting at high-memory pressure
1478 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1480 struct mem_cgroup *from;
1481 struct mem_cgroup *to;
1484 * Unlike task_move routines, we access mc.to, mc.from not under
1485 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1487 spin_lock(&mc.lock);
1493 ret = mem_cgroup_is_descendant(from, memcg) ||
1494 mem_cgroup_is_descendant(to, memcg);
1496 spin_unlock(&mc.lock);
1500 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1502 if (mc.moving_task && current != mc.moving_task) {
1503 if (mem_cgroup_under_move(memcg)) {
1505 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1506 /* moving charge context might have finished. */
1509 finish_wait(&mc.waitq, &wait);
1516 struct memory_stat {
1521 static const struct memory_stat memory_stats[] = {
1522 { "anon", NR_ANON_MAPPED },
1523 { "file", NR_FILE_PAGES },
1524 { "kernel", MEMCG_KMEM },
1525 { "kernel_stack", NR_KERNEL_STACK_KB },
1526 { "pagetables", NR_PAGETABLE },
1527 { "sec_pagetables", NR_SECONDARY_PAGETABLE },
1528 { "percpu", MEMCG_PERCPU_B },
1529 { "sock", MEMCG_SOCK },
1530 { "vmalloc", MEMCG_VMALLOC },
1531 { "shmem", NR_SHMEM },
1532 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
1533 { "zswap", MEMCG_ZSWAP_B },
1534 { "zswapped", MEMCG_ZSWAPPED },
1536 { "file_mapped", NR_FILE_MAPPED },
1537 { "file_dirty", NR_FILE_DIRTY },
1538 { "file_writeback", NR_WRITEBACK },
1540 { "swapcached", NR_SWAPCACHE },
1542 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1543 { "anon_thp", NR_ANON_THPS },
1544 { "file_thp", NR_FILE_THPS },
1545 { "shmem_thp", NR_SHMEM_THPS },
1547 { "inactive_anon", NR_INACTIVE_ANON },
1548 { "active_anon", NR_ACTIVE_ANON },
1549 { "inactive_file", NR_INACTIVE_FILE },
1550 { "active_file", NR_ACTIVE_FILE },
1551 { "unevictable", NR_UNEVICTABLE },
1552 { "slab_reclaimable", NR_SLAB_RECLAIMABLE_B },
1553 { "slab_unreclaimable", NR_SLAB_UNRECLAIMABLE_B },
1555 /* The memory events */
1556 { "workingset_refault_anon", WORKINGSET_REFAULT_ANON },
1557 { "workingset_refault_file", WORKINGSET_REFAULT_FILE },
1558 { "workingset_activate_anon", WORKINGSET_ACTIVATE_ANON },
1559 { "workingset_activate_file", WORKINGSET_ACTIVATE_FILE },
1560 { "workingset_restore_anon", WORKINGSET_RESTORE_ANON },
1561 { "workingset_restore_file", WORKINGSET_RESTORE_FILE },
1562 { "workingset_nodereclaim", WORKINGSET_NODERECLAIM },
1565 /* The actual unit of the state item, not the same as the output unit */
1566 static int memcg_page_state_unit(int item)
1569 case MEMCG_PERCPU_B:
1571 case NR_SLAB_RECLAIMABLE_B:
1572 case NR_SLAB_UNRECLAIMABLE_B:
1574 case NR_KERNEL_STACK_KB:
1581 /* Translate stat items to the correct unit for memory.stat output */
1582 static int memcg_page_state_output_unit(int item)
1585 * Workingset state is actually in pages, but we export it to userspace
1586 * as a scalar count of events, so special case it here.
1589 case WORKINGSET_REFAULT_ANON:
1590 case WORKINGSET_REFAULT_FILE:
1591 case WORKINGSET_ACTIVATE_ANON:
1592 case WORKINGSET_ACTIVATE_FILE:
1593 case WORKINGSET_RESTORE_ANON:
1594 case WORKINGSET_RESTORE_FILE:
1595 case WORKINGSET_NODERECLAIM:
1598 return memcg_page_state_unit(item);
1602 static inline unsigned long memcg_page_state_output(struct mem_cgroup *memcg,
1605 return memcg_page_state(memcg, item) *
1606 memcg_page_state_output_unit(item);
1609 static inline unsigned long memcg_page_state_local_output(
1610 struct mem_cgroup *memcg, int item)
1612 return memcg_page_state_local(memcg, item) *
1613 memcg_page_state_output_unit(item);
1616 static void memcg_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
1621 * Provide statistics on the state of the memory subsystem as
1622 * well as cumulative event counters that show past behavior.
1624 * This list is ordered following a combination of these gradients:
1625 * 1) generic big picture -> specifics and details
1626 * 2) reflecting userspace activity -> reflecting kernel heuristics
1628 * Current memory state:
1630 mem_cgroup_flush_stats();
1632 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
1635 size = memcg_page_state_output(memcg, memory_stats[i].idx);
1636 seq_buf_printf(s, "%s %llu\n", memory_stats[i].name, size);
1638 if (unlikely(memory_stats[i].idx == NR_SLAB_UNRECLAIMABLE_B)) {
1639 size += memcg_page_state_output(memcg,
1640 NR_SLAB_RECLAIMABLE_B);
1641 seq_buf_printf(s, "slab %llu\n", size);
1645 /* Accumulated memory events */
1646 seq_buf_printf(s, "pgscan %lu\n",
1647 memcg_events(memcg, PGSCAN_KSWAPD) +
1648 memcg_events(memcg, PGSCAN_DIRECT) +
1649 memcg_events(memcg, PGSCAN_KHUGEPAGED));
1650 seq_buf_printf(s, "pgsteal %lu\n",
1651 memcg_events(memcg, PGSTEAL_KSWAPD) +
1652 memcg_events(memcg, PGSTEAL_DIRECT) +
1653 memcg_events(memcg, PGSTEAL_KHUGEPAGED));
1655 for (i = 0; i < ARRAY_SIZE(memcg_vm_event_stat); i++) {
1656 if (memcg_vm_event_stat[i] == PGPGIN ||
1657 memcg_vm_event_stat[i] == PGPGOUT)
1660 seq_buf_printf(s, "%s %lu\n",
1661 vm_event_name(memcg_vm_event_stat[i]),
1662 memcg_events(memcg, memcg_vm_event_stat[i]));
1665 /* The above should easily fit into one page */
1666 WARN_ON_ONCE(seq_buf_has_overflowed(s));
1669 static void memcg1_stat_format(struct mem_cgroup *memcg, struct seq_buf *s);
1671 static void memory_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
1673 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1674 memcg_stat_format(memcg, s);
1676 memcg1_stat_format(memcg, s);
1677 WARN_ON_ONCE(seq_buf_has_overflowed(s));
1681 * mem_cgroup_print_oom_context: Print OOM information relevant to
1682 * memory controller.
1683 * @memcg: The memory cgroup that went over limit
1684 * @p: Task that is going to be killed
1686 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1689 void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p)
1694 pr_cont(",oom_memcg=");
1695 pr_cont_cgroup_path(memcg->css.cgroup);
1697 pr_cont(",global_oom");
1699 pr_cont(",task_memcg=");
1700 pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
1706 * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
1707 * memory controller.
1708 * @memcg: The memory cgroup that went over limit
1710 void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
1712 /* Use static buffer, for the caller is holding oom_lock. */
1713 static char buf[PAGE_SIZE];
1716 lockdep_assert_held(&oom_lock);
1718 pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1719 K((u64)page_counter_read(&memcg->memory)),
1720 K((u64)READ_ONCE(memcg->memory.max)), memcg->memory.failcnt);
1721 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1722 pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n",
1723 K((u64)page_counter_read(&memcg->swap)),
1724 K((u64)READ_ONCE(memcg->swap.max)), memcg->swap.failcnt);
1726 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1727 K((u64)page_counter_read(&memcg->memsw)),
1728 K((u64)memcg->memsw.max), memcg->memsw.failcnt);
1729 pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1730 K((u64)page_counter_read(&memcg->kmem)),
1731 K((u64)memcg->kmem.max), memcg->kmem.failcnt);
1734 pr_info("Memory cgroup stats for ");
1735 pr_cont_cgroup_path(memcg->css.cgroup);
1737 seq_buf_init(&s, buf, sizeof(buf));
1738 memory_stat_format(memcg, &s);
1739 seq_buf_do_printk(&s, KERN_INFO);
1743 * Return the memory (and swap, if configured) limit for a memcg.
1745 unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg)
1747 unsigned long max = READ_ONCE(memcg->memory.max);
1749 if (do_memsw_account()) {
1750 if (mem_cgroup_swappiness(memcg)) {
1751 /* Calculate swap excess capacity from memsw limit */
1752 unsigned long swap = READ_ONCE(memcg->memsw.max) - max;
1754 max += min(swap, (unsigned long)total_swap_pages);
1757 if (mem_cgroup_swappiness(memcg))
1758 max += min(READ_ONCE(memcg->swap.max),
1759 (unsigned long)total_swap_pages);
1764 unsigned long mem_cgroup_size(struct mem_cgroup *memcg)
1766 return page_counter_read(&memcg->memory);
1769 static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1772 struct oom_control oc = {
1776 .gfp_mask = gfp_mask,
1781 if (mutex_lock_killable(&oom_lock))
1784 if (mem_cgroup_margin(memcg) >= (1 << order))
1788 * A few threads which were not waiting at mutex_lock_killable() can
1789 * fail to bail out. Therefore, check again after holding oom_lock.
1791 ret = task_is_dying() || out_of_memory(&oc);
1794 mutex_unlock(&oom_lock);
1798 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
1801 unsigned long *total_scanned)
1803 struct mem_cgroup *victim = NULL;
1806 unsigned long excess;
1807 unsigned long nr_scanned;
1808 struct mem_cgroup_reclaim_cookie reclaim = {
1812 excess = soft_limit_excess(root_memcg);
1815 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1820 * If we have not been able to reclaim
1821 * anything, it might because there are
1822 * no reclaimable pages under this hierarchy
1827 * We want to do more targeted reclaim.
1828 * excess >> 2 is not to excessive so as to
1829 * reclaim too much, nor too less that we keep
1830 * coming back to reclaim from this cgroup
1832 if (total >= (excess >> 2) ||
1833 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1838 total += mem_cgroup_shrink_node(victim, gfp_mask, false,
1839 pgdat, &nr_scanned);
1840 *total_scanned += nr_scanned;
1841 if (!soft_limit_excess(root_memcg))
1844 mem_cgroup_iter_break(root_memcg, victim);
1848 #ifdef CONFIG_LOCKDEP
1849 static struct lockdep_map memcg_oom_lock_dep_map = {
1850 .name = "memcg_oom_lock",
1854 static DEFINE_SPINLOCK(memcg_oom_lock);
1857 * Check OOM-Killer is already running under our hierarchy.
1858 * If someone is running, return false.
1860 static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
1862 struct mem_cgroup *iter, *failed = NULL;
1864 spin_lock(&memcg_oom_lock);
1866 for_each_mem_cgroup_tree(iter, memcg) {
1867 if (iter->oom_lock) {
1869 * this subtree of our hierarchy is already locked
1870 * so we cannot give a lock.
1873 mem_cgroup_iter_break(memcg, iter);
1876 iter->oom_lock = true;
1881 * OK, we failed to lock the whole subtree so we have
1882 * to clean up what we set up to the failing subtree
1884 for_each_mem_cgroup_tree(iter, memcg) {
1885 if (iter == failed) {
1886 mem_cgroup_iter_break(memcg, iter);
1889 iter->oom_lock = false;
1892 mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
1894 spin_unlock(&memcg_oom_lock);
1899 static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1901 struct mem_cgroup *iter;
1903 spin_lock(&memcg_oom_lock);
1904 mutex_release(&memcg_oom_lock_dep_map, _RET_IP_);
1905 for_each_mem_cgroup_tree(iter, memcg)
1906 iter->oom_lock = false;
1907 spin_unlock(&memcg_oom_lock);
1910 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1912 struct mem_cgroup *iter;
1914 spin_lock(&memcg_oom_lock);
1915 for_each_mem_cgroup_tree(iter, memcg)
1917 spin_unlock(&memcg_oom_lock);
1920 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1922 struct mem_cgroup *iter;
1925 * Be careful about under_oom underflows because a child memcg
1926 * could have been added after mem_cgroup_mark_under_oom.
1928 spin_lock(&memcg_oom_lock);
1929 for_each_mem_cgroup_tree(iter, memcg)
1930 if (iter->under_oom > 0)
1932 spin_unlock(&memcg_oom_lock);
1935 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1937 struct oom_wait_info {
1938 struct mem_cgroup *memcg;
1939 wait_queue_entry_t wait;
1942 static int memcg_oom_wake_function(wait_queue_entry_t *wait,
1943 unsigned mode, int sync, void *arg)
1945 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
1946 struct mem_cgroup *oom_wait_memcg;
1947 struct oom_wait_info *oom_wait_info;
1949 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1950 oom_wait_memcg = oom_wait_info->memcg;
1952 if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
1953 !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
1955 return autoremove_wake_function(wait, mode, sync, arg);
1958 static void memcg_oom_recover(struct mem_cgroup *memcg)
1961 * For the following lockless ->under_oom test, the only required
1962 * guarantee is that it must see the state asserted by an OOM when
1963 * this function is called as a result of userland actions
1964 * triggered by the notification of the OOM. This is trivially
1965 * achieved by invoking mem_cgroup_mark_under_oom() before
1966 * triggering notification.
1968 if (memcg && memcg->under_oom)
1969 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
1973 * Returns true if successfully killed one or more processes. Though in some
1974 * corner cases it can return true even without killing any process.
1976 static bool mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
1980 if (order > PAGE_ALLOC_COSTLY_ORDER)
1983 memcg_memory_event(memcg, MEMCG_OOM);
1986 * We are in the middle of the charge context here, so we
1987 * don't want to block when potentially sitting on a callstack
1988 * that holds all kinds of filesystem and mm locks.
1990 * cgroup1 allows disabling the OOM killer and waiting for outside
1991 * handling until the charge can succeed; remember the context and put
1992 * the task to sleep at the end of the page fault when all locks are
1995 * On the other hand, in-kernel OOM killer allows for an async victim
1996 * memory reclaim (oom_reaper) and that means that we are not solely
1997 * relying on the oom victim to make a forward progress and we can
1998 * invoke the oom killer here.
2000 * Please note that mem_cgroup_out_of_memory might fail to find a
2001 * victim and then we have to bail out from the charge path.
2003 if (READ_ONCE(memcg->oom_kill_disable)) {
2004 if (current->in_user_fault) {
2005 css_get(&memcg->css);
2006 current->memcg_in_oom = memcg;
2007 current->memcg_oom_gfp_mask = mask;
2008 current->memcg_oom_order = order;
2013 mem_cgroup_mark_under_oom(memcg);
2015 locked = mem_cgroup_oom_trylock(memcg);
2018 mem_cgroup_oom_notify(memcg);
2020 mem_cgroup_unmark_under_oom(memcg);
2021 ret = mem_cgroup_out_of_memory(memcg, mask, order);
2024 mem_cgroup_oom_unlock(memcg);
2030 * mem_cgroup_oom_synchronize - complete memcg OOM handling
2031 * @handle: actually kill/wait or just clean up the OOM state
2033 * This has to be called at the end of a page fault if the memcg OOM
2034 * handler was enabled.
2036 * Memcg supports userspace OOM handling where failed allocations must
2037 * sleep on a waitqueue until the userspace task resolves the
2038 * situation. Sleeping directly in the charge context with all kinds
2039 * of locks held is not a good idea, instead we remember an OOM state
2040 * in the task and mem_cgroup_oom_synchronize() has to be called at
2041 * the end of the page fault to complete the OOM handling.
2043 * Returns %true if an ongoing memcg OOM situation was detected and
2044 * completed, %false otherwise.
2046 bool mem_cgroup_oom_synchronize(bool handle)
2048 struct mem_cgroup *memcg = current->memcg_in_oom;
2049 struct oom_wait_info owait;
2052 /* OOM is global, do not handle */
2059 owait.memcg = memcg;
2060 owait.wait.flags = 0;
2061 owait.wait.func = memcg_oom_wake_function;
2062 owait.wait.private = current;
2063 INIT_LIST_HEAD(&owait.wait.entry);
2065 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
2066 mem_cgroup_mark_under_oom(memcg);
2068 locked = mem_cgroup_oom_trylock(memcg);
2071 mem_cgroup_oom_notify(memcg);
2074 mem_cgroup_unmark_under_oom(memcg);
2075 finish_wait(&memcg_oom_waitq, &owait.wait);
2078 mem_cgroup_oom_unlock(memcg);
2080 current->memcg_in_oom = NULL;
2081 css_put(&memcg->css);
2086 * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
2087 * @victim: task to be killed by the OOM killer
2088 * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
2090 * Returns a pointer to a memory cgroup, which has to be cleaned up
2091 * by killing all belonging OOM-killable tasks.
2093 * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
2095 struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim,
2096 struct mem_cgroup *oom_domain)
2098 struct mem_cgroup *oom_group = NULL;
2099 struct mem_cgroup *memcg;
2101 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
2105 oom_domain = root_mem_cgroup;
2109 memcg = mem_cgroup_from_task(victim);
2110 if (mem_cgroup_is_root(memcg))
2114 * If the victim task has been asynchronously moved to a different
2115 * memory cgroup, we might end up killing tasks outside oom_domain.
2116 * In this case it's better to ignore memory.group.oom.
2118 if (unlikely(!mem_cgroup_is_descendant(memcg, oom_domain)))
2122 * Traverse the memory cgroup hierarchy from the victim task's
2123 * cgroup up to the OOMing cgroup (or root) to find the
2124 * highest-level memory cgroup with oom.group set.
2126 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
2127 if (READ_ONCE(memcg->oom_group))
2130 if (memcg == oom_domain)
2135 css_get(&oom_group->css);
2142 void mem_cgroup_print_oom_group(struct mem_cgroup *memcg)
2144 pr_info("Tasks in ");
2145 pr_cont_cgroup_path(memcg->css.cgroup);
2146 pr_cont(" are going to be killed due to memory.oom.group set\n");
2150 * folio_memcg_lock - Bind a folio to its memcg.
2151 * @folio: The folio.
2153 * This function prevents unlocked LRU folios from being moved to
2156 * It ensures lifetime of the bound memcg. The caller is responsible
2157 * for the lifetime of the folio.
2159 void folio_memcg_lock(struct folio *folio)
2161 struct mem_cgroup *memcg;
2162 unsigned long flags;
2165 * The RCU lock is held throughout the transaction. The fast
2166 * path can get away without acquiring the memcg->move_lock
2167 * because page moving starts with an RCU grace period.
2171 if (mem_cgroup_disabled())
2174 memcg = folio_memcg(folio);
2175 if (unlikely(!memcg))
2178 #ifdef CONFIG_PROVE_LOCKING
2179 local_irq_save(flags);
2180 might_lock(&memcg->move_lock);
2181 local_irq_restore(flags);
2184 if (atomic_read(&memcg->moving_account) <= 0)
2187 spin_lock_irqsave(&memcg->move_lock, flags);
2188 if (memcg != folio_memcg(folio)) {
2189 spin_unlock_irqrestore(&memcg->move_lock, flags);
2194 * When charge migration first begins, we can have multiple
2195 * critical sections holding the fast-path RCU lock and one
2196 * holding the slowpath move_lock. Track the task who has the
2197 * move_lock for folio_memcg_unlock().
2199 memcg->move_lock_task = current;
2200 memcg->move_lock_flags = flags;
2203 static void __folio_memcg_unlock(struct mem_cgroup *memcg)
2205 if (memcg && memcg->move_lock_task == current) {
2206 unsigned long flags = memcg->move_lock_flags;
2208 memcg->move_lock_task = NULL;
2209 memcg->move_lock_flags = 0;
2211 spin_unlock_irqrestore(&memcg->move_lock, flags);
2218 * folio_memcg_unlock - Release the binding between a folio and its memcg.
2219 * @folio: The folio.
2221 * This releases the binding created by folio_memcg_lock(). This does
2222 * not change the accounting of this folio to its memcg, but it does
2223 * permit others to change it.
2225 void folio_memcg_unlock(struct folio *folio)
2227 __folio_memcg_unlock(folio_memcg(folio));
2230 struct memcg_stock_pcp {
2231 local_lock_t stock_lock;
2232 struct mem_cgroup *cached; /* this never be root cgroup */
2233 unsigned int nr_pages;
2235 #ifdef CONFIG_MEMCG_KMEM
2236 struct obj_cgroup *cached_objcg;
2237 struct pglist_data *cached_pgdat;
2238 unsigned int nr_bytes;
2239 int nr_slab_reclaimable_b;
2240 int nr_slab_unreclaimable_b;
2243 struct work_struct work;
2244 unsigned long flags;
2245 #define FLUSHING_CACHED_CHARGE 0
2247 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock) = {
2248 .stock_lock = INIT_LOCAL_LOCK(stock_lock),
2250 static DEFINE_MUTEX(percpu_charge_mutex);
2252 #ifdef CONFIG_MEMCG_KMEM
2253 static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock);
2254 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2255 struct mem_cgroup *root_memcg);
2256 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages);
2259 static inline struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock)
2263 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2264 struct mem_cgroup *root_memcg)
2268 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages)
2274 * consume_stock: Try to consume stocked charge on this cpu.
2275 * @memcg: memcg to consume from.
2276 * @nr_pages: how many pages to charge.
2278 * The charges will only happen if @memcg matches the current cpu's memcg
2279 * stock, and at least @nr_pages are available in that stock. Failure to
2280 * service an allocation will refill the stock.
2282 * returns true if successful, false otherwise.
2284 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2286 struct memcg_stock_pcp *stock;
2287 unsigned long flags;
2290 if (nr_pages > MEMCG_CHARGE_BATCH)
2293 local_lock_irqsave(&memcg_stock.stock_lock, flags);
2295 stock = this_cpu_ptr(&memcg_stock);
2296 if (memcg == READ_ONCE(stock->cached) && stock->nr_pages >= nr_pages) {
2297 stock->nr_pages -= nr_pages;
2301 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2307 * Returns stocks cached in percpu and reset cached information.
2309 static void drain_stock(struct memcg_stock_pcp *stock)
2311 struct mem_cgroup *old = READ_ONCE(stock->cached);
2316 if (stock->nr_pages) {
2317 page_counter_uncharge(&old->memory, stock->nr_pages);
2318 if (do_memsw_account())
2319 page_counter_uncharge(&old->memsw, stock->nr_pages);
2320 stock->nr_pages = 0;
2324 WRITE_ONCE(stock->cached, NULL);
2327 static void drain_local_stock(struct work_struct *dummy)
2329 struct memcg_stock_pcp *stock;
2330 struct obj_cgroup *old = NULL;
2331 unsigned long flags;
2334 * The only protection from cpu hotplug (memcg_hotplug_cpu_dead) vs.
2335 * drain_stock races is that we always operate on local CPU stock
2336 * here with IRQ disabled
2338 local_lock_irqsave(&memcg_stock.stock_lock, flags);
2340 stock = this_cpu_ptr(&memcg_stock);
2341 old = drain_obj_stock(stock);
2343 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2345 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2347 obj_cgroup_put(old);
2351 * Cache charges(val) to local per_cpu area.
2352 * This will be consumed by consume_stock() function, later.
2354 static void __refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2356 struct memcg_stock_pcp *stock;
2358 stock = this_cpu_ptr(&memcg_stock);
2359 if (READ_ONCE(stock->cached) != memcg) { /* reset if necessary */
2361 css_get(&memcg->css);
2362 WRITE_ONCE(stock->cached, memcg);
2364 stock->nr_pages += nr_pages;
2366 if (stock->nr_pages > MEMCG_CHARGE_BATCH)
2370 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2372 unsigned long flags;
2374 local_lock_irqsave(&memcg_stock.stock_lock, flags);
2375 __refill_stock(memcg, nr_pages);
2376 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2380 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2381 * of the hierarchy under it.
2383 static void drain_all_stock(struct mem_cgroup *root_memcg)
2387 /* If someone's already draining, avoid adding running more workers. */
2388 if (!mutex_trylock(&percpu_charge_mutex))
2391 * Notify other cpus that system-wide "drain" is running
2392 * We do not care about races with the cpu hotplug because cpu down
2393 * as well as workers from this path always operate on the local
2394 * per-cpu data. CPU up doesn't touch memcg_stock at all.
2397 curcpu = smp_processor_id();
2398 for_each_online_cpu(cpu) {
2399 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2400 struct mem_cgroup *memcg;
2404 memcg = READ_ONCE(stock->cached);
2405 if (memcg && stock->nr_pages &&
2406 mem_cgroup_is_descendant(memcg, root_memcg))
2408 else if (obj_stock_flush_required(stock, root_memcg))
2413 !test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2415 drain_local_stock(&stock->work);
2416 else if (!cpu_is_isolated(cpu))
2417 schedule_work_on(cpu, &stock->work);
2421 mutex_unlock(&percpu_charge_mutex);
2424 static int memcg_hotplug_cpu_dead(unsigned int cpu)
2426 struct memcg_stock_pcp *stock;
2428 stock = &per_cpu(memcg_stock, cpu);
2434 static unsigned long reclaim_high(struct mem_cgroup *memcg,
2435 unsigned int nr_pages,
2438 unsigned long nr_reclaimed = 0;
2441 unsigned long pflags;
2443 if (page_counter_read(&memcg->memory) <=
2444 READ_ONCE(memcg->memory.high))
2447 memcg_memory_event(memcg, MEMCG_HIGH);
2449 psi_memstall_enter(&pflags);
2450 nr_reclaimed += try_to_free_mem_cgroup_pages(memcg, nr_pages,
2452 MEMCG_RECLAIM_MAY_SWAP);
2453 psi_memstall_leave(&pflags);
2454 } while ((memcg = parent_mem_cgroup(memcg)) &&
2455 !mem_cgroup_is_root(memcg));
2457 return nr_reclaimed;
2460 static void high_work_func(struct work_struct *work)
2462 struct mem_cgroup *memcg;
2464 memcg = container_of(work, struct mem_cgroup, high_work);
2465 reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
2469 * Clamp the maximum sleep time per allocation batch to 2 seconds. This is
2470 * enough to still cause a significant slowdown in most cases, while still
2471 * allowing diagnostics and tracing to proceed without becoming stuck.
2473 #define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ)
2476 * When calculating the delay, we use these either side of the exponentiation to
2477 * maintain precision and scale to a reasonable number of jiffies (see the table
2480 * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the
2481 * overage ratio to a delay.
2482 * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down the
2483 * proposed penalty in order to reduce to a reasonable number of jiffies, and
2484 * to produce a reasonable delay curve.
2486 * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a
2487 * reasonable delay curve compared to precision-adjusted overage, not
2488 * penalising heavily at first, but still making sure that growth beyond the
2489 * limit penalises misbehaviour cgroups by slowing them down exponentially. For
2490 * example, with a high of 100 megabytes:
2492 * +-------+------------------------+
2493 * | usage | time to allocate in ms |
2494 * +-------+------------------------+
2516 * +-------+------------------------+
2518 #define MEMCG_DELAY_PRECISION_SHIFT 20
2519 #define MEMCG_DELAY_SCALING_SHIFT 14
2521 static u64 calculate_overage(unsigned long usage, unsigned long high)
2529 * Prevent division by 0 in overage calculation by acting as if
2530 * it was a threshold of 1 page
2532 high = max(high, 1UL);
2534 overage = usage - high;
2535 overage <<= MEMCG_DELAY_PRECISION_SHIFT;
2536 return div64_u64(overage, high);
2539 static u64 mem_find_max_overage(struct mem_cgroup *memcg)
2541 u64 overage, max_overage = 0;
2544 overage = calculate_overage(page_counter_read(&memcg->memory),
2545 READ_ONCE(memcg->memory.high));
2546 max_overage = max(overage, max_overage);
2547 } while ((memcg = parent_mem_cgroup(memcg)) &&
2548 !mem_cgroup_is_root(memcg));
2553 static u64 swap_find_max_overage(struct mem_cgroup *memcg)
2555 u64 overage, max_overage = 0;
2558 overage = calculate_overage(page_counter_read(&memcg->swap),
2559 READ_ONCE(memcg->swap.high));
2561 memcg_memory_event(memcg, MEMCG_SWAP_HIGH);
2562 max_overage = max(overage, max_overage);
2563 } while ((memcg = parent_mem_cgroup(memcg)) &&
2564 !mem_cgroup_is_root(memcg));
2570 * Get the number of jiffies that we should penalise a mischievous cgroup which
2571 * is exceeding its memory.high by checking both it and its ancestors.
2573 static unsigned long calculate_high_delay(struct mem_cgroup *memcg,
2574 unsigned int nr_pages,
2577 unsigned long penalty_jiffies;
2583 * We use overage compared to memory.high to calculate the number of
2584 * jiffies to sleep (penalty_jiffies). Ideally this value should be
2585 * fairly lenient on small overages, and increasingly harsh when the
2586 * memcg in question makes it clear that it has no intention of stopping
2587 * its crazy behaviour, so we exponentially increase the delay based on
2590 penalty_jiffies = max_overage * max_overage * HZ;
2591 penalty_jiffies >>= MEMCG_DELAY_PRECISION_SHIFT;
2592 penalty_jiffies >>= MEMCG_DELAY_SCALING_SHIFT;
2595 * Factor in the task's own contribution to the overage, such that four
2596 * N-sized allocations are throttled approximately the same as one
2597 * 4N-sized allocation.
2599 * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or
2600 * larger the current charge patch is than that.
2602 return penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH;
2606 * Scheduled by try_charge() to be executed from the userland return path
2607 * and reclaims memory over the high limit.
2609 void mem_cgroup_handle_over_high(gfp_t gfp_mask)
2611 unsigned long penalty_jiffies;
2612 unsigned long pflags;
2613 unsigned long nr_reclaimed;
2614 unsigned int nr_pages = current->memcg_nr_pages_over_high;
2615 int nr_retries = MAX_RECLAIM_RETRIES;
2616 struct mem_cgroup *memcg;
2617 bool in_retry = false;
2619 if (likely(!nr_pages))
2622 memcg = get_mem_cgroup_from_mm(current->mm);
2623 current->memcg_nr_pages_over_high = 0;
2627 * The allocating task should reclaim at least the batch size, but for
2628 * subsequent retries we only want to do what's necessary to prevent oom
2629 * or breaching resource isolation.
2631 * This is distinct from memory.max or page allocator behaviour because
2632 * memory.high is currently batched, whereas memory.max and the page
2633 * allocator run every time an allocation is made.
2635 nr_reclaimed = reclaim_high(memcg,
2636 in_retry ? SWAP_CLUSTER_MAX : nr_pages,
2640 * memory.high is breached and reclaim is unable to keep up. Throttle
2641 * allocators proactively to slow down excessive growth.
2643 penalty_jiffies = calculate_high_delay(memcg, nr_pages,
2644 mem_find_max_overage(memcg));
2646 penalty_jiffies += calculate_high_delay(memcg, nr_pages,
2647 swap_find_max_overage(memcg));
2650 * Clamp the max delay per usermode return so as to still keep the
2651 * application moving forwards and also permit diagnostics, albeit
2654 penalty_jiffies = min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES);
2657 * Don't sleep if the amount of jiffies this memcg owes us is so low
2658 * that it's not even worth doing, in an attempt to be nice to those who
2659 * go only a small amount over their memory.high value and maybe haven't
2660 * been aggressively reclaimed enough yet.
2662 if (penalty_jiffies <= HZ / 100)
2666 * If reclaim is making forward progress but we're still over
2667 * memory.high, we want to encourage that rather than doing allocator
2670 if (nr_reclaimed || nr_retries--) {
2676 * If we exit early, we're guaranteed to die (since
2677 * schedule_timeout_killable sets TASK_KILLABLE). This means we don't
2678 * need to account for any ill-begotten jiffies to pay them off later.
2680 psi_memstall_enter(&pflags);
2681 schedule_timeout_killable(penalty_jiffies);
2682 psi_memstall_leave(&pflags);
2685 css_put(&memcg->css);
2688 static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask,
2689 unsigned int nr_pages)
2691 unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
2692 int nr_retries = MAX_RECLAIM_RETRIES;
2693 struct mem_cgroup *mem_over_limit;
2694 struct page_counter *counter;
2695 unsigned long nr_reclaimed;
2696 bool passed_oom = false;
2697 unsigned int reclaim_options = MEMCG_RECLAIM_MAY_SWAP;
2698 bool drained = false;
2699 bool raised_max_event = false;
2700 unsigned long pflags;
2703 if (consume_stock(memcg, nr_pages))
2706 if (!do_memsw_account() ||
2707 page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2708 if (page_counter_try_charge(&memcg->memory, batch, &counter))
2710 if (do_memsw_account())
2711 page_counter_uncharge(&memcg->memsw, batch);
2712 mem_over_limit = mem_cgroup_from_counter(counter, memory);
2714 mem_over_limit = mem_cgroup_from_counter(counter, memsw);
2715 reclaim_options &= ~MEMCG_RECLAIM_MAY_SWAP;
2718 if (batch > nr_pages) {
2724 * Prevent unbounded recursion when reclaim operations need to
2725 * allocate memory. This might exceed the limits temporarily,
2726 * but we prefer facilitating memory reclaim and getting back
2727 * under the limit over triggering OOM kills in these cases.
2729 if (unlikely(current->flags & PF_MEMALLOC))
2732 if (unlikely(task_in_memcg_oom(current)))
2735 if (!gfpflags_allow_blocking(gfp_mask))
2738 memcg_memory_event(mem_over_limit, MEMCG_MAX);
2739 raised_max_event = true;
2741 psi_memstall_enter(&pflags);
2742 nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
2743 gfp_mask, reclaim_options);
2744 psi_memstall_leave(&pflags);
2746 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2750 drain_all_stock(mem_over_limit);
2755 if (gfp_mask & __GFP_NORETRY)
2758 * Even though the limit is exceeded at this point, reclaim
2759 * may have been able to free some pages. Retry the charge
2760 * before killing the task.
2762 * Only for regular pages, though: huge pages are rather
2763 * unlikely to succeed so close to the limit, and we fall back
2764 * to regular pages anyway in case of failure.
2766 if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
2769 * At task move, charge accounts can be doubly counted. So, it's
2770 * better to wait until the end of task_move if something is going on.
2772 if (mem_cgroup_wait_acct_move(mem_over_limit))
2778 if (gfp_mask & __GFP_RETRY_MAYFAIL)
2781 /* Avoid endless loop for tasks bypassed by the oom killer */
2782 if (passed_oom && task_is_dying())
2786 * keep retrying as long as the memcg oom killer is able to make
2787 * a forward progress or bypass the charge if the oom killer
2788 * couldn't make any progress.
2790 if (mem_cgroup_oom(mem_over_limit, gfp_mask,
2791 get_order(nr_pages * PAGE_SIZE))) {
2793 nr_retries = MAX_RECLAIM_RETRIES;
2798 * Memcg doesn't have a dedicated reserve for atomic
2799 * allocations. But like the global atomic pool, we need to
2800 * put the burden of reclaim on regular allocation requests
2801 * and let these go through as privileged allocations.
2803 if (!(gfp_mask & (__GFP_NOFAIL | __GFP_HIGH)))
2807 * If the allocation has to be enforced, don't forget to raise
2808 * a MEMCG_MAX event.
2810 if (!raised_max_event)
2811 memcg_memory_event(mem_over_limit, MEMCG_MAX);
2814 * The allocation either can't fail or will lead to more memory
2815 * being freed very soon. Allow memory usage go over the limit
2816 * temporarily by force charging it.
2818 page_counter_charge(&memcg->memory, nr_pages);
2819 if (do_memsw_account())
2820 page_counter_charge(&memcg->memsw, nr_pages);
2825 if (batch > nr_pages)
2826 refill_stock(memcg, batch - nr_pages);
2829 * If the hierarchy is above the normal consumption range, schedule
2830 * reclaim on returning to userland. We can perform reclaim here
2831 * if __GFP_RECLAIM but let's always punt for simplicity and so that
2832 * GFP_KERNEL can consistently be used during reclaim. @memcg is
2833 * not recorded as it most likely matches current's and won't
2834 * change in the meantime. As high limit is checked again before
2835 * reclaim, the cost of mismatch is negligible.
2838 bool mem_high, swap_high;
2840 mem_high = page_counter_read(&memcg->memory) >
2841 READ_ONCE(memcg->memory.high);
2842 swap_high = page_counter_read(&memcg->swap) >
2843 READ_ONCE(memcg->swap.high);
2845 /* Don't bother a random interrupted task */
2848 schedule_work(&memcg->high_work);
2854 if (mem_high || swap_high) {
2856 * The allocating tasks in this cgroup will need to do
2857 * reclaim or be throttled to prevent further growth
2858 * of the memory or swap footprints.
2860 * Target some best-effort fairness between the tasks,
2861 * and distribute reclaim work and delay penalties
2862 * based on how much each task is actually allocating.
2864 current->memcg_nr_pages_over_high += batch;
2865 set_notify_resume(current);
2868 } while ((memcg = parent_mem_cgroup(memcg)));
2870 if (current->memcg_nr_pages_over_high > MEMCG_CHARGE_BATCH &&
2871 !(current->flags & PF_MEMALLOC) &&
2872 gfpflags_allow_blocking(gfp_mask)) {
2873 mem_cgroup_handle_over_high(gfp_mask);
2878 static inline int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2879 unsigned int nr_pages)
2881 if (mem_cgroup_is_root(memcg))
2884 return try_charge_memcg(memcg, gfp_mask, nr_pages);
2888 * mem_cgroup_cancel_charge() - cancel an uncommitted try_charge() call.
2889 * @memcg: memcg previously charged.
2890 * @nr_pages: number of pages previously charged.
2892 void mem_cgroup_cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
2894 if (mem_cgroup_is_root(memcg))
2897 page_counter_uncharge(&memcg->memory, nr_pages);
2898 if (do_memsw_account())
2899 page_counter_uncharge(&memcg->memsw, nr_pages);
2902 static void commit_charge(struct folio *folio, struct mem_cgroup *memcg)
2904 VM_BUG_ON_FOLIO(folio_memcg(folio), folio);
2906 * Any of the following ensures page's memcg stability:
2910 * - folio_memcg_lock()
2911 * - exclusive reference
2912 * - mem_cgroup_trylock_pages()
2914 folio->memcg_data = (unsigned long)memcg;
2918 * mem_cgroup_commit_charge - commit a previously successful try_charge().
2919 * @folio: folio to commit the charge to.
2920 * @memcg: memcg previously charged.
2922 void mem_cgroup_commit_charge(struct folio *folio, struct mem_cgroup *memcg)
2924 css_get(&memcg->css);
2925 commit_charge(folio, memcg);
2927 local_irq_disable();
2928 mem_cgroup_charge_statistics(memcg, folio_nr_pages(folio));
2929 memcg_check_events(memcg, folio_nid(folio));
2933 #ifdef CONFIG_MEMCG_KMEM
2935 * The allocated objcg pointers array is not accounted directly.
2936 * Moreover, it should not come from DMA buffer and is not readily
2937 * reclaimable. So those GFP bits should be masked off.
2939 #define OBJCGS_CLEAR_MASK (__GFP_DMA | __GFP_RECLAIMABLE | \
2940 __GFP_ACCOUNT | __GFP_NOFAIL)
2943 * mod_objcg_mlstate() may be called with irq enabled, so
2944 * mod_memcg_lruvec_state() should be used.
2946 static inline void mod_objcg_mlstate(struct obj_cgroup *objcg,
2947 struct pglist_data *pgdat,
2948 enum node_stat_item idx, int nr)
2950 struct mem_cgroup *memcg;
2951 struct lruvec *lruvec;
2954 memcg = obj_cgroup_memcg(objcg);
2955 lruvec = mem_cgroup_lruvec(memcg, pgdat);
2956 mod_memcg_lruvec_state(lruvec, idx, nr);
2960 int memcg_alloc_slab_cgroups(struct slab *slab, struct kmem_cache *s,
2961 gfp_t gfp, bool new_slab)
2963 unsigned int objects = objs_per_slab(s, slab);
2964 unsigned long memcg_data;
2967 gfp &= ~OBJCGS_CLEAR_MASK;
2968 vec = kcalloc_node(objects, sizeof(struct obj_cgroup *), gfp,
2973 memcg_data = (unsigned long) vec | MEMCG_DATA_OBJCGS;
2976 * If the slab is brand new and nobody can yet access its
2977 * memcg_data, no synchronization is required and memcg_data can
2978 * be simply assigned.
2980 slab->memcg_data = memcg_data;
2981 } else if (cmpxchg(&slab->memcg_data, 0, memcg_data)) {
2983 * If the slab is already in use, somebody can allocate and
2984 * assign obj_cgroups in parallel. In this case the existing
2985 * objcg vector should be reused.
2991 kmemleak_not_leak(vec);
2995 static __always_inline
2996 struct mem_cgroup *mem_cgroup_from_obj_folio(struct folio *folio, void *p)
2999 * Slab objects are accounted individually, not per-page.
3000 * Memcg membership data for each individual object is saved in
3003 if (folio_test_slab(folio)) {
3004 struct obj_cgroup **objcgs;
3008 slab = folio_slab(folio);
3009 objcgs = slab_objcgs(slab);
3013 off = obj_to_index(slab->slab_cache, slab, p);
3015 return obj_cgroup_memcg(objcgs[off]);
3021 * folio_memcg_check() is used here, because in theory we can encounter
3022 * a folio where the slab flag has been cleared already, but
3023 * slab->memcg_data has not been freed yet
3024 * folio_memcg_check() will guarantee that a proper memory
3025 * cgroup pointer or NULL will be returned.
3027 return folio_memcg_check(folio);
3031 * Returns a pointer to the memory cgroup to which the kernel object is charged.
3033 * A passed kernel object can be a slab object, vmalloc object or a generic
3034 * kernel page, so different mechanisms for getting the memory cgroup pointer
3037 * In certain cases (e.g. kernel stacks or large kmallocs with SLUB) the caller
3038 * can not know for sure how the kernel object is implemented.
3039 * mem_cgroup_from_obj() can be safely used in such cases.
3041 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
3042 * cgroup_mutex, etc.
3044 struct mem_cgroup *mem_cgroup_from_obj(void *p)
3046 struct folio *folio;
3048 if (mem_cgroup_disabled())
3051 if (unlikely(is_vmalloc_addr(p)))
3052 folio = page_folio(vmalloc_to_page(p));
3054 folio = virt_to_folio(p);
3056 return mem_cgroup_from_obj_folio(folio, p);
3060 * Returns a pointer to the memory cgroup to which the kernel object is charged.
3061 * Similar to mem_cgroup_from_obj(), but faster and not suitable for objects,
3062 * allocated using vmalloc().
3064 * A passed kernel object must be a slab object or a generic kernel page.
3066 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
3067 * cgroup_mutex, etc.
3069 struct mem_cgroup *mem_cgroup_from_slab_obj(void *p)
3071 if (mem_cgroup_disabled())
3074 return mem_cgroup_from_obj_folio(virt_to_folio(p), p);
3077 static struct obj_cgroup *__get_obj_cgroup_from_memcg(struct mem_cgroup *memcg)
3079 struct obj_cgroup *objcg = NULL;
3081 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
3082 objcg = rcu_dereference(memcg->objcg);
3083 if (likely(objcg && obj_cgroup_tryget(objcg)))
3090 static struct obj_cgroup *current_objcg_update(void)
3092 struct mem_cgroup *memcg;
3093 struct obj_cgroup *old, *objcg = NULL;
3096 /* Atomically drop the update bit. */
3097 old = xchg(¤t->objcg, NULL);
3099 old = (struct obj_cgroup *)
3100 ((unsigned long)old & ~CURRENT_OBJCG_UPDATE_FLAG);
3102 obj_cgroup_put(old);
3107 /* If new objcg is NULL, no reason for the second atomic update. */
3108 if (!current->mm || (current->flags & PF_KTHREAD))
3112 * Release the objcg pointer from the previous iteration,
3113 * if try_cmpxcg() below fails.
3115 if (unlikely(objcg)) {
3116 obj_cgroup_put(objcg);
3121 * Obtain the new objcg pointer. The current task can be
3122 * asynchronously moved to another memcg and the previous
3123 * memcg can be offlined. So let's get the memcg pointer
3124 * and try get a reference to objcg under a rcu read lock.
3128 memcg = mem_cgroup_from_task(current);
3129 objcg = __get_obj_cgroup_from_memcg(memcg);
3133 * Try set up a new objcg pointer atomically. If it
3134 * fails, it means the update flag was set concurrently, so
3135 * the whole procedure should be repeated.
3137 } while (!try_cmpxchg(¤t->objcg, &old, objcg));
3142 __always_inline struct obj_cgroup *current_obj_cgroup(void)
3144 struct mem_cgroup *memcg;
3145 struct obj_cgroup *objcg;
3148 memcg = current->active_memcg;
3149 if (unlikely(memcg))
3152 objcg = READ_ONCE(current->objcg);
3153 if (unlikely((unsigned long)objcg & CURRENT_OBJCG_UPDATE_FLAG))
3154 objcg = current_objcg_update();
3156 * Objcg reference is kept by the task, so it's safe
3157 * to use the objcg by the current task.
3162 memcg = this_cpu_read(int_active_memcg);
3163 if (unlikely(memcg))
3170 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
3172 * Memcg pointer is protected by scope (see set_active_memcg())
3173 * and is pinning the corresponding objcg, so objcg can't go
3174 * away and can be used within the scope without any additional
3177 objcg = rcu_dereference_check(memcg->objcg, 1);
3185 struct obj_cgroup *get_obj_cgroup_from_folio(struct folio *folio)
3187 struct obj_cgroup *objcg;
3189 if (!memcg_kmem_online())
3192 if (folio_memcg_kmem(folio)) {
3193 objcg = __folio_objcg(folio);
3194 obj_cgroup_get(objcg);
3196 struct mem_cgroup *memcg;
3199 memcg = __folio_memcg(folio);
3201 objcg = __get_obj_cgroup_from_memcg(memcg);
3209 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages)
3211 mod_memcg_state(memcg, MEMCG_KMEM, nr_pages);
3212 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
3214 page_counter_charge(&memcg->kmem, nr_pages);
3216 page_counter_uncharge(&memcg->kmem, -nr_pages);
3222 * obj_cgroup_uncharge_pages: uncharge a number of kernel pages from a objcg
3223 * @objcg: object cgroup to uncharge
3224 * @nr_pages: number of pages to uncharge
3226 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
3227 unsigned int nr_pages)
3229 struct mem_cgroup *memcg;
3231 memcg = get_mem_cgroup_from_objcg(objcg);
3233 memcg_account_kmem(memcg, -nr_pages);
3234 refill_stock(memcg, nr_pages);
3236 css_put(&memcg->css);
3240 * obj_cgroup_charge_pages: charge a number of kernel pages to a objcg
3241 * @objcg: object cgroup to charge
3242 * @gfp: reclaim mode
3243 * @nr_pages: number of pages to charge
3245 * Returns 0 on success, an error code on failure.
3247 static int obj_cgroup_charge_pages(struct obj_cgroup *objcg, gfp_t gfp,
3248 unsigned int nr_pages)
3250 struct mem_cgroup *memcg;
3253 memcg = get_mem_cgroup_from_objcg(objcg);
3255 ret = try_charge_memcg(memcg, gfp, nr_pages);
3259 memcg_account_kmem(memcg, nr_pages);
3261 css_put(&memcg->css);
3267 * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup
3268 * @page: page to charge
3269 * @gfp: reclaim mode
3270 * @order: allocation order
3272 * Returns 0 on success, an error code on failure.
3274 int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
3276 struct obj_cgroup *objcg;
3279 objcg = current_obj_cgroup();
3281 ret = obj_cgroup_charge_pages(objcg, gfp, 1 << order);
3283 obj_cgroup_get(objcg);
3284 page->memcg_data = (unsigned long)objcg |
3293 * __memcg_kmem_uncharge_page: uncharge a kmem page
3294 * @page: page to uncharge
3295 * @order: allocation order
3297 void __memcg_kmem_uncharge_page(struct page *page, int order)
3299 struct folio *folio = page_folio(page);
3300 struct obj_cgroup *objcg;
3301 unsigned int nr_pages = 1 << order;
3303 if (!folio_memcg_kmem(folio))
3306 objcg = __folio_objcg(folio);
3307 obj_cgroup_uncharge_pages(objcg, nr_pages);
3308 folio->memcg_data = 0;
3309 obj_cgroup_put(objcg);
3312 void mod_objcg_state(struct obj_cgroup *objcg, struct pglist_data *pgdat,
3313 enum node_stat_item idx, int nr)
3315 struct memcg_stock_pcp *stock;
3316 struct obj_cgroup *old = NULL;
3317 unsigned long flags;
3320 local_lock_irqsave(&memcg_stock.stock_lock, flags);
3321 stock = this_cpu_ptr(&memcg_stock);
3324 * Save vmstat data in stock and skip vmstat array update unless
3325 * accumulating over a page of vmstat data or when pgdat or idx
3328 if (READ_ONCE(stock->cached_objcg) != objcg) {
3329 old = drain_obj_stock(stock);
3330 obj_cgroup_get(objcg);
3331 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3332 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3333 WRITE_ONCE(stock->cached_objcg, objcg);
3334 stock->cached_pgdat = pgdat;
3335 } else if (stock->cached_pgdat != pgdat) {
3336 /* Flush the existing cached vmstat data */
3337 struct pglist_data *oldpg = stock->cached_pgdat;
3339 if (stock->nr_slab_reclaimable_b) {
3340 mod_objcg_mlstate(objcg, oldpg, NR_SLAB_RECLAIMABLE_B,
3341 stock->nr_slab_reclaimable_b);
3342 stock->nr_slab_reclaimable_b = 0;
3344 if (stock->nr_slab_unreclaimable_b) {
3345 mod_objcg_mlstate(objcg, oldpg, NR_SLAB_UNRECLAIMABLE_B,
3346 stock->nr_slab_unreclaimable_b);
3347 stock->nr_slab_unreclaimable_b = 0;
3349 stock->cached_pgdat = pgdat;
3352 bytes = (idx == NR_SLAB_RECLAIMABLE_B) ? &stock->nr_slab_reclaimable_b
3353 : &stock->nr_slab_unreclaimable_b;
3355 * Even for large object >= PAGE_SIZE, the vmstat data will still be
3356 * cached locally at least once before pushing it out.
3363 if (abs(*bytes) > PAGE_SIZE) {
3371 mod_objcg_mlstate(objcg, pgdat, idx, nr);
3373 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3375 obj_cgroup_put(old);
3378 static bool consume_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes)
3380 struct memcg_stock_pcp *stock;
3381 unsigned long flags;
3384 local_lock_irqsave(&memcg_stock.stock_lock, flags);
3386 stock = this_cpu_ptr(&memcg_stock);
3387 if (objcg == READ_ONCE(stock->cached_objcg) && stock->nr_bytes >= nr_bytes) {
3388 stock->nr_bytes -= nr_bytes;
3392 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3397 static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock)
3399 struct obj_cgroup *old = READ_ONCE(stock->cached_objcg);
3404 if (stock->nr_bytes) {
3405 unsigned int nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3406 unsigned int nr_bytes = stock->nr_bytes & (PAGE_SIZE - 1);
3409 struct mem_cgroup *memcg;
3411 memcg = get_mem_cgroup_from_objcg(old);
3413 memcg_account_kmem(memcg, -nr_pages);
3414 __refill_stock(memcg, nr_pages);
3416 css_put(&memcg->css);
3420 * The leftover is flushed to the centralized per-memcg value.
3421 * On the next attempt to refill obj stock it will be moved
3422 * to a per-cpu stock (probably, on an other CPU), see
3423 * refill_obj_stock().
3425 * How often it's flushed is a trade-off between the memory
3426 * limit enforcement accuracy and potential CPU contention,
3427 * so it might be changed in the future.
3429 atomic_add(nr_bytes, &old->nr_charged_bytes);
3430 stock->nr_bytes = 0;
3434 * Flush the vmstat data in current stock
3436 if (stock->nr_slab_reclaimable_b || stock->nr_slab_unreclaimable_b) {
3437 if (stock->nr_slab_reclaimable_b) {
3438 mod_objcg_mlstate(old, stock->cached_pgdat,
3439 NR_SLAB_RECLAIMABLE_B,
3440 stock->nr_slab_reclaimable_b);
3441 stock->nr_slab_reclaimable_b = 0;
3443 if (stock->nr_slab_unreclaimable_b) {
3444 mod_objcg_mlstate(old, stock->cached_pgdat,
3445 NR_SLAB_UNRECLAIMABLE_B,
3446 stock->nr_slab_unreclaimable_b);
3447 stock->nr_slab_unreclaimable_b = 0;
3449 stock->cached_pgdat = NULL;
3452 WRITE_ONCE(stock->cached_objcg, NULL);
3454 * The `old' objects needs to be released by the caller via
3455 * obj_cgroup_put() outside of memcg_stock_pcp::stock_lock.
3460 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
3461 struct mem_cgroup *root_memcg)
3463 struct obj_cgroup *objcg = READ_ONCE(stock->cached_objcg);
3464 struct mem_cgroup *memcg;
3467 memcg = obj_cgroup_memcg(objcg);
3468 if (memcg && mem_cgroup_is_descendant(memcg, root_memcg))
3475 static void refill_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes,
3476 bool allow_uncharge)
3478 struct memcg_stock_pcp *stock;
3479 struct obj_cgroup *old = NULL;
3480 unsigned long flags;
3481 unsigned int nr_pages = 0;
3483 local_lock_irqsave(&memcg_stock.stock_lock, flags);
3485 stock = this_cpu_ptr(&memcg_stock);
3486 if (READ_ONCE(stock->cached_objcg) != objcg) { /* reset if necessary */
3487 old = drain_obj_stock(stock);
3488 obj_cgroup_get(objcg);
3489 WRITE_ONCE(stock->cached_objcg, objcg);
3490 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3491 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3492 allow_uncharge = true; /* Allow uncharge when objcg changes */
3494 stock->nr_bytes += nr_bytes;
3496 if (allow_uncharge && (stock->nr_bytes > PAGE_SIZE)) {
3497 nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3498 stock->nr_bytes &= (PAGE_SIZE - 1);
3501 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3503 obj_cgroup_put(old);
3506 obj_cgroup_uncharge_pages(objcg, nr_pages);
3509 int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size)
3511 unsigned int nr_pages, nr_bytes;
3514 if (consume_obj_stock(objcg, size))
3518 * In theory, objcg->nr_charged_bytes can have enough
3519 * pre-charged bytes to satisfy the allocation. However,
3520 * flushing objcg->nr_charged_bytes requires two atomic
3521 * operations, and objcg->nr_charged_bytes can't be big.
3522 * The shared objcg->nr_charged_bytes can also become a
3523 * performance bottleneck if all tasks of the same memcg are
3524 * trying to update it. So it's better to ignore it and try
3525 * grab some new pages. The stock's nr_bytes will be flushed to
3526 * objcg->nr_charged_bytes later on when objcg changes.
3528 * The stock's nr_bytes may contain enough pre-charged bytes
3529 * to allow one less page from being charged, but we can't rely
3530 * on the pre-charged bytes not being changed outside of
3531 * consume_obj_stock() or refill_obj_stock(). So ignore those
3532 * pre-charged bytes as well when charging pages. To avoid a
3533 * page uncharge right after a page charge, we set the
3534 * allow_uncharge flag to false when calling refill_obj_stock()
3535 * to temporarily allow the pre-charged bytes to exceed the page
3536 * size limit. The maximum reachable value of the pre-charged
3537 * bytes is (sizeof(object) + PAGE_SIZE - 2) if there is no data
3540 nr_pages = size >> PAGE_SHIFT;
3541 nr_bytes = size & (PAGE_SIZE - 1);
3546 ret = obj_cgroup_charge_pages(objcg, gfp, nr_pages);
3547 if (!ret && nr_bytes)
3548 refill_obj_stock(objcg, PAGE_SIZE - nr_bytes, false);
3553 void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size)
3555 refill_obj_stock(objcg, size, true);
3558 #endif /* CONFIG_MEMCG_KMEM */
3561 * Because page_memcg(head) is not set on tails, set it now.
3563 void split_page_memcg(struct page *head, unsigned int nr)
3565 struct folio *folio = page_folio(head);
3566 struct mem_cgroup *memcg = folio_memcg(folio);
3569 if (mem_cgroup_disabled() || !memcg)
3572 for (i = 1; i < nr; i++)
3573 folio_page(folio, i)->memcg_data = folio->memcg_data;
3575 if (folio_memcg_kmem(folio))
3576 obj_cgroup_get_many(__folio_objcg(folio), nr - 1);
3578 css_get_many(&memcg->css, nr - 1);
3583 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3584 * @entry: swap entry to be moved
3585 * @from: mem_cgroup which the entry is moved from
3586 * @to: mem_cgroup which the entry is moved to
3588 * It succeeds only when the swap_cgroup's record for this entry is the same
3589 * as the mem_cgroup's id of @from.
3591 * Returns 0 on success, -EINVAL on failure.
3593 * The caller must have charged to @to, IOW, called page_counter_charge() about
3594 * both res and memsw, and called css_get().
3596 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3597 struct mem_cgroup *from, struct mem_cgroup *to)
3599 unsigned short old_id, new_id;
3601 old_id = mem_cgroup_id(from);
3602 new_id = mem_cgroup_id(to);
3604 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3605 mod_memcg_state(from, MEMCG_SWAP, -1);
3606 mod_memcg_state(to, MEMCG_SWAP, 1);
3612 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3613 struct mem_cgroup *from, struct mem_cgroup *to)
3619 static DEFINE_MUTEX(memcg_max_mutex);
3621 static int mem_cgroup_resize_max(struct mem_cgroup *memcg,
3622 unsigned long max, bool memsw)
3624 bool enlarge = false;
3625 bool drained = false;
3627 bool limits_invariant;
3628 struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory;
3631 if (signal_pending(current)) {
3636 mutex_lock(&memcg_max_mutex);
3638 * Make sure that the new limit (memsw or memory limit) doesn't
3639 * break our basic invariant rule memory.max <= memsw.max.
3641 limits_invariant = memsw ? max >= READ_ONCE(memcg->memory.max) :
3642 max <= memcg->memsw.max;
3643 if (!limits_invariant) {
3644 mutex_unlock(&memcg_max_mutex);
3648 if (max > counter->max)
3650 ret = page_counter_set_max(counter, max);
3651 mutex_unlock(&memcg_max_mutex);
3657 drain_all_stock(memcg);
3662 if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,
3663 memsw ? 0 : MEMCG_RECLAIM_MAY_SWAP)) {
3669 if (!ret && enlarge)
3670 memcg_oom_recover(memcg);
3675 unsigned long mem_cgroup_soft_limit_reclaim(pg_data_t *pgdat, int order,
3677 unsigned long *total_scanned)
3679 unsigned long nr_reclaimed = 0;
3680 struct mem_cgroup_per_node *mz, *next_mz = NULL;
3681 unsigned long reclaimed;
3683 struct mem_cgroup_tree_per_node *mctz;
3684 unsigned long excess;
3686 if (lru_gen_enabled())
3692 mctz = soft_limit_tree.rb_tree_per_node[pgdat->node_id];
3695 * Do not even bother to check the largest node if the root
3696 * is empty. Do it lockless to prevent lock bouncing. Races
3697 * are acceptable as soft limit is best effort anyway.
3699 if (!mctz || RB_EMPTY_ROOT(&mctz->rb_root))
3703 * This loop can run a while, specially if mem_cgroup's continuously
3704 * keep exceeding their soft limit and putting the system under
3711 mz = mem_cgroup_largest_soft_limit_node(mctz);
3715 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, pgdat,
3716 gfp_mask, total_scanned);
3717 nr_reclaimed += reclaimed;
3718 spin_lock_irq(&mctz->lock);
3721 * If we failed to reclaim anything from this memory cgroup
3722 * it is time to move on to the next cgroup
3726 next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
3728 excess = soft_limit_excess(mz->memcg);
3730 * One school of thought says that we should not add
3731 * back the node to the tree if reclaim returns 0.
3732 * But our reclaim could return 0, simply because due
3733 * to priority we are exposing a smaller subset of
3734 * memory to reclaim from. Consider this as a longer
3737 /* If excess == 0, no tree ops */
3738 __mem_cgroup_insert_exceeded(mz, mctz, excess);
3739 spin_unlock_irq(&mctz->lock);
3740 css_put(&mz->memcg->css);
3743 * Could not reclaim anything and there are no more
3744 * mem cgroups to try or we seem to be looping without
3745 * reclaiming anything.
3747 if (!nr_reclaimed &&
3749 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3751 } while (!nr_reclaimed);
3753 css_put(&next_mz->memcg->css);
3754 return nr_reclaimed;
3758 * Reclaims as many pages from the given memcg as possible.
3760 * Caller is responsible for holding css reference for memcg.
3762 static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
3764 int nr_retries = MAX_RECLAIM_RETRIES;
3766 /* we call try-to-free pages for make this cgroup empty */
3767 lru_add_drain_all();
3769 drain_all_stock(memcg);
3771 /* try to free all pages in this cgroup */
3772 while (nr_retries && page_counter_read(&memcg->memory)) {
3773 if (signal_pending(current))
3776 if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,
3777 MEMCG_RECLAIM_MAY_SWAP))
3784 static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
3785 char *buf, size_t nbytes,
3788 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3790 if (mem_cgroup_is_root(memcg))
3792 return mem_cgroup_force_empty(memcg) ?: nbytes;
3795 static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
3801 static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
3802 struct cftype *cft, u64 val)
3807 pr_warn_once("Non-hierarchical mode is deprecated. "
3808 "Please report your usecase to linux-mm@kvack.org if you "
3809 "depend on this functionality.\n");
3814 static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3818 if (mem_cgroup_is_root(memcg)) {
3820 * Approximate root's usage from global state. This isn't
3821 * perfect, but the root usage was always an approximation.
3823 val = global_node_page_state(NR_FILE_PAGES) +
3824 global_node_page_state(NR_ANON_MAPPED);
3826 val += total_swap_pages - get_nr_swap_pages();
3829 val = page_counter_read(&memcg->memory);
3831 val = page_counter_read(&memcg->memsw);
3844 static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
3847 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3848 struct page_counter *counter;
3850 switch (MEMFILE_TYPE(cft->private)) {
3852 counter = &memcg->memory;
3855 counter = &memcg->memsw;
3858 counter = &memcg->kmem;
3861 counter = &memcg->tcpmem;
3867 switch (MEMFILE_ATTR(cft->private)) {
3869 if (counter == &memcg->memory)
3870 return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
3871 if (counter == &memcg->memsw)
3872 return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
3873 return (u64)page_counter_read(counter) * PAGE_SIZE;
3875 return (u64)counter->max * PAGE_SIZE;
3877 return (u64)counter->watermark * PAGE_SIZE;
3879 return counter->failcnt;
3880 case RES_SOFT_LIMIT:
3881 return (u64)READ_ONCE(memcg->soft_limit) * PAGE_SIZE;
3888 * This function doesn't do anything useful. Its only job is to provide a read
3889 * handler for a file so that cgroup_file_mode() will add read permissions.
3891 static int mem_cgroup_dummy_seq_show(__always_unused struct seq_file *m,
3892 __always_unused void *v)
3897 #ifdef CONFIG_MEMCG_KMEM
3898 static int memcg_online_kmem(struct mem_cgroup *memcg)
3900 struct obj_cgroup *objcg;
3902 if (mem_cgroup_kmem_disabled())
3905 if (unlikely(mem_cgroup_is_root(memcg)))
3908 objcg = obj_cgroup_alloc();
3912 objcg->memcg = memcg;
3913 rcu_assign_pointer(memcg->objcg, objcg);
3914 obj_cgroup_get(objcg);
3915 memcg->orig_objcg = objcg;
3917 static_branch_enable(&memcg_kmem_online_key);
3919 memcg->kmemcg_id = memcg->id.id;
3924 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3926 struct mem_cgroup *parent;
3928 if (mem_cgroup_kmem_disabled())
3931 if (unlikely(mem_cgroup_is_root(memcg)))
3934 parent = parent_mem_cgroup(memcg);
3936 parent = root_mem_cgroup;
3938 memcg_reparent_objcgs(memcg, parent);
3941 * After we have finished memcg_reparent_objcgs(), all list_lrus
3942 * corresponding to this cgroup are guaranteed to remain empty.
3943 * The ordering is imposed by list_lru_node->lock taken by
3944 * memcg_reparent_list_lrus().
3946 memcg_reparent_list_lrus(memcg, parent);
3949 static int memcg_online_kmem(struct mem_cgroup *memcg)
3953 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3956 #endif /* CONFIG_MEMCG_KMEM */
3958 static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max)
3962 mutex_lock(&memcg_max_mutex);
3964 ret = page_counter_set_max(&memcg->tcpmem, max);
3968 if (!memcg->tcpmem_active) {
3970 * The active flag needs to be written after the static_key
3971 * update. This is what guarantees that the socket activation
3972 * function is the last one to run. See mem_cgroup_sk_alloc()
3973 * for details, and note that we don't mark any socket as
3974 * belonging to this memcg until that flag is up.
3976 * We need to do this, because static_keys will span multiple
3977 * sites, but we can't control their order. If we mark a socket
3978 * as accounted, but the accounting functions are not patched in
3979 * yet, we'll lose accounting.
3981 * We never race with the readers in mem_cgroup_sk_alloc(),
3982 * because when this value change, the code to process it is not
3985 static_branch_inc(&memcg_sockets_enabled_key);
3986 memcg->tcpmem_active = true;
3989 mutex_unlock(&memcg_max_mutex);
3994 * The user of this function is...
3997 static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
3998 char *buf, size_t nbytes, loff_t off)
4000 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4001 unsigned long nr_pages;
4004 buf = strstrip(buf);
4005 ret = page_counter_memparse(buf, "-1", &nr_pages);
4009 switch (MEMFILE_ATTR(of_cft(of)->private)) {
4011 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
4015 switch (MEMFILE_TYPE(of_cft(of)->private)) {
4017 ret = mem_cgroup_resize_max(memcg, nr_pages, false);
4020 ret = mem_cgroup_resize_max(memcg, nr_pages, true);
4023 pr_warn_once("kmem.limit_in_bytes is deprecated and will be removed. "
4024 "Writing any value to this file has no effect. "
4025 "Please report your usecase to linux-mm@kvack.org if you "
4026 "depend on this functionality.\n");
4030 ret = memcg_update_tcp_max(memcg, nr_pages);
4034 case RES_SOFT_LIMIT:
4035 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
4038 WRITE_ONCE(memcg->soft_limit, nr_pages);
4043 return ret ?: nbytes;
4046 static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
4047 size_t nbytes, loff_t off)
4049 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4050 struct page_counter *counter;
4052 switch (MEMFILE_TYPE(of_cft(of)->private)) {
4054 counter = &memcg->memory;
4057 counter = &memcg->memsw;
4060 counter = &memcg->kmem;
4063 counter = &memcg->tcpmem;
4069 switch (MEMFILE_ATTR(of_cft(of)->private)) {
4071 page_counter_reset_watermark(counter);
4074 counter->failcnt = 0;
4083 static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
4086 return mem_cgroup_from_css(css)->move_charge_at_immigrate;
4090 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
4091 struct cftype *cft, u64 val)
4093 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4095 pr_warn_once("Cgroup memory moving (move_charge_at_immigrate) is deprecated. "
4096 "Please report your usecase to linux-mm@kvack.org if you "
4097 "depend on this functionality.\n");
4099 if (val & ~MOVE_MASK)
4103 * No kind of locking is needed in here, because ->can_attach() will
4104 * check this value once in the beginning of the process, and then carry
4105 * on with stale data. This means that changes to this value will only
4106 * affect task migrations starting after the change.
4108 memcg->move_charge_at_immigrate = val;
4112 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
4113 struct cftype *cft, u64 val)
4121 #define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE))
4122 #define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON))
4123 #define LRU_ALL ((1 << NR_LRU_LISTS) - 1)
4125 static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
4126 int nid, unsigned int lru_mask, bool tree)
4128 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
4129 unsigned long nr = 0;
4132 VM_BUG_ON((unsigned)nid >= nr_node_ids);
4135 if (!(BIT(lru) & lru_mask))
4138 nr += lruvec_page_state(lruvec, NR_LRU_BASE + lru);
4140 nr += lruvec_page_state_local(lruvec, NR_LRU_BASE + lru);
4145 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
4146 unsigned int lru_mask,
4149 unsigned long nr = 0;
4153 if (!(BIT(lru) & lru_mask))
4156 nr += memcg_page_state(memcg, NR_LRU_BASE + lru);
4158 nr += memcg_page_state_local(memcg, NR_LRU_BASE + lru);
4163 static int memcg_numa_stat_show(struct seq_file *m, void *v)
4167 unsigned int lru_mask;
4170 static const struct numa_stat stats[] = {
4171 { "total", LRU_ALL },
4172 { "file", LRU_ALL_FILE },
4173 { "anon", LRU_ALL_ANON },
4174 { "unevictable", BIT(LRU_UNEVICTABLE) },
4176 const struct numa_stat *stat;
4178 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
4180 mem_cgroup_flush_stats();
4182 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
4183 seq_printf(m, "%s=%lu", stat->name,
4184 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
4186 for_each_node_state(nid, N_MEMORY)
4187 seq_printf(m, " N%d=%lu", nid,
4188 mem_cgroup_node_nr_lru_pages(memcg, nid,
4189 stat->lru_mask, false));
4193 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
4195 seq_printf(m, "hierarchical_%s=%lu", stat->name,
4196 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
4198 for_each_node_state(nid, N_MEMORY)
4199 seq_printf(m, " N%d=%lu", nid,
4200 mem_cgroup_node_nr_lru_pages(memcg, nid,
4201 stat->lru_mask, true));
4207 #endif /* CONFIG_NUMA */
4209 static const unsigned int memcg1_stats[] = {
4212 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4219 WORKINGSET_REFAULT_ANON,
4220 WORKINGSET_REFAULT_FILE,
4227 static const char *const memcg1_stat_names[] = {
4230 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4237 "workingset_refault_anon",
4238 "workingset_refault_file",
4245 /* Universal VM events cgroup1 shows, original sort order */
4246 static const unsigned int memcg1_events[] = {
4253 static void memcg1_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
4255 unsigned long memory, memsw;
4256 struct mem_cgroup *mi;
4259 BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats));
4261 mem_cgroup_flush_stats();
4263 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
4266 nr = memcg_page_state_local_output(memcg, memcg1_stats[i]);
4267 seq_buf_printf(s, "%s %lu\n", memcg1_stat_names[i], nr);
4270 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
4271 seq_buf_printf(s, "%s %lu\n", vm_event_name(memcg1_events[i]),
4272 memcg_events_local(memcg, memcg1_events[i]));
4274 for (i = 0; i < NR_LRU_LISTS; i++)
4275 seq_buf_printf(s, "%s %lu\n", lru_list_name(i),
4276 memcg_page_state_local(memcg, NR_LRU_BASE + i) *
4279 /* Hierarchical information */
4280 memory = memsw = PAGE_COUNTER_MAX;
4281 for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
4282 memory = min(memory, READ_ONCE(mi->memory.max));
4283 memsw = min(memsw, READ_ONCE(mi->memsw.max));
4285 seq_buf_printf(s, "hierarchical_memory_limit %llu\n",
4286 (u64)memory * PAGE_SIZE);
4287 seq_buf_printf(s, "hierarchical_memsw_limit %llu\n",
4288 (u64)memsw * PAGE_SIZE);
4290 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
4293 nr = memcg_page_state_output(memcg, memcg1_stats[i]);
4294 seq_buf_printf(s, "total_%s %llu\n", memcg1_stat_names[i],
4298 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
4299 seq_buf_printf(s, "total_%s %llu\n",
4300 vm_event_name(memcg1_events[i]),
4301 (u64)memcg_events(memcg, memcg1_events[i]));
4303 for (i = 0; i < NR_LRU_LISTS; i++)
4304 seq_buf_printf(s, "total_%s %llu\n", lru_list_name(i),
4305 (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
4308 #ifdef CONFIG_DEBUG_VM
4311 struct mem_cgroup_per_node *mz;
4312 unsigned long anon_cost = 0;
4313 unsigned long file_cost = 0;
4315 for_each_online_pgdat(pgdat) {
4316 mz = memcg->nodeinfo[pgdat->node_id];
4318 anon_cost += mz->lruvec.anon_cost;
4319 file_cost += mz->lruvec.file_cost;
4321 seq_buf_printf(s, "anon_cost %lu\n", anon_cost);
4322 seq_buf_printf(s, "file_cost %lu\n", file_cost);
4327 static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
4330 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4332 return mem_cgroup_swappiness(memcg);
4335 static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
4336 struct cftype *cft, u64 val)
4338 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4343 if (!mem_cgroup_is_root(memcg))
4344 WRITE_ONCE(memcg->swappiness, val);
4346 WRITE_ONCE(vm_swappiness, val);
4351 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4353 struct mem_cgroup_threshold_ary *t;
4354 unsigned long usage;
4359 t = rcu_dereference(memcg->thresholds.primary);
4361 t = rcu_dereference(memcg->memsw_thresholds.primary);
4366 usage = mem_cgroup_usage(memcg, swap);
4369 * current_threshold points to threshold just below or equal to usage.
4370 * If it's not true, a threshold was crossed after last
4371 * call of __mem_cgroup_threshold().
4373 i = t->current_threshold;
4376 * Iterate backward over array of thresholds starting from
4377 * current_threshold and check if a threshold is crossed.
4378 * If none of thresholds below usage is crossed, we read
4379 * only one element of the array here.
4381 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4382 eventfd_signal(t->entries[i].eventfd, 1);
4384 /* i = current_threshold + 1 */
4388 * Iterate forward over array of thresholds starting from
4389 * current_threshold+1 and check if a threshold is crossed.
4390 * If none of thresholds above usage is crossed, we read
4391 * only one element of the array here.
4393 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4394 eventfd_signal(t->entries[i].eventfd, 1);
4396 /* Update current_threshold */
4397 t->current_threshold = i - 1;
4402 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4405 __mem_cgroup_threshold(memcg, false);
4406 if (do_memsw_account())
4407 __mem_cgroup_threshold(memcg, true);
4409 memcg = parent_mem_cgroup(memcg);
4413 static int compare_thresholds(const void *a, const void *b)
4415 const struct mem_cgroup_threshold *_a = a;
4416 const struct mem_cgroup_threshold *_b = b;
4418 if (_a->threshold > _b->threshold)
4421 if (_a->threshold < _b->threshold)
4427 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
4429 struct mem_cgroup_eventfd_list *ev;
4431 spin_lock(&memcg_oom_lock);
4433 list_for_each_entry(ev, &memcg->oom_notify, list)
4434 eventfd_signal(ev->eventfd, 1);
4436 spin_unlock(&memcg_oom_lock);
4440 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
4442 struct mem_cgroup *iter;
4444 for_each_mem_cgroup_tree(iter, memcg)
4445 mem_cgroup_oom_notify_cb(iter);
4448 static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4449 struct eventfd_ctx *eventfd, const char *args, enum res_type type)
4451 struct mem_cgroup_thresholds *thresholds;
4452 struct mem_cgroup_threshold_ary *new;
4453 unsigned long threshold;
4454 unsigned long usage;
4457 ret = page_counter_memparse(args, "-1", &threshold);
4461 mutex_lock(&memcg->thresholds_lock);
4464 thresholds = &memcg->thresholds;
4465 usage = mem_cgroup_usage(memcg, false);
4466 } else if (type == _MEMSWAP) {
4467 thresholds = &memcg->memsw_thresholds;
4468 usage = mem_cgroup_usage(memcg, true);
4472 /* Check if a threshold crossed before adding a new one */
4473 if (thresholds->primary)
4474 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4476 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4478 /* Allocate memory for new array of thresholds */
4479 new = kmalloc(struct_size(new, entries, size), GFP_KERNEL);
4486 /* Copy thresholds (if any) to new array */
4487 if (thresholds->primary)
4488 memcpy(new->entries, thresholds->primary->entries,
4489 flex_array_size(new, entries, size - 1));
4491 /* Add new threshold */
4492 new->entries[size - 1].eventfd = eventfd;
4493 new->entries[size - 1].threshold = threshold;
4495 /* Sort thresholds. Registering of new threshold isn't time-critical */
4496 sort(new->entries, size, sizeof(*new->entries),
4497 compare_thresholds, NULL);
4499 /* Find current threshold */
4500 new->current_threshold = -1;
4501 for (i = 0; i < size; i++) {
4502 if (new->entries[i].threshold <= usage) {
4504 * new->current_threshold will not be used until
4505 * rcu_assign_pointer(), so it's safe to increment
4508 ++new->current_threshold;
4513 /* Free old spare buffer and save old primary buffer as spare */
4514 kfree(thresholds->spare);
4515 thresholds->spare = thresholds->primary;
4517 rcu_assign_pointer(thresholds->primary, new);
4519 /* To be sure that nobody uses thresholds */
4523 mutex_unlock(&memcg->thresholds_lock);
4528 static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4529 struct eventfd_ctx *eventfd, const char *args)
4531 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
4534 static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
4535 struct eventfd_ctx *eventfd, const char *args)
4537 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
4540 static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4541 struct eventfd_ctx *eventfd, enum res_type type)
4543 struct mem_cgroup_thresholds *thresholds;
4544 struct mem_cgroup_threshold_ary *new;
4545 unsigned long usage;
4546 int i, j, size, entries;
4548 mutex_lock(&memcg->thresholds_lock);
4551 thresholds = &memcg->thresholds;
4552 usage = mem_cgroup_usage(memcg, false);
4553 } else if (type == _MEMSWAP) {
4554 thresholds = &memcg->memsw_thresholds;
4555 usage = mem_cgroup_usage(memcg, true);
4559 if (!thresholds->primary)
4562 /* Check if a threshold crossed before removing */
4563 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4565 /* Calculate new number of threshold */
4567 for (i = 0; i < thresholds->primary->size; i++) {
4568 if (thresholds->primary->entries[i].eventfd != eventfd)
4574 new = thresholds->spare;
4576 /* If no items related to eventfd have been cleared, nothing to do */
4580 /* Set thresholds array to NULL if we don't have thresholds */
4589 /* Copy thresholds and find current threshold */
4590 new->current_threshold = -1;
4591 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4592 if (thresholds->primary->entries[i].eventfd == eventfd)
4595 new->entries[j] = thresholds->primary->entries[i];
4596 if (new->entries[j].threshold <= usage) {
4598 * new->current_threshold will not be used
4599 * until rcu_assign_pointer(), so it's safe to increment
4602 ++new->current_threshold;
4608 /* Swap primary and spare array */
4609 thresholds->spare = thresholds->primary;
4611 rcu_assign_pointer(thresholds->primary, new);
4613 /* To be sure that nobody uses thresholds */
4616 /* If all events are unregistered, free the spare array */
4618 kfree(thresholds->spare);
4619 thresholds->spare = NULL;
4622 mutex_unlock(&memcg->thresholds_lock);
4625 static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4626 struct eventfd_ctx *eventfd)
4628 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
4631 static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4632 struct eventfd_ctx *eventfd)
4634 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
4637 static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
4638 struct eventfd_ctx *eventfd, const char *args)
4640 struct mem_cgroup_eventfd_list *event;
4642 event = kmalloc(sizeof(*event), GFP_KERNEL);
4646 spin_lock(&memcg_oom_lock);
4648 event->eventfd = eventfd;
4649 list_add(&event->list, &memcg->oom_notify);
4651 /* already in OOM ? */
4652 if (memcg->under_oom)
4653 eventfd_signal(eventfd, 1);
4654 spin_unlock(&memcg_oom_lock);
4659 static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
4660 struct eventfd_ctx *eventfd)
4662 struct mem_cgroup_eventfd_list *ev, *tmp;
4664 spin_lock(&memcg_oom_lock);
4666 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
4667 if (ev->eventfd == eventfd) {
4668 list_del(&ev->list);
4673 spin_unlock(&memcg_oom_lock);
4676 static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
4678 struct mem_cgroup *memcg = mem_cgroup_from_seq(sf);
4680 seq_printf(sf, "oom_kill_disable %d\n", READ_ONCE(memcg->oom_kill_disable));
4681 seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
4682 seq_printf(sf, "oom_kill %lu\n",
4683 atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
4687 static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
4688 struct cftype *cft, u64 val)
4690 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4692 /* cannot set to root cgroup and only 0 and 1 are allowed */
4693 if (mem_cgroup_is_root(memcg) || !((val == 0) || (val == 1)))
4696 WRITE_ONCE(memcg->oom_kill_disable, val);
4698 memcg_oom_recover(memcg);
4703 #ifdef CONFIG_CGROUP_WRITEBACK
4705 #include <trace/events/writeback.h>
4707 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4709 return wb_domain_init(&memcg->cgwb_domain, gfp);
4712 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4714 wb_domain_exit(&memcg->cgwb_domain);
4717 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4719 wb_domain_size_changed(&memcg->cgwb_domain);
4722 struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
4724 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4726 if (!memcg->css.parent)
4729 return &memcg->cgwb_domain;
4733 * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
4734 * @wb: bdi_writeback in question
4735 * @pfilepages: out parameter for number of file pages
4736 * @pheadroom: out parameter for number of allocatable pages according to memcg
4737 * @pdirty: out parameter for number of dirty pages
4738 * @pwriteback: out parameter for number of pages under writeback
4740 * Determine the numbers of file, headroom, dirty, and writeback pages in
4741 * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom
4742 * is a bit more involved.
4744 * A memcg's headroom is "min(max, high) - used". In the hierarchy, the
4745 * headroom is calculated as the lowest headroom of itself and the
4746 * ancestors. Note that this doesn't consider the actual amount of
4747 * available memory in the system. The caller should further cap
4748 * *@pheadroom accordingly.
4750 void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
4751 unsigned long *pheadroom, unsigned long *pdirty,
4752 unsigned long *pwriteback)
4754 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4755 struct mem_cgroup *parent;
4757 mem_cgroup_flush_stats();
4759 *pdirty = memcg_page_state(memcg, NR_FILE_DIRTY);
4760 *pwriteback = memcg_page_state(memcg, NR_WRITEBACK);
4761 *pfilepages = memcg_page_state(memcg, NR_INACTIVE_FILE) +
4762 memcg_page_state(memcg, NR_ACTIVE_FILE);
4764 *pheadroom = PAGE_COUNTER_MAX;
4765 while ((parent = parent_mem_cgroup(memcg))) {
4766 unsigned long ceiling = min(READ_ONCE(memcg->memory.max),
4767 READ_ONCE(memcg->memory.high));
4768 unsigned long used = page_counter_read(&memcg->memory);
4770 *pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
4776 * Foreign dirty flushing
4778 * There's an inherent mismatch between memcg and writeback. The former
4779 * tracks ownership per-page while the latter per-inode. This was a
4780 * deliberate design decision because honoring per-page ownership in the
4781 * writeback path is complicated, may lead to higher CPU and IO overheads
4782 * and deemed unnecessary given that write-sharing an inode across
4783 * different cgroups isn't a common use-case.
4785 * Combined with inode majority-writer ownership switching, this works well
4786 * enough in most cases but there are some pathological cases. For
4787 * example, let's say there are two cgroups A and B which keep writing to
4788 * different but confined parts of the same inode. B owns the inode and
4789 * A's memory is limited far below B's. A's dirty ratio can rise enough to
4790 * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
4791 * triggering background writeback. A will be slowed down without a way to
4792 * make writeback of the dirty pages happen.
4794 * Conditions like the above can lead to a cgroup getting repeatedly and
4795 * severely throttled after making some progress after each
4796 * dirty_expire_interval while the underlying IO device is almost
4799 * Solving this problem completely requires matching the ownership tracking
4800 * granularities between memcg and writeback in either direction. However,
4801 * the more egregious behaviors can be avoided by simply remembering the
4802 * most recent foreign dirtying events and initiating remote flushes on
4803 * them when local writeback isn't enough to keep the memory clean enough.
4805 * The following two functions implement such mechanism. When a foreign
4806 * page - a page whose memcg and writeback ownerships don't match - is
4807 * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
4808 * bdi_writeback on the page owning memcg. When balance_dirty_pages()
4809 * decides that the memcg needs to sleep due to high dirty ratio, it calls
4810 * mem_cgroup_flush_foreign() which queues writeback on the recorded
4811 * foreign bdi_writebacks which haven't expired. Both the numbers of
4812 * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
4813 * limited to MEMCG_CGWB_FRN_CNT.
4815 * The mechanism only remembers IDs and doesn't hold any object references.
4816 * As being wrong occasionally doesn't matter, updates and accesses to the
4817 * records are lockless and racy.
4819 void mem_cgroup_track_foreign_dirty_slowpath(struct folio *folio,
4820 struct bdi_writeback *wb)
4822 struct mem_cgroup *memcg = folio_memcg(folio);
4823 struct memcg_cgwb_frn *frn;
4824 u64 now = get_jiffies_64();
4825 u64 oldest_at = now;
4829 trace_track_foreign_dirty(folio, wb);
4832 * Pick the slot to use. If there is already a slot for @wb, keep
4833 * using it. If not replace the oldest one which isn't being
4836 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4837 frn = &memcg->cgwb_frn[i];
4838 if (frn->bdi_id == wb->bdi->id &&
4839 frn->memcg_id == wb->memcg_css->id)
4841 if (time_before64(frn->at, oldest_at) &&
4842 atomic_read(&frn->done.cnt) == 1) {
4844 oldest_at = frn->at;
4848 if (i < MEMCG_CGWB_FRN_CNT) {
4850 * Re-using an existing one. Update timestamp lazily to
4851 * avoid making the cacheline hot. We want them to be
4852 * reasonably up-to-date and significantly shorter than
4853 * dirty_expire_interval as that's what expires the record.
4854 * Use the shorter of 1s and dirty_expire_interval / 8.
4856 unsigned long update_intv =
4857 min_t(unsigned long, HZ,
4858 msecs_to_jiffies(dirty_expire_interval * 10) / 8);
4860 if (time_before64(frn->at, now - update_intv))
4862 } else if (oldest >= 0) {
4863 /* replace the oldest free one */
4864 frn = &memcg->cgwb_frn[oldest];
4865 frn->bdi_id = wb->bdi->id;
4866 frn->memcg_id = wb->memcg_css->id;
4871 /* issue foreign writeback flushes for recorded foreign dirtying events */
4872 void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
4874 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4875 unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
4876 u64 now = jiffies_64;
4879 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4880 struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
4883 * If the record is older than dirty_expire_interval,
4884 * writeback on it has already started. No need to kick it
4885 * off again. Also, don't start a new one if there's
4886 * already one in flight.
4888 if (time_after64(frn->at, now - intv) &&
4889 atomic_read(&frn->done.cnt) == 1) {
4891 trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
4892 cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id,
4893 WB_REASON_FOREIGN_FLUSH,
4899 #else /* CONFIG_CGROUP_WRITEBACK */
4901 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4906 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4910 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4914 #endif /* CONFIG_CGROUP_WRITEBACK */
4917 * DO NOT USE IN NEW FILES.
4919 * "cgroup.event_control" implementation.
4921 * This is way over-engineered. It tries to support fully configurable
4922 * events for each user. Such level of flexibility is completely
4923 * unnecessary especially in the light of the planned unified hierarchy.
4925 * Please deprecate this and replace with something simpler if at all
4930 * Unregister event and free resources.
4932 * Gets called from workqueue.
4934 static void memcg_event_remove(struct work_struct *work)
4936 struct mem_cgroup_event *event =
4937 container_of(work, struct mem_cgroup_event, remove);
4938 struct mem_cgroup *memcg = event->memcg;
4940 remove_wait_queue(event->wqh, &event->wait);
4942 event->unregister_event(memcg, event->eventfd);
4944 /* Notify userspace the event is going away. */
4945 eventfd_signal(event->eventfd, 1);
4947 eventfd_ctx_put(event->eventfd);
4949 css_put(&memcg->css);
4953 * Gets called on EPOLLHUP on eventfd when user closes it.
4955 * Called with wqh->lock held and interrupts disabled.
4957 static int memcg_event_wake(wait_queue_entry_t *wait, unsigned mode,
4958 int sync, void *key)
4960 struct mem_cgroup_event *event =
4961 container_of(wait, struct mem_cgroup_event, wait);
4962 struct mem_cgroup *memcg = event->memcg;
4963 __poll_t flags = key_to_poll(key);
4965 if (flags & EPOLLHUP) {
4967 * If the event has been detached at cgroup removal, we
4968 * can simply return knowing the other side will cleanup
4971 * We can't race against event freeing since the other
4972 * side will require wqh->lock via remove_wait_queue(),
4975 spin_lock(&memcg->event_list_lock);
4976 if (!list_empty(&event->list)) {
4977 list_del_init(&event->list);
4979 * We are in atomic context, but cgroup_event_remove()
4980 * may sleep, so we have to call it in workqueue.
4982 schedule_work(&event->remove);
4984 spin_unlock(&memcg->event_list_lock);
4990 static void memcg_event_ptable_queue_proc(struct file *file,
4991 wait_queue_head_t *wqh, poll_table *pt)
4993 struct mem_cgroup_event *event =
4994 container_of(pt, struct mem_cgroup_event, pt);
4997 add_wait_queue(wqh, &event->wait);
5001 * DO NOT USE IN NEW FILES.
5003 * Parse input and register new cgroup event handler.
5005 * Input must be in format '<event_fd> <control_fd> <args>'.
5006 * Interpretation of args is defined by control file implementation.
5008 static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
5009 char *buf, size_t nbytes, loff_t off)
5011 struct cgroup_subsys_state *css = of_css(of);
5012 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5013 struct mem_cgroup_event *event;
5014 struct cgroup_subsys_state *cfile_css;
5015 unsigned int efd, cfd;
5018 struct dentry *cdentry;
5023 if (IS_ENABLED(CONFIG_PREEMPT_RT))
5026 buf = strstrip(buf);
5028 efd = simple_strtoul(buf, &endp, 10);
5033 cfd = simple_strtoul(buf, &endp, 10);
5034 if ((*endp != ' ') && (*endp != '\0'))
5038 event = kzalloc(sizeof(*event), GFP_KERNEL);
5042 event->memcg = memcg;
5043 INIT_LIST_HEAD(&event->list);
5044 init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
5045 init_waitqueue_func_entry(&event->wait, memcg_event_wake);
5046 INIT_WORK(&event->remove, memcg_event_remove);
5054 event->eventfd = eventfd_ctx_fileget(efile.file);
5055 if (IS_ERR(event->eventfd)) {
5056 ret = PTR_ERR(event->eventfd);
5063 goto out_put_eventfd;
5066 /* the process need read permission on control file */
5067 /* AV: shouldn't we check that it's been opened for read instead? */
5068 ret = file_permission(cfile.file, MAY_READ);
5073 * The control file must be a regular cgroup1 file. As a regular cgroup
5074 * file can't be renamed, it's safe to access its name afterwards.
5076 cdentry = cfile.file->f_path.dentry;
5077 if (cdentry->d_sb->s_type != &cgroup_fs_type || !d_is_reg(cdentry)) {
5083 * Determine the event callbacks and set them in @event. This used
5084 * to be done via struct cftype but cgroup core no longer knows
5085 * about these events. The following is crude but the whole thing
5086 * is for compatibility anyway.
5088 * DO NOT ADD NEW FILES.
5090 name = cdentry->d_name.name;
5092 if (!strcmp(name, "memory.usage_in_bytes")) {
5093 event->register_event = mem_cgroup_usage_register_event;
5094 event->unregister_event = mem_cgroup_usage_unregister_event;
5095 } else if (!strcmp(name, "memory.oom_control")) {
5096 event->register_event = mem_cgroup_oom_register_event;
5097 event->unregister_event = mem_cgroup_oom_unregister_event;
5098 } else if (!strcmp(name, "memory.pressure_level")) {
5099 event->register_event = vmpressure_register_event;
5100 event->unregister_event = vmpressure_unregister_event;
5101 } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
5102 event->register_event = memsw_cgroup_usage_register_event;
5103 event->unregister_event = memsw_cgroup_usage_unregister_event;
5110 * Verify @cfile should belong to @css. Also, remaining events are
5111 * automatically removed on cgroup destruction but the removal is
5112 * asynchronous, so take an extra ref on @css.
5114 cfile_css = css_tryget_online_from_dir(cdentry->d_parent,
5115 &memory_cgrp_subsys);
5117 if (IS_ERR(cfile_css))
5119 if (cfile_css != css) {
5124 ret = event->register_event(memcg, event->eventfd, buf);
5128 vfs_poll(efile.file, &event->pt);
5130 spin_lock_irq(&memcg->event_list_lock);
5131 list_add(&event->list, &memcg->event_list);
5132 spin_unlock_irq(&memcg->event_list_lock);
5144 eventfd_ctx_put(event->eventfd);
5153 #if defined(CONFIG_MEMCG_KMEM) && (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG))
5154 static int mem_cgroup_slab_show(struct seq_file *m, void *p)
5158 * Please, take a look at tools/cgroup/memcg_slabinfo.py .
5164 static int memory_stat_show(struct seq_file *m, void *v);
5166 static struct cftype mem_cgroup_legacy_files[] = {
5168 .name = "usage_in_bytes",
5169 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
5170 .read_u64 = mem_cgroup_read_u64,
5173 .name = "max_usage_in_bytes",
5174 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
5175 .write = mem_cgroup_reset,
5176 .read_u64 = mem_cgroup_read_u64,
5179 .name = "limit_in_bytes",
5180 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
5181 .write = mem_cgroup_write,
5182 .read_u64 = mem_cgroup_read_u64,
5185 .name = "soft_limit_in_bytes",
5186 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
5187 .write = mem_cgroup_write,
5188 .read_u64 = mem_cgroup_read_u64,
5192 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
5193 .write = mem_cgroup_reset,
5194 .read_u64 = mem_cgroup_read_u64,
5198 .seq_show = memory_stat_show,
5201 .name = "force_empty",
5202 .write = mem_cgroup_force_empty_write,
5205 .name = "use_hierarchy",
5206 .write_u64 = mem_cgroup_hierarchy_write,
5207 .read_u64 = mem_cgroup_hierarchy_read,
5210 .name = "cgroup.event_control", /* XXX: for compat */
5211 .write = memcg_write_event_control,
5212 .flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE,
5215 .name = "swappiness",
5216 .read_u64 = mem_cgroup_swappiness_read,
5217 .write_u64 = mem_cgroup_swappiness_write,
5220 .name = "move_charge_at_immigrate",
5221 .read_u64 = mem_cgroup_move_charge_read,
5222 .write_u64 = mem_cgroup_move_charge_write,
5225 .name = "oom_control",
5226 .seq_show = mem_cgroup_oom_control_read,
5227 .write_u64 = mem_cgroup_oom_control_write,
5230 .name = "pressure_level",
5231 .seq_show = mem_cgroup_dummy_seq_show,
5235 .name = "numa_stat",
5236 .seq_show = memcg_numa_stat_show,
5240 .name = "kmem.limit_in_bytes",
5241 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
5242 .write = mem_cgroup_write,
5243 .read_u64 = mem_cgroup_read_u64,
5246 .name = "kmem.usage_in_bytes",
5247 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
5248 .read_u64 = mem_cgroup_read_u64,
5251 .name = "kmem.failcnt",
5252 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
5253 .write = mem_cgroup_reset,
5254 .read_u64 = mem_cgroup_read_u64,
5257 .name = "kmem.max_usage_in_bytes",
5258 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
5259 .write = mem_cgroup_reset,
5260 .read_u64 = mem_cgroup_read_u64,
5262 #if defined(CONFIG_MEMCG_KMEM) && \
5263 (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG))
5265 .name = "kmem.slabinfo",
5266 .seq_show = mem_cgroup_slab_show,
5270 .name = "kmem.tcp.limit_in_bytes",
5271 .private = MEMFILE_PRIVATE(_TCP, RES_LIMIT),
5272 .write = mem_cgroup_write,
5273 .read_u64 = mem_cgroup_read_u64,
5276 .name = "kmem.tcp.usage_in_bytes",
5277 .private = MEMFILE_PRIVATE(_TCP, RES_USAGE),
5278 .read_u64 = mem_cgroup_read_u64,
5281 .name = "kmem.tcp.failcnt",
5282 .private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT),
5283 .write = mem_cgroup_reset,
5284 .read_u64 = mem_cgroup_read_u64,
5287 .name = "kmem.tcp.max_usage_in_bytes",
5288 .private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE),
5289 .write = mem_cgroup_reset,
5290 .read_u64 = mem_cgroup_read_u64,
5292 { }, /* terminate */
5296 * Private memory cgroup IDR
5298 * Swap-out records and page cache shadow entries need to store memcg
5299 * references in constrained space, so we maintain an ID space that is
5300 * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
5301 * memory-controlled cgroups to 64k.
5303 * However, there usually are many references to the offline CSS after
5304 * the cgroup has been destroyed, such as page cache or reclaimable
5305 * slab objects, that don't need to hang on to the ID. We want to keep
5306 * those dead CSS from occupying IDs, or we might quickly exhaust the
5307 * relatively small ID space and prevent the creation of new cgroups
5308 * even when there are much fewer than 64k cgroups - possibly none.
5310 * Maintain a private 16-bit ID space for memcg, and allow the ID to
5311 * be freed and recycled when it's no longer needed, which is usually
5312 * when the CSS is offlined.
5314 * The only exception to that are records of swapped out tmpfs/shmem
5315 * pages that need to be attributed to live ancestors on swapin. But
5316 * those references are manageable from userspace.
5319 #define MEM_CGROUP_ID_MAX ((1UL << MEM_CGROUP_ID_SHIFT) - 1)
5320 static DEFINE_IDR(mem_cgroup_idr);
5322 static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
5324 if (memcg->id.id > 0) {
5325 idr_remove(&mem_cgroup_idr, memcg->id.id);
5330 static void __maybe_unused mem_cgroup_id_get_many(struct mem_cgroup *memcg,
5333 refcount_add(n, &memcg->id.ref);
5336 static void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
5338 if (refcount_sub_and_test(n, &memcg->id.ref)) {
5339 mem_cgroup_id_remove(memcg);
5341 /* Memcg ID pins CSS */
5342 css_put(&memcg->css);
5346 static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
5348 mem_cgroup_id_put_many(memcg, 1);
5352 * mem_cgroup_from_id - look up a memcg from a memcg id
5353 * @id: the memcg id to look up
5355 * Caller must hold rcu_read_lock().
5357 struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
5359 WARN_ON_ONCE(!rcu_read_lock_held());
5360 return idr_find(&mem_cgroup_idr, id);
5363 #ifdef CONFIG_SHRINKER_DEBUG
5364 struct mem_cgroup *mem_cgroup_get_from_ino(unsigned long ino)
5366 struct cgroup *cgrp;
5367 struct cgroup_subsys_state *css;
5368 struct mem_cgroup *memcg;
5370 cgrp = cgroup_get_from_id(ino);
5372 return ERR_CAST(cgrp);
5374 css = cgroup_get_e_css(cgrp, &memory_cgrp_subsys);
5376 memcg = container_of(css, struct mem_cgroup, css);
5378 memcg = ERR_PTR(-ENOENT);
5386 static int alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5388 struct mem_cgroup_per_node *pn;
5390 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, node);
5394 pn->lruvec_stats_percpu = alloc_percpu_gfp(struct lruvec_stats_percpu,
5395 GFP_KERNEL_ACCOUNT);
5396 if (!pn->lruvec_stats_percpu) {
5401 lruvec_init(&pn->lruvec);
5404 memcg->nodeinfo[node] = pn;
5408 static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5410 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
5415 free_percpu(pn->lruvec_stats_percpu);
5419 static void __mem_cgroup_free(struct mem_cgroup *memcg)
5423 if (memcg->orig_objcg)
5424 obj_cgroup_put(memcg->orig_objcg);
5427 free_mem_cgroup_per_node_info(memcg, node);
5428 kfree(memcg->vmstats);
5429 free_percpu(memcg->vmstats_percpu);
5433 static void mem_cgroup_free(struct mem_cgroup *memcg)
5435 lru_gen_exit_memcg(memcg);
5436 memcg_wb_domain_exit(memcg);
5437 __mem_cgroup_free(memcg);
5440 static struct mem_cgroup *mem_cgroup_alloc(void)
5442 struct mem_cgroup *memcg;
5444 int __maybe_unused i;
5445 long error = -ENOMEM;
5447 memcg = kzalloc(struct_size(memcg, nodeinfo, nr_node_ids), GFP_KERNEL);
5449 return ERR_PTR(error);
5451 memcg->id.id = idr_alloc(&mem_cgroup_idr, NULL,
5452 1, MEM_CGROUP_ID_MAX + 1, GFP_KERNEL);
5453 if (memcg->id.id < 0) {
5454 error = memcg->id.id;
5458 memcg->vmstats = kzalloc(sizeof(struct memcg_vmstats), GFP_KERNEL);
5459 if (!memcg->vmstats)
5462 memcg->vmstats_percpu = alloc_percpu_gfp(struct memcg_vmstats_percpu,
5463 GFP_KERNEL_ACCOUNT);
5464 if (!memcg->vmstats_percpu)
5468 if (alloc_mem_cgroup_per_node_info(memcg, node))
5471 if (memcg_wb_domain_init(memcg, GFP_KERNEL))
5474 INIT_WORK(&memcg->high_work, high_work_func);
5475 INIT_LIST_HEAD(&memcg->oom_notify);
5476 mutex_init(&memcg->thresholds_lock);
5477 spin_lock_init(&memcg->move_lock);
5478 vmpressure_init(&memcg->vmpressure);
5479 INIT_LIST_HEAD(&memcg->event_list);
5480 spin_lock_init(&memcg->event_list_lock);
5481 memcg->socket_pressure = jiffies;
5482 #ifdef CONFIG_MEMCG_KMEM
5483 memcg->kmemcg_id = -1;
5484 INIT_LIST_HEAD(&memcg->objcg_list);
5486 #ifdef CONFIG_CGROUP_WRITEBACK
5487 INIT_LIST_HEAD(&memcg->cgwb_list);
5488 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5489 memcg->cgwb_frn[i].done =
5490 __WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
5492 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5493 spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
5494 INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
5495 memcg->deferred_split_queue.split_queue_len = 0;
5497 lru_gen_init_memcg(memcg);
5500 mem_cgroup_id_remove(memcg);
5501 __mem_cgroup_free(memcg);
5502 return ERR_PTR(error);
5505 static struct cgroup_subsys_state * __ref
5506 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
5508 struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
5509 struct mem_cgroup *memcg, *old_memcg;
5511 old_memcg = set_active_memcg(parent);
5512 memcg = mem_cgroup_alloc();
5513 set_active_memcg(old_memcg);
5515 return ERR_CAST(memcg);
5517 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5518 WRITE_ONCE(memcg->soft_limit, PAGE_COUNTER_MAX);
5519 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
5520 memcg->zswap_max = PAGE_COUNTER_MAX;
5522 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5524 WRITE_ONCE(memcg->swappiness, mem_cgroup_swappiness(parent));
5525 WRITE_ONCE(memcg->oom_kill_disable, READ_ONCE(parent->oom_kill_disable));
5527 page_counter_init(&memcg->memory, &parent->memory);
5528 page_counter_init(&memcg->swap, &parent->swap);
5529 page_counter_init(&memcg->kmem, &parent->kmem);
5530 page_counter_init(&memcg->tcpmem, &parent->tcpmem);
5532 init_memcg_events();
5533 page_counter_init(&memcg->memory, NULL);
5534 page_counter_init(&memcg->swap, NULL);
5535 page_counter_init(&memcg->kmem, NULL);
5536 page_counter_init(&memcg->tcpmem, NULL);
5538 root_mem_cgroup = memcg;
5542 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5543 static_branch_inc(&memcg_sockets_enabled_key);
5545 #if defined(CONFIG_MEMCG_KMEM)
5546 if (!cgroup_memory_nobpf)
5547 static_branch_inc(&memcg_bpf_enabled_key);
5553 static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
5555 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5557 if (memcg_online_kmem(memcg))
5561 * A memcg must be visible for expand_shrinker_info()
5562 * by the time the maps are allocated. So, we allocate maps
5563 * here, when for_each_mem_cgroup() can't skip it.
5565 if (alloc_shrinker_info(memcg))
5568 if (unlikely(mem_cgroup_is_root(memcg)))
5569 queue_delayed_work(system_unbound_wq, &stats_flush_dwork,
5571 lru_gen_online_memcg(memcg);
5573 /* Online state pins memcg ID, memcg ID pins CSS */
5574 refcount_set(&memcg->id.ref, 1);
5578 * Ensure mem_cgroup_from_id() works once we're fully online.
5580 * We could do this earlier and require callers to filter with
5581 * css_tryget_online(). But right now there are no users that
5582 * need earlier access, and the workingset code relies on the
5583 * cgroup tree linkage (mem_cgroup_get_nr_swap_pages()). So
5584 * publish it here at the end of onlining. This matches the
5585 * regular ID destruction during offlining.
5587 idr_replace(&mem_cgroup_idr, memcg, memcg->id.id);
5591 memcg_offline_kmem(memcg);
5593 mem_cgroup_id_remove(memcg);
5597 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
5599 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5600 struct mem_cgroup_event *event, *tmp;
5603 * Unregister events and notify userspace.
5604 * Notify userspace about cgroup removing only after rmdir of cgroup
5605 * directory to avoid race between userspace and kernelspace.
5607 spin_lock_irq(&memcg->event_list_lock);
5608 list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
5609 list_del_init(&event->list);
5610 schedule_work(&event->remove);
5612 spin_unlock_irq(&memcg->event_list_lock);
5614 page_counter_set_min(&memcg->memory, 0);
5615 page_counter_set_low(&memcg->memory, 0);
5617 memcg_offline_kmem(memcg);
5618 reparent_shrinker_deferred(memcg);
5619 wb_memcg_offline(memcg);
5620 lru_gen_offline_memcg(memcg);
5622 drain_all_stock(memcg);
5624 mem_cgroup_id_put(memcg);
5627 static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
5629 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5631 invalidate_reclaim_iterators(memcg);
5632 lru_gen_release_memcg(memcg);
5635 static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
5637 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5638 int __maybe_unused i;
5640 #ifdef CONFIG_CGROUP_WRITEBACK
5641 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5642 wb_wait_for_completion(&memcg->cgwb_frn[i].done);
5644 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5645 static_branch_dec(&memcg_sockets_enabled_key);
5647 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg->tcpmem_active)
5648 static_branch_dec(&memcg_sockets_enabled_key);
5650 #if defined(CONFIG_MEMCG_KMEM)
5651 if (!cgroup_memory_nobpf)
5652 static_branch_dec(&memcg_bpf_enabled_key);
5655 vmpressure_cleanup(&memcg->vmpressure);
5656 cancel_work_sync(&memcg->high_work);
5657 mem_cgroup_remove_from_trees(memcg);
5658 free_shrinker_info(memcg);
5659 mem_cgroup_free(memcg);
5663 * mem_cgroup_css_reset - reset the states of a mem_cgroup
5664 * @css: the target css
5666 * Reset the states of the mem_cgroup associated with @css. This is
5667 * invoked when the userland requests disabling on the default hierarchy
5668 * but the memcg is pinned through dependency. The memcg should stop
5669 * applying policies and should revert to the vanilla state as it may be
5670 * made visible again.
5672 * The current implementation only resets the essential configurations.
5673 * This needs to be expanded to cover all the visible parts.
5675 static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
5677 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5679 page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
5680 page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
5681 page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
5682 page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
5683 page_counter_set_min(&memcg->memory, 0);
5684 page_counter_set_low(&memcg->memory, 0);
5685 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5686 WRITE_ONCE(memcg->soft_limit, PAGE_COUNTER_MAX);
5687 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5688 memcg_wb_domain_size_changed(memcg);
5691 static void mem_cgroup_css_rstat_flush(struct cgroup_subsys_state *css, int cpu)
5693 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5694 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
5695 struct memcg_vmstats_percpu *statc;
5696 long delta, delta_cpu, v;
5699 statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
5701 for (i = 0; i < MEMCG_NR_STAT; i++) {
5703 * Collect the aggregated propagation counts of groups
5704 * below us. We're in a per-cpu loop here and this is
5705 * a global counter, so the first cycle will get them.
5707 delta = memcg->vmstats->state_pending[i];
5709 memcg->vmstats->state_pending[i] = 0;
5711 /* Add CPU changes on this level since the last flush */
5713 v = READ_ONCE(statc->state[i]);
5714 if (v != statc->state_prev[i]) {
5715 delta_cpu = v - statc->state_prev[i];
5717 statc->state_prev[i] = v;
5720 /* Aggregate counts on this level and propagate upwards */
5722 memcg->vmstats->state_local[i] += delta_cpu;
5725 memcg->vmstats->state[i] += delta;
5727 parent->vmstats->state_pending[i] += delta;
5731 for (i = 0; i < NR_MEMCG_EVENTS; i++) {
5732 delta = memcg->vmstats->events_pending[i];
5734 memcg->vmstats->events_pending[i] = 0;
5737 v = READ_ONCE(statc->events[i]);
5738 if (v != statc->events_prev[i]) {
5739 delta_cpu = v - statc->events_prev[i];
5741 statc->events_prev[i] = v;
5745 memcg->vmstats->events_local[i] += delta_cpu;
5748 memcg->vmstats->events[i] += delta;
5750 parent->vmstats->events_pending[i] += delta;
5754 for_each_node_state(nid, N_MEMORY) {
5755 struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
5756 struct mem_cgroup_per_node *ppn = NULL;
5757 struct lruvec_stats_percpu *lstatc;
5760 ppn = parent->nodeinfo[nid];
5762 lstatc = per_cpu_ptr(pn->lruvec_stats_percpu, cpu);
5764 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++) {
5765 delta = pn->lruvec_stats.state_pending[i];
5767 pn->lruvec_stats.state_pending[i] = 0;
5770 v = READ_ONCE(lstatc->state[i]);
5771 if (v != lstatc->state_prev[i]) {
5772 delta_cpu = v - lstatc->state_prev[i];
5774 lstatc->state_prev[i] = v;
5778 pn->lruvec_stats.state_local[i] += delta_cpu;
5781 pn->lruvec_stats.state[i] += delta;
5783 ppn->lruvec_stats.state_pending[i] += delta;
5790 /* Handlers for move charge at task migration. */
5791 static int mem_cgroup_do_precharge(unsigned long count)
5795 /* Try a single bulk charge without reclaim first, kswapd may wake */
5796 ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count);
5798 mc.precharge += count;
5802 /* Try charges one by one with reclaim, but do not retry */
5804 ret = try_charge(mc.to, GFP_KERNEL | __GFP_NORETRY, 1);
5818 enum mc_target_type {
5825 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5826 unsigned long addr, pte_t ptent)
5828 struct page *page = vm_normal_page(vma, addr, ptent);
5832 if (PageAnon(page)) {
5833 if (!(mc.flags & MOVE_ANON))
5836 if (!(mc.flags & MOVE_FILE))
5844 #if defined(CONFIG_SWAP) || defined(CONFIG_DEVICE_PRIVATE)
5845 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5846 pte_t ptent, swp_entry_t *entry)
5848 struct page *page = NULL;
5849 swp_entry_t ent = pte_to_swp_entry(ptent);
5851 if (!(mc.flags & MOVE_ANON))
5855 * Handle device private pages that are not accessible by the CPU, but
5856 * stored as special swap entries in the page table.
5858 if (is_device_private_entry(ent)) {
5859 page = pfn_swap_entry_to_page(ent);
5860 if (!get_page_unless_zero(page))
5865 if (non_swap_entry(ent))
5869 * Because swap_cache_get_folio() updates some statistics counter,
5870 * we call find_get_page() with swapper_space directly.
5872 page = find_get_page(swap_address_space(ent), swp_offset(ent));
5873 entry->val = ent.val;
5878 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5879 pte_t ptent, swp_entry_t *entry)
5885 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5886 unsigned long addr, pte_t ptent)
5888 unsigned long index;
5889 struct folio *folio;
5891 if (!vma->vm_file) /* anonymous vma */
5893 if (!(mc.flags & MOVE_FILE))
5896 /* folio is moved even if it's not RSS of this task(page-faulted). */
5897 /* shmem/tmpfs may report page out on swap: account for that too. */
5898 index = linear_page_index(vma, addr);
5899 folio = filemap_get_incore_folio(vma->vm_file->f_mapping, index);
5902 return folio_file_page(folio, index);
5906 * mem_cgroup_move_account - move account of the page
5908 * @compound: charge the page as compound or small page
5909 * @from: mem_cgroup which the page is moved from.
5910 * @to: mem_cgroup which the page is moved to. @from != @to.
5912 * The page must be locked and not on the LRU.
5914 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
5917 static int mem_cgroup_move_account(struct page *page,
5919 struct mem_cgroup *from,
5920 struct mem_cgroup *to)
5922 struct folio *folio = page_folio(page);
5923 struct lruvec *from_vec, *to_vec;
5924 struct pglist_data *pgdat;
5925 unsigned int nr_pages = compound ? folio_nr_pages(folio) : 1;
5928 VM_BUG_ON(from == to);
5929 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
5930 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
5931 VM_BUG_ON(compound && !folio_test_large(folio));
5934 if (folio_memcg(folio) != from)
5937 pgdat = folio_pgdat(folio);
5938 from_vec = mem_cgroup_lruvec(from, pgdat);
5939 to_vec = mem_cgroup_lruvec(to, pgdat);
5941 folio_memcg_lock(folio);
5943 if (folio_test_anon(folio)) {
5944 if (folio_mapped(folio)) {
5945 __mod_lruvec_state(from_vec, NR_ANON_MAPPED, -nr_pages);
5946 __mod_lruvec_state(to_vec, NR_ANON_MAPPED, nr_pages);
5947 if (folio_test_pmd_mappable(folio)) {
5948 __mod_lruvec_state(from_vec, NR_ANON_THPS,
5950 __mod_lruvec_state(to_vec, NR_ANON_THPS,
5955 __mod_lruvec_state(from_vec, NR_FILE_PAGES, -nr_pages);
5956 __mod_lruvec_state(to_vec, NR_FILE_PAGES, nr_pages);
5958 if (folio_test_swapbacked(folio)) {
5959 __mod_lruvec_state(from_vec, NR_SHMEM, -nr_pages);
5960 __mod_lruvec_state(to_vec, NR_SHMEM, nr_pages);
5963 if (folio_mapped(folio)) {
5964 __mod_lruvec_state(from_vec, NR_FILE_MAPPED, -nr_pages);
5965 __mod_lruvec_state(to_vec, NR_FILE_MAPPED, nr_pages);
5968 if (folio_test_dirty(folio)) {
5969 struct address_space *mapping = folio_mapping(folio);
5971 if (mapping_can_writeback(mapping)) {
5972 __mod_lruvec_state(from_vec, NR_FILE_DIRTY,
5974 __mod_lruvec_state(to_vec, NR_FILE_DIRTY,
5981 if (folio_test_swapcache(folio)) {
5982 __mod_lruvec_state(from_vec, NR_SWAPCACHE, -nr_pages);
5983 __mod_lruvec_state(to_vec, NR_SWAPCACHE, nr_pages);
5986 if (folio_test_writeback(folio)) {
5987 __mod_lruvec_state(from_vec, NR_WRITEBACK, -nr_pages);
5988 __mod_lruvec_state(to_vec, NR_WRITEBACK, nr_pages);
5992 * All state has been migrated, let's switch to the new memcg.
5994 * It is safe to change page's memcg here because the page
5995 * is referenced, charged, isolated, and locked: we can't race
5996 * with (un)charging, migration, LRU putback, or anything else
5997 * that would rely on a stable page's memory cgroup.
5999 * Note that folio_memcg_lock is a memcg lock, not a page lock,
6000 * to save space. As soon as we switch page's memory cgroup to a
6001 * new memcg that isn't locked, the above state can change
6002 * concurrently again. Make sure we're truly done with it.
6007 css_put(&from->css);
6009 folio->memcg_data = (unsigned long)to;
6011 __folio_memcg_unlock(from);
6014 nid = folio_nid(folio);
6016 local_irq_disable();
6017 mem_cgroup_charge_statistics(to, nr_pages);
6018 memcg_check_events(to, nid);
6019 mem_cgroup_charge_statistics(from, -nr_pages);
6020 memcg_check_events(from, nid);
6027 * get_mctgt_type - get target type of moving charge
6028 * @vma: the vma the pte to be checked belongs
6029 * @addr: the address corresponding to the pte to be checked
6030 * @ptent: the pte to be checked
6031 * @target: the pointer the target page or swap ent will be stored(can be NULL)
6033 * Context: Called with pte lock held.
6035 * * MC_TARGET_NONE - If the pte is not a target for move charge.
6036 * * MC_TARGET_PAGE - If the page corresponding to this pte is a target for
6037 * move charge. If @target is not NULL, the page is stored in target->page
6038 * with extra refcnt taken (Caller should release it).
6039 * * MC_TARGET_SWAP - If the swap entry corresponding to this pte is a
6040 * target for charge migration. If @target is not NULL, the entry is
6041 * stored in target->ent.
6042 * * MC_TARGET_DEVICE - Like MC_TARGET_PAGE but page is device memory and
6043 * thus not on the lru. For now such page is charged like a regular page
6044 * would be as it is just special memory taking the place of a regular page.
6045 * See Documentations/vm/hmm.txt and include/linux/hmm.h
6047 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
6048 unsigned long addr, pte_t ptent, union mc_target *target)
6050 struct page *page = NULL;
6051 enum mc_target_type ret = MC_TARGET_NONE;
6052 swp_entry_t ent = { .val = 0 };
6054 if (pte_present(ptent))
6055 page = mc_handle_present_pte(vma, addr, ptent);
6056 else if (pte_none_mostly(ptent))
6058 * PTE markers should be treated as a none pte here, separated
6059 * from other swap handling below.
6061 page = mc_handle_file_pte(vma, addr, ptent);
6062 else if (is_swap_pte(ptent))
6063 page = mc_handle_swap_pte(vma, ptent, &ent);
6065 if (target && page) {
6066 if (!trylock_page(page)) {
6071 * page_mapped() must be stable during the move. This
6072 * pte is locked, so if it's present, the page cannot
6073 * become unmapped. If it isn't, we have only partial
6074 * control over the mapped state: the page lock will
6075 * prevent new faults against pagecache and swapcache,
6076 * so an unmapped page cannot become mapped. However,
6077 * if the page is already mapped elsewhere, it can
6078 * unmap, and there is nothing we can do about it.
6079 * Alas, skip moving the page in this case.
6081 if (!pte_present(ptent) && page_mapped(page)) {
6088 if (!page && !ent.val)
6092 * Do only loose check w/o serialization.
6093 * mem_cgroup_move_account() checks the page is valid or
6094 * not under LRU exclusion.
6096 if (page_memcg(page) == mc.from) {
6097 ret = MC_TARGET_PAGE;
6098 if (is_device_private_page(page) ||
6099 is_device_coherent_page(page))
6100 ret = MC_TARGET_DEVICE;
6102 target->page = page;
6104 if (!ret || !target) {
6111 * There is a swap entry and a page doesn't exist or isn't charged.
6112 * But we cannot move a tail-page in a THP.
6114 if (ent.val && !ret && (!page || !PageTransCompound(page)) &&
6115 mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
6116 ret = MC_TARGET_SWAP;
6123 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
6125 * We don't consider PMD mapped swapping or file mapped pages because THP does
6126 * not support them for now.
6127 * Caller should make sure that pmd_trans_huge(pmd) is true.
6129 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
6130 unsigned long addr, pmd_t pmd, union mc_target *target)
6132 struct page *page = NULL;
6133 enum mc_target_type ret = MC_TARGET_NONE;
6135 if (unlikely(is_swap_pmd(pmd))) {
6136 VM_BUG_ON(thp_migration_supported() &&
6137 !is_pmd_migration_entry(pmd));
6140 page = pmd_page(pmd);
6141 VM_BUG_ON_PAGE(!page || !PageHead(page), page);
6142 if (!(mc.flags & MOVE_ANON))
6144 if (page_memcg(page) == mc.from) {
6145 ret = MC_TARGET_PAGE;
6148 if (!trylock_page(page)) {
6150 return MC_TARGET_NONE;
6152 target->page = page;
6158 static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
6159 unsigned long addr, pmd_t pmd, union mc_target *target)
6161 return MC_TARGET_NONE;
6165 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
6166 unsigned long addr, unsigned long end,
6167 struct mm_walk *walk)
6169 struct vm_area_struct *vma = walk->vma;
6173 ptl = pmd_trans_huge_lock(pmd, vma);
6176 * Note their can not be MC_TARGET_DEVICE for now as we do not
6177 * support transparent huge page with MEMORY_DEVICE_PRIVATE but
6178 * this might change.
6180 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
6181 mc.precharge += HPAGE_PMD_NR;
6186 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6189 for (; addr != end; pte++, addr += PAGE_SIZE)
6190 if (get_mctgt_type(vma, addr, ptep_get(pte), NULL))
6191 mc.precharge++; /* increment precharge temporarily */
6192 pte_unmap_unlock(pte - 1, ptl);
6198 static const struct mm_walk_ops precharge_walk_ops = {
6199 .pmd_entry = mem_cgroup_count_precharge_pte_range,
6200 .walk_lock = PGWALK_RDLOCK,
6203 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
6205 unsigned long precharge;
6208 walk_page_range(mm, 0, ULONG_MAX, &precharge_walk_ops, NULL);
6209 mmap_read_unlock(mm);
6211 precharge = mc.precharge;
6217 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
6219 unsigned long precharge = mem_cgroup_count_precharge(mm);
6221 VM_BUG_ON(mc.moving_task);
6222 mc.moving_task = current;
6223 return mem_cgroup_do_precharge(precharge);
6226 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
6227 static void __mem_cgroup_clear_mc(void)
6229 struct mem_cgroup *from = mc.from;
6230 struct mem_cgroup *to = mc.to;
6232 /* we must uncharge all the leftover precharges from mc.to */
6234 mem_cgroup_cancel_charge(mc.to, mc.precharge);
6238 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
6239 * we must uncharge here.
6241 if (mc.moved_charge) {
6242 mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
6243 mc.moved_charge = 0;
6245 /* we must fixup refcnts and charges */
6246 if (mc.moved_swap) {
6247 /* uncharge swap account from the old cgroup */
6248 if (!mem_cgroup_is_root(mc.from))
6249 page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
6251 mem_cgroup_id_put_many(mc.from, mc.moved_swap);
6254 * we charged both to->memory and to->memsw, so we
6255 * should uncharge to->memory.
6257 if (!mem_cgroup_is_root(mc.to))
6258 page_counter_uncharge(&mc.to->memory, mc.moved_swap);
6262 memcg_oom_recover(from);
6263 memcg_oom_recover(to);
6264 wake_up_all(&mc.waitq);
6267 static void mem_cgroup_clear_mc(void)
6269 struct mm_struct *mm = mc.mm;
6272 * we must clear moving_task before waking up waiters at the end of
6275 mc.moving_task = NULL;
6276 __mem_cgroup_clear_mc();
6277 spin_lock(&mc.lock);
6281 spin_unlock(&mc.lock);
6286 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
6288 struct cgroup_subsys_state *css;
6289 struct mem_cgroup *memcg = NULL; /* unneeded init to make gcc happy */
6290 struct mem_cgroup *from;
6291 struct task_struct *leader, *p;
6292 struct mm_struct *mm;
6293 unsigned long move_flags;
6296 /* charge immigration isn't supported on the default hierarchy */
6297 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
6301 * Multi-process migrations only happen on the default hierarchy
6302 * where charge immigration is not used. Perform charge
6303 * immigration if @tset contains a leader and whine if there are
6307 cgroup_taskset_for_each_leader(leader, css, tset) {
6310 memcg = mem_cgroup_from_css(css);
6316 * We are now committed to this value whatever it is. Changes in this
6317 * tunable will only affect upcoming migrations, not the current one.
6318 * So we need to save it, and keep it going.
6320 move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
6324 from = mem_cgroup_from_task(p);
6326 VM_BUG_ON(from == memcg);
6328 mm = get_task_mm(p);
6331 /* We move charges only when we move a owner of the mm */
6332 if (mm->owner == p) {
6335 VM_BUG_ON(mc.precharge);
6336 VM_BUG_ON(mc.moved_charge);
6337 VM_BUG_ON(mc.moved_swap);
6339 spin_lock(&mc.lock);
6343 mc.flags = move_flags;
6344 spin_unlock(&mc.lock);
6345 /* We set mc.moving_task later */
6347 ret = mem_cgroup_precharge_mc(mm);
6349 mem_cgroup_clear_mc();
6356 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6359 mem_cgroup_clear_mc();
6362 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
6363 unsigned long addr, unsigned long end,
6364 struct mm_walk *walk)
6367 struct vm_area_struct *vma = walk->vma;
6370 enum mc_target_type target_type;
6371 union mc_target target;
6374 ptl = pmd_trans_huge_lock(pmd, vma);
6376 if (mc.precharge < HPAGE_PMD_NR) {
6380 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
6381 if (target_type == MC_TARGET_PAGE) {
6383 if (isolate_lru_page(page)) {
6384 if (!mem_cgroup_move_account(page, true,
6386 mc.precharge -= HPAGE_PMD_NR;
6387 mc.moved_charge += HPAGE_PMD_NR;
6389 putback_lru_page(page);
6393 } else if (target_type == MC_TARGET_DEVICE) {
6395 if (!mem_cgroup_move_account(page, true,
6397 mc.precharge -= HPAGE_PMD_NR;
6398 mc.moved_charge += HPAGE_PMD_NR;
6408 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6411 for (; addr != end; addr += PAGE_SIZE) {
6412 pte_t ptent = ptep_get(pte++);
6413 bool device = false;
6419 switch (get_mctgt_type(vma, addr, ptent, &target)) {
6420 case MC_TARGET_DEVICE:
6423 case MC_TARGET_PAGE:
6426 * We can have a part of the split pmd here. Moving it
6427 * can be done but it would be too convoluted so simply
6428 * ignore such a partial THP and keep it in original
6429 * memcg. There should be somebody mapping the head.
6431 if (PageTransCompound(page))
6433 if (!device && !isolate_lru_page(page))
6435 if (!mem_cgroup_move_account(page, false,
6438 /* we uncharge from mc.from later. */
6442 putback_lru_page(page);
6443 put: /* get_mctgt_type() gets & locks the page */
6447 case MC_TARGET_SWAP:
6449 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
6451 mem_cgroup_id_get_many(mc.to, 1);
6452 /* we fixup other refcnts and charges later. */
6460 pte_unmap_unlock(pte - 1, ptl);
6465 * We have consumed all precharges we got in can_attach().
6466 * We try charge one by one, but don't do any additional
6467 * charges to mc.to if we have failed in charge once in attach()
6470 ret = mem_cgroup_do_precharge(1);
6478 static const struct mm_walk_ops charge_walk_ops = {
6479 .pmd_entry = mem_cgroup_move_charge_pte_range,
6480 .walk_lock = PGWALK_RDLOCK,
6483 static void mem_cgroup_move_charge(void)
6485 lru_add_drain_all();
6487 * Signal folio_memcg_lock() to take the memcg's move_lock
6488 * while we're moving its pages to another memcg. Then wait
6489 * for already started RCU-only updates to finish.
6491 atomic_inc(&mc.from->moving_account);
6494 if (unlikely(!mmap_read_trylock(mc.mm))) {
6496 * Someone who are holding the mmap_lock might be waiting in
6497 * waitq. So we cancel all extra charges, wake up all waiters,
6498 * and retry. Because we cancel precharges, we might not be able
6499 * to move enough charges, but moving charge is a best-effort
6500 * feature anyway, so it wouldn't be a big problem.
6502 __mem_cgroup_clear_mc();
6507 * When we have consumed all precharges and failed in doing
6508 * additional charge, the page walk just aborts.
6510 walk_page_range(mc.mm, 0, ULONG_MAX, &charge_walk_ops, NULL);
6511 mmap_read_unlock(mc.mm);
6512 atomic_dec(&mc.from->moving_account);
6515 static void mem_cgroup_move_task(void)
6518 mem_cgroup_move_charge();
6519 mem_cgroup_clear_mc();
6523 #else /* !CONFIG_MMU */
6524 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
6528 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6531 static void mem_cgroup_move_task(void)
6536 #ifdef CONFIG_MEMCG_KMEM
6537 static void mem_cgroup_fork(struct task_struct *task)
6540 * Set the update flag to cause task->objcg to be initialized lazily
6541 * on the first allocation. It can be done without any synchronization
6542 * because it's always performed on the current task, so does
6543 * current_objcg_update().
6545 task->objcg = (struct obj_cgroup *)CURRENT_OBJCG_UPDATE_FLAG;
6548 static void mem_cgroup_exit(struct task_struct *task)
6550 struct obj_cgroup *objcg = task->objcg;
6552 objcg = (struct obj_cgroup *)
6553 ((unsigned long)objcg & ~CURRENT_OBJCG_UPDATE_FLAG);
6555 obj_cgroup_put(objcg);
6558 * Some kernel allocations can happen after this point,
6559 * but let's ignore them. It can be done without any synchronization
6560 * because it's always performed on the current task, so does
6561 * current_objcg_update().
6567 #ifdef CONFIG_LRU_GEN
6568 static void mem_cgroup_lru_gen_attach(struct cgroup_taskset *tset)
6570 struct task_struct *task;
6571 struct cgroup_subsys_state *css;
6573 /* find the first leader if there is any */
6574 cgroup_taskset_for_each_leader(task, css, tset)
6581 if (task->mm && READ_ONCE(task->mm->owner) == task)
6582 lru_gen_migrate_mm(task->mm);
6586 static void mem_cgroup_lru_gen_attach(struct cgroup_taskset *tset) {}
6587 #endif /* CONFIG_LRU_GEN */
6589 #ifdef CONFIG_MEMCG_KMEM
6590 static void mem_cgroup_kmem_attach(struct cgroup_taskset *tset)
6592 struct task_struct *task;
6593 struct cgroup_subsys_state *css;
6595 cgroup_taskset_for_each(task, css, tset) {
6596 /* atomically set the update bit */
6597 set_bit(CURRENT_OBJCG_UPDATE_BIT, (unsigned long *)&task->objcg);
6601 static void mem_cgroup_kmem_attach(struct cgroup_taskset *tset) {}
6602 #endif /* CONFIG_MEMCG_KMEM */
6604 #if defined(CONFIG_LRU_GEN) || defined(CONFIG_MEMCG_KMEM)
6605 static void mem_cgroup_attach(struct cgroup_taskset *tset)
6607 mem_cgroup_lru_gen_attach(tset);
6608 mem_cgroup_kmem_attach(tset);
6612 static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
6614 if (value == PAGE_COUNTER_MAX)
6615 seq_puts(m, "max\n");
6617 seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
6622 static u64 memory_current_read(struct cgroup_subsys_state *css,
6625 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6627 return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
6630 static u64 memory_peak_read(struct cgroup_subsys_state *css,
6633 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6635 return (u64)memcg->memory.watermark * PAGE_SIZE;
6638 static int memory_min_show(struct seq_file *m, void *v)
6640 return seq_puts_memcg_tunable(m,
6641 READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
6644 static ssize_t memory_min_write(struct kernfs_open_file *of,
6645 char *buf, size_t nbytes, loff_t off)
6647 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6651 buf = strstrip(buf);
6652 err = page_counter_memparse(buf, "max", &min);
6656 page_counter_set_min(&memcg->memory, min);
6661 static int memory_low_show(struct seq_file *m, void *v)
6663 return seq_puts_memcg_tunable(m,
6664 READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
6667 static ssize_t memory_low_write(struct kernfs_open_file *of,
6668 char *buf, size_t nbytes, loff_t off)
6670 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6674 buf = strstrip(buf);
6675 err = page_counter_memparse(buf, "max", &low);
6679 page_counter_set_low(&memcg->memory, low);
6684 static int memory_high_show(struct seq_file *m, void *v)
6686 return seq_puts_memcg_tunable(m,
6687 READ_ONCE(mem_cgroup_from_seq(m)->memory.high));
6690 static ssize_t memory_high_write(struct kernfs_open_file *of,
6691 char *buf, size_t nbytes, loff_t off)
6693 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6694 unsigned int nr_retries = MAX_RECLAIM_RETRIES;
6695 bool drained = false;
6699 buf = strstrip(buf);
6700 err = page_counter_memparse(buf, "max", &high);
6704 page_counter_set_high(&memcg->memory, high);
6707 unsigned long nr_pages = page_counter_read(&memcg->memory);
6708 unsigned long reclaimed;
6710 if (nr_pages <= high)
6713 if (signal_pending(current))
6717 drain_all_stock(memcg);
6722 reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
6723 GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP);
6725 if (!reclaimed && !nr_retries--)
6729 memcg_wb_domain_size_changed(memcg);
6733 static int memory_max_show(struct seq_file *m, void *v)
6735 return seq_puts_memcg_tunable(m,
6736 READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
6739 static ssize_t memory_max_write(struct kernfs_open_file *of,
6740 char *buf, size_t nbytes, loff_t off)
6742 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6743 unsigned int nr_reclaims = MAX_RECLAIM_RETRIES;
6744 bool drained = false;
6748 buf = strstrip(buf);
6749 err = page_counter_memparse(buf, "max", &max);
6753 xchg(&memcg->memory.max, max);
6756 unsigned long nr_pages = page_counter_read(&memcg->memory);
6758 if (nr_pages <= max)
6761 if (signal_pending(current))
6765 drain_all_stock(memcg);
6771 if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
6772 GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP))
6777 memcg_memory_event(memcg, MEMCG_OOM);
6778 if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
6782 memcg_wb_domain_size_changed(memcg);
6786 static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
6788 seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
6789 seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
6790 seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
6791 seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
6792 seq_printf(m, "oom_kill %lu\n",
6793 atomic_long_read(&events[MEMCG_OOM_KILL]));
6794 seq_printf(m, "oom_group_kill %lu\n",
6795 atomic_long_read(&events[MEMCG_OOM_GROUP_KILL]));
6798 static int memory_events_show(struct seq_file *m, void *v)
6800 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6802 __memory_events_show(m, memcg->memory_events);
6806 static int memory_events_local_show(struct seq_file *m, void *v)
6808 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6810 __memory_events_show(m, memcg->memory_events_local);
6814 static int memory_stat_show(struct seq_file *m, void *v)
6816 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6817 char *buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
6822 seq_buf_init(&s, buf, PAGE_SIZE);
6823 memory_stat_format(memcg, &s);
6830 static inline unsigned long lruvec_page_state_output(struct lruvec *lruvec,
6833 return lruvec_page_state(lruvec, item) *
6834 memcg_page_state_output_unit(item);
6837 static int memory_numa_stat_show(struct seq_file *m, void *v)
6840 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6842 mem_cgroup_flush_stats();
6844 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
6847 if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS)
6850 seq_printf(m, "%s", memory_stats[i].name);
6851 for_each_node_state(nid, N_MEMORY) {
6853 struct lruvec *lruvec;
6855 lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
6856 size = lruvec_page_state_output(lruvec,
6857 memory_stats[i].idx);
6858 seq_printf(m, " N%d=%llu", nid, size);
6867 static int memory_oom_group_show(struct seq_file *m, void *v)
6869 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6871 seq_printf(m, "%d\n", READ_ONCE(memcg->oom_group));
6876 static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
6877 char *buf, size_t nbytes, loff_t off)
6879 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6882 buf = strstrip(buf);
6886 ret = kstrtoint(buf, 0, &oom_group);
6890 if (oom_group != 0 && oom_group != 1)
6893 WRITE_ONCE(memcg->oom_group, oom_group);
6898 static ssize_t memory_reclaim(struct kernfs_open_file *of, char *buf,
6899 size_t nbytes, loff_t off)
6901 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6902 unsigned int nr_retries = MAX_RECLAIM_RETRIES;
6903 unsigned long nr_to_reclaim, nr_reclaimed = 0;
6904 unsigned int reclaim_options;
6907 buf = strstrip(buf);
6908 err = page_counter_memparse(buf, "", &nr_to_reclaim);
6912 reclaim_options = MEMCG_RECLAIM_MAY_SWAP | MEMCG_RECLAIM_PROACTIVE;
6913 while (nr_reclaimed < nr_to_reclaim) {
6914 unsigned long reclaimed;
6916 if (signal_pending(current))
6920 * This is the final attempt, drain percpu lru caches in the
6921 * hope of introducing more evictable pages for
6922 * try_to_free_mem_cgroup_pages().
6925 lru_add_drain_all();
6927 reclaimed = try_to_free_mem_cgroup_pages(memcg,
6928 min(nr_to_reclaim - nr_reclaimed, SWAP_CLUSTER_MAX),
6929 GFP_KERNEL, reclaim_options);
6931 if (!reclaimed && !nr_retries--)
6934 nr_reclaimed += reclaimed;
6940 static struct cftype memory_files[] = {
6943 .flags = CFTYPE_NOT_ON_ROOT,
6944 .read_u64 = memory_current_read,
6948 .flags = CFTYPE_NOT_ON_ROOT,
6949 .read_u64 = memory_peak_read,
6953 .flags = CFTYPE_NOT_ON_ROOT,
6954 .seq_show = memory_min_show,
6955 .write = memory_min_write,
6959 .flags = CFTYPE_NOT_ON_ROOT,
6960 .seq_show = memory_low_show,
6961 .write = memory_low_write,
6965 .flags = CFTYPE_NOT_ON_ROOT,
6966 .seq_show = memory_high_show,
6967 .write = memory_high_write,
6971 .flags = CFTYPE_NOT_ON_ROOT,
6972 .seq_show = memory_max_show,
6973 .write = memory_max_write,
6977 .flags = CFTYPE_NOT_ON_ROOT,
6978 .file_offset = offsetof(struct mem_cgroup, events_file),
6979 .seq_show = memory_events_show,
6982 .name = "events.local",
6983 .flags = CFTYPE_NOT_ON_ROOT,
6984 .file_offset = offsetof(struct mem_cgroup, events_local_file),
6985 .seq_show = memory_events_local_show,
6989 .seq_show = memory_stat_show,
6993 .name = "numa_stat",
6994 .seq_show = memory_numa_stat_show,
6998 .name = "oom.group",
6999 .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
7000 .seq_show = memory_oom_group_show,
7001 .write = memory_oom_group_write,
7005 .flags = CFTYPE_NS_DELEGATABLE,
7006 .write = memory_reclaim,
7011 struct cgroup_subsys memory_cgrp_subsys = {
7012 .css_alloc = mem_cgroup_css_alloc,
7013 .css_online = mem_cgroup_css_online,
7014 .css_offline = mem_cgroup_css_offline,
7015 .css_released = mem_cgroup_css_released,
7016 .css_free = mem_cgroup_css_free,
7017 .css_reset = mem_cgroup_css_reset,
7018 .css_rstat_flush = mem_cgroup_css_rstat_flush,
7019 .can_attach = mem_cgroup_can_attach,
7020 #if defined(CONFIG_LRU_GEN) || defined(CONFIG_MEMCG_KMEM)
7021 .attach = mem_cgroup_attach,
7023 .cancel_attach = mem_cgroup_cancel_attach,
7024 .post_attach = mem_cgroup_move_task,
7025 #ifdef CONFIG_MEMCG_KMEM
7026 .fork = mem_cgroup_fork,
7027 .exit = mem_cgroup_exit,
7029 .dfl_cftypes = memory_files,
7030 .legacy_cftypes = mem_cgroup_legacy_files,
7035 * This function calculates an individual cgroup's effective
7036 * protection which is derived from its own memory.min/low, its
7037 * parent's and siblings' settings, as well as the actual memory
7038 * distribution in the tree.
7040 * The following rules apply to the effective protection values:
7042 * 1. At the first level of reclaim, effective protection is equal to
7043 * the declared protection in memory.min and memory.low.
7045 * 2. To enable safe delegation of the protection configuration, at
7046 * subsequent levels the effective protection is capped to the
7047 * parent's effective protection.
7049 * 3. To make complex and dynamic subtrees easier to configure, the
7050 * user is allowed to overcommit the declared protection at a given
7051 * level. If that is the case, the parent's effective protection is
7052 * distributed to the children in proportion to how much protection
7053 * they have declared and how much of it they are utilizing.
7055 * This makes distribution proportional, but also work-conserving:
7056 * if one cgroup claims much more protection than it uses memory,
7057 * the unused remainder is available to its siblings.
7059 * 4. Conversely, when the declared protection is undercommitted at a
7060 * given level, the distribution of the larger parental protection
7061 * budget is NOT proportional. A cgroup's protection from a sibling
7062 * is capped to its own memory.min/low setting.
7064 * 5. However, to allow protecting recursive subtrees from each other
7065 * without having to declare each individual cgroup's fixed share
7066 * of the ancestor's claim to protection, any unutilized -
7067 * "floating" - protection from up the tree is distributed in
7068 * proportion to each cgroup's *usage*. This makes the protection
7069 * neutral wrt sibling cgroups and lets them compete freely over
7070 * the shared parental protection budget, but it protects the
7071 * subtree as a whole from neighboring subtrees.
7073 * Note that 4. and 5. are not in conflict: 4. is about protecting
7074 * against immediate siblings whereas 5. is about protecting against
7075 * neighboring subtrees.
7077 static unsigned long effective_protection(unsigned long usage,
7078 unsigned long parent_usage,
7079 unsigned long setting,
7080 unsigned long parent_effective,
7081 unsigned long siblings_protected)
7083 unsigned long protected;
7086 protected = min(usage, setting);
7088 * If all cgroups at this level combined claim and use more
7089 * protection than what the parent affords them, distribute
7090 * shares in proportion to utilization.
7092 * We are using actual utilization rather than the statically
7093 * claimed protection in order to be work-conserving: claimed
7094 * but unused protection is available to siblings that would
7095 * otherwise get a smaller chunk than what they claimed.
7097 if (siblings_protected > parent_effective)
7098 return protected * parent_effective / siblings_protected;
7101 * Ok, utilized protection of all children is within what the
7102 * parent affords them, so we know whatever this child claims
7103 * and utilizes is effectively protected.
7105 * If there is unprotected usage beyond this value, reclaim
7106 * will apply pressure in proportion to that amount.
7108 * If there is unutilized protection, the cgroup will be fully
7109 * shielded from reclaim, but we do return a smaller value for
7110 * protection than what the group could enjoy in theory. This
7111 * is okay. With the overcommit distribution above, effective
7112 * protection is always dependent on how memory is actually
7113 * consumed among the siblings anyway.
7118 * If the children aren't claiming (all of) the protection
7119 * afforded to them by the parent, distribute the remainder in
7120 * proportion to the (unprotected) memory of each cgroup. That
7121 * way, cgroups that aren't explicitly prioritized wrt each
7122 * other compete freely over the allowance, but they are
7123 * collectively protected from neighboring trees.
7125 * We're using unprotected memory for the weight so that if
7126 * some cgroups DO claim explicit protection, we don't protect
7127 * the same bytes twice.
7129 * Check both usage and parent_usage against the respective
7130 * protected values. One should imply the other, but they
7131 * aren't read atomically - make sure the division is sane.
7133 if (!(cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT))
7135 if (parent_effective > siblings_protected &&
7136 parent_usage > siblings_protected &&
7137 usage > protected) {
7138 unsigned long unclaimed;
7140 unclaimed = parent_effective - siblings_protected;
7141 unclaimed *= usage - protected;
7142 unclaimed /= parent_usage - siblings_protected;
7151 * mem_cgroup_calculate_protection - check if memory consumption is in the normal range
7152 * @root: the top ancestor of the sub-tree being checked
7153 * @memcg: the memory cgroup to check
7155 * WARNING: This function is not stateless! It can only be used as part
7156 * of a top-down tree iteration, not for isolated queries.
7158 void mem_cgroup_calculate_protection(struct mem_cgroup *root,
7159 struct mem_cgroup *memcg)
7161 unsigned long usage, parent_usage;
7162 struct mem_cgroup *parent;
7164 if (mem_cgroup_disabled())
7168 root = root_mem_cgroup;
7171 * Effective values of the reclaim targets are ignored so they
7172 * can be stale. Have a look at mem_cgroup_protection for more
7174 * TODO: calculation should be more robust so that we do not need
7175 * that special casing.
7180 usage = page_counter_read(&memcg->memory);
7184 parent = parent_mem_cgroup(memcg);
7186 if (parent == root) {
7187 memcg->memory.emin = READ_ONCE(memcg->memory.min);
7188 memcg->memory.elow = READ_ONCE(memcg->memory.low);
7192 parent_usage = page_counter_read(&parent->memory);
7194 WRITE_ONCE(memcg->memory.emin, effective_protection(usage, parent_usage,
7195 READ_ONCE(memcg->memory.min),
7196 READ_ONCE(parent->memory.emin),
7197 atomic_long_read(&parent->memory.children_min_usage)));
7199 WRITE_ONCE(memcg->memory.elow, effective_protection(usage, parent_usage,
7200 READ_ONCE(memcg->memory.low),
7201 READ_ONCE(parent->memory.elow),
7202 atomic_long_read(&parent->memory.children_low_usage)));
7205 static int charge_memcg(struct folio *folio, struct mem_cgroup *memcg,
7210 ret = try_charge(memcg, gfp, folio_nr_pages(folio));
7214 mem_cgroup_commit_charge(folio, memcg);
7219 int __mem_cgroup_charge(struct folio *folio, struct mm_struct *mm, gfp_t gfp)
7221 struct mem_cgroup *memcg;
7224 memcg = get_mem_cgroup_from_mm(mm);
7225 ret = charge_memcg(folio, memcg, gfp);
7226 css_put(&memcg->css);
7232 * mem_cgroup_hugetlb_try_charge - try to charge the memcg for a hugetlb folio
7233 * @memcg: memcg to charge.
7234 * @gfp: reclaim mode.
7235 * @nr_pages: number of pages to charge.
7237 * This function is called when allocating a huge page folio to determine if
7238 * the memcg has the capacity for it. It does not commit the charge yet,
7239 * as the hugetlb folio itself has not been obtained from the hugetlb pool.
7241 * Once we have obtained the hugetlb folio, we can call
7242 * mem_cgroup_commit_charge() to commit the charge. If we fail to obtain the
7243 * folio, we should instead call mem_cgroup_cancel_charge() to undo the effect
7246 * Returns 0 on success. Otherwise, an error code is returned.
7248 int mem_cgroup_hugetlb_try_charge(struct mem_cgroup *memcg, gfp_t gfp,
7252 * If hugetlb memcg charging is not enabled, do not fail hugetlb allocation,
7253 * but do not attempt to commit charge later (or cancel on error) either.
7255 if (mem_cgroup_disabled() || !memcg ||
7256 !cgroup_subsys_on_dfl(memory_cgrp_subsys) ||
7257 !(cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_HUGETLB_ACCOUNTING))
7260 if (try_charge(memcg, gfp, nr_pages))
7267 * mem_cgroup_swapin_charge_folio - Charge a newly allocated folio for swapin.
7268 * @folio: folio to charge.
7269 * @mm: mm context of the victim
7270 * @gfp: reclaim mode
7271 * @entry: swap entry for which the folio is allocated
7273 * This function charges a folio allocated for swapin. Please call this before
7274 * adding the folio to the swapcache.
7276 * Returns 0 on success. Otherwise, an error code is returned.
7278 int mem_cgroup_swapin_charge_folio(struct folio *folio, struct mm_struct *mm,
7279 gfp_t gfp, swp_entry_t entry)
7281 struct mem_cgroup *memcg;
7285 if (mem_cgroup_disabled())
7288 id = lookup_swap_cgroup_id(entry);
7290 memcg = mem_cgroup_from_id(id);
7291 if (!memcg || !css_tryget_online(&memcg->css))
7292 memcg = get_mem_cgroup_from_mm(mm);
7295 ret = charge_memcg(folio, memcg, gfp);
7297 css_put(&memcg->css);
7302 * mem_cgroup_swapin_uncharge_swap - uncharge swap slot
7303 * @entry: swap entry for which the page is charged
7305 * Call this function after successfully adding the charged page to swapcache.
7307 * Note: This function assumes the page for which swap slot is being uncharged
7310 void mem_cgroup_swapin_uncharge_swap(swp_entry_t entry)
7313 * Cgroup1's unified memory+swap counter has been charged with the
7314 * new swapcache page, finish the transfer by uncharging the swap
7315 * slot. The swap slot would also get uncharged when it dies, but
7316 * it can stick around indefinitely and we'd count the page twice
7319 * Cgroup2 has separate resource counters for memory and swap,
7320 * so this is a non-issue here. Memory and swap charge lifetimes
7321 * correspond 1:1 to page and swap slot lifetimes: we charge the
7322 * page to memory here, and uncharge swap when the slot is freed.
7324 if (!mem_cgroup_disabled() && do_memsw_account()) {
7326 * The swap entry might not get freed for a long time,
7327 * let's not wait for it. The page already received a
7328 * memory+swap charge, drop the swap entry duplicate.
7330 mem_cgroup_uncharge_swap(entry, 1);
7334 struct uncharge_gather {
7335 struct mem_cgroup *memcg;
7336 unsigned long nr_memory;
7337 unsigned long pgpgout;
7338 unsigned long nr_kmem;
7342 static inline void uncharge_gather_clear(struct uncharge_gather *ug)
7344 memset(ug, 0, sizeof(*ug));
7347 static void uncharge_batch(const struct uncharge_gather *ug)
7349 unsigned long flags;
7351 if (ug->nr_memory) {
7352 page_counter_uncharge(&ug->memcg->memory, ug->nr_memory);
7353 if (do_memsw_account())
7354 page_counter_uncharge(&ug->memcg->memsw, ug->nr_memory);
7356 memcg_account_kmem(ug->memcg, -ug->nr_kmem);
7357 memcg_oom_recover(ug->memcg);
7360 local_irq_save(flags);
7361 __count_memcg_events(ug->memcg, PGPGOUT, ug->pgpgout);
7362 __this_cpu_add(ug->memcg->vmstats_percpu->nr_page_events, ug->nr_memory);
7363 memcg_check_events(ug->memcg, ug->nid);
7364 local_irq_restore(flags);
7366 /* drop reference from uncharge_folio */
7367 css_put(&ug->memcg->css);
7370 static void uncharge_folio(struct folio *folio, struct uncharge_gather *ug)
7373 struct mem_cgroup *memcg;
7374 struct obj_cgroup *objcg;
7376 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
7379 * Nobody should be changing or seriously looking at
7380 * folio memcg or objcg at this point, we have fully
7381 * exclusive access to the folio.
7383 if (folio_memcg_kmem(folio)) {
7384 objcg = __folio_objcg(folio);
7386 * This get matches the put at the end of the function and
7387 * kmem pages do not hold memcg references anymore.
7389 memcg = get_mem_cgroup_from_objcg(objcg);
7391 memcg = __folio_memcg(folio);
7397 if (ug->memcg != memcg) {
7400 uncharge_gather_clear(ug);
7403 ug->nid = folio_nid(folio);
7405 /* pairs with css_put in uncharge_batch */
7406 css_get(&memcg->css);
7409 nr_pages = folio_nr_pages(folio);
7411 if (folio_memcg_kmem(folio)) {
7412 ug->nr_memory += nr_pages;
7413 ug->nr_kmem += nr_pages;
7415 folio->memcg_data = 0;
7416 obj_cgroup_put(objcg);
7418 /* LRU pages aren't accounted at the root level */
7419 if (!mem_cgroup_is_root(memcg))
7420 ug->nr_memory += nr_pages;
7423 folio->memcg_data = 0;
7426 css_put(&memcg->css);
7429 void __mem_cgroup_uncharge(struct folio *folio)
7431 struct uncharge_gather ug;
7433 /* Don't touch folio->lru of any random page, pre-check: */
7434 if (!folio_memcg(folio))
7437 uncharge_gather_clear(&ug);
7438 uncharge_folio(folio, &ug);
7439 uncharge_batch(&ug);
7443 * __mem_cgroup_uncharge_list - uncharge a list of page
7444 * @page_list: list of pages to uncharge
7446 * Uncharge a list of pages previously charged with
7447 * __mem_cgroup_charge().
7449 void __mem_cgroup_uncharge_list(struct list_head *page_list)
7451 struct uncharge_gather ug;
7452 struct folio *folio;
7454 uncharge_gather_clear(&ug);
7455 list_for_each_entry(folio, page_list, lru)
7456 uncharge_folio(folio, &ug);
7458 uncharge_batch(&ug);
7462 * mem_cgroup_replace_folio - Charge a folio's replacement.
7463 * @old: Currently circulating folio.
7464 * @new: Replacement folio.
7466 * Charge @new as a replacement folio for @old. @old will
7467 * be uncharged upon free. This is only used by the page cache
7468 * (in replace_page_cache_folio()).
7470 * Both folios must be locked, @new->mapping must be set up.
7472 void mem_cgroup_replace_folio(struct folio *old, struct folio *new)
7474 struct mem_cgroup *memcg;
7475 long nr_pages = folio_nr_pages(new);
7476 unsigned long flags;
7478 VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
7479 VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
7480 VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
7481 VM_BUG_ON_FOLIO(folio_nr_pages(old) != nr_pages, new);
7483 if (mem_cgroup_disabled())
7486 /* Page cache replacement: new folio already charged? */
7487 if (folio_memcg(new))
7490 memcg = folio_memcg(old);
7491 VM_WARN_ON_ONCE_FOLIO(!memcg, old);
7495 /* Force-charge the new page. The old one will be freed soon */
7496 if (!mem_cgroup_is_root(memcg)) {
7497 page_counter_charge(&memcg->memory, nr_pages);
7498 if (do_memsw_account())
7499 page_counter_charge(&memcg->memsw, nr_pages);
7502 css_get(&memcg->css);
7503 commit_charge(new, memcg);
7505 local_irq_save(flags);
7506 mem_cgroup_charge_statistics(memcg, nr_pages);
7507 memcg_check_events(memcg, folio_nid(new));
7508 local_irq_restore(flags);
7512 * mem_cgroup_migrate - Transfer the memcg data from the old to the new folio.
7513 * @old: Currently circulating folio.
7514 * @new: Replacement folio.
7516 * Transfer the memcg data from the old folio to the new folio for migration.
7517 * The old folio's data info will be cleared. Note that the memory counters
7518 * will remain unchanged throughout the process.
7520 * Both folios must be locked, @new->mapping must be set up.
7522 void mem_cgroup_migrate(struct folio *old, struct folio *new)
7524 struct mem_cgroup *memcg;
7526 VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
7527 VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
7528 VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
7529 VM_BUG_ON_FOLIO(folio_nr_pages(old) != folio_nr_pages(new), new);
7531 if (mem_cgroup_disabled())
7534 memcg = folio_memcg(old);
7536 * Note that it is normal to see !memcg for a hugetlb folio.
7537 * For e.g, itt could have been allocated when memory_hugetlb_accounting
7540 VM_WARN_ON_ONCE_FOLIO(!folio_test_hugetlb(old) && !memcg, old);
7544 /* Transfer the charge and the css ref */
7545 commit_charge(new, memcg);
7546 old->memcg_data = 0;
7549 DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
7550 EXPORT_SYMBOL(memcg_sockets_enabled_key);
7552 void mem_cgroup_sk_alloc(struct sock *sk)
7554 struct mem_cgroup *memcg;
7556 if (!mem_cgroup_sockets_enabled)
7559 /* Do not associate the sock with unrelated interrupted task's memcg. */
7564 memcg = mem_cgroup_from_task(current);
7565 if (mem_cgroup_is_root(memcg))
7567 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg->tcpmem_active)
7569 if (css_tryget(&memcg->css))
7570 sk->sk_memcg = memcg;
7575 void mem_cgroup_sk_free(struct sock *sk)
7578 css_put(&sk->sk_memcg->css);
7582 * mem_cgroup_charge_skmem - charge socket memory
7583 * @memcg: memcg to charge
7584 * @nr_pages: number of pages to charge
7585 * @gfp_mask: reclaim mode
7587 * Charges @nr_pages to @memcg. Returns %true if the charge fit within
7588 * @memcg's configured limit, %false if it doesn't.
7590 bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages,
7593 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
7594 struct page_counter *fail;
7596 if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) {
7597 memcg->tcpmem_pressure = 0;
7600 memcg->tcpmem_pressure = 1;
7601 if (gfp_mask & __GFP_NOFAIL) {
7602 page_counter_charge(&memcg->tcpmem, nr_pages);
7608 if (try_charge(memcg, gfp_mask, nr_pages) == 0) {
7609 mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
7617 * mem_cgroup_uncharge_skmem - uncharge socket memory
7618 * @memcg: memcg to uncharge
7619 * @nr_pages: number of pages to uncharge
7621 void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
7623 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
7624 page_counter_uncharge(&memcg->tcpmem, nr_pages);
7628 mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
7630 refill_stock(memcg, nr_pages);
7633 static int __init cgroup_memory(char *s)
7637 while ((token = strsep(&s, ",")) != NULL) {
7640 if (!strcmp(token, "nosocket"))
7641 cgroup_memory_nosocket = true;
7642 if (!strcmp(token, "nokmem"))
7643 cgroup_memory_nokmem = true;
7644 if (!strcmp(token, "nobpf"))
7645 cgroup_memory_nobpf = true;
7649 __setup("cgroup.memory=", cgroup_memory);
7652 * subsys_initcall() for memory controller.
7654 * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
7655 * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
7656 * basically everything that doesn't depend on a specific mem_cgroup structure
7657 * should be initialized from here.
7659 static int __init mem_cgroup_init(void)
7664 * Currently s32 type (can refer to struct batched_lruvec_stat) is
7665 * used for per-memcg-per-cpu caching of per-node statistics. In order
7666 * to work fine, we should make sure that the overfill threshold can't
7667 * exceed S32_MAX / PAGE_SIZE.
7669 BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE);
7671 cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
7672 memcg_hotplug_cpu_dead);
7674 for_each_possible_cpu(cpu)
7675 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
7678 for_each_node(node) {
7679 struct mem_cgroup_tree_per_node *rtpn;
7681 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, node);
7683 rtpn->rb_root = RB_ROOT;
7684 rtpn->rb_rightmost = NULL;
7685 spin_lock_init(&rtpn->lock);
7686 soft_limit_tree.rb_tree_per_node[node] = rtpn;
7691 subsys_initcall(mem_cgroup_init);
7694 static struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
7696 while (!refcount_inc_not_zero(&memcg->id.ref)) {
7698 * The root cgroup cannot be destroyed, so it's refcount must
7701 if (WARN_ON_ONCE(mem_cgroup_is_root(memcg))) {
7705 memcg = parent_mem_cgroup(memcg);
7707 memcg = root_mem_cgroup;
7713 * mem_cgroup_swapout - transfer a memsw charge to swap
7714 * @folio: folio whose memsw charge to transfer
7715 * @entry: swap entry to move the charge to
7717 * Transfer the memsw charge of @folio to @entry.
7719 void mem_cgroup_swapout(struct folio *folio, swp_entry_t entry)
7721 struct mem_cgroup *memcg, *swap_memcg;
7722 unsigned int nr_entries;
7723 unsigned short oldid;
7725 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
7726 VM_BUG_ON_FOLIO(folio_ref_count(folio), folio);
7728 if (mem_cgroup_disabled())
7731 if (!do_memsw_account())
7734 memcg = folio_memcg(folio);
7736 VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
7741 * In case the memcg owning these pages has been offlined and doesn't
7742 * have an ID allocated to it anymore, charge the closest online
7743 * ancestor for the swap instead and transfer the memory+swap charge.
7745 swap_memcg = mem_cgroup_id_get_online(memcg);
7746 nr_entries = folio_nr_pages(folio);
7747 /* Get references for the tail pages, too */
7749 mem_cgroup_id_get_many(swap_memcg, nr_entries - 1);
7750 oldid = swap_cgroup_record(entry, mem_cgroup_id(swap_memcg),
7752 VM_BUG_ON_FOLIO(oldid, folio);
7753 mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries);
7755 folio->memcg_data = 0;
7757 if (!mem_cgroup_is_root(memcg))
7758 page_counter_uncharge(&memcg->memory, nr_entries);
7760 if (memcg != swap_memcg) {
7761 if (!mem_cgroup_is_root(swap_memcg))
7762 page_counter_charge(&swap_memcg->memsw, nr_entries);
7763 page_counter_uncharge(&memcg->memsw, nr_entries);
7767 * Interrupts should be disabled here because the caller holds the
7768 * i_pages lock which is taken with interrupts-off. It is
7769 * important here to have the interrupts disabled because it is the
7770 * only synchronisation we have for updating the per-CPU variables.
7773 mem_cgroup_charge_statistics(memcg, -nr_entries);
7774 memcg_stats_unlock();
7775 memcg_check_events(memcg, folio_nid(folio));
7777 css_put(&memcg->css);
7781 * __mem_cgroup_try_charge_swap - try charging swap space for a folio
7782 * @folio: folio being added to swap
7783 * @entry: swap entry to charge
7785 * Try to charge @folio's memcg for the swap space at @entry.
7787 * Returns 0 on success, -ENOMEM on failure.
7789 int __mem_cgroup_try_charge_swap(struct folio *folio, swp_entry_t entry)
7791 unsigned int nr_pages = folio_nr_pages(folio);
7792 struct page_counter *counter;
7793 struct mem_cgroup *memcg;
7794 unsigned short oldid;
7796 if (do_memsw_account())
7799 memcg = folio_memcg(folio);
7801 VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
7806 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7810 memcg = mem_cgroup_id_get_online(memcg);
7812 if (!mem_cgroup_is_root(memcg) &&
7813 !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
7814 memcg_memory_event(memcg, MEMCG_SWAP_MAX);
7815 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7816 mem_cgroup_id_put(memcg);
7820 /* Get references for the tail pages, too */
7822 mem_cgroup_id_get_many(memcg, nr_pages - 1);
7823 oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg), nr_pages);
7824 VM_BUG_ON_FOLIO(oldid, folio);
7825 mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
7831 * __mem_cgroup_uncharge_swap - uncharge swap space
7832 * @entry: swap entry to uncharge
7833 * @nr_pages: the amount of swap space to uncharge
7835 void __mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
7837 struct mem_cgroup *memcg;
7840 id = swap_cgroup_record(entry, 0, nr_pages);
7842 memcg = mem_cgroup_from_id(id);
7844 if (!mem_cgroup_is_root(memcg)) {
7845 if (do_memsw_account())
7846 page_counter_uncharge(&memcg->memsw, nr_pages);
7848 page_counter_uncharge(&memcg->swap, nr_pages);
7850 mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
7851 mem_cgroup_id_put_many(memcg, nr_pages);
7856 long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
7858 long nr_swap_pages = get_nr_swap_pages();
7860 if (mem_cgroup_disabled() || do_memsw_account())
7861 return nr_swap_pages;
7862 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg))
7863 nr_swap_pages = min_t(long, nr_swap_pages,
7864 READ_ONCE(memcg->swap.max) -
7865 page_counter_read(&memcg->swap));
7866 return nr_swap_pages;
7869 bool mem_cgroup_swap_full(struct folio *folio)
7871 struct mem_cgroup *memcg;
7873 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
7877 if (do_memsw_account())
7880 memcg = folio_memcg(folio);
7884 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
7885 unsigned long usage = page_counter_read(&memcg->swap);
7887 if (usage * 2 >= READ_ONCE(memcg->swap.high) ||
7888 usage * 2 >= READ_ONCE(memcg->swap.max))
7895 static int __init setup_swap_account(char *s)
7897 pr_warn_once("The swapaccount= commandline option is deprecated. "
7898 "Please report your usecase to linux-mm@kvack.org if you "
7899 "depend on this functionality.\n");
7902 __setup("swapaccount=", setup_swap_account);
7904 static u64 swap_current_read(struct cgroup_subsys_state *css,
7907 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7909 return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
7912 static u64 swap_peak_read(struct cgroup_subsys_state *css,
7915 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7917 return (u64)memcg->swap.watermark * PAGE_SIZE;
7920 static int swap_high_show(struct seq_file *m, void *v)
7922 return seq_puts_memcg_tunable(m,
7923 READ_ONCE(mem_cgroup_from_seq(m)->swap.high));
7926 static ssize_t swap_high_write(struct kernfs_open_file *of,
7927 char *buf, size_t nbytes, loff_t off)
7929 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7933 buf = strstrip(buf);
7934 err = page_counter_memparse(buf, "max", &high);
7938 page_counter_set_high(&memcg->swap, high);
7943 static int swap_max_show(struct seq_file *m, void *v)
7945 return seq_puts_memcg_tunable(m,
7946 READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
7949 static ssize_t swap_max_write(struct kernfs_open_file *of,
7950 char *buf, size_t nbytes, loff_t off)
7952 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7956 buf = strstrip(buf);
7957 err = page_counter_memparse(buf, "max", &max);
7961 xchg(&memcg->swap.max, max);
7966 static int swap_events_show(struct seq_file *m, void *v)
7968 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
7970 seq_printf(m, "high %lu\n",
7971 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH]));
7972 seq_printf(m, "max %lu\n",
7973 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
7974 seq_printf(m, "fail %lu\n",
7975 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
7980 static struct cftype swap_files[] = {
7982 .name = "swap.current",
7983 .flags = CFTYPE_NOT_ON_ROOT,
7984 .read_u64 = swap_current_read,
7987 .name = "swap.high",
7988 .flags = CFTYPE_NOT_ON_ROOT,
7989 .seq_show = swap_high_show,
7990 .write = swap_high_write,
7994 .flags = CFTYPE_NOT_ON_ROOT,
7995 .seq_show = swap_max_show,
7996 .write = swap_max_write,
7999 .name = "swap.peak",
8000 .flags = CFTYPE_NOT_ON_ROOT,
8001 .read_u64 = swap_peak_read,
8004 .name = "swap.events",
8005 .flags = CFTYPE_NOT_ON_ROOT,
8006 .file_offset = offsetof(struct mem_cgroup, swap_events_file),
8007 .seq_show = swap_events_show,
8012 static struct cftype memsw_files[] = {
8014 .name = "memsw.usage_in_bytes",
8015 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
8016 .read_u64 = mem_cgroup_read_u64,
8019 .name = "memsw.max_usage_in_bytes",
8020 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
8021 .write = mem_cgroup_reset,
8022 .read_u64 = mem_cgroup_read_u64,
8025 .name = "memsw.limit_in_bytes",
8026 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
8027 .write = mem_cgroup_write,
8028 .read_u64 = mem_cgroup_read_u64,
8031 .name = "memsw.failcnt",
8032 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
8033 .write = mem_cgroup_reset,
8034 .read_u64 = mem_cgroup_read_u64,
8036 { }, /* terminate */
8039 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
8041 * obj_cgroup_may_zswap - check if this cgroup can zswap
8042 * @objcg: the object cgroup
8044 * Check if the hierarchical zswap limit has been reached.
8046 * This doesn't check for specific headroom, and it is not atomic
8047 * either. But with zswap, the size of the allocation is only known
8048 * once compression has occurred, and this optimistic pre-check avoids
8049 * spending cycles on compression when there is already no room left
8050 * or zswap is disabled altogether somewhere in the hierarchy.
8052 bool obj_cgroup_may_zswap(struct obj_cgroup *objcg)
8054 struct mem_cgroup *memcg, *original_memcg;
8057 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
8060 original_memcg = get_mem_cgroup_from_objcg(objcg);
8061 for (memcg = original_memcg; !mem_cgroup_is_root(memcg);
8062 memcg = parent_mem_cgroup(memcg)) {
8063 unsigned long max = READ_ONCE(memcg->zswap_max);
8064 unsigned long pages;
8066 if (max == PAGE_COUNTER_MAX)
8073 cgroup_rstat_flush(memcg->css.cgroup);
8074 pages = memcg_page_state(memcg, MEMCG_ZSWAP_B) / PAGE_SIZE;
8080 mem_cgroup_put(original_memcg);
8085 * obj_cgroup_charge_zswap - charge compression backend memory
8086 * @objcg: the object cgroup
8087 * @size: size of compressed object
8089 * This forces the charge after obj_cgroup_may_zswap() allowed
8090 * compression and storage in zwap for this cgroup to go ahead.
8092 void obj_cgroup_charge_zswap(struct obj_cgroup *objcg, size_t size)
8094 struct mem_cgroup *memcg;
8096 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
8099 VM_WARN_ON_ONCE(!(current->flags & PF_MEMALLOC));
8101 /* PF_MEMALLOC context, charging must succeed */
8102 if (obj_cgroup_charge(objcg, GFP_KERNEL, size))
8106 memcg = obj_cgroup_memcg(objcg);
8107 mod_memcg_state(memcg, MEMCG_ZSWAP_B, size);
8108 mod_memcg_state(memcg, MEMCG_ZSWAPPED, 1);
8113 * obj_cgroup_uncharge_zswap - uncharge compression backend memory
8114 * @objcg: the object cgroup
8115 * @size: size of compressed object
8117 * Uncharges zswap memory on page in.
8119 void obj_cgroup_uncharge_zswap(struct obj_cgroup *objcg, size_t size)
8121 struct mem_cgroup *memcg;
8123 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
8126 obj_cgroup_uncharge(objcg, size);
8129 memcg = obj_cgroup_memcg(objcg);
8130 mod_memcg_state(memcg, MEMCG_ZSWAP_B, -size);
8131 mod_memcg_state(memcg, MEMCG_ZSWAPPED, -1);
8135 static u64 zswap_current_read(struct cgroup_subsys_state *css,
8138 cgroup_rstat_flush(css->cgroup);
8139 return memcg_page_state(mem_cgroup_from_css(css), MEMCG_ZSWAP_B);
8142 static int zswap_max_show(struct seq_file *m, void *v)
8144 return seq_puts_memcg_tunable(m,
8145 READ_ONCE(mem_cgroup_from_seq(m)->zswap_max));
8148 static ssize_t zswap_max_write(struct kernfs_open_file *of,
8149 char *buf, size_t nbytes, loff_t off)
8151 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
8155 buf = strstrip(buf);
8156 err = page_counter_memparse(buf, "max", &max);
8160 xchg(&memcg->zswap_max, max);
8165 static struct cftype zswap_files[] = {
8167 .name = "zswap.current",
8168 .flags = CFTYPE_NOT_ON_ROOT,
8169 .read_u64 = zswap_current_read,
8172 .name = "zswap.max",
8173 .flags = CFTYPE_NOT_ON_ROOT,
8174 .seq_show = zswap_max_show,
8175 .write = zswap_max_write,
8179 #endif /* CONFIG_MEMCG_KMEM && CONFIG_ZSWAP */
8181 static int __init mem_cgroup_swap_init(void)
8183 if (mem_cgroup_disabled())
8186 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files));
8187 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files));
8188 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
8189 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, zswap_files));
8193 subsys_initcall(mem_cgroup_swap_init);
8195 #endif /* CONFIG_SWAP */