1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* memcontrol.c - Memory Controller
4 * Copyright IBM Corporation, 2007
5 * Author Balbir Singh <balbir@linux.vnet.ibm.com>
7 * Copyright 2007 OpenVZ SWsoft Inc
8 * Author: Pavel Emelianov <xemul@openvz.org>
11 * Copyright (C) 2009 Nokia Corporation
12 * Author: Kirill A. Shutemov
14 * Kernel Memory Controller
15 * Copyright (C) 2012 Parallels Inc. and Google Inc.
16 * Authors: Glauber Costa and Suleiman Souhlal
19 * Charge lifetime sanitation
20 * Lockless page tracking & accounting
21 * Unified hierarchy configuration model
22 * Copyright (C) 2015 Red Hat, Inc., Johannes Weiner
24 * Per memcg lru locking
25 * Copyright (C) 2020 Alibaba, Inc, Alex Shi
28 #include <linux/page_counter.h>
29 #include <linux/memcontrol.h>
30 #include <linux/cgroup.h>
31 #include <linux/pagewalk.h>
32 #include <linux/sched/mm.h>
33 #include <linux/shmem_fs.h>
34 #include <linux/hugetlb.h>
35 #include <linux/pagemap.h>
36 #include <linux/vm_event_item.h>
37 #include <linux/smp.h>
38 #include <linux/page-flags.h>
39 #include <linux/backing-dev.h>
40 #include <linux/bit_spinlock.h>
41 #include <linux/rcupdate.h>
42 #include <linux/limits.h>
43 #include <linux/export.h>
44 #include <linux/mutex.h>
45 #include <linux/rbtree.h>
46 #include <linux/slab.h>
47 #include <linux/swap.h>
48 #include <linux/swapops.h>
49 #include <linux/spinlock.h>
50 #include <linux/eventfd.h>
51 #include <linux/poll.h>
52 #include <linux/sort.h>
54 #include <linux/seq_file.h>
55 #include <linux/vmpressure.h>
56 #include <linux/memremap.h>
57 #include <linux/mm_inline.h>
58 #include <linux/swap_cgroup.h>
59 #include <linux/cpu.h>
60 #include <linux/oom.h>
61 #include <linux/lockdep.h>
62 #include <linux/file.h>
63 #include <linux/resume_user_mode.h>
64 #include <linux/psi.h>
65 #include <linux/seq_buf.h>
66 #include <linux/sched/isolation.h>
73 #include <linux/uaccess.h>
75 #include <trace/events/vmscan.h>
77 struct cgroup_subsys memory_cgrp_subsys __read_mostly;
78 EXPORT_SYMBOL(memory_cgrp_subsys);
80 struct mem_cgroup *root_mem_cgroup __read_mostly;
82 /* Active memory cgroup to use from an interrupt context */
83 DEFINE_PER_CPU(struct mem_cgroup *, int_active_memcg);
84 EXPORT_PER_CPU_SYMBOL_GPL(int_active_memcg);
86 /* Socket memory accounting disabled? */
87 static bool cgroup_memory_nosocket __ro_after_init;
89 /* Kernel memory accounting disabled? */
90 static bool cgroup_memory_nokmem __ro_after_init;
92 /* BPF memory accounting disabled? */
93 static bool cgroup_memory_nobpf __ro_after_init;
95 #ifdef CONFIG_CGROUP_WRITEBACK
96 static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq);
99 /* Whether legacy memory+swap accounting is active */
100 static bool do_memsw_account(void)
102 return !cgroup_subsys_on_dfl(memory_cgrp_subsys);
105 #define THRESHOLDS_EVENTS_TARGET 128
106 #define SOFTLIMIT_EVENTS_TARGET 1024
109 * Cgroups above their limits are maintained in a RB-Tree, independent of
110 * their hierarchy representation
113 struct mem_cgroup_tree_per_node {
114 struct rb_root rb_root;
115 struct rb_node *rb_rightmost;
119 struct mem_cgroup_tree {
120 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
123 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
126 struct mem_cgroup_eventfd_list {
127 struct list_head list;
128 struct eventfd_ctx *eventfd;
132 * cgroup_event represents events which userspace want to receive.
134 struct mem_cgroup_event {
136 * memcg which the event belongs to.
138 struct mem_cgroup *memcg;
140 * eventfd to signal userspace about the event.
142 struct eventfd_ctx *eventfd;
144 * Each of these stored in a list by the cgroup.
146 struct list_head list;
148 * register_event() callback will be used to add new userspace
149 * waiter for changes related to this event. Use eventfd_signal()
150 * on eventfd to send notification to userspace.
152 int (*register_event)(struct mem_cgroup *memcg,
153 struct eventfd_ctx *eventfd, const char *args);
155 * unregister_event() callback will be called when userspace closes
156 * the eventfd or on cgroup removing. This callback must be set,
157 * if you want provide notification functionality.
159 void (*unregister_event)(struct mem_cgroup *memcg,
160 struct eventfd_ctx *eventfd);
162 * All fields below needed to unregister event when
163 * userspace closes eventfd.
166 wait_queue_head_t *wqh;
167 wait_queue_entry_t wait;
168 struct work_struct remove;
171 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
172 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
174 /* Stuffs for move charges at task migration. */
176 * Types of charges to be moved.
178 #define MOVE_ANON 0x1U
179 #define MOVE_FILE 0x2U
180 #define MOVE_MASK (MOVE_ANON | MOVE_FILE)
182 /* "mc" and its members are protected by cgroup_mutex */
183 static struct move_charge_struct {
184 spinlock_t lock; /* for from, to */
185 struct mm_struct *mm;
186 struct mem_cgroup *from;
187 struct mem_cgroup *to;
189 unsigned long precharge;
190 unsigned long moved_charge;
191 unsigned long moved_swap;
192 struct task_struct *moving_task; /* a task moving charges */
193 wait_queue_head_t waitq; /* a waitq for other context */
195 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
196 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
200 * Maximum loops in mem_cgroup_soft_reclaim(), used for soft
201 * limit reclaim to prevent infinite loops, if they ever occur.
203 #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
204 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
206 /* for encoding cft->private value on file */
214 #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
215 #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
216 #define MEMFILE_ATTR(val) ((val) & 0xffff)
219 * Iteration constructs for visiting all cgroups (under a tree). If
220 * loops are exited prematurely (break), mem_cgroup_iter_break() must
221 * be used for reference counting.
223 #define for_each_mem_cgroup_tree(iter, root) \
224 for (iter = mem_cgroup_iter(root, NULL, NULL); \
226 iter = mem_cgroup_iter(root, iter, NULL))
228 #define for_each_mem_cgroup(iter) \
229 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
231 iter = mem_cgroup_iter(NULL, iter, NULL))
233 static inline bool task_is_dying(void)
235 return tsk_is_oom_victim(current) || fatal_signal_pending(current) ||
236 (current->flags & PF_EXITING);
239 /* Some nice accessors for the vmpressure. */
240 struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
243 memcg = root_mem_cgroup;
244 return &memcg->vmpressure;
247 struct mem_cgroup *vmpressure_to_memcg(struct vmpressure *vmpr)
249 return container_of(vmpr, struct mem_cgroup, vmpressure);
252 #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, nid);
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 /* Non-hierarchical (CPU aggregated) page state & events */
746 long state_local[MEMCG_NR_STAT];
747 unsigned long events_local[NR_MEMCG_EVENTS];
749 /* Pending child counts during tree propagation */
750 long state_pending[MEMCG_NR_STAT];
751 unsigned long events_pending[NR_MEMCG_EVENTS];
754 unsigned long memcg_page_state(struct mem_cgroup *memcg, int idx)
756 long x = READ_ONCE(memcg->vmstats->state[idx]);
765 * __mod_memcg_state - update cgroup memory statistics
766 * @memcg: the memory cgroup
767 * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item
768 * @val: delta to add to the counter, can be negative
770 void __mod_memcg_state(struct mem_cgroup *memcg, int idx, int val)
772 if (mem_cgroup_disabled())
775 __this_cpu_add(memcg->vmstats_percpu->state[idx], val);
776 memcg_rstat_updated(memcg, val);
779 /* idx can be of type enum memcg_stat_item or node_stat_item. */
780 static unsigned long memcg_page_state_local(struct mem_cgroup *memcg, int idx)
782 long x = READ_ONCE(memcg->vmstats->state_local[idx]);
791 void __mod_memcg_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
794 struct mem_cgroup_per_node *pn;
795 struct mem_cgroup *memcg;
797 pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
801 * The caller from rmap relay on disabled preemption becase they never
802 * update their counter from in-interrupt context. For these two
803 * counters we check that the update is never performed from an
804 * interrupt context while other caller need to have disabled interrupt.
806 __memcg_stats_lock();
807 if (IS_ENABLED(CONFIG_DEBUG_VM)) {
812 case NR_SHMEM_PMDMAPPED:
813 case NR_FILE_PMDMAPPED:
814 WARN_ON_ONCE(!in_task());
817 VM_WARN_ON_IRQS_ENABLED();
822 __this_cpu_add(memcg->vmstats_percpu->state[idx], val);
825 __this_cpu_add(pn->lruvec_stats_percpu->state[idx], val);
827 memcg_rstat_updated(memcg, val);
828 memcg_stats_unlock();
832 * __mod_lruvec_state - update lruvec memory statistics
833 * @lruvec: the lruvec
834 * @idx: the stat item
835 * @val: delta to add to the counter, can be negative
837 * The lruvec is the intersection of the NUMA node and a cgroup. This
838 * function updates the all three counters that are affected by a
839 * change of state at this level: per-node, per-cgroup, per-lruvec.
841 void __mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
845 __mod_node_page_state(lruvec_pgdat(lruvec), idx, val);
847 /* Update memcg and lruvec */
848 if (!mem_cgroup_disabled())
849 __mod_memcg_lruvec_state(lruvec, idx, val);
852 void __mod_lruvec_page_state(struct page *page, enum node_stat_item idx,
855 struct page *head = compound_head(page); /* rmap on tail pages */
856 struct mem_cgroup *memcg;
857 pg_data_t *pgdat = page_pgdat(page);
858 struct lruvec *lruvec;
861 memcg = page_memcg(head);
862 /* Untracked pages have no memcg, no lruvec. Update only the node */
865 __mod_node_page_state(pgdat, idx, val);
869 lruvec = mem_cgroup_lruvec(memcg, pgdat);
870 __mod_lruvec_state(lruvec, idx, val);
873 EXPORT_SYMBOL(__mod_lruvec_page_state);
875 void __mod_lruvec_kmem_state(void *p, enum node_stat_item idx, int val)
877 pg_data_t *pgdat = page_pgdat(virt_to_page(p));
878 struct mem_cgroup *memcg;
879 struct lruvec *lruvec;
882 memcg = mem_cgroup_from_slab_obj(p);
885 * Untracked pages have no memcg, no lruvec. Update only the
886 * node. If we reparent the slab objects to the root memcg,
887 * when we free the slab object, we need to update the per-memcg
888 * vmstats to keep it correct for the root memcg.
891 __mod_node_page_state(pgdat, idx, val);
893 lruvec = mem_cgroup_lruvec(memcg, pgdat);
894 __mod_lruvec_state(lruvec, idx, val);
900 * __count_memcg_events - account VM events in a cgroup
901 * @memcg: the memory cgroup
902 * @idx: the event item
903 * @count: the number of events that occurred
905 void __count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx,
908 int index = memcg_events_index(idx);
910 if (mem_cgroup_disabled() || index < 0)
914 __this_cpu_add(memcg->vmstats_percpu->events[index], count);
915 memcg_rstat_updated(memcg, count);
916 memcg_stats_unlock();
919 static unsigned long memcg_events(struct mem_cgroup *memcg, int event)
921 int index = memcg_events_index(event);
925 return READ_ONCE(memcg->vmstats->events[index]);
928 static unsigned long memcg_events_local(struct mem_cgroup *memcg, int event)
930 int index = memcg_events_index(event);
935 return READ_ONCE(memcg->vmstats->events_local[index]);
938 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
941 /* pagein of a big page is an event. So, ignore page size */
943 __count_memcg_events(memcg, PGPGIN, 1);
945 __count_memcg_events(memcg, PGPGOUT, 1);
946 nr_pages = -nr_pages; /* for event */
949 __this_cpu_add(memcg->vmstats_percpu->nr_page_events, nr_pages);
952 static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
953 enum mem_cgroup_events_target target)
955 unsigned long val, next;
957 val = __this_cpu_read(memcg->vmstats_percpu->nr_page_events);
958 next = __this_cpu_read(memcg->vmstats_percpu->targets[target]);
959 /* from time_after() in jiffies.h */
960 if ((long)(next - val) < 0) {
962 case MEM_CGROUP_TARGET_THRESH:
963 next = val + THRESHOLDS_EVENTS_TARGET;
965 case MEM_CGROUP_TARGET_SOFTLIMIT:
966 next = val + SOFTLIMIT_EVENTS_TARGET;
971 __this_cpu_write(memcg->vmstats_percpu->targets[target], next);
978 * Check events in order.
981 static void memcg_check_events(struct mem_cgroup *memcg, int nid)
983 if (IS_ENABLED(CONFIG_PREEMPT_RT))
986 /* threshold event is triggered in finer grain than soft limit */
987 if (unlikely(mem_cgroup_event_ratelimit(memcg,
988 MEM_CGROUP_TARGET_THRESH))) {
991 do_softlimit = mem_cgroup_event_ratelimit(memcg,
992 MEM_CGROUP_TARGET_SOFTLIMIT);
993 mem_cgroup_threshold(memcg);
994 if (unlikely(do_softlimit))
995 mem_cgroup_update_tree(memcg, nid);
999 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
1002 * mm_update_next_owner() may clear mm->owner to NULL
1003 * if it races with swapoff, page migration, etc.
1004 * So this can be called with p == NULL.
1009 return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
1011 EXPORT_SYMBOL(mem_cgroup_from_task);
1013 static __always_inline struct mem_cgroup *active_memcg(void)
1016 return this_cpu_read(int_active_memcg);
1018 return current->active_memcg;
1022 * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
1023 * @mm: mm from which memcg should be extracted. It can be NULL.
1025 * Obtain a reference on mm->memcg and returns it if successful. If mm
1026 * is NULL, then the memcg is chosen as follows:
1027 * 1) The active memcg, if set.
1028 * 2) current->mm->memcg, if available
1030 * If mem_cgroup is disabled, NULL is returned.
1032 struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
1034 struct mem_cgroup *memcg;
1036 if (mem_cgroup_disabled())
1040 * Page cache insertions can happen without an
1041 * actual mm context, e.g. during disk probing
1042 * on boot, loopback IO, acct() writes etc.
1044 * No need to css_get on root memcg as the reference
1045 * counting is disabled on the root level in the
1046 * cgroup core. See CSS_NO_REF.
1048 if (unlikely(!mm)) {
1049 memcg = active_memcg();
1050 if (unlikely(memcg)) {
1051 /* remote memcg must hold a ref */
1052 css_get(&memcg->css);
1057 return root_mem_cgroup;
1062 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1063 if (unlikely(!memcg))
1064 memcg = root_mem_cgroup;
1065 } while (!css_tryget(&memcg->css));
1069 EXPORT_SYMBOL(get_mem_cgroup_from_mm);
1071 static __always_inline bool memcg_kmem_bypass(void)
1073 /* Allow remote memcg charging from any context. */
1074 if (unlikely(active_memcg()))
1077 /* Memcg to charge can't be determined. */
1078 if (!in_task() || !current->mm || (current->flags & PF_KTHREAD))
1085 * mem_cgroup_iter - iterate over memory cgroup hierarchy
1086 * @root: hierarchy root
1087 * @prev: previously returned memcg, NULL on first invocation
1088 * @reclaim: cookie for shared reclaim walks, NULL for full walks
1090 * Returns references to children of the hierarchy below @root, or
1091 * @root itself, or %NULL after a full round-trip.
1093 * Caller must pass the return value in @prev on subsequent
1094 * invocations for reference counting, or use mem_cgroup_iter_break()
1095 * to cancel a hierarchy walk before the round-trip is complete.
1097 * Reclaimers can specify a node in @reclaim to divide up the memcgs
1098 * in the hierarchy among all concurrent reclaimers operating on the
1101 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
1102 struct mem_cgroup *prev,
1103 struct mem_cgroup_reclaim_cookie *reclaim)
1105 struct mem_cgroup_reclaim_iter *iter;
1106 struct cgroup_subsys_state *css = NULL;
1107 struct mem_cgroup *memcg = NULL;
1108 struct mem_cgroup *pos = NULL;
1110 if (mem_cgroup_disabled())
1114 root = root_mem_cgroup;
1119 struct mem_cgroup_per_node *mz;
1121 mz = root->nodeinfo[reclaim->pgdat->node_id];
1125 * On start, join the current reclaim iteration cycle.
1126 * Exit when a concurrent walker completes it.
1129 reclaim->generation = iter->generation;
1130 else if (reclaim->generation != iter->generation)
1134 pos = READ_ONCE(iter->position);
1135 if (!pos || css_tryget(&pos->css))
1138 * css reference reached zero, so iter->position will
1139 * be cleared by ->css_released. However, we should not
1140 * rely on this happening soon, because ->css_released
1141 * is called from a work queue, and by busy-waiting we
1142 * might block it. So we clear iter->position right
1145 (void)cmpxchg(&iter->position, pos, NULL);
1155 css = css_next_descendant_pre(css, &root->css);
1158 * Reclaimers share the hierarchy walk, and a
1159 * new one might jump in right at the end of
1160 * the hierarchy - make sure they see at least
1161 * one group and restart from the beginning.
1169 * Verify the css and acquire a reference. The root
1170 * is provided by the caller, so we know it's alive
1171 * and kicking, and don't take an extra reference.
1173 if (css == &root->css || css_tryget(css)) {
1174 memcg = mem_cgroup_from_css(css);
1181 * The position could have already been updated by a competing
1182 * thread, so check that the value hasn't changed since we read
1183 * it to avoid reclaiming from the same cgroup twice.
1185 (void)cmpxchg(&iter->position, pos, memcg);
1196 if (prev && prev != root)
1197 css_put(&prev->css);
1203 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1204 * @root: hierarchy root
1205 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1207 void mem_cgroup_iter_break(struct mem_cgroup *root,
1208 struct mem_cgroup *prev)
1211 root = root_mem_cgroup;
1212 if (prev && prev != root)
1213 css_put(&prev->css);
1216 static void __invalidate_reclaim_iterators(struct mem_cgroup *from,
1217 struct mem_cgroup *dead_memcg)
1219 struct mem_cgroup_reclaim_iter *iter;
1220 struct mem_cgroup_per_node *mz;
1223 for_each_node(nid) {
1224 mz = from->nodeinfo[nid];
1226 cmpxchg(&iter->position, dead_memcg, NULL);
1230 static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
1232 struct mem_cgroup *memcg = dead_memcg;
1233 struct mem_cgroup *last;
1236 __invalidate_reclaim_iterators(memcg, dead_memcg);
1238 } while ((memcg = parent_mem_cgroup(memcg)));
1241 * When cgroup1 non-hierarchy mode is used,
1242 * parent_mem_cgroup() does not walk all the way up to the
1243 * cgroup root (root_mem_cgroup). So we have to handle
1244 * dead_memcg from cgroup root separately.
1246 if (!mem_cgroup_is_root(last))
1247 __invalidate_reclaim_iterators(root_mem_cgroup,
1252 * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
1253 * @memcg: hierarchy root
1254 * @fn: function to call for each task
1255 * @arg: argument passed to @fn
1257 * This function iterates over tasks attached to @memcg or to any of its
1258 * descendants and calls @fn for each task. If @fn returns a non-zero
1259 * value, the function breaks the iteration loop. Otherwise, it will iterate
1260 * over all tasks and return 0.
1262 * This function must not be called for the root memory cgroup.
1264 void mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
1265 int (*fn)(struct task_struct *, void *), void *arg)
1267 struct mem_cgroup *iter;
1270 BUG_ON(mem_cgroup_is_root(memcg));
1272 for_each_mem_cgroup_tree(iter, memcg) {
1273 struct css_task_iter it;
1274 struct task_struct *task;
1276 css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it);
1277 while (!ret && (task = css_task_iter_next(&it)))
1278 ret = fn(task, arg);
1279 css_task_iter_end(&it);
1281 mem_cgroup_iter_break(memcg, iter);
1287 #ifdef CONFIG_DEBUG_VM
1288 void lruvec_memcg_debug(struct lruvec *lruvec, struct folio *folio)
1290 struct mem_cgroup *memcg;
1292 if (mem_cgroup_disabled())
1295 memcg = folio_memcg(folio);
1298 VM_BUG_ON_FOLIO(!mem_cgroup_is_root(lruvec_memcg(lruvec)), folio);
1300 VM_BUG_ON_FOLIO(lruvec_memcg(lruvec) != memcg, folio);
1305 * folio_lruvec_lock - Lock the lruvec for a folio.
1306 * @folio: Pointer to the folio.
1308 * These functions are safe to use under any of the following conditions:
1310 * - folio_test_lru false
1311 * - folio_memcg_lock()
1312 * - folio frozen (refcount of 0)
1314 * Return: The lruvec this folio is on with its lock held.
1316 struct lruvec *folio_lruvec_lock(struct folio *folio)
1318 struct lruvec *lruvec = folio_lruvec(folio);
1320 spin_lock(&lruvec->lru_lock);
1321 lruvec_memcg_debug(lruvec, folio);
1327 * folio_lruvec_lock_irq - Lock the lruvec for a folio.
1328 * @folio: Pointer to the folio.
1330 * These functions are safe to use under any of the following conditions:
1332 * - folio_test_lru false
1333 * - folio_memcg_lock()
1334 * - folio frozen (refcount of 0)
1336 * Return: The lruvec this folio is on with its lock held and interrupts
1339 struct lruvec *folio_lruvec_lock_irq(struct folio *folio)
1341 struct lruvec *lruvec = folio_lruvec(folio);
1343 spin_lock_irq(&lruvec->lru_lock);
1344 lruvec_memcg_debug(lruvec, folio);
1350 * folio_lruvec_lock_irqsave - Lock the lruvec for a folio.
1351 * @folio: Pointer to the folio.
1352 * @flags: Pointer to irqsave flags.
1354 * These functions are safe to use under any of the following conditions:
1356 * - folio_test_lru false
1357 * - folio_memcg_lock()
1358 * - folio frozen (refcount of 0)
1360 * Return: The lruvec this folio is on with its lock held and interrupts
1363 struct lruvec *folio_lruvec_lock_irqsave(struct folio *folio,
1364 unsigned long *flags)
1366 struct lruvec *lruvec = folio_lruvec(folio);
1368 spin_lock_irqsave(&lruvec->lru_lock, *flags);
1369 lruvec_memcg_debug(lruvec, folio);
1375 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1376 * @lruvec: mem_cgroup per zone lru vector
1377 * @lru: index of lru list the page is sitting on
1378 * @zid: zone id of the accounted pages
1379 * @nr_pages: positive when adding or negative when removing
1381 * This function must be called under lru_lock, just before a page is added
1382 * to or just after a page is removed from an lru list.
1384 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1385 int zid, int nr_pages)
1387 struct mem_cgroup_per_node *mz;
1388 unsigned long *lru_size;
1391 if (mem_cgroup_disabled())
1394 mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
1395 lru_size = &mz->lru_zone_size[zid][lru];
1398 *lru_size += nr_pages;
1401 if (WARN_ONCE(size < 0,
1402 "%s(%p, %d, %d): lru_size %ld\n",
1403 __func__, lruvec, lru, nr_pages, size)) {
1409 *lru_size += nr_pages;
1413 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1414 * @memcg: the memory cgroup
1416 * Returns the maximum amount of memory @mem can be charged with, in
1419 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1421 unsigned long margin = 0;
1422 unsigned long count;
1423 unsigned long limit;
1425 count = page_counter_read(&memcg->memory);
1426 limit = READ_ONCE(memcg->memory.max);
1428 margin = limit - count;
1430 if (do_memsw_account()) {
1431 count = page_counter_read(&memcg->memsw);
1432 limit = READ_ONCE(memcg->memsw.max);
1434 margin = min(margin, limit - count);
1443 * A routine for checking "mem" is under move_account() or not.
1445 * Checking a cgroup is mc.from or mc.to or under hierarchy of
1446 * moving cgroups. This is for waiting at high-memory pressure
1449 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1451 struct mem_cgroup *from;
1452 struct mem_cgroup *to;
1455 * Unlike task_move routines, we access mc.to, mc.from not under
1456 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1458 spin_lock(&mc.lock);
1464 ret = mem_cgroup_is_descendant(from, memcg) ||
1465 mem_cgroup_is_descendant(to, memcg);
1467 spin_unlock(&mc.lock);
1471 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1473 if (mc.moving_task && current != mc.moving_task) {
1474 if (mem_cgroup_under_move(memcg)) {
1476 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1477 /* moving charge context might have finished. */
1480 finish_wait(&mc.waitq, &wait);
1487 struct memory_stat {
1492 static const struct memory_stat memory_stats[] = {
1493 { "anon", NR_ANON_MAPPED },
1494 { "file", NR_FILE_PAGES },
1495 { "kernel", MEMCG_KMEM },
1496 { "kernel_stack", NR_KERNEL_STACK_KB },
1497 { "pagetables", NR_PAGETABLE },
1498 { "sec_pagetables", NR_SECONDARY_PAGETABLE },
1499 { "percpu", MEMCG_PERCPU_B },
1500 { "sock", MEMCG_SOCK },
1501 { "vmalloc", MEMCG_VMALLOC },
1502 { "shmem", NR_SHMEM },
1503 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
1504 { "zswap", MEMCG_ZSWAP_B },
1505 { "zswapped", MEMCG_ZSWAPPED },
1507 { "file_mapped", NR_FILE_MAPPED },
1508 { "file_dirty", NR_FILE_DIRTY },
1509 { "file_writeback", NR_WRITEBACK },
1511 { "swapcached", NR_SWAPCACHE },
1513 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1514 { "anon_thp", NR_ANON_THPS },
1515 { "file_thp", NR_FILE_THPS },
1516 { "shmem_thp", NR_SHMEM_THPS },
1518 { "inactive_anon", NR_INACTIVE_ANON },
1519 { "active_anon", NR_ACTIVE_ANON },
1520 { "inactive_file", NR_INACTIVE_FILE },
1521 { "active_file", NR_ACTIVE_FILE },
1522 { "unevictable", NR_UNEVICTABLE },
1523 { "slab_reclaimable", NR_SLAB_RECLAIMABLE_B },
1524 { "slab_unreclaimable", NR_SLAB_UNRECLAIMABLE_B },
1526 /* The memory events */
1527 { "workingset_refault_anon", WORKINGSET_REFAULT_ANON },
1528 { "workingset_refault_file", WORKINGSET_REFAULT_FILE },
1529 { "workingset_activate_anon", WORKINGSET_ACTIVATE_ANON },
1530 { "workingset_activate_file", WORKINGSET_ACTIVATE_FILE },
1531 { "workingset_restore_anon", WORKINGSET_RESTORE_ANON },
1532 { "workingset_restore_file", WORKINGSET_RESTORE_FILE },
1533 { "workingset_nodereclaim", WORKINGSET_NODERECLAIM },
1536 /* Translate stat items to the correct unit for memory.stat output */
1537 static int memcg_page_state_unit(int item)
1540 case MEMCG_PERCPU_B:
1542 case NR_SLAB_RECLAIMABLE_B:
1543 case NR_SLAB_UNRECLAIMABLE_B:
1544 case WORKINGSET_REFAULT_ANON:
1545 case WORKINGSET_REFAULT_FILE:
1546 case WORKINGSET_ACTIVATE_ANON:
1547 case WORKINGSET_ACTIVATE_FILE:
1548 case WORKINGSET_RESTORE_ANON:
1549 case WORKINGSET_RESTORE_FILE:
1550 case WORKINGSET_NODERECLAIM:
1552 case NR_KERNEL_STACK_KB:
1559 static inline unsigned long memcg_page_state_output(struct mem_cgroup *memcg,
1562 return memcg_page_state(memcg, item) * memcg_page_state_unit(item);
1565 static void memcg_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
1570 * Provide statistics on the state of the memory subsystem as
1571 * well as cumulative event counters that show past behavior.
1573 * This list is ordered following a combination of these gradients:
1574 * 1) generic big picture -> specifics and details
1575 * 2) reflecting userspace activity -> reflecting kernel heuristics
1577 * Current memory state:
1579 mem_cgroup_flush_stats();
1581 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
1584 size = memcg_page_state_output(memcg, memory_stats[i].idx);
1585 seq_buf_printf(s, "%s %llu\n", memory_stats[i].name, size);
1587 if (unlikely(memory_stats[i].idx == NR_SLAB_UNRECLAIMABLE_B)) {
1588 size += memcg_page_state_output(memcg,
1589 NR_SLAB_RECLAIMABLE_B);
1590 seq_buf_printf(s, "slab %llu\n", size);
1594 /* Accumulated memory events */
1595 seq_buf_printf(s, "pgscan %lu\n",
1596 memcg_events(memcg, PGSCAN_KSWAPD) +
1597 memcg_events(memcg, PGSCAN_DIRECT) +
1598 memcg_events(memcg, PGSCAN_KHUGEPAGED));
1599 seq_buf_printf(s, "pgsteal %lu\n",
1600 memcg_events(memcg, PGSTEAL_KSWAPD) +
1601 memcg_events(memcg, PGSTEAL_DIRECT) +
1602 memcg_events(memcg, PGSTEAL_KHUGEPAGED));
1604 for (i = 0; i < ARRAY_SIZE(memcg_vm_event_stat); i++) {
1605 if (memcg_vm_event_stat[i] == PGPGIN ||
1606 memcg_vm_event_stat[i] == PGPGOUT)
1609 seq_buf_printf(s, "%s %lu\n",
1610 vm_event_name(memcg_vm_event_stat[i]),
1611 memcg_events(memcg, memcg_vm_event_stat[i]));
1614 /* The above should easily fit into one page */
1615 WARN_ON_ONCE(seq_buf_has_overflowed(s));
1618 static void memcg1_stat_format(struct mem_cgroup *memcg, struct seq_buf *s);
1620 static void memory_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
1622 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1623 memcg_stat_format(memcg, s);
1625 memcg1_stat_format(memcg, s);
1626 WARN_ON_ONCE(seq_buf_has_overflowed(s));
1630 * mem_cgroup_print_oom_context: Print OOM information relevant to
1631 * memory controller.
1632 * @memcg: The memory cgroup that went over limit
1633 * @p: Task that is going to be killed
1635 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1638 void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p)
1643 pr_cont(",oom_memcg=");
1644 pr_cont_cgroup_path(memcg->css.cgroup);
1646 pr_cont(",global_oom");
1648 pr_cont(",task_memcg=");
1649 pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
1655 * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
1656 * memory controller.
1657 * @memcg: The memory cgroup that went over limit
1659 void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
1661 /* Use static buffer, for the caller is holding oom_lock. */
1662 static char buf[PAGE_SIZE];
1665 lockdep_assert_held(&oom_lock);
1667 pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1668 K((u64)page_counter_read(&memcg->memory)),
1669 K((u64)READ_ONCE(memcg->memory.max)), memcg->memory.failcnt);
1670 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1671 pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n",
1672 K((u64)page_counter_read(&memcg->swap)),
1673 K((u64)READ_ONCE(memcg->swap.max)), memcg->swap.failcnt);
1675 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1676 K((u64)page_counter_read(&memcg->memsw)),
1677 K((u64)memcg->memsw.max), memcg->memsw.failcnt);
1678 pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1679 K((u64)page_counter_read(&memcg->kmem)),
1680 K((u64)memcg->kmem.max), memcg->kmem.failcnt);
1683 pr_info("Memory cgroup stats for ");
1684 pr_cont_cgroup_path(memcg->css.cgroup);
1686 seq_buf_init(&s, buf, sizeof(buf));
1687 memory_stat_format(memcg, &s);
1688 seq_buf_do_printk(&s, KERN_INFO);
1692 * Return the memory (and swap, if configured) limit for a memcg.
1694 unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg)
1696 unsigned long max = READ_ONCE(memcg->memory.max);
1698 if (do_memsw_account()) {
1699 if (mem_cgroup_swappiness(memcg)) {
1700 /* Calculate swap excess capacity from memsw limit */
1701 unsigned long swap = READ_ONCE(memcg->memsw.max) - max;
1703 max += min(swap, (unsigned long)total_swap_pages);
1706 if (mem_cgroup_swappiness(memcg))
1707 max += min(READ_ONCE(memcg->swap.max),
1708 (unsigned long)total_swap_pages);
1713 unsigned long mem_cgroup_size(struct mem_cgroup *memcg)
1715 return page_counter_read(&memcg->memory);
1718 static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1721 struct oom_control oc = {
1725 .gfp_mask = gfp_mask,
1730 if (mutex_lock_killable(&oom_lock))
1733 if (mem_cgroup_margin(memcg) >= (1 << order))
1737 * A few threads which were not waiting at mutex_lock_killable() can
1738 * fail to bail out. Therefore, check again after holding oom_lock.
1740 ret = task_is_dying() || out_of_memory(&oc);
1743 mutex_unlock(&oom_lock);
1747 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
1750 unsigned long *total_scanned)
1752 struct mem_cgroup *victim = NULL;
1755 unsigned long excess;
1756 unsigned long nr_scanned;
1757 struct mem_cgroup_reclaim_cookie reclaim = {
1761 excess = soft_limit_excess(root_memcg);
1764 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1769 * If we have not been able to reclaim
1770 * anything, it might because there are
1771 * no reclaimable pages under this hierarchy
1776 * We want to do more targeted reclaim.
1777 * excess >> 2 is not to excessive so as to
1778 * reclaim too much, nor too less that we keep
1779 * coming back to reclaim from this cgroup
1781 if (total >= (excess >> 2) ||
1782 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1787 total += mem_cgroup_shrink_node(victim, gfp_mask, false,
1788 pgdat, &nr_scanned);
1789 *total_scanned += nr_scanned;
1790 if (!soft_limit_excess(root_memcg))
1793 mem_cgroup_iter_break(root_memcg, victim);
1797 #ifdef CONFIG_LOCKDEP
1798 static struct lockdep_map memcg_oom_lock_dep_map = {
1799 .name = "memcg_oom_lock",
1803 static DEFINE_SPINLOCK(memcg_oom_lock);
1806 * Check OOM-Killer is already running under our hierarchy.
1807 * If someone is running, return false.
1809 static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
1811 struct mem_cgroup *iter, *failed = NULL;
1813 spin_lock(&memcg_oom_lock);
1815 for_each_mem_cgroup_tree(iter, memcg) {
1816 if (iter->oom_lock) {
1818 * this subtree of our hierarchy is already locked
1819 * so we cannot give a lock.
1822 mem_cgroup_iter_break(memcg, iter);
1825 iter->oom_lock = true;
1830 * OK, we failed to lock the whole subtree so we have
1831 * to clean up what we set up to the failing subtree
1833 for_each_mem_cgroup_tree(iter, memcg) {
1834 if (iter == failed) {
1835 mem_cgroup_iter_break(memcg, iter);
1838 iter->oom_lock = false;
1841 mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
1843 spin_unlock(&memcg_oom_lock);
1848 static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1850 struct mem_cgroup *iter;
1852 spin_lock(&memcg_oom_lock);
1853 mutex_release(&memcg_oom_lock_dep_map, _RET_IP_);
1854 for_each_mem_cgroup_tree(iter, memcg)
1855 iter->oom_lock = false;
1856 spin_unlock(&memcg_oom_lock);
1859 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1861 struct mem_cgroup *iter;
1863 spin_lock(&memcg_oom_lock);
1864 for_each_mem_cgroup_tree(iter, memcg)
1866 spin_unlock(&memcg_oom_lock);
1869 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1871 struct mem_cgroup *iter;
1874 * Be careful about under_oom underflows because a child memcg
1875 * could have been added after mem_cgroup_mark_under_oom.
1877 spin_lock(&memcg_oom_lock);
1878 for_each_mem_cgroup_tree(iter, memcg)
1879 if (iter->under_oom > 0)
1881 spin_unlock(&memcg_oom_lock);
1884 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1886 struct oom_wait_info {
1887 struct mem_cgroup *memcg;
1888 wait_queue_entry_t wait;
1891 static int memcg_oom_wake_function(wait_queue_entry_t *wait,
1892 unsigned mode, int sync, void *arg)
1894 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
1895 struct mem_cgroup *oom_wait_memcg;
1896 struct oom_wait_info *oom_wait_info;
1898 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1899 oom_wait_memcg = oom_wait_info->memcg;
1901 if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
1902 !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
1904 return autoremove_wake_function(wait, mode, sync, arg);
1907 static void memcg_oom_recover(struct mem_cgroup *memcg)
1910 * For the following lockless ->under_oom test, the only required
1911 * guarantee is that it must see the state asserted by an OOM when
1912 * this function is called as a result of userland actions
1913 * triggered by the notification of the OOM. This is trivially
1914 * achieved by invoking mem_cgroup_mark_under_oom() before
1915 * triggering notification.
1917 if (memcg && memcg->under_oom)
1918 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
1922 * Returns true if successfully killed one or more processes. Though in some
1923 * corner cases it can return true even without killing any process.
1925 static bool mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
1929 if (order > PAGE_ALLOC_COSTLY_ORDER)
1932 memcg_memory_event(memcg, MEMCG_OOM);
1935 * We are in the middle of the charge context here, so we
1936 * don't want to block when potentially sitting on a callstack
1937 * that holds all kinds of filesystem and mm locks.
1939 * cgroup1 allows disabling the OOM killer and waiting for outside
1940 * handling until the charge can succeed; remember the context and put
1941 * the task to sleep at the end of the page fault when all locks are
1944 * On the other hand, in-kernel OOM killer allows for an async victim
1945 * memory reclaim (oom_reaper) and that means that we are not solely
1946 * relying on the oom victim to make a forward progress and we can
1947 * invoke the oom killer here.
1949 * Please note that mem_cgroup_out_of_memory might fail to find a
1950 * victim and then we have to bail out from the charge path.
1952 if (READ_ONCE(memcg->oom_kill_disable)) {
1953 if (current->in_user_fault) {
1954 css_get(&memcg->css);
1955 current->memcg_in_oom = memcg;
1956 current->memcg_oom_gfp_mask = mask;
1957 current->memcg_oom_order = order;
1962 mem_cgroup_mark_under_oom(memcg);
1964 locked = mem_cgroup_oom_trylock(memcg);
1967 mem_cgroup_oom_notify(memcg);
1969 mem_cgroup_unmark_under_oom(memcg);
1970 ret = mem_cgroup_out_of_memory(memcg, mask, order);
1973 mem_cgroup_oom_unlock(memcg);
1979 * mem_cgroup_oom_synchronize - complete memcg OOM handling
1980 * @handle: actually kill/wait or just clean up the OOM state
1982 * This has to be called at the end of a page fault if the memcg OOM
1983 * handler was enabled.
1985 * Memcg supports userspace OOM handling where failed allocations must
1986 * sleep on a waitqueue until the userspace task resolves the
1987 * situation. Sleeping directly in the charge context with all kinds
1988 * of locks held is not a good idea, instead we remember an OOM state
1989 * in the task and mem_cgroup_oom_synchronize() has to be called at
1990 * the end of the page fault to complete the OOM handling.
1992 * Returns %true if an ongoing memcg OOM situation was detected and
1993 * completed, %false otherwise.
1995 bool mem_cgroup_oom_synchronize(bool handle)
1997 struct mem_cgroup *memcg = current->memcg_in_oom;
1998 struct oom_wait_info owait;
2001 /* OOM is global, do not handle */
2008 owait.memcg = memcg;
2009 owait.wait.flags = 0;
2010 owait.wait.func = memcg_oom_wake_function;
2011 owait.wait.private = current;
2012 INIT_LIST_HEAD(&owait.wait.entry);
2014 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
2015 mem_cgroup_mark_under_oom(memcg);
2017 locked = mem_cgroup_oom_trylock(memcg);
2020 mem_cgroup_oom_notify(memcg);
2023 mem_cgroup_unmark_under_oom(memcg);
2024 finish_wait(&memcg_oom_waitq, &owait.wait);
2027 mem_cgroup_oom_unlock(memcg);
2029 current->memcg_in_oom = NULL;
2030 css_put(&memcg->css);
2035 * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
2036 * @victim: task to be killed by the OOM killer
2037 * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
2039 * Returns a pointer to a memory cgroup, which has to be cleaned up
2040 * by killing all belonging OOM-killable tasks.
2042 * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
2044 struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim,
2045 struct mem_cgroup *oom_domain)
2047 struct mem_cgroup *oom_group = NULL;
2048 struct mem_cgroup *memcg;
2050 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
2054 oom_domain = root_mem_cgroup;
2058 memcg = mem_cgroup_from_task(victim);
2059 if (mem_cgroup_is_root(memcg))
2063 * If the victim task has been asynchronously moved to a different
2064 * memory cgroup, we might end up killing tasks outside oom_domain.
2065 * In this case it's better to ignore memory.group.oom.
2067 if (unlikely(!mem_cgroup_is_descendant(memcg, oom_domain)))
2071 * Traverse the memory cgroup hierarchy from the victim task's
2072 * cgroup up to the OOMing cgroup (or root) to find the
2073 * highest-level memory cgroup with oom.group set.
2075 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
2076 if (READ_ONCE(memcg->oom_group))
2079 if (memcg == oom_domain)
2084 css_get(&oom_group->css);
2091 void mem_cgroup_print_oom_group(struct mem_cgroup *memcg)
2093 pr_info("Tasks in ");
2094 pr_cont_cgroup_path(memcg->css.cgroup);
2095 pr_cont(" are going to be killed due to memory.oom.group set\n");
2099 * folio_memcg_lock - Bind a folio to its memcg.
2100 * @folio: The folio.
2102 * This function prevents unlocked LRU folios from being moved to
2105 * It ensures lifetime of the bound memcg. The caller is responsible
2106 * for the lifetime of the folio.
2108 void folio_memcg_lock(struct folio *folio)
2110 struct mem_cgroup *memcg;
2111 unsigned long flags;
2114 * The RCU lock is held throughout the transaction. The fast
2115 * path can get away without acquiring the memcg->move_lock
2116 * because page moving starts with an RCU grace period.
2120 if (mem_cgroup_disabled())
2123 memcg = folio_memcg(folio);
2124 if (unlikely(!memcg))
2127 #ifdef CONFIG_PROVE_LOCKING
2128 local_irq_save(flags);
2129 might_lock(&memcg->move_lock);
2130 local_irq_restore(flags);
2133 if (atomic_read(&memcg->moving_account) <= 0)
2136 spin_lock_irqsave(&memcg->move_lock, flags);
2137 if (memcg != folio_memcg(folio)) {
2138 spin_unlock_irqrestore(&memcg->move_lock, flags);
2143 * When charge migration first begins, we can have multiple
2144 * critical sections holding the fast-path RCU lock and one
2145 * holding the slowpath move_lock. Track the task who has the
2146 * move_lock for folio_memcg_unlock().
2148 memcg->move_lock_task = current;
2149 memcg->move_lock_flags = flags;
2152 static void __folio_memcg_unlock(struct mem_cgroup *memcg)
2154 if (memcg && memcg->move_lock_task == current) {
2155 unsigned long flags = memcg->move_lock_flags;
2157 memcg->move_lock_task = NULL;
2158 memcg->move_lock_flags = 0;
2160 spin_unlock_irqrestore(&memcg->move_lock, flags);
2167 * folio_memcg_unlock - Release the binding between a folio and its memcg.
2168 * @folio: The folio.
2170 * This releases the binding created by folio_memcg_lock(). This does
2171 * not change the accounting of this folio to its memcg, but it does
2172 * permit others to change it.
2174 void folio_memcg_unlock(struct folio *folio)
2176 __folio_memcg_unlock(folio_memcg(folio));
2179 struct memcg_stock_pcp {
2180 local_lock_t stock_lock;
2181 struct mem_cgroup *cached; /* this never be root cgroup */
2182 unsigned int nr_pages;
2184 #ifdef CONFIG_MEMCG_KMEM
2185 struct obj_cgroup *cached_objcg;
2186 struct pglist_data *cached_pgdat;
2187 unsigned int nr_bytes;
2188 int nr_slab_reclaimable_b;
2189 int nr_slab_unreclaimable_b;
2192 struct work_struct work;
2193 unsigned long flags;
2194 #define FLUSHING_CACHED_CHARGE 0
2196 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock) = {
2197 .stock_lock = INIT_LOCAL_LOCK(stock_lock),
2199 static DEFINE_MUTEX(percpu_charge_mutex);
2201 #ifdef CONFIG_MEMCG_KMEM
2202 static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock);
2203 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2204 struct mem_cgroup *root_memcg);
2205 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages);
2208 static inline struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock)
2212 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2213 struct mem_cgroup *root_memcg)
2217 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages)
2223 * consume_stock: Try to consume stocked charge on this cpu.
2224 * @memcg: memcg to consume from.
2225 * @nr_pages: how many pages to charge.
2227 * The charges will only happen if @memcg matches the current cpu's memcg
2228 * stock, and at least @nr_pages are available in that stock. Failure to
2229 * service an allocation will refill the stock.
2231 * returns true if successful, false otherwise.
2233 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2235 struct memcg_stock_pcp *stock;
2236 unsigned long flags;
2239 if (nr_pages > MEMCG_CHARGE_BATCH)
2242 local_lock_irqsave(&memcg_stock.stock_lock, flags);
2244 stock = this_cpu_ptr(&memcg_stock);
2245 if (memcg == READ_ONCE(stock->cached) && stock->nr_pages >= nr_pages) {
2246 stock->nr_pages -= nr_pages;
2250 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2256 * Returns stocks cached in percpu and reset cached information.
2258 static void drain_stock(struct memcg_stock_pcp *stock)
2260 struct mem_cgroup *old = READ_ONCE(stock->cached);
2265 if (stock->nr_pages) {
2266 page_counter_uncharge(&old->memory, stock->nr_pages);
2267 if (do_memsw_account())
2268 page_counter_uncharge(&old->memsw, stock->nr_pages);
2269 stock->nr_pages = 0;
2273 WRITE_ONCE(stock->cached, NULL);
2276 static void drain_local_stock(struct work_struct *dummy)
2278 struct memcg_stock_pcp *stock;
2279 struct obj_cgroup *old = NULL;
2280 unsigned long flags;
2283 * The only protection from cpu hotplug (memcg_hotplug_cpu_dead) vs.
2284 * drain_stock races is that we always operate on local CPU stock
2285 * here with IRQ disabled
2287 local_lock_irqsave(&memcg_stock.stock_lock, flags);
2289 stock = this_cpu_ptr(&memcg_stock);
2290 old = drain_obj_stock(stock);
2292 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2294 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2296 obj_cgroup_put(old);
2300 * Cache charges(val) to local per_cpu area.
2301 * This will be consumed by consume_stock() function, later.
2303 static void __refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2305 struct memcg_stock_pcp *stock;
2307 stock = this_cpu_ptr(&memcg_stock);
2308 if (READ_ONCE(stock->cached) != memcg) { /* reset if necessary */
2310 css_get(&memcg->css);
2311 WRITE_ONCE(stock->cached, memcg);
2313 stock->nr_pages += nr_pages;
2315 if (stock->nr_pages > MEMCG_CHARGE_BATCH)
2319 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2321 unsigned long flags;
2323 local_lock_irqsave(&memcg_stock.stock_lock, flags);
2324 __refill_stock(memcg, nr_pages);
2325 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2329 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2330 * of the hierarchy under it.
2332 static void drain_all_stock(struct mem_cgroup *root_memcg)
2336 /* If someone's already draining, avoid adding running more workers. */
2337 if (!mutex_trylock(&percpu_charge_mutex))
2340 * Notify other cpus that system-wide "drain" is running
2341 * We do not care about races with the cpu hotplug because cpu down
2342 * as well as workers from this path always operate on the local
2343 * per-cpu data. CPU up doesn't touch memcg_stock at all.
2346 curcpu = smp_processor_id();
2347 for_each_online_cpu(cpu) {
2348 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2349 struct mem_cgroup *memcg;
2353 memcg = READ_ONCE(stock->cached);
2354 if (memcg && stock->nr_pages &&
2355 mem_cgroup_is_descendant(memcg, root_memcg))
2357 else if (obj_stock_flush_required(stock, root_memcg))
2362 !test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2364 drain_local_stock(&stock->work);
2365 else if (!cpu_is_isolated(cpu))
2366 schedule_work_on(cpu, &stock->work);
2370 mutex_unlock(&percpu_charge_mutex);
2373 static int memcg_hotplug_cpu_dead(unsigned int cpu)
2375 struct memcg_stock_pcp *stock;
2377 stock = &per_cpu(memcg_stock, cpu);
2383 static unsigned long reclaim_high(struct mem_cgroup *memcg,
2384 unsigned int nr_pages,
2387 unsigned long nr_reclaimed = 0;
2390 unsigned long pflags;
2392 if (page_counter_read(&memcg->memory) <=
2393 READ_ONCE(memcg->memory.high))
2396 memcg_memory_event(memcg, MEMCG_HIGH);
2398 psi_memstall_enter(&pflags);
2399 nr_reclaimed += try_to_free_mem_cgroup_pages(memcg, nr_pages,
2401 MEMCG_RECLAIM_MAY_SWAP);
2402 psi_memstall_leave(&pflags);
2403 } while ((memcg = parent_mem_cgroup(memcg)) &&
2404 !mem_cgroup_is_root(memcg));
2406 return nr_reclaimed;
2409 static void high_work_func(struct work_struct *work)
2411 struct mem_cgroup *memcg;
2413 memcg = container_of(work, struct mem_cgroup, high_work);
2414 reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
2418 * Clamp the maximum sleep time per allocation batch to 2 seconds. This is
2419 * enough to still cause a significant slowdown in most cases, while still
2420 * allowing diagnostics and tracing to proceed without becoming stuck.
2422 #define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ)
2425 * When calculating the delay, we use these either side of the exponentiation to
2426 * maintain precision and scale to a reasonable number of jiffies (see the table
2429 * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the
2430 * overage ratio to a delay.
2431 * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down the
2432 * proposed penalty in order to reduce to a reasonable number of jiffies, and
2433 * to produce a reasonable delay curve.
2435 * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a
2436 * reasonable delay curve compared to precision-adjusted overage, not
2437 * penalising heavily at first, but still making sure that growth beyond the
2438 * limit penalises misbehaviour cgroups by slowing them down exponentially. For
2439 * example, with a high of 100 megabytes:
2441 * +-------+------------------------+
2442 * | usage | time to allocate in ms |
2443 * +-------+------------------------+
2465 * +-------+------------------------+
2467 #define MEMCG_DELAY_PRECISION_SHIFT 20
2468 #define MEMCG_DELAY_SCALING_SHIFT 14
2470 static u64 calculate_overage(unsigned long usage, unsigned long high)
2478 * Prevent division by 0 in overage calculation by acting as if
2479 * it was a threshold of 1 page
2481 high = max(high, 1UL);
2483 overage = usage - high;
2484 overage <<= MEMCG_DELAY_PRECISION_SHIFT;
2485 return div64_u64(overage, high);
2488 static u64 mem_find_max_overage(struct mem_cgroup *memcg)
2490 u64 overage, max_overage = 0;
2493 overage = calculate_overage(page_counter_read(&memcg->memory),
2494 READ_ONCE(memcg->memory.high));
2495 max_overage = max(overage, max_overage);
2496 } while ((memcg = parent_mem_cgroup(memcg)) &&
2497 !mem_cgroup_is_root(memcg));
2502 static u64 swap_find_max_overage(struct mem_cgroup *memcg)
2504 u64 overage, max_overage = 0;
2507 overage = calculate_overage(page_counter_read(&memcg->swap),
2508 READ_ONCE(memcg->swap.high));
2510 memcg_memory_event(memcg, MEMCG_SWAP_HIGH);
2511 max_overage = max(overage, max_overage);
2512 } while ((memcg = parent_mem_cgroup(memcg)) &&
2513 !mem_cgroup_is_root(memcg));
2519 * Get the number of jiffies that we should penalise a mischievous cgroup which
2520 * is exceeding its memory.high by checking both it and its ancestors.
2522 static unsigned long calculate_high_delay(struct mem_cgroup *memcg,
2523 unsigned int nr_pages,
2526 unsigned long penalty_jiffies;
2532 * We use overage compared to memory.high to calculate the number of
2533 * jiffies to sleep (penalty_jiffies). Ideally this value should be
2534 * fairly lenient on small overages, and increasingly harsh when the
2535 * memcg in question makes it clear that it has no intention of stopping
2536 * its crazy behaviour, so we exponentially increase the delay based on
2539 penalty_jiffies = max_overage * max_overage * HZ;
2540 penalty_jiffies >>= MEMCG_DELAY_PRECISION_SHIFT;
2541 penalty_jiffies >>= MEMCG_DELAY_SCALING_SHIFT;
2544 * Factor in the task's own contribution to the overage, such that four
2545 * N-sized allocations are throttled approximately the same as one
2546 * 4N-sized allocation.
2548 * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or
2549 * larger the current charge patch is than that.
2551 return penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH;
2555 * Scheduled by try_charge() to be executed from the userland return path
2556 * and reclaims memory over the high limit.
2558 void mem_cgroup_handle_over_high(gfp_t gfp_mask)
2560 unsigned long penalty_jiffies;
2561 unsigned long pflags;
2562 unsigned long nr_reclaimed;
2563 unsigned int nr_pages = current->memcg_nr_pages_over_high;
2564 int nr_retries = MAX_RECLAIM_RETRIES;
2565 struct mem_cgroup *memcg;
2566 bool in_retry = false;
2568 if (likely(!nr_pages))
2571 memcg = get_mem_cgroup_from_mm(current->mm);
2572 current->memcg_nr_pages_over_high = 0;
2576 * The allocating task should reclaim at least the batch size, but for
2577 * subsequent retries we only want to do what's necessary to prevent oom
2578 * or breaching resource isolation.
2580 * This is distinct from memory.max or page allocator behaviour because
2581 * memory.high is currently batched, whereas memory.max and the page
2582 * allocator run every time an allocation is made.
2584 nr_reclaimed = reclaim_high(memcg,
2585 in_retry ? SWAP_CLUSTER_MAX : nr_pages,
2589 * memory.high is breached and reclaim is unable to keep up. Throttle
2590 * allocators proactively to slow down excessive growth.
2592 penalty_jiffies = calculate_high_delay(memcg, nr_pages,
2593 mem_find_max_overage(memcg));
2595 penalty_jiffies += calculate_high_delay(memcg, nr_pages,
2596 swap_find_max_overage(memcg));
2599 * Clamp the max delay per usermode return so as to still keep the
2600 * application moving forwards and also permit diagnostics, albeit
2603 penalty_jiffies = min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES);
2606 * Don't sleep if the amount of jiffies this memcg owes us is so low
2607 * that it's not even worth doing, in an attempt to be nice to those who
2608 * go only a small amount over their memory.high value and maybe haven't
2609 * been aggressively reclaimed enough yet.
2611 if (penalty_jiffies <= HZ / 100)
2615 * If reclaim is making forward progress but we're still over
2616 * memory.high, we want to encourage that rather than doing allocator
2619 if (nr_reclaimed || nr_retries--) {
2625 * If we exit early, we're guaranteed to die (since
2626 * schedule_timeout_killable sets TASK_KILLABLE). This means we don't
2627 * need to account for any ill-begotten jiffies to pay them off later.
2629 psi_memstall_enter(&pflags);
2630 schedule_timeout_killable(penalty_jiffies);
2631 psi_memstall_leave(&pflags);
2634 css_put(&memcg->css);
2637 static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask,
2638 unsigned int nr_pages)
2640 unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
2641 int nr_retries = MAX_RECLAIM_RETRIES;
2642 struct mem_cgroup *mem_over_limit;
2643 struct page_counter *counter;
2644 unsigned long nr_reclaimed;
2645 bool passed_oom = false;
2646 unsigned int reclaim_options = MEMCG_RECLAIM_MAY_SWAP;
2647 bool drained = false;
2648 bool raised_max_event = false;
2649 unsigned long pflags;
2652 if (consume_stock(memcg, nr_pages))
2655 if (!do_memsw_account() ||
2656 page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2657 if (page_counter_try_charge(&memcg->memory, batch, &counter))
2659 if (do_memsw_account())
2660 page_counter_uncharge(&memcg->memsw, batch);
2661 mem_over_limit = mem_cgroup_from_counter(counter, memory);
2663 mem_over_limit = mem_cgroup_from_counter(counter, memsw);
2664 reclaim_options &= ~MEMCG_RECLAIM_MAY_SWAP;
2667 if (batch > nr_pages) {
2673 * Prevent unbounded recursion when reclaim operations need to
2674 * allocate memory. This might exceed the limits temporarily,
2675 * but we prefer facilitating memory reclaim and getting back
2676 * under the limit over triggering OOM kills in these cases.
2678 if (unlikely(current->flags & PF_MEMALLOC))
2681 if (unlikely(task_in_memcg_oom(current)))
2684 if (!gfpflags_allow_blocking(gfp_mask))
2687 memcg_memory_event(mem_over_limit, MEMCG_MAX);
2688 raised_max_event = true;
2690 psi_memstall_enter(&pflags);
2691 nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
2692 gfp_mask, reclaim_options);
2693 psi_memstall_leave(&pflags);
2695 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2699 drain_all_stock(mem_over_limit);
2704 if (gfp_mask & __GFP_NORETRY)
2707 * Even though the limit is exceeded at this point, reclaim
2708 * may have been able to free some pages. Retry the charge
2709 * before killing the task.
2711 * Only for regular pages, though: huge pages are rather
2712 * unlikely to succeed so close to the limit, and we fall back
2713 * to regular pages anyway in case of failure.
2715 if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
2718 * At task move, charge accounts can be doubly counted. So, it's
2719 * better to wait until the end of task_move if something is going on.
2721 if (mem_cgroup_wait_acct_move(mem_over_limit))
2727 if (gfp_mask & __GFP_RETRY_MAYFAIL)
2730 /* Avoid endless loop for tasks bypassed by the oom killer */
2731 if (passed_oom && task_is_dying())
2735 * keep retrying as long as the memcg oom killer is able to make
2736 * a forward progress or bypass the charge if the oom killer
2737 * couldn't make any progress.
2739 if (mem_cgroup_oom(mem_over_limit, gfp_mask,
2740 get_order(nr_pages * PAGE_SIZE))) {
2742 nr_retries = MAX_RECLAIM_RETRIES;
2747 * Memcg doesn't have a dedicated reserve for atomic
2748 * allocations. But like the global atomic pool, we need to
2749 * put the burden of reclaim on regular allocation requests
2750 * and let these go through as privileged allocations.
2752 if (!(gfp_mask & (__GFP_NOFAIL | __GFP_HIGH)))
2756 * If the allocation has to be enforced, don't forget to raise
2757 * a MEMCG_MAX event.
2759 if (!raised_max_event)
2760 memcg_memory_event(mem_over_limit, MEMCG_MAX);
2763 * The allocation either can't fail or will lead to more memory
2764 * being freed very soon. Allow memory usage go over the limit
2765 * temporarily by force charging it.
2767 page_counter_charge(&memcg->memory, nr_pages);
2768 if (do_memsw_account())
2769 page_counter_charge(&memcg->memsw, nr_pages);
2774 if (batch > nr_pages)
2775 refill_stock(memcg, batch - nr_pages);
2778 * If the hierarchy is above the normal consumption range, schedule
2779 * reclaim on returning to userland. We can perform reclaim here
2780 * if __GFP_RECLAIM but let's always punt for simplicity and so that
2781 * GFP_KERNEL can consistently be used during reclaim. @memcg is
2782 * not recorded as it most likely matches current's and won't
2783 * change in the meantime. As high limit is checked again before
2784 * reclaim, the cost of mismatch is negligible.
2787 bool mem_high, swap_high;
2789 mem_high = page_counter_read(&memcg->memory) >
2790 READ_ONCE(memcg->memory.high);
2791 swap_high = page_counter_read(&memcg->swap) >
2792 READ_ONCE(memcg->swap.high);
2794 /* Don't bother a random interrupted task */
2797 schedule_work(&memcg->high_work);
2803 if (mem_high || swap_high) {
2805 * The allocating tasks in this cgroup will need to do
2806 * reclaim or be throttled to prevent further growth
2807 * of the memory or swap footprints.
2809 * Target some best-effort fairness between the tasks,
2810 * and distribute reclaim work and delay penalties
2811 * based on how much each task is actually allocating.
2813 current->memcg_nr_pages_over_high += batch;
2814 set_notify_resume(current);
2817 } while ((memcg = parent_mem_cgroup(memcg)));
2819 if (current->memcg_nr_pages_over_high > MEMCG_CHARGE_BATCH &&
2820 !(current->flags & PF_MEMALLOC) &&
2821 gfpflags_allow_blocking(gfp_mask)) {
2822 mem_cgroup_handle_over_high(gfp_mask);
2827 static inline int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2828 unsigned int nr_pages)
2830 if (mem_cgroup_is_root(memcg))
2833 return try_charge_memcg(memcg, gfp_mask, nr_pages);
2836 static inline void cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
2838 if (mem_cgroup_is_root(memcg))
2841 page_counter_uncharge(&memcg->memory, nr_pages);
2842 if (do_memsw_account())
2843 page_counter_uncharge(&memcg->memsw, nr_pages);
2846 static void commit_charge(struct folio *folio, struct mem_cgroup *memcg)
2848 VM_BUG_ON_FOLIO(folio_memcg(folio), folio);
2850 * Any of the following ensures page's memcg stability:
2854 * - folio_memcg_lock()
2855 * - exclusive reference
2856 * - mem_cgroup_trylock_pages()
2858 folio->memcg_data = (unsigned long)memcg;
2861 #ifdef CONFIG_MEMCG_KMEM
2863 * The allocated objcg pointers array is not accounted directly.
2864 * Moreover, it should not come from DMA buffer and is not readily
2865 * reclaimable. So those GFP bits should be masked off.
2867 #define OBJCGS_CLEAR_MASK (__GFP_DMA | __GFP_RECLAIMABLE | \
2868 __GFP_ACCOUNT | __GFP_NOFAIL)
2871 * mod_objcg_mlstate() may be called with irq enabled, so
2872 * mod_memcg_lruvec_state() should be used.
2874 static inline void mod_objcg_mlstate(struct obj_cgroup *objcg,
2875 struct pglist_data *pgdat,
2876 enum node_stat_item idx, int nr)
2878 struct mem_cgroup *memcg;
2879 struct lruvec *lruvec;
2882 memcg = obj_cgroup_memcg(objcg);
2883 lruvec = mem_cgroup_lruvec(memcg, pgdat);
2884 mod_memcg_lruvec_state(lruvec, idx, nr);
2888 int memcg_alloc_slab_cgroups(struct slab *slab, struct kmem_cache *s,
2889 gfp_t gfp, bool new_slab)
2891 unsigned int objects = objs_per_slab(s, slab);
2892 unsigned long memcg_data;
2895 gfp &= ~OBJCGS_CLEAR_MASK;
2896 vec = kcalloc_node(objects, sizeof(struct obj_cgroup *), gfp,
2901 memcg_data = (unsigned long) vec | MEMCG_DATA_OBJCGS;
2904 * If the slab is brand new and nobody can yet access its
2905 * memcg_data, no synchronization is required and memcg_data can
2906 * be simply assigned.
2908 slab->memcg_data = memcg_data;
2909 } else if (cmpxchg(&slab->memcg_data, 0, memcg_data)) {
2911 * If the slab is already in use, somebody can allocate and
2912 * assign obj_cgroups in parallel. In this case the existing
2913 * objcg vector should be reused.
2919 kmemleak_not_leak(vec);
2923 static __always_inline
2924 struct mem_cgroup *mem_cgroup_from_obj_folio(struct folio *folio, void *p)
2927 * Slab objects are accounted individually, not per-page.
2928 * Memcg membership data for each individual object is saved in
2931 if (folio_test_slab(folio)) {
2932 struct obj_cgroup **objcgs;
2936 slab = folio_slab(folio);
2937 objcgs = slab_objcgs(slab);
2941 off = obj_to_index(slab->slab_cache, slab, p);
2943 return obj_cgroup_memcg(objcgs[off]);
2949 * folio_memcg_check() is used here, because in theory we can encounter
2950 * a folio where the slab flag has been cleared already, but
2951 * slab->memcg_data has not been freed yet
2952 * folio_memcg_check() will guarantee that a proper memory
2953 * cgroup pointer or NULL will be returned.
2955 return folio_memcg_check(folio);
2959 * Returns a pointer to the memory cgroup to which the kernel object is charged.
2961 * A passed kernel object can be a slab object, vmalloc object or a generic
2962 * kernel page, so different mechanisms for getting the memory cgroup pointer
2965 * In certain cases (e.g. kernel stacks or large kmallocs with SLUB) the caller
2966 * can not know for sure how the kernel object is implemented.
2967 * mem_cgroup_from_obj() can be safely used in such cases.
2969 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
2970 * cgroup_mutex, etc.
2972 struct mem_cgroup *mem_cgroup_from_obj(void *p)
2974 struct folio *folio;
2976 if (mem_cgroup_disabled())
2979 if (unlikely(is_vmalloc_addr(p)))
2980 folio = page_folio(vmalloc_to_page(p));
2982 folio = virt_to_folio(p);
2984 return mem_cgroup_from_obj_folio(folio, p);
2988 * Returns a pointer to the memory cgroup to which the kernel object is charged.
2989 * Similar to mem_cgroup_from_obj(), but faster and not suitable for objects,
2990 * allocated using vmalloc().
2992 * A passed kernel object must be a slab object or a generic kernel page.
2994 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
2995 * cgroup_mutex, etc.
2997 struct mem_cgroup *mem_cgroup_from_slab_obj(void *p)
2999 if (mem_cgroup_disabled())
3002 return mem_cgroup_from_obj_folio(virt_to_folio(p), p);
3005 static struct obj_cgroup *__get_obj_cgroup_from_memcg(struct mem_cgroup *memcg)
3007 struct obj_cgroup *objcg = NULL;
3009 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
3010 objcg = rcu_dereference(memcg->objcg);
3011 if (objcg && obj_cgroup_tryget(objcg))
3018 __always_inline struct obj_cgroup *get_obj_cgroup_from_current(void)
3020 struct obj_cgroup *objcg = NULL;
3021 struct mem_cgroup *memcg;
3023 if (memcg_kmem_bypass())
3027 if (unlikely(active_memcg()))
3028 memcg = active_memcg();
3030 memcg = mem_cgroup_from_task(current);
3031 objcg = __get_obj_cgroup_from_memcg(memcg);
3036 struct obj_cgroup *get_obj_cgroup_from_folio(struct folio *folio)
3038 struct obj_cgroup *objcg;
3040 if (!memcg_kmem_online())
3043 if (folio_memcg_kmem(folio)) {
3044 objcg = __folio_objcg(folio);
3045 obj_cgroup_get(objcg);
3047 struct mem_cgroup *memcg;
3050 memcg = __folio_memcg(folio);
3052 objcg = __get_obj_cgroup_from_memcg(memcg);
3060 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages)
3062 mod_memcg_state(memcg, MEMCG_KMEM, nr_pages);
3063 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
3065 page_counter_charge(&memcg->kmem, nr_pages);
3067 page_counter_uncharge(&memcg->kmem, -nr_pages);
3073 * obj_cgroup_uncharge_pages: uncharge a number of kernel pages from a objcg
3074 * @objcg: object cgroup to uncharge
3075 * @nr_pages: number of pages to uncharge
3077 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
3078 unsigned int nr_pages)
3080 struct mem_cgroup *memcg;
3082 memcg = get_mem_cgroup_from_objcg(objcg);
3084 memcg_account_kmem(memcg, -nr_pages);
3085 refill_stock(memcg, nr_pages);
3087 css_put(&memcg->css);
3091 * obj_cgroup_charge_pages: charge a number of kernel pages to a objcg
3092 * @objcg: object cgroup to charge
3093 * @gfp: reclaim mode
3094 * @nr_pages: number of pages to charge
3096 * Returns 0 on success, an error code on failure.
3098 static int obj_cgroup_charge_pages(struct obj_cgroup *objcg, gfp_t gfp,
3099 unsigned int nr_pages)
3101 struct mem_cgroup *memcg;
3104 memcg = get_mem_cgroup_from_objcg(objcg);
3106 ret = try_charge_memcg(memcg, gfp, nr_pages);
3110 memcg_account_kmem(memcg, nr_pages);
3112 css_put(&memcg->css);
3118 * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup
3119 * @page: page to charge
3120 * @gfp: reclaim mode
3121 * @order: allocation order
3123 * Returns 0 on success, an error code on failure.
3125 int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
3127 struct obj_cgroup *objcg;
3130 objcg = get_obj_cgroup_from_current();
3132 ret = obj_cgroup_charge_pages(objcg, gfp, 1 << order);
3134 page->memcg_data = (unsigned long)objcg |
3138 obj_cgroup_put(objcg);
3144 * __memcg_kmem_uncharge_page: uncharge a kmem page
3145 * @page: page to uncharge
3146 * @order: allocation order
3148 void __memcg_kmem_uncharge_page(struct page *page, int order)
3150 struct folio *folio = page_folio(page);
3151 struct obj_cgroup *objcg;
3152 unsigned int nr_pages = 1 << order;
3154 if (!folio_memcg_kmem(folio))
3157 objcg = __folio_objcg(folio);
3158 obj_cgroup_uncharge_pages(objcg, nr_pages);
3159 folio->memcg_data = 0;
3160 obj_cgroup_put(objcg);
3163 void mod_objcg_state(struct obj_cgroup *objcg, struct pglist_data *pgdat,
3164 enum node_stat_item idx, int nr)
3166 struct memcg_stock_pcp *stock;
3167 struct obj_cgroup *old = NULL;
3168 unsigned long flags;
3171 local_lock_irqsave(&memcg_stock.stock_lock, flags);
3172 stock = this_cpu_ptr(&memcg_stock);
3175 * Save vmstat data in stock and skip vmstat array update unless
3176 * accumulating over a page of vmstat data or when pgdat or idx
3179 if (READ_ONCE(stock->cached_objcg) != objcg) {
3180 old = drain_obj_stock(stock);
3181 obj_cgroup_get(objcg);
3182 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3183 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3184 WRITE_ONCE(stock->cached_objcg, objcg);
3185 stock->cached_pgdat = pgdat;
3186 } else if (stock->cached_pgdat != pgdat) {
3187 /* Flush the existing cached vmstat data */
3188 struct pglist_data *oldpg = stock->cached_pgdat;
3190 if (stock->nr_slab_reclaimable_b) {
3191 mod_objcg_mlstate(objcg, oldpg, NR_SLAB_RECLAIMABLE_B,
3192 stock->nr_slab_reclaimable_b);
3193 stock->nr_slab_reclaimable_b = 0;
3195 if (stock->nr_slab_unreclaimable_b) {
3196 mod_objcg_mlstate(objcg, oldpg, NR_SLAB_UNRECLAIMABLE_B,
3197 stock->nr_slab_unreclaimable_b);
3198 stock->nr_slab_unreclaimable_b = 0;
3200 stock->cached_pgdat = pgdat;
3203 bytes = (idx == NR_SLAB_RECLAIMABLE_B) ? &stock->nr_slab_reclaimable_b
3204 : &stock->nr_slab_unreclaimable_b;
3206 * Even for large object >= PAGE_SIZE, the vmstat data will still be
3207 * cached locally at least once before pushing it out.
3214 if (abs(*bytes) > PAGE_SIZE) {
3222 mod_objcg_mlstate(objcg, pgdat, idx, nr);
3224 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3226 obj_cgroup_put(old);
3229 static bool consume_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes)
3231 struct memcg_stock_pcp *stock;
3232 unsigned long flags;
3235 local_lock_irqsave(&memcg_stock.stock_lock, flags);
3237 stock = this_cpu_ptr(&memcg_stock);
3238 if (objcg == READ_ONCE(stock->cached_objcg) && stock->nr_bytes >= nr_bytes) {
3239 stock->nr_bytes -= nr_bytes;
3243 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3248 static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock)
3250 struct obj_cgroup *old = READ_ONCE(stock->cached_objcg);
3255 if (stock->nr_bytes) {
3256 unsigned int nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3257 unsigned int nr_bytes = stock->nr_bytes & (PAGE_SIZE - 1);
3260 struct mem_cgroup *memcg;
3262 memcg = get_mem_cgroup_from_objcg(old);
3264 memcg_account_kmem(memcg, -nr_pages);
3265 __refill_stock(memcg, nr_pages);
3267 css_put(&memcg->css);
3271 * The leftover is flushed to the centralized per-memcg value.
3272 * On the next attempt to refill obj stock it will be moved
3273 * to a per-cpu stock (probably, on an other CPU), see
3274 * refill_obj_stock().
3276 * How often it's flushed is a trade-off between the memory
3277 * limit enforcement accuracy and potential CPU contention,
3278 * so it might be changed in the future.
3280 atomic_add(nr_bytes, &old->nr_charged_bytes);
3281 stock->nr_bytes = 0;
3285 * Flush the vmstat data in current stock
3287 if (stock->nr_slab_reclaimable_b || stock->nr_slab_unreclaimable_b) {
3288 if (stock->nr_slab_reclaimable_b) {
3289 mod_objcg_mlstate(old, stock->cached_pgdat,
3290 NR_SLAB_RECLAIMABLE_B,
3291 stock->nr_slab_reclaimable_b);
3292 stock->nr_slab_reclaimable_b = 0;
3294 if (stock->nr_slab_unreclaimable_b) {
3295 mod_objcg_mlstate(old, stock->cached_pgdat,
3296 NR_SLAB_UNRECLAIMABLE_B,
3297 stock->nr_slab_unreclaimable_b);
3298 stock->nr_slab_unreclaimable_b = 0;
3300 stock->cached_pgdat = NULL;
3303 WRITE_ONCE(stock->cached_objcg, NULL);
3305 * The `old' objects needs to be released by the caller via
3306 * obj_cgroup_put() outside of memcg_stock_pcp::stock_lock.
3311 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
3312 struct mem_cgroup *root_memcg)
3314 struct obj_cgroup *objcg = READ_ONCE(stock->cached_objcg);
3315 struct mem_cgroup *memcg;
3318 memcg = obj_cgroup_memcg(objcg);
3319 if (memcg && mem_cgroup_is_descendant(memcg, root_memcg))
3326 static void refill_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes,
3327 bool allow_uncharge)
3329 struct memcg_stock_pcp *stock;
3330 struct obj_cgroup *old = NULL;
3331 unsigned long flags;
3332 unsigned int nr_pages = 0;
3334 local_lock_irqsave(&memcg_stock.stock_lock, flags);
3336 stock = this_cpu_ptr(&memcg_stock);
3337 if (READ_ONCE(stock->cached_objcg) != objcg) { /* reset if necessary */
3338 old = drain_obj_stock(stock);
3339 obj_cgroup_get(objcg);
3340 WRITE_ONCE(stock->cached_objcg, objcg);
3341 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3342 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3343 allow_uncharge = true; /* Allow uncharge when objcg changes */
3345 stock->nr_bytes += nr_bytes;
3347 if (allow_uncharge && (stock->nr_bytes > PAGE_SIZE)) {
3348 nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3349 stock->nr_bytes &= (PAGE_SIZE - 1);
3352 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3354 obj_cgroup_put(old);
3357 obj_cgroup_uncharge_pages(objcg, nr_pages);
3360 int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size)
3362 unsigned int nr_pages, nr_bytes;
3365 if (consume_obj_stock(objcg, size))
3369 * In theory, objcg->nr_charged_bytes can have enough
3370 * pre-charged bytes to satisfy the allocation. However,
3371 * flushing objcg->nr_charged_bytes requires two atomic
3372 * operations, and objcg->nr_charged_bytes can't be big.
3373 * The shared objcg->nr_charged_bytes can also become a
3374 * performance bottleneck if all tasks of the same memcg are
3375 * trying to update it. So it's better to ignore it and try
3376 * grab some new pages. The stock's nr_bytes will be flushed to
3377 * objcg->nr_charged_bytes later on when objcg changes.
3379 * The stock's nr_bytes may contain enough pre-charged bytes
3380 * to allow one less page from being charged, but we can't rely
3381 * on the pre-charged bytes not being changed outside of
3382 * consume_obj_stock() or refill_obj_stock(). So ignore those
3383 * pre-charged bytes as well when charging pages. To avoid a
3384 * page uncharge right after a page charge, we set the
3385 * allow_uncharge flag to false when calling refill_obj_stock()
3386 * to temporarily allow the pre-charged bytes to exceed the page
3387 * size limit. The maximum reachable value of the pre-charged
3388 * bytes is (sizeof(object) + PAGE_SIZE - 2) if there is no data
3391 nr_pages = size >> PAGE_SHIFT;
3392 nr_bytes = size & (PAGE_SIZE - 1);
3397 ret = obj_cgroup_charge_pages(objcg, gfp, nr_pages);
3398 if (!ret && nr_bytes)
3399 refill_obj_stock(objcg, PAGE_SIZE - nr_bytes, false);
3404 void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size)
3406 refill_obj_stock(objcg, size, true);
3409 #endif /* CONFIG_MEMCG_KMEM */
3412 * Because page_memcg(head) is not set on tails, set it now.
3414 void split_page_memcg(struct page *head, unsigned int nr)
3416 struct folio *folio = page_folio(head);
3417 struct mem_cgroup *memcg = folio_memcg(folio);
3420 if (mem_cgroup_disabled() || !memcg)
3423 for (i = 1; i < nr; i++)
3424 folio_page(folio, i)->memcg_data = folio->memcg_data;
3426 if (folio_memcg_kmem(folio))
3427 obj_cgroup_get_many(__folio_objcg(folio), nr - 1);
3429 css_get_many(&memcg->css, nr - 1);
3434 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3435 * @entry: swap entry to be moved
3436 * @from: mem_cgroup which the entry is moved from
3437 * @to: mem_cgroup which the entry is moved to
3439 * It succeeds only when the swap_cgroup's record for this entry is the same
3440 * as the mem_cgroup's id of @from.
3442 * Returns 0 on success, -EINVAL on failure.
3444 * The caller must have charged to @to, IOW, called page_counter_charge() about
3445 * both res and memsw, and called css_get().
3447 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3448 struct mem_cgroup *from, struct mem_cgroup *to)
3450 unsigned short old_id, new_id;
3452 old_id = mem_cgroup_id(from);
3453 new_id = mem_cgroup_id(to);
3455 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3456 mod_memcg_state(from, MEMCG_SWAP, -1);
3457 mod_memcg_state(to, MEMCG_SWAP, 1);
3463 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3464 struct mem_cgroup *from, struct mem_cgroup *to)
3470 static DEFINE_MUTEX(memcg_max_mutex);
3472 static int mem_cgroup_resize_max(struct mem_cgroup *memcg,
3473 unsigned long max, bool memsw)
3475 bool enlarge = false;
3476 bool drained = false;
3478 bool limits_invariant;
3479 struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory;
3482 if (signal_pending(current)) {
3487 mutex_lock(&memcg_max_mutex);
3489 * Make sure that the new limit (memsw or memory limit) doesn't
3490 * break our basic invariant rule memory.max <= memsw.max.
3492 limits_invariant = memsw ? max >= READ_ONCE(memcg->memory.max) :
3493 max <= memcg->memsw.max;
3494 if (!limits_invariant) {
3495 mutex_unlock(&memcg_max_mutex);
3499 if (max > counter->max)
3501 ret = page_counter_set_max(counter, max);
3502 mutex_unlock(&memcg_max_mutex);
3508 drain_all_stock(memcg);
3513 if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,
3514 memsw ? 0 : MEMCG_RECLAIM_MAY_SWAP)) {
3520 if (!ret && enlarge)
3521 memcg_oom_recover(memcg);
3526 unsigned long mem_cgroup_soft_limit_reclaim(pg_data_t *pgdat, int order,
3528 unsigned long *total_scanned)
3530 unsigned long nr_reclaimed = 0;
3531 struct mem_cgroup_per_node *mz, *next_mz = NULL;
3532 unsigned long reclaimed;
3534 struct mem_cgroup_tree_per_node *mctz;
3535 unsigned long excess;
3537 if (lru_gen_enabled())
3543 mctz = soft_limit_tree.rb_tree_per_node[pgdat->node_id];
3546 * Do not even bother to check the largest node if the root
3547 * is empty. Do it lockless to prevent lock bouncing. Races
3548 * are acceptable as soft limit is best effort anyway.
3550 if (!mctz || RB_EMPTY_ROOT(&mctz->rb_root))
3554 * This loop can run a while, specially if mem_cgroup's continuously
3555 * keep exceeding their soft limit and putting the system under
3562 mz = mem_cgroup_largest_soft_limit_node(mctz);
3566 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, pgdat,
3567 gfp_mask, total_scanned);
3568 nr_reclaimed += reclaimed;
3569 spin_lock_irq(&mctz->lock);
3572 * If we failed to reclaim anything from this memory cgroup
3573 * it is time to move on to the next cgroup
3577 next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
3579 excess = soft_limit_excess(mz->memcg);
3581 * One school of thought says that we should not add
3582 * back the node to the tree if reclaim returns 0.
3583 * But our reclaim could return 0, simply because due
3584 * to priority we are exposing a smaller subset of
3585 * memory to reclaim from. Consider this as a longer
3588 /* If excess == 0, no tree ops */
3589 __mem_cgroup_insert_exceeded(mz, mctz, excess);
3590 spin_unlock_irq(&mctz->lock);
3591 css_put(&mz->memcg->css);
3594 * Could not reclaim anything and there are no more
3595 * mem cgroups to try or we seem to be looping without
3596 * reclaiming anything.
3598 if (!nr_reclaimed &&
3600 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3602 } while (!nr_reclaimed);
3604 css_put(&next_mz->memcg->css);
3605 return nr_reclaimed;
3609 * Reclaims as many pages from the given memcg as possible.
3611 * Caller is responsible for holding css reference for memcg.
3613 static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
3615 int nr_retries = MAX_RECLAIM_RETRIES;
3617 /* we call try-to-free pages for make this cgroup empty */
3618 lru_add_drain_all();
3620 drain_all_stock(memcg);
3622 /* try to free all pages in this cgroup */
3623 while (nr_retries && page_counter_read(&memcg->memory)) {
3624 if (signal_pending(current))
3627 if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,
3628 MEMCG_RECLAIM_MAY_SWAP))
3635 static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
3636 char *buf, size_t nbytes,
3639 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3641 if (mem_cgroup_is_root(memcg))
3643 return mem_cgroup_force_empty(memcg) ?: nbytes;
3646 #if defined(CONFIG_MEMCG) && defined(CONFIG_SWAP)
3647 static int mem_cgroup_force_reclaim(struct cgroup_subsys_state *css,
3648 struct cftype *cft, u64 val)
3650 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3651 unsigned long nr_to_reclaim = val;
3652 unsigned long total = 0;
3655 for (loop = 0; loop < MEM_CGROUP_MAX_RECLAIM_LOOPS; loop++) {
3656 total += try_to_free_mem_cgroup_pages(memcg, nr_to_reclaim,
3660 * If nothing was reclaimed after two attempts, there
3661 * may be no reclaimable pages in this hierarchy.
3662 * If more than nr_to_reclaim pages were already reclaimed,
3663 * finish force reclaim.
3665 if (loop && (!total || total > nr_to_reclaim))
3669 pr_info("%s: [Mem_reclaim] Loop: %d - Total_reclaimed: %lu - nr_to_reclaim: %lu\n",
3670 __func__, loop, total, nr_to_reclaim);
3676 static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
3682 static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
3683 struct cftype *cft, u64 val)
3688 pr_warn_once("Non-hierarchical mode is deprecated. "
3689 "Please report your usecase to linux-mm@kvack.org if you "
3690 "depend on this functionality.\n");
3695 static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3699 if (mem_cgroup_is_root(memcg)) {
3701 * Approximate root's usage from global state. This isn't
3702 * perfect, but the root usage was always an approximation.
3704 val = global_node_page_state(NR_FILE_PAGES) +
3705 global_node_page_state(NR_ANON_MAPPED);
3707 val += total_swap_pages - get_nr_swap_pages();
3710 val = page_counter_read(&memcg->memory);
3712 val = page_counter_read(&memcg->memsw);
3725 static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
3728 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3729 struct page_counter *counter;
3731 switch (MEMFILE_TYPE(cft->private)) {
3733 counter = &memcg->memory;
3736 counter = &memcg->memsw;
3739 counter = &memcg->kmem;
3742 counter = &memcg->tcpmem;
3748 switch (MEMFILE_ATTR(cft->private)) {
3750 if (counter == &memcg->memory)
3751 return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
3752 if (counter == &memcg->memsw)
3753 return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
3754 return (u64)page_counter_read(counter) * PAGE_SIZE;
3756 return (u64)counter->max * PAGE_SIZE;
3758 return (u64)counter->watermark * PAGE_SIZE;
3760 return counter->failcnt;
3761 case RES_SOFT_LIMIT:
3762 return (u64)READ_ONCE(memcg->soft_limit) * PAGE_SIZE;
3769 * This function doesn't do anything useful. Its only job is to provide a read
3770 * handler for a file so that cgroup_file_mode() will add read permissions.
3772 static int mem_cgroup_dummy_seq_show(__always_unused struct seq_file *m,
3773 __always_unused void *v)
3778 #ifdef CONFIG_MEMCG_KMEM
3779 static int memcg_online_kmem(struct mem_cgroup *memcg)
3781 struct obj_cgroup *objcg;
3783 if (mem_cgroup_kmem_disabled())
3786 if (unlikely(mem_cgroup_is_root(memcg)))
3789 objcg = obj_cgroup_alloc();
3793 objcg->memcg = memcg;
3794 rcu_assign_pointer(memcg->objcg, objcg);
3796 static_branch_enable(&memcg_kmem_online_key);
3798 memcg->kmemcg_id = memcg->id.id;
3803 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3805 struct mem_cgroup *parent;
3807 if (mem_cgroup_kmem_disabled())
3810 if (unlikely(mem_cgroup_is_root(memcg)))
3813 parent = parent_mem_cgroup(memcg);
3815 parent = root_mem_cgroup;
3817 memcg_reparent_objcgs(memcg, parent);
3820 * After we have finished memcg_reparent_objcgs(), all list_lrus
3821 * corresponding to this cgroup are guaranteed to remain empty.
3822 * The ordering is imposed by list_lru_node->lock taken by
3823 * memcg_reparent_list_lrus().
3825 memcg_reparent_list_lrus(memcg, parent);
3828 static int memcg_online_kmem(struct mem_cgroup *memcg)
3832 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3835 #endif /* CONFIG_MEMCG_KMEM */
3837 static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max)
3841 mutex_lock(&memcg_max_mutex);
3843 ret = page_counter_set_max(&memcg->tcpmem, max);
3847 if (!memcg->tcpmem_active) {
3849 * The active flag needs to be written after the static_key
3850 * update. This is what guarantees that the socket activation
3851 * function is the last one to run. See mem_cgroup_sk_alloc()
3852 * for details, and note that we don't mark any socket as
3853 * belonging to this memcg until that flag is up.
3855 * We need to do this, because static_keys will span multiple
3856 * sites, but we can't control their order. If we mark a socket
3857 * as accounted, but the accounting functions are not patched in
3858 * yet, we'll lose accounting.
3860 * We never race with the readers in mem_cgroup_sk_alloc(),
3861 * because when this value change, the code to process it is not
3864 static_branch_inc(&memcg_sockets_enabled_key);
3865 memcg->tcpmem_active = true;
3868 mutex_unlock(&memcg_max_mutex);
3873 * The user of this function is...
3876 static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
3877 char *buf, size_t nbytes, loff_t off)
3879 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3880 unsigned long nr_pages;
3883 buf = strstrip(buf);
3884 ret = page_counter_memparse(buf, "-1", &nr_pages);
3888 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3890 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3894 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3896 ret = mem_cgroup_resize_max(memcg, nr_pages, false);
3899 ret = mem_cgroup_resize_max(memcg, nr_pages, true);
3902 pr_warn_once("kmem.limit_in_bytes is deprecated and will be removed. "
3903 "Writing any value to this file has no effect. "
3904 "Please report your usecase to linux-mm@kvack.org if you "
3905 "depend on this functionality.\n");
3909 ret = memcg_update_tcp_max(memcg, nr_pages);
3913 case RES_SOFT_LIMIT:
3914 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
3917 WRITE_ONCE(memcg->soft_limit, nr_pages);
3922 return ret ?: nbytes;
3925 static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
3926 size_t nbytes, loff_t off)
3928 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3929 struct page_counter *counter;
3931 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3933 counter = &memcg->memory;
3936 counter = &memcg->memsw;
3939 counter = &memcg->kmem;
3942 counter = &memcg->tcpmem;
3948 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3950 page_counter_reset_watermark(counter);
3953 counter->failcnt = 0;
3962 static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
3965 return mem_cgroup_from_css(css)->move_charge_at_immigrate;
3969 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3970 struct cftype *cft, u64 val)
3972 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3974 pr_warn_once("Cgroup memory moving (move_charge_at_immigrate) is deprecated. "
3975 "Please report your usecase to linux-mm@kvack.org if you "
3976 "depend on this functionality.\n");
3978 if (val & ~MOVE_MASK)
3982 * No kind of locking is needed in here, because ->can_attach() will
3983 * check this value once in the beginning of the process, and then carry
3984 * on with stale data. This means that changes to this value will only
3985 * affect task migrations starting after the change.
3987 memcg->move_charge_at_immigrate = val;
3991 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3992 struct cftype *cft, u64 val)
4000 #define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE))
4001 #define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON))
4002 #define LRU_ALL ((1 << NR_LRU_LISTS) - 1)
4004 static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
4005 int nid, unsigned int lru_mask, bool tree)
4007 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
4008 unsigned long nr = 0;
4011 VM_BUG_ON((unsigned)nid >= nr_node_ids);
4014 if (!(BIT(lru) & lru_mask))
4017 nr += lruvec_page_state(lruvec, NR_LRU_BASE + lru);
4019 nr += lruvec_page_state_local(lruvec, NR_LRU_BASE + lru);
4024 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
4025 unsigned int lru_mask,
4028 unsigned long nr = 0;
4032 if (!(BIT(lru) & lru_mask))
4035 nr += memcg_page_state(memcg, NR_LRU_BASE + lru);
4037 nr += memcg_page_state_local(memcg, NR_LRU_BASE + lru);
4042 static int memcg_numa_stat_show(struct seq_file *m, void *v)
4046 unsigned int lru_mask;
4049 static const struct numa_stat stats[] = {
4050 { "total", LRU_ALL },
4051 { "file", LRU_ALL_FILE },
4052 { "anon", LRU_ALL_ANON },
4053 { "unevictable", BIT(LRU_UNEVICTABLE) },
4055 const struct numa_stat *stat;
4057 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
4059 mem_cgroup_flush_stats();
4061 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
4062 seq_printf(m, "%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, false));
4072 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
4074 seq_printf(m, "hierarchical_%s=%lu", stat->name,
4075 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
4077 for_each_node_state(nid, N_MEMORY)
4078 seq_printf(m, " N%d=%lu", nid,
4079 mem_cgroup_node_nr_lru_pages(memcg, nid,
4080 stat->lru_mask, true));
4086 #endif /* CONFIG_NUMA */
4088 static const unsigned int memcg1_stats[] = {
4091 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4098 WORKINGSET_REFAULT_ANON,
4099 WORKINGSET_REFAULT_FILE,
4103 static const char *const memcg1_stat_names[] = {
4106 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4113 "workingset_refault_anon",
4114 "workingset_refault_file",
4118 /* Universal VM events cgroup1 shows, original sort order */
4119 static const unsigned int memcg1_events[] = {
4126 static void memcg1_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
4128 unsigned long memory, memsw;
4129 struct mem_cgroup *mi;
4132 BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats));
4134 mem_cgroup_flush_stats();
4136 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
4139 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
4141 nr = memcg_page_state_local(memcg, memcg1_stats[i]);
4142 seq_buf_printf(s, "%s %lu\n", memcg1_stat_names[i],
4143 nr * memcg_page_state_unit(memcg1_stats[i]));
4146 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
4147 seq_buf_printf(s, "%s %lu\n", vm_event_name(memcg1_events[i]),
4148 memcg_events_local(memcg, memcg1_events[i]));
4150 for (i = 0; i < NR_LRU_LISTS; i++)
4151 seq_buf_printf(s, "%s %lu\n", lru_list_name(i),
4152 memcg_page_state_local(memcg, NR_LRU_BASE + i) *
4155 /* Hierarchical information */
4156 memory = memsw = PAGE_COUNTER_MAX;
4157 for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
4158 memory = min(memory, READ_ONCE(mi->memory.max));
4159 memsw = min(memsw, READ_ONCE(mi->memsw.max));
4161 seq_buf_printf(s, "hierarchical_memory_limit %llu\n",
4162 (u64)memory * PAGE_SIZE);
4163 if (do_memsw_account())
4164 seq_buf_printf(s, "hierarchical_memsw_limit %llu\n",
4165 (u64)memsw * PAGE_SIZE);
4167 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
4170 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
4172 nr = memcg_page_state(memcg, memcg1_stats[i]);
4173 seq_buf_printf(s, "total_%s %llu\n", memcg1_stat_names[i],
4174 (u64)nr * memcg_page_state_unit(memcg1_stats[i]));
4177 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
4178 seq_buf_printf(s, "total_%s %llu\n",
4179 vm_event_name(memcg1_events[i]),
4180 (u64)memcg_events(memcg, memcg1_events[i]));
4182 for (i = 0; i < NR_LRU_LISTS; i++)
4183 seq_buf_printf(s, "total_%s %llu\n", lru_list_name(i),
4184 (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
4187 #ifdef CONFIG_DEBUG_VM
4190 struct mem_cgroup_per_node *mz;
4191 unsigned long anon_cost = 0;
4192 unsigned long file_cost = 0;
4194 for_each_online_pgdat(pgdat) {
4195 mz = memcg->nodeinfo[pgdat->node_id];
4197 anon_cost += mz->lruvec.anon_cost;
4198 file_cost += mz->lruvec.file_cost;
4200 seq_buf_printf(s, "anon_cost %lu\n", anon_cost);
4201 seq_buf_printf(s, "file_cost %lu\n", file_cost);
4206 static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
4209 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4211 return mem_cgroup_swappiness(memcg);
4214 static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
4215 struct cftype *cft, u64 val)
4217 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4222 if (!mem_cgroup_is_root(memcg))
4223 WRITE_ONCE(memcg->swappiness, val);
4225 WRITE_ONCE(vm_swappiness, val);
4230 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4232 struct mem_cgroup_threshold_ary *t;
4233 unsigned long usage;
4238 t = rcu_dereference(memcg->thresholds.primary);
4240 t = rcu_dereference(memcg->memsw_thresholds.primary);
4245 usage = mem_cgroup_usage(memcg, swap);
4248 * current_threshold points to threshold just below or equal to usage.
4249 * If it's not true, a threshold was crossed after last
4250 * call of __mem_cgroup_threshold().
4252 i = t->current_threshold;
4255 * Iterate backward over array of thresholds starting from
4256 * current_threshold and check if a threshold is crossed.
4257 * If none of thresholds below usage is crossed, we read
4258 * only one element of the array here.
4260 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4261 eventfd_signal(t->entries[i].eventfd, 1);
4263 /* i = current_threshold + 1 */
4267 * Iterate forward over array of thresholds starting from
4268 * current_threshold+1 and check if a threshold is crossed.
4269 * If none of thresholds above usage is crossed, we read
4270 * only one element of the array here.
4272 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4273 eventfd_signal(t->entries[i].eventfd, 1);
4275 /* Update current_threshold */
4276 t->current_threshold = i - 1;
4281 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4284 __mem_cgroup_threshold(memcg, false);
4285 if (do_memsw_account())
4286 __mem_cgroup_threshold(memcg, true);
4288 memcg = parent_mem_cgroup(memcg);
4292 static int compare_thresholds(const void *a, const void *b)
4294 const struct mem_cgroup_threshold *_a = a;
4295 const struct mem_cgroup_threshold *_b = b;
4297 if (_a->threshold > _b->threshold)
4300 if (_a->threshold < _b->threshold)
4306 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
4308 struct mem_cgroup_eventfd_list *ev;
4310 spin_lock(&memcg_oom_lock);
4312 list_for_each_entry(ev, &memcg->oom_notify, list)
4313 eventfd_signal(ev->eventfd, 1);
4315 spin_unlock(&memcg_oom_lock);
4319 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
4321 struct mem_cgroup *iter;
4323 for_each_mem_cgroup_tree(iter, memcg)
4324 mem_cgroup_oom_notify_cb(iter);
4327 static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4328 struct eventfd_ctx *eventfd, const char *args, enum res_type type)
4330 struct mem_cgroup_thresholds *thresholds;
4331 struct mem_cgroup_threshold_ary *new;
4332 unsigned long threshold;
4333 unsigned long usage;
4336 ret = page_counter_memparse(args, "-1", &threshold);
4340 mutex_lock(&memcg->thresholds_lock);
4343 thresholds = &memcg->thresholds;
4344 usage = mem_cgroup_usage(memcg, false);
4345 } else if (type == _MEMSWAP) {
4346 thresholds = &memcg->memsw_thresholds;
4347 usage = mem_cgroup_usage(memcg, true);
4351 /* Check if a threshold crossed before adding a new one */
4352 if (thresholds->primary)
4353 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4355 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4357 /* Allocate memory for new array of thresholds */
4358 new = kmalloc(struct_size(new, entries, size), GFP_KERNEL);
4365 /* Copy thresholds (if any) to new array */
4366 if (thresholds->primary)
4367 memcpy(new->entries, thresholds->primary->entries,
4368 flex_array_size(new, entries, size - 1));
4370 /* Add new threshold */
4371 new->entries[size - 1].eventfd = eventfd;
4372 new->entries[size - 1].threshold = threshold;
4374 /* Sort thresholds. Registering of new threshold isn't time-critical */
4375 sort(new->entries, size, sizeof(*new->entries),
4376 compare_thresholds, NULL);
4378 /* Find current threshold */
4379 new->current_threshold = -1;
4380 for (i = 0; i < size; i++) {
4381 if (new->entries[i].threshold <= usage) {
4383 * new->current_threshold will not be used until
4384 * rcu_assign_pointer(), so it's safe to increment
4387 ++new->current_threshold;
4392 /* Free old spare buffer and save old primary buffer as spare */
4393 kfree(thresholds->spare);
4394 thresholds->spare = thresholds->primary;
4396 rcu_assign_pointer(thresholds->primary, new);
4398 /* To be sure that nobody uses thresholds */
4402 mutex_unlock(&memcg->thresholds_lock);
4407 static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4408 struct eventfd_ctx *eventfd, const char *args)
4410 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
4413 static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
4414 struct eventfd_ctx *eventfd, const char *args)
4416 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
4419 static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4420 struct eventfd_ctx *eventfd, enum res_type type)
4422 struct mem_cgroup_thresholds *thresholds;
4423 struct mem_cgroup_threshold_ary *new;
4424 unsigned long usage;
4425 int i, j, size, entries;
4427 mutex_lock(&memcg->thresholds_lock);
4430 thresholds = &memcg->thresholds;
4431 usage = mem_cgroup_usage(memcg, false);
4432 } else if (type == _MEMSWAP) {
4433 thresholds = &memcg->memsw_thresholds;
4434 usage = mem_cgroup_usage(memcg, true);
4438 if (!thresholds->primary)
4441 /* Check if a threshold crossed before removing */
4442 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4444 /* Calculate new number of threshold */
4446 for (i = 0; i < thresholds->primary->size; i++) {
4447 if (thresholds->primary->entries[i].eventfd != eventfd)
4453 new = thresholds->spare;
4455 /* If no items related to eventfd have been cleared, nothing to do */
4459 /* Set thresholds array to NULL if we don't have thresholds */
4468 /* Copy thresholds and find current threshold */
4469 new->current_threshold = -1;
4470 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4471 if (thresholds->primary->entries[i].eventfd == eventfd)
4474 new->entries[j] = thresholds->primary->entries[i];
4475 if (new->entries[j].threshold <= usage) {
4477 * new->current_threshold will not be used
4478 * until rcu_assign_pointer(), so it's safe to increment
4481 ++new->current_threshold;
4487 /* Swap primary and spare array */
4488 thresholds->spare = thresholds->primary;
4490 rcu_assign_pointer(thresholds->primary, new);
4492 /* To be sure that nobody uses thresholds */
4495 /* If all events are unregistered, free the spare array */
4497 kfree(thresholds->spare);
4498 thresholds->spare = NULL;
4501 mutex_unlock(&memcg->thresholds_lock);
4504 static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4505 struct eventfd_ctx *eventfd)
4507 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
4510 static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4511 struct eventfd_ctx *eventfd)
4513 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
4516 static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
4517 struct eventfd_ctx *eventfd, const char *args)
4519 struct mem_cgroup_eventfd_list *event;
4521 event = kmalloc(sizeof(*event), GFP_KERNEL);
4525 spin_lock(&memcg_oom_lock);
4527 event->eventfd = eventfd;
4528 list_add(&event->list, &memcg->oom_notify);
4530 /* already in OOM ? */
4531 if (memcg->under_oom)
4532 eventfd_signal(eventfd, 1);
4533 spin_unlock(&memcg_oom_lock);
4538 static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
4539 struct eventfd_ctx *eventfd)
4541 struct mem_cgroup_eventfd_list *ev, *tmp;
4543 spin_lock(&memcg_oom_lock);
4545 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
4546 if (ev->eventfd == eventfd) {
4547 list_del(&ev->list);
4552 spin_unlock(&memcg_oom_lock);
4555 static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
4557 struct mem_cgroup *memcg = mem_cgroup_from_seq(sf);
4559 seq_printf(sf, "oom_kill_disable %d\n", READ_ONCE(memcg->oom_kill_disable));
4560 seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
4561 seq_printf(sf, "oom_kill %lu\n",
4562 atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
4566 static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
4567 struct cftype *cft, u64 val)
4569 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4571 /* cannot set to root cgroup and only 0 and 1 are allowed */
4572 if (mem_cgroup_is_root(memcg) || !((val == 0) || (val == 1)))
4575 WRITE_ONCE(memcg->oom_kill_disable, val);
4577 memcg_oom_recover(memcg);
4582 #ifdef CONFIG_CGROUP_WRITEBACK
4584 #include <trace/events/writeback.h>
4586 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4588 return wb_domain_init(&memcg->cgwb_domain, gfp);
4591 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4593 wb_domain_exit(&memcg->cgwb_domain);
4596 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4598 wb_domain_size_changed(&memcg->cgwb_domain);
4601 struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
4603 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4605 if (!memcg->css.parent)
4608 return &memcg->cgwb_domain;
4612 * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
4613 * @wb: bdi_writeback in question
4614 * @pfilepages: out parameter for number of file pages
4615 * @pheadroom: out parameter for number of allocatable pages according to memcg
4616 * @pdirty: out parameter for number of dirty pages
4617 * @pwriteback: out parameter for number of pages under writeback
4619 * Determine the numbers of file, headroom, dirty, and writeback pages in
4620 * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom
4621 * is a bit more involved.
4623 * A memcg's headroom is "min(max, high) - used". In the hierarchy, the
4624 * headroom is calculated as the lowest headroom of itself and the
4625 * ancestors. Note that this doesn't consider the actual amount of
4626 * available memory in the system. The caller should further cap
4627 * *@pheadroom accordingly.
4629 void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
4630 unsigned long *pheadroom, unsigned long *pdirty,
4631 unsigned long *pwriteback)
4633 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4634 struct mem_cgroup *parent;
4636 mem_cgroup_flush_stats();
4638 *pdirty = memcg_page_state(memcg, NR_FILE_DIRTY);
4639 *pwriteback = memcg_page_state(memcg, NR_WRITEBACK);
4640 *pfilepages = memcg_page_state(memcg, NR_INACTIVE_FILE) +
4641 memcg_page_state(memcg, NR_ACTIVE_FILE);
4643 *pheadroom = PAGE_COUNTER_MAX;
4644 while ((parent = parent_mem_cgroup(memcg))) {
4645 unsigned long ceiling = min(READ_ONCE(memcg->memory.max),
4646 READ_ONCE(memcg->memory.high));
4647 unsigned long used = page_counter_read(&memcg->memory);
4649 *pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
4655 * Foreign dirty flushing
4657 * There's an inherent mismatch between memcg and writeback. The former
4658 * tracks ownership per-page while the latter per-inode. This was a
4659 * deliberate design decision because honoring per-page ownership in the
4660 * writeback path is complicated, may lead to higher CPU and IO overheads
4661 * and deemed unnecessary given that write-sharing an inode across
4662 * different cgroups isn't a common use-case.
4664 * Combined with inode majority-writer ownership switching, this works well
4665 * enough in most cases but there are some pathological cases. For
4666 * example, let's say there are two cgroups A and B which keep writing to
4667 * different but confined parts of the same inode. B owns the inode and
4668 * A's memory is limited far below B's. A's dirty ratio can rise enough to
4669 * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
4670 * triggering background writeback. A will be slowed down without a way to
4671 * make writeback of the dirty pages happen.
4673 * Conditions like the above can lead to a cgroup getting repeatedly and
4674 * severely throttled after making some progress after each
4675 * dirty_expire_interval while the underlying IO device is almost
4678 * Solving this problem completely requires matching the ownership tracking
4679 * granularities between memcg and writeback in either direction. However,
4680 * the more egregious behaviors can be avoided by simply remembering the
4681 * most recent foreign dirtying events and initiating remote flushes on
4682 * them when local writeback isn't enough to keep the memory clean enough.
4684 * The following two functions implement such mechanism. When a foreign
4685 * page - a page whose memcg and writeback ownerships don't match - is
4686 * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
4687 * bdi_writeback on the page owning memcg. When balance_dirty_pages()
4688 * decides that the memcg needs to sleep due to high dirty ratio, it calls
4689 * mem_cgroup_flush_foreign() which queues writeback on the recorded
4690 * foreign bdi_writebacks which haven't expired. Both the numbers of
4691 * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
4692 * limited to MEMCG_CGWB_FRN_CNT.
4694 * The mechanism only remembers IDs and doesn't hold any object references.
4695 * As being wrong occasionally doesn't matter, updates and accesses to the
4696 * records are lockless and racy.
4698 void mem_cgroup_track_foreign_dirty_slowpath(struct folio *folio,
4699 struct bdi_writeback *wb)
4701 struct mem_cgroup *memcg = folio_memcg(folio);
4702 struct memcg_cgwb_frn *frn;
4703 u64 now = get_jiffies_64();
4704 u64 oldest_at = now;
4708 trace_track_foreign_dirty(folio, wb);
4711 * Pick the slot to use. If there is already a slot for @wb, keep
4712 * using it. If not replace the oldest one which isn't being
4715 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4716 frn = &memcg->cgwb_frn[i];
4717 if (frn->bdi_id == wb->bdi->id &&
4718 frn->memcg_id == wb->memcg_css->id)
4720 if (time_before64(frn->at, oldest_at) &&
4721 atomic_read(&frn->done.cnt) == 1) {
4723 oldest_at = frn->at;
4727 if (i < MEMCG_CGWB_FRN_CNT) {
4729 * Re-using an existing one. Update timestamp lazily to
4730 * avoid making the cacheline hot. We want them to be
4731 * reasonably up-to-date and significantly shorter than
4732 * dirty_expire_interval as that's what expires the record.
4733 * Use the shorter of 1s and dirty_expire_interval / 8.
4735 unsigned long update_intv =
4736 min_t(unsigned long, HZ,
4737 msecs_to_jiffies(dirty_expire_interval * 10) / 8);
4739 if (time_before64(frn->at, now - update_intv))
4741 } else if (oldest >= 0) {
4742 /* replace the oldest free one */
4743 frn = &memcg->cgwb_frn[oldest];
4744 frn->bdi_id = wb->bdi->id;
4745 frn->memcg_id = wb->memcg_css->id;
4750 /* issue foreign writeback flushes for recorded foreign dirtying events */
4751 void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
4753 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4754 unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
4755 u64 now = jiffies_64;
4758 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4759 struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
4762 * If the record is older than dirty_expire_interval,
4763 * writeback on it has already started. No need to kick it
4764 * off again. Also, don't start a new one if there's
4765 * already one in flight.
4767 if (time_after64(frn->at, now - intv) &&
4768 atomic_read(&frn->done.cnt) == 1) {
4770 trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
4771 cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id,
4772 WB_REASON_FOREIGN_FLUSH,
4778 #else /* CONFIG_CGROUP_WRITEBACK */
4780 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4785 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4789 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4793 #endif /* CONFIG_CGROUP_WRITEBACK */
4796 * DO NOT USE IN NEW FILES.
4798 * "cgroup.event_control" implementation.
4800 * This is way over-engineered. It tries to support fully configurable
4801 * events for each user. Such level of flexibility is completely
4802 * unnecessary especially in the light of the planned unified hierarchy.
4804 * Please deprecate this and replace with something simpler if at all
4809 * Unregister event and free resources.
4811 * Gets called from workqueue.
4813 static void memcg_event_remove(struct work_struct *work)
4815 struct mem_cgroup_event *event =
4816 container_of(work, struct mem_cgroup_event, remove);
4817 struct mem_cgroup *memcg = event->memcg;
4819 remove_wait_queue(event->wqh, &event->wait);
4821 event->unregister_event(memcg, event->eventfd);
4823 /* Notify userspace the event is going away. */
4824 eventfd_signal(event->eventfd, 1);
4826 eventfd_ctx_put(event->eventfd);
4828 css_put(&memcg->css);
4832 * Gets called on EPOLLHUP on eventfd when user closes it.
4834 * Called with wqh->lock held and interrupts disabled.
4836 static int memcg_event_wake(wait_queue_entry_t *wait, unsigned mode,
4837 int sync, void *key)
4839 struct mem_cgroup_event *event =
4840 container_of(wait, struct mem_cgroup_event, wait);
4841 struct mem_cgroup *memcg = event->memcg;
4842 __poll_t flags = key_to_poll(key);
4844 if (flags & EPOLLHUP) {
4846 * If the event has been detached at cgroup removal, we
4847 * can simply return knowing the other side will cleanup
4850 * We can't race against event freeing since the other
4851 * side will require wqh->lock via remove_wait_queue(),
4854 spin_lock(&memcg->event_list_lock);
4855 if (!list_empty(&event->list)) {
4856 list_del_init(&event->list);
4858 * We are in atomic context, but cgroup_event_remove()
4859 * may sleep, so we have to call it in workqueue.
4861 schedule_work(&event->remove);
4863 spin_unlock(&memcg->event_list_lock);
4869 static void memcg_event_ptable_queue_proc(struct file *file,
4870 wait_queue_head_t *wqh, poll_table *pt)
4872 struct mem_cgroup_event *event =
4873 container_of(pt, struct mem_cgroup_event, pt);
4876 add_wait_queue(wqh, &event->wait);
4880 * DO NOT USE IN NEW FILES.
4882 * Parse input and register new cgroup event handler.
4884 * Input must be in format '<event_fd> <control_fd> <args>'.
4885 * Interpretation of args is defined by control file implementation.
4887 static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
4888 char *buf, size_t nbytes, loff_t off)
4890 struct cgroup_subsys_state *css = of_css(of);
4891 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4892 struct mem_cgroup_event *event;
4893 struct cgroup_subsys_state *cfile_css;
4894 unsigned int efd, cfd;
4897 struct dentry *cdentry;
4902 if (IS_ENABLED(CONFIG_PREEMPT_RT))
4905 buf = strstrip(buf);
4907 efd = simple_strtoul(buf, &endp, 10);
4912 cfd = simple_strtoul(buf, &endp, 10);
4913 if ((*endp != ' ') && (*endp != '\0'))
4917 event = kzalloc(sizeof(*event), GFP_KERNEL);
4921 event->memcg = memcg;
4922 INIT_LIST_HEAD(&event->list);
4923 init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
4924 init_waitqueue_func_entry(&event->wait, memcg_event_wake);
4925 INIT_WORK(&event->remove, memcg_event_remove);
4933 event->eventfd = eventfd_ctx_fileget(efile.file);
4934 if (IS_ERR(event->eventfd)) {
4935 ret = PTR_ERR(event->eventfd);
4942 goto out_put_eventfd;
4945 /* the process need read permission on control file */
4946 /* AV: shouldn't we check that it's been opened for read instead? */
4947 ret = file_permission(cfile.file, MAY_READ);
4952 * The control file must be a regular cgroup1 file. As a regular cgroup
4953 * file can't be renamed, it's safe to access its name afterwards.
4955 cdentry = cfile.file->f_path.dentry;
4956 if (cdentry->d_sb->s_type != &cgroup_fs_type || !d_is_reg(cdentry)) {
4962 * Determine the event callbacks and set them in @event. This used
4963 * to be done via struct cftype but cgroup core no longer knows
4964 * about these events. The following is crude but the whole thing
4965 * is for compatibility anyway.
4967 * DO NOT ADD NEW FILES.
4969 name = cdentry->d_name.name;
4971 if (!strcmp(name, "memory.usage_in_bytes")) {
4972 event->register_event = mem_cgroup_usage_register_event;
4973 event->unregister_event = mem_cgroup_usage_unregister_event;
4974 } else if (!strcmp(name, "memory.oom_control")) {
4975 event->register_event = mem_cgroup_oom_register_event;
4976 event->unregister_event = mem_cgroup_oom_unregister_event;
4977 } else if (!strcmp(name, "memory.pressure_level")) {
4978 event->register_event = vmpressure_register_event;
4979 event->unregister_event = vmpressure_unregister_event;
4980 } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
4981 event->register_event = memsw_cgroup_usage_register_event;
4982 event->unregister_event = memsw_cgroup_usage_unregister_event;
4989 * Verify @cfile should belong to @css. Also, remaining events are
4990 * automatically removed on cgroup destruction but the removal is
4991 * asynchronous, so take an extra ref on @css.
4993 cfile_css = css_tryget_online_from_dir(cdentry->d_parent,
4994 &memory_cgrp_subsys);
4996 if (IS_ERR(cfile_css))
4998 if (cfile_css != css) {
5003 ret = event->register_event(memcg, event->eventfd, buf);
5007 vfs_poll(efile.file, &event->pt);
5009 spin_lock_irq(&memcg->event_list_lock);
5010 list_add(&event->list, &memcg->event_list);
5011 spin_unlock_irq(&memcg->event_list_lock);
5023 eventfd_ctx_put(event->eventfd);
5032 #if defined(CONFIG_MEMCG_KMEM) && (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG))
5033 static int mem_cgroup_slab_show(struct seq_file *m, void *p)
5037 * Please, take a look at tools/cgroup/memcg_slabinfo.py .
5043 static int memory_stat_show(struct seq_file *m, void *v);
5045 static struct cftype mem_cgroup_legacy_files[] = {
5047 .name = "usage_in_bytes",
5048 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
5049 .read_u64 = mem_cgroup_read_u64,
5052 .name = "max_usage_in_bytes",
5053 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
5054 .write = mem_cgroup_reset,
5055 .read_u64 = mem_cgroup_read_u64,
5058 .name = "limit_in_bytes",
5059 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
5060 .write = mem_cgroup_write,
5061 .read_u64 = mem_cgroup_read_u64,
5064 .name = "soft_limit_in_bytes",
5065 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
5066 .write = mem_cgroup_write,
5067 .read_u64 = mem_cgroup_read_u64,
5071 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
5072 .write = mem_cgroup_reset,
5073 .read_u64 = mem_cgroup_read_u64,
5077 .seq_show = memory_stat_show,
5080 .name = "force_empty",
5081 .write = mem_cgroup_force_empty_write,
5084 .name = "use_hierarchy",
5085 .write_u64 = mem_cgroup_hierarchy_write,
5086 .read_u64 = mem_cgroup_hierarchy_read,
5089 .name = "cgroup.event_control", /* XXX: for compat */
5090 .write = memcg_write_event_control,
5091 .flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE,
5094 .name = "swappiness",
5095 .read_u64 = mem_cgroup_swappiness_read,
5096 .write_u64 = mem_cgroup_swappiness_write,
5099 .name = "move_charge_at_immigrate",
5100 .read_u64 = mem_cgroup_move_charge_read,
5101 .write_u64 = mem_cgroup_move_charge_write,
5104 .name = "oom_control",
5105 .seq_show = mem_cgroup_oom_control_read,
5106 .write_u64 = mem_cgroup_oom_control_write,
5109 .name = "pressure_level",
5110 .seq_show = mem_cgroup_dummy_seq_show,
5114 .name = "numa_stat",
5115 .seq_show = memcg_numa_stat_show,
5119 .name = "kmem.limit_in_bytes",
5120 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
5121 .write = mem_cgroup_write,
5122 .read_u64 = mem_cgroup_read_u64,
5125 .name = "kmem.usage_in_bytes",
5126 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
5127 .read_u64 = mem_cgroup_read_u64,
5130 .name = "kmem.failcnt",
5131 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
5132 .write = mem_cgroup_reset,
5133 .read_u64 = mem_cgroup_read_u64,
5136 .name = "kmem.max_usage_in_bytes",
5137 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
5138 .write = mem_cgroup_reset,
5139 .read_u64 = mem_cgroup_read_u64,
5141 #if defined(CONFIG_MEMCG_KMEM) && \
5142 (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG))
5144 .name = "kmem.slabinfo",
5145 .seq_show = mem_cgroup_slab_show,
5149 .name = "kmem.tcp.limit_in_bytes",
5150 .private = MEMFILE_PRIVATE(_TCP, RES_LIMIT),
5151 .write = mem_cgroup_write,
5152 .read_u64 = mem_cgroup_read_u64,
5155 .name = "kmem.tcp.usage_in_bytes",
5156 .private = MEMFILE_PRIVATE(_TCP, RES_USAGE),
5157 .read_u64 = mem_cgroup_read_u64,
5160 .name = "kmem.tcp.failcnt",
5161 .private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT),
5162 .write = mem_cgroup_reset,
5163 .read_u64 = mem_cgroup_read_u64,
5166 .name = "kmem.tcp.max_usage_in_bytes",
5167 .private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE),
5168 .write = mem_cgroup_reset,
5169 .read_u64 = mem_cgroup_read_u64,
5171 { }, /* terminate */
5175 * Private memory cgroup IDR
5177 * Swap-out records and page cache shadow entries need to store memcg
5178 * references in constrained space, so we maintain an ID space that is
5179 * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
5180 * memory-controlled cgroups to 64k.
5182 * However, there usually are many references to the offline CSS after
5183 * the cgroup has been destroyed, such as page cache or reclaimable
5184 * slab objects, that don't need to hang on to the ID. We want to keep
5185 * those dead CSS from occupying IDs, or we might quickly exhaust the
5186 * relatively small ID space and prevent the creation of new cgroups
5187 * even when there are much fewer than 64k cgroups - possibly none.
5189 * Maintain a private 16-bit ID space for memcg, and allow the ID to
5190 * be freed and recycled when it's no longer needed, which is usually
5191 * when the CSS is offlined.
5193 * The only exception to that are records of swapped out tmpfs/shmem
5194 * pages that need to be attributed to live ancestors on swapin. But
5195 * those references are manageable from userspace.
5198 #define MEM_CGROUP_ID_MAX ((1UL << MEM_CGROUP_ID_SHIFT) - 1)
5199 static DEFINE_IDR(mem_cgroup_idr);
5201 static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
5203 if (memcg->id.id > 0) {
5204 idr_remove(&mem_cgroup_idr, memcg->id.id);
5209 static void __maybe_unused mem_cgroup_id_get_many(struct mem_cgroup *memcg,
5212 refcount_add(n, &memcg->id.ref);
5215 static void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
5217 if (refcount_sub_and_test(n, &memcg->id.ref)) {
5218 mem_cgroup_id_remove(memcg);
5220 /* Memcg ID pins CSS */
5221 css_put(&memcg->css);
5225 static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
5227 mem_cgroup_id_put_many(memcg, 1);
5231 * mem_cgroup_from_id - look up a memcg from a memcg id
5232 * @id: the memcg id to look up
5234 * Caller must hold rcu_read_lock().
5236 struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
5238 WARN_ON_ONCE(!rcu_read_lock_held());
5239 return idr_find(&mem_cgroup_idr, id);
5242 #ifdef CONFIG_SHRINKER_DEBUG
5243 struct mem_cgroup *mem_cgroup_get_from_ino(unsigned long ino)
5245 struct cgroup *cgrp;
5246 struct cgroup_subsys_state *css;
5247 struct mem_cgroup *memcg;
5249 cgrp = cgroup_get_from_id(ino);
5251 return ERR_CAST(cgrp);
5253 css = cgroup_get_e_css(cgrp, &memory_cgrp_subsys);
5255 memcg = container_of(css, struct mem_cgroup, css);
5257 memcg = ERR_PTR(-ENOENT);
5265 static int alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5267 struct mem_cgroup_per_node *pn;
5269 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, node);
5273 pn->lruvec_stats_percpu = alloc_percpu_gfp(struct lruvec_stats_percpu,
5274 GFP_KERNEL_ACCOUNT);
5275 if (!pn->lruvec_stats_percpu) {
5280 lruvec_init(&pn->lruvec);
5283 memcg->nodeinfo[node] = pn;
5287 static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5289 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
5294 free_percpu(pn->lruvec_stats_percpu);
5298 static void __mem_cgroup_free(struct mem_cgroup *memcg)
5303 free_mem_cgroup_per_node_info(memcg, node);
5304 kfree(memcg->vmstats);
5305 free_percpu(memcg->vmstats_percpu);
5309 static void mem_cgroup_free(struct mem_cgroup *memcg)
5311 lru_gen_exit_memcg(memcg);
5312 memcg_wb_domain_exit(memcg);
5313 __mem_cgroup_free(memcg);
5316 static struct mem_cgroup *mem_cgroup_alloc(void)
5318 struct mem_cgroup *memcg;
5320 int __maybe_unused i;
5321 long error = -ENOMEM;
5323 memcg = kzalloc(struct_size(memcg, nodeinfo, nr_node_ids), GFP_KERNEL);
5325 return ERR_PTR(error);
5327 memcg->id.id = idr_alloc(&mem_cgroup_idr, NULL,
5328 1, MEM_CGROUP_ID_MAX + 1, GFP_KERNEL);
5329 if (memcg->id.id < 0) {
5330 error = memcg->id.id;
5334 memcg->vmstats = kzalloc(sizeof(struct memcg_vmstats), GFP_KERNEL);
5335 if (!memcg->vmstats)
5338 memcg->vmstats_percpu = alloc_percpu_gfp(struct memcg_vmstats_percpu,
5339 GFP_KERNEL_ACCOUNT);
5340 if (!memcg->vmstats_percpu)
5344 if (alloc_mem_cgroup_per_node_info(memcg, node))
5347 if (memcg_wb_domain_init(memcg, GFP_KERNEL))
5350 INIT_WORK(&memcg->high_work, high_work_func);
5351 INIT_LIST_HEAD(&memcg->oom_notify);
5352 mutex_init(&memcg->thresholds_lock);
5353 spin_lock_init(&memcg->move_lock);
5354 vmpressure_init(&memcg->vmpressure);
5355 INIT_LIST_HEAD(&memcg->event_list);
5356 spin_lock_init(&memcg->event_list_lock);
5357 memcg->socket_pressure = jiffies;
5358 #ifdef CONFIG_MEMCG_KMEM
5359 memcg->kmemcg_id = -1;
5360 INIT_LIST_HEAD(&memcg->objcg_list);
5362 #ifdef CONFIG_CGROUP_WRITEBACK
5363 INIT_LIST_HEAD(&memcg->cgwb_list);
5364 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5365 memcg->cgwb_frn[i].done =
5366 __WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
5368 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5369 spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
5370 INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
5371 memcg->deferred_split_queue.split_queue_len = 0;
5373 lru_gen_init_memcg(memcg);
5376 mem_cgroup_id_remove(memcg);
5377 __mem_cgroup_free(memcg);
5378 return ERR_PTR(error);
5381 static struct cgroup_subsys_state * __ref
5382 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
5384 struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
5385 struct mem_cgroup *memcg, *old_memcg;
5387 old_memcg = set_active_memcg(parent);
5388 memcg = mem_cgroup_alloc();
5389 set_active_memcg(old_memcg);
5391 return ERR_CAST(memcg);
5393 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5394 WRITE_ONCE(memcg->soft_limit, PAGE_COUNTER_MAX);
5395 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
5396 memcg->zswap_max = PAGE_COUNTER_MAX;
5398 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5400 WRITE_ONCE(memcg->swappiness, mem_cgroup_swappiness(parent));
5401 WRITE_ONCE(memcg->oom_kill_disable, READ_ONCE(parent->oom_kill_disable));
5403 page_counter_init(&memcg->memory, &parent->memory);
5404 page_counter_init(&memcg->swap, &parent->swap);
5405 page_counter_init(&memcg->kmem, &parent->kmem);
5406 page_counter_init(&memcg->tcpmem, &parent->tcpmem);
5408 init_memcg_events();
5409 page_counter_init(&memcg->memory, NULL);
5410 page_counter_init(&memcg->swap, NULL);
5411 page_counter_init(&memcg->kmem, NULL);
5412 page_counter_init(&memcg->tcpmem, NULL);
5414 root_mem_cgroup = memcg;
5418 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5419 static_branch_inc(&memcg_sockets_enabled_key);
5421 #if defined(CONFIG_MEMCG_KMEM)
5422 if (!cgroup_memory_nobpf)
5423 static_branch_inc(&memcg_bpf_enabled_key);
5429 static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
5431 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5433 if (memcg_online_kmem(memcg))
5437 * A memcg must be visible for expand_shrinker_info()
5438 * by the time the maps are allocated. So, we allocate maps
5439 * here, when for_each_mem_cgroup() can't skip it.
5441 if (alloc_shrinker_info(memcg))
5444 if (unlikely(mem_cgroup_is_root(memcg)))
5445 queue_delayed_work(system_unbound_wq, &stats_flush_dwork,
5447 lru_gen_online_memcg(memcg);
5449 /* Online state pins memcg ID, memcg ID pins CSS */
5450 refcount_set(&memcg->id.ref, 1);
5454 * Ensure mem_cgroup_from_id() works once we're fully online.
5456 * We could do this earlier and require callers to filter with
5457 * css_tryget_online(). But right now there are no users that
5458 * need earlier access, and the workingset code relies on the
5459 * cgroup tree linkage (mem_cgroup_get_nr_swap_pages()). So
5460 * publish it here at the end of onlining. This matches the
5461 * regular ID destruction during offlining.
5463 idr_replace(&mem_cgroup_idr, memcg, memcg->id.id);
5467 memcg_offline_kmem(memcg);
5469 mem_cgroup_id_remove(memcg);
5473 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
5475 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5476 struct mem_cgroup_event *event, *tmp;
5479 * Unregister events and notify userspace.
5480 * Notify userspace about cgroup removing only after rmdir of cgroup
5481 * directory to avoid race between userspace and kernelspace.
5483 spin_lock_irq(&memcg->event_list_lock);
5484 list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
5485 list_del_init(&event->list);
5486 schedule_work(&event->remove);
5488 spin_unlock_irq(&memcg->event_list_lock);
5490 page_counter_set_min(&memcg->memory, 0);
5491 page_counter_set_low(&memcg->memory, 0);
5493 memcg_offline_kmem(memcg);
5494 reparent_shrinker_deferred(memcg);
5495 wb_memcg_offline(memcg);
5496 lru_gen_offline_memcg(memcg);
5498 drain_all_stock(memcg);
5500 mem_cgroup_id_put(memcg);
5503 static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
5505 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5507 invalidate_reclaim_iterators(memcg);
5508 lru_gen_release_memcg(memcg);
5511 static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
5513 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5514 int __maybe_unused i;
5516 #ifdef CONFIG_CGROUP_WRITEBACK
5517 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5518 wb_wait_for_completion(&memcg->cgwb_frn[i].done);
5520 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5521 static_branch_dec(&memcg_sockets_enabled_key);
5523 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg->tcpmem_active)
5524 static_branch_dec(&memcg_sockets_enabled_key);
5526 #if defined(CONFIG_MEMCG_KMEM)
5527 if (!cgroup_memory_nobpf)
5528 static_branch_dec(&memcg_bpf_enabled_key);
5531 vmpressure_cleanup(&memcg->vmpressure);
5532 cancel_work_sync(&memcg->high_work);
5533 mem_cgroup_remove_from_trees(memcg);
5534 free_shrinker_info(memcg);
5535 mem_cgroup_free(memcg);
5539 * mem_cgroup_css_reset - reset the states of a mem_cgroup
5540 * @css: the target css
5542 * Reset the states of the mem_cgroup associated with @css. This is
5543 * invoked when the userland requests disabling on the default hierarchy
5544 * but the memcg is pinned through dependency. The memcg should stop
5545 * applying policies and should revert to the vanilla state as it may be
5546 * made visible again.
5548 * The current implementation only resets the essential configurations.
5549 * This needs to be expanded to cover all the visible parts.
5551 static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
5553 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5555 page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
5556 page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
5557 page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
5558 page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
5559 page_counter_set_min(&memcg->memory, 0);
5560 page_counter_set_low(&memcg->memory, 0);
5561 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5562 WRITE_ONCE(memcg->soft_limit, PAGE_COUNTER_MAX);
5563 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5564 memcg_wb_domain_size_changed(memcg);
5567 static void mem_cgroup_css_rstat_flush(struct cgroup_subsys_state *css, int cpu)
5569 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5570 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
5571 struct memcg_vmstats_percpu *statc;
5572 long delta, delta_cpu, v;
5575 statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
5577 for (i = 0; i < MEMCG_NR_STAT; i++) {
5579 * Collect the aggregated propagation counts of groups
5580 * below us. We're in a per-cpu loop here and this is
5581 * a global counter, so the first cycle will get them.
5583 delta = memcg->vmstats->state_pending[i];
5585 memcg->vmstats->state_pending[i] = 0;
5587 /* Add CPU changes on this level since the last flush */
5589 v = READ_ONCE(statc->state[i]);
5590 if (v != statc->state_prev[i]) {
5591 delta_cpu = v - statc->state_prev[i];
5593 statc->state_prev[i] = v;
5596 /* Aggregate counts on this level and propagate upwards */
5598 memcg->vmstats->state_local[i] += delta_cpu;
5601 memcg->vmstats->state[i] += delta;
5603 parent->vmstats->state_pending[i] += delta;
5607 for (i = 0; i < NR_MEMCG_EVENTS; i++) {
5608 delta = memcg->vmstats->events_pending[i];
5610 memcg->vmstats->events_pending[i] = 0;
5613 v = READ_ONCE(statc->events[i]);
5614 if (v != statc->events_prev[i]) {
5615 delta_cpu = v - statc->events_prev[i];
5617 statc->events_prev[i] = v;
5621 memcg->vmstats->events_local[i] += delta_cpu;
5624 memcg->vmstats->events[i] += delta;
5626 parent->vmstats->events_pending[i] += delta;
5630 for_each_node_state(nid, N_MEMORY) {
5631 struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
5632 struct mem_cgroup_per_node *ppn = NULL;
5633 struct lruvec_stats_percpu *lstatc;
5636 ppn = parent->nodeinfo[nid];
5638 lstatc = per_cpu_ptr(pn->lruvec_stats_percpu, cpu);
5640 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++) {
5641 delta = pn->lruvec_stats.state_pending[i];
5643 pn->lruvec_stats.state_pending[i] = 0;
5646 v = READ_ONCE(lstatc->state[i]);
5647 if (v != lstatc->state_prev[i]) {
5648 delta_cpu = v - lstatc->state_prev[i];
5650 lstatc->state_prev[i] = v;
5654 pn->lruvec_stats.state_local[i] += delta_cpu;
5657 pn->lruvec_stats.state[i] += delta;
5659 ppn->lruvec_stats.state_pending[i] += delta;
5666 /* Handlers for move charge at task migration. */
5667 static int mem_cgroup_do_precharge(unsigned long count)
5671 /* Try a single bulk charge without reclaim first, kswapd may wake */
5672 ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count);
5674 mc.precharge += count;
5678 /* Try charges one by one with reclaim, but do not retry */
5680 ret = try_charge(mc.to, GFP_KERNEL | __GFP_NORETRY, 1);
5694 enum mc_target_type {
5701 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5702 unsigned long addr, pte_t ptent)
5704 struct page *page = vm_normal_page(vma, addr, ptent);
5708 if (PageAnon(page)) {
5709 if (!(mc.flags & MOVE_ANON))
5712 if (!(mc.flags & MOVE_FILE))
5720 #if defined(CONFIG_SWAP) || defined(CONFIG_DEVICE_PRIVATE)
5721 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5722 pte_t ptent, swp_entry_t *entry)
5724 struct page *page = NULL;
5725 swp_entry_t ent = pte_to_swp_entry(ptent);
5727 if (!(mc.flags & MOVE_ANON))
5731 * Handle device private pages that are not accessible by the CPU, but
5732 * stored as special swap entries in the page table.
5734 if (is_device_private_entry(ent)) {
5735 page = pfn_swap_entry_to_page(ent);
5736 if (!get_page_unless_zero(page))
5741 if (non_swap_entry(ent))
5745 * Because swap_cache_get_folio() updates some statistics counter,
5746 * we call find_get_page() with swapper_space directly.
5748 page = find_get_page(swap_address_space(ent), swp_offset(ent));
5749 entry->val = ent.val;
5754 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5755 pte_t ptent, swp_entry_t *entry)
5761 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5762 unsigned long addr, pte_t ptent)
5764 unsigned long index;
5765 struct folio *folio;
5767 if (!vma->vm_file) /* anonymous vma */
5769 if (!(mc.flags & MOVE_FILE))
5772 /* folio is moved even if it's not RSS of this task(page-faulted). */
5773 /* shmem/tmpfs may report page out on swap: account for that too. */
5774 index = linear_page_index(vma, addr);
5775 folio = filemap_get_incore_folio(vma->vm_file->f_mapping, index);
5778 return folio_file_page(folio, index);
5782 * mem_cgroup_move_account - move account of the page
5784 * @compound: charge the page as compound or small page
5785 * @from: mem_cgroup which the page is moved from.
5786 * @to: mem_cgroup which the page is moved to. @from != @to.
5788 * The page must be locked and not on the LRU.
5790 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
5793 static int mem_cgroup_move_account(struct page *page,
5795 struct mem_cgroup *from,
5796 struct mem_cgroup *to)
5798 struct folio *folio = page_folio(page);
5799 struct lruvec *from_vec, *to_vec;
5800 struct pglist_data *pgdat;
5801 unsigned int nr_pages = compound ? folio_nr_pages(folio) : 1;
5804 VM_BUG_ON(from == to);
5805 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
5806 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
5807 VM_BUG_ON(compound && !folio_test_large(folio));
5810 if (folio_memcg(folio) != from)
5813 pgdat = folio_pgdat(folio);
5814 from_vec = mem_cgroup_lruvec(from, pgdat);
5815 to_vec = mem_cgroup_lruvec(to, pgdat);
5817 folio_memcg_lock(folio);
5819 if (folio_test_anon(folio)) {
5820 if (folio_mapped(folio)) {
5821 __mod_lruvec_state(from_vec, NR_ANON_MAPPED, -nr_pages);
5822 __mod_lruvec_state(to_vec, NR_ANON_MAPPED, nr_pages);
5823 if (folio_test_pmd_mappable(folio)) {
5824 __mod_lruvec_state(from_vec, NR_ANON_THPS,
5826 __mod_lruvec_state(to_vec, NR_ANON_THPS,
5831 __mod_lruvec_state(from_vec, NR_FILE_PAGES, -nr_pages);
5832 __mod_lruvec_state(to_vec, NR_FILE_PAGES, nr_pages);
5834 if (folio_test_swapbacked(folio)) {
5835 __mod_lruvec_state(from_vec, NR_SHMEM, -nr_pages);
5836 __mod_lruvec_state(to_vec, NR_SHMEM, nr_pages);
5839 if (folio_mapped(folio)) {
5840 __mod_lruvec_state(from_vec, NR_FILE_MAPPED, -nr_pages);
5841 __mod_lruvec_state(to_vec, NR_FILE_MAPPED, nr_pages);
5844 if (folio_test_dirty(folio)) {
5845 struct address_space *mapping = folio_mapping(folio);
5847 if (mapping_can_writeback(mapping)) {
5848 __mod_lruvec_state(from_vec, NR_FILE_DIRTY,
5850 __mod_lruvec_state(to_vec, NR_FILE_DIRTY,
5857 if (folio_test_swapcache(folio)) {
5858 __mod_lruvec_state(from_vec, NR_SWAPCACHE, -nr_pages);
5859 __mod_lruvec_state(to_vec, NR_SWAPCACHE, nr_pages);
5862 if (folio_test_writeback(folio)) {
5863 __mod_lruvec_state(from_vec, NR_WRITEBACK, -nr_pages);
5864 __mod_lruvec_state(to_vec, NR_WRITEBACK, nr_pages);
5868 * All state has been migrated, let's switch to the new memcg.
5870 * It is safe to change page's memcg here because the page
5871 * is referenced, charged, isolated, and locked: we can't race
5872 * with (un)charging, migration, LRU putback, or anything else
5873 * that would rely on a stable page's memory cgroup.
5875 * Note that folio_memcg_lock is a memcg lock, not a page lock,
5876 * to save space. As soon as we switch page's memory cgroup to a
5877 * new memcg that isn't locked, the above state can change
5878 * concurrently again. Make sure we're truly done with it.
5883 css_put(&from->css);
5885 folio->memcg_data = (unsigned long)to;
5887 __folio_memcg_unlock(from);
5890 nid = folio_nid(folio);
5892 local_irq_disable();
5893 mem_cgroup_charge_statistics(to, nr_pages);
5894 memcg_check_events(to, nid);
5895 mem_cgroup_charge_statistics(from, -nr_pages);
5896 memcg_check_events(from, nid);
5903 * get_mctgt_type - get target type of moving charge
5904 * @vma: the vma the pte to be checked belongs
5905 * @addr: the address corresponding to the pte to be checked
5906 * @ptent: the pte to be checked
5907 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5909 * Context: Called with pte lock held.
5911 * * MC_TARGET_NONE - If the pte is not a target for move charge.
5912 * * MC_TARGET_PAGE - If the page corresponding to this pte is a target for
5913 * move charge. If @target is not NULL, the page is stored in target->page
5914 * with extra refcnt taken (Caller should release it).
5915 * * MC_TARGET_SWAP - If the swap entry corresponding to this pte is a
5916 * target for charge migration. If @target is not NULL, the entry is
5917 * stored in target->ent.
5918 * * MC_TARGET_DEVICE - Like MC_TARGET_PAGE but page is device memory and
5919 * thus not on the lru. For now such page is charged like a regular page
5920 * would be as it is just special memory taking the place of a regular page.
5921 * See Documentations/vm/hmm.txt and include/linux/hmm.h
5923 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
5924 unsigned long addr, pte_t ptent, union mc_target *target)
5926 struct page *page = NULL;
5927 enum mc_target_type ret = MC_TARGET_NONE;
5928 swp_entry_t ent = { .val = 0 };
5930 if (pte_present(ptent))
5931 page = mc_handle_present_pte(vma, addr, ptent);
5932 else if (pte_none_mostly(ptent))
5934 * PTE markers should be treated as a none pte here, separated
5935 * from other swap handling below.
5937 page = mc_handle_file_pte(vma, addr, ptent);
5938 else if (is_swap_pte(ptent))
5939 page = mc_handle_swap_pte(vma, ptent, &ent);
5941 if (target && page) {
5942 if (!trylock_page(page)) {
5947 * page_mapped() must be stable during the move. This
5948 * pte is locked, so if it's present, the page cannot
5949 * become unmapped. If it isn't, we have only partial
5950 * control over the mapped state: the page lock will
5951 * prevent new faults against pagecache and swapcache,
5952 * so an unmapped page cannot become mapped. However,
5953 * if the page is already mapped elsewhere, it can
5954 * unmap, and there is nothing we can do about it.
5955 * Alas, skip moving the page in this case.
5957 if (!pte_present(ptent) && page_mapped(page)) {
5964 if (!page && !ent.val)
5968 * Do only loose check w/o serialization.
5969 * mem_cgroup_move_account() checks the page is valid or
5970 * not under LRU exclusion.
5972 if (page_memcg(page) == mc.from) {
5973 ret = MC_TARGET_PAGE;
5974 if (is_device_private_page(page) ||
5975 is_device_coherent_page(page))
5976 ret = MC_TARGET_DEVICE;
5978 target->page = page;
5980 if (!ret || !target) {
5987 * There is a swap entry and a page doesn't exist or isn't charged.
5988 * But we cannot move a tail-page in a THP.
5990 if (ent.val && !ret && (!page || !PageTransCompound(page)) &&
5991 mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
5992 ret = MC_TARGET_SWAP;
5999 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
6001 * We don't consider PMD mapped swapping or file mapped pages because THP does
6002 * not support them for now.
6003 * Caller should make sure that pmd_trans_huge(pmd) is true.
6005 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
6006 unsigned long addr, pmd_t pmd, union mc_target *target)
6008 struct page *page = NULL;
6009 enum mc_target_type ret = MC_TARGET_NONE;
6011 if (unlikely(is_swap_pmd(pmd))) {
6012 VM_BUG_ON(thp_migration_supported() &&
6013 !is_pmd_migration_entry(pmd));
6016 page = pmd_page(pmd);
6017 VM_BUG_ON_PAGE(!page || !PageHead(page), page);
6018 if (!(mc.flags & MOVE_ANON))
6020 if (page_memcg(page) == mc.from) {
6021 ret = MC_TARGET_PAGE;
6024 if (!trylock_page(page)) {
6026 return MC_TARGET_NONE;
6028 target->page = page;
6034 static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
6035 unsigned long addr, pmd_t pmd, union mc_target *target)
6037 return MC_TARGET_NONE;
6041 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
6042 unsigned long addr, unsigned long end,
6043 struct mm_walk *walk)
6045 struct vm_area_struct *vma = walk->vma;
6049 ptl = pmd_trans_huge_lock(pmd, vma);
6052 * Note their can not be MC_TARGET_DEVICE for now as we do not
6053 * support transparent huge page with MEMORY_DEVICE_PRIVATE but
6054 * this might change.
6056 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
6057 mc.precharge += HPAGE_PMD_NR;
6062 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6065 for (; addr != end; pte++, addr += PAGE_SIZE)
6066 if (get_mctgt_type(vma, addr, ptep_get(pte), NULL))
6067 mc.precharge++; /* increment precharge temporarily */
6068 pte_unmap_unlock(pte - 1, ptl);
6074 static const struct mm_walk_ops precharge_walk_ops = {
6075 .pmd_entry = mem_cgroup_count_precharge_pte_range,
6076 .walk_lock = PGWALK_RDLOCK,
6079 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
6081 unsigned long precharge;
6084 walk_page_range(mm, 0, ULONG_MAX, &precharge_walk_ops, NULL);
6085 mmap_read_unlock(mm);
6087 precharge = mc.precharge;
6093 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
6095 unsigned long precharge = mem_cgroup_count_precharge(mm);
6097 VM_BUG_ON(mc.moving_task);
6098 mc.moving_task = current;
6099 return mem_cgroup_do_precharge(precharge);
6102 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
6103 static void __mem_cgroup_clear_mc(void)
6105 struct mem_cgroup *from = mc.from;
6106 struct mem_cgroup *to = mc.to;
6108 /* we must uncharge all the leftover precharges from mc.to */
6110 cancel_charge(mc.to, mc.precharge);
6114 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
6115 * we must uncharge here.
6117 if (mc.moved_charge) {
6118 cancel_charge(mc.from, mc.moved_charge);
6119 mc.moved_charge = 0;
6121 /* we must fixup refcnts and charges */
6122 if (mc.moved_swap) {
6123 /* uncharge swap account from the old cgroup */
6124 if (!mem_cgroup_is_root(mc.from))
6125 page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
6127 mem_cgroup_id_put_many(mc.from, mc.moved_swap);
6130 * we charged both to->memory and to->memsw, so we
6131 * should uncharge to->memory.
6133 if (!mem_cgroup_is_root(mc.to))
6134 page_counter_uncharge(&mc.to->memory, mc.moved_swap);
6138 memcg_oom_recover(from);
6139 memcg_oom_recover(to);
6140 wake_up_all(&mc.waitq);
6143 static void mem_cgroup_clear_mc(void)
6145 struct mm_struct *mm = mc.mm;
6148 * we must clear moving_task before waking up waiters at the end of
6151 mc.moving_task = NULL;
6152 __mem_cgroup_clear_mc();
6153 spin_lock(&mc.lock);
6157 spin_unlock(&mc.lock);
6162 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
6164 struct cgroup_subsys_state *css;
6165 struct mem_cgroup *memcg = NULL; /* unneeded init to make gcc happy */
6166 struct mem_cgroup *from;
6167 struct task_struct *leader, *p;
6168 struct mm_struct *mm;
6169 unsigned long move_flags;
6172 /* charge immigration isn't supported on the default hierarchy */
6173 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
6177 * Multi-process migrations only happen on the default hierarchy
6178 * where charge immigration is not used. Perform charge
6179 * immigration if @tset contains a leader and whine if there are
6183 cgroup_taskset_for_each_leader(leader, css, tset) {
6186 memcg = mem_cgroup_from_css(css);
6192 * We are now committed to this value whatever it is. Changes in this
6193 * tunable will only affect upcoming migrations, not the current one.
6194 * So we need to save it, and keep it going.
6196 move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
6200 from = mem_cgroup_from_task(p);
6202 VM_BUG_ON(from == memcg);
6204 mm = get_task_mm(p);
6207 /* We move charges only when we move a owner of the mm */
6208 if (mm->owner == p) {
6211 VM_BUG_ON(mc.precharge);
6212 VM_BUG_ON(mc.moved_charge);
6213 VM_BUG_ON(mc.moved_swap);
6215 spin_lock(&mc.lock);
6219 mc.flags = move_flags;
6220 spin_unlock(&mc.lock);
6221 /* We set mc.moving_task later */
6223 ret = mem_cgroup_precharge_mc(mm);
6225 mem_cgroup_clear_mc();
6232 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6235 mem_cgroup_clear_mc();
6238 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
6239 unsigned long addr, unsigned long end,
6240 struct mm_walk *walk)
6243 struct vm_area_struct *vma = walk->vma;
6246 enum mc_target_type target_type;
6247 union mc_target target;
6250 ptl = pmd_trans_huge_lock(pmd, vma);
6252 if (mc.precharge < HPAGE_PMD_NR) {
6256 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
6257 if (target_type == MC_TARGET_PAGE) {
6259 if (isolate_lru_page(page)) {
6260 if (!mem_cgroup_move_account(page, true,
6262 mc.precharge -= HPAGE_PMD_NR;
6263 mc.moved_charge += HPAGE_PMD_NR;
6265 putback_lru_page(page);
6269 } else if (target_type == MC_TARGET_DEVICE) {
6271 if (!mem_cgroup_move_account(page, true,
6273 mc.precharge -= HPAGE_PMD_NR;
6274 mc.moved_charge += HPAGE_PMD_NR;
6284 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6287 for (; addr != end; addr += PAGE_SIZE) {
6288 pte_t ptent = ptep_get(pte++);
6289 bool device = false;
6295 switch (get_mctgt_type(vma, addr, ptent, &target)) {
6296 case MC_TARGET_DEVICE:
6299 case MC_TARGET_PAGE:
6302 * We can have a part of the split pmd here. Moving it
6303 * can be done but it would be too convoluted so simply
6304 * ignore such a partial THP and keep it in original
6305 * memcg. There should be somebody mapping the head.
6307 if (PageTransCompound(page))
6309 if (!device && !isolate_lru_page(page))
6311 if (!mem_cgroup_move_account(page, false,
6314 /* we uncharge from mc.from later. */
6318 putback_lru_page(page);
6319 put: /* get_mctgt_type() gets & locks the page */
6323 case MC_TARGET_SWAP:
6325 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
6327 mem_cgroup_id_get_many(mc.to, 1);
6328 /* we fixup other refcnts and charges later. */
6336 pte_unmap_unlock(pte - 1, ptl);
6341 * We have consumed all precharges we got in can_attach().
6342 * We try charge one by one, but don't do any additional
6343 * charges to mc.to if we have failed in charge once in attach()
6346 ret = mem_cgroup_do_precharge(1);
6354 static const struct mm_walk_ops charge_walk_ops = {
6355 .pmd_entry = mem_cgroup_move_charge_pte_range,
6356 .walk_lock = PGWALK_RDLOCK,
6359 static void mem_cgroup_move_charge(void)
6361 lru_add_drain_all();
6363 * Signal folio_memcg_lock() to take the memcg's move_lock
6364 * while we're moving its pages to another memcg. Then wait
6365 * for already started RCU-only updates to finish.
6367 atomic_inc(&mc.from->moving_account);
6370 if (unlikely(!mmap_read_trylock(mc.mm))) {
6372 * Someone who are holding the mmap_lock might be waiting in
6373 * waitq. So we cancel all extra charges, wake up all waiters,
6374 * and retry. Because we cancel precharges, we might not be able
6375 * to move enough charges, but moving charge is a best-effort
6376 * feature anyway, so it wouldn't be a big problem.
6378 __mem_cgroup_clear_mc();
6383 * When we have consumed all precharges and failed in doing
6384 * additional charge, the page walk just aborts.
6386 walk_page_range(mc.mm, 0, ULONG_MAX, &charge_walk_ops, NULL);
6387 mmap_read_unlock(mc.mm);
6388 atomic_dec(&mc.from->moving_account);
6391 static void mem_cgroup_move_task(void)
6394 mem_cgroup_move_charge();
6395 mem_cgroup_clear_mc();
6398 #else /* !CONFIG_MMU */
6399 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
6403 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6406 static void mem_cgroup_move_task(void)
6411 #ifdef CONFIG_LRU_GEN
6412 static void mem_cgroup_attach(struct cgroup_taskset *tset)
6414 struct task_struct *task;
6415 struct cgroup_subsys_state *css;
6417 /* find the first leader if there is any */
6418 cgroup_taskset_for_each_leader(task, css, tset)
6425 if (task->mm && READ_ONCE(task->mm->owner) == task)
6426 lru_gen_migrate_mm(task->mm);
6430 static void mem_cgroup_attach(struct cgroup_taskset *tset)
6433 #endif /* CONFIG_LRU_GEN */
6435 static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
6437 if (value == PAGE_COUNTER_MAX)
6438 seq_puts(m, "max\n");
6440 seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
6445 static u64 memory_current_read(struct cgroup_subsys_state *css,
6448 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6450 return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
6453 static u64 memory_peak_read(struct cgroup_subsys_state *css,
6456 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6458 return (u64)memcg->memory.watermark * PAGE_SIZE;
6461 static int memory_min_show(struct seq_file *m, void *v)
6463 return seq_puts_memcg_tunable(m,
6464 READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
6467 static ssize_t memory_min_write(struct kernfs_open_file *of,
6468 char *buf, size_t nbytes, loff_t off)
6470 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6474 buf = strstrip(buf);
6475 err = page_counter_memparse(buf, "max", &min);
6479 page_counter_set_min(&memcg->memory, min);
6484 static int memory_low_show(struct seq_file *m, void *v)
6486 return seq_puts_memcg_tunable(m,
6487 READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
6490 static ssize_t memory_low_write(struct kernfs_open_file *of,
6491 char *buf, size_t nbytes, loff_t off)
6493 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6497 buf = strstrip(buf);
6498 err = page_counter_memparse(buf, "max", &low);
6502 page_counter_set_low(&memcg->memory, low);
6507 static int memory_high_show(struct seq_file *m, void *v)
6509 return seq_puts_memcg_tunable(m,
6510 READ_ONCE(mem_cgroup_from_seq(m)->memory.high));
6513 static ssize_t memory_high_write(struct kernfs_open_file *of,
6514 char *buf, size_t nbytes, loff_t off)
6516 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6517 unsigned int nr_retries = MAX_RECLAIM_RETRIES;
6518 bool drained = false;
6522 buf = strstrip(buf);
6523 err = page_counter_memparse(buf, "max", &high);
6527 page_counter_set_high(&memcg->memory, high);
6530 unsigned long nr_pages = page_counter_read(&memcg->memory);
6531 unsigned long reclaimed;
6533 if (nr_pages <= high)
6536 if (signal_pending(current))
6540 drain_all_stock(memcg);
6545 reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
6546 GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP);
6548 if (!reclaimed && !nr_retries--)
6552 memcg_wb_domain_size_changed(memcg);
6556 static int memory_max_show(struct seq_file *m, void *v)
6558 return seq_puts_memcg_tunable(m,
6559 READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
6562 static ssize_t memory_max_write(struct kernfs_open_file *of,
6563 char *buf, size_t nbytes, loff_t off)
6565 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6566 unsigned int nr_reclaims = MAX_RECLAIM_RETRIES;
6567 bool drained = false;
6571 buf = strstrip(buf);
6572 err = page_counter_memparse(buf, "max", &max);
6576 xchg(&memcg->memory.max, max);
6579 unsigned long nr_pages = page_counter_read(&memcg->memory);
6581 if (nr_pages <= max)
6584 if (signal_pending(current))
6588 drain_all_stock(memcg);
6594 if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
6595 GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP))
6600 memcg_memory_event(memcg, MEMCG_OOM);
6601 if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
6605 memcg_wb_domain_size_changed(memcg);
6609 static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
6611 seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
6612 seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
6613 seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
6614 seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
6615 seq_printf(m, "oom_kill %lu\n",
6616 atomic_long_read(&events[MEMCG_OOM_KILL]));
6617 seq_printf(m, "oom_group_kill %lu\n",
6618 atomic_long_read(&events[MEMCG_OOM_GROUP_KILL]));
6621 static int memory_events_show(struct seq_file *m, void *v)
6623 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6625 __memory_events_show(m, memcg->memory_events);
6629 static int memory_events_local_show(struct seq_file *m, void *v)
6631 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6633 __memory_events_show(m, memcg->memory_events_local);
6637 static int memory_stat_show(struct seq_file *m, void *v)
6639 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6640 char *buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
6645 seq_buf_init(&s, buf, PAGE_SIZE);
6646 memory_stat_format(memcg, &s);
6653 static inline unsigned long lruvec_page_state_output(struct lruvec *lruvec,
6656 return lruvec_page_state(lruvec, item) * memcg_page_state_unit(item);
6659 static int memory_numa_stat_show(struct seq_file *m, void *v)
6662 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6664 mem_cgroup_flush_stats();
6666 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
6669 if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS)
6672 seq_printf(m, "%s", memory_stats[i].name);
6673 for_each_node_state(nid, N_MEMORY) {
6675 struct lruvec *lruvec;
6677 lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
6678 size = lruvec_page_state_output(lruvec,
6679 memory_stats[i].idx);
6680 seq_printf(m, " N%d=%llu", nid, size);
6689 static int memory_oom_group_show(struct seq_file *m, void *v)
6691 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6693 seq_printf(m, "%d\n", READ_ONCE(memcg->oom_group));
6698 static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
6699 char *buf, size_t nbytes, loff_t off)
6701 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6704 buf = strstrip(buf);
6708 ret = kstrtoint(buf, 0, &oom_group);
6712 if (oom_group != 0 && oom_group != 1)
6715 WRITE_ONCE(memcg->oom_group, oom_group);
6720 static ssize_t memory_reclaim(struct kernfs_open_file *of, char *buf,
6721 size_t nbytes, loff_t off)
6723 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6724 unsigned int nr_retries = MAX_RECLAIM_RETRIES;
6725 unsigned long nr_to_reclaim, nr_reclaimed = 0;
6726 unsigned int reclaim_options;
6729 buf = strstrip(buf);
6730 err = page_counter_memparse(buf, "", &nr_to_reclaim);
6734 reclaim_options = MEMCG_RECLAIM_MAY_SWAP | MEMCG_RECLAIM_PROACTIVE;
6735 while (nr_reclaimed < nr_to_reclaim) {
6736 unsigned long reclaimed;
6738 if (signal_pending(current))
6742 * This is the final attempt, drain percpu lru caches in the
6743 * hope of introducing more evictable pages for
6744 * try_to_free_mem_cgroup_pages().
6747 lru_add_drain_all();
6749 reclaimed = try_to_free_mem_cgroup_pages(memcg,
6750 min(nr_to_reclaim - nr_reclaimed, SWAP_CLUSTER_MAX),
6751 GFP_KERNEL, reclaim_options);
6753 if (!reclaimed && !nr_retries--)
6756 nr_reclaimed += reclaimed;
6762 static struct cftype memory_files[] = {
6765 .flags = CFTYPE_NOT_ON_ROOT,
6766 .read_u64 = memory_current_read,
6770 .flags = CFTYPE_NOT_ON_ROOT,
6771 .read_u64 = memory_peak_read,
6775 .flags = CFTYPE_NOT_ON_ROOT,
6776 .seq_show = memory_min_show,
6777 .write = memory_min_write,
6781 .flags = CFTYPE_NOT_ON_ROOT,
6782 .seq_show = memory_low_show,
6783 .write = memory_low_write,
6787 .flags = CFTYPE_NOT_ON_ROOT,
6788 .seq_show = memory_high_show,
6789 .write = memory_high_write,
6793 .flags = CFTYPE_NOT_ON_ROOT,
6794 .seq_show = memory_max_show,
6795 .write = memory_max_write,
6799 .flags = CFTYPE_NOT_ON_ROOT,
6800 .file_offset = offsetof(struct mem_cgroup, events_file),
6801 .seq_show = memory_events_show,
6804 .name = "events.local",
6805 .flags = CFTYPE_NOT_ON_ROOT,
6806 .file_offset = offsetof(struct mem_cgroup, events_local_file),
6807 .seq_show = memory_events_local_show,
6811 .seq_show = memory_stat_show,
6815 .name = "numa_stat",
6816 .seq_show = memory_numa_stat_show,
6820 .name = "oom.group",
6821 .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
6822 .seq_show = memory_oom_group_show,
6823 .write = memory_oom_group_write,
6827 .flags = CFTYPE_NS_DELEGATABLE,
6828 .write = memory_reclaim,
6833 struct cgroup_subsys memory_cgrp_subsys = {
6834 .css_alloc = mem_cgroup_css_alloc,
6835 .css_online = mem_cgroup_css_online,
6836 .css_offline = mem_cgroup_css_offline,
6837 .css_released = mem_cgroup_css_released,
6838 .css_free = mem_cgroup_css_free,
6839 .css_reset = mem_cgroup_css_reset,
6840 .css_rstat_flush = mem_cgroup_css_rstat_flush,
6841 .can_attach = mem_cgroup_can_attach,
6842 .attach = mem_cgroup_attach,
6843 .cancel_attach = mem_cgroup_cancel_attach,
6844 .post_attach = mem_cgroup_move_task,
6845 .dfl_cftypes = memory_files,
6846 .legacy_cftypes = mem_cgroup_legacy_files,
6851 * This function calculates an individual cgroup's effective
6852 * protection which is derived from its own memory.min/low, its
6853 * parent's and siblings' settings, as well as the actual memory
6854 * distribution in the tree.
6856 * The following rules apply to the effective protection values:
6858 * 1. At the first level of reclaim, effective protection is equal to
6859 * the declared protection in memory.min and memory.low.
6861 * 2. To enable safe delegation of the protection configuration, at
6862 * subsequent levels the effective protection is capped to the
6863 * parent's effective protection.
6865 * 3. To make complex and dynamic subtrees easier to configure, the
6866 * user is allowed to overcommit the declared protection at a given
6867 * level. If that is the case, the parent's effective protection is
6868 * distributed to the children in proportion to how much protection
6869 * they have declared and how much of it they are utilizing.
6871 * This makes distribution proportional, but also work-conserving:
6872 * if one cgroup claims much more protection than it uses memory,
6873 * the unused remainder is available to its siblings.
6875 * 4. Conversely, when the declared protection is undercommitted at a
6876 * given level, the distribution of the larger parental protection
6877 * budget is NOT proportional. A cgroup's protection from a sibling
6878 * is capped to its own memory.min/low setting.
6880 * 5. However, to allow protecting recursive subtrees from each other
6881 * without having to declare each individual cgroup's fixed share
6882 * of the ancestor's claim to protection, any unutilized -
6883 * "floating" - protection from up the tree is distributed in
6884 * proportion to each cgroup's *usage*. This makes the protection
6885 * neutral wrt sibling cgroups and lets them compete freely over
6886 * the shared parental protection budget, but it protects the
6887 * subtree as a whole from neighboring subtrees.
6889 * Note that 4. and 5. are not in conflict: 4. is about protecting
6890 * against immediate siblings whereas 5. is about protecting against
6891 * neighboring subtrees.
6893 static unsigned long effective_protection(unsigned long usage,
6894 unsigned long parent_usage,
6895 unsigned long setting,
6896 unsigned long parent_effective,
6897 unsigned long siblings_protected)
6899 unsigned long protected;
6902 protected = min(usage, setting);
6904 * If all cgroups at this level combined claim and use more
6905 * protection than what the parent affords them, distribute
6906 * shares in proportion to utilization.
6908 * We are using actual utilization rather than the statically
6909 * claimed protection in order to be work-conserving: claimed
6910 * but unused protection is available to siblings that would
6911 * otherwise get a smaller chunk than what they claimed.
6913 if (siblings_protected > parent_effective)
6914 return protected * parent_effective / siblings_protected;
6917 * Ok, utilized protection of all children is within what the
6918 * parent affords them, so we know whatever this child claims
6919 * and utilizes is effectively protected.
6921 * If there is unprotected usage beyond this value, reclaim
6922 * will apply pressure in proportion to that amount.
6924 * If there is unutilized protection, the cgroup will be fully
6925 * shielded from reclaim, but we do return a smaller value for
6926 * protection than what the group could enjoy in theory. This
6927 * is okay. With the overcommit distribution above, effective
6928 * protection is always dependent on how memory is actually
6929 * consumed among the siblings anyway.
6934 * If the children aren't claiming (all of) the protection
6935 * afforded to them by the parent, distribute the remainder in
6936 * proportion to the (unprotected) memory of each cgroup. That
6937 * way, cgroups that aren't explicitly prioritized wrt each
6938 * other compete freely over the allowance, but they are
6939 * collectively protected from neighboring trees.
6941 * We're using unprotected memory for the weight so that if
6942 * some cgroups DO claim explicit protection, we don't protect
6943 * the same bytes twice.
6945 * Check both usage and parent_usage against the respective
6946 * protected values. One should imply the other, but they
6947 * aren't read atomically - make sure the division is sane.
6949 if (!(cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT))
6951 if (parent_effective > siblings_protected &&
6952 parent_usage > siblings_protected &&
6953 usage > protected) {
6954 unsigned long unclaimed;
6956 unclaimed = parent_effective - siblings_protected;
6957 unclaimed *= usage - protected;
6958 unclaimed /= parent_usage - siblings_protected;
6967 * mem_cgroup_calculate_protection - check if memory consumption is in the normal range
6968 * @root: the top ancestor of the sub-tree being checked
6969 * @memcg: the memory cgroup to check
6971 * WARNING: This function is not stateless! It can only be used as part
6972 * of a top-down tree iteration, not for isolated queries.
6974 void mem_cgroup_calculate_protection(struct mem_cgroup *root,
6975 struct mem_cgroup *memcg)
6977 unsigned long usage, parent_usage;
6978 struct mem_cgroup *parent;
6980 if (mem_cgroup_disabled())
6984 root = root_mem_cgroup;
6987 * Effective values of the reclaim targets are ignored so they
6988 * can be stale. Have a look at mem_cgroup_protection for more
6990 * TODO: calculation should be more robust so that we do not need
6991 * that special casing.
6996 usage = page_counter_read(&memcg->memory);
7000 parent = parent_mem_cgroup(memcg);
7002 if (parent == root) {
7003 memcg->memory.emin = READ_ONCE(memcg->memory.min);
7004 memcg->memory.elow = READ_ONCE(memcg->memory.low);
7008 parent_usage = page_counter_read(&parent->memory);
7010 WRITE_ONCE(memcg->memory.emin, effective_protection(usage, parent_usage,
7011 READ_ONCE(memcg->memory.min),
7012 READ_ONCE(parent->memory.emin),
7013 atomic_long_read(&parent->memory.children_min_usage)));
7015 WRITE_ONCE(memcg->memory.elow, effective_protection(usage, parent_usage,
7016 READ_ONCE(memcg->memory.low),
7017 READ_ONCE(parent->memory.elow),
7018 atomic_long_read(&parent->memory.children_low_usage)));
7021 static int charge_memcg(struct folio *folio, struct mem_cgroup *memcg,
7024 long nr_pages = folio_nr_pages(folio);
7027 ret = try_charge(memcg, gfp, nr_pages);
7031 css_get(&memcg->css);
7032 commit_charge(folio, memcg);
7034 local_irq_disable();
7035 mem_cgroup_charge_statistics(memcg, nr_pages);
7036 memcg_check_events(memcg, folio_nid(folio));
7042 int __mem_cgroup_charge(struct folio *folio, struct mm_struct *mm, gfp_t gfp)
7044 struct mem_cgroup *memcg;
7047 memcg = get_mem_cgroup_from_mm(mm);
7048 ret = charge_memcg(folio, memcg, gfp);
7049 css_put(&memcg->css);
7055 * mem_cgroup_swapin_charge_folio - Charge a newly allocated folio for swapin.
7056 * @folio: folio to charge.
7057 * @mm: mm context of the victim
7058 * @gfp: reclaim mode
7059 * @entry: swap entry for which the folio is allocated
7061 * This function charges a folio allocated for swapin. Please call this before
7062 * adding the folio to the swapcache.
7064 * Returns 0 on success. Otherwise, an error code is returned.
7066 int mem_cgroup_swapin_charge_folio(struct folio *folio, struct mm_struct *mm,
7067 gfp_t gfp, swp_entry_t entry)
7069 struct mem_cgroup *memcg;
7073 if (mem_cgroup_disabled())
7076 id = lookup_swap_cgroup_id(entry);
7078 memcg = mem_cgroup_from_id(id);
7079 if (!memcg || !css_tryget_online(&memcg->css))
7080 memcg = get_mem_cgroup_from_mm(mm);
7083 ret = charge_memcg(folio, memcg, gfp);
7085 css_put(&memcg->css);
7090 * mem_cgroup_swapin_uncharge_swap - uncharge swap slot
7091 * @entry: swap entry for which the page is charged
7093 * Call this function after successfully adding the charged page to swapcache.
7095 * Note: This function assumes the page for which swap slot is being uncharged
7098 void mem_cgroup_swapin_uncharge_swap(swp_entry_t entry)
7101 * Cgroup1's unified memory+swap counter has been charged with the
7102 * new swapcache page, finish the transfer by uncharging the swap
7103 * slot. The swap slot would also get uncharged when it dies, but
7104 * it can stick around indefinitely and we'd count the page twice
7107 * Cgroup2 has separate resource counters for memory and swap,
7108 * so this is a non-issue here. Memory and swap charge lifetimes
7109 * correspond 1:1 to page and swap slot lifetimes: we charge the
7110 * page to memory here, and uncharge swap when the slot is freed.
7112 if (!mem_cgroup_disabled() && do_memsw_account()) {
7114 * The swap entry might not get freed for a long time,
7115 * let's not wait for it. The page already received a
7116 * memory+swap charge, drop the swap entry duplicate.
7118 mem_cgroup_uncharge_swap(entry, 1);
7122 struct uncharge_gather {
7123 struct mem_cgroup *memcg;
7124 unsigned long nr_memory;
7125 unsigned long pgpgout;
7126 unsigned long nr_kmem;
7130 static inline void uncharge_gather_clear(struct uncharge_gather *ug)
7132 memset(ug, 0, sizeof(*ug));
7135 static void uncharge_batch(const struct uncharge_gather *ug)
7137 unsigned long flags;
7139 if (ug->nr_memory) {
7140 page_counter_uncharge(&ug->memcg->memory, ug->nr_memory);
7141 if (do_memsw_account())
7142 page_counter_uncharge(&ug->memcg->memsw, ug->nr_memory);
7144 memcg_account_kmem(ug->memcg, -ug->nr_kmem);
7145 memcg_oom_recover(ug->memcg);
7148 local_irq_save(flags);
7149 __count_memcg_events(ug->memcg, PGPGOUT, ug->pgpgout);
7150 __this_cpu_add(ug->memcg->vmstats_percpu->nr_page_events, ug->nr_memory);
7151 memcg_check_events(ug->memcg, ug->nid);
7152 local_irq_restore(flags);
7154 /* drop reference from uncharge_folio */
7155 css_put(&ug->memcg->css);
7158 static void uncharge_folio(struct folio *folio, struct uncharge_gather *ug)
7161 struct mem_cgroup *memcg;
7162 struct obj_cgroup *objcg;
7164 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
7167 * Nobody should be changing or seriously looking at
7168 * folio memcg or objcg at this point, we have fully
7169 * exclusive access to the folio.
7171 if (folio_memcg_kmem(folio)) {
7172 objcg = __folio_objcg(folio);
7174 * This get matches the put at the end of the function and
7175 * kmem pages do not hold memcg references anymore.
7177 memcg = get_mem_cgroup_from_objcg(objcg);
7179 memcg = __folio_memcg(folio);
7185 if (ug->memcg != memcg) {
7188 uncharge_gather_clear(ug);
7191 ug->nid = folio_nid(folio);
7193 /* pairs with css_put in uncharge_batch */
7194 css_get(&memcg->css);
7197 nr_pages = folio_nr_pages(folio);
7199 if (folio_memcg_kmem(folio)) {
7200 ug->nr_memory += nr_pages;
7201 ug->nr_kmem += nr_pages;
7203 folio->memcg_data = 0;
7204 obj_cgroup_put(objcg);
7206 /* LRU pages aren't accounted at the root level */
7207 if (!mem_cgroup_is_root(memcg))
7208 ug->nr_memory += nr_pages;
7211 folio->memcg_data = 0;
7214 css_put(&memcg->css);
7217 void __mem_cgroup_uncharge(struct folio *folio)
7219 struct uncharge_gather ug;
7221 /* Don't touch folio->lru of any random page, pre-check: */
7222 if (!folio_memcg(folio))
7225 uncharge_gather_clear(&ug);
7226 uncharge_folio(folio, &ug);
7227 uncharge_batch(&ug);
7231 * __mem_cgroup_uncharge_list - uncharge a list of page
7232 * @page_list: list of pages to uncharge
7234 * Uncharge a list of pages previously charged with
7235 * __mem_cgroup_charge().
7237 void __mem_cgroup_uncharge_list(struct list_head *page_list)
7239 struct uncharge_gather ug;
7240 struct folio *folio;
7242 uncharge_gather_clear(&ug);
7243 list_for_each_entry(folio, page_list, lru)
7244 uncharge_folio(folio, &ug);
7246 uncharge_batch(&ug);
7250 * mem_cgroup_migrate - Charge a folio's replacement.
7251 * @old: Currently circulating folio.
7252 * @new: Replacement folio.
7254 * Charge @new as a replacement folio for @old. @old will
7255 * be uncharged upon free.
7257 * Both folios must be locked, @new->mapping must be set up.
7259 void mem_cgroup_migrate(struct folio *old, struct folio *new)
7261 struct mem_cgroup *memcg;
7262 long nr_pages = folio_nr_pages(new);
7263 unsigned long flags;
7265 VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
7266 VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
7267 VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
7268 VM_BUG_ON_FOLIO(folio_nr_pages(old) != nr_pages, new);
7270 if (mem_cgroup_disabled())
7273 /* Page cache replacement: new folio already charged? */
7274 if (folio_memcg(new))
7277 memcg = folio_memcg(old);
7278 VM_WARN_ON_ONCE_FOLIO(!memcg, old);
7282 /* Force-charge the new page. The old one will be freed soon */
7283 if (!mem_cgroup_is_root(memcg)) {
7284 page_counter_charge(&memcg->memory, nr_pages);
7285 if (do_memsw_account())
7286 page_counter_charge(&memcg->memsw, nr_pages);
7289 css_get(&memcg->css);
7290 commit_charge(new, memcg);
7292 local_irq_save(flags);
7293 mem_cgroup_charge_statistics(memcg, nr_pages);
7294 memcg_check_events(memcg, folio_nid(new));
7295 local_irq_restore(flags);
7298 DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
7299 EXPORT_SYMBOL(memcg_sockets_enabled_key);
7301 void mem_cgroup_sk_alloc(struct sock *sk)
7303 struct mem_cgroup *memcg;
7305 if (!mem_cgroup_sockets_enabled)
7308 /* Do not associate the sock with unrelated interrupted task's memcg. */
7313 memcg = mem_cgroup_from_task(current);
7314 if (mem_cgroup_is_root(memcg))
7316 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg->tcpmem_active)
7318 if (css_tryget(&memcg->css))
7319 sk->sk_memcg = memcg;
7324 void mem_cgroup_sk_free(struct sock *sk)
7327 css_put(&sk->sk_memcg->css);
7331 * mem_cgroup_charge_skmem - charge socket memory
7332 * @memcg: memcg to charge
7333 * @nr_pages: number of pages to charge
7334 * @gfp_mask: reclaim mode
7336 * Charges @nr_pages to @memcg. Returns %true if the charge fit within
7337 * @memcg's configured limit, %false if it doesn't.
7339 bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages,
7342 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
7343 struct page_counter *fail;
7345 if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) {
7346 memcg->tcpmem_pressure = 0;
7349 memcg->tcpmem_pressure = 1;
7350 if (gfp_mask & __GFP_NOFAIL) {
7351 page_counter_charge(&memcg->tcpmem, nr_pages);
7357 if (try_charge(memcg, gfp_mask, nr_pages) == 0) {
7358 mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
7366 * mem_cgroup_uncharge_skmem - uncharge socket memory
7367 * @memcg: memcg to uncharge
7368 * @nr_pages: number of pages to uncharge
7370 void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
7372 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
7373 page_counter_uncharge(&memcg->tcpmem, nr_pages);
7377 mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
7379 refill_stock(memcg, nr_pages);
7382 static int __init cgroup_memory(char *s)
7386 while ((token = strsep(&s, ",")) != NULL) {
7389 if (!strcmp(token, "nosocket"))
7390 cgroup_memory_nosocket = true;
7391 if (!strcmp(token, "nokmem"))
7392 cgroup_memory_nokmem = true;
7393 if (!strcmp(token, "nobpf"))
7394 cgroup_memory_nobpf = true;
7398 __setup("cgroup.memory=", cgroup_memory);
7401 * subsys_initcall() for memory controller.
7403 * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
7404 * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
7405 * basically everything that doesn't depend on a specific mem_cgroup structure
7406 * should be initialized from here.
7408 static int __init mem_cgroup_init(void)
7413 * Currently s32 type (can refer to struct batched_lruvec_stat) is
7414 * used for per-memcg-per-cpu caching of per-node statistics. In order
7415 * to work fine, we should make sure that the overfill threshold can't
7416 * exceed S32_MAX / PAGE_SIZE.
7418 BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE);
7420 cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
7421 memcg_hotplug_cpu_dead);
7423 for_each_possible_cpu(cpu)
7424 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
7427 for_each_node(node) {
7428 struct mem_cgroup_tree_per_node *rtpn;
7430 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, node);
7432 rtpn->rb_root = RB_ROOT;
7433 rtpn->rb_rightmost = NULL;
7434 spin_lock_init(&rtpn->lock);
7435 soft_limit_tree.rb_tree_per_node[node] = rtpn;
7440 subsys_initcall(mem_cgroup_init);
7443 static struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
7445 while (!refcount_inc_not_zero(&memcg->id.ref)) {
7447 * The root cgroup cannot be destroyed, so it's refcount must
7450 if (WARN_ON_ONCE(mem_cgroup_is_root(memcg))) {
7454 memcg = parent_mem_cgroup(memcg);
7456 memcg = root_mem_cgroup;
7462 * mem_cgroup_swapout - transfer a memsw charge to swap
7463 * @folio: folio whose memsw charge to transfer
7464 * @entry: swap entry to move the charge to
7466 * Transfer the memsw charge of @folio to @entry.
7468 void mem_cgroup_swapout(struct folio *folio, swp_entry_t entry)
7470 struct mem_cgroup *memcg, *swap_memcg;
7471 unsigned int nr_entries;
7472 unsigned short oldid;
7474 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
7475 VM_BUG_ON_FOLIO(folio_ref_count(folio), folio);
7477 if (mem_cgroup_disabled())
7480 if (!do_memsw_account())
7483 memcg = folio_memcg(folio);
7485 VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
7490 * In case the memcg owning these pages has been offlined and doesn't
7491 * have an ID allocated to it anymore, charge the closest online
7492 * ancestor for the swap instead and transfer the memory+swap charge.
7494 swap_memcg = mem_cgroup_id_get_online(memcg);
7495 nr_entries = folio_nr_pages(folio);
7496 /* Get references for the tail pages, too */
7498 mem_cgroup_id_get_many(swap_memcg, nr_entries - 1);
7499 oldid = swap_cgroup_record(entry, mem_cgroup_id(swap_memcg),
7501 VM_BUG_ON_FOLIO(oldid, folio);
7502 mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries);
7504 folio->memcg_data = 0;
7506 if (!mem_cgroup_is_root(memcg))
7507 page_counter_uncharge(&memcg->memory, nr_entries);
7509 if (memcg != swap_memcg) {
7510 if (!mem_cgroup_is_root(swap_memcg))
7511 page_counter_charge(&swap_memcg->memsw, nr_entries);
7512 page_counter_uncharge(&memcg->memsw, nr_entries);
7516 * Interrupts should be disabled here because the caller holds the
7517 * i_pages lock which is taken with interrupts-off. It is
7518 * important here to have the interrupts disabled because it is the
7519 * only synchronisation we have for updating the per-CPU variables.
7522 mem_cgroup_charge_statistics(memcg, -nr_entries);
7523 memcg_stats_unlock();
7524 memcg_check_events(memcg, folio_nid(folio));
7526 css_put(&memcg->css);
7530 * __mem_cgroup_try_charge_swap - try charging swap space for a folio
7531 * @folio: folio being added to swap
7532 * @entry: swap entry to charge
7534 * Try to charge @folio's memcg for the swap space at @entry.
7536 * Returns 0 on success, -ENOMEM on failure.
7538 int __mem_cgroup_try_charge_swap(struct folio *folio, swp_entry_t entry)
7540 unsigned int nr_pages = folio_nr_pages(folio);
7541 struct page_counter *counter;
7542 struct mem_cgroup *memcg;
7543 unsigned short oldid;
7545 if (do_memsw_account())
7548 memcg = folio_memcg(folio);
7550 VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
7555 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7559 memcg = mem_cgroup_id_get_online(memcg);
7561 if (!mem_cgroup_is_root(memcg) &&
7562 !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
7563 memcg_memory_event(memcg, MEMCG_SWAP_MAX);
7564 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7565 mem_cgroup_id_put(memcg);
7569 /* Get references for the tail pages, too */
7571 mem_cgroup_id_get_many(memcg, nr_pages - 1);
7572 oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg), nr_pages);
7573 VM_BUG_ON_FOLIO(oldid, folio);
7574 mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
7580 * __mem_cgroup_uncharge_swap - uncharge swap space
7581 * @entry: swap entry to uncharge
7582 * @nr_pages: the amount of swap space to uncharge
7584 void __mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
7586 struct mem_cgroup *memcg;
7589 id = swap_cgroup_record(entry, 0, nr_pages);
7591 memcg = mem_cgroup_from_id(id);
7593 if (!mem_cgroup_is_root(memcg)) {
7594 if (do_memsw_account())
7595 page_counter_uncharge(&memcg->memsw, nr_pages);
7597 page_counter_uncharge(&memcg->swap, nr_pages);
7599 mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
7600 mem_cgroup_id_put_many(memcg, nr_pages);
7605 long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
7607 long nr_swap_pages = get_nr_swap_pages();
7609 if (mem_cgroup_disabled() || do_memsw_account())
7610 return nr_swap_pages;
7611 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg))
7612 nr_swap_pages = min_t(long, nr_swap_pages,
7613 READ_ONCE(memcg->swap.max) -
7614 page_counter_read(&memcg->swap));
7615 return nr_swap_pages;
7618 bool mem_cgroup_swap_full(struct folio *folio)
7620 struct mem_cgroup *memcg;
7622 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
7626 if (do_memsw_account())
7629 memcg = folio_memcg(folio);
7633 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
7634 unsigned long usage = page_counter_read(&memcg->swap);
7636 if (usage * 2 >= READ_ONCE(memcg->swap.high) ||
7637 usage * 2 >= READ_ONCE(memcg->swap.max))
7644 static int __init setup_swap_account(char *s)
7646 pr_warn_once("The swapaccount= commandline option is deprecated. "
7647 "Please report your usecase to linux-mm@kvack.org if you "
7648 "depend on this functionality.\n");
7651 __setup("swapaccount=", setup_swap_account);
7653 static u64 swap_current_read(struct cgroup_subsys_state *css,
7656 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7658 return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
7661 static u64 swap_peak_read(struct cgroup_subsys_state *css,
7664 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7666 return (u64)memcg->swap.watermark * PAGE_SIZE;
7669 static int swap_high_show(struct seq_file *m, void *v)
7671 return seq_puts_memcg_tunable(m,
7672 READ_ONCE(mem_cgroup_from_seq(m)->swap.high));
7675 static ssize_t swap_high_write(struct kernfs_open_file *of,
7676 char *buf, size_t nbytes, loff_t off)
7678 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7682 buf = strstrip(buf);
7683 err = page_counter_memparse(buf, "max", &high);
7687 page_counter_set_high(&memcg->swap, high);
7692 static int swap_max_show(struct seq_file *m, void *v)
7694 return seq_puts_memcg_tunable(m,
7695 READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
7698 static ssize_t swap_max_write(struct kernfs_open_file *of,
7699 char *buf, size_t nbytes, loff_t off)
7701 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7705 buf = strstrip(buf);
7706 err = page_counter_memparse(buf, "max", &max);
7710 xchg(&memcg->swap.max, max);
7715 static int swap_events_show(struct seq_file *m, void *v)
7717 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
7719 seq_printf(m, "high %lu\n",
7720 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH]));
7721 seq_printf(m, "max %lu\n",
7722 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
7723 seq_printf(m, "fail %lu\n",
7724 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
7729 static struct cftype swap_files[] = {
7731 .name = "swap.current",
7732 .flags = CFTYPE_NOT_ON_ROOT,
7733 .read_u64 = swap_current_read,
7736 .name = "swap.high",
7737 .flags = CFTYPE_NOT_ON_ROOT,
7738 .seq_show = swap_high_show,
7739 .write = swap_high_write,
7743 .flags = CFTYPE_NOT_ON_ROOT,
7744 .seq_show = swap_max_show,
7745 .write = swap_max_write,
7748 .name = "swap.peak",
7749 .flags = CFTYPE_NOT_ON_ROOT,
7750 .read_u64 = swap_peak_read,
7753 .name = "swap.events",
7754 .flags = CFTYPE_NOT_ON_ROOT,
7755 .file_offset = offsetof(struct mem_cgroup, swap_events_file),
7756 .seq_show = swap_events_show,
7761 static struct cftype memsw_files[] = {
7763 .name = "memsw.usage_in_bytes",
7764 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
7765 .read_u64 = mem_cgroup_read_u64,
7768 .name = "memsw.max_usage_in_bytes",
7769 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
7770 .write = mem_cgroup_reset,
7771 .read_u64 = mem_cgroup_read_u64,
7774 .name = "memsw.limit_in_bytes",
7775 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
7776 .write = mem_cgroup_write,
7777 .read_u64 = mem_cgroup_read_u64,
7780 .name = "memsw.failcnt",
7781 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
7782 .write = mem_cgroup_reset,
7783 .read_u64 = mem_cgroup_read_u64,
7785 #if defined(CONFIG_MEMCG) && defined(CONFIG_SWAP)
7787 .name = "force_reclaim",
7788 .write_u64 = mem_cgroup_force_reclaim,
7791 { }, /* terminate */
7794 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
7796 * obj_cgroup_may_zswap - check if this cgroup can zswap
7797 * @objcg: the object cgroup
7799 * Check if the hierarchical zswap limit has been reached.
7801 * This doesn't check for specific headroom, and it is not atomic
7802 * either. But with zswap, the size of the allocation is only known
7803 * once compression has occured, and this optimistic pre-check avoids
7804 * spending cycles on compression when there is already no room left
7805 * or zswap is disabled altogether somewhere in the hierarchy.
7807 bool obj_cgroup_may_zswap(struct obj_cgroup *objcg)
7809 struct mem_cgroup *memcg, *original_memcg;
7812 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
7815 original_memcg = get_mem_cgroup_from_objcg(objcg);
7816 for (memcg = original_memcg; !mem_cgroup_is_root(memcg);
7817 memcg = parent_mem_cgroup(memcg)) {
7818 unsigned long max = READ_ONCE(memcg->zswap_max);
7819 unsigned long pages;
7821 if (max == PAGE_COUNTER_MAX)
7828 cgroup_rstat_flush(memcg->css.cgroup);
7829 pages = memcg_page_state(memcg, MEMCG_ZSWAP_B) / PAGE_SIZE;
7835 mem_cgroup_put(original_memcg);
7840 * obj_cgroup_charge_zswap - charge compression backend memory
7841 * @objcg: the object cgroup
7842 * @size: size of compressed object
7844 * This forces the charge after obj_cgroup_may_zswap() allowed
7845 * compression and storage in zwap for this cgroup to go ahead.
7847 void obj_cgroup_charge_zswap(struct obj_cgroup *objcg, size_t size)
7849 struct mem_cgroup *memcg;
7851 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
7854 VM_WARN_ON_ONCE(!(current->flags & PF_MEMALLOC));
7856 /* PF_MEMALLOC context, charging must succeed */
7857 if (obj_cgroup_charge(objcg, GFP_KERNEL, size))
7861 memcg = obj_cgroup_memcg(objcg);
7862 mod_memcg_state(memcg, MEMCG_ZSWAP_B, size);
7863 mod_memcg_state(memcg, MEMCG_ZSWAPPED, 1);
7868 * obj_cgroup_uncharge_zswap - uncharge compression backend memory
7869 * @objcg: the object cgroup
7870 * @size: size of compressed object
7872 * Uncharges zswap memory on page in.
7874 void obj_cgroup_uncharge_zswap(struct obj_cgroup *objcg, size_t size)
7876 struct mem_cgroup *memcg;
7878 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
7881 obj_cgroup_uncharge(objcg, size);
7884 memcg = obj_cgroup_memcg(objcg);
7885 mod_memcg_state(memcg, MEMCG_ZSWAP_B, -size);
7886 mod_memcg_state(memcg, MEMCG_ZSWAPPED, -1);
7890 static u64 zswap_current_read(struct cgroup_subsys_state *css,
7893 cgroup_rstat_flush(css->cgroup);
7894 return memcg_page_state(mem_cgroup_from_css(css), MEMCG_ZSWAP_B);
7897 static int zswap_max_show(struct seq_file *m, void *v)
7899 return seq_puts_memcg_tunable(m,
7900 READ_ONCE(mem_cgroup_from_seq(m)->zswap_max));
7903 static ssize_t zswap_max_write(struct kernfs_open_file *of,
7904 char *buf, size_t nbytes, loff_t off)
7906 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7910 buf = strstrip(buf);
7911 err = page_counter_memparse(buf, "max", &max);
7915 xchg(&memcg->zswap_max, max);
7920 static struct cftype zswap_files[] = {
7922 .name = "zswap.current",
7923 .flags = CFTYPE_NOT_ON_ROOT,
7924 .read_u64 = zswap_current_read,
7927 .name = "zswap.max",
7928 .flags = CFTYPE_NOT_ON_ROOT,
7929 .seq_show = zswap_max_show,
7930 .write = zswap_max_write,
7934 #endif /* CONFIG_MEMCG_KMEM && CONFIG_ZSWAP */
7936 static int __init mem_cgroup_swap_init(void)
7938 if (mem_cgroup_disabled())
7941 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files));
7942 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files));
7943 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
7944 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, zswap_files));
7948 subsys_initcall(mem_cgroup_swap_init);
7950 #endif /* CONFIG_SWAP */