1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* memcontrol.c - Memory Controller
4 * Copyright IBM Corporation, 2007
5 * Author Balbir Singh <balbir@linux.vnet.ibm.com>
7 * Copyright 2007 OpenVZ SWsoft Inc
8 * Author: Pavel Emelianov <xemul@openvz.org>
11 * Copyright (C) 2009 Nokia Corporation
12 * Author: Kirill A. Shutemov
14 * Kernel Memory Controller
15 * Copyright (C) 2012 Parallels Inc. and Google Inc.
16 * Authors: Glauber Costa and Suleiman Souhlal
19 * Charge lifetime sanitation
20 * Lockless page tracking & accounting
21 * Unified hierarchy configuration model
22 * Copyright (C) 2015 Red Hat, Inc., Johannes Weiner
24 * Per memcg lru locking
25 * Copyright (C) 2020 Alibaba, Inc, Alex Shi
28 #include <linux/page_counter.h>
29 #include <linux/memcontrol.h>
30 #include <linux/cgroup.h>
31 #include <linux/pagewalk.h>
32 #include <linux/sched/mm.h>
33 #include <linux/shmem_fs.h>
34 #include <linux/hugetlb.h>
35 #include <linux/pagemap.h>
36 #include <linux/vm_event_item.h>
37 #include <linux/smp.h>
38 #include <linux/page-flags.h>
39 #include <linux/backing-dev.h>
40 #include <linux/bit_spinlock.h>
41 #include <linux/rcupdate.h>
42 #include <linux/limits.h>
43 #include <linux/export.h>
44 #include <linux/mutex.h>
45 #include <linux/rbtree.h>
46 #include <linux/slab.h>
47 #include <linux/swap.h>
48 #include <linux/swapops.h>
49 #include <linux/spinlock.h>
50 #include <linux/eventfd.h>
51 #include <linux/poll.h>
52 #include <linux/sort.h>
54 #include <linux/seq_file.h>
55 #include <linux/vmpressure.h>
56 #include <linux/memremap.h>
57 #include <linux/mm_inline.h>
58 #include <linux/swap_cgroup.h>
59 #include <linux/cpu.h>
60 #include <linux/oom.h>
61 #include <linux/lockdep.h>
62 #include <linux/file.h>
63 #include <linux/resume_user_mode.h>
64 #include <linux/psi.h>
65 #include <linux/seq_buf.h>
66 #include <linux/sched/isolation.h>
73 #include <linux/uaccess.h>
75 #include <trace/events/vmscan.h>
77 struct cgroup_subsys memory_cgrp_subsys __read_mostly;
78 EXPORT_SYMBOL(memory_cgrp_subsys);
80 struct mem_cgroup *root_mem_cgroup __read_mostly;
82 /* Active memory cgroup to use from an interrupt context */
83 DEFINE_PER_CPU(struct mem_cgroup *, int_active_memcg);
84 EXPORT_PER_CPU_SYMBOL_GPL(int_active_memcg);
86 /* Socket memory accounting disabled? */
87 static bool cgroup_memory_nosocket __ro_after_init;
89 /* Kernel memory accounting disabled? */
90 static bool cgroup_memory_nokmem __ro_after_init;
92 /* BPF memory accounting disabled? */
93 static bool cgroup_memory_nobpf __ro_after_init;
95 #ifdef CONFIG_CGROUP_WRITEBACK
96 static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq);
99 /* Whether legacy memory+swap accounting is active */
100 static bool do_memsw_account(void)
102 return !cgroup_subsys_on_dfl(memory_cgrp_subsys);
105 #define THRESHOLDS_EVENTS_TARGET 128
106 #define SOFTLIMIT_EVENTS_TARGET 1024
109 * Cgroups above their limits are maintained in a RB-Tree, independent of
110 * their hierarchy representation
113 struct mem_cgroup_tree_per_node {
114 struct rb_root rb_root;
115 struct rb_node *rb_rightmost;
119 struct mem_cgroup_tree {
120 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
123 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
126 struct mem_cgroup_eventfd_list {
127 struct list_head list;
128 struct eventfd_ctx *eventfd;
132 * cgroup_event represents events which userspace want to receive.
134 struct mem_cgroup_event {
136 * memcg which the event belongs to.
138 struct mem_cgroup *memcg;
140 * eventfd to signal userspace about the event.
142 struct eventfd_ctx *eventfd;
144 * Each of these stored in a list by the cgroup.
146 struct list_head list;
148 * register_event() callback will be used to add new userspace
149 * waiter for changes related to this event. Use eventfd_signal()
150 * on eventfd to send notification to userspace.
152 int (*register_event)(struct mem_cgroup *memcg,
153 struct eventfd_ctx *eventfd, const char *args);
155 * unregister_event() callback will be called when userspace closes
156 * the eventfd or on cgroup removing. This callback must be set,
157 * if you want provide notification functionality.
159 void (*unregister_event)(struct mem_cgroup *memcg,
160 struct eventfd_ctx *eventfd);
162 * All fields below needed to unregister event when
163 * userspace closes eventfd.
166 wait_queue_head_t *wqh;
167 wait_queue_entry_t wait;
168 struct work_struct remove;
171 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
172 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
174 /* Stuffs for move charges at task migration. */
176 * Types of charges to be moved.
178 #define MOVE_ANON 0x1U
179 #define MOVE_FILE 0x2U
180 #define MOVE_MASK (MOVE_ANON | MOVE_FILE)
182 /* "mc" and its members are protected by cgroup_mutex */
183 static struct move_charge_struct {
184 spinlock_t lock; /* for from, to */
185 struct mm_struct *mm;
186 struct mem_cgroup *from;
187 struct mem_cgroup *to;
189 unsigned long precharge;
190 unsigned long moved_charge;
191 unsigned long moved_swap;
192 struct task_struct *moving_task; /* a task moving charges */
193 wait_queue_head_t waitq; /* a waitq for other context */
195 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
196 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
200 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
201 * limit reclaim to prevent infinite loops, if they ever occur.
203 #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
204 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
206 /* for encoding cft->private value on file */
214 #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
215 #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
216 #define MEMFILE_ATTR(val) ((val) & 0xffff)
219 * Iteration constructs for visiting all cgroups (under a tree). If
220 * loops are exited prematurely (break), mem_cgroup_iter_break() must
221 * be used for reference counting.
223 #define for_each_mem_cgroup_tree(iter, root) \
224 for (iter = mem_cgroup_iter(root, NULL, NULL); \
226 iter = mem_cgroup_iter(root, iter, NULL))
228 #define for_each_mem_cgroup(iter) \
229 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
231 iter = mem_cgroup_iter(NULL, iter, NULL))
233 static inline bool task_is_dying(void)
235 return tsk_is_oom_victim(current) || fatal_signal_pending(current) ||
236 (current->flags & PF_EXITING);
239 /* Some nice accessors for the vmpressure. */
240 struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
243 memcg = root_mem_cgroup;
244 return &memcg->vmpressure;
247 struct mem_cgroup *vmpressure_to_memcg(struct vmpressure *vmpr)
249 return container_of(vmpr, struct mem_cgroup, vmpressure);
252 #ifdef CONFIG_MEMCG_KMEM
253 static DEFINE_SPINLOCK(objcg_lock);
255 bool mem_cgroup_kmem_disabled(void)
257 return cgroup_memory_nokmem;
260 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
261 unsigned int nr_pages);
263 static void obj_cgroup_release(struct percpu_ref *ref)
265 struct obj_cgroup *objcg = container_of(ref, struct obj_cgroup, refcnt);
266 unsigned int nr_bytes;
267 unsigned int nr_pages;
271 * At this point all allocated objects are freed, and
272 * objcg->nr_charged_bytes can't have an arbitrary byte value.
273 * However, it can be PAGE_SIZE or (x * PAGE_SIZE).
275 * The following sequence can lead to it:
276 * 1) CPU0: objcg == stock->cached_objcg
277 * 2) CPU1: we do a small allocation (e.g. 92 bytes),
278 * PAGE_SIZE bytes are charged
279 * 3) CPU1: a process from another memcg is allocating something,
280 * the stock if flushed,
281 * objcg->nr_charged_bytes = PAGE_SIZE - 92
282 * 5) CPU0: we do release this object,
283 * 92 bytes are added to stock->nr_bytes
284 * 6) CPU0: stock is flushed,
285 * 92 bytes are added to objcg->nr_charged_bytes
287 * In the result, nr_charged_bytes == PAGE_SIZE.
288 * This page will be uncharged in obj_cgroup_release().
290 nr_bytes = atomic_read(&objcg->nr_charged_bytes);
291 WARN_ON_ONCE(nr_bytes & (PAGE_SIZE - 1));
292 nr_pages = nr_bytes >> PAGE_SHIFT;
295 obj_cgroup_uncharge_pages(objcg, nr_pages);
297 spin_lock_irqsave(&objcg_lock, flags);
298 list_del(&objcg->list);
299 spin_unlock_irqrestore(&objcg_lock, flags);
301 percpu_ref_exit(ref);
302 kfree_rcu(objcg, rcu);
305 static struct obj_cgroup *obj_cgroup_alloc(void)
307 struct obj_cgroup *objcg;
310 objcg = kzalloc(sizeof(struct obj_cgroup), GFP_KERNEL);
314 ret = percpu_ref_init(&objcg->refcnt, obj_cgroup_release, 0,
320 INIT_LIST_HEAD(&objcg->list);
324 static void memcg_reparent_objcgs(struct mem_cgroup *memcg,
325 struct mem_cgroup *parent)
327 struct obj_cgroup *objcg, *iter;
329 objcg = rcu_replace_pointer(memcg->objcg, NULL, true);
331 spin_lock_irq(&objcg_lock);
333 /* 1) Ready to reparent active objcg. */
334 list_add(&objcg->list, &memcg->objcg_list);
335 /* 2) Reparent active objcg and already reparented objcgs to parent. */
336 list_for_each_entry(iter, &memcg->objcg_list, list)
337 WRITE_ONCE(iter->memcg, parent);
338 /* 3) Move already reparented objcgs to the parent's list */
339 list_splice(&memcg->objcg_list, &parent->objcg_list);
341 spin_unlock_irq(&objcg_lock);
343 percpu_ref_kill(&objcg->refcnt);
347 * A lot of the calls to the cache allocation functions are expected to be
348 * inlined by the compiler. Since the calls to memcg_slab_pre_alloc_hook() are
349 * conditional to this static branch, we'll have to allow modules that does
350 * kmem_cache_alloc and the such to see this symbol as well
352 DEFINE_STATIC_KEY_FALSE(memcg_kmem_online_key);
353 EXPORT_SYMBOL(memcg_kmem_online_key);
355 DEFINE_STATIC_KEY_FALSE(memcg_bpf_enabled_key);
356 EXPORT_SYMBOL(memcg_bpf_enabled_key);
360 * mem_cgroup_css_from_folio - css of the memcg associated with a folio
361 * @folio: folio of interest
363 * If memcg is bound to the default hierarchy, css of the memcg associated
364 * with @folio is returned. The returned css remains associated with @folio
365 * until it is released.
367 * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
370 struct cgroup_subsys_state *mem_cgroup_css_from_folio(struct folio *folio)
372 struct mem_cgroup *memcg = folio_memcg(folio);
374 if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
375 memcg = root_mem_cgroup;
381 * page_cgroup_ino - return inode number of the memcg a page is charged to
384 * Look up the closest online ancestor of the memory cgroup @page is charged to
385 * and return its inode number or 0 if @page is not charged to any cgroup. It
386 * is safe to call this function without holding a reference to @page.
388 * Note, this function is inherently racy, because there is nothing to prevent
389 * the cgroup inode from getting torn down and potentially reallocated a moment
390 * after page_cgroup_ino() returns, so it only should be used by callers that
391 * do not care (such as procfs interfaces).
393 ino_t page_cgroup_ino(struct page *page)
395 struct mem_cgroup *memcg;
396 unsigned long ino = 0;
399 /* page_folio() is racy here, but the entire function is racy anyway */
400 memcg = folio_memcg_check(page_folio(page));
402 while (memcg && !(memcg->css.flags & CSS_ONLINE))
403 memcg = parent_mem_cgroup(memcg);
405 ino = cgroup_ino(memcg->css.cgroup);
410 static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_node *mz,
411 struct mem_cgroup_tree_per_node *mctz,
412 unsigned long new_usage_in_excess)
414 struct rb_node **p = &mctz->rb_root.rb_node;
415 struct rb_node *parent = NULL;
416 struct mem_cgroup_per_node *mz_node;
417 bool rightmost = true;
422 mz->usage_in_excess = new_usage_in_excess;
423 if (!mz->usage_in_excess)
427 mz_node = rb_entry(parent, struct mem_cgroup_per_node,
429 if (mz->usage_in_excess < mz_node->usage_in_excess) {
438 mctz->rb_rightmost = &mz->tree_node;
440 rb_link_node(&mz->tree_node, parent, p);
441 rb_insert_color(&mz->tree_node, &mctz->rb_root);
445 static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
446 struct mem_cgroup_tree_per_node *mctz)
451 if (&mz->tree_node == mctz->rb_rightmost)
452 mctz->rb_rightmost = rb_prev(&mz->tree_node);
454 rb_erase(&mz->tree_node, &mctz->rb_root);
458 static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
459 struct mem_cgroup_tree_per_node *mctz)
463 spin_lock_irqsave(&mctz->lock, flags);
464 __mem_cgroup_remove_exceeded(mz, mctz);
465 spin_unlock_irqrestore(&mctz->lock, flags);
468 static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
470 unsigned long nr_pages = page_counter_read(&memcg->memory);
471 unsigned long soft_limit = READ_ONCE(memcg->soft_limit);
472 unsigned long excess = 0;
474 if (nr_pages > soft_limit)
475 excess = nr_pages - soft_limit;
480 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, int nid)
482 unsigned long excess;
483 struct mem_cgroup_per_node *mz;
484 struct mem_cgroup_tree_per_node *mctz;
486 if (lru_gen_enabled()) {
487 if (soft_limit_excess(memcg))
488 lru_gen_soft_reclaim(&memcg->nodeinfo[nid]->lruvec);
492 mctz = soft_limit_tree.rb_tree_per_node[nid];
496 * Necessary to update all ancestors when hierarchy is used.
497 * because their event counter is not touched.
499 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
500 mz = memcg->nodeinfo[nid];
501 excess = soft_limit_excess(memcg);
503 * We have to update the tree if mz is on RB-tree or
504 * mem is over its softlimit.
506 if (excess || mz->on_tree) {
509 spin_lock_irqsave(&mctz->lock, flags);
510 /* if on-tree, remove it */
512 __mem_cgroup_remove_exceeded(mz, mctz);
514 * Insert again. mz->usage_in_excess will be updated.
515 * If excess is 0, no tree ops.
517 __mem_cgroup_insert_exceeded(mz, mctz, excess);
518 spin_unlock_irqrestore(&mctz->lock, flags);
523 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
525 struct mem_cgroup_tree_per_node *mctz;
526 struct mem_cgroup_per_node *mz;
530 mz = memcg->nodeinfo[nid];
531 mctz = soft_limit_tree.rb_tree_per_node[nid];
533 mem_cgroup_remove_exceeded(mz, mctz);
537 static struct mem_cgroup_per_node *
538 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
540 struct mem_cgroup_per_node *mz;
544 if (!mctz->rb_rightmost)
545 goto done; /* Nothing to reclaim from */
547 mz = rb_entry(mctz->rb_rightmost,
548 struct mem_cgroup_per_node, tree_node);
550 * Remove the node now but someone else can add it back,
551 * we will to add it back at the end of reclaim to its correct
552 * position in the tree.
554 __mem_cgroup_remove_exceeded(mz, mctz);
555 if (!soft_limit_excess(mz->memcg) ||
556 !css_tryget(&mz->memcg->css))
562 static struct mem_cgroup_per_node *
563 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
565 struct mem_cgroup_per_node *mz;
567 spin_lock_irq(&mctz->lock);
568 mz = __mem_cgroup_largest_soft_limit_node(mctz);
569 spin_unlock_irq(&mctz->lock);
574 * memcg and lruvec stats flushing
576 * Many codepaths leading to stats update or read are performance sensitive and
577 * adding stats flushing in such codepaths is not desirable. So, to optimize the
578 * flushing the kernel does:
580 * 1) Periodically and asynchronously flush the stats every 2 seconds to not let
581 * rstat update tree grow unbounded.
583 * 2) Flush the stats synchronously on reader side only when there are more than
584 * (MEMCG_CHARGE_BATCH * nr_cpus) update events. Though this optimization
585 * will let stats be out of sync by atmost (MEMCG_CHARGE_BATCH * nr_cpus) but
586 * only for 2 seconds due to (1).
588 static void flush_memcg_stats_dwork(struct work_struct *w);
589 static DECLARE_DEFERRABLE_WORK(stats_flush_dwork, flush_memcg_stats_dwork);
590 static DEFINE_PER_CPU(unsigned int, stats_updates);
591 static atomic_t stats_flush_ongoing = ATOMIC_INIT(0);
592 static atomic_t stats_flush_threshold = ATOMIC_INIT(0);
593 static u64 flush_next_time;
595 #define FLUSH_TIME (2UL*HZ)
598 * Accessors to ensure that preemption is disabled on PREEMPT_RT because it can
599 * not rely on this as part of an acquired spinlock_t lock. These functions are
600 * never used in hardirq context on PREEMPT_RT and therefore disabling preemtion
603 static void memcg_stats_lock(void)
605 preempt_disable_nested();
606 VM_WARN_ON_IRQS_ENABLED();
609 static void __memcg_stats_lock(void)
611 preempt_disable_nested();
614 static void memcg_stats_unlock(void)
616 preempt_enable_nested();
619 static inline void memcg_rstat_updated(struct mem_cgroup *memcg, int val)
626 cgroup_rstat_updated(memcg->css.cgroup, smp_processor_id());
628 x = __this_cpu_add_return(stats_updates, abs(val));
629 if (x > MEMCG_CHARGE_BATCH) {
631 * If stats_flush_threshold exceeds the threshold
632 * (>num_online_cpus()), cgroup stats update will be triggered
633 * in __mem_cgroup_flush_stats(). Increasing this var further
634 * is redundant and simply adds overhead in atomic update.
636 if (atomic_read(&stats_flush_threshold) <= num_online_cpus())
637 atomic_add(x / MEMCG_CHARGE_BATCH, &stats_flush_threshold);
638 __this_cpu_write(stats_updates, 0);
642 static void do_flush_stats(void)
645 * We always flush the entire tree, so concurrent flushers can just
646 * skip. This avoids a thundering herd problem on the rstat global lock
647 * from memcg flushers (e.g. reclaim, refault, etc).
649 if (atomic_read(&stats_flush_ongoing) ||
650 atomic_xchg(&stats_flush_ongoing, 1))
653 WRITE_ONCE(flush_next_time, jiffies_64 + 2*FLUSH_TIME);
655 cgroup_rstat_flush(root_mem_cgroup->css.cgroup);
657 atomic_set(&stats_flush_threshold, 0);
658 atomic_set(&stats_flush_ongoing, 0);
661 void mem_cgroup_flush_stats(void)
663 if (atomic_read(&stats_flush_threshold) > num_online_cpus())
667 void mem_cgroup_flush_stats_ratelimited(void)
669 if (time_after64(jiffies_64, READ_ONCE(flush_next_time)))
670 mem_cgroup_flush_stats();
673 static void flush_memcg_stats_dwork(struct work_struct *w)
676 * Always flush here so that flushing in latency-sensitive paths is
677 * as cheap as possible.
680 queue_delayed_work(system_unbound_wq, &stats_flush_dwork, FLUSH_TIME);
683 /* Subset of vm_event_item to report for memcg event stats */
684 static const unsigned int memcg_vm_event_stat[] = {
700 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
704 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
710 #define NR_MEMCG_EVENTS ARRAY_SIZE(memcg_vm_event_stat)
711 static int mem_cgroup_events_index[NR_VM_EVENT_ITEMS] __read_mostly;
713 static void init_memcg_events(void)
717 for (i = 0; i < NR_MEMCG_EVENTS; ++i)
718 mem_cgroup_events_index[memcg_vm_event_stat[i]] = i + 1;
721 static inline int memcg_events_index(enum vm_event_item idx)
723 return mem_cgroup_events_index[idx] - 1;
726 struct memcg_vmstats_percpu {
727 /* Local (CPU and cgroup) page state & events */
728 long state[MEMCG_NR_STAT];
729 unsigned long events[NR_MEMCG_EVENTS];
731 /* Delta calculation for lockless upward propagation */
732 long state_prev[MEMCG_NR_STAT];
733 unsigned long events_prev[NR_MEMCG_EVENTS];
735 /* Cgroup1: threshold notifications & softlimit tree updates */
736 unsigned long nr_page_events;
737 unsigned long targets[MEM_CGROUP_NTARGETS];
740 struct memcg_vmstats {
741 /* Aggregated (CPU and subtree) page state & events */
742 long state[MEMCG_NR_STAT];
743 unsigned long events[NR_MEMCG_EVENTS];
745 /* Pending child counts during tree propagation */
746 long state_pending[MEMCG_NR_STAT];
747 unsigned long events_pending[NR_MEMCG_EVENTS];
750 unsigned long memcg_page_state(struct mem_cgroup *memcg, int idx)
752 long x = READ_ONCE(memcg->vmstats->state[idx]);
761 * __mod_memcg_state - update cgroup memory statistics
762 * @memcg: the memory cgroup
763 * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item
764 * @val: delta to add to the counter, can be negative
766 void __mod_memcg_state(struct mem_cgroup *memcg, int idx, int val)
768 if (mem_cgroup_disabled())
771 __this_cpu_add(memcg->vmstats_percpu->state[idx], val);
772 memcg_rstat_updated(memcg, val);
775 /* idx can be of type enum memcg_stat_item or node_stat_item. */
776 static unsigned long memcg_page_state_local(struct mem_cgroup *memcg, int idx)
781 for_each_possible_cpu(cpu)
782 x += per_cpu(memcg->vmstats_percpu->state[idx], cpu);
790 void __mod_memcg_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
793 struct mem_cgroup_per_node *pn;
794 struct mem_cgroup *memcg;
796 pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
800 * The caller from rmap relay on disabled preemption becase they never
801 * update their counter from in-interrupt context. For these two
802 * counters we check that the update is never performed from an
803 * interrupt context while other caller need to have disabled interrupt.
805 __memcg_stats_lock();
806 if (IS_ENABLED(CONFIG_DEBUG_VM)) {
811 case NR_SHMEM_PMDMAPPED:
812 case NR_FILE_PMDMAPPED:
813 WARN_ON_ONCE(!in_task());
816 VM_WARN_ON_IRQS_ENABLED();
821 __this_cpu_add(memcg->vmstats_percpu->state[idx], val);
824 __this_cpu_add(pn->lruvec_stats_percpu->state[idx], val);
826 memcg_rstat_updated(memcg, val);
827 memcg_stats_unlock();
831 * __mod_lruvec_state - update lruvec memory statistics
832 * @lruvec: the lruvec
833 * @idx: the stat item
834 * @val: delta to add to the counter, can be negative
836 * The lruvec is the intersection of the NUMA node and a cgroup. This
837 * function updates the all three counters that are affected by a
838 * change of state at this level: per-node, per-cgroup, per-lruvec.
840 void __mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
844 __mod_node_page_state(lruvec_pgdat(lruvec), idx, val);
846 /* Update memcg and lruvec */
847 if (!mem_cgroup_disabled())
848 __mod_memcg_lruvec_state(lruvec, idx, val);
851 void __mod_lruvec_page_state(struct page *page, enum node_stat_item idx,
854 struct page *head = compound_head(page); /* rmap on tail pages */
855 struct mem_cgroup *memcg;
856 pg_data_t *pgdat = page_pgdat(page);
857 struct lruvec *lruvec;
860 memcg = page_memcg(head);
861 /* Untracked pages have no memcg, no lruvec. Update only the node */
864 __mod_node_page_state(pgdat, idx, val);
868 lruvec = mem_cgroup_lruvec(memcg, pgdat);
869 __mod_lruvec_state(lruvec, idx, val);
872 EXPORT_SYMBOL(__mod_lruvec_page_state);
874 void __mod_lruvec_kmem_state(void *p, enum node_stat_item idx, int val)
876 pg_data_t *pgdat = page_pgdat(virt_to_page(p));
877 struct mem_cgroup *memcg;
878 struct lruvec *lruvec;
881 memcg = mem_cgroup_from_slab_obj(p);
884 * Untracked pages have no memcg, no lruvec. Update only the
885 * node. If we reparent the slab objects to the root memcg,
886 * when we free the slab object, we need to update the per-memcg
887 * vmstats to keep it correct for the root memcg.
890 __mod_node_page_state(pgdat, idx, val);
892 lruvec = mem_cgroup_lruvec(memcg, pgdat);
893 __mod_lruvec_state(lruvec, idx, val);
899 * __count_memcg_events - account VM events in a cgroup
900 * @memcg: the memory cgroup
901 * @idx: the event item
902 * @count: the number of events that occurred
904 void __count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx,
907 int index = memcg_events_index(idx);
909 if (mem_cgroup_disabled() || index < 0)
913 __this_cpu_add(memcg->vmstats_percpu->events[index], count);
914 memcg_rstat_updated(memcg, count);
915 memcg_stats_unlock();
918 static unsigned long memcg_events(struct mem_cgroup *memcg, int event)
920 int index = memcg_events_index(event);
924 return READ_ONCE(memcg->vmstats->events[index]);
927 static unsigned long memcg_events_local(struct mem_cgroup *memcg, int event)
931 int index = memcg_events_index(event);
936 for_each_possible_cpu(cpu)
937 x += per_cpu(memcg->vmstats_percpu->events[index], cpu);
941 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
944 /* pagein of a big page is an event. So, ignore page size */
946 __count_memcg_events(memcg, PGPGIN, 1);
948 __count_memcg_events(memcg, PGPGOUT, 1);
949 nr_pages = -nr_pages; /* for event */
952 __this_cpu_add(memcg->vmstats_percpu->nr_page_events, nr_pages);
955 static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
956 enum mem_cgroup_events_target target)
958 unsigned long val, next;
960 val = __this_cpu_read(memcg->vmstats_percpu->nr_page_events);
961 next = __this_cpu_read(memcg->vmstats_percpu->targets[target]);
962 /* from time_after() in jiffies.h */
963 if ((long)(next - val) < 0) {
965 case MEM_CGROUP_TARGET_THRESH:
966 next = val + THRESHOLDS_EVENTS_TARGET;
968 case MEM_CGROUP_TARGET_SOFTLIMIT:
969 next = val + SOFTLIMIT_EVENTS_TARGET;
974 __this_cpu_write(memcg->vmstats_percpu->targets[target], next);
981 * Check events in order.
984 static void memcg_check_events(struct mem_cgroup *memcg, int nid)
986 if (IS_ENABLED(CONFIG_PREEMPT_RT))
989 /* threshold event is triggered in finer grain than soft limit */
990 if (unlikely(mem_cgroup_event_ratelimit(memcg,
991 MEM_CGROUP_TARGET_THRESH))) {
994 do_softlimit = mem_cgroup_event_ratelimit(memcg,
995 MEM_CGROUP_TARGET_SOFTLIMIT);
996 mem_cgroup_threshold(memcg);
997 if (unlikely(do_softlimit))
998 mem_cgroup_update_tree(memcg, nid);
1002 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
1005 * mm_update_next_owner() may clear mm->owner to NULL
1006 * if it races with swapoff, page migration, etc.
1007 * So this can be called with p == NULL.
1012 return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
1014 EXPORT_SYMBOL(mem_cgroup_from_task);
1016 static __always_inline struct mem_cgroup *active_memcg(void)
1019 return this_cpu_read(int_active_memcg);
1021 return current->active_memcg;
1025 * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
1026 * @mm: mm from which memcg should be extracted. It can be NULL.
1028 * Obtain a reference on mm->memcg and returns it if successful. If mm
1029 * is NULL, then the memcg is chosen as follows:
1030 * 1) The active memcg, if set.
1031 * 2) current->mm->memcg, if available
1033 * If mem_cgroup is disabled, NULL is returned.
1035 struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
1037 struct mem_cgroup *memcg;
1039 if (mem_cgroup_disabled())
1043 * Page cache insertions can happen without an
1044 * actual mm context, e.g. during disk probing
1045 * on boot, loopback IO, acct() writes etc.
1047 * No need to css_get on root memcg as the reference
1048 * counting is disabled on the root level in the
1049 * cgroup core. See CSS_NO_REF.
1051 if (unlikely(!mm)) {
1052 memcg = active_memcg();
1053 if (unlikely(memcg)) {
1054 /* remote memcg must hold a ref */
1055 css_get(&memcg->css);
1060 return root_mem_cgroup;
1065 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1066 if (unlikely(!memcg))
1067 memcg = root_mem_cgroup;
1068 } while (!css_tryget(&memcg->css));
1072 EXPORT_SYMBOL(get_mem_cgroup_from_mm);
1074 static __always_inline bool memcg_kmem_bypass(void)
1076 /* Allow remote memcg charging from any context. */
1077 if (unlikely(active_memcg()))
1080 /* Memcg to charge can't be determined. */
1081 if (!in_task() || !current->mm || (current->flags & PF_KTHREAD))
1088 * mem_cgroup_iter - iterate over memory cgroup hierarchy
1089 * @root: hierarchy root
1090 * @prev: previously returned memcg, NULL on first invocation
1091 * @reclaim: cookie for shared reclaim walks, NULL for full walks
1093 * Returns references to children of the hierarchy below @root, or
1094 * @root itself, or %NULL after a full round-trip.
1096 * Caller must pass the return value in @prev on subsequent
1097 * invocations for reference counting, or use mem_cgroup_iter_break()
1098 * to cancel a hierarchy walk before the round-trip is complete.
1100 * Reclaimers can specify a node in @reclaim to divide up the memcgs
1101 * in the hierarchy among all concurrent reclaimers operating on the
1104 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
1105 struct mem_cgroup *prev,
1106 struct mem_cgroup_reclaim_cookie *reclaim)
1108 struct mem_cgroup_reclaim_iter *iter;
1109 struct cgroup_subsys_state *css = NULL;
1110 struct mem_cgroup *memcg = NULL;
1111 struct mem_cgroup *pos = NULL;
1113 if (mem_cgroup_disabled())
1117 root = root_mem_cgroup;
1122 struct mem_cgroup_per_node *mz;
1124 mz = root->nodeinfo[reclaim->pgdat->node_id];
1128 * On start, join the current reclaim iteration cycle.
1129 * Exit when a concurrent walker completes it.
1132 reclaim->generation = iter->generation;
1133 else if (reclaim->generation != iter->generation)
1137 pos = READ_ONCE(iter->position);
1138 if (!pos || css_tryget(&pos->css))
1141 * css reference reached zero, so iter->position will
1142 * be cleared by ->css_released. However, we should not
1143 * rely on this happening soon, because ->css_released
1144 * is called from a work queue, and by busy-waiting we
1145 * might block it. So we clear iter->position right
1148 (void)cmpxchg(&iter->position, pos, NULL);
1158 css = css_next_descendant_pre(css, &root->css);
1161 * Reclaimers share the hierarchy walk, and a
1162 * new one might jump in right at the end of
1163 * the hierarchy - make sure they see at least
1164 * one group and restart from the beginning.
1172 * Verify the css and acquire a reference. The root
1173 * is provided by the caller, so we know it's alive
1174 * and kicking, and don't take an extra reference.
1176 if (css == &root->css || css_tryget(css)) {
1177 memcg = mem_cgroup_from_css(css);
1184 * The position could have already been updated by a competing
1185 * thread, so check that the value hasn't changed since we read
1186 * it to avoid reclaiming from the same cgroup twice.
1188 (void)cmpxchg(&iter->position, pos, memcg);
1199 if (prev && prev != root)
1200 css_put(&prev->css);
1206 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1207 * @root: hierarchy root
1208 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1210 void mem_cgroup_iter_break(struct mem_cgroup *root,
1211 struct mem_cgroup *prev)
1214 root = root_mem_cgroup;
1215 if (prev && prev != root)
1216 css_put(&prev->css);
1219 static void __invalidate_reclaim_iterators(struct mem_cgroup *from,
1220 struct mem_cgroup *dead_memcg)
1222 struct mem_cgroup_reclaim_iter *iter;
1223 struct mem_cgroup_per_node *mz;
1226 for_each_node(nid) {
1227 mz = from->nodeinfo[nid];
1229 cmpxchg(&iter->position, dead_memcg, NULL);
1233 static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
1235 struct mem_cgroup *memcg = dead_memcg;
1236 struct mem_cgroup *last;
1239 __invalidate_reclaim_iterators(memcg, dead_memcg);
1241 } while ((memcg = parent_mem_cgroup(memcg)));
1244 * When cgroup1 non-hierarchy mode is used,
1245 * parent_mem_cgroup() does not walk all the way up to the
1246 * cgroup root (root_mem_cgroup). So we have to handle
1247 * dead_memcg from cgroup root separately.
1249 if (!mem_cgroup_is_root(last))
1250 __invalidate_reclaim_iterators(root_mem_cgroup,
1255 * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
1256 * @memcg: hierarchy root
1257 * @fn: function to call for each task
1258 * @arg: argument passed to @fn
1260 * This function iterates over tasks attached to @memcg or to any of its
1261 * descendants and calls @fn for each task. If @fn returns a non-zero
1262 * value, the function breaks the iteration loop and returns the value.
1263 * Otherwise, it will iterate over all tasks and return 0.
1265 * This function must not be called for the root memory cgroup.
1267 int mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
1268 int (*fn)(struct task_struct *, void *), void *arg)
1270 struct mem_cgroup *iter;
1273 BUG_ON(mem_cgroup_is_root(memcg));
1275 for_each_mem_cgroup_tree(iter, memcg) {
1276 struct css_task_iter it;
1277 struct task_struct *task;
1279 css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it);
1280 while (!ret && (task = css_task_iter_next(&it)))
1281 ret = fn(task, arg);
1282 css_task_iter_end(&it);
1284 mem_cgroup_iter_break(memcg, iter);
1291 #ifdef CONFIG_DEBUG_VM
1292 void lruvec_memcg_debug(struct lruvec *lruvec, struct folio *folio)
1294 struct mem_cgroup *memcg;
1296 if (mem_cgroup_disabled())
1299 memcg = folio_memcg(folio);
1302 VM_BUG_ON_FOLIO(!mem_cgroup_is_root(lruvec_memcg(lruvec)), folio);
1304 VM_BUG_ON_FOLIO(lruvec_memcg(lruvec) != memcg, folio);
1309 * folio_lruvec_lock - Lock the lruvec for a folio.
1310 * @folio: Pointer to the folio.
1312 * These functions are safe to use under any of the following conditions:
1314 * - folio_test_lru false
1315 * - folio_memcg_lock()
1316 * - folio frozen (refcount of 0)
1318 * Return: The lruvec this folio is on with its lock held.
1320 struct lruvec *folio_lruvec_lock(struct folio *folio)
1322 struct lruvec *lruvec = folio_lruvec(folio);
1324 spin_lock(&lruvec->lru_lock);
1325 lruvec_memcg_debug(lruvec, folio);
1331 * folio_lruvec_lock_irq - Lock the lruvec for a folio.
1332 * @folio: Pointer to the folio.
1334 * These functions are safe to use under any of the following conditions:
1336 * - folio_test_lru false
1337 * - folio_memcg_lock()
1338 * - folio frozen (refcount of 0)
1340 * Return: The lruvec this folio is on with its lock held and interrupts
1343 struct lruvec *folio_lruvec_lock_irq(struct folio *folio)
1345 struct lruvec *lruvec = folio_lruvec(folio);
1347 spin_lock_irq(&lruvec->lru_lock);
1348 lruvec_memcg_debug(lruvec, folio);
1354 * folio_lruvec_lock_irqsave - Lock the lruvec for a folio.
1355 * @folio: Pointer to the folio.
1356 * @flags: Pointer to irqsave flags.
1358 * These functions are safe to use under any of the following conditions:
1360 * - folio_test_lru false
1361 * - folio_memcg_lock()
1362 * - folio frozen (refcount of 0)
1364 * Return: The lruvec this folio is on with its lock held and interrupts
1367 struct lruvec *folio_lruvec_lock_irqsave(struct folio *folio,
1368 unsigned long *flags)
1370 struct lruvec *lruvec = folio_lruvec(folio);
1372 spin_lock_irqsave(&lruvec->lru_lock, *flags);
1373 lruvec_memcg_debug(lruvec, folio);
1379 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1380 * @lruvec: mem_cgroup per zone lru vector
1381 * @lru: index of lru list the page is sitting on
1382 * @zid: zone id of the accounted pages
1383 * @nr_pages: positive when adding or negative when removing
1385 * This function must be called under lru_lock, just before a page is added
1386 * to or just after a page is removed from an lru list.
1388 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1389 int zid, int nr_pages)
1391 struct mem_cgroup_per_node *mz;
1392 unsigned long *lru_size;
1395 if (mem_cgroup_disabled())
1398 mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
1399 lru_size = &mz->lru_zone_size[zid][lru];
1402 *lru_size += nr_pages;
1405 if (WARN_ONCE(size < 0,
1406 "%s(%p, %d, %d): lru_size %ld\n",
1407 __func__, lruvec, lru, nr_pages, size)) {
1413 *lru_size += nr_pages;
1417 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1418 * @memcg: the memory cgroup
1420 * Returns the maximum amount of memory @mem can be charged with, in
1423 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1425 unsigned long margin = 0;
1426 unsigned long count;
1427 unsigned long limit;
1429 count = page_counter_read(&memcg->memory);
1430 limit = READ_ONCE(memcg->memory.max);
1432 margin = limit - count;
1434 if (do_memsw_account()) {
1435 count = page_counter_read(&memcg->memsw);
1436 limit = READ_ONCE(memcg->memsw.max);
1438 margin = min(margin, limit - count);
1447 * A routine for checking "mem" is under move_account() or not.
1449 * Checking a cgroup is mc.from or mc.to or under hierarchy of
1450 * moving cgroups. This is for waiting at high-memory pressure
1453 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1455 struct mem_cgroup *from;
1456 struct mem_cgroup *to;
1459 * Unlike task_move routines, we access mc.to, mc.from not under
1460 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1462 spin_lock(&mc.lock);
1468 ret = mem_cgroup_is_descendant(from, memcg) ||
1469 mem_cgroup_is_descendant(to, memcg);
1471 spin_unlock(&mc.lock);
1475 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1477 if (mc.moving_task && current != mc.moving_task) {
1478 if (mem_cgroup_under_move(memcg)) {
1480 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1481 /* moving charge context might have finished. */
1484 finish_wait(&mc.waitq, &wait);
1491 struct memory_stat {
1496 static const struct memory_stat memory_stats[] = {
1497 { "anon", NR_ANON_MAPPED },
1498 { "file", NR_FILE_PAGES },
1499 { "kernel", MEMCG_KMEM },
1500 { "kernel_stack", NR_KERNEL_STACK_KB },
1501 { "pagetables", NR_PAGETABLE },
1502 { "sec_pagetables", NR_SECONDARY_PAGETABLE },
1503 { "percpu", MEMCG_PERCPU_B },
1504 { "sock", MEMCG_SOCK },
1505 { "vmalloc", MEMCG_VMALLOC },
1506 { "shmem", NR_SHMEM },
1507 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
1508 { "zswap", MEMCG_ZSWAP_B },
1509 { "zswapped", MEMCG_ZSWAPPED },
1511 { "file_mapped", NR_FILE_MAPPED },
1512 { "file_dirty", NR_FILE_DIRTY },
1513 { "file_writeback", NR_WRITEBACK },
1515 { "swapcached", NR_SWAPCACHE },
1517 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1518 { "anon_thp", NR_ANON_THPS },
1519 { "file_thp", NR_FILE_THPS },
1520 { "shmem_thp", NR_SHMEM_THPS },
1522 { "inactive_anon", NR_INACTIVE_ANON },
1523 { "active_anon", NR_ACTIVE_ANON },
1524 { "inactive_file", NR_INACTIVE_FILE },
1525 { "active_file", NR_ACTIVE_FILE },
1526 { "unevictable", NR_UNEVICTABLE },
1527 { "slab_reclaimable", NR_SLAB_RECLAIMABLE_B },
1528 { "slab_unreclaimable", NR_SLAB_UNRECLAIMABLE_B },
1530 /* The memory events */
1531 { "workingset_refault_anon", WORKINGSET_REFAULT_ANON },
1532 { "workingset_refault_file", WORKINGSET_REFAULT_FILE },
1533 { "workingset_activate_anon", WORKINGSET_ACTIVATE_ANON },
1534 { "workingset_activate_file", WORKINGSET_ACTIVATE_FILE },
1535 { "workingset_restore_anon", WORKINGSET_RESTORE_ANON },
1536 { "workingset_restore_file", WORKINGSET_RESTORE_FILE },
1537 { "workingset_nodereclaim", WORKINGSET_NODERECLAIM },
1540 /* Translate stat items to the correct unit for memory.stat output */
1541 static int memcg_page_state_unit(int item)
1544 case MEMCG_PERCPU_B:
1546 case NR_SLAB_RECLAIMABLE_B:
1547 case NR_SLAB_UNRECLAIMABLE_B:
1548 case WORKINGSET_REFAULT_ANON:
1549 case WORKINGSET_REFAULT_FILE:
1550 case WORKINGSET_ACTIVATE_ANON:
1551 case WORKINGSET_ACTIVATE_FILE:
1552 case WORKINGSET_RESTORE_ANON:
1553 case WORKINGSET_RESTORE_FILE:
1554 case WORKINGSET_NODERECLAIM:
1556 case NR_KERNEL_STACK_KB:
1563 static inline unsigned long memcg_page_state_output(struct mem_cgroup *memcg,
1566 return memcg_page_state(memcg, item) * memcg_page_state_unit(item);
1569 static void memcg_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
1574 * Provide statistics on the state of the memory subsystem as
1575 * well as cumulative event counters that show past behavior.
1577 * This list is ordered following a combination of these gradients:
1578 * 1) generic big picture -> specifics and details
1579 * 2) reflecting userspace activity -> reflecting kernel heuristics
1581 * Current memory state:
1583 mem_cgroup_flush_stats();
1585 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
1588 size = memcg_page_state_output(memcg, memory_stats[i].idx);
1589 seq_buf_printf(s, "%s %llu\n", memory_stats[i].name, size);
1591 if (unlikely(memory_stats[i].idx == NR_SLAB_UNRECLAIMABLE_B)) {
1592 size += memcg_page_state_output(memcg,
1593 NR_SLAB_RECLAIMABLE_B);
1594 seq_buf_printf(s, "slab %llu\n", size);
1598 /* Accumulated memory events */
1599 seq_buf_printf(s, "pgscan %lu\n",
1600 memcg_events(memcg, PGSCAN_KSWAPD) +
1601 memcg_events(memcg, PGSCAN_DIRECT) +
1602 memcg_events(memcg, PGSCAN_KHUGEPAGED));
1603 seq_buf_printf(s, "pgsteal %lu\n",
1604 memcg_events(memcg, PGSTEAL_KSWAPD) +
1605 memcg_events(memcg, PGSTEAL_DIRECT) +
1606 memcg_events(memcg, PGSTEAL_KHUGEPAGED));
1608 for (i = 0; i < ARRAY_SIZE(memcg_vm_event_stat); i++) {
1609 if (memcg_vm_event_stat[i] == PGPGIN ||
1610 memcg_vm_event_stat[i] == PGPGOUT)
1613 seq_buf_printf(s, "%s %lu\n",
1614 vm_event_name(memcg_vm_event_stat[i]),
1615 memcg_events(memcg, memcg_vm_event_stat[i]));
1618 /* The above should easily fit into one page */
1619 WARN_ON_ONCE(seq_buf_has_overflowed(s));
1622 static void memcg1_stat_format(struct mem_cgroup *memcg, struct seq_buf *s);
1624 static void memory_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
1626 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1627 memcg_stat_format(memcg, s);
1629 memcg1_stat_format(memcg, s);
1630 WARN_ON_ONCE(seq_buf_has_overflowed(s));
1633 #define K(x) ((x) << (PAGE_SHIFT-10))
1635 * mem_cgroup_print_oom_context: Print OOM information relevant to
1636 * memory controller.
1637 * @memcg: The memory cgroup that went over limit
1638 * @p: Task that is going to be killed
1640 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1643 void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p)
1648 pr_cont(",oom_memcg=");
1649 pr_cont_cgroup_path(memcg->css.cgroup);
1651 pr_cont(",global_oom");
1653 pr_cont(",task_memcg=");
1654 pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
1660 * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
1661 * memory controller.
1662 * @memcg: The memory cgroup that went over limit
1664 void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
1666 /* Use static buffer, for the caller is holding oom_lock. */
1667 static char buf[PAGE_SIZE];
1670 lockdep_assert_held(&oom_lock);
1672 pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1673 K((u64)page_counter_read(&memcg->memory)),
1674 K((u64)READ_ONCE(memcg->memory.max)), memcg->memory.failcnt);
1675 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1676 pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n",
1677 K((u64)page_counter_read(&memcg->swap)),
1678 K((u64)READ_ONCE(memcg->swap.max)), memcg->swap.failcnt);
1680 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1681 K((u64)page_counter_read(&memcg->memsw)),
1682 K((u64)memcg->memsw.max), memcg->memsw.failcnt);
1683 pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1684 K((u64)page_counter_read(&memcg->kmem)),
1685 K((u64)memcg->kmem.max), memcg->kmem.failcnt);
1688 pr_info("Memory cgroup stats for ");
1689 pr_cont_cgroup_path(memcg->css.cgroup);
1691 seq_buf_init(&s, buf, sizeof(buf));
1692 memory_stat_format(memcg, &s);
1693 seq_buf_do_printk(&s, KERN_INFO);
1697 * Return the memory (and swap, if configured) limit for a memcg.
1699 unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg)
1701 unsigned long max = READ_ONCE(memcg->memory.max);
1703 if (do_memsw_account()) {
1704 if (mem_cgroup_swappiness(memcg)) {
1705 /* Calculate swap excess capacity from memsw limit */
1706 unsigned long swap = READ_ONCE(memcg->memsw.max) - max;
1708 max += min(swap, (unsigned long)total_swap_pages);
1711 if (mem_cgroup_swappiness(memcg))
1712 max += min(READ_ONCE(memcg->swap.max),
1713 (unsigned long)total_swap_pages);
1718 unsigned long mem_cgroup_size(struct mem_cgroup *memcg)
1720 return page_counter_read(&memcg->memory);
1723 static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1726 struct oom_control oc = {
1730 .gfp_mask = gfp_mask,
1735 if (mutex_lock_killable(&oom_lock))
1738 if (mem_cgroup_margin(memcg) >= (1 << order))
1742 * A few threads which were not waiting at mutex_lock_killable() can
1743 * fail to bail out. Therefore, check again after holding oom_lock.
1745 ret = task_is_dying() || out_of_memory(&oc);
1748 mutex_unlock(&oom_lock);
1752 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
1755 unsigned long *total_scanned)
1757 struct mem_cgroup *victim = NULL;
1760 unsigned long excess;
1761 unsigned long nr_scanned;
1762 struct mem_cgroup_reclaim_cookie reclaim = {
1766 excess = soft_limit_excess(root_memcg);
1769 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1774 * If we have not been able to reclaim
1775 * anything, it might because there are
1776 * no reclaimable pages under this hierarchy
1781 * We want to do more targeted reclaim.
1782 * excess >> 2 is not to excessive so as to
1783 * reclaim too much, nor too less that we keep
1784 * coming back to reclaim from this cgroup
1786 if (total >= (excess >> 2) ||
1787 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1792 total += mem_cgroup_shrink_node(victim, gfp_mask, false,
1793 pgdat, &nr_scanned);
1794 *total_scanned += nr_scanned;
1795 if (!soft_limit_excess(root_memcg))
1798 mem_cgroup_iter_break(root_memcg, victim);
1802 #ifdef CONFIG_LOCKDEP
1803 static struct lockdep_map memcg_oom_lock_dep_map = {
1804 .name = "memcg_oom_lock",
1808 static DEFINE_SPINLOCK(memcg_oom_lock);
1811 * Check OOM-Killer is already running under our hierarchy.
1812 * If someone is running, return false.
1814 static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
1816 struct mem_cgroup *iter, *failed = NULL;
1818 spin_lock(&memcg_oom_lock);
1820 for_each_mem_cgroup_tree(iter, memcg) {
1821 if (iter->oom_lock) {
1823 * this subtree of our hierarchy is already locked
1824 * so we cannot give a lock.
1827 mem_cgroup_iter_break(memcg, iter);
1830 iter->oom_lock = true;
1835 * OK, we failed to lock the whole subtree so we have
1836 * to clean up what we set up to the failing subtree
1838 for_each_mem_cgroup_tree(iter, memcg) {
1839 if (iter == failed) {
1840 mem_cgroup_iter_break(memcg, iter);
1843 iter->oom_lock = false;
1846 mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
1848 spin_unlock(&memcg_oom_lock);
1853 static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1855 struct mem_cgroup *iter;
1857 spin_lock(&memcg_oom_lock);
1858 mutex_release(&memcg_oom_lock_dep_map, _RET_IP_);
1859 for_each_mem_cgroup_tree(iter, memcg)
1860 iter->oom_lock = false;
1861 spin_unlock(&memcg_oom_lock);
1864 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1866 struct mem_cgroup *iter;
1868 spin_lock(&memcg_oom_lock);
1869 for_each_mem_cgroup_tree(iter, memcg)
1871 spin_unlock(&memcg_oom_lock);
1874 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1876 struct mem_cgroup *iter;
1879 * Be careful about under_oom underflows because a child memcg
1880 * could have been added after mem_cgroup_mark_under_oom.
1882 spin_lock(&memcg_oom_lock);
1883 for_each_mem_cgroup_tree(iter, memcg)
1884 if (iter->under_oom > 0)
1886 spin_unlock(&memcg_oom_lock);
1889 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1891 struct oom_wait_info {
1892 struct mem_cgroup *memcg;
1893 wait_queue_entry_t wait;
1896 static int memcg_oom_wake_function(wait_queue_entry_t *wait,
1897 unsigned mode, int sync, void *arg)
1899 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
1900 struct mem_cgroup *oom_wait_memcg;
1901 struct oom_wait_info *oom_wait_info;
1903 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1904 oom_wait_memcg = oom_wait_info->memcg;
1906 if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
1907 !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
1909 return autoremove_wake_function(wait, mode, sync, arg);
1912 static void memcg_oom_recover(struct mem_cgroup *memcg)
1915 * For the following lockless ->under_oom test, the only required
1916 * guarantee is that it must see the state asserted by an OOM when
1917 * this function is called as a result of userland actions
1918 * triggered by the notification of the OOM. This is trivially
1919 * achieved by invoking mem_cgroup_mark_under_oom() before
1920 * triggering notification.
1922 if (memcg && memcg->under_oom)
1923 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
1927 * Returns true if successfully killed one or more processes. Though in some
1928 * corner cases it can return true even without killing any process.
1930 static bool mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
1934 if (order > PAGE_ALLOC_COSTLY_ORDER)
1937 memcg_memory_event(memcg, MEMCG_OOM);
1940 * We are in the middle of the charge context here, so we
1941 * don't want to block when potentially sitting on a callstack
1942 * that holds all kinds of filesystem and mm locks.
1944 * cgroup1 allows disabling the OOM killer and waiting for outside
1945 * handling until the charge can succeed; remember the context and put
1946 * the task to sleep at the end of the page fault when all locks are
1949 * On the other hand, in-kernel OOM killer allows for an async victim
1950 * memory reclaim (oom_reaper) and that means that we are not solely
1951 * relying on the oom victim to make a forward progress and we can
1952 * invoke the oom killer here.
1954 * Please note that mem_cgroup_out_of_memory might fail to find a
1955 * victim and then we have to bail out from the charge path.
1957 if (READ_ONCE(memcg->oom_kill_disable)) {
1958 if (current->in_user_fault) {
1959 css_get(&memcg->css);
1960 current->memcg_in_oom = memcg;
1961 current->memcg_oom_gfp_mask = mask;
1962 current->memcg_oom_order = order;
1967 mem_cgroup_mark_under_oom(memcg);
1969 locked = mem_cgroup_oom_trylock(memcg);
1972 mem_cgroup_oom_notify(memcg);
1974 mem_cgroup_unmark_under_oom(memcg);
1975 ret = mem_cgroup_out_of_memory(memcg, mask, order);
1978 mem_cgroup_oom_unlock(memcg);
1984 * mem_cgroup_oom_synchronize - complete memcg OOM handling
1985 * @handle: actually kill/wait or just clean up the OOM state
1987 * This has to be called at the end of a page fault if the memcg OOM
1988 * handler was enabled.
1990 * Memcg supports userspace OOM handling where failed allocations must
1991 * sleep on a waitqueue until the userspace task resolves the
1992 * situation. Sleeping directly in the charge context with all kinds
1993 * of locks held is not a good idea, instead we remember an OOM state
1994 * in the task and mem_cgroup_oom_synchronize() has to be called at
1995 * the end of the page fault to complete the OOM handling.
1997 * Returns %true if an ongoing memcg OOM situation was detected and
1998 * completed, %false otherwise.
2000 bool mem_cgroup_oom_synchronize(bool handle)
2002 struct mem_cgroup *memcg = current->memcg_in_oom;
2003 struct oom_wait_info owait;
2006 /* OOM is global, do not handle */
2013 owait.memcg = memcg;
2014 owait.wait.flags = 0;
2015 owait.wait.func = memcg_oom_wake_function;
2016 owait.wait.private = current;
2017 INIT_LIST_HEAD(&owait.wait.entry);
2019 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
2020 mem_cgroup_mark_under_oom(memcg);
2022 locked = mem_cgroup_oom_trylock(memcg);
2025 mem_cgroup_oom_notify(memcg);
2028 mem_cgroup_unmark_under_oom(memcg);
2029 finish_wait(&memcg_oom_waitq, &owait.wait);
2032 mem_cgroup_oom_unlock(memcg);
2034 * There is no guarantee that an OOM-lock contender
2035 * sees the wakeups triggered by the OOM kill
2036 * uncharges. Wake any sleepers explicitly.
2038 memcg_oom_recover(memcg);
2041 current->memcg_in_oom = NULL;
2042 css_put(&memcg->css);
2047 * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
2048 * @victim: task to be killed by the OOM killer
2049 * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
2051 * Returns a pointer to a memory cgroup, which has to be cleaned up
2052 * by killing all belonging OOM-killable tasks.
2054 * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
2056 struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim,
2057 struct mem_cgroup *oom_domain)
2059 struct mem_cgroup *oom_group = NULL;
2060 struct mem_cgroup *memcg;
2062 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
2066 oom_domain = root_mem_cgroup;
2070 memcg = mem_cgroup_from_task(victim);
2071 if (mem_cgroup_is_root(memcg))
2075 * If the victim task has been asynchronously moved to a different
2076 * memory cgroup, we might end up killing tasks outside oom_domain.
2077 * In this case it's better to ignore memory.group.oom.
2079 if (unlikely(!mem_cgroup_is_descendant(memcg, oom_domain)))
2083 * Traverse the memory cgroup hierarchy from the victim task's
2084 * cgroup up to the OOMing cgroup (or root) to find the
2085 * highest-level memory cgroup with oom.group set.
2087 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
2088 if (READ_ONCE(memcg->oom_group))
2091 if (memcg == oom_domain)
2096 css_get(&oom_group->css);
2103 void mem_cgroup_print_oom_group(struct mem_cgroup *memcg)
2105 pr_info("Tasks in ");
2106 pr_cont_cgroup_path(memcg->css.cgroup);
2107 pr_cont(" are going to be killed due to memory.oom.group set\n");
2111 * folio_memcg_lock - Bind a folio to its memcg.
2112 * @folio: The folio.
2114 * This function prevents unlocked LRU folios from being moved to
2117 * It ensures lifetime of the bound memcg. The caller is responsible
2118 * for the lifetime of the folio.
2120 void folio_memcg_lock(struct folio *folio)
2122 struct mem_cgroup *memcg;
2123 unsigned long flags;
2126 * The RCU lock is held throughout the transaction. The fast
2127 * path can get away without acquiring the memcg->move_lock
2128 * because page moving starts with an RCU grace period.
2132 if (mem_cgroup_disabled())
2135 memcg = folio_memcg(folio);
2136 if (unlikely(!memcg))
2139 #ifdef CONFIG_PROVE_LOCKING
2140 local_irq_save(flags);
2141 might_lock(&memcg->move_lock);
2142 local_irq_restore(flags);
2145 if (atomic_read(&memcg->moving_account) <= 0)
2148 spin_lock_irqsave(&memcg->move_lock, flags);
2149 if (memcg != folio_memcg(folio)) {
2150 spin_unlock_irqrestore(&memcg->move_lock, flags);
2155 * When charge migration first begins, we can have multiple
2156 * critical sections holding the fast-path RCU lock and one
2157 * holding the slowpath move_lock. Track the task who has the
2158 * move_lock for unlock_page_memcg().
2160 memcg->move_lock_task = current;
2161 memcg->move_lock_flags = flags;
2164 void lock_page_memcg(struct page *page)
2166 folio_memcg_lock(page_folio(page));
2169 static void __folio_memcg_unlock(struct mem_cgroup *memcg)
2171 if (memcg && memcg->move_lock_task == current) {
2172 unsigned long flags = memcg->move_lock_flags;
2174 memcg->move_lock_task = NULL;
2175 memcg->move_lock_flags = 0;
2177 spin_unlock_irqrestore(&memcg->move_lock, flags);
2184 * folio_memcg_unlock - Release the binding between a folio and its memcg.
2185 * @folio: The folio.
2187 * This releases the binding created by folio_memcg_lock(). This does
2188 * not change the accounting of this folio to its memcg, but it does
2189 * permit others to change it.
2191 void folio_memcg_unlock(struct folio *folio)
2193 __folio_memcg_unlock(folio_memcg(folio));
2196 void unlock_page_memcg(struct page *page)
2198 folio_memcg_unlock(page_folio(page));
2201 struct memcg_stock_pcp {
2202 local_lock_t stock_lock;
2203 struct mem_cgroup *cached; /* this never be root cgroup */
2204 unsigned int nr_pages;
2206 #ifdef CONFIG_MEMCG_KMEM
2207 struct obj_cgroup *cached_objcg;
2208 struct pglist_data *cached_pgdat;
2209 unsigned int nr_bytes;
2210 int nr_slab_reclaimable_b;
2211 int nr_slab_unreclaimable_b;
2214 struct work_struct work;
2215 unsigned long flags;
2216 #define FLUSHING_CACHED_CHARGE 0
2218 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock) = {
2219 .stock_lock = INIT_LOCAL_LOCK(stock_lock),
2221 static DEFINE_MUTEX(percpu_charge_mutex);
2223 #ifdef CONFIG_MEMCG_KMEM
2224 static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock);
2225 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2226 struct mem_cgroup *root_memcg);
2227 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages);
2230 static inline struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock)
2234 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2235 struct mem_cgroup *root_memcg)
2239 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages)
2245 * consume_stock: Try to consume stocked charge on this cpu.
2246 * @memcg: memcg to consume from.
2247 * @nr_pages: how many pages to charge.
2249 * The charges will only happen if @memcg matches the current cpu's memcg
2250 * stock, and at least @nr_pages are available in that stock. Failure to
2251 * service an allocation will refill the stock.
2253 * returns true if successful, false otherwise.
2255 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2257 struct memcg_stock_pcp *stock;
2258 unsigned long flags;
2261 if (nr_pages > MEMCG_CHARGE_BATCH)
2264 local_lock_irqsave(&memcg_stock.stock_lock, flags);
2266 stock = this_cpu_ptr(&memcg_stock);
2267 if (memcg == READ_ONCE(stock->cached) && stock->nr_pages >= nr_pages) {
2268 stock->nr_pages -= nr_pages;
2272 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2278 * Returns stocks cached in percpu and reset cached information.
2280 static void drain_stock(struct memcg_stock_pcp *stock)
2282 struct mem_cgroup *old = READ_ONCE(stock->cached);
2287 if (stock->nr_pages) {
2288 page_counter_uncharge(&old->memory, stock->nr_pages);
2289 if (do_memsw_account())
2290 page_counter_uncharge(&old->memsw, stock->nr_pages);
2291 stock->nr_pages = 0;
2295 WRITE_ONCE(stock->cached, NULL);
2298 static void drain_local_stock(struct work_struct *dummy)
2300 struct memcg_stock_pcp *stock;
2301 struct obj_cgroup *old = NULL;
2302 unsigned long flags;
2305 * The only protection from cpu hotplug (memcg_hotplug_cpu_dead) vs.
2306 * drain_stock races is that we always operate on local CPU stock
2307 * here with IRQ disabled
2309 local_lock_irqsave(&memcg_stock.stock_lock, flags);
2311 stock = this_cpu_ptr(&memcg_stock);
2312 old = drain_obj_stock(stock);
2314 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2316 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2318 obj_cgroup_put(old);
2322 * Cache charges(val) to local per_cpu area.
2323 * This will be consumed by consume_stock() function, later.
2325 static void __refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2327 struct memcg_stock_pcp *stock;
2329 stock = this_cpu_ptr(&memcg_stock);
2330 if (READ_ONCE(stock->cached) != memcg) { /* reset if necessary */
2332 css_get(&memcg->css);
2333 WRITE_ONCE(stock->cached, memcg);
2335 stock->nr_pages += nr_pages;
2337 if (stock->nr_pages > MEMCG_CHARGE_BATCH)
2341 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2343 unsigned long flags;
2345 local_lock_irqsave(&memcg_stock.stock_lock, flags);
2346 __refill_stock(memcg, nr_pages);
2347 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2351 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2352 * of the hierarchy under it.
2354 static void drain_all_stock(struct mem_cgroup *root_memcg)
2358 /* If someone's already draining, avoid adding running more workers. */
2359 if (!mutex_trylock(&percpu_charge_mutex))
2362 * Notify other cpus that system-wide "drain" is running
2363 * We do not care about races with the cpu hotplug because cpu down
2364 * as well as workers from this path always operate on the local
2365 * per-cpu data. CPU up doesn't touch memcg_stock at all.
2368 curcpu = smp_processor_id();
2369 for_each_online_cpu(cpu) {
2370 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2371 struct mem_cgroup *memcg;
2375 memcg = READ_ONCE(stock->cached);
2376 if (memcg && stock->nr_pages &&
2377 mem_cgroup_is_descendant(memcg, root_memcg))
2379 else if (obj_stock_flush_required(stock, root_memcg))
2384 !test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2386 drain_local_stock(&stock->work);
2387 else if (!cpu_is_isolated(cpu))
2388 schedule_work_on(cpu, &stock->work);
2392 mutex_unlock(&percpu_charge_mutex);
2395 static int memcg_hotplug_cpu_dead(unsigned int cpu)
2397 struct memcg_stock_pcp *stock;
2399 stock = &per_cpu(memcg_stock, cpu);
2405 static unsigned long reclaim_high(struct mem_cgroup *memcg,
2406 unsigned int nr_pages,
2409 unsigned long nr_reclaimed = 0;
2412 unsigned long pflags;
2414 if (page_counter_read(&memcg->memory) <=
2415 READ_ONCE(memcg->memory.high))
2418 memcg_memory_event(memcg, MEMCG_HIGH);
2420 psi_memstall_enter(&pflags);
2421 nr_reclaimed += try_to_free_mem_cgroup_pages(memcg, nr_pages,
2423 MEMCG_RECLAIM_MAY_SWAP);
2424 psi_memstall_leave(&pflags);
2425 } while ((memcg = parent_mem_cgroup(memcg)) &&
2426 !mem_cgroup_is_root(memcg));
2428 return nr_reclaimed;
2431 static void high_work_func(struct work_struct *work)
2433 struct mem_cgroup *memcg;
2435 memcg = container_of(work, struct mem_cgroup, high_work);
2436 reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
2440 * Clamp the maximum sleep time per allocation batch to 2 seconds. This is
2441 * enough to still cause a significant slowdown in most cases, while still
2442 * allowing diagnostics and tracing to proceed without becoming stuck.
2444 #define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ)
2447 * When calculating the delay, we use these either side of the exponentiation to
2448 * maintain precision and scale to a reasonable number of jiffies (see the table
2451 * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the
2452 * overage ratio to a delay.
2453 * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down the
2454 * proposed penalty in order to reduce to a reasonable number of jiffies, and
2455 * to produce a reasonable delay curve.
2457 * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a
2458 * reasonable delay curve compared to precision-adjusted overage, not
2459 * penalising heavily at first, but still making sure that growth beyond the
2460 * limit penalises misbehaviour cgroups by slowing them down exponentially. For
2461 * example, with a high of 100 megabytes:
2463 * +-------+------------------------+
2464 * | usage | time to allocate in ms |
2465 * +-------+------------------------+
2487 * +-------+------------------------+
2489 #define MEMCG_DELAY_PRECISION_SHIFT 20
2490 #define MEMCG_DELAY_SCALING_SHIFT 14
2492 static u64 calculate_overage(unsigned long usage, unsigned long high)
2500 * Prevent division by 0 in overage calculation by acting as if
2501 * it was a threshold of 1 page
2503 high = max(high, 1UL);
2505 overage = usage - high;
2506 overage <<= MEMCG_DELAY_PRECISION_SHIFT;
2507 return div64_u64(overage, high);
2510 static u64 mem_find_max_overage(struct mem_cgroup *memcg)
2512 u64 overage, max_overage = 0;
2515 overage = calculate_overage(page_counter_read(&memcg->memory),
2516 READ_ONCE(memcg->memory.high));
2517 max_overage = max(overage, max_overage);
2518 } while ((memcg = parent_mem_cgroup(memcg)) &&
2519 !mem_cgroup_is_root(memcg));
2524 static u64 swap_find_max_overage(struct mem_cgroup *memcg)
2526 u64 overage, max_overage = 0;
2529 overage = calculate_overage(page_counter_read(&memcg->swap),
2530 READ_ONCE(memcg->swap.high));
2532 memcg_memory_event(memcg, MEMCG_SWAP_HIGH);
2533 max_overage = max(overage, max_overage);
2534 } while ((memcg = parent_mem_cgroup(memcg)) &&
2535 !mem_cgroup_is_root(memcg));
2541 * Get the number of jiffies that we should penalise a mischievous cgroup which
2542 * is exceeding its memory.high by checking both it and its ancestors.
2544 static unsigned long calculate_high_delay(struct mem_cgroup *memcg,
2545 unsigned int nr_pages,
2548 unsigned long penalty_jiffies;
2554 * We use overage compared to memory.high to calculate the number of
2555 * jiffies to sleep (penalty_jiffies). Ideally this value should be
2556 * fairly lenient on small overages, and increasingly harsh when the
2557 * memcg in question makes it clear that it has no intention of stopping
2558 * its crazy behaviour, so we exponentially increase the delay based on
2561 penalty_jiffies = max_overage * max_overage * HZ;
2562 penalty_jiffies >>= MEMCG_DELAY_PRECISION_SHIFT;
2563 penalty_jiffies >>= MEMCG_DELAY_SCALING_SHIFT;
2566 * Factor in the task's own contribution to the overage, such that four
2567 * N-sized allocations are throttled approximately the same as one
2568 * 4N-sized allocation.
2570 * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or
2571 * larger the current charge patch is than that.
2573 return penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH;
2577 * Scheduled by try_charge() to be executed from the userland return path
2578 * and reclaims memory over the high limit.
2580 void mem_cgroup_handle_over_high(void)
2582 unsigned long penalty_jiffies;
2583 unsigned long pflags;
2584 unsigned long nr_reclaimed;
2585 unsigned int nr_pages = current->memcg_nr_pages_over_high;
2586 int nr_retries = MAX_RECLAIM_RETRIES;
2587 struct mem_cgroup *memcg;
2588 bool in_retry = false;
2590 if (likely(!nr_pages))
2593 memcg = get_mem_cgroup_from_mm(current->mm);
2594 current->memcg_nr_pages_over_high = 0;
2598 * The allocating task should reclaim at least the batch size, but for
2599 * subsequent retries we only want to do what's necessary to prevent oom
2600 * or breaching resource isolation.
2602 * This is distinct from memory.max or page allocator behaviour because
2603 * memory.high is currently batched, whereas memory.max and the page
2604 * allocator run every time an allocation is made.
2606 nr_reclaimed = reclaim_high(memcg,
2607 in_retry ? SWAP_CLUSTER_MAX : nr_pages,
2611 * memory.high is breached and reclaim is unable to keep up. Throttle
2612 * allocators proactively to slow down excessive growth.
2614 penalty_jiffies = calculate_high_delay(memcg, nr_pages,
2615 mem_find_max_overage(memcg));
2617 penalty_jiffies += calculate_high_delay(memcg, nr_pages,
2618 swap_find_max_overage(memcg));
2621 * Clamp the max delay per usermode return so as to still keep the
2622 * application moving forwards and also permit diagnostics, albeit
2625 penalty_jiffies = min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES);
2628 * Don't sleep if the amount of jiffies this memcg owes us is so low
2629 * that it's not even worth doing, in an attempt to be nice to those who
2630 * go only a small amount over their memory.high value and maybe haven't
2631 * been aggressively reclaimed enough yet.
2633 if (penalty_jiffies <= HZ / 100)
2637 * If reclaim is making forward progress but we're still over
2638 * memory.high, we want to encourage that rather than doing allocator
2641 if (nr_reclaimed || nr_retries--) {
2647 * If we exit early, we're guaranteed to die (since
2648 * schedule_timeout_killable sets TASK_KILLABLE). This means we don't
2649 * need to account for any ill-begotten jiffies to pay them off later.
2651 psi_memstall_enter(&pflags);
2652 schedule_timeout_killable(penalty_jiffies);
2653 psi_memstall_leave(&pflags);
2656 css_put(&memcg->css);
2659 static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask,
2660 unsigned int nr_pages)
2662 unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
2663 int nr_retries = MAX_RECLAIM_RETRIES;
2664 struct mem_cgroup *mem_over_limit;
2665 struct page_counter *counter;
2666 unsigned long nr_reclaimed;
2667 bool passed_oom = false;
2668 unsigned int reclaim_options = MEMCG_RECLAIM_MAY_SWAP;
2669 bool drained = false;
2670 bool raised_max_event = false;
2671 unsigned long pflags;
2674 if (consume_stock(memcg, nr_pages))
2677 if (!do_memsw_account() ||
2678 page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2679 if (page_counter_try_charge(&memcg->memory, batch, &counter))
2681 if (do_memsw_account())
2682 page_counter_uncharge(&memcg->memsw, batch);
2683 mem_over_limit = mem_cgroup_from_counter(counter, memory);
2685 mem_over_limit = mem_cgroup_from_counter(counter, memsw);
2686 reclaim_options &= ~MEMCG_RECLAIM_MAY_SWAP;
2689 if (batch > nr_pages) {
2695 * Prevent unbounded recursion when reclaim operations need to
2696 * allocate memory. This might exceed the limits temporarily,
2697 * but we prefer facilitating memory reclaim and getting back
2698 * under the limit over triggering OOM kills in these cases.
2700 if (unlikely(current->flags & PF_MEMALLOC))
2703 if (unlikely(task_in_memcg_oom(current)))
2706 if (!gfpflags_allow_blocking(gfp_mask))
2709 memcg_memory_event(mem_over_limit, MEMCG_MAX);
2710 raised_max_event = true;
2712 psi_memstall_enter(&pflags);
2713 nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
2714 gfp_mask, reclaim_options);
2715 psi_memstall_leave(&pflags);
2717 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2721 drain_all_stock(mem_over_limit);
2726 if (gfp_mask & __GFP_NORETRY)
2729 * Even though the limit is exceeded at this point, reclaim
2730 * may have been able to free some pages. Retry the charge
2731 * before killing the task.
2733 * Only for regular pages, though: huge pages are rather
2734 * unlikely to succeed so close to the limit, and we fall back
2735 * to regular pages anyway in case of failure.
2737 if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
2740 * At task move, charge accounts can be doubly counted. So, it's
2741 * better to wait until the end of task_move if something is going on.
2743 if (mem_cgroup_wait_acct_move(mem_over_limit))
2749 if (gfp_mask & __GFP_RETRY_MAYFAIL)
2752 /* Avoid endless loop for tasks bypassed by the oom killer */
2753 if (passed_oom && task_is_dying())
2757 * keep retrying as long as the memcg oom killer is able to make
2758 * a forward progress or bypass the charge if the oom killer
2759 * couldn't make any progress.
2761 if (mem_cgroup_oom(mem_over_limit, gfp_mask,
2762 get_order(nr_pages * PAGE_SIZE))) {
2764 nr_retries = MAX_RECLAIM_RETRIES;
2769 * Memcg doesn't have a dedicated reserve for atomic
2770 * allocations. But like the global atomic pool, we need to
2771 * put the burden of reclaim on regular allocation requests
2772 * and let these go through as privileged allocations.
2774 if (!(gfp_mask & (__GFP_NOFAIL | __GFP_HIGH)))
2778 * If the allocation has to be enforced, don't forget to raise
2779 * a MEMCG_MAX event.
2781 if (!raised_max_event)
2782 memcg_memory_event(mem_over_limit, MEMCG_MAX);
2785 * The allocation either can't fail or will lead to more memory
2786 * being freed very soon. Allow memory usage go over the limit
2787 * temporarily by force charging it.
2789 page_counter_charge(&memcg->memory, nr_pages);
2790 if (do_memsw_account())
2791 page_counter_charge(&memcg->memsw, nr_pages);
2796 if (batch > nr_pages)
2797 refill_stock(memcg, batch - nr_pages);
2800 * If the hierarchy is above the normal consumption range, schedule
2801 * reclaim on returning to userland. We can perform reclaim here
2802 * if __GFP_RECLAIM but let's always punt for simplicity and so that
2803 * GFP_KERNEL can consistently be used during reclaim. @memcg is
2804 * not recorded as it most likely matches current's and won't
2805 * change in the meantime. As high limit is checked again before
2806 * reclaim, the cost of mismatch is negligible.
2809 bool mem_high, swap_high;
2811 mem_high = page_counter_read(&memcg->memory) >
2812 READ_ONCE(memcg->memory.high);
2813 swap_high = page_counter_read(&memcg->swap) >
2814 READ_ONCE(memcg->swap.high);
2816 /* Don't bother a random interrupted task */
2819 schedule_work(&memcg->high_work);
2825 if (mem_high || swap_high) {
2827 * The allocating tasks in this cgroup will need to do
2828 * reclaim or be throttled to prevent further growth
2829 * of the memory or swap footprints.
2831 * Target some best-effort fairness between the tasks,
2832 * and distribute reclaim work and delay penalties
2833 * based on how much each task is actually allocating.
2835 current->memcg_nr_pages_over_high += batch;
2836 set_notify_resume(current);
2839 } while ((memcg = parent_mem_cgroup(memcg)));
2841 if (current->memcg_nr_pages_over_high > MEMCG_CHARGE_BATCH &&
2842 !(current->flags & PF_MEMALLOC) &&
2843 gfpflags_allow_blocking(gfp_mask)) {
2844 mem_cgroup_handle_over_high();
2849 static inline int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2850 unsigned int nr_pages)
2852 if (mem_cgroup_is_root(memcg))
2855 return try_charge_memcg(memcg, gfp_mask, nr_pages);
2858 static inline void cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
2860 if (mem_cgroup_is_root(memcg))
2863 page_counter_uncharge(&memcg->memory, nr_pages);
2864 if (do_memsw_account())
2865 page_counter_uncharge(&memcg->memsw, nr_pages);
2868 static void commit_charge(struct folio *folio, struct mem_cgroup *memcg)
2870 VM_BUG_ON_FOLIO(folio_memcg(folio), folio);
2872 * Any of the following ensures page's memcg stability:
2876 * - lock_page_memcg()
2877 * - exclusive reference
2878 * - mem_cgroup_trylock_pages()
2880 folio->memcg_data = (unsigned long)memcg;
2883 #ifdef CONFIG_MEMCG_KMEM
2885 * The allocated objcg pointers array is not accounted directly.
2886 * Moreover, it should not come from DMA buffer and is not readily
2887 * reclaimable. So those GFP bits should be masked off.
2889 #define OBJCGS_CLEAR_MASK (__GFP_DMA | __GFP_RECLAIMABLE | __GFP_ACCOUNT)
2892 * mod_objcg_mlstate() may be called with irq enabled, so
2893 * mod_memcg_lruvec_state() should be used.
2895 static inline void mod_objcg_mlstate(struct obj_cgroup *objcg,
2896 struct pglist_data *pgdat,
2897 enum node_stat_item idx, int nr)
2899 struct mem_cgroup *memcg;
2900 struct lruvec *lruvec;
2903 memcg = obj_cgroup_memcg(objcg);
2904 lruvec = mem_cgroup_lruvec(memcg, pgdat);
2905 mod_memcg_lruvec_state(lruvec, idx, nr);
2909 int memcg_alloc_slab_cgroups(struct slab *slab, struct kmem_cache *s,
2910 gfp_t gfp, bool new_slab)
2912 unsigned int objects = objs_per_slab(s, slab);
2913 unsigned long memcg_data;
2916 gfp &= ~OBJCGS_CLEAR_MASK;
2917 vec = kcalloc_node(objects, sizeof(struct obj_cgroup *), gfp,
2922 memcg_data = (unsigned long) vec | MEMCG_DATA_OBJCGS;
2925 * If the slab is brand new and nobody can yet access its
2926 * memcg_data, no synchronization is required and memcg_data can
2927 * be simply assigned.
2929 slab->memcg_data = memcg_data;
2930 } else if (cmpxchg(&slab->memcg_data, 0, memcg_data)) {
2932 * If the slab is already in use, somebody can allocate and
2933 * assign obj_cgroups in parallel. In this case the existing
2934 * objcg vector should be reused.
2940 kmemleak_not_leak(vec);
2944 static __always_inline
2945 struct mem_cgroup *mem_cgroup_from_obj_folio(struct folio *folio, void *p)
2948 * Slab objects are accounted individually, not per-page.
2949 * Memcg membership data for each individual object is saved in
2952 if (folio_test_slab(folio)) {
2953 struct obj_cgroup **objcgs;
2957 slab = folio_slab(folio);
2958 objcgs = slab_objcgs(slab);
2962 off = obj_to_index(slab->slab_cache, slab, p);
2964 return obj_cgroup_memcg(objcgs[off]);
2970 * folio_memcg_check() is used here, because in theory we can encounter
2971 * a folio where the slab flag has been cleared already, but
2972 * slab->memcg_data has not been freed yet
2973 * folio_memcg_check() will guarantee that a proper memory
2974 * cgroup pointer or NULL will be returned.
2976 return folio_memcg_check(folio);
2980 * Returns a pointer to the memory cgroup to which the kernel object is charged.
2982 * A passed kernel object can be a slab object, vmalloc object or a generic
2983 * kernel page, so different mechanisms for getting the memory cgroup pointer
2986 * In certain cases (e.g. kernel stacks or large kmallocs with SLUB) the caller
2987 * can not know for sure how the kernel object is implemented.
2988 * mem_cgroup_from_obj() can be safely used in such cases.
2990 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
2991 * cgroup_mutex, etc.
2993 struct mem_cgroup *mem_cgroup_from_obj(void *p)
2995 struct folio *folio;
2997 if (mem_cgroup_disabled())
3000 if (unlikely(is_vmalloc_addr(p)))
3001 folio = page_folio(vmalloc_to_page(p));
3003 folio = virt_to_folio(p);
3005 return mem_cgroup_from_obj_folio(folio, p);
3009 * Returns a pointer to the memory cgroup to which the kernel object is charged.
3010 * Similar to mem_cgroup_from_obj(), but faster and not suitable for objects,
3011 * allocated using vmalloc().
3013 * A passed kernel object must be a slab object or a generic kernel page.
3015 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
3016 * cgroup_mutex, etc.
3018 struct mem_cgroup *mem_cgroup_from_slab_obj(void *p)
3020 if (mem_cgroup_disabled())
3023 return mem_cgroup_from_obj_folio(virt_to_folio(p), p);
3026 static struct obj_cgroup *__get_obj_cgroup_from_memcg(struct mem_cgroup *memcg)
3028 struct obj_cgroup *objcg = NULL;
3030 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
3031 objcg = rcu_dereference(memcg->objcg);
3032 if (objcg && obj_cgroup_tryget(objcg))
3039 __always_inline struct obj_cgroup *get_obj_cgroup_from_current(void)
3041 struct obj_cgroup *objcg = NULL;
3042 struct mem_cgroup *memcg;
3044 if (memcg_kmem_bypass())
3048 if (unlikely(active_memcg()))
3049 memcg = active_memcg();
3051 memcg = mem_cgroup_from_task(current);
3052 objcg = __get_obj_cgroup_from_memcg(memcg);
3057 struct obj_cgroup *get_obj_cgroup_from_page(struct page *page)
3059 struct obj_cgroup *objcg;
3061 if (!memcg_kmem_online())
3064 if (PageMemcgKmem(page)) {
3065 objcg = __folio_objcg(page_folio(page));
3066 obj_cgroup_get(objcg);
3068 struct mem_cgroup *memcg;
3071 memcg = __folio_memcg(page_folio(page));
3073 objcg = __get_obj_cgroup_from_memcg(memcg);
3081 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages)
3083 mod_memcg_state(memcg, MEMCG_KMEM, nr_pages);
3084 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
3086 page_counter_charge(&memcg->kmem, nr_pages);
3088 page_counter_uncharge(&memcg->kmem, -nr_pages);
3094 * obj_cgroup_uncharge_pages: uncharge a number of kernel pages from a objcg
3095 * @objcg: object cgroup to uncharge
3096 * @nr_pages: number of pages to uncharge
3098 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
3099 unsigned int nr_pages)
3101 struct mem_cgroup *memcg;
3103 memcg = get_mem_cgroup_from_objcg(objcg);
3105 memcg_account_kmem(memcg, -nr_pages);
3106 refill_stock(memcg, nr_pages);
3108 css_put(&memcg->css);
3112 * obj_cgroup_charge_pages: charge a number of kernel pages to a objcg
3113 * @objcg: object cgroup to charge
3114 * @gfp: reclaim mode
3115 * @nr_pages: number of pages to charge
3117 * Returns 0 on success, an error code on failure.
3119 static int obj_cgroup_charge_pages(struct obj_cgroup *objcg, gfp_t gfp,
3120 unsigned int nr_pages)
3122 struct mem_cgroup *memcg;
3125 memcg = get_mem_cgroup_from_objcg(objcg);
3127 ret = try_charge_memcg(memcg, gfp, nr_pages);
3131 memcg_account_kmem(memcg, nr_pages);
3133 css_put(&memcg->css);
3139 * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup
3140 * @page: page to charge
3141 * @gfp: reclaim mode
3142 * @order: allocation order
3144 * Returns 0 on success, an error code on failure.
3146 int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
3148 struct obj_cgroup *objcg;
3151 objcg = get_obj_cgroup_from_current();
3153 ret = obj_cgroup_charge_pages(objcg, gfp, 1 << order);
3155 page->memcg_data = (unsigned long)objcg |
3159 obj_cgroup_put(objcg);
3165 * __memcg_kmem_uncharge_page: uncharge a kmem page
3166 * @page: page to uncharge
3167 * @order: allocation order
3169 void __memcg_kmem_uncharge_page(struct page *page, int order)
3171 struct folio *folio = page_folio(page);
3172 struct obj_cgroup *objcg;
3173 unsigned int nr_pages = 1 << order;
3175 if (!folio_memcg_kmem(folio))
3178 objcg = __folio_objcg(folio);
3179 obj_cgroup_uncharge_pages(objcg, nr_pages);
3180 folio->memcg_data = 0;
3181 obj_cgroup_put(objcg);
3184 void mod_objcg_state(struct obj_cgroup *objcg, struct pglist_data *pgdat,
3185 enum node_stat_item idx, int nr)
3187 struct memcg_stock_pcp *stock;
3188 struct obj_cgroup *old = NULL;
3189 unsigned long flags;
3192 local_lock_irqsave(&memcg_stock.stock_lock, flags);
3193 stock = this_cpu_ptr(&memcg_stock);
3196 * Save vmstat data in stock and skip vmstat array update unless
3197 * accumulating over a page of vmstat data or when pgdat or idx
3200 if (READ_ONCE(stock->cached_objcg) != objcg) {
3201 old = drain_obj_stock(stock);
3202 obj_cgroup_get(objcg);
3203 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3204 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3205 WRITE_ONCE(stock->cached_objcg, objcg);
3206 stock->cached_pgdat = pgdat;
3207 } else if (stock->cached_pgdat != pgdat) {
3208 /* Flush the existing cached vmstat data */
3209 struct pglist_data *oldpg = stock->cached_pgdat;
3211 if (stock->nr_slab_reclaimable_b) {
3212 mod_objcg_mlstate(objcg, oldpg, NR_SLAB_RECLAIMABLE_B,
3213 stock->nr_slab_reclaimable_b);
3214 stock->nr_slab_reclaimable_b = 0;
3216 if (stock->nr_slab_unreclaimable_b) {
3217 mod_objcg_mlstate(objcg, oldpg, NR_SLAB_UNRECLAIMABLE_B,
3218 stock->nr_slab_unreclaimable_b);
3219 stock->nr_slab_unreclaimable_b = 0;
3221 stock->cached_pgdat = pgdat;
3224 bytes = (idx == NR_SLAB_RECLAIMABLE_B) ? &stock->nr_slab_reclaimable_b
3225 : &stock->nr_slab_unreclaimable_b;
3227 * Even for large object >= PAGE_SIZE, the vmstat data will still be
3228 * cached locally at least once before pushing it out.
3235 if (abs(*bytes) > PAGE_SIZE) {
3243 mod_objcg_mlstate(objcg, pgdat, idx, nr);
3245 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3247 obj_cgroup_put(old);
3250 static bool consume_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes)
3252 struct memcg_stock_pcp *stock;
3253 unsigned long flags;
3256 local_lock_irqsave(&memcg_stock.stock_lock, flags);
3258 stock = this_cpu_ptr(&memcg_stock);
3259 if (objcg == READ_ONCE(stock->cached_objcg) && stock->nr_bytes >= nr_bytes) {
3260 stock->nr_bytes -= nr_bytes;
3264 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3269 static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock)
3271 struct obj_cgroup *old = READ_ONCE(stock->cached_objcg);
3276 if (stock->nr_bytes) {
3277 unsigned int nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3278 unsigned int nr_bytes = stock->nr_bytes & (PAGE_SIZE - 1);
3281 struct mem_cgroup *memcg;
3283 memcg = get_mem_cgroup_from_objcg(old);
3285 memcg_account_kmem(memcg, -nr_pages);
3286 __refill_stock(memcg, nr_pages);
3288 css_put(&memcg->css);
3292 * The leftover is flushed to the centralized per-memcg value.
3293 * On the next attempt to refill obj stock it will be moved
3294 * to a per-cpu stock (probably, on an other CPU), see
3295 * refill_obj_stock().
3297 * How often it's flushed is a trade-off between the memory
3298 * limit enforcement accuracy and potential CPU contention,
3299 * so it might be changed in the future.
3301 atomic_add(nr_bytes, &old->nr_charged_bytes);
3302 stock->nr_bytes = 0;
3306 * Flush the vmstat data in current stock
3308 if (stock->nr_slab_reclaimable_b || stock->nr_slab_unreclaimable_b) {
3309 if (stock->nr_slab_reclaimable_b) {
3310 mod_objcg_mlstate(old, stock->cached_pgdat,
3311 NR_SLAB_RECLAIMABLE_B,
3312 stock->nr_slab_reclaimable_b);
3313 stock->nr_slab_reclaimable_b = 0;
3315 if (stock->nr_slab_unreclaimable_b) {
3316 mod_objcg_mlstate(old, stock->cached_pgdat,
3317 NR_SLAB_UNRECLAIMABLE_B,
3318 stock->nr_slab_unreclaimable_b);
3319 stock->nr_slab_unreclaimable_b = 0;
3321 stock->cached_pgdat = NULL;
3324 WRITE_ONCE(stock->cached_objcg, NULL);
3326 * The `old' objects needs to be released by the caller via
3327 * obj_cgroup_put() outside of memcg_stock_pcp::stock_lock.
3332 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
3333 struct mem_cgroup *root_memcg)
3335 struct obj_cgroup *objcg = READ_ONCE(stock->cached_objcg);
3336 struct mem_cgroup *memcg;
3339 memcg = obj_cgroup_memcg(objcg);
3340 if (memcg && mem_cgroup_is_descendant(memcg, root_memcg))
3347 static void refill_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes,
3348 bool allow_uncharge)
3350 struct memcg_stock_pcp *stock;
3351 struct obj_cgroup *old = NULL;
3352 unsigned long flags;
3353 unsigned int nr_pages = 0;
3355 local_lock_irqsave(&memcg_stock.stock_lock, flags);
3357 stock = this_cpu_ptr(&memcg_stock);
3358 if (READ_ONCE(stock->cached_objcg) != objcg) { /* reset if necessary */
3359 old = drain_obj_stock(stock);
3360 obj_cgroup_get(objcg);
3361 WRITE_ONCE(stock->cached_objcg, objcg);
3362 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3363 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3364 allow_uncharge = true; /* Allow uncharge when objcg changes */
3366 stock->nr_bytes += nr_bytes;
3368 if (allow_uncharge && (stock->nr_bytes > PAGE_SIZE)) {
3369 nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3370 stock->nr_bytes &= (PAGE_SIZE - 1);
3373 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3375 obj_cgroup_put(old);
3378 obj_cgroup_uncharge_pages(objcg, nr_pages);
3381 int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size)
3383 unsigned int nr_pages, nr_bytes;
3386 if (consume_obj_stock(objcg, size))
3390 * In theory, objcg->nr_charged_bytes can have enough
3391 * pre-charged bytes to satisfy the allocation. However,
3392 * flushing objcg->nr_charged_bytes requires two atomic
3393 * operations, and objcg->nr_charged_bytes can't be big.
3394 * The shared objcg->nr_charged_bytes can also become a
3395 * performance bottleneck if all tasks of the same memcg are
3396 * trying to update it. So it's better to ignore it and try
3397 * grab some new pages. The stock's nr_bytes will be flushed to
3398 * objcg->nr_charged_bytes later on when objcg changes.
3400 * The stock's nr_bytes may contain enough pre-charged bytes
3401 * to allow one less page from being charged, but we can't rely
3402 * on the pre-charged bytes not being changed outside of
3403 * consume_obj_stock() or refill_obj_stock(). So ignore those
3404 * pre-charged bytes as well when charging pages. To avoid a
3405 * page uncharge right after a page charge, we set the
3406 * allow_uncharge flag to false when calling refill_obj_stock()
3407 * to temporarily allow the pre-charged bytes to exceed the page
3408 * size limit. The maximum reachable value of the pre-charged
3409 * bytes is (sizeof(object) + PAGE_SIZE - 2) if there is no data
3412 nr_pages = size >> PAGE_SHIFT;
3413 nr_bytes = size & (PAGE_SIZE - 1);
3418 ret = obj_cgroup_charge_pages(objcg, gfp, nr_pages);
3419 if (!ret && nr_bytes)
3420 refill_obj_stock(objcg, PAGE_SIZE - nr_bytes, false);
3425 void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size)
3427 refill_obj_stock(objcg, size, true);
3430 #endif /* CONFIG_MEMCG_KMEM */
3433 * Because page_memcg(head) is not set on tails, set it now.
3435 void split_page_memcg(struct page *head, unsigned int nr)
3437 struct folio *folio = page_folio(head);
3438 struct mem_cgroup *memcg = folio_memcg(folio);
3441 if (mem_cgroup_disabled() || !memcg)
3444 for (i = 1; i < nr; i++)
3445 folio_page(folio, i)->memcg_data = folio->memcg_data;
3447 if (folio_memcg_kmem(folio))
3448 obj_cgroup_get_many(__folio_objcg(folio), nr - 1);
3450 css_get_many(&memcg->css, nr - 1);
3455 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3456 * @entry: swap entry to be moved
3457 * @from: mem_cgroup which the entry is moved from
3458 * @to: mem_cgroup which the entry is moved to
3460 * It succeeds only when the swap_cgroup's record for this entry is the same
3461 * as the mem_cgroup's id of @from.
3463 * Returns 0 on success, -EINVAL on failure.
3465 * The caller must have charged to @to, IOW, called page_counter_charge() about
3466 * both res and memsw, and called css_get().
3468 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3469 struct mem_cgroup *from, struct mem_cgroup *to)
3471 unsigned short old_id, new_id;
3473 old_id = mem_cgroup_id(from);
3474 new_id = mem_cgroup_id(to);
3476 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3477 mod_memcg_state(from, MEMCG_SWAP, -1);
3478 mod_memcg_state(to, MEMCG_SWAP, 1);
3484 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3485 struct mem_cgroup *from, struct mem_cgroup *to)
3491 static DEFINE_MUTEX(memcg_max_mutex);
3493 static int mem_cgroup_resize_max(struct mem_cgroup *memcg,
3494 unsigned long max, bool memsw)
3496 bool enlarge = false;
3497 bool drained = false;
3499 bool limits_invariant;
3500 struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory;
3503 if (signal_pending(current)) {
3508 mutex_lock(&memcg_max_mutex);
3510 * Make sure that the new limit (memsw or memory limit) doesn't
3511 * break our basic invariant rule memory.max <= memsw.max.
3513 limits_invariant = memsw ? max >= READ_ONCE(memcg->memory.max) :
3514 max <= memcg->memsw.max;
3515 if (!limits_invariant) {
3516 mutex_unlock(&memcg_max_mutex);
3520 if (max > counter->max)
3522 ret = page_counter_set_max(counter, max);
3523 mutex_unlock(&memcg_max_mutex);
3529 drain_all_stock(memcg);
3534 if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,
3535 memsw ? 0 : MEMCG_RECLAIM_MAY_SWAP)) {
3541 if (!ret && enlarge)
3542 memcg_oom_recover(memcg);
3547 unsigned long mem_cgroup_soft_limit_reclaim(pg_data_t *pgdat, int order,
3549 unsigned long *total_scanned)
3551 unsigned long nr_reclaimed = 0;
3552 struct mem_cgroup_per_node *mz, *next_mz = NULL;
3553 unsigned long reclaimed;
3555 struct mem_cgroup_tree_per_node *mctz;
3556 unsigned long excess;
3558 if (lru_gen_enabled())
3564 mctz = soft_limit_tree.rb_tree_per_node[pgdat->node_id];
3567 * Do not even bother to check the largest node if the root
3568 * is empty. Do it lockless to prevent lock bouncing. Races
3569 * are acceptable as soft limit is best effort anyway.
3571 if (!mctz || RB_EMPTY_ROOT(&mctz->rb_root))
3575 * This loop can run a while, specially if mem_cgroup's continuously
3576 * keep exceeding their soft limit and putting the system under
3583 mz = mem_cgroup_largest_soft_limit_node(mctz);
3587 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, pgdat,
3588 gfp_mask, total_scanned);
3589 nr_reclaimed += reclaimed;
3590 spin_lock_irq(&mctz->lock);
3593 * If we failed to reclaim anything from this memory cgroup
3594 * it is time to move on to the next cgroup
3598 next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
3600 excess = soft_limit_excess(mz->memcg);
3602 * One school of thought says that we should not add
3603 * back the node to the tree if reclaim returns 0.
3604 * But our reclaim could return 0, simply because due
3605 * to priority we are exposing a smaller subset of
3606 * memory to reclaim from. Consider this as a longer
3609 /* If excess == 0, no tree ops */
3610 __mem_cgroup_insert_exceeded(mz, mctz, excess);
3611 spin_unlock_irq(&mctz->lock);
3612 css_put(&mz->memcg->css);
3615 * Could not reclaim anything and there are no more
3616 * mem cgroups to try or we seem to be looping without
3617 * reclaiming anything.
3619 if (!nr_reclaimed &&
3621 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3623 } while (!nr_reclaimed);
3625 css_put(&next_mz->memcg->css);
3626 return nr_reclaimed;
3630 * Reclaims as many pages from the given memcg as possible.
3632 * Caller is responsible for holding css reference for memcg.
3634 static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
3636 int nr_retries = MAX_RECLAIM_RETRIES;
3638 /* we call try-to-free pages for make this cgroup empty */
3639 lru_add_drain_all();
3641 drain_all_stock(memcg);
3643 /* try to free all pages in this cgroup */
3644 while (nr_retries && page_counter_read(&memcg->memory)) {
3645 if (signal_pending(current))
3648 if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,
3649 MEMCG_RECLAIM_MAY_SWAP))
3656 static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
3657 char *buf, size_t nbytes,
3660 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3662 if (mem_cgroup_is_root(memcg))
3664 return mem_cgroup_force_empty(memcg) ?: nbytes;
3667 static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
3673 static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
3674 struct cftype *cft, u64 val)
3679 pr_warn_once("Non-hierarchical mode is deprecated. "
3680 "Please report your usecase to linux-mm@kvack.org if you "
3681 "depend on this functionality.\n");
3686 static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3690 if (mem_cgroup_is_root(memcg)) {
3692 * Approximate root's usage from global state. This isn't
3693 * perfect, but the root usage was always an approximation.
3695 val = global_node_page_state(NR_FILE_PAGES) +
3696 global_node_page_state(NR_ANON_MAPPED);
3698 val += total_swap_pages - get_nr_swap_pages();
3701 val = page_counter_read(&memcg->memory);
3703 val = page_counter_read(&memcg->memsw);
3716 static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
3719 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3720 struct page_counter *counter;
3722 switch (MEMFILE_TYPE(cft->private)) {
3724 counter = &memcg->memory;
3727 counter = &memcg->memsw;
3730 counter = &memcg->kmem;
3733 counter = &memcg->tcpmem;
3739 switch (MEMFILE_ATTR(cft->private)) {
3741 if (counter == &memcg->memory)
3742 return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
3743 if (counter == &memcg->memsw)
3744 return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
3745 return (u64)page_counter_read(counter) * PAGE_SIZE;
3747 return (u64)counter->max * PAGE_SIZE;
3749 return (u64)counter->watermark * PAGE_SIZE;
3751 return counter->failcnt;
3752 case RES_SOFT_LIMIT:
3753 return (u64)READ_ONCE(memcg->soft_limit) * PAGE_SIZE;
3760 * This function doesn't do anything useful. Its only job is to provide a read
3761 * handler for a file so that cgroup_file_mode() will add read permissions.
3763 static int mem_cgroup_dummy_seq_show(__always_unused struct seq_file *m,
3764 __always_unused void *v)
3769 #ifdef CONFIG_MEMCG_KMEM
3770 static int memcg_online_kmem(struct mem_cgroup *memcg)
3772 struct obj_cgroup *objcg;
3774 if (mem_cgroup_kmem_disabled())
3777 if (unlikely(mem_cgroup_is_root(memcg)))
3780 objcg = obj_cgroup_alloc();
3784 objcg->memcg = memcg;
3785 rcu_assign_pointer(memcg->objcg, objcg);
3787 static_branch_enable(&memcg_kmem_online_key);
3789 memcg->kmemcg_id = memcg->id.id;
3794 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3796 struct mem_cgroup *parent;
3798 if (mem_cgroup_kmem_disabled())
3801 if (unlikely(mem_cgroup_is_root(memcg)))
3804 parent = parent_mem_cgroup(memcg);
3806 parent = root_mem_cgroup;
3808 memcg_reparent_objcgs(memcg, parent);
3811 * After we have finished memcg_reparent_objcgs(), all list_lrus
3812 * corresponding to this cgroup are guaranteed to remain empty.
3813 * The ordering is imposed by list_lru_node->lock taken by
3814 * memcg_reparent_list_lrus().
3816 memcg_reparent_list_lrus(memcg, parent);
3819 static int memcg_online_kmem(struct mem_cgroup *memcg)
3823 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3826 #endif /* CONFIG_MEMCG_KMEM */
3828 static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max)
3832 mutex_lock(&memcg_max_mutex);
3834 ret = page_counter_set_max(&memcg->tcpmem, max);
3838 if (!memcg->tcpmem_active) {
3840 * The active flag needs to be written after the static_key
3841 * update. This is what guarantees that the socket activation
3842 * function is the last one to run. See mem_cgroup_sk_alloc()
3843 * for details, and note that we don't mark any socket as
3844 * belonging to this memcg until that flag is up.
3846 * We need to do this, because static_keys will span multiple
3847 * sites, but we can't control their order. If we mark a socket
3848 * as accounted, but the accounting functions are not patched in
3849 * yet, we'll lose accounting.
3851 * We never race with the readers in mem_cgroup_sk_alloc(),
3852 * because when this value change, the code to process it is not
3855 static_branch_inc(&memcg_sockets_enabled_key);
3856 memcg->tcpmem_active = true;
3859 mutex_unlock(&memcg_max_mutex);
3864 * The user of this function is...
3867 static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
3868 char *buf, size_t nbytes, loff_t off)
3870 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3871 unsigned long nr_pages;
3874 buf = strstrip(buf);
3875 ret = page_counter_memparse(buf, "-1", &nr_pages);
3879 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3881 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3885 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3887 ret = mem_cgroup_resize_max(memcg, nr_pages, false);
3890 ret = mem_cgroup_resize_max(memcg, nr_pages, true);
3893 /* kmem.limit_in_bytes is deprecated. */
3897 ret = memcg_update_tcp_max(memcg, nr_pages);
3901 case RES_SOFT_LIMIT:
3902 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
3905 WRITE_ONCE(memcg->soft_limit, nr_pages);
3910 return ret ?: nbytes;
3913 static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
3914 size_t nbytes, loff_t off)
3916 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3917 struct page_counter *counter;
3919 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3921 counter = &memcg->memory;
3924 counter = &memcg->memsw;
3927 counter = &memcg->kmem;
3930 counter = &memcg->tcpmem;
3936 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3938 page_counter_reset_watermark(counter);
3941 counter->failcnt = 0;
3950 static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
3953 return mem_cgroup_from_css(css)->move_charge_at_immigrate;
3957 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3958 struct cftype *cft, u64 val)
3960 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3962 pr_warn_once("Cgroup memory moving (move_charge_at_immigrate) is deprecated. "
3963 "Please report your usecase to linux-mm@kvack.org if you "
3964 "depend on this functionality.\n");
3966 if (val & ~MOVE_MASK)
3970 * No kind of locking is needed in here, because ->can_attach() will
3971 * check this value once in the beginning of the process, and then carry
3972 * on with stale data. This means that changes to this value will only
3973 * affect task migrations starting after the change.
3975 memcg->move_charge_at_immigrate = val;
3979 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3980 struct cftype *cft, u64 val)
3988 #define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE))
3989 #define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON))
3990 #define LRU_ALL ((1 << NR_LRU_LISTS) - 1)
3992 static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
3993 int nid, unsigned int lru_mask, bool tree)
3995 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
3996 unsigned long nr = 0;
3999 VM_BUG_ON((unsigned)nid >= nr_node_ids);
4002 if (!(BIT(lru) & lru_mask))
4005 nr += lruvec_page_state(lruvec, NR_LRU_BASE + lru);
4007 nr += lruvec_page_state_local(lruvec, NR_LRU_BASE + lru);
4012 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
4013 unsigned int lru_mask,
4016 unsigned long nr = 0;
4020 if (!(BIT(lru) & lru_mask))
4023 nr += memcg_page_state(memcg, NR_LRU_BASE + lru);
4025 nr += memcg_page_state_local(memcg, NR_LRU_BASE + lru);
4030 static int memcg_numa_stat_show(struct seq_file *m, void *v)
4034 unsigned int lru_mask;
4037 static const struct numa_stat stats[] = {
4038 { "total", LRU_ALL },
4039 { "file", LRU_ALL_FILE },
4040 { "anon", LRU_ALL_ANON },
4041 { "unevictable", BIT(LRU_UNEVICTABLE) },
4043 const struct numa_stat *stat;
4045 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
4047 mem_cgroup_flush_stats();
4049 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
4050 seq_printf(m, "%s=%lu", stat->name,
4051 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
4053 for_each_node_state(nid, N_MEMORY)
4054 seq_printf(m, " N%d=%lu", nid,
4055 mem_cgroup_node_nr_lru_pages(memcg, nid,
4056 stat->lru_mask, false));
4060 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
4062 seq_printf(m, "hierarchical_%s=%lu", stat->name,
4063 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
4065 for_each_node_state(nid, N_MEMORY)
4066 seq_printf(m, " N%d=%lu", nid,
4067 mem_cgroup_node_nr_lru_pages(memcg, nid,
4068 stat->lru_mask, true));
4074 #endif /* CONFIG_NUMA */
4076 static const unsigned int memcg1_stats[] = {
4079 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4086 WORKINGSET_REFAULT_ANON,
4087 WORKINGSET_REFAULT_FILE,
4091 static const char *const memcg1_stat_names[] = {
4094 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4101 "workingset_refault_anon",
4102 "workingset_refault_file",
4106 /* Universal VM events cgroup1 shows, original sort order */
4107 static const unsigned int memcg1_events[] = {
4114 static void memcg1_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
4116 unsigned long memory, memsw;
4117 struct mem_cgroup *mi;
4120 BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats));
4122 mem_cgroup_flush_stats();
4124 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
4127 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
4129 nr = memcg_page_state_local(memcg, memcg1_stats[i]);
4130 seq_buf_printf(s, "%s %lu\n", memcg1_stat_names[i],
4131 nr * memcg_page_state_unit(memcg1_stats[i]));
4134 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
4135 seq_buf_printf(s, "%s %lu\n", vm_event_name(memcg1_events[i]),
4136 memcg_events_local(memcg, memcg1_events[i]));
4138 for (i = 0; i < NR_LRU_LISTS; i++)
4139 seq_buf_printf(s, "%s %lu\n", lru_list_name(i),
4140 memcg_page_state_local(memcg, NR_LRU_BASE + i) *
4143 /* Hierarchical information */
4144 memory = memsw = PAGE_COUNTER_MAX;
4145 for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
4146 memory = min(memory, READ_ONCE(mi->memory.max));
4147 memsw = min(memsw, READ_ONCE(mi->memsw.max));
4149 seq_buf_printf(s, "hierarchical_memory_limit %llu\n",
4150 (u64)memory * PAGE_SIZE);
4151 if (do_memsw_account())
4152 seq_buf_printf(s, "hierarchical_memsw_limit %llu\n",
4153 (u64)memsw * PAGE_SIZE);
4155 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
4158 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
4160 nr = memcg_page_state(memcg, memcg1_stats[i]);
4161 seq_buf_printf(s, "total_%s %llu\n", memcg1_stat_names[i],
4162 (u64)nr * memcg_page_state_unit(memcg1_stats[i]));
4165 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
4166 seq_buf_printf(s, "total_%s %llu\n",
4167 vm_event_name(memcg1_events[i]),
4168 (u64)memcg_events(memcg, memcg1_events[i]));
4170 for (i = 0; i < NR_LRU_LISTS; i++)
4171 seq_buf_printf(s, "total_%s %llu\n", lru_list_name(i),
4172 (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
4175 #ifdef CONFIG_DEBUG_VM
4178 struct mem_cgroup_per_node *mz;
4179 unsigned long anon_cost = 0;
4180 unsigned long file_cost = 0;
4182 for_each_online_pgdat(pgdat) {
4183 mz = memcg->nodeinfo[pgdat->node_id];
4185 anon_cost += mz->lruvec.anon_cost;
4186 file_cost += mz->lruvec.file_cost;
4188 seq_buf_printf(s, "anon_cost %lu\n", anon_cost);
4189 seq_buf_printf(s, "file_cost %lu\n", file_cost);
4194 static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
4197 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4199 return mem_cgroup_swappiness(memcg);
4202 static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
4203 struct cftype *cft, u64 val)
4205 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4210 if (!mem_cgroup_is_root(memcg))
4211 WRITE_ONCE(memcg->swappiness, val);
4213 WRITE_ONCE(vm_swappiness, val);
4218 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4220 struct mem_cgroup_threshold_ary *t;
4221 unsigned long usage;
4226 t = rcu_dereference(memcg->thresholds.primary);
4228 t = rcu_dereference(memcg->memsw_thresholds.primary);
4233 usage = mem_cgroup_usage(memcg, swap);
4236 * current_threshold points to threshold just below or equal to usage.
4237 * If it's not true, a threshold was crossed after last
4238 * call of __mem_cgroup_threshold().
4240 i = t->current_threshold;
4243 * Iterate backward over array of thresholds starting from
4244 * current_threshold and check if a threshold is crossed.
4245 * If none of thresholds below usage is crossed, we read
4246 * only one element of the array here.
4248 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4249 eventfd_signal(t->entries[i].eventfd, 1);
4251 /* i = current_threshold + 1 */
4255 * Iterate forward over array of thresholds starting from
4256 * current_threshold+1 and check if a threshold is crossed.
4257 * If none of thresholds above usage is crossed, we read
4258 * only one element of the array here.
4260 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4261 eventfd_signal(t->entries[i].eventfd, 1);
4263 /* Update current_threshold */
4264 t->current_threshold = i - 1;
4269 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4272 __mem_cgroup_threshold(memcg, false);
4273 if (do_memsw_account())
4274 __mem_cgroup_threshold(memcg, true);
4276 memcg = parent_mem_cgroup(memcg);
4280 static int compare_thresholds(const void *a, const void *b)
4282 const struct mem_cgroup_threshold *_a = a;
4283 const struct mem_cgroup_threshold *_b = b;
4285 if (_a->threshold > _b->threshold)
4288 if (_a->threshold < _b->threshold)
4294 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
4296 struct mem_cgroup_eventfd_list *ev;
4298 spin_lock(&memcg_oom_lock);
4300 list_for_each_entry(ev, &memcg->oom_notify, list)
4301 eventfd_signal(ev->eventfd, 1);
4303 spin_unlock(&memcg_oom_lock);
4307 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
4309 struct mem_cgroup *iter;
4311 for_each_mem_cgroup_tree(iter, memcg)
4312 mem_cgroup_oom_notify_cb(iter);
4315 static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4316 struct eventfd_ctx *eventfd, const char *args, enum res_type type)
4318 struct mem_cgroup_thresholds *thresholds;
4319 struct mem_cgroup_threshold_ary *new;
4320 unsigned long threshold;
4321 unsigned long usage;
4324 ret = page_counter_memparse(args, "-1", &threshold);
4328 mutex_lock(&memcg->thresholds_lock);
4331 thresholds = &memcg->thresholds;
4332 usage = mem_cgroup_usage(memcg, false);
4333 } else if (type == _MEMSWAP) {
4334 thresholds = &memcg->memsw_thresholds;
4335 usage = mem_cgroup_usage(memcg, true);
4339 /* Check if a threshold crossed before adding a new one */
4340 if (thresholds->primary)
4341 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4343 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4345 /* Allocate memory for new array of thresholds */
4346 new = kmalloc(struct_size(new, entries, size), GFP_KERNEL);
4353 /* Copy thresholds (if any) to new array */
4354 if (thresholds->primary)
4355 memcpy(new->entries, thresholds->primary->entries,
4356 flex_array_size(new, entries, size - 1));
4358 /* Add new threshold */
4359 new->entries[size - 1].eventfd = eventfd;
4360 new->entries[size - 1].threshold = threshold;
4362 /* Sort thresholds. Registering of new threshold isn't time-critical */
4363 sort(new->entries, size, sizeof(*new->entries),
4364 compare_thresholds, NULL);
4366 /* Find current threshold */
4367 new->current_threshold = -1;
4368 for (i = 0; i < size; i++) {
4369 if (new->entries[i].threshold <= usage) {
4371 * new->current_threshold will not be used until
4372 * rcu_assign_pointer(), so it's safe to increment
4375 ++new->current_threshold;
4380 /* Free old spare buffer and save old primary buffer as spare */
4381 kfree(thresholds->spare);
4382 thresholds->spare = thresholds->primary;
4384 rcu_assign_pointer(thresholds->primary, new);
4386 /* To be sure that nobody uses thresholds */
4390 mutex_unlock(&memcg->thresholds_lock);
4395 static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4396 struct eventfd_ctx *eventfd, const char *args)
4398 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
4401 static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
4402 struct eventfd_ctx *eventfd, const char *args)
4404 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
4407 static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4408 struct eventfd_ctx *eventfd, enum res_type type)
4410 struct mem_cgroup_thresholds *thresholds;
4411 struct mem_cgroup_threshold_ary *new;
4412 unsigned long usage;
4413 int i, j, size, entries;
4415 mutex_lock(&memcg->thresholds_lock);
4418 thresholds = &memcg->thresholds;
4419 usage = mem_cgroup_usage(memcg, false);
4420 } else if (type == _MEMSWAP) {
4421 thresholds = &memcg->memsw_thresholds;
4422 usage = mem_cgroup_usage(memcg, true);
4426 if (!thresholds->primary)
4429 /* Check if a threshold crossed before removing */
4430 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4432 /* Calculate new number of threshold */
4434 for (i = 0; i < thresholds->primary->size; i++) {
4435 if (thresholds->primary->entries[i].eventfd != eventfd)
4441 new = thresholds->spare;
4443 /* If no items related to eventfd have been cleared, nothing to do */
4447 /* Set thresholds array to NULL if we don't have thresholds */
4456 /* Copy thresholds and find current threshold */
4457 new->current_threshold = -1;
4458 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4459 if (thresholds->primary->entries[i].eventfd == eventfd)
4462 new->entries[j] = thresholds->primary->entries[i];
4463 if (new->entries[j].threshold <= usage) {
4465 * new->current_threshold will not be used
4466 * until rcu_assign_pointer(), so it's safe to increment
4469 ++new->current_threshold;
4475 /* Swap primary and spare array */
4476 thresholds->spare = thresholds->primary;
4478 rcu_assign_pointer(thresholds->primary, new);
4480 /* To be sure that nobody uses thresholds */
4483 /* If all events are unregistered, free the spare array */
4485 kfree(thresholds->spare);
4486 thresholds->spare = NULL;
4489 mutex_unlock(&memcg->thresholds_lock);
4492 static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4493 struct eventfd_ctx *eventfd)
4495 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
4498 static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4499 struct eventfd_ctx *eventfd)
4501 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
4504 static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
4505 struct eventfd_ctx *eventfd, const char *args)
4507 struct mem_cgroup_eventfd_list *event;
4509 event = kmalloc(sizeof(*event), GFP_KERNEL);
4513 spin_lock(&memcg_oom_lock);
4515 event->eventfd = eventfd;
4516 list_add(&event->list, &memcg->oom_notify);
4518 /* already in OOM ? */
4519 if (memcg->under_oom)
4520 eventfd_signal(eventfd, 1);
4521 spin_unlock(&memcg_oom_lock);
4526 static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
4527 struct eventfd_ctx *eventfd)
4529 struct mem_cgroup_eventfd_list *ev, *tmp;
4531 spin_lock(&memcg_oom_lock);
4533 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
4534 if (ev->eventfd == eventfd) {
4535 list_del(&ev->list);
4540 spin_unlock(&memcg_oom_lock);
4543 static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
4545 struct mem_cgroup *memcg = mem_cgroup_from_seq(sf);
4547 seq_printf(sf, "oom_kill_disable %d\n", READ_ONCE(memcg->oom_kill_disable));
4548 seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
4549 seq_printf(sf, "oom_kill %lu\n",
4550 atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
4554 static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
4555 struct cftype *cft, u64 val)
4557 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4559 /* cannot set to root cgroup and only 0 and 1 are allowed */
4560 if (mem_cgroup_is_root(memcg) || !((val == 0) || (val == 1)))
4563 WRITE_ONCE(memcg->oom_kill_disable, val);
4565 memcg_oom_recover(memcg);
4570 #ifdef CONFIG_CGROUP_WRITEBACK
4572 #include <trace/events/writeback.h>
4574 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4576 return wb_domain_init(&memcg->cgwb_domain, gfp);
4579 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4581 wb_domain_exit(&memcg->cgwb_domain);
4584 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4586 wb_domain_size_changed(&memcg->cgwb_domain);
4589 struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
4591 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4593 if (!memcg->css.parent)
4596 return &memcg->cgwb_domain;
4600 * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
4601 * @wb: bdi_writeback in question
4602 * @pfilepages: out parameter for number of file pages
4603 * @pheadroom: out parameter for number of allocatable pages according to memcg
4604 * @pdirty: out parameter for number of dirty pages
4605 * @pwriteback: out parameter for number of pages under writeback
4607 * Determine the numbers of file, headroom, dirty, and writeback pages in
4608 * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom
4609 * is a bit more involved.
4611 * A memcg's headroom is "min(max, high) - used". In the hierarchy, the
4612 * headroom is calculated as the lowest headroom of itself and the
4613 * ancestors. Note that this doesn't consider the actual amount of
4614 * available memory in the system. The caller should further cap
4615 * *@pheadroom accordingly.
4617 void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
4618 unsigned long *pheadroom, unsigned long *pdirty,
4619 unsigned long *pwriteback)
4621 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4622 struct mem_cgroup *parent;
4624 mem_cgroup_flush_stats();
4626 *pdirty = memcg_page_state(memcg, NR_FILE_DIRTY);
4627 *pwriteback = memcg_page_state(memcg, NR_WRITEBACK);
4628 *pfilepages = memcg_page_state(memcg, NR_INACTIVE_FILE) +
4629 memcg_page_state(memcg, NR_ACTIVE_FILE);
4631 *pheadroom = PAGE_COUNTER_MAX;
4632 while ((parent = parent_mem_cgroup(memcg))) {
4633 unsigned long ceiling = min(READ_ONCE(memcg->memory.max),
4634 READ_ONCE(memcg->memory.high));
4635 unsigned long used = page_counter_read(&memcg->memory);
4637 *pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
4643 * Foreign dirty flushing
4645 * There's an inherent mismatch between memcg and writeback. The former
4646 * tracks ownership per-page while the latter per-inode. This was a
4647 * deliberate design decision because honoring per-page ownership in the
4648 * writeback path is complicated, may lead to higher CPU and IO overheads
4649 * and deemed unnecessary given that write-sharing an inode across
4650 * different cgroups isn't a common use-case.
4652 * Combined with inode majority-writer ownership switching, this works well
4653 * enough in most cases but there are some pathological cases. For
4654 * example, let's say there are two cgroups A and B which keep writing to
4655 * different but confined parts of the same inode. B owns the inode and
4656 * A's memory is limited far below B's. A's dirty ratio can rise enough to
4657 * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
4658 * triggering background writeback. A will be slowed down without a way to
4659 * make writeback of the dirty pages happen.
4661 * Conditions like the above can lead to a cgroup getting repeatedly and
4662 * severely throttled after making some progress after each
4663 * dirty_expire_interval while the underlying IO device is almost
4666 * Solving this problem completely requires matching the ownership tracking
4667 * granularities between memcg and writeback in either direction. However,
4668 * the more egregious behaviors can be avoided by simply remembering the
4669 * most recent foreign dirtying events and initiating remote flushes on
4670 * them when local writeback isn't enough to keep the memory clean enough.
4672 * The following two functions implement such mechanism. When a foreign
4673 * page - a page whose memcg and writeback ownerships don't match - is
4674 * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
4675 * bdi_writeback on the page owning memcg. When balance_dirty_pages()
4676 * decides that the memcg needs to sleep due to high dirty ratio, it calls
4677 * mem_cgroup_flush_foreign() which queues writeback on the recorded
4678 * foreign bdi_writebacks which haven't expired. Both the numbers of
4679 * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
4680 * limited to MEMCG_CGWB_FRN_CNT.
4682 * The mechanism only remembers IDs and doesn't hold any object references.
4683 * As being wrong occasionally doesn't matter, updates and accesses to the
4684 * records are lockless and racy.
4686 void mem_cgroup_track_foreign_dirty_slowpath(struct folio *folio,
4687 struct bdi_writeback *wb)
4689 struct mem_cgroup *memcg = folio_memcg(folio);
4690 struct memcg_cgwb_frn *frn;
4691 u64 now = get_jiffies_64();
4692 u64 oldest_at = now;
4696 trace_track_foreign_dirty(folio, wb);
4699 * Pick the slot to use. If there is already a slot for @wb, keep
4700 * using it. If not replace the oldest one which isn't being
4703 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4704 frn = &memcg->cgwb_frn[i];
4705 if (frn->bdi_id == wb->bdi->id &&
4706 frn->memcg_id == wb->memcg_css->id)
4708 if (time_before64(frn->at, oldest_at) &&
4709 atomic_read(&frn->done.cnt) == 1) {
4711 oldest_at = frn->at;
4715 if (i < MEMCG_CGWB_FRN_CNT) {
4717 * Re-using an existing one. Update timestamp lazily to
4718 * avoid making the cacheline hot. We want them to be
4719 * reasonably up-to-date and significantly shorter than
4720 * dirty_expire_interval as that's what expires the record.
4721 * Use the shorter of 1s and dirty_expire_interval / 8.
4723 unsigned long update_intv =
4724 min_t(unsigned long, HZ,
4725 msecs_to_jiffies(dirty_expire_interval * 10) / 8);
4727 if (time_before64(frn->at, now - update_intv))
4729 } else if (oldest >= 0) {
4730 /* replace the oldest free one */
4731 frn = &memcg->cgwb_frn[oldest];
4732 frn->bdi_id = wb->bdi->id;
4733 frn->memcg_id = wb->memcg_css->id;
4738 /* issue foreign writeback flushes for recorded foreign dirtying events */
4739 void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
4741 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4742 unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
4743 u64 now = jiffies_64;
4746 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4747 struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
4750 * If the record is older than dirty_expire_interval,
4751 * writeback on it has already started. No need to kick it
4752 * off again. Also, don't start a new one if there's
4753 * already one in flight.
4755 if (time_after64(frn->at, now - intv) &&
4756 atomic_read(&frn->done.cnt) == 1) {
4758 trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
4759 cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id,
4760 WB_REASON_FOREIGN_FLUSH,
4766 #else /* CONFIG_CGROUP_WRITEBACK */
4768 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4773 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4777 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4781 #endif /* CONFIG_CGROUP_WRITEBACK */
4784 * DO NOT USE IN NEW FILES.
4786 * "cgroup.event_control" implementation.
4788 * This is way over-engineered. It tries to support fully configurable
4789 * events for each user. Such level of flexibility is completely
4790 * unnecessary especially in the light of the planned unified hierarchy.
4792 * Please deprecate this and replace with something simpler if at all
4797 * Unregister event and free resources.
4799 * Gets called from workqueue.
4801 static void memcg_event_remove(struct work_struct *work)
4803 struct mem_cgroup_event *event =
4804 container_of(work, struct mem_cgroup_event, remove);
4805 struct mem_cgroup *memcg = event->memcg;
4807 remove_wait_queue(event->wqh, &event->wait);
4809 event->unregister_event(memcg, event->eventfd);
4811 /* Notify userspace the event is going away. */
4812 eventfd_signal(event->eventfd, 1);
4814 eventfd_ctx_put(event->eventfd);
4816 css_put(&memcg->css);
4820 * Gets called on EPOLLHUP on eventfd when user closes it.
4822 * Called with wqh->lock held and interrupts disabled.
4824 static int memcg_event_wake(wait_queue_entry_t *wait, unsigned mode,
4825 int sync, void *key)
4827 struct mem_cgroup_event *event =
4828 container_of(wait, struct mem_cgroup_event, wait);
4829 struct mem_cgroup *memcg = event->memcg;
4830 __poll_t flags = key_to_poll(key);
4832 if (flags & EPOLLHUP) {
4834 * If the event has been detached at cgroup removal, we
4835 * can simply return knowing the other side will cleanup
4838 * We can't race against event freeing since the other
4839 * side will require wqh->lock via remove_wait_queue(),
4842 spin_lock(&memcg->event_list_lock);
4843 if (!list_empty(&event->list)) {
4844 list_del_init(&event->list);
4846 * We are in atomic context, but cgroup_event_remove()
4847 * may sleep, so we have to call it in workqueue.
4849 schedule_work(&event->remove);
4851 spin_unlock(&memcg->event_list_lock);
4857 static void memcg_event_ptable_queue_proc(struct file *file,
4858 wait_queue_head_t *wqh, poll_table *pt)
4860 struct mem_cgroup_event *event =
4861 container_of(pt, struct mem_cgroup_event, pt);
4864 add_wait_queue(wqh, &event->wait);
4868 * DO NOT USE IN NEW FILES.
4870 * Parse input and register new cgroup event handler.
4872 * Input must be in format '<event_fd> <control_fd> <args>'.
4873 * Interpretation of args is defined by control file implementation.
4875 static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
4876 char *buf, size_t nbytes, loff_t off)
4878 struct cgroup_subsys_state *css = of_css(of);
4879 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4880 struct mem_cgroup_event *event;
4881 struct cgroup_subsys_state *cfile_css;
4882 unsigned int efd, cfd;
4885 struct dentry *cdentry;
4890 if (IS_ENABLED(CONFIG_PREEMPT_RT))
4893 buf = strstrip(buf);
4895 efd = simple_strtoul(buf, &endp, 10);
4900 cfd = simple_strtoul(buf, &endp, 10);
4901 if ((*endp != ' ') && (*endp != '\0'))
4905 event = kzalloc(sizeof(*event), GFP_KERNEL);
4909 event->memcg = memcg;
4910 INIT_LIST_HEAD(&event->list);
4911 init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
4912 init_waitqueue_func_entry(&event->wait, memcg_event_wake);
4913 INIT_WORK(&event->remove, memcg_event_remove);
4921 event->eventfd = eventfd_ctx_fileget(efile.file);
4922 if (IS_ERR(event->eventfd)) {
4923 ret = PTR_ERR(event->eventfd);
4930 goto out_put_eventfd;
4933 /* the process need read permission on control file */
4934 /* AV: shouldn't we check that it's been opened for read instead? */
4935 ret = file_permission(cfile.file, MAY_READ);
4940 * The control file must be a regular cgroup1 file. As a regular cgroup
4941 * file can't be renamed, it's safe to access its name afterwards.
4943 cdentry = cfile.file->f_path.dentry;
4944 if (cdentry->d_sb->s_type != &cgroup_fs_type || !d_is_reg(cdentry)) {
4950 * Determine the event callbacks and set them in @event. This used
4951 * to be done via struct cftype but cgroup core no longer knows
4952 * about these events. The following is crude but the whole thing
4953 * is for compatibility anyway.
4955 * DO NOT ADD NEW FILES.
4957 name = cdentry->d_name.name;
4959 if (!strcmp(name, "memory.usage_in_bytes")) {
4960 event->register_event = mem_cgroup_usage_register_event;
4961 event->unregister_event = mem_cgroup_usage_unregister_event;
4962 } else if (!strcmp(name, "memory.oom_control")) {
4963 event->register_event = mem_cgroup_oom_register_event;
4964 event->unregister_event = mem_cgroup_oom_unregister_event;
4965 } else if (!strcmp(name, "memory.pressure_level")) {
4966 event->register_event = vmpressure_register_event;
4967 event->unregister_event = vmpressure_unregister_event;
4968 } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
4969 event->register_event = memsw_cgroup_usage_register_event;
4970 event->unregister_event = memsw_cgroup_usage_unregister_event;
4977 * Verify @cfile should belong to @css. Also, remaining events are
4978 * automatically removed on cgroup destruction but the removal is
4979 * asynchronous, so take an extra ref on @css.
4981 cfile_css = css_tryget_online_from_dir(cdentry->d_parent,
4982 &memory_cgrp_subsys);
4984 if (IS_ERR(cfile_css))
4986 if (cfile_css != css) {
4991 ret = event->register_event(memcg, event->eventfd, buf);
4995 vfs_poll(efile.file, &event->pt);
4997 spin_lock_irq(&memcg->event_list_lock);
4998 list_add(&event->list, &memcg->event_list);
4999 spin_unlock_irq(&memcg->event_list_lock);
5011 eventfd_ctx_put(event->eventfd);
5020 #if defined(CONFIG_MEMCG_KMEM) && (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG))
5021 static int mem_cgroup_slab_show(struct seq_file *m, void *p)
5025 * Please, take a look at tools/cgroup/memcg_slabinfo.py .
5031 static int memory_stat_show(struct seq_file *m, void *v);
5033 static struct cftype mem_cgroup_legacy_files[] = {
5035 .name = "usage_in_bytes",
5036 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
5037 .read_u64 = mem_cgroup_read_u64,
5040 .name = "max_usage_in_bytes",
5041 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
5042 .write = mem_cgroup_reset,
5043 .read_u64 = mem_cgroup_read_u64,
5046 .name = "limit_in_bytes",
5047 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
5048 .write = mem_cgroup_write,
5049 .read_u64 = mem_cgroup_read_u64,
5052 .name = "soft_limit_in_bytes",
5053 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
5054 .write = mem_cgroup_write,
5055 .read_u64 = mem_cgroup_read_u64,
5059 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
5060 .write = mem_cgroup_reset,
5061 .read_u64 = mem_cgroup_read_u64,
5065 .seq_show = memory_stat_show,
5068 .name = "force_empty",
5069 .write = mem_cgroup_force_empty_write,
5072 .name = "use_hierarchy",
5073 .write_u64 = mem_cgroup_hierarchy_write,
5074 .read_u64 = mem_cgroup_hierarchy_read,
5077 .name = "cgroup.event_control", /* XXX: for compat */
5078 .write = memcg_write_event_control,
5079 .flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE,
5082 .name = "swappiness",
5083 .read_u64 = mem_cgroup_swappiness_read,
5084 .write_u64 = mem_cgroup_swappiness_write,
5087 .name = "move_charge_at_immigrate",
5088 .read_u64 = mem_cgroup_move_charge_read,
5089 .write_u64 = mem_cgroup_move_charge_write,
5092 .name = "oom_control",
5093 .seq_show = mem_cgroup_oom_control_read,
5094 .write_u64 = mem_cgroup_oom_control_write,
5097 .name = "pressure_level",
5098 .seq_show = mem_cgroup_dummy_seq_show,
5102 .name = "numa_stat",
5103 .seq_show = memcg_numa_stat_show,
5107 .name = "kmem.limit_in_bytes",
5108 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
5109 .write = mem_cgroup_write,
5110 .read_u64 = mem_cgroup_read_u64,
5113 .name = "kmem.usage_in_bytes",
5114 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
5115 .read_u64 = mem_cgroup_read_u64,
5118 .name = "kmem.failcnt",
5119 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
5120 .write = mem_cgroup_reset,
5121 .read_u64 = mem_cgroup_read_u64,
5124 .name = "kmem.max_usage_in_bytes",
5125 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
5126 .write = mem_cgroup_reset,
5127 .read_u64 = mem_cgroup_read_u64,
5129 #if defined(CONFIG_MEMCG_KMEM) && \
5130 (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG))
5132 .name = "kmem.slabinfo",
5133 .seq_show = mem_cgroup_slab_show,
5137 .name = "kmem.tcp.limit_in_bytes",
5138 .private = MEMFILE_PRIVATE(_TCP, RES_LIMIT),
5139 .write = mem_cgroup_write,
5140 .read_u64 = mem_cgroup_read_u64,
5143 .name = "kmem.tcp.usage_in_bytes",
5144 .private = MEMFILE_PRIVATE(_TCP, RES_USAGE),
5145 .read_u64 = mem_cgroup_read_u64,
5148 .name = "kmem.tcp.failcnt",
5149 .private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT),
5150 .write = mem_cgroup_reset,
5151 .read_u64 = mem_cgroup_read_u64,
5154 .name = "kmem.tcp.max_usage_in_bytes",
5155 .private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE),
5156 .write = mem_cgroup_reset,
5157 .read_u64 = mem_cgroup_read_u64,
5159 { }, /* terminate */
5163 * Private memory cgroup IDR
5165 * Swap-out records and page cache shadow entries need to store memcg
5166 * references in constrained space, so we maintain an ID space that is
5167 * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
5168 * memory-controlled cgroups to 64k.
5170 * However, there usually are many references to the offline CSS after
5171 * the cgroup has been destroyed, such as page cache or reclaimable
5172 * slab objects, that don't need to hang on to the ID. We want to keep
5173 * those dead CSS from occupying IDs, or we might quickly exhaust the
5174 * relatively small ID space and prevent the creation of new cgroups
5175 * even when there are much fewer than 64k cgroups - possibly none.
5177 * Maintain a private 16-bit ID space for memcg, and allow the ID to
5178 * be freed and recycled when it's no longer needed, which is usually
5179 * when the CSS is offlined.
5181 * The only exception to that are records of swapped out tmpfs/shmem
5182 * pages that need to be attributed to live ancestors on swapin. But
5183 * those references are manageable from userspace.
5186 static DEFINE_IDR(mem_cgroup_idr);
5188 static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
5190 if (memcg->id.id > 0) {
5191 idr_remove(&mem_cgroup_idr, memcg->id.id);
5196 static void __maybe_unused mem_cgroup_id_get_many(struct mem_cgroup *memcg,
5199 refcount_add(n, &memcg->id.ref);
5202 static void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
5204 if (refcount_sub_and_test(n, &memcg->id.ref)) {
5205 mem_cgroup_id_remove(memcg);
5207 /* Memcg ID pins CSS */
5208 css_put(&memcg->css);
5212 static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
5214 mem_cgroup_id_put_many(memcg, 1);
5218 * mem_cgroup_from_id - look up a memcg from a memcg id
5219 * @id: the memcg id to look up
5221 * Caller must hold rcu_read_lock().
5223 struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
5225 WARN_ON_ONCE(!rcu_read_lock_held());
5226 return idr_find(&mem_cgroup_idr, id);
5229 #ifdef CONFIG_SHRINKER_DEBUG
5230 struct mem_cgroup *mem_cgroup_get_from_ino(unsigned long ino)
5232 struct cgroup *cgrp;
5233 struct cgroup_subsys_state *css;
5234 struct mem_cgroup *memcg;
5236 cgrp = cgroup_get_from_id(ino);
5238 return ERR_CAST(cgrp);
5240 css = cgroup_get_e_css(cgrp, &memory_cgrp_subsys);
5242 memcg = container_of(css, struct mem_cgroup, css);
5244 memcg = ERR_PTR(-ENOENT);
5252 static int alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5254 struct mem_cgroup_per_node *pn;
5256 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, node);
5260 pn->lruvec_stats_percpu = alloc_percpu_gfp(struct lruvec_stats_percpu,
5261 GFP_KERNEL_ACCOUNT);
5262 if (!pn->lruvec_stats_percpu) {
5267 lruvec_init(&pn->lruvec);
5270 memcg->nodeinfo[node] = pn;
5274 static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5276 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
5281 free_percpu(pn->lruvec_stats_percpu);
5285 static void __mem_cgroup_free(struct mem_cgroup *memcg)
5290 free_mem_cgroup_per_node_info(memcg, node);
5291 kfree(memcg->vmstats);
5292 free_percpu(memcg->vmstats_percpu);
5296 static void mem_cgroup_free(struct mem_cgroup *memcg)
5298 lru_gen_exit_memcg(memcg);
5299 memcg_wb_domain_exit(memcg);
5300 __mem_cgroup_free(memcg);
5303 static struct mem_cgroup *mem_cgroup_alloc(void)
5305 struct mem_cgroup *memcg;
5307 int __maybe_unused i;
5308 long error = -ENOMEM;
5310 memcg = kzalloc(struct_size(memcg, nodeinfo, nr_node_ids), GFP_KERNEL);
5312 return ERR_PTR(error);
5314 memcg->id.id = idr_alloc(&mem_cgroup_idr, NULL,
5315 1, MEM_CGROUP_ID_MAX + 1, GFP_KERNEL);
5316 if (memcg->id.id < 0) {
5317 error = memcg->id.id;
5321 memcg->vmstats = kzalloc(sizeof(struct memcg_vmstats), GFP_KERNEL);
5322 if (!memcg->vmstats)
5325 memcg->vmstats_percpu = alloc_percpu_gfp(struct memcg_vmstats_percpu,
5326 GFP_KERNEL_ACCOUNT);
5327 if (!memcg->vmstats_percpu)
5331 if (alloc_mem_cgroup_per_node_info(memcg, node))
5334 if (memcg_wb_domain_init(memcg, GFP_KERNEL))
5337 INIT_WORK(&memcg->high_work, high_work_func);
5338 INIT_LIST_HEAD(&memcg->oom_notify);
5339 mutex_init(&memcg->thresholds_lock);
5340 spin_lock_init(&memcg->move_lock);
5341 vmpressure_init(&memcg->vmpressure);
5342 INIT_LIST_HEAD(&memcg->event_list);
5343 spin_lock_init(&memcg->event_list_lock);
5344 memcg->socket_pressure = jiffies;
5345 #ifdef CONFIG_MEMCG_KMEM
5346 memcg->kmemcg_id = -1;
5347 INIT_LIST_HEAD(&memcg->objcg_list);
5349 #ifdef CONFIG_CGROUP_WRITEBACK
5350 INIT_LIST_HEAD(&memcg->cgwb_list);
5351 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5352 memcg->cgwb_frn[i].done =
5353 __WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
5355 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5356 spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
5357 INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
5358 memcg->deferred_split_queue.split_queue_len = 0;
5360 idr_replace(&mem_cgroup_idr, memcg, memcg->id.id);
5361 lru_gen_init_memcg(memcg);
5364 mem_cgroup_id_remove(memcg);
5365 __mem_cgroup_free(memcg);
5366 return ERR_PTR(error);
5369 static struct cgroup_subsys_state * __ref
5370 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
5372 struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
5373 struct mem_cgroup *memcg, *old_memcg;
5375 old_memcg = set_active_memcg(parent);
5376 memcg = mem_cgroup_alloc();
5377 set_active_memcg(old_memcg);
5379 return ERR_CAST(memcg);
5381 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5382 WRITE_ONCE(memcg->soft_limit, PAGE_COUNTER_MAX);
5383 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
5384 memcg->zswap_max = PAGE_COUNTER_MAX;
5386 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5388 WRITE_ONCE(memcg->swappiness, mem_cgroup_swappiness(parent));
5389 WRITE_ONCE(memcg->oom_kill_disable, READ_ONCE(parent->oom_kill_disable));
5391 page_counter_init(&memcg->memory, &parent->memory);
5392 page_counter_init(&memcg->swap, &parent->swap);
5393 page_counter_init(&memcg->kmem, &parent->kmem);
5394 page_counter_init(&memcg->tcpmem, &parent->tcpmem);
5396 init_memcg_events();
5397 page_counter_init(&memcg->memory, NULL);
5398 page_counter_init(&memcg->swap, NULL);
5399 page_counter_init(&memcg->kmem, NULL);
5400 page_counter_init(&memcg->tcpmem, NULL);
5402 root_mem_cgroup = memcg;
5406 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5407 static_branch_inc(&memcg_sockets_enabled_key);
5409 #if defined(CONFIG_MEMCG_KMEM)
5410 if (!cgroup_memory_nobpf)
5411 static_branch_inc(&memcg_bpf_enabled_key);
5417 static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
5419 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5421 if (memcg_online_kmem(memcg))
5425 * A memcg must be visible for expand_shrinker_info()
5426 * by the time the maps are allocated. So, we allocate maps
5427 * here, when for_each_mem_cgroup() can't skip it.
5429 if (alloc_shrinker_info(memcg))
5432 /* Online state pins memcg ID, memcg ID pins CSS */
5433 refcount_set(&memcg->id.ref, 1);
5436 if (unlikely(mem_cgroup_is_root(memcg)))
5437 queue_delayed_work(system_unbound_wq, &stats_flush_dwork,
5439 lru_gen_online_memcg(memcg);
5442 memcg_offline_kmem(memcg);
5444 mem_cgroup_id_remove(memcg);
5448 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
5450 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5451 struct mem_cgroup_event *event, *tmp;
5454 * Unregister events and notify userspace.
5455 * Notify userspace about cgroup removing only after rmdir of cgroup
5456 * directory to avoid race between userspace and kernelspace.
5458 spin_lock_irq(&memcg->event_list_lock);
5459 list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
5460 list_del_init(&event->list);
5461 schedule_work(&event->remove);
5463 spin_unlock_irq(&memcg->event_list_lock);
5465 page_counter_set_min(&memcg->memory, 0);
5466 page_counter_set_low(&memcg->memory, 0);
5468 memcg_offline_kmem(memcg);
5469 reparent_shrinker_deferred(memcg);
5470 wb_memcg_offline(memcg);
5471 lru_gen_offline_memcg(memcg);
5473 drain_all_stock(memcg);
5475 mem_cgroup_id_put(memcg);
5478 static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
5480 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5482 invalidate_reclaim_iterators(memcg);
5483 lru_gen_release_memcg(memcg);
5486 static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
5488 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5489 int __maybe_unused i;
5491 #ifdef CONFIG_CGROUP_WRITEBACK
5492 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5493 wb_wait_for_completion(&memcg->cgwb_frn[i].done);
5495 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5496 static_branch_dec(&memcg_sockets_enabled_key);
5498 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg->tcpmem_active)
5499 static_branch_dec(&memcg_sockets_enabled_key);
5501 #if defined(CONFIG_MEMCG_KMEM)
5502 if (!cgroup_memory_nobpf)
5503 static_branch_dec(&memcg_bpf_enabled_key);
5506 vmpressure_cleanup(&memcg->vmpressure);
5507 cancel_work_sync(&memcg->high_work);
5508 mem_cgroup_remove_from_trees(memcg);
5509 free_shrinker_info(memcg);
5510 mem_cgroup_free(memcg);
5514 * mem_cgroup_css_reset - reset the states of a mem_cgroup
5515 * @css: the target css
5517 * Reset the states of the mem_cgroup associated with @css. This is
5518 * invoked when the userland requests disabling on the default hierarchy
5519 * but the memcg is pinned through dependency. The memcg should stop
5520 * applying policies and should revert to the vanilla state as it may be
5521 * made visible again.
5523 * The current implementation only resets the essential configurations.
5524 * This needs to be expanded to cover all the visible parts.
5526 static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
5528 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5530 page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
5531 page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
5532 page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
5533 page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
5534 page_counter_set_min(&memcg->memory, 0);
5535 page_counter_set_low(&memcg->memory, 0);
5536 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5537 WRITE_ONCE(memcg->soft_limit, PAGE_COUNTER_MAX);
5538 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5539 memcg_wb_domain_size_changed(memcg);
5542 static void mem_cgroup_css_rstat_flush(struct cgroup_subsys_state *css, int cpu)
5544 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5545 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
5546 struct memcg_vmstats_percpu *statc;
5550 statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
5552 for (i = 0; i < MEMCG_NR_STAT; i++) {
5554 * Collect the aggregated propagation counts of groups
5555 * below us. We're in a per-cpu loop here and this is
5556 * a global counter, so the first cycle will get them.
5558 delta = memcg->vmstats->state_pending[i];
5560 memcg->vmstats->state_pending[i] = 0;
5562 /* Add CPU changes on this level since the last flush */
5563 v = READ_ONCE(statc->state[i]);
5564 if (v != statc->state_prev[i]) {
5565 delta += v - statc->state_prev[i];
5566 statc->state_prev[i] = v;
5572 /* Aggregate counts on this level and propagate upwards */
5573 memcg->vmstats->state[i] += delta;
5575 parent->vmstats->state_pending[i] += delta;
5578 for (i = 0; i < NR_MEMCG_EVENTS; i++) {
5579 delta = memcg->vmstats->events_pending[i];
5581 memcg->vmstats->events_pending[i] = 0;
5583 v = READ_ONCE(statc->events[i]);
5584 if (v != statc->events_prev[i]) {
5585 delta += v - statc->events_prev[i];
5586 statc->events_prev[i] = v;
5592 memcg->vmstats->events[i] += delta;
5594 parent->vmstats->events_pending[i] += delta;
5597 for_each_node_state(nid, N_MEMORY) {
5598 struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
5599 struct mem_cgroup_per_node *ppn = NULL;
5600 struct lruvec_stats_percpu *lstatc;
5603 ppn = parent->nodeinfo[nid];
5605 lstatc = per_cpu_ptr(pn->lruvec_stats_percpu, cpu);
5607 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++) {
5608 delta = pn->lruvec_stats.state_pending[i];
5610 pn->lruvec_stats.state_pending[i] = 0;
5612 v = READ_ONCE(lstatc->state[i]);
5613 if (v != lstatc->state_prev[i]) {
5614 delta += v - lstatc->state_prev[i];
5615 lstatc->state_prev[i] = v;
5621 pn->lruvec_stats.state[i] += delta;
5623 ppn->lruvec_stats.state_pending[i] += delta;
5629 /* Handlers for move charge at task migration. */
5630 static int mem_cgroup_do_precharge(unsigned long count)
5634 /* Try a single bulk charge without reclaim first, kswapd may wake */
5635 ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count);
5637 mc.precharge += count;
5641 /* Try charges one by one with reclaim, but do not retry */
5643 ret = try_charge(mc.to, GFP_KERNEL | __GFP_NORETRY, 1);
5657 enum mc_target_type {
5664 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5665 unsigned long addr, pte_t ptent)
5667 struct page *page = vm_normal_page(vma, addr, ptent);
5669 if (!page || !page_mapped(page))
5671 if (PageAnon(page)) {
5672 if (!(mc.flags & MOVE_ANON))
5675 if (!(mc.flags & MOVE_FILE))
5678 if (!get_page_unless_zero(page))
5684 #if defined(CONFIG_SWAP) || defined(CONFIG_DEVICE_PRIVATE)
5685 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5686 pte_t ptent, swp_entry_t *entry)
5688 struct page *page = NULL;
5689 swp_entry_t ent = pte_to_swp_entry(ptent);
5691 if (!(mc.flags & MOVE_ANON))
5695 * Handle device private pages that are not accessible by the CPU, but
5696 * stored as special swap entries in the page table.
5698 if (is_device_private_entry(ent)) {
5699 page = pfn_swap_entry_to_page(ent);
5700 if (!get_page_unless_zero(page))
5705 if (non_swap_entry(ent))
5709 * Because swap_cache_get_folio() updates some statistics counter,
5710 * we call find_get_page() with swapper_space directly.
5712 page = find_get_page(swap_address_space(ent), swp_offset(ent));
5713 entry->val = ent.val;
5718 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5719 pte_t ptent, swp_entry_t *entry)
5725 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5726 unsigned long addr, pte_t ptent)
5728 unsigned long index;
5729 struct folio *folio;
5731 if (!vma->vm_file) /* anonymous vma */
5733 if (!(mc.flags & MOVE_FILE))
5736 /* folio is moved even if it's not RSS of this task(page-faulted). */
5737 /* shmem/tmpfs may report page out on swap: account for that too. */
5738 index = linear_page_index(vma, addr);
5739 folio = filemap_get_incore_folio(vma->vm_file->f_mapping, index);
5742 return folio_file_page(folio, index);
5746 * mem_cgroup_move_account - move account of the page
5748 * @compound: charge the page as compound or small page
5749 * @from: mem_cgroup which the page is moved from.
5750 * @to: mem_cgroup which the page is moved to. @from != @to.
5752 * The page must be locked and not on the LRU.
5754 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
5757 static int mem_cgroup_move_account(struct page *page,
5759 struct mem_cgroup *from,
5760 struct mem_cgroup *to)
5762 struct folio *folio = page_folio(page);
5763 struct lruvec *from_vec, *to_vec;
5764 struct pglist_data *pgdat;
5765 unsigned int nr_pages = compound ? folio_nr_pages(folio) : 1;
5768 VM_BUG_ON(from == to);
5769 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
5770 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
5771 VM_BUG_ON(compound && !folio_test_large(folio));
5774 if (folio_memcg(folio) != from)
5777 pgdat = folio_pgdat(folio);
5778 from_vec = mem_cgroup_lruvec(from, pgdat);
5779 to_vec = mem_cgroup_lruvec(to, pgdat);
5781 folio_memcg_lock(folio);
5783 if (folio_test_anon(folio)) {
5784 if (folio_mapped(folio)) {
5785 __mod_lruvec_state(from_vec, NR_ANON_MAPPED, -nr_pages);
5786 __mod_lruvec_state(to_vec, NR_ANON_MAPPED, nr_pages);
5787 if (folio_test_transhuge(folio)) {
5788 __mod_lruvec_state(from_vec, NR_ANON_THPS,
5790 __mod_lruvec_state(to_vec, NR_ANON_THPS,
5795 __mod_lruvec_state(from_vec, NR_FILE_PAGES, -nr_pages);
5796 __mod_lruvec_state(to_vec, NR_FILE_PAGES, nr_pages);
5798 if (folio_test_swapbacked(folio)) {
5799 __mod_lruvec_state(from_vec, NR_SHMEM, -nr_pages);
5800 __mod_lruvec_state(to_vec, NR_SHMEM, nr_pages);
5803 if (folio_mapped(folio)) {
5804 __mod_lruvec_state(from_vec, NR_FILE_MAPPED, -nr_pages);
5805 __mod_lruvec_state(to_vec, NR_FILE_MAPPED, nr_pages);
5808 if (folio_test_dirty(folio)) {
5809 struct address_space *mapping = folio_mapping(folio);
5811 if (mapping_can_writeback(mapping)) {
5812 __mod_lruvec_state(from_vec, NR_FILE_DIRTY,
5814 __mod_lruvec_state(to_vec, NR_FILE_DIRTY,
5821 if (folio_test_swapcache(folio)) {
5822 __mod_lruvec_state(from_vec, NR_SWAPCACHE, -nr_pages);
5823 __mod_lruvec_state(to_vec, NR_SWAPCACHE, nr_pages);
5826 if (folio_test_writeback(folio)) {
5827 __mod_lruvec_state(from_vec, NR_WRITEBACK, -nr_pages);
5828 __mod_lruvec_state(to_vec, NR_WRITEBACK, nr_pages);
5832 * All state has been migrated, let's switch to the new memcg.
5834 * It is safe to change page's memcg here because the page
5835 * is referenced, charged, isolated, and locked: we can't race
5836 * with (un)charging, migration, LRU putback, or anything else
5837 * that would rely on a stable page's memory cgroup.
5839 * Note that lock_page_memcg is a memcg lock, not a page lock,
5840 * to save space. As soon as we switch page's memory cgroup to a
5841 * new memcg that isn't locked, the above state can change
5842 * concurrently again. Make sure we're truly done with it.
5847 css_put(&from->css);
5849 folio->memcg_data = (unsigned long)to;
5851 __folio_memcg_unlock(from);
5854 nid = folio_nid(folio);
5856 local_irq_disable();
5857 mem_cgroup_charge_statistics(to, nr_pages);
5858 memcg_check_events(to, nid);
5859 mem_cgroup_charge_statistics(from, -nr_pages);
5860 memcg_check_events(from, nid);
5867 * get_mctgt_type - get target type of moving charge
5868 * @vma: the vma the pte to be checked belongs
5869 * @addr: the address corresponding to the pte to be checked
5870 * @ptent: the pte to be checked
5871 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5874 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5875 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5876 * move charge. if @target is not NULL, the page is stored in target->page
5877 * with extra refcnt got(Callers should handle it).
5878 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5879 * target for charge migration. if @target is not NULL, the entry is stored
5881 * 3(MC_TARGET_DEVICE): like MC_TARGET_PAGE but page is device memory and
5882 * thus not on the lru.
5883 * For now we such page is charge like a regular page would be as for all
5884 * intent and purposes it is just special memory taking the place of a
5887 * See Documentations/vm/hmm.txt and include/linux/hmm.h
5889 * Called with pte lock held.
5892 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
5893 unsigned long addr, pte_t ptent, union mc_target *target)
5895 struct page *page = NULL;
5896 enum mc_target_type ret = MC_TARGET_NONE;
5897 swp_entry_t ent = { .val = 0 };
5899 if (pte_present(ptent))
5900 page = mc_handle_present_pte(vma, addr, ptent);
5901 else if (pte_none_mostly(ptent))
5903 * PTE markers should be treated as a none pte here, separated
5904 * from other swap handling below.
5906 page = mc_handle_file_pte(vma, addr, ptent);
5907 else if (is_swap_pte(ptent))
5908 page = mc_handle_swap_pte(vma, ptent, &ent);
5910 if (target && page) {
5911 if (!trylock_page(page)) {
5916 * page_mapped() must be stable during the move. This
5917 * pte is locked, so if it's present, the page cannot
5918 * become unmapped. If it isn't, we have only partial
5919 * control over the mapped state: the page lock will
5920 * prevent new faults against pagecache and swapcache,
5921 * so an unmapped page cannot become mapped. However,
5922 * if the page is already mapped elsewhere, it can
5923 * unmap, and there is nothing we can do about it.
5924 * Alas, skip moving the page in this case.
5926 if (!pte_present(ptent) && page_mapped(page)) {
5933 if (!page && !ent.val)
5937 * Do only loose check w/o serialization.
5938 * mem_cgroup_move_account() checks the page is valid or
5939 * not under LRU exclusion.
5941 if (page_memcg(page) == mc.from) {
5942 ret = MC_TARGET_PAGE;
5943 if (is_device_private_page(page) ||
5944 is_device_coherent_page(page))
5945 ret = MC_TARGET_DEVICE;
5947 target->page = page;
5949 if (!ret || !target) {
5956 * There is a swap entry and a page doesn't exist or isn't charged.
5957 * But we cannot move a tail-page in a THP.
5959 if (ent.val && !ret && (!page || !PageTransCompound(page)) &&
5960 mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
5961 ret = MC_TARGET_SWAP;
5968 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5970 * We don't consider PMD mapped swapping or file mapped pages because THP does
5971 * not support them for now.
5972 * Caller should make sure that pmd_trans_huge(pmd) is true.
5974 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5975 unsigned long addr, pmd_t pmd, union mc_target *target)
5977 struct page *page = NULL;
5978 enum mc_target_type ret = MC_TARGET_NONE;
5980 if (unlikely(is_swap_pmd(pmd))) {
5981 VM_BUG_ON(thp_migration_supported() &&
5982 !is_pmd_migration_entry(pmd));
5985 page = pmd_page(pmd);
5986 VM_BUG_ON_PAGE(!page || !PageHead(page), page);
5987 if (!(mc.flags & MOVE_ANON))
5989 if (page_memcg(page) == mc.from) {
5990 ret = MC_TARGET_PAGE;
5993 if (!trylock_page(page)) {
5995 return MC_TARGET_NONE;
5997 target->page = page;
6003 static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
6004 unsigned long addr, pmd_t pmd, union mc_target *target)
6006 return MC_TARGET_NONE;
6010 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
6011 unsigned long addr, unsigned long end,
6012 struct mm_walk *walk)
6014 struct vm_area_struct *vma = walk->vma;
6018 ptl = pmd_trans_huge_lock(pmd, vma);
6021 * Note their can not be MC_TARGET_DEVICE for now as we do not
6022 * support transparent huge page with MEMORY_DEVICE_PRIVATE but
6023 * this might change.
6025 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
6026 mc.precharge += HPAGE_PMD_NR;
6031 if (pmd_trans_unstable(pmd))
6033 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6034 for (; addr != end; pte++, addr += PAGE_SIZE)
6035 if (get_mctgt_type(vma, addr, *pte, NULL))
6036 mc.precharge++; /* increment precharge temporarily */
6037 pte_unmap_unlock(pte - 1, ptl);
6043 static const struct mm_walk_ops precharge_walk_ops = {
6044 .pmd_entry = mem_cgroup_count_precharge_pte_range,
6047 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
6049 unsigned long precharge;
6052 walk_page_range(mm, 0, ULONG_MAX, &precharge_walk_ops, NULL);
6053 mmap_read_unlock(mm);
6055 precharge = mc.precharge;
6061 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
6063 unsigned long precharge = mem_cgroup_count_precharge(mm);
6065 VM_BUG_ON(mc.moving_task);
6066 mc.moving_task = current;
6067 return mem_cgroup_do_precharge(precharge);
6070 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
6071 static void __mem_cgroup_clear_mc(void)
6073 struct mem_cgroup *from = mc.from;
6074 struct mem_cgroup *to = mc.to;
6076 /* we must uncharge all the leftover precharges from mc.to */
6078 cancel_charge(mc.to, mc.precharge);
6082 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
6083 * we must uncharge here.
6085 if (mc.moved_charge) {
6086 cancel_charge(mc.from, mc.moved_charge);
6087 mc.moved_charge = 0;
6089 /* we must fixup refcnts and charges */
6090 if (mc.moved_swap) {
6091 /* uncharge swap account from the old cgroup */
6092 if (!mem_cgroup_is_root(mc.from))
6093 page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
6095 mem_cgroup_id_put_many(mc.from, mc.moved_swap);
6098 * we charged both to->memory and to->memsw, so we
6099 * should uncharge to->memory.
6101 if (!mem_cgroup_is_root(mc.to))
6102 page_counter_uncharge(&mc.to->memory, mc.moved_swap);
6106 memcg_oom_recover(from);
6107 memcg_oom_recover(to);
6108 wake_up_all(&mc.waitq);
6111 static void mem_cgroup_clear_mc(void)
6113 struct mm_struct *mm = mc.mm;
6116 * we must clear moving_task before waking up waiters at the end of
6119 mc.moving_task = NULL;
6120 __mem_cgroup_clear_mc();
6121 spin_lock(&mc.lock);
6125 spin_unlock(&mc.lock);
6130 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
6132 struct cgroup_subsys_state *css;
6133 struct mem_cgroup *memcg = NULL; /* unneeded init to make gcc happy */
6134 struct mem_cgroup *from;
6135 struct task_struct *leader, *p;
6136 struct mm_struct *mm;
6137 unsigned long move_flags;
6140 /* charge immigration isn't supported on the default hierarchy */
6141 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
6145 * Multi-process migrations only happen on the default hierarchy
6146 * where charge immigration is not used. Perform charge
6147 * immigration if @tset contains a leader and whine if there are
6151 cgroup_taskset_for_each_leader(leader, css, tset) {
6154 memcg = mem_cgroup_from_css(css);
6160 * We are now committed to this value whatever it is. Changes in this
6161 * tunable will only affect upcoming migrations, not the current one.
6162 * So we need to save it, and keep it going.
6164 move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
6168 from = mem_cgroup_from_task(p);
6170 VM_BUG_ON(from == memcg);
6172 mm = get_task_mm(p);
6175 /* We move charges only when we move a owner of the mm */
6176 if (mm->owner == p) {
6179 VM_BUG_ON(mc.precharge);
6180 VM_BUG_ON(mc.moved_charge);
6181 VM_BUG_ON(mc.moved_swap);
6183 spin_lock(&mc.lock);
6187 mc.flags = move_flags;
6188 spin_unlock(&mc.lock);
6189 /* We set mc.moving_task later */
6191 ret = mem_cgroup_precharge_mc(mm);
6193 mem_cgroup_clear_mc();
6200 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6203 mem_cgroup_clear_mc();
6206 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
6207 unsigned long addr, unsigned long end,
6208 struct mm_walk *walk)
6211 struct vm_area_struct *vma = walk->vma;
6214 enum mc_target_type target_type;
6215 union mc_target target;
6218 ptl = pmd_trans_huge_lock(pmd, vma);
6220 if (mc.precharge < HPAGE_PMD_NR) {
6224 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
6225 if (target_type == MC_TARGET_PAGE) {
6227 if (isolate_lru_page(page)) {
6228 if (!mem_cgroup_move_account(page, true,
6230 mc.precharge -= HPAGE_PMD_NR;
6231 mc.moved_charge += HPAGE_PMD_NR;
6233 putback_lru_page(page);
6237 } else if (target_type == MC_TARGET_DEVICE) {
6239 if (!mem_cgroup_move_account(page, true,
6241 mc.precharge -= HPAGE_PMD_NR;
6242 mc.moved_charge += HPAGE_PMD_NR;
6251 if (pmd_trans_unstable(pmd))
6254 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6255 for (; addr != end; addr += PAGE_SIZE) {
6256 pte_t ptent = *(pte++);
6257 bool device = false;
6263 switch (get_mctgt_type(vma, addr, ptent, &target)) {
6264 case MC_TARGET_DEVICE:
6267 case MC_TARGET_PAGE:
6270 * We can have a part of the split pmd here. Moving it
6271 * can be done but it would be too convoluted so simply
6272 * ignore such a partial THP and keep it in original
6273 * memcg. There should be somebody mapping the head.
6275 if (PageTransCompound(page))
6277 if (!device && !isolate_lru_page(page))
6279 if (!mem_cgroup_move_account(page, false,
6282 /* we uncharge from mc.from later. */
6286 putback_lru_page(page);
6287 put: /* get_mctgt_type() gets & locks the page */
6291 case MC_TARGET_SWAP:
6293 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
6295 mem_cgroup_id_get_many(mc.to, 1);
6296 /* we fixup other refcnts and charges later. */
6304 pte_unmap_unlock(pte - 1, ptl);
6309 * We have consumed all precharges we got in can_attach().
6310 * We try charge one by one, but don't do any additional
6311 * charges to mc.to if we have failed in charge once in attach()
6314 ret = mem_cgroup_do_precharge(1);
6322 static const struct mm_walk_ops charge_walk_ops = {
6323 .pmd_entry = mem_cgroup_move_charge_pte_range,
6326 static void mem_cgroup_move_charge(void)
6328 lru_add_drain_all();
6330 * Signal lock_page_memcg() to take the memcg's move_lock
6331 * while we're moving its pages to another memcg. Then wait
6332 * for already started RCU-only updates to finish.
6334 atomic_inc(&mc.from->moving_account);
6337 if (unlikely(!mmap_read_trylock(mc.mm))) {
6339 * Someone who are holding the mmap_lock might be waiting in
6340 * waitq. So we cancel all extra charges, wake up all waiters,
6341 * and retry. Because we cancel precharges, we might not be able
6342 * to move enough charges, but moving charge is a best-effort
6343 * feature anyway, so it wouldn't be a big problem.
6345 __mem_cgroup_clear_mc();
6350 * When we have consumed all precharges and failed in doing
6351 * additional charge, the page walk just aborts.
6353 walk_page_range(mc.mm, 0, ULONG_MAX, &charge_walk_ops, NULL);
6354 mmap_read_unlock(mc.mm);
6355 atomic_dec(&mc.from->moving_account);
6358 static void mem_cgroup_move_task(void)
6361 mem_cgroup_move_charge();
6362 mem_cgroup_clear_mc();
6365 #else /* !CONFIG_MMU */
6366 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
6370 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6373 static void mem_cgroup_move_task(void)
6378 #ifdef CONFIG_LRU_GEN
6379 static void mem_cgroup_attach(struct cgroup_taskset *tset)
6381 struct task_struct *task;
6382 struct cgroup_subsys_state *css;
6384 /* find the first leader if there is any */
6385 cgroup_taskset_for_each_leader(task, css, tset)
6392 if (task->mm && READ_ONCE(task->mm->owner) == task)
6393 lru_gen_migrate_mm(task->mm);
6397 static void mem_cgroup_attach(struct cgroup_taskset *tset)
6400 #endif /* CONFIG_LRU_GEN */
6402 static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
6404 if (value == PAGE_COUNTER_MAX)
6405 seq_puts(m, "max\n");
6407 seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
6412 static u64 memory_current_read(struct cgroup_subsys_state *css,
6415 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6417 return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
6420 static u64 memory_peak_read(struct cgroup_subsys_state *css,
6423 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6425 return (u64)memcg->memory.watermark * PAGE_SIZE;
6428 static int memory_min_show(struct seq_file *m, void *v)
6430 return seq_puts_memcg_tunable(m,
6431 READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
6434 static ssize_t memory_min_write(struct kernfs_open_file *of,
6435 char *buf, size_t nbytes, loff_t off)
6437 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6441 buf = strstrip(buf);
6442 err = page_counter_memparse(buf, "max", &min);
6446 page_counter_set_min(&memcg->memory, min);
6451 static int memory_low_show(struct seq_file *m, void *v)
6453 return seq_puts_memcg_tunable(m,
6454 READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
6457 static ssize_t memory_low_write(struct kernfs_open_file *of,
6458 char *buf, size_t nbytes, loff_t off)
6460 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6464 buf = strstrip(buf);
6465 err = page_counter_memparse(buf, "max", &low);
6469 page_counter_set_low(&memcg->memory, low);
6474 static int memory_high_show(struct seq_file *m, void *v)
6476 return seq_puts_memcg_tunable(m,
6477 READ_ONCE(mem_cgroup_from_seq(m)->memory.high));
6480 static ssize_t memory_high_write(struct kernfs_open_file *of,
6481 char *buf, size_t nbytes, loff_t off)
6483 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6484 unsigned int nr_retries = MAX_RECLAIM_RETRIES;
6485 bool drained = false;
6489 buf = strstrip(buf);
6490 err = page_counter_memparse(buf, "max", &high);
6494 page_counter_set_high(&memcg->memory, high);
6497 unsigned long nr_pages = page_counter_read(&memcg->memory);
6498 unsigned long reclaimed;
6500 if (nr_pages <= high)
6503 if (signal_pending(current))
6507 drain_all_stock(memcg);
6512 reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
6513 GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP);
6515 if (!reclaimed && !nr_retries--)
6519 memcg_wb_domain_size_changed(memcg);
6523 static int memory_max_show(struct seq_file *m, void *v)
6525 return seq_puts_memcg_tunable(m,
6526 READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
6529 static ssize_t memory_max_write(struct kernfs_open_file *of,
6530 char *buf, size_t nbytes, loff_t off)
6532 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6533 unsigned int nr_reclaims = MAX_RECLAIM_RETRIES;
6534 bool drained = false;
6538 buf = strstrip(buf);
6539 err = page_counter_memparse(buf, "max", &max);
6543 xchg(&memcg->memory.max, max);
6546 unsigned long nr_pages = page_counter_read(&memcg->memory);
6548 if (nr_pages <= max)
6551 if (signal_pending(current))
6555 drain_all_stock(memcg);
6561 if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
6562 GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP))
6567 memcg_memory_event(memcg, MEMCG_OOM);
6568 if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
6572 memcg_wb_domain_size_changed(memcg);
6576 static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
6578 seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
6579 seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
6580 seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
6581 seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
6582 seq_printf(m, "oom_kill %lu\n",
6583 atomic_long_read(&events[MEMCG_OOM_KILL]));
6584 seq_printf(m, "oom_group_kill %lu\n",
6585 atomic_long_read(&events[MEMCG_OOM_GROUP_KILL]));
6588 static int memory_events_show(struct seq_file *m, void *v)
6590 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6592 __memory_events_show(m, memcg->memory_events);
6596 static int memory_events_local_show(struct seq_file *m, void *v)
6598 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6600 __memory_events_show(m, memcg->memory_events_local);
6604 static int memory_stat_show(struct seq_file *m, void *v)
6606 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6607 char *buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
6612 seq_buf_init(&s, buf, PAGE_SIZE);
6613 memory_stat_format(memcg, &s);
6620 static inline unsigned long lruvec_page_state_output(struct lruvec *lruvec,
6623 return lruvec_page_state(lruvec, item) * memcg_page_state_unit(item);
6626 static int memory_numa_stat_show(struct seq_file *m, void *v)
6629 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6631 mem_cgroup_flush_stats();
6633 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
6636 if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS)
6639 seq_printf(m, "%s", memory_stats[i].name);
6640 for_each_node_state(nid, N_MEMORY) {
6642 struct lruvec *lruvec;
6644 lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
6645 size = lruvec_page_state_output(lruvec,
6646 memory_stats[i].idx);
6647 seq_printf(m, " N%d=%llu", nid, size);
6656 static int memory_oom_group_show(struct seq_file *m, void *v)
6658 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6660 seq_printf(m, "%d\n", READ_ONCE(memcg->oom_group));
6665 static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
6666 char *buf, size_t nbytes, loff_t off)
6668 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6671 buf = strstrip(buf);
6675 ret = kstrtoint(buf, 0, &oom_group);
6679 if (oom_group != 0 && oom_group != 1)
6682 WRITE_ONCE(memcg->oom_group, oom_group);
6687 static ssize_t memory_reclaim(struct kernfs_open_file *of, char *buf,
6688 size_t nbytes, loff_t off)
6690 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6691 unsigned int nr_retries = MAX_RECLAIM_RETRIES;
6692 unsigned long nr_to_reclaim, nr_reclaimed = 0;
6693 unsigned int reclaim_options;
6696 buf = strstrip(buf);
6697 err = page_counter_memparse(buf, "", &nr_to_reclaim);
6701 reclaim_options = MEMCG_RECLAIM_MAY_SWAP | MEMCG_RECLAIM_PROACTIVE;
6702 while (nr_reclaimed < nr_to_reclaim) {
6703 unsigned long reclaimed;
6705 if (signal_pending(current))
6709 * This is the final attempt, drain percpu lru caches in the
6710 * hope of introducing more evictable pages for
6711 * try_to_free_mem_cgroup_pages().
6714 lru_add_drain_all();
6716 reclaimed = try_to_free_mem_cgroup_pages(memcg,
6717 nr_to_reclaim - nr_reclaimed,
6718 GFP_KERNEL, reclaim_options);
6720 if (!reclaimed && !nr_retries--)
6723 nr_reclaimed += reclaimed;
6729 static struct cftype memory_files[] = {
6732 .flags = CFTYPE_NOT_ON_ROOT,
6733 .read_u64 = memory_current_read,
6737 .flags = CFTYPE_NOT_ON_ROOT,
6738 .read_u64 = memory_peak_read,
6742 .flags = CFTYPE_NOT_ON_ROOT,
6743 .seq_show = memory_min_show,
6744 .write = memory_min_write,
6748 .flags = CFTYPE_NOT_ON_ROOT,
6749 .seq_show = memory_low_show,
6750 .write = memory_low_write,
6754 .flags = CFTYPE_NOT_ON_ROOT,
6755 .seq_show = memory_high_show,
6756 .write = memory_high_write,
6760 .flags = CFTYPE_NOT_ON_ROOT,
6761 .seq_show = memory_max_show,
6762 .write = memory_max_write,
6766 .flags = CFTYPE_NOT_ON_ROOT,
6767 .file_offset = offsetof(struct mem_cgroup, events_file),
6768 .seq_show = memory_events_show,
6771 .name = "events.local",
6772 .flags = CFTYPE_NOT_ON_ROOT,
6773 .file_offset = offsetof(struct mem_cgroup, events_local_file),
6774 .seq_show = memory_events_local_show,
6778 .seq_show = memory_stat_show,
6782 .name = "numa_stat",
6783 .seq_show = memory_numa_stat_show,
6787 .name = "oom.group",
6788 .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
6789 .seq_show = memory_oom_group_show,
6790 .write = memory_oom_group_write,
6794 .flags = CFTYPE_NS_DELEGATABLE,
6795 .write = memory_reclaim,
6800 struct cgroup_subsys memory_cgrp_subsys = {
6801 .css_alloc = mem_cgroup_css_alloc,
6802 .css_online = mem_cgroup_css_online,
6803 .css_offline = mem_cgroup_css_offline,
6804 .css_released = mem_cgroup_css_released,
6805 .css_free = mem_cgroup_css_free,
6806 .css_reset = mem_cgroup_css_reset,
6807 .css_rstat_flush = mem_cgroup_css_rstat_flush,
6808 .can_attach = mem_cgroup_can_attach,
6809 .attach = mem_cgroup_attach,
6810 .cancel_attach = mem_cgroup_cancel_attach,
6811 .post_attach = mem_cgroup_move_task,
6812 .dfl_cftypes = memory_files,
6813 .legacy_cftypes = mem_cgroup_legacy_files,
6818 * This function calculates an individual cgroup's effective
6819 * protection which is derived from its own memory.min/low, its
6820 * parent's and siblings' settings, as well as the actual memory
6821 * distribution in the tree.
6823 * The following rules apply to the effective protection values:
6825 * 1. At the first level of reclaim, effective protection is equal to
6826 * the declared protection in memory.min and memory.low.
6828 * 2. To enable safe delegation of the protection configuration, at
6829 * subsequent levels the effective protection is capped to the
6830 * parent's effective protection.
6832 * 3. To make complex and dynamic subtrees easier to configure, the
6833 * user is allowed to overcommit the declared protection at a given
6834 * level. If that is the case, the parent's effective protection is
6835 * distributed to the children in proportion to how much protection
6836 * they have declared and how much of it they are utilizing.
6838 * This makes distribution proportional, but also work-conserving:
6839 * if one cgroup claims much more protection than it uses memory,
6840 * the unused remainder is available to its siblings.
6842 * 4. Conversely, when the declared protection is undercommitted at a
6843 * given level, the distribution of the larger parental protection
6844 * budget is NOT proportional. A cgroup's protection from a sibling
6845 * is capped to its own memory.min/low setting.
6847 * 5. However, to allow protecting recursive subtrees from each other
6848 * without having to declare each individual cgroup's fixed share
6849 * of the ancestor's claim to protection, any unutilized -
6850 * "floating" - protection from up the tree is distributed in
6851 * proportion to each cgroup's *usage*. This makes the protection
6852 * neutral wrt sibling cgroups and lets them compete freely over
6853 * the shared parental protection budget, but it protects the
6854 * subtree as a whole from neighboring subtrees.
6856 * Note that 4. and 5. are not in conflict: 4. is about protecting
6857 * against immediate siblings whereas 5. is about protecting against
6858 * neighboring subtrees.
6860 static unsigned long effective_protection(unsigned long usage,
6861 unsigned long parent_usage,
6862 unsigned long setting,
6863 unsigned long parent_effective,
6864 unsigned long siblings_protected)
6866 unsigned long protected;
6869 protected = min(usage, setting);
6871 * If all cgroups at this level combined claim and use more
6872 * protection then what the parent affords them, distribute
6873 * shares in proportion to utilization.
6875 * We are using actual utilization rather than the statically
6876 * claimed protection in order to be work-conserving: claimed
6877 * but unused protection is available to siblings that would
6878 * otherwise get a smaller chunk than what they claimed.
6880 if (siblings_protected > parent_effective)
6881 return protected * parent_effective / siblings_protected;
6884 * Ok, utilized protection of all children is within what the
6885 * parent affords them, so we know whatever this child claims
6886 * and utilizes is effectively protected.
6888 * If there is unprotected usage beyond this value, reclaim
6889 * will apply pressure in proportion to that amount.
6891 * If there is unutilized protection, the cgroup will be fully
6892 * shielded from reclaim, but we do return a smaller value for
6893 * protection than what the group could enjoy in theory. This
6894 * is okay. With the overcommit distribution above, effective
6895 * protection is always dependent on how memory is actually
6896 * consumed among the siblings anyway.
6901 * If the children aren't claiming (all of) the protection
6902 * afforded to them by the parent, distribute the remainder in
6903 * proportion to the (unprotected) memory of each cgroup. That
6904 * way, cgroups that aren't explicitly prioritized wrt each
6905 * other compete freely over the allowance, but they are
6906 * collectively protected from neighboring trees.
6908 * We're using unprotected memory for the weight so that if
6909 * some cgroups DO claim explicit protection, we don't protect
6910 * the same bytes twice.
6912 * Check both usage and parent_usage against the respective
6913 * protected values. One should imply the other, but they
6914 * aren't read atomically - make sure the division is sane.
6916 if (!(cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT))
6918 if (parent_effective > siblings_protected &&
6919 parent_usage > siblings_protected &&
6920 usage > protected) {
6921 unsigned long unclaimed;
6923 unclaimed = parent_effective - siblings_protected;
6924 unclaimed *= usage - protected;
6925 unclaimed /= parent_usage - siblings_protected;
6934 * mem_cgroup_calculate_protection - check if memory consumption is in the normal range
6935 * @root: the top ancestor of the sub-tree being checked
6936 * @memcg: the memory cgroup to check
6938 * WARNING: This function is not stateless! It can only be used as part
6939 * of a top-down tree iteration, not for isolated queries.
6941 void mem_cgroup_calculate_protection(struct mem_cgroup *root,
6942 struct mem_cgroup *memcg)
6944 unsigned long usage, parent_usage;
6945 struct mem_cgroup *parent;
6947 if (mem_cgroup_disabled())
6951 root = root_mem_cgroup;
6954 * Effective values of the reclaim targets are ignored so they
6955 * can be stale. Have a look at mem_cgroup_protection for more
6957 * TODO: calculation should be more robust so that we do not need
6958 * that special casing.
6963 usage = page_counter_read(&memcg->memory);
6967 parent = parent_mem_cgroup(memcg);
6969 if (parent == root) {
6970 memcg->memory.emin = READ_ONCE(memcg->memory.min);
6971 memcg->memory.elow = READ_ONCE(memcg->memory.low);
6975 parent_usage = page_counter_read(&parent->memory);
6977 WRITE_ONCE(memcg->memory.emin, effective_protection(usage, parent_usage,
6978 READ_ONCE(memcg->memory.min),
6979 READ_ONCE(parent->memory.emin),
6980 atomic_long_read(&parent->memory.children_min_usage)));
6982 WRITE_ONCE(memcg->memory.elow, effective_protection(usage, parent_usage,
6983 READ_ONCE(memcg->memory.low),
6984 READ_ONCE(parent->memory.elow),
6985 atomic_long_read(&parent->memory.children_low_usage)));
6988 static int charge_memcg(struct folio *folio, struct mem_cgroup *memcg,
6991 long nr_pages = folio_nr_pages(folio);
6994 ret = try_charge(memcg, gfp, nr_pages);
6998 css_get(&memcg->css);
6999 commit_charge(folio, memcg);
7001 local_irq_disable();
7002 mem_cgroup_charge_statistics(memcg, nr_pages);
7003 memcg_check_events(memcg, folio_nid(folio));
7009 int __mem_cgroup_charge(struct folio *folio, struct mm_struct *mm, gfp_t gfp)
7011 struct mem_cgroup *memcg;
7014 memcg = get_mem_cgroup_from_mm(mm);
7015 ret = charge_memcg(folio, memcg, gfp);
7016 css_put(&memcg->css);
7022 * mem_cgroup_swapin_charge_folio - Charge a newly allocated folio for swapin.
7023 * @folio: folio to charge.
7024 * @mm: mm context of the victim
7025 * @gfp: reclaim mode
7026 * @entry: swap entry for which the folio is allocated
7028 * This function charges a folio allocated for swapin. Please call this before
7029 * adding the folio to the swapcache.
7031 * Returns 0 on success. Otherwise, an error code is returned.
7033 int mem_cgroup_swapin_charge_folio(struct folio *folio, struct mm_struct *mm,
7034 gfp_t gfp, swp_entry_t entry)
7036 struct mem_cgroup *memcg;
7040 if (mem_cgroup_disabled())
7043 id = lookup_swap_cgroup_id(entry);
7045 memcg = mem_cgroup_from_id(id);
7046 if (!memcg || !css_tryget_online(&memcg->css))
7047 memcg = get_mem_cgroup_from_mm(mm);
7050 ret = charge_memcg(folio, memcg, gfp);
7052 css_put(&memcg->css);
7057 * mem_cgroup_swapin_uncharge_swap - uncharge swap slot
7058 * @entry: swap entry for which the page is charged
7060 * Call this function after successfully adding the charged page to swapcache.
7062 * Note: This function assumes the page for which swap slot is being uncharged
7065 void mem_cgroup_swapin_uncharge_swap(swp_entry_t entry)
7068 * Cgroup1's unified memory+swap counter has been charged with the
7069 * new swapcache page, finish the transfer by uncharging the swap
7070 * slot. The swap slot would also get uncharged when it dies, but
7071 * it can stick around indefinitely and we'd count the page twice
7074 * Cgroup2 has separate resource counters for memory and swap,
7075 * so this is a non-issue here. Memory and swap charge lifetimes
7076 * correspond 1:1 to page and swap slot lifetimes: we charge the
7077 * page to memory here, and uncharge swap when the slot is freed.
7079 if (!mem_cgroup_disabled() && do_memsw_account()) {
7081 * The swap entry might not get freed for a long time,
7082 * let's not wait for it. The page already received a
7083 * memory+swap charge, drop the swap entry duplicate.
7085 mem_cgroup_uncharge_swap(entry, 1);
7089 struct uncharge_gather {
7090 struct mem_cgroup *memcg;
7091 unsigned long nr_memory;
7092 unsigned long pgpgout;
7093 unsigned long nr_kmem;
7097 static inline void uncharge_gather_clear(struct uncharge_gather *ug)
7099 memset(ug, 0, sizeof(*ug));
7102 static void uncharge_batch(const struct uncharge_gather *ug)
7104 unsigned long flags;
7106 if (ug->nr_memory) {
7107 page_counter_uncharge(&ug->memcg->memory, ug->nr_memory);
7108 if (do_memsw_account())
7109 page_counter_uncharge(&ug->memcg->memsw, ug->nr_memory);
7111 memcg_account_kmem(ug->memcg, -ug->nr_kmem);
7112 memcg_oom_recover(ug->memcg);
7115 local_irq_save(flags);
7116 __count_memcg_events(ug->memcg, PGPGOUT, ug->pgpgout);
7117 __this_cpu_add(ug->memcg->vmstats_percpu->nr_page_events, ug->nr_memory);
7118 memcg_check_events(ug->memcg, ug->nid);
7119 local_irq_restore(flags);
7121 /* drop reference from uncharge_folio */
7122 css_put(&ug->memcg->css);
7125 static void uncharge_folio(struct folio *folio, struct uncharge_gather *ug)
7128 struct mem_cgroup *memcg;
7129 struct obj_cgroup *objcg;
7131 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
7134 * Nobody should be changing or seriously looking at
7135 * folio memcg or objcg at this point, we have fully
7136 * exclusive access to the folio.
7138 if (folio_memcg_kmem(folio)) {
7139 objcg = __folio_objcg(folio);
7141 * This get matches the put at the end of the function and
7142 * kmem pages do not hold memcg references anymore.
7144 memcg = get_mem_cgroup_from_objcg(objcg);
7146 memcg = __folio_memcg(folio);
7152 if (ug->memcg != memcg) {
7155 uncharge_gather_clear(ug);
7158 ug->nid = folio_nid(folio);
7160 /* pairs with css_put in uncharge_batch */
7161 css_get(&memcg->css);
7164 nr_pages = folio_nr_pages(folio);
7166 if (folio_memcg_kmem(folio)) {
7167 ug->nr_memory += nr_pages;
7168 ug->nr_kmem += nr_pages;
7170 folio->memcg_data = 0;
7171 obj_cgroup_put(objcg);
7173 /* LRU pages aren't accounted at the root level */
7174 if (!mem_cgroup_is_root(memcg))
7175 ug->nr_memory += nr_pages;
7178 folio->memcg_data = 0;
7181 css_put(&memcg->css);
7184 void __mem_cgroup_uncharge(struct folio *folio)
7186 struct uncharge_gather ug;
7188 /* Don't touch folio->lru of any random page, pre-check: */
7189 if (!folio_memcg(folio))
7192 uncharge_gather_clear(&ug);
7193 uncharge_folio(folio, &ug);
7194 uncharge_batch(&ug);
7198 * __mem_cgroup_uncharge_list - uncharge a list of page
7199 * @page_list: list of pages to uncharge
7201 * Uncharge a list of pages previously charged with
7202 * __mem_cgroup_charge().
7204 void __mem_cgroup_uncharge_list(struct list_head *page_list)
7206 struct uncharge_gather ug;
7207 struct folio *folio;
7209 uncharge_gather_clear(&ug);
7210 list_for_each_entry(folio, page_list, lru)
7211 uncharge_folio(folio, &ug);
7213 uncharge_batch(&ug);
7217 * mem_cgroup_migrate - Charge a folio's replacement.
7218 * @old: Currently circulating folio.
7219 * @new: Replacement folio.
7221 * Charge @new as a replacement folio for @old. @old will
7222 * be uncharged upon free.
7224 * Both folios must be locked, @new->mapping must be set up.
7226 void mem_cgroup_migrate(struct folio *old, struct folio *new)
7228 struct mem_cgroup *memcg;
7229 long nr_pages = folio_nr_pages(new);
7230 unsigned long flags;
7232 VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
7233 VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
7234 VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
7235 VM_BUG_ON_FOLIO(folio_nr_pages(old) != nr_pages, new);
7237 if (mem_cgroup_disabled())
7240 /* Page cache replacement: new folio already charged? */
7241 if (folio_memcg(new))
7244 memcg = folio_memcg(old);
7245 VM_WARN_ON_ONCE_FOLIO(!memcg, old);
7249 /* Force-charge the new page. The old one will be freed soon */
7250 if (!mem_cgroup_is_root(memcg)) {
7251 page_counter_charge(&memcg->memory, nr_pages);
7252 if (do_memsw_account())
7253 page_counter_charge(&memcg->memsw, nr_pages);
7256 css_get(&memcg->css);
7257 commit_charge(new, memcg);
7259 local_irq_save(flags);
7260 mem_cgroup_charge_statistics(memcg, nr_pages);
7261 memcg_check_events(memcg, folio_nid(new));
7262 local_irq_restore(flags);
7265 DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
7266 EXPORT_SYMBOL(memcg_sockets_enabled_key);
7268 void mem_cgroup_sk_alloc(struct sock *sk)
7270 struct mem_cgroup *memcg;
7272 if (!mem_cgroup_sockets_enabled)
7275 /* Do not associate the sock with unrelated interrupted task's memcg. */
7280 memcg = mem_cgroup_from_task(current);
7281 if (mem_cgroup_is_root(memcg))
7283 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg->tcpmem_active)
7285 if (css_tryget(&memcg->css))
7286 sk->sk_memcg = memcg;
7291 void mem_cgroup_sk_free(struct sock *sk)
7294 css_put(&sk->sk_memcg->css);
7298 * mem_cgroup_charge_skmem - charge socket memory
7299 * @memcg: memcg to charge
7300 * @nr_pages: number of pages to charge
7301 * @gfp_mask: reclaim mode
7303 * Charges @nr_pages to @memcg. Returns %true if the charge fit within
7304 * @memcg's configured limit, %false if it doesn't.
7306 bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages,
7309 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
7310 struct page_counter *fail;
7312 if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) {
7313 memcg->tcpmem_pressure = 0;
7316 memcg->tcpmem_pressure = 1;
7317 if (gfp_mask & __GFP_NOFAIL) {
7318 page_counter_charge(&memcg->tcpmem, nr_pages);
7324 if (try_charge(memcg, gfp_mask, nr_pages) == 0) {
7325 mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
7333 * mem_cgroup_uncharge_skmem - uncharge socket memory
7334 * @memcg: memcg to uncharge
7335 * @nr_pages: number of pages to uncharge
7337 void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
7339 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
7340 page_counter_uncharge(&memcg->tcpmem, nr_pages);
7344 mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
7346 refill_stock(memcg, nr_pages);
7349 static int __init cgroup_memory(char *s)
7353 while ((token = strsep(&s, ",")) != NULL) {
7356 if (!strcmp(token, "nosocket"))
7357 cgroup_memory_nosocket = true;
7358 if (!strcmp(token, "nokmem"))
7359 cgroup_memory_nokmem = true;
7360 if (!strcmp(token, "nobpf"))
7361 cgroup_memory_nobpf = true;
7365 __setup("cgroup.memory=", cgroup_memory);
7368 * subsys_initcall() for memory controller.
7370 * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
7371 * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
7372 * basically everything that doesn't depend on a specific mem_cgroup structure
7373 * should be initialized from here.
7375 static int __init mem_cgroup_init(void)
7380 * Currently s32 type (can refer to struct batched_lruvec_stat) is
7381 * used for per-memcg-per-cpu caching of per-node statistics. In order
7382 * to work fine, we should make sure that the overfill threshold can't
7383 * exceed S32_MAX / PAGE_SIZE.
7385 BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE);
7387 cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
7388 memcg_hotplug_cpu_dead);
7390 for_each_possible_cpu(cpu)
7391 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
7394 for_each_node(node) {
7395 struct mem_cgroup_tree_per_node *rtpn;
7397 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL,
7398 node_online(node) ? node : NUMA_NO_NODE);
7400 rtpn->rb_root = RB_ROOT;
7401 rtpn->rb_rightmost = NULL;
7402 spin_lock_init(&rtpn->lock);
7403 soft_limit_tree.rb_tree_per_node[node] = rtpn;
7408 subsys_initcall(mem_cgroup_init);
7411 static struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
7413 while (!refcount_inc_not_zero(&memcg->id.ref)) {
7415 * The root cgroup cannot be destroyed, so it's refcount must
7418 if (WARN_ON_ONCE(mem_cgroup_is_root(memcg))) {
7422 memcg = parent_mem_cgroup(memcg);
7424 memcg = root_mem_cgroup;
7430 * mem_cgroup_swapout - transfer a memsw charge to swap
7431 * @folio: folio whose memsw charge to transfer
7432 * @entry: swap entry to move the charge to
7434 * Transfer the memsw charge of @folio to @entry.
7436 void mem_cgroup_swapout(struct folio *folio, swp_entry_t entry)
7438 struct mem_cgroup *memcg, *swap_memcg;
7439 unsigned int nr_entries;
7440 unsigned short oldid;
7442 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
7443 VM_BUG_ON_FOLIO(folio_ref_count(folio), folio);
7445 if (mem_cgroup_disabled())
7448 if (!do_memsw_account())
7451 memcg = folio_memcg(folio);
7453 VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
7458 * In case the memcg owning these pages has been offlined and doesn't
7459 * have an ID allocated to it anymore, charge the closest online
7460 * ancestor for the swap instead and transfer the memory+swap charge.
7462 swap_memcg = mem_cgroup_id_get_online(memcg);
7463 nr_entries = folio_nr_pages(folio);
7464 /* Get references for the tail pages, too */
7466 mem_cgroup_id_get_many(swap_memcg, nr_entries - 1);
7467 oldid = swap_cgroup_record(entry, mem_cgroup_id(swap_memcg),
7469 VM_BUG_ON_FOLIO(oldid, folio);
7470 mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries);
7472 folio->memcg_data = 0;
7474 if (!mem_cgroup_is_root(memcg))
7475 page_counter_uncharge(&memcg->memory, nr_entries);
7477 if (memcg != swap_memcg) {
7478 if (!mem_cgroup_is_root(swap_memcg))
7479 page_counter_charge(&swap_memcg->memsw, nr_entries);
7480 page_counter_uncharge(&memcg->memsw, nr_entries);
7484 * Interrupts should be disabled here because the caller holds the
7485 * i_pages lock which is taken with interrupts-off. It is
7486 * important here to have the interrupts disabled because it is the
7487 * only synchronisation we have for updating the per-CPU variables.
7490 mem_cgroup_charge_statistics(memcg, -nr_entries);
7491 memcg_stats_unlock();
7492 memcg_check_events(memcg, folio_nid(folio));
7494 css_put(&memcg->css);
7498 * __mem_cgroup_try_charge_swap - try charging swap space for a folio
7499 * @folio: folio being added to swap
7500 * @entry: swap entry to charge
7502 * Try to charge @folio's memcg for the swap space at @entry.
7504 * Returns 0 on success, -ENOMEM on failure.
7506 int __mem_cgroup_try_charge_swap(struct folio *folio, swp_entry_t entry)
7508 unsigned int nr_pages = folio_nr_pages(folio);
7509 struct page_counter *counter;
7510 struct mem_cgroup *memcg;
7511 unsigned short oldid;
7513 if (do_memsw_account())
7516 memcg = folio_memcg(folio);
7518 VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
7523 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7527 memcg = mem_cgroup_id_get_online(memcg);
7529 if (!mem_cgroup_is_root(memcg) &&
7530 !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
7531 memcg_memory_event(memcg, MEMCG_SWAP_MAX);
7532 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7533 mem_cgroup_id_put(memcg);
7537 /* Get references for the tail pages, too */
7539 mem_cgroup_id_get_many(memcg, nr_pages - 1);
7540 oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg), nr_pages);
7541 VM_BUG_ON_FOLIO(oldid, folio);
7542 mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
7548 * __mem_cgroup_uncharge_swap - uncharge swap space
7549 * @entry: swap entry to uncharge
7550 * @nr_pages: the amount of swap space to uncharge
7552 void __mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
7554 struct mem_cgroup *memcg;
7557 if (mem_cgroup_disabled())
7560 id = swap_cgroup_record(entry, 0, nr_pages);
7562 memcg = mem_cgroup_from_id(id);
7564 if (!mem_cgroup_is_root(memcg)) {
7565 if (do_memsw_account())
7566 page_counter_uncharge(&memcg->memsw, nr_pages);
7568 page_counter_uncharge(&memcg->swap, nr_pages);
7570 mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
7571 mem_cgroup_id_put_many(memcg, nr_pages);
7576 long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
7578 long nr_swap_pages = get_nr_swap_pages();
7580 if (mem_cgroup_disabled() || do_memsw_account())
7581 return nr_swap_pages;
7582 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg))
7583 nr_swap_pages = min_t(long, nr_swap_pages,
7584 READ_ONCE(memcg->swap.max) -
7585 page_counter_read(&memcg->swap));
7586 return nr_swap_pages;
7589 bool mem_cgroup_swap_full(struct folio *folio)
7591 struct mem_cgroup *memcg;
7593 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
7597 if (do_memsw_account())
7600 memcg = folio_memcg(folio);
7604 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
7605 unsigned long usage = page_counter_read(&memcg->swap);
7607 if (usage * 2 >= READ_ONCE(memcg->swap.high) ||
7608 usage * 2 >= READ_ONCE(memcg->swap.max))
7615 static int __init setup_swap_account(char *s)
7617 pr_warn_once("The swapaccount= commandline option is deprecated. "
7618 "Please report your usecase to linux-mm@kvack.org if you "
7619 "depend on this functionality.\n");
7622 __setup("swapaccount=", setup_swap_account);
7624 static u64 swap_current_read(struct cgroup_subsys_state *css,
7627 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7629 return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
7632 static int swap_high_show(struct seq_file *m, void *v)
7634 return seq_puts_memcg_tunable(m,
7635 READ_ONCE(mem_cgroup_from_seq(m)->swap.high));
7638 static ssize_t swap_high_write(struct kernfs_open_file *of,
7639 char *buf, size_t nbytes, loff_t off)
7641 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7645 buf = strstrip(buf);
7646 err = page_counter_memparse(buf, "max", &high);
7650 page_counter_set_high(&memcg->swap, high);
7655 static int swap_max_show(struct seq_file *m, void *v)
7657 return seq_puts_memcg_tunable(m,
7658 READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
7661 static ssize_t swap_max_write(struct kernfs_open_file *of,
7662 char *buf, size_t nbytes, loff_t off)
7664 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7668 buf = strstrip(buf);
7669 err = page_counter_memparse(buf, "max", &max);
7673 xchg(&memcg->swap.max, max);
7678 static int swap_events_show(struct seq_file *m, void *v)
7680 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
7682 seq_printf(m, "high %lu\n",
7683 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH]));
7684 seq_printf(m, "max %lu\n",
7685 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
7686 seq_printf(m, "fail %lu\n",
7687 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
7692 static struct cftype swap_files[] = {
7694 .name = "swap.current",
7695 .flags = CFTYPE_NOT_ON_ROOT,
7696 .read_u64 = swap_current_read,
7699 .name = "swap.high",
7700 .flags = CFTYPE_NOT_ON_ROOT,
7701 .seq_show = swap_high_show,
7702 .write = swap_high_write,
7706 .flags = CFTYPE_NOT_ON_ROOT,
7707 .seq_show = swap_max_show,
7708 .write = swap_max_write,
7711 .name = "swap.events",
7712 .flags = CFTYPE_NOT_ON_ROOT,
7713 .file_offset = offsetof(struct mem_cgroup, swap_events_file),
7714 .seq_show = swap_events_show,
7719 static struct cftype memsw_files[] = {
7721 .name = "memsw.usage_in_bytes",
7722 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
7723 .read_u64 = mem_cgroup_read_u64,
7726 .name = "memsw.max_usage_in_bytes",
7727 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
7728 .write = mem_cgroup_reset,
7729 .read_u64 = mem_cgroup_read_u64,
7732 .name = "memsw.limit_in_bytes",
7733 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
7734 .write = mem_cgroup_write,
7735 .read_u64 = mem_cgroup_read_u64,
7738 .name = "memsw.failcnt",
7739 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
7740 .write = mem_cgroup_reset,
7741 .read_u64 = mem_cgroup_read_u64,
7743 { }, /* terminate */
7746 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
7748 * obj_cgroup_may_zswap - check if this cgroup can zswap
7749 * @objcg: the object cgroup
7751 * Check if the hierarchical zswap limit has been reached.
7753 * This doesn't check for specific headroom, and it is not atomic
7754 * either. But with zswap, the size of the allocation is only known
7755 * once compression has occured, and this optimistic pre-check avoids
7756 * spending cycles on compression when there is already no room left
7757 * or zswap is disabled altogether somewhere in the hierarchy.
7759 bool obj_cgroup_may_zswap(struct obj_cgroup *objcg)
7761 struct mem_cgroup *memcg, *original_memcg;
7764 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
7767 original_memcg = get_mem_cgroup_from_objcg(objcg);
7768 for (memcg = original_memcg; !mem_cgroup_is_root(memcg);
7769 memcg = parent_mem_cgroup(memcg)) {
7770 unsigned long max = READ_ONCE(memcg->zswap_max);
7771 unsigned long pages;
7773 if (max == PAGE_COUNTER_MAX)
7780 cgroup_rstat_flush(memcg->css.cgroup);
7781 pages = memcg_page_state(memcg, MEMCG_ZSWAP_B) / PAGE_SIZE;
7787 mem_cgroup_put(original_memcg);
7792 * obj_cgroup_charge_zswap - charge compression backend memory
7793 * @objcg: the object cgroup
7794 * @size: size of compressed object
7796 * This forces the charge after obj_cgroup_may_swap() allowed
7797 * compression and storage in zwap for this cgroup to go ahead.
7799 void obj_cgroup_charge_zswap(struct obj_cgroup *objcg, size_t size)
7801 struct mem_cgroup *memcg;
7803 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
7806 VM_WARN_ON_ONCE(!(current->flags & PF_MEMALLOC));
7808 /* PF_MEMALLOC context, charging must succeed */
7809 if (obj_cgroup_charge(objcg, GFP_KERNEL, size))
7813 memcg = obj_cgroup_memcg(objcg);
7814 mod_memcg_state(memcg, MEMCG_ZSWAP_B, size);
7815 mod_memcg_state(memcg, MEMCG_ZSWAPPED, 1);
7820 * obj_cgroup_uncharge_zswap - uncharge compression backend memory
7821 * @objcg: the object cgroup
7822 * @size: size of compressed object
7824 * Uncharges zswap memory on page in.
7826 void obj_cgroup_uncharge_zswap(struct obj_cgroup *objcg, size_t size)
7828 struct mem_cgroup *memcg;
7830 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
7833 obj_cgroup_uncharge(objcg, size);
7836 memcg = obj_cgroup_memcg(objcg);
7837 mod_memcg_state(memcg, MEMCG_ZSWAP_B, -size);
7838 mod_memcg_state(memcg, MEMCG_ZSWAPPED, -1);
7842 static u64 zswap_current_read(struct cgroup_subsys_state *css,
7845 cgroup_rstat_flush(css->cgroup);
7846 return memcg_page_state(mem_cgroup_from_css(css), MEMCG_ZSWAP_B);
7849 static int zswap_max_show(struct seq_file *m, void *v)
7851 return seq_puts_memcg_tunable(m,
7852 READ_ONCE(mem_cgroup_from_seq(m)->zswap_max));
7855 static ssize_t zswap_max_write(struct kernfs_open_file *of,
7856 char *buf, size_t nbytes, loff_t off)
7858 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7862 buf = strstrip(buf);
7863 err = page_counter_memparse(buf, "max", &max);
7867 xchg(&memcg->zswap_max, max);
7872 static struct cftype zswap_files[] = {
7874 .name = "zswap.current",
7875 .flags = CFTYPE_NOT_ON_ROOT,
7876 .read_u64 = zswap_current_read,
7879 .name = "zswap.max",
7880 .flags = CFTYPE_NOT_ON_ROOT,
7881 .seq_show = zswap_max_show,
7882 .write = zswap_max_write,
7886 #endif /* CONFIG_MEMCG_KMEM && CONFIG_ZSWAP */
7888 static int __init mem_cgroup_swap_init(void)
7890 if (mem_cgroup_disabled())
7893 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files));
7894 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files));
7895 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
7896 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, zswap_files));
7900 subsys_initcall(mem_cgroup_swap_init);
7902 #endif /* CONFIG_SWAP */