1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* memcontrol.c - Memory Controller
4 * Copyright IBM Corporation, 2007
5 * Author Balbir Singh <balbir@linux.vnet.ibm.com>
7 * Copyright 2007 OpenVZ SWsoft Inc
8 * Author: Pavel Emelianov <xemul@openvz.org>
11 * Copyright (C) 2009 Nokia Corporation
12 * Author: Kirill A. Shutemov
14 * Kernel Memory Controller
15 * Copyright (C) 2012 Parallels Inc. and Google Inc.
16 * Authors: Glauber Costa and Suleiman Souhlal
19 * Charge lifetime sanitation
20 * Lockless page tracking & accounting
21 * Unified hierarchy configuration model
22 * Copyright (C) 2015 Red Hat, Inc., Johannes Weiner
24 * Per memcg lru locking
25 * Copyright (C) 2020 Alibaba, Inc, Alex Shi
28 #include <linux/page_counter.h>
29 #include <linux/memcontrol.h>
30 #include <linux/cgroup.h>
31 #include <linux/pagewalk.h>
32 #include <linux/sched/mm.h>
33 #include <linux/shmem_fs.h>
34 #include <linux/hugetlb.h>
35 #include <linux/pagemap.h>
36 #include <linux/vm_event_item.h>
37 #include <linux/smp.h>
38 #include <linux/page-flags.h>
39 #include <linux/backing-dev.h>
40 #include <linux/bit_spinlock.h>
41 #include <linux/rcupdate.h>
42 #include <linux/limits.h>
43 #include <linux/export.h>
44 #include <linux/mutex.h>
45 #include <linux/rbtree.h>
46 #include <linux/slab.h>
47 #include <linux/swap.h>
48 #include <linux/swapops.h>
49 #include <linux/spinlock.h>
50 #include <linux/eventfd.h>
51 #include <linux/poll.h>
52 #include <linux/sort.h>
54 #include <linux/seq_file.h>
55 #include <linux/vmpressure.h>
56 #include <linux/memremap.h>
57 #include <linux/mm_inline.h>
58 #include <linux/swap_cgroup.h>
59 #include <linux/cpu.h>
60 #include <linux/oom.h>
61 #include <linux/lockdep.h>
62 #include <linux/file.h>
63 #include <linux/resume_user_mode.h>
64 #include <linux/psi.h>
65 #include <linux/seq_buf.h>
66 #include <linux/sched/isolation.h>
73 #include <linux/uaccess.h>
75 #include <trace/events/vmscan.h>
77 struct cgroup_subsys memory_cgrp_subsys __read_mostly;
78 EXPORT_SYMBOL(memory_cgrp_subsys);
80 struct mem_cgroup *root_mem_cgroup __read_mostly;
82 /* Active memory cgroup to use from an interrupt context */
83 DEFINE_PER_CPU(struct mem_cgroup *, int_active_memcg);
84 EXPORT_PER_CPU_SYMBOL_GPL(int_active_memcg);
86 /* Socket memory accounting disabled? */
87 static bool cgroup_memory_nosocket __ro_after_init;
89 /* Kernel memory accounting disabled? */
90 static bool cgroup_memory_nokmem __ro_after_init;
92 /* BPF memory accounting disabled? */
93 static bool cgroup_memory_nobpf __ro_after_init;
95 #ifdef CONFIG_CGROUP_WRITEBACK
96 static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq);
99 /* Whether legacy memory+swap accounting is active */
100 static bool do_memsw_account(void)
102 return !cgroup_subsys_on_dfl(memory_cgrp_subsys);
105 #define THRESHOLDS_EVENTS_TARGET 128
106 #define SOFTLIMIT_EVENTS_TARGET 1024
109 * Cgroups above their limits are maintained in a RB-Tree, independent of
110 * their hierarchy representation
113 struct mem_cgroup_tree_per_node {
114 struct rb_root rb_root;
115 struct rb_node *rb_rightmost;
119 struct mem_cgroup_tree {
120 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
123 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
126 struct mem_cgroup_eventfd_list {
127 struct list_head list;
128 struct eventfd_ctx *eventfd;
132 * cgroup_event represents events which userspace want to receive.
134 struct mem_cgroup_event {
136 * memcg which the event belongs to.
138 struct mem_cgroup *memcg;
140 * eventfd to signal userspace about the event.
142 struct eventfd_ctx *eventfd;
144 * Each of these stored in a list by the cgroup.
146 struct list_head list;
148 * register_event() callback will be used to add new userspace
149 * waiter for changes related to this event. Use eventfd_signal()
150 * on eventfd to send notification to userspace.
152 int (*register_event)(struct mem_cgroup *memcg,
153 struct eventfd_ctx *eventfd, const char *args);
155 * unregister_event() callback will be called when userspace closes
156 * the eventfd or on cgroup removing. This callback must be set,
157 * if you want provide notification functionality.
159 void (*unregister_event)(struct mem_cgroup *memcg,
160 struct eventfd_ctx *eventfd);
162 * All fields below needed to unregister event when
163 * userspace closes eventfd.
166 wait_queue_head_t *wqh;
167 wait_queue_entry_t wait;
168 struct work_struct remove;
171 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
172 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
174 /* Stuffs for move charges at task migration. */
176 * Types of charges to be moved.
178 #define MOVE_ANON 0x1U
179 #define MOVE_FILE 0x2U
180 #define MOVE_MASK (MOVE_ANON | MOVE_FILE)
182 /* "mc" and its members are protected by cgroup_mutex */
183 static struct move_charge_struct {
184 spinlock_t lock; /* for from, to */
185 struct mm_struct *mm;
186 struct mem_cgroup *from;
187 struct mem_cgroup *to;
189 unsigned long precharge;
190 unsigned long moved_charge;
191 unsigned long moved_swap;
192 struct task_struct *moving_task; /* a task moving charges */
193 wait_queue_head_t waitq; /* a waitq for other context */
195 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
196 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
200 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
201 * limit reclaim to prevent infinite loops, if they ever occur.
203 #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
204 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
206 /* for encoding cft->private value on file */
214 #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
215 #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
216 #define MEMFILE_ATTR(val) ((val) & 0xffff)
219 * Iteration constructs for visiting all cgroups (under a tree). If
220 * loops are exited prematurely (break), mem_cgroup_iter_break() must
221 * be used for reference counting.
223 #define for_each_mem_cgroup_tree(iter, root) \
224 for (iter = mem_cgroup_iter(root, NULL, NULL); \
226 iter = mem_cgroup_iter(root, iter, NULL))
228 #define for_each_mem_cgroup(iter) \
229 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
231 iter = mem_cgroup_iter(NULL, iter, NULL))
233 static inline bool task_is_dying(void)
235 return tsk_is_oom_victim(current) || fatal_signal_pending(current) ||
236 (current->flags & PF_EXITING);
239 /* Some nice accessors for the vmpressure. */
240 struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
243 memcg = root_mem_cgroup;
244 return &memcg->vmpressure;
247 struct mem_cgroup *vmpressure_to_memcg(struct vmpressure *vmpr)
249 return container_of(vmpr, struct mem_cgroup, vmpressure);
252 #ifdef CONFIG_MEMCG_KMEM
253 static DEFINE_SPINLOCK(objcg_lock);
255 bool mem_cgroup_kmem_disabled(void)
257 return cgroup_memory_nokmem;
260 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
261 unsigned int nr_pages);
263 static void obj_cgroup_release(struct percpu_ref *ref)
265 struct obj_cgroup *objcg = container_of(ref, struct obj_cgroup, refcnt);
266 unsigned int nr_bytes;
267 unsigned int nr_pages;
271 * At this point all allocated objects are freed, and
272 * objcg->nr_charged_bytes can't have an arbitrary byte value.
273 * However, it can be PAGE_SIZE or (x * PAGE_SIZE).
275 * The following sequence can lead to it:
276 * 1) CPU0: objcg == stock->cached_objcg
277 * 2) CPU1: we do a small allocation (e.g. 92 bytes),
278 * PAGE_SIZE bytes are charged
279 * 3) CPU1: a process from another memcg is allocating something,
280 * the stock if flushed,
281 * objcg->nr_charged_bytes = PAGE_SIZE - 92
282 * 5) CPU0: we do release this object,
283 * 92 bytes are added to stock->nr_bytes
284 * 6) CPU0: stock is flushed,
285 * 92 bytes are added to objcg->nr_charged_bytes
287 * In the result, nr_charged_bytes == PAGE_SIZE.
288 * This page will be uncharged in obj_cgroup_release().
290 nr_bytes = atomic_read(&objcg->nr_charged_bytes);
291 WARN_ON_ONCE(nr_bytes & (PAGE_SIZE - 1));
292 nr_pages = nr_bytes >> PAGE_SHIFT;
295 obj_cgroup_uncharge_pages(objcg, nr_pages);
297 spin_lock_irqsave(&objcg_lock, flags);
298 list_del(&objcg->list);
299 spin_unlock_irqrestore(&objcg_lock, flags);
301 percpu_ref_exit(ref);
302 kfree_rcu(objcg, rcu);
305 static struct obj_cgroup *obj_cgroup_alloc(void)
307 struct obj_cgroup *objcg;
310 objcg = kzalloc(sizeof(struct obj_cgroup), GFP_KERNEL);
314 ret = percpu_ref_init(&objcg->refcnt, obj_cgroup_release, 0,
320 INIT_LIST_HEAD(&objcg->list);
324 static void memcg_reparent_objcgs(struct mem_cgroup *memcg,
325 struct mem_cgroup *parent)
327 struct obj_cgroup *objcg, *iter;
329 objcg = rcu_replace_pointer(memcg->objcg, NULL, true);
331 spin_lock_irq(&objcg_lock);
333 /* 1) Ready to reparent active objcg. */
334 list_add(&objcg->list, &memcg->objcg_list);
335 /* 2) Reparent active objcg and already reparented objcgs to parent. */
336 list_for_each_entry(iter, &memcg->objcg_list, list)
337 WRITE_ONCE(iter->memcg, parent);
338 /* 3) Move already reparented objcgs to the parent's list */
339 list_splice(&memcg->objcg_list, &parent->objcg_list);
341 spin_unlock_irq(&objcg_lock);
343 percpu_ref_kill(&objcg->refcnt);
347 * A lot of the calls to the cache allocation functions are expected to be
348 * inlined by the compiler. Since the calls to memcg_slab_pre_alloc_hook() are
349 * conditional to this static branch, we'll have to allow modules that does
350 * kmem_cache_alloc and the such to see this symbol as well
352 DEFINE_STATIC_KEY_FALSE(memcg_kmem_online_key);
353 EXPORT_SYMBOL(memcg_kmem_online_key);
355 DEFINE_STATIC_KEY_FALSE(memcg_bpf_enabled_key);
356 EXPORT_SYMBOL(memcg_bpf_enabled_key);
360 * mem_cgroup_css_from_folio - css of the memcg associated with a folio
361 * @folio: folio of interest
363 * If memcg is bound to the default hierarchy, css of the memcg associated
364 * with @folio is returned. The returned css remains associated with @folio
365 * until it is released.
367 * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
370 struct cgroup_subsys_state *mem_cgroup_css_from_folio(struct folio *folio)
372 struct mem_cgroup *memcg = folio_memcg(folio);
374 if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
375 memcg = root_mem_cgroup;
381 * page_cgroup_ino - return inode number of the memcg a page is charged to
384 * Look up the closest online ancestor of the memory cgroup @page is charged to
385 * and return its inode number or 0 if @page is not charged to any cgroup. It
386 * is safe to call this function without holding a reference to @page.
388 * Note, this function is inherently racy, because there is nothing to prevent
389 * the cgroup inode from getting torn down and potentially reallocated a moment
390 * after page_cgroup_ino() returns, so it only should be used by callers that
391 * do not care (such as procfs interfaces).
393 ino_t page_cgroup_ino(struct page *page)
395 struct mem_cgroup *memcg;
396 unsigned long ino = 0;
399 /* page_folio() is racy here, but the entire function is racy anyway */
400 memcg = folio_memcg_check(page_folio(page));
402 while (memcg && !(memcg->css.flags & CSS_ONLINE))
403 memcg = parent_mem_cgroup(memcg);
405 ino = cgroup_ino(memcg->css.cgroup);
410 static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_node *mz,
411 struct mem_cgroup_tree_per_node *mctz,
412 unsigned long new_usage_in_excess)
414 struct rb_node **p = &mctz->rb_root.rb_node;
415 struct rb_node *parent = NULL;
416 struct mem_cgroup_per_node *mz_node;
417 bool rightmost = true;
422 mz->usage_in_excess = new_usage_in_excess;
423 if (!mz->usage_in_excess)
427 mz_node = rb_entry(parent, struct mem_cgroup_per_node,
429 if (mz->usage_in_excess < mz_node->usage_in_excess) {
438 mctz->rb_rightmost = &mz->tree_node;
440 rb_link_node(&mz->tree_node, parent, p);
441 rb_insert_color(&mz->tree_node, &mctz->rb_root);
445 static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
446 struct mem_cgroup_tree_per_node *mctz)
451 if (&mz->tree_node == mctz->rb_rightmost)
452 mctz->rb_rightmost = rb_prev(&mz->tree_node);
454 rb_erase(&mz->tree_node, &mctz->rb_root);
458 static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
459 struct mem_cgroup_tree_per_node *mctz)
463 spin_lock_irqsave(&mctz->lock, flags);
464 __mem_cgroup_remove_exceeded(mz, mctz);
465 spin_unlock_irqrestore(&mctz->lock, flags);
468 static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
470 unsigned long nr_pages = page_counter_read(&memcg->memory);
471 unsigned long soft_limit = READ_ONCE(memcg->soft_limit);
472 unsigned long excess = 0;
474 if (nr_pages > soft_limit)
475 excess = nr_pages - soft_limit;
480 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, int nid)
482 unsigned long excess;
483 struct mem_cgroup_per_node *mz;
484 struct mem_cgroup_tree_per_node *mctz;
486 if (lru_gen_enabled()) {
487 if (soft_limit_excess(memcg))
488 lru_gen_soft_reclaim(memcg, 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 /* Pending child counts during tree propagation */
746 long state_pending[MEMCG_NR_STAT];
747 unsigned long events_pending[NR_MEMCG_EVENTS];
750 unsigned long memcg_page_state(struct mem_cgroup *memcg, int idx)
752 long x = READ_ONCE(memcg->vmstats->state[idx]);
761 * __mod_memcg_state - update cgroup memory statistics
762 * @memcg: the memory cgroup
763 * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item
764 * @val: delta to add to the counter, can be negative
766 void __mod_memcg_state(struct mem_cgroup *memcg, int idx, int val)
768 if (mem_cgroup_disabled())
771 __this_cpu_add(memcg->vmstats_percpu->state[idx], val);
772 memcg_rstat_updated(memcg, val);
775 /* idx can be of type enum memcg_stat_item or node_stat_item. */
776 static unsigned long memcg_page_state_local(struct mem_cgroup *memcg, int idx)
781 for_each_possible_cpu(cpu)
782 x += per_cpu(memcg->vmstats_percpu->state[idx], cpu);
790 void __mod_memcg_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
793 struct mem_cgroup_per_node *pn;
794 struct mem_cgroup *memcg;
796 pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
800 * The caller from rmap relay on disabled preemption becase they never
801 * update their counter from in-interrupt context. For these two
802 * counters we check that the update is never performed from an
803 * interrupt context while other caller need to have disabled interrupt.
805 __memcg_stats_lock();
806 if (IS_ENABLED(CONFIG_DEBUG_VM)) {
811 case NR_SHMEM_PMDMAPPED:
812 case NR_FILE_PMDMAPPED:
813 WARN_ON_ONCE(!in_task());
816 VM_WARN_ON_IRQS_ENABLED();
821 __this_cpu_add(memcg->vmstats_percpu->state[idx], val);
824 __this_cpu_add(pn->lruvec_stats_percpu->state[idx], val);
826 memcg_rstat_updated(memcg, val);
827 memcg_stats_unlock();
831 * __mod_lruvec_state - update lruvec memory statistics
832 * @lruvec: the lruvec
833 * @idx: the stat item
834 * @val: delta to add to the counter, can be negative
836 * The lruvec is the intersection of the NUMA node and a cgroup. This
837 * function updates the all three counters that are affected by a
838 * change of state at this level: per-node, per-cgroup, per-lruvec.
840 void __mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
844 __mod_node_page_state(lruvec_pgdat(lruvec), idx, val);
846 /* Update memcg and lruvec */
847 if (!mem_cgroup_disabled())
848 __mod_memcg_lruvec_state(lruvec, idx, val);
851 void __mod_lruvec_page_state(struct page *page, enum node_stat_item idx,
854 struct page *head = compound_head(page); /* rmap on tail pages */
855 struct mem_cgroup *memcg;
856 pg_data_t *pgdat = page_pgdat(page);
857 struct lruvec *lruvec;
860 memcg = page_memcg(head);
861 /* Untracked pages have no memcg, no lruvec. Update only the node */
864 __mod_node_page_state(pgdat, idx, val);
868 lruvec = mem_cgroup_lruvec(memcg, pgdat);
869 __mod_lruvec_state(lruvec, idx, val);
872 EXPORT_SYMBOL(__mod_lruvec_page_state);
874 void __mod_lruvec_kmem_state(void *p, enum node_stat_item idx, int val)
876 pg_data_t *pgdat = page_pgdat(virt_to_page(p));
877 struct mem_cgroup *memcg;
878 struct lruvec *lruvec;
881 memcg = mem_cgroup_from_slab_obj(p);
884 * Untracked pages have no memcg, no lruvec. Update only the
885 * node. If we reparent the slab objects to the root memcg,
886 * when we free the slab object, we need to update the per-memcg
887 * vmstats to keep it correct for the root memcg.
890 __mod_node_page_state(pgdat, idx, val);
892 lruvec = mem_cgroup_lruvec(memcg, pgdat);
893 __mod_lruvec_state(lruvec, idx, val);
899 * __count_memcg_events - account VM events in a cgroup
900 * @memcg: the memory cgroup
901 * @idx: the event item
902 * @count: the number of events that occurred
904 void __count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx,
907 int index = memcg_events_index(idx);
909 if (mem_cgroup_disabled() || index < 0)
913 __this_cpu_add(memcg->vmstats_percpu->events[index], count);
914 memcg_rstat_updated(memcg, count);
915 memcg_stats_unlock();
918 static unsigned long memcg_events(struct mem_cgroup *memcg, int event)
920 int index = memcg_events_index(event);
924 return READ_ONCE(memcg->vmstats->events[index]);
927 static unsigned long memcg_events_local(struct mem_cgroup *memcg, int event)
931 int index = memcg_events_index(event);
936 for_each_possible_cpu(cpu)
937 x += per_cpu(memcg->vmstats_percpu->events[index], cpu);
941 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
944 /* pagein of a big page is an event. So, ignore page size */
946 __count_memcg_events(memcg, PGPGIN, 1);
948 __count_memcg_events(memcg, PGPGOUT, 1);
949 nr_pages = -nr_pages; /* for event */
952 __this_cpu_add(memcg->vmstats_percpu->nr_page_events, nr_pages);
955 static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
956 enum mem_cgroup_events_target target)
958 unsigned long val, next;
960 val = __this_cpu_read(memcg->vmstats_percpu->nr_page_events);
961 next = __this_cpu_read(memcg->vmstats_percpu->targets[target]);
962 /* from time_after() in jiffies.h */
963 if ((long)(next - val) < 0) {
965 case MEM_CGROUP_TARGET_THRESH:
966 next = val + THRESHOLDS_EVENTS_TARGET;
968 case MEM_CGROUP_TARGET_SOFTLIMIT:
969 next = val + SOFTLIMIT_EVENTS_TARGET;
974 __this_cpu_write(memcg->vmstats_percpu->targets[target], next);
981 * Check events in order.
984 static void memcg_check_events(struct mem_cgroup *memcg, int nid)
986 if (IS_ENABLED(CONFIG_PREEMPT_RT))
989 /* threshold event is triggered in finer grain than soft limit */
990 if (unlikely(mem_cgroup_event_ratelimit(memcg,
991 MEM_CGROUP_TARGET_THRESH))) {
994 do_softlimit = mem_cgroup_event_ratelimit(memcg,
995 MEM_CGROUP_TARGET_SOFTLIMIT);
996 mem_cgroup_threshold(memcg);
997 if (unlikely(do_softlimit))
998 mem_cgroup_update_tree(memcg, nid);
1002 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
1005 * mm_update_next_owner() may clear mm->owner to NULL
1006 * if it races with swapoff, page migration, etc.
1007 * So this can be called with p == NULL.
1012 return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
1014 EXPORT_SYMBOL(mem_cgroup_from_task);
1016 static __always_inline struct mem_cgroup *active_memcg(void)
1019 return this_cpu_read(int_active_memcg);
1021 return current->active_memcg;
1025 * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
1026 * @mm: mm from which memcg should be extracted. It can be NULL.
1028 * Obtain a reference on mm->memcg and returns it if successful. If mm
1029 * is NULL, then the memcg is chosen as follows:
1030 * 1) The active memcg, if set.
1031 * 2) current->mm->memcg, if available
1033 * If mem_cgroup is disabled, NULL is returned.
1035 struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
1037 struct mem_cgroup *memcg;
1039 if (mem_cgroup_disabled())
1043 * Page cache insertions can happen without an
1044 * actual mm context, e.g. during disk probing
1045 * on boot, loopback IO, acct() writes etc.
1047 * No need to css_get on root memcg as the reference
1048 * counting is disabled on the root level in the
1049 * cgroup core. See CSS_NO_REF.
1051 if (unlikely(!mm)) {
1052 memcg = active_memcg();
1053 if (unlikely(memcg)) {
1054 /* remote memcg must hold a ref */
1055 css_get(&memcg->css);
1060 return root_mem_cgroup;
1065 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1066 if (unlikely(!memcg))
1067 memcg = root_mem_cgroup;
1068 } while (!css_tryget(&memcg->css));
1072 EXPORT_SYMBOL(get_mem_cgroup_from_mm);
1074 static __always_inline bool memcg_kmem_bypass(void)
1076 /* Allow remote memcg charging from any context. */
1077 if (unlikely(active_memcg()))
1080 /* Memcg to charge can't be determined. */
1081 if (!in_task() || !current->mm || (current->flags & PF_KTHREAD))
1088 * mem_cgroup_iter - iterate over memory cgroup hierarchy
1089 * @root: hierarchy root
1090 * @prev: previously returned memcg, NULL on first invocation
1091 * @reclaim: cookie for shared reclaim walks, NULL for full walks
1093 * Returns references to children of the hierarchy below @root, or
1094 * @root itself, or %NULL after a full round-trip.
1096 * Caller must pass the return value in @prev on subsequent
1097 * invocations for reference counting, or use mem_cgroup_iter_break()
1098 * to cancel a hierarchy walk before the round-trip is complete.
1100 * Reclaimers can specify a node in @reclaim to divide up the memcgs
1101 * in the hierarchy among all concurrent reclaimers operating on the
1104 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
1105 struct mem_cgroup *prev,
1106 struct mem_cgroup_reclaim_cookie *reclaim)
1108 struct mem_cgroup_reclaim_iter *iter;
1109 struct cgroup_subsys_state *css = NULL;
1110 struct mem_cgroup *memcg = NULL;
1111 struct mem_cgroup *pos = NULL;
1113 if (mem_cgroup_disabled())
1117 root = root_mem_cgroup;
1122 struct mem_cgroup_per_node *mz;
1124 mz = root->nodeinfo[reclaim->pgdat->node_id];
1128 * On start, join the current reclaim iteration cycle.
1129 * Exit when a concurrent walker completes it.
1132 reclaim->generation = iter->generation;
1133 else if (reclaim->generation != iter->generation)
1137 pos = READ_ONCE(iter->position);
1138 if (!pos || css_tryget(&pos->css))
1141 * css reference reached zero, so iter->position will
1142 * be cleared by ->css_released. However, we should not
1143 * rely on this happening soon, because ->css_released
1144 * is called from a work queue, and by busy-waiting we
1145 * might block it. So we clear iter->position right
1148 (void)cmpxchg(&iter->position, pos, NULL);
1158 css = css_next_descendant_pre(css, &root->css);
1161 * Reclaimers share the hierarchy walk, and a
1162 * new one might jump in right at the end of
1163 * the hierarchy - make sure they see at least
1164 * one group and restart from the beginning.
1172 * Verify the css and acquire a reference. The root
1173 * is provided by the caller, so we know it's alive
1174 * and kicking, and don't take an extra reference.
1176 if (css == &root->css || css_tryget(css)) {
1177 memcg = mem_cgroup_from_css(css);
1184 * The position could have already been updated by a competing
1185 * thread, so check that the value hasn't changed since we read
1186 * it to avoid reclaiming from the same cgroup twice.
1188 (void)cmpxchg(&iter->position, pos, memcg);
1199 if (prev && prev != root)
1200 css_put(&prev->css);
1206 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1207 * @root: hierarchy root
1208 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1210 void mem_cgroup_iter_break(struct mem_cgroup *root,
1211 struct mem_cgroup *prev)
1214 root = root_mem_cgroup;
1215 if (prev && prev != root)
1216 css_put(&prev->css);
1219 static void __invalidate_reclaim_iterators(struct mem_cgroup *from,
1220 struct mem_cgroup *dead_memcg)
1222 struct mem_cgroup_reclaim_iter *iter;
1223 struct mem_cgroup_per_node *mz;
1226 for_each_node(nid) {
1227 mz = from->nodeinfo[nid];
1229 cmpxchg(&iter->position, dead_memcg, NULL);
1233 static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
1235 struct mem_cgroup *memcg = dead_memcg;
1236 struct mem_cgroup *last;
1239 __invalidate_reclaim_iterators(memcg, dead_memcg);
1241 } while ((memcg = parent_mem_cgroup(memcg)));
1244 * When cgroup1 non-hierarchy mode is used,
1245 * parent_mem_cgroup() does not walk all the way up to the
1246 * cgroup root (root_mem_cgroup). So we have to handle
1247 * dead_memcg from cgroup root separately.
1249 if (!mem_cgroup_is_root(last))
1250 __invalidate_reclaim_iterators(root_mem_cgroup,
1255 * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
1256 * @memcg: hierarchy root
1257 * @fn: function to call for each task
1258 * @arg: argument passed to @fn
1260 * This function iterates over tasks attached to @memcg or to any of its
1261 * descendants and calls @fn for each task. If @fn returns a non-zero
1262 * value, the function breaks the iteration loop. Otherwise, it will iterate
1263 * over all tasks and return 0.
1265 * This function must not be called for the root memory cgroup.
1267 void mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
1268 int (*fn)(struct task_struct *, void *), void *arg)
1270 struct mem_cgroup *iter;
1273 BUG_ON(mem_cgroup_is_root(memcg));
1275 for_each_mem_cgroup_tree(iter, memcg) {
1276 struct css_task_iter it;
1277 struct task_struct *task;
1279 css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it);
1280 while (!ret && (task = css_task_iter_next(&it)))
1281 ret = fn(task, arg);
1282 css_task_iter_end(&it);
1284 mem_cgroup_iter_break(memcg, iter);
1290 #ifdef CONFIG_DEBUG_VM
1291 void lruvec_memcg_debug(struct lruvec *lruvec, struct folio *folio)
1293 struct mem_cgroup *memcg;
1295 if (mem_cgroup_disabled())
1298 memcg = folio_memcg(folio);
1301 VM_BUG_ON_FOLIO(!mem_cgroup_is_root(lruvec_memcg(lruvec)), folio);
1303 VM_BUG_ON_FOLIO(lruvec_memcg(lruvec) != memcg, folio);
1308 * folio_lruvec_lock - Lock the lruvec for a folio.
1309 * @folio: Pointer to the folio.
1311 * These functions are safe to use under any of the following conditions:
1313 * - folio_test_lru false
1314 * - folio_memcg_lock()
1315 * - folio frozen (refcount of 0)
1317 * Return: The lruvec this folio is on with its lock held.
1319 struct lruvec *folio_lruvec_lock(struct folio *folio)
1321 struct lruvec *lruvec = folio_lruvec(folio);
1323 spin_lock(&lruvec->lru_lock);
1324 lruvec_memcg_debug(lruvec, folio);
1330 * folio_lruvec_lock_irq - Lock the lruvec for a folio.
1331 * @folio: Pointer to the folio.
1333 * These functions are safe to use under any of the following conditions:
1335 * - folio_test_lru false
1336 * - folio_memcg_lock()
1337 * - folio frozen (refcount of 0)
1339 * Return: The lruvec this folio is on with its lock held and interrupts
1342 struct lruvec *folio_lruvec_lock_irq(struct folio *folio)
1344 struct lruvec *lruvec = folio_lruvec(folio);
1346 spin_lock_irq(&lruvec->lru_lock);
1347 lruvec_memcg_debug(lruvec, folio);
1353 * folio_lruvec_lock_irqsave - Lock the lruvec for a folio.
1354 * @folio: Pointer to the folio.
1355 * @flags: Pointer to irqsave flags.
1357 * These functions are safe to use under any of the following conditions:
1359 * - folio_test_lru false
1360 * - folio_memcg_lock()
1361 * - folio frozen (refcount of 0)
1363 * Return: The lruvec this folio is on with its lock held and interrupts
1366 struct lruvec *folio_lruvec_lock_irqsave(struct folio *folio,
1367 unsigned long *flags)
1369 struct lruvec *lruvec = folio_lruvec(folio);
1371 spin_lock_irqsave(&lruvec->lru_lock, *flags);
1372 lruvec_memcg_debug(lruvec, folio);
1378 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1379 * @lruvec: mem_cgroup per zone lru vector
1380 * @lru: index of lru list the page is sitting on
1381 * @zid: zone id of the accounted pages
1382 * @nr_pages: positive when adding or negative when removing
1384 * This function must be called under lru_lock, just before a page is added
1385 * to or just after a page is removed from an lru list.
1387 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1388 int zid, int nr_pages)
1390 struct mem_cgroup_per_node *mz;
1391 unsigned long *lru_size;
1394 if (mem_cgroup_disabled())
1397 mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
1398 lru_size = &mz->lru_zone_size[zid][lru];
1401 *lru_size += nr_pages;
1404 if (WARN_ONCE(size < 0,
1405 "%s(%p, %d, %d): lru_size %ld\n",
1406 __func__, lruvec, lru, nr_pages, size)) {
1412 *lru_size += nr_pages;
1416 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1417 * @memcg: the memory cgroup
1419 * Returns the maximum amount of memory @mem can be charged with, in
1422 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1424 unsigned long margin = 0;
1425 unsigned long count;
1426 unsigned long limit;
1428 count = page_counter_read(&memcg->memory);
1429 limit = READ_ONCE(memcg->memory.max);
1431 margin = limit - count;
1433 if (do_memsw_account()) {
1434 count = page_counter_read(&memcg->memsw);
1435 limit = READ_ONCE(memcg->memsw.max);
1437 margin = min(margin, limit - count);
1446 * A routine for checking "mem" is under move_account() or not.
1448 * Checking a cgroup is mc.from or mc.to or under hierarchy of
1449 * moving cgroups. This is for waiting at high-memory pressure
1452 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1454 struct mem_cgroup *from;
1455 struct mem_cgroup *to;
1458 * Unlike task_move routines, we access mc.to, mc.from not under
1459 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1461 spin_lock(&mc.lock);
1467 ret = mem_cgroup_is_descendant(from, memcg) ||
1468 mem_cgroup_is_descendant(to, memcg);
1470 spin_unlock(&mc.lock);
1474 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1476 if (mc.moving_task && current != mc.moving_task) {
1477 if (mem_cgroup_under_move(memcg)) {
1479 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1480 /* moving charge context might have finished. */
1483 finish_wait(&mc.waitq, &wait);
1490 struct memory_stat {
1495 static const struct memory_stat memory_stats[] = {
1496 { "anon", NR_ANON_MAPPED },
1497 { "file", NR_FILE_PAGES },
1498 { "kernel", MEMCG_KMEM },
1499 { "kernel_stack", NR_KERNEL_STACK_KB },
1500 { "pagetables", NR_PAGETABLE },
1501 { "sec_pagetables", NR_SECONDARY_PAGETABLE },
1502 { "percpu", MEMCG_PERCPU_B },
1503 { "sock", MEMCG_SOCK },
1504 { "vmalloc", MEMCG_VMALLOC },
1505 { "shmem", NR_SHMEM },
1506 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
1507 { "zswap", MEMCG_ZSWAP_B },
1508 { "zswapped", MEMCG_ZSWAPPED },
1510 { "file_mapped", NR_FILE_MAPPED },
1511 { "file_dirty", NR_FILE_DIRTY },
1512 { "file_writeback", NR_WRITEBACK },
1514 { "swapcached", NR_SWAPCACHE },
1516 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1517 { "anon_thp", NR_ANON_THPS },
1518 { "file_thp", NR_FILE_THPS },
1519 { "shmem_thp", NR_SHMEM_THPS },
1521 { "inactive_anon", NR_INACTIVE_ANON },
1522 { "active_anon", NR_ACTIVE_ANON },
1523 { "inactive_file", NR_INACTIVE_FILE },
1524 { "active_file", NR_ACTIVE_FILE },
1525 { "unevictable", NR_UNEVICTABLE },
1526 { "slab_reclaimable", NR_SLAB_RECLAIMABLE_B },
1527 { "slab_unreclaimable", NR_SLAB_UNRECLAIMABLE_B },
1529 /* The memory events */
1530 { "workingset_refault_anon", WORKINGSET_REFAULT_ANON },
1531 { "workingset_refault_file", WORKINGSET_REFAULT_FILE },
1532 { "workingset_activate_anon", WORKINGSET_ACTIVATE_ANON },
1533 { "workingset_activate_file", WORKINGSET_ACTIVATE_FILE },
1534 { "workingset_restore_anon", WORKINGSET_RESTORE_ANON },
1535 { "workingset_restore_file", WORKINGSET_RESTORE_FILE },
1536 { "workingset_nodereclaim", WORKINGSET_NODERECLAIM },
1539 /* Translate stat items to the correct unit for memory.stat output */
1540 static int memcg_page_state_unit(int item)
1543 case MEMCG_PERCPU_B:
1545 case NR_SLAB_RECLAIMABLE_B:
1546 case NR_SLAB_UNRECLAIMABLE_B:
1547 case WORKINGSET_REFAULT_ANON:
1548 case WORKINGSET_REFAULT_FILE:
1549 case WORKINGSET_ACTIVATE_ANON:
1550 case WORKINGSET_ACTIVATE_FILE:
1551 case WORKINGSET_RESTORE_ANON:
1552 case WORKINGSET_RESTORE_FILE:
1553 case WORKINGSET_NODERECLAIM:
1555 case NR_KERNEL_STACK_KB:
1562 static inline unsigned long memcg_page_state_output(struct mem_cgroup *memcg,
1565 return memcg_page_state(memcg, item) * memcg_page_state_unit(item);
1568 static void memcg_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
1573 * Provide statistics on the state of the memory subsystem as
1574 * well as cumulative event counters that show past behavior.
1576 * This list is ordered following a combination of these gradients:
1577 * 1) generic big picture -> specifics and details
1578 * 2) reflecting userspace activity -> reflecting kernel heuristics
1580 * Current memory state:
1582 mem_cgroup_flush_stats();
1584 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
1587 size = memcg_page_state_output(memcg, memory_stats[i].idx);
1588 seq_buf_printf(s, "%s %llu\n", memory_stats[i].name, size);
1590 if (unlikely(memory_stats[i].idx == NR_SLAB_UNRECLAIMABLE_B)) {
1591 size += memcg_page_state_output(memcg,
1592 NR_SLAB_RECLAIMABLE_B);
1593 seq_buf_printf(s, "slab %llu\n", size);
1597 /* Accumulated memory events */
1598 seq_buf_printf(s, "pgscan %lu\n",
1599 memcg_events(memcg, PGSCAN_KSWAPD) +
1600 memcg_events(memcg, PGSCAN_DIRECT) +
1601 memcg_events(memcg, PGSCAN_KHUGEPAGED));
1602 seq_buf_printf(s, "pgsteal %lu\n",
1603 memcg_events(memcg, PGSTEAL_KSWAPD) +
1604 memcg_events(memcg, PGSTEAL_DIRECT) +
1605 memcg_events(memcg, PGSTEAL_KHUGEPAGED));
1607 for (i = 0; i < ARRAY_SIZE(memcg_vm_event_stat); i++) {
1608 if (memcg_vm_event_stat[i] == PGPGIN ||
1609 memcg_vm_event_stat[i] == PGPGOUT)
1612 seq_buf_printf(s, "%s %lu\n",
1613 vm_event_name(memcg_vm_event_stat[i]),
1614 memcg_events(memcg, memcg_vm_event_stat[i]));
1617 /* The above should easily fit into one page */
1618 WARN_ON_ONCE(seq_buf_has_overflowed(s));
1621 static void memcg1_stat_format(struct mem_cgroup *memcg, struct seq_buf *s);
1623 static void memory_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
1625 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1626 memcg_stat_format(memcg, s);
1628 memcg1_stat_format(memcg, s);
1629 WARN_ON_ONCE(seq_buf_has_overflowed(s));
1632 #define K(x) ((x) << (PAGE_SHIFT-10))
1634 * mem_cgroup_print_oom_context: Print OOM information relevant to
1635 * memory controller.
1636 * @memcg: The memory cgroup that went over limit
1637 * @p: Task that is going to be killed
1639 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1642 void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p)
1647 pr_cont(",oom_memcg=");
1648 pr_cont_cgroup_path(memcg->css.cgroup);
1650 pr_cont(",global_oom");
1652 pr_cont(",task_memcg=");
1653 pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
1659 * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
1660 * memory controller.
1661 * @memcg: The memory cgroup that went over limit
1663 void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
1665 /* Use static buffer, for the caller is holding oom_lock. */
1666 static char buf[PAGE_SIZE];
1669 lockdep_assert_held(&oom_lock);
1671 pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1672 K((u64)page_counter_read(&memcg->memory)),
1673 K((u64)READ_ONCE(memcg->memory.max)), memcg->memory.failcnt);
1674 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1675 pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n",
1676 K((u64)page_counter_read(&memcg->swap)),
1677 K((u64)READ_ONCE(memcg->swap.max)), memcg->swap.failcnt);
1679 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1680 K((u64)page_counter_read(&memcg->memsw)),
1681 K((u64)memcg->memsw.max), memcg->memsw.failcnt);
1682 pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1683 K((u64)page_counter_read(&memcg->kmem)),
1684 K((u64)memcg->kmem.max), memcg->kmem.failcnt);
1687 pr_info("Memory cgroup stats for ");
1688 pr_cont_cgroup_path(memcg->css.cgroup);
1690 seq_buf_init(&s, buf, sizeof(buf));
1691 memory_stat_format(memcg, &s);
1692 seq_buf_do_printk(&s, KERN_INFO);
1696 * Return the memory (and swap, if configured) limit for a memcg.
1698 unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg)
1700 unsigned long max = READ_ONCE(memcg->memory.max);
1702 if (do_memsw_account()) {
1703 if (mem_cgroup_swappiness(memcg)) {
1704 /* Calculate swap excess capacity from memsw limit */
1705 unsigned long swap = READ_ONCE(memcg->memsw.max) - max;
1707 max += min(swap, (unsigned long)total_swap_pages);
1710 if (mem_cgroup_swappiness(memcg))
1711 max += min(READ_ONCE(memcg->swap.max),
1712 (unsigned long)total_swap_pages);
1717 unsigned long mem_cgroup_size(struct mem_cgroup *memcg)
1719 return page_counter_read(&memcg->memory);
1722 static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1725 struct oom_control oc = {
1729 .gfp_mask = gfp_mask,
1734 if (mutex_lock_killable(&oom_lock))
1737 if (mem_cgroup_margin(memcg) >= (1 << order))
1741 * A few threads which were not waiting at mutex_lock_killable() can
1742 * fail to bail out. Therefore, check again after holding oom_lock.
1744 ret = task_is_dying() || out_of_memory(&oc);
1747 mutex_unlock(&oom_lock);
1751 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
1754 unsigned long *total_scanned)
1756 struct mem_cgroup *victim = NULL;
1759 unsigned long excess;
1760 unsigned long nr_scanned;
1761 struct mem_cgroup_reclaim_cookie reclaim = {
1765 excess = soft_limit_excess(root_memcg);
1768 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1773 * If we have not been able to reclaim
1774 * anything, it might because there are
1775 * no reclaimable pages under this hierarchy
1780 * We want to do more targeted reclaim.
1781 * excess >> 2 is not to excessive so as to
1782 * reclaim too much, nor too less that we keep
1783 * coming back to reclaim from this cgroup
1785 if (total >= (excess >> 2) ||
1786 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1791 total += mem_cgroup_shrink_node(victim, gfp_mask, false,
1792 pgdat, &nr_scanned);
1793 *total_scanned += nr_scanned;
1794 if (!soft_limit_excess(root_memcg))
1797 mem_cgroup_iter_break(root_memcg, victim);
1801 #ifdef CONFIG_LOCKDEP
1802 static struct lockdep_map memcg_oom_lock_dep_map = {
1803 .name = "memcg_oom_lock",
1807 static DEFINE_SPINLOCK(memcg_oom_lock);
1810 * Check OOM-Killer is already running under our hierarchy.
1811 * If someone is running, return false.
1813 static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
1815 struct mem_cgroup *iter, *failed = NULL;
1817 spin_lock(&memcg_oom_lock);
1819 for_each_mem_cgroup_tree(iter, memcg) {
1820 if (iter->oom_lock) {
1822 * this subtree of our hierarchy is already locked
1823 * so we cannot give a lock.
1826 mem_cgroup_iter_break(memcg, iter);
1829 iter->oom_lock = true;
1834 * OK, we failed to lock the whole subtree so we have
1835 * to clean up what we set up to the failing subtree
1837 for_each_mem_cgroup_tree(iter, memcg) {
1838 if (iter == failed) {
1839 mem_cgroup_iter_break(memcg, iter);
1842 iter->oom_lock = false;
1845 mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
1847 spin_unlock(&memcg_oom_lock);
1852 static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1854 struct mem_cgroup *iter;
1856 spin_lock(&memcg_oom_lock);
1857 mutex_release(&memcg_oom_lock_dep_map, _RET_IP_);
1858 for_each_mem_cgroup_tree(iter, memcg)
1859 iter->oom_lock = false;
1860 spin_unlock(&memcg_oom_lock);
1863 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1865 struct mem_cgroup *iter;
1867 spin_lock(&memcg_oom_lock);
1868 for_each_mem_cgroup_tree(iter, memcg)
1870 spin_unlock(&memcg_oom_lock);
1873 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1875 struct mem_cgroup *iter;
1878 * Be careful about under_oom underflows because a child memcg
1879 * could have been added after mem_cgroup_mark_under_oom.
1881 spin_lock(&memcg_oom_lock);
1882 for_each_mem_cgroup_tree(iter, memcg)
1883 if (iter->under_oom > 0)
1885 spin_unlock(&memcg_oom_lock);
1888 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1890 struct oom_wait_info {
1891 struct mem_cgroup *memcg;
1892 wait_queue_entry_t wait;
1895 static int memcg_oom_wake_function(wait_queue_entry_t *wait,
1896 unsigned mode, int sync, void *arg)
1898 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
1899 struct mem_cgroup *oom_wait_memcg;
1900 struct oom_wait_info *oom_wait_info;
1902 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1903 oom_wait_memcg = oom_wait_info->memcg;
1905 if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
1906 !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
1908 return autoremove_wake_function(wait, mode, sync, arg);
1911 static void memcg_oom_recover(struct mem_cgroup *memcg)
1914 * For the following lockless ->under_oom test, the only required
1915 * guarantee is that it must see the state asserted by an OOM when
1916 * this function is called as a result of userland actions
1917 * triggered by the notification of the OOM. This is trivially
1918 * achieved by invoking mem_cgroup_mark_under_oom() before
1919 * triggering notification.
1921 if (memcg && memcg->under_oom)
1922 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
1926 * Returns true if successfully killed one or more processes. Though in some
1927 * corner cases it can return true even without killing any process.
1929 static bool mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
1933 if (order > PAGE_ALLOC_COSTLY_ORDER)
1936 memcg_memory_event(memcg, MEMCG_OOM);
1939 * We are in the middle of the charge context here, so we
1940 * don't want to block when potentially sitting on a callstack
1941 * that holds all kinds of filesystem and mm locks.
1943 * cgroup1 allows disabling the OOM killer and waiting for outside
1944 * handling until the charge can succeed; remember the context and put
1945 * the task to sleep at the end of the page fault when all locks are
1948 * On the other hand, in-kernel OOM killer allows for an async victim
1949 * memory reclaim (oom_reaper) and that means that we are not solely
1950 * relying on the oom victim to make a forward progress and we can
1951 * invoke the oom killer here.
1953 * Please note that mem_cgroup_out_of_memory might fail to find a
1954 * victim and then we have to bail out from the charge path.
1956 if (READ_ONCE(memcg->oom_kill_disable)) {
1957 if (current->in_user_fault) {
1958 css_get(&memcg->css);
1959 current->memcg_in_oom = memcg;
1960 current->memcg_oom_gfp_mask = mask;
1961 current->memcg_oom_order = order;
1966 mem_cgroup_mark_under_oom(memcg);
1968 locked = mem_cgroup_oom_trylock(memcg);
1971 mem_cgroup_oom_notify(memcg);
1973 mem_cgroup_unmark_under_oom(memcg);
1974 ret = mem_cgroup_out_of_memory(memcg, mask, order);
1977 mem_cgroup_oom_unlock(memcg);
1983 * mem_cgroup_oom_synchronize - complete memcg OOM handling
1984 * @handle: actually kill/wait or just clean up the OOM state
1986 * This has to be called at the end of a page fault if the memcg OOM
1987 * handler was enabled.
1989 * Memcg supports userspace OOM handling where failed allocations must
1990 * sleep on a waitqueue until the userspace task resolves the
1991 * situation. Sleeping directly in the charge context with all kinds
1992 * of locks held is not a good idea, instead we remember an OOM state
1993 * in the task and mem_cgroup_oom_synchronize() has to be called at
1994 * the end of the page fault to complete the OOM handling.
1996 * Returns %true if an ongoing memcg OOM situation was detected and
1997 * completed, %false otherwise.
1999 bool mem_cgroup_oom_synchronize(bool handle)
2001 struct mem_cgroup *memcg = current->memcg_in_oom;
2002 struct oom_wait_info owait;
2005 /* OOM is global, do not handle */
2012 owait.memcg = memcg;
2013 owait.wait.flags = 0;
2014 owait.wait.func = memcg_oom_wake_function;
2015 owait.wait.private = current;
2016 INIT_LIST_HEAD(&owait.wait.entry);
2018 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
2019 mem_cgroup_mark_under_oom(memcg);
2021 locked = mem_cgroup_oom_trylock(memcg);
2024 mem_cgroup_oom_notify(memcg);
2027 mem_cgroup_unmark_under_oom(memcg);
2028 finish_wait(&memcg_oom_waitq, &owait.wait);
2031 mem_cgroup_oom_unlock(memcg);
2033 current->memcg_in_oom = NULL;
2034 css_put(&memcg->css);
2039 * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
2040 * @victim: task to be killed by the OOM killer
2041 * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
2043 * Returns a pointer to a memory cgroup, which has to be cleaned up
2044 * by killing all belonging OOM-killable tasks.
2046 * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
2048 struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim,
2049 struct mem_cgroup *oom_domain)
2051 struct mem_cgroup *oom_group = NULL;
2052 struct mem_cgroup *memcg;
2054 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
2058 oom_domain = root_mem_cgroup;
2062 memcg = mem_cgroup_from_task(victim);
2063 if (mem_cgroup_is_root(memcg))
2067 * If the victim task has been asynchronously moved to a different
2068 * memory cgroup, we might end up killing tasks outside oom_domain.
2069 * In this case it's better to ignore memory.group.oom.
2071 if (unlikely(!mem_cgroup_is_descendant(memcg, oom_domain)))
2075 * Traverse the memory cgroup hierarchy from the victim task's
2076 * cgroup up to the OOMing cgroup (or root) to find the
2077 * highest-level memory cgroup with oom.group set.
2079 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
2080 if (READ_ONCE(memcg->oom_group))
2083 if (memcg == oom_domain)
2088 css_get(&oom_group->css);
2095 void mem_cgroup_print_oom_group(struct mem_cgroup *memcg)
2097 pr_info("Tasks in ");
2098 pr_cont_cgroup_path(memcg->css.cgroup);
2099 pr_cont(" are going to be killed due to memory.oom.group set\n");
2103 * folio_memcg_lock - Bind a folio to its memcg.
2104 * @folio: The folio.
2106 * This function prevents unlocked LRU folios from being moved to
2109 * It ensures lifetime of the bound memcg. The caller is responsible
2110 * for the lifetime of the folio.
2112 void folio_memcg_lock(struct folio *folio)
2114 struct mem_cgroup *memcg;
2115 unsigned long flags;
2118 * The RCU lock is held throughout the transaction. The fast
2119 * path can get away without acquiring the memcg->move_lock
2120 * because page moving starts with an RCU grace period.
2124 if (mem_cgroup_disabled())
2127 memcg = folio_memcg(folio);
2128 if (unlikely(!memcg))
2131 #ifdef CONFIG_PROVE_LOCKING
2132 local_irq_save(flags);
2133 might_lock(&memcg->move_lock);
2134 local_irq_restore(flags);
2137 if (atomic_read(&memcg->moving_account) <= 0)
2140 spin_lock_irqsave(&memcg->move_lock, flags);
2141 if (memcg != folio_memcg(folio)) {
2142 spin_unlock_irqrestore(&memcg->move_lock, flags);
2147 * When charge migration first begins, we can have multiple
2148 * critical sections holding the fast-path RCU lock and one
2149 * holding the slowpath move_lock. Track the task who has the
2150 * move_lock for folio_memcg_unlock().
2152 memcg->move_lock_task = current;
2153 memcg->move_lock_flags = flags;
2156 static void __folio_memcg_unlock(struct mem_cgroup *memcg)
2158 if (memcg && memcg->move_lock_task == current) {
2159 unsigned long flags = memcg->move_lock_flags;
2161 memcg->move_lock_task = NULL;
2162 memcg->move_lock_flags = 0;
2164 spin_unlock_irqrestore(&memcg->move_lock, flags);
2171 * folio_memcg_unlock - Release the binding between a folio and its memcg.
2172 * @folio: The folio.
2174 * This releases the binding created by folio_memcg_lock(). This does
2175 * not change the accounting of this folio to its memcg, but it does
2176 * permit others to change it.
2178 void folio_memcg_unlock(struct folio *folio)
2180 __folio_memcg_unlock(folio_memcg(folio));
2183 struct memcg_stock_pcp {
2184 local_lock_t stock_lock;
2185 struct mem_cgroup *cached; /* this never be root cgroup */
2186 unsigned int nr_pages;
2188 #ifdef CONFIG_MEMCG_KMEM
2189 struct obj_cgroup *cached_objcg;
2190 struct pglist_data *cached_pgdat;
2191 unsigned int nr_bytes;
2192 int nr_slab_reclaimable_b;
2193 int nr_slab_unreclaimable_b;
2196 struct work_struct work;
2197 unsigned long flags;
2198 #define FLUSHING_CACHED_CHARGE 0
2200 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock) = {
2201 .stock_lock = INIT_LOCAL_LOCK(stock_lock),
2203 static DEFINE_MUTEX(percpu_charge_mutex);
2205 #ifdef CONFIG_MEMCG_KMEM
2206 static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock);
2207 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2208 struct mem_cgroup *root_memcg);
2209 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages);
2212 static inline struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock)
2216 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2217 struct mem_cgroup *root_memcg)
2221 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages)
2227 * consume_stock: Try to consume stocked charge on this cpu.
2228 * @memcg: memcg to consume from.
2229 * @nr_pages: how many pages to charge.
2231 * The charges will only happen if @memcg matches the current cpu's memcg
2232 * stock, and at least @nr_pages are available in that stock. Failure to
2233 * service an allocation will refill the stock.
2235 * returns true if successful, false otherwise.
2237 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2239 struct memcg_stock_pcp *stock;
2240 unsigned long flags;
2243 if (nr_pages > MEMCG_CHARGE_BATCH)
2246 local_lock_irqsave(&memcg_stock.stock_lock, flags);
2248 stock = this_cpu_ptr(&memcg_stock);
2249 if (memcg == READ_ONCE(stock->cached) && stock->nr_pages >= nr_pages) {
2250 stock->nr_pages -= nr_pages;
2254 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2260 * Returns stocks cached in percpu and reset cached information.
2262 static void drain_stock(struct memcg_stock_pcp *stock)
2264 struct mem_cgroup *old = READ_ONCE(stock->cached);
2269 if (stock->nr_pages) {
2270 page_counter_uncharge(&old->memory, stock->nr_pages);
2271 if (do_memsw_account())
2272 page_counter_uncharge(&old->memsw, stock->nr_pages);
2273 stock->nr_pages = 0;
2277 WRITE_ONCE(stock->cached, NULL);
2280 static void drain_local_stock(struct work_struct *dummy)
2282 struct memcg_stock_pcp *stock;
2283 struct obj_cgroup *old = NULL;
2284 unsigned long flags;
2287 * The only protection from cpu hotplug (memcg_hotplug_cpu_dead) vs.
2288 * drain_stock races is that we always operate on local CPU stock
2289 * here with IRQ disabled
2291 local_lock_irqsave(&memcg_stock.stock_lock, flags);
2293 stock = this_cpu_ptr(&memcg_stock);
2294 old = drain_obj_stock(stock);
2296 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2298 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2300 obj_cgroup_put(old);
2304 * Cache charges(val) to local per_cpu area.
2305 * This will be consumed by consume_stock() function, later.
2307 static void __refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2309 struct memcg_stock_pcp *stock;
2311 stock = this_cpu_ptr(&memcg_stock);
2312 if (READ_ONCE(stock->cached) != memcg) { /* reset if necessary */
2314 css_get(&memcg->css);
2315 WRITE_ONCE(stock->cached, memcg);
2317 stock->nr_pages += nr_pages;
2319 if (stock->nr_pages > MEMCG_CHARGE_BATCH)
2323 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2325 unsigned long flags;
2327 local_lock_irqsave(&memcg_stock.stock_lock, flags);
2328 __refill_stock(memcg, nr_pages);
2329 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2333 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2334 * of the hierarchy under it.
2336 static void drain_all_stock(struct mem_cgroup *root_memcg)
2340 /* If someone's already draining, avoid adding running more workers. */
2341 if (!mutex_trylock(&percpu_charge_mutex))
2344 * Notify other cpus that system-wide "drain" is running
2345 * We do not care about races with the cpu hotplug because cpu down
2346 * as well as workers from this path always operate on the local
2347 * per-cpu data. CPU up doesn't touch memcg_stock at all.
2350 curcpu = smp_processor_id();
2351 for_each_online_cpu(cpu) {
2352 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2353 struct mem_cgroup *memcg;
2357 memcg = READ_ONCE(stock->cached);
2358 if (memcg && stock->nr_pages &&
2359 mem_cgroup_is_descendant(memcg, root_memcg))
2361 else if (obj_stock_flush_required(stock, root_memcg))
2366 !test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2368 drain_local_stock(&stock->work);
2369 else if (!cpu_is_isolated(cpu))
2370 schedule_work_on(cpu, &stock->work);
2374 mutex_unlock(&percpu_charge_mutex);
2377 static int memcg_hotplug_cpu_dead(unsigned int cpu)
2379 struct memcg_stock_pcp *stock;
2381 stock = &per_cpu(memcg_stock, cpu);
2387 static unsigned long reclaim_high(struct mem_cgroup *memcg,
2388 unsigned int nr_pages,
2391 unsigned long nr_reclaimed = 0;
2394 unsigned long pflags;
2396 if (page_counter_read(&memcg->memory) <=
2397 READ_ONCE(memcg->memory.high))
2400 memcg_memory_event(memcg, MEMCG_HIGH);
2402 psi_memstall_enter(&pflags);
2403 nr_reclaimed += try_to_free_mem_cgroup_pages(memcg, nr_pages,
2405 MEMCG_RECLAIM_MAY_SWAP);
2406 psi_memstall_leave(&pflags);
2407 } while ((memcg = parent_mem_cgroup(memcg)) &&
2408 !mem_cgroup_is_root(memcg));
2410 return nr_reclaimed;
2413 static void high_work_func(struct work_struct *work)
2415 struct mem_cgroup *memcg;
2417 memcg = container_of(work, struct mem_cgroup, high_work);
2418 reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
2422 * Clamp the maximum sleep time per allocation batch to 2 seconds. This is
2423 * enough to still cause a significant slowdown in most cases, while still
2424 * allowing diagnostics and tracing to proceed without becoming stuck.
2426 #define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ)
2429 * When calculating the delay, we use these either side of the exponentiation to
2430 * maintain precision and scale to a reasonable number of jiffies (see the table
2433 * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the
2434 * overage ratio to a delay.
2435 * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down the
2436 * proposed penalty in order to reduce to a reasonable number of jiffies, and
2437 * to produce a reasonable delay curve.
2439 * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a
2440 * reasonable delay curve compared to precision-adjusted overage, not
2441 * penalising heavily at first, but still making sure that growth beyond the
2442 * limit penalises misbehaviour cgroups by slowing them down exponentially. For
2443 * example, with a high of 100 megabytes:
2445 * +-------+------------------------+
2446 * | usage | time to allocate in ms |
2447 * +-------+------------------------+
2469 * +-------+------------------------+
2471 #define MEMCG_DELAY_PRECISION_SHIFT 20
2472 #define MEMCG_DELAY_SCALING_SHIFT 14
2474 static u64 calculate_overage(unsigned long usage, unsigned long high)
2482 * Prevent division by 0 in overage calculation by acting as if
2483 * it was a threshold of 1 page
2485 high = max(high, 1UL);
2487 overage = usage - high;
2488 overage <<= MEMCG_DELAY_PRECISION_SHIFT;
2489 return div64_u64(overage, high);
2492 static u64 mem_find_max_overage(struct mem_cgroup *memcg)
2494 u64 overage, max_overage = 0;
2497 overage = calculate_overage(page_counter_read(&memcg->memory),
2498 READ_ONCE(memcg->memory.high));
2499 max_overage = max(overage, max_overage);
2500 } while ((memcg = parent_mem_cgroup(memcg)) &&
2501 !mem_cgroup_is_root(memcg));
2506 static u64 swap_find_max_overage(struct mem_cgroup *memcg)
2508 u64 overage, max_overage = 0;
2511 overage = calculate_overage(page_counter_read(&memcg->swap),
2512 READ_ONCE(memcg->swap.high));
2514 memcg_memory_event(memcg, MEMCG_SWAP_HIGH);
2515 max_overage = max(overage, max_overage);
2516 } while ((memcg = parent_mem_cgroup(memcg)) &&
2517 !mem_cgroup_is_root(memcg));
2523 * Get the number of jiffies that we should penalise a mischievous cgroup which
2524 * is exceeding its memory.high by checking both it and its ancestors.
2526 static unsigned long calculate_high_delay(struct mem_cgroup *memcg,
2527 unsigned int nr_pages,
2530 unsigned long penalty_jiffies;
2536 * We use overage compared to memory.high to calculate the number of
2537 * jiffies to sleep (penalty_jiffies). Ideally this value should be
2538 * fairly lenient on small overages, and increasingly harsh when the
2539 * memcg in question makes it clear that it has no intention of stopping
2540 * its crazy behaviour, so we exponentially increase the delay based on
2543 penalty_jiffies = max_overage * max_overage * HZ;
2544 penalty_jiffies >>= MEMCG_DELAY_PRECISION_SHIFT;
2545 penalty_jiffies >>= MEMCG_DELAY_SCALING_SHIFT;
2548 * Factor in the task's own contribution to the overage, such that four
2549 * N-sized allocations are throttled approximately the same as one
2550 * 4N-sized allocation.
2552 * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or
2553 * larger the current charge patch is than that.
2555 return penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH;
2559 * Scheduled by try_charge() to be executed from the userland return path
2560 * and reclaims memory over the high limit.
2562 void mem_cgroup_handle_over_high(void)
2564 unsigned long penalty_jiffies;
2565 unsigned long pflags;
2566 unsigned long nr_reclaimed;
2567 unsigned int nr_pages = current->memcg_nr_pages_over_high;
2568 int nr_retries = MAX_RECLAIM_RETRIES;
2569 struct mem_cgroup *memcg;
2570 bool in_retry = false;
2572 if (likely(!nr_pages))
2575 memcg = get_mem_cgroup_from_mm(current->mm);
2576 current->memcg_nr_pages_over_high = 0;
2580 * The allocating task should reclaim at least the batch size, but for
2581 * subsequent retries we only want to do what's necessary to prevent oom
2582 * or breaching resource isolation.
2584 * This is distinct from memory.max or page allocator behaviour because
2585 * memory.high is currently batched, whereas memory.max and the page
2586 * allocator run every time an allocation is made.
2588 nr_reclaimed = reclaim_high(memcg,
2589 in_retry ? SWAP_CLUSTER_MAX : nr_pages,
2593 * memory.high is breached and reclaim is unable to keep up. Throttle
2594 * allocators proactively to slow down excessive growth.
2596 penalty_jiffies = calculate_high_delay(memcg, nr_pages,
2597 mem_find_max_overage(memcg));
2599 penalty_jiffies += calculate_high_delay(memcg, nr_pages,
2600 swap_find_max_overage(memcg));
2603 * Clamp the max delay per usermode return so as to still keep the
2604 * application moving forwards and also permit diagnostics, albeit
2607 penalty_jiffies = min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES);
2610 * Don't sleep if the amount of jiffies this memcg owes us is so low
2611 * that it's not even worth doing, in an attempt to be nice to those who
2612 * go only a small amount over their memory.high value and maybe haven't
2613 * been aggressively reclaimed enough yet.
2615 if (penalty_jiffies <= HZ / 100)
2619 * If reclaim is making forward progress but we're still over
2620 * memory.high, we want to encourage that rather than doing allocator
2623 if (nr_reclaimed || nr_retries--) {
2629 * If we exit early, we're guaranteed to die (since
2630 * schedule_timeout_killable sets TASK_KILLABLE). This means we don't
2631 * need to account for any ill-begotten jiffies to pay them off later.
2633 psi_memstall_enter(&pflags);
2634 schedule_timeout_killable(penalty_jiffies);
2635 psi_memstall_leave(&pflags);
2638 css_put(&memcg->css);
2641 static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask,
2642 unsigned int nr_pages)
2644 unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
2645 int nr_retries = MAX_RECLAIM_RETRIES;
2646 struct mem_cgroup *mem_over_limit;
2647 struct page_counter *counter;
2648 unsigned long nr_reclaimed;
2649 bool passed_oom = false;
2650 unsigned int reclaim_options = MEMCG_RECLAIM_MAY_SWAP;
2651 bool drained = false;
2652 bool raised_max_event = false;
2653 unsigned long pflags;
2656 if (consume_stock(memcg, nr_pages))
2659 if (!do_memsw_account() ||
2660 page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2661 if (page_counter_try_charge(&memcg->memory, batch, &counter))
2663 if (do_memsw_account())
2664 page_counter_uncharge(&memcg->memsw, batch);
2665 mem_over_limit = mem_cgroup_from_counter(counter, memory);
2667 mem_over_limit = mem_cgroup_from_counter(counter, memsw);
2668 reclaim_options &= ~MEMCG_RECLAIM_MAY_SWAP;
2671 if (batch > nr_pages) {
2677 * Prevent unbounded recursion when reclaim operations need to
2678 * allocate memory. This might exceed the limits temporarily,
2679 * but we prefer facilitating memory reclaim and getting back
2680 * under the limit over triggering OOM kills in these cases.
2682 if (unlikely(current->flags & PF_MEMALLOC))
2685 if (unlikely(task_in_memcg_oom(current)))
2688 if (!gfpflags_allow_blocking(gfp_mask))
2691 memcg_memory_event(mem_over_limit, MEMCG_MAX);
2692 raised_max_event = true;
2694 psi_memstall_enter(&pflags);
2695 nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
2696 gfp_mask, reclaim_options);
2697 psi_memstall_leave(&pflags);
2699 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2703 drain_all_stock(mem_over_limit);
2708 if (gfp_mask & __GFP_NORETRY)
2711 * Even though the limit is exceeded at this point, reclaim
2712 * may have been able to free some pages. Retry the charge
2713 * before killing the task.
2715 * Only for regular pages, though: huge pages are rather
2716 * unlikely to succeed so close to the limit, and we fall back
2717 * to regular pages anyway in case of failure.
2719 if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
2722 * At task move, charge accounts can be doubly counted. So, it's
2723 * better to wait until the end of task_move if something is going on.
2725 if (mem_cgroup_wait_acct_move(mem_over_limit))
2731 if (gfp_mask & __GFP_RETRY_MAYFAIL)
2734 /* Avoid endless loop for tasks bypassed by the oom killer */
2735 if (passed_oom && task_is_dying())
2739 * keep retrying as long as the memcg oom killer is able to make
2740 * a forward progress or bypass the charge if the oom killer
2741 * couldn't make any progress.
2743 if (mem_cgroup_oom(mem_over_limit, gfp_mask,
2744 get_order(nr_pages * PAGE_SIZE))) {
2746 nr_retries = MAX_RECLAIM_RETRIES;
2751 * Memcg doesn't have a dedicated reserve for atomic
2752 * allocations. But like the global atomic pool, we need to
2753 * put the burden of reclaim on regular allocation requests
2754 * and let these go through as privileged allocations.
2756 if (!(gfp_mask & (__GFP_NOFAIL | __GFP_HIGH)))
2760 * If the allocation has to be enforced, don't forget to raise
2761 * a MEMCG_MAX event.
2763 if (!raised_max_event)
2764 memcg_memory_event(mem_over_limit, MEMCG_MAX);
2767 * The allocation either can't fail or will lead to more memory
2768 * being freed very soon. Allow memory usage go over the limit
2769 * temporarily by force charging it.
2771 page_counter_charge(&memcg->memory, nr_pages);
2772 if (do_memsw_account())
2773 page_counter_charge(&memcg->memsw, nr_pages);
2778 if (batch > nr_pages)
2779 refill_stock(memcg, batch - nr_pages);
2782 * If the hierarchy is above the normal consumption range, schedule
2783 * reclaim on returning to userland. We can perform reclaim here
2784 * if __GFP_RECLAIM but let's always punt for simplicity and so that
2785 * GFP_KERNEL can consistently be used during reclaim. @memcg is
2786 * not recorded as it most likely matches current's and won't
2787 * change in the meantime. As high limit is checked again before
2788 * reclaim, the cost of mismatch is negligible.
2791 bool mem_high, swap_high;
2793 mem_high = page_counter_read(&memcg->memory) >
2794 READ_ONCE(memcg->memory.high);
2795 swap_high = page_counter_read(&memcg->swap) >
2796 READ_ONCE(memcg->swap.high);
2798 /* Don't bother a random interrupted task */
2801 schedule_work(&memcg->high_work);
2807 if (mem_high || swap_high) {
2809 * The allocating tasks in this cgroup will need to do
2810 * reclaim or be throttled to prevent further growth
2811 * of the memory or swap footprints.
2813 * Target some best-effort fairness between the tasks,
2814 * and distribute reclaim work and delay penalties
2815 * based on how much each task is actually allocating.
2817 current->memcg_nr_pages_over_high += batch;
2818 set_notify_resume(current);
2821 } while ((memcg = parent_mem_cgroup(memcg)));
2823 if (current->memcg_nr_pages_over_high > MEMCG_CHARGE_BATCH &&
2824 !(current->flags & PF_MEMALLOC) &&
2825 gfpflags_allow_blocking(gfp_mask)) {
2826 mem_cgroup_handle_over_high();
2831 static inline int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2832 unsigned int nr_pages)
2834 if (mem_cgroup_is_root(memcg))
2837 return try_charge_memcg(memcg, gfp_mask, nr_pages);
2840 static inline void cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
2842 if (mem_cgroup_is_root(memcg))
2845 page_counter_uncharge(&memcg->memory, nr_pages);
2846 if (do_memsw_account())
2847 page_counter_uncharge(&memcg->memsw, nr_pages);
2850 static void commit_charge(struct folio *folio, struct mem_cgroup *memcg)
2852 VM_BUG_ON_FOLIO(folio_memcg(folio), folio);
2854 * Any of the following ensures page's memcg stability:
2858 * - folio_memcg_lock()
2859 * - exclusive reference
2860 * - mem_cgroup_trylock_pages()
2862 folio->memcg_data = (unsigned long)memcg;
2865 #ifdef CONFIG_MEMCG_KMEM
2867 * The allocated objcg pointers array is not accounted directly.
2868 * Moreover, it should not come from DMA buffer and is not readily
2869 * reclaimable. So those GFP bits should be masked off.
2871 #define OBJCGS_CLEAR_MASK (__GFP_DMA | __GFP_RECLAIMABLE | __GFP_ACCOUNT)
2874 * mod_objcg_mlstate() may be called with irq enabled, so
2875 * mod_memcg_lruvec_state() should be used.
2877 static inline void mod_objcg_mlstate(struct obj_cgroup *objcg,
2878 struct pglist_data *pgdat,
2879 enum node_stat_item idx, int nr)
2881 struct mem_cgroup *memcg;
2882 struct lruvec *lruvec;
2885 memcg = obj_cgroup_memcg(objcg);
2886 lruvec = mem_cgroup_lruvec(memcg, pgdat);
2887 mod_memcg_lruvec_state(lruvec, idx, nr);
2891 int memcg_alloc_slab_cgroups(struct slab *slab, struct kmem_cache *s,
2892 gfp_t gfp, bool new_slab)
2894 unsigned int objects = objs_per_slab(s, slab);
2895 unsigned long memcg_data;
2898 gfp &= ~OBJCGS_CLEAR_MASK;
2899 vec = kcalloc_node(objects, sizeof(struct obj_cgroup *), gfp,
2904 memcg_data = (unsigned long) vec | MEMCG_DATA_OBJCGS;
2907 * If the slab is brand new and nobody can yet access its
2908 * memcg_data, no synchronization is required and memcg_data can
2909 * be simply assigned.
2911 slab->memcg_data = memcg_data;
2912 } else if (cmpxchg(&slab->memcg_data, 0, memcg_data)) {
2914 * If the slab is already in use, somebody can allocate and
2915 * assign obj_cgroups in parallel. In this case the existing
2916 * objcg vector should be reused.
2922 kmemleak_not_leak(vec);
2926 static __always_inline
2927 struct mem_cgroup *mem_cgroup_from_obj_folio(struct folio *folio, void *p)
2930 * Slab objects are accounted individually, not per-page.
2931 * Memcg membership data for each individual object is saved in
2934 if (folio_test_slab(folio)) {
2935 struct obj_cgroup **objcgs;
2939 slab = folio_slab(folio);
2940 objcgs = slab_objcgs(slab);
2944 off = obj_to_index(slab->slab_cache, slab, p);
2946 return obj_cgroup_memcg(objcgs[off]);
2952 * folio_memcg_check() is used here, because in theory we can encounter
2953 * a folio where the slab flag has been cleared already, but
2954 * slab->memcg_data has not been freed yet
2955 * folio_memcg_check() will guarantee that a proper memory
2956 * cgroup pointer or NULL will be returned.
2958 return folio_memcg_check(folio);
2962 * Returns a pointer to the memory cgroup to which the kernel object is charged.
2964 * A passed kernel object can be a slab object, vmalloc object or a generic
2965 * kernel page, so different mechanisms for getting the memory cgroup pointer
2968 * In certain cases (e.g. kernel stacks or large kmallocs with SLUB) the caller
2969 * can not know for sure how the kernel object is implemented.
2970 * mem_cgroup_from_obj() can be safely used in such cases.
2972 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
2973 * cgroup_mutex, etc.
2975 struct mem_cgroup *mem_cgroup_from_obj(void *p)
2977 struct folio *folio;
2979 if (mem_cgroup_disabled())
2982 if (unlikely(is_vmalloc_addr(p)))
2983 folio = page_folio(vmalloc_to_page(p));
2985 folio = virt_to_folio(p);
2987 return mem_cgroup_from_obj_folio(folio, p);
2991 * Returns a pointer to the memory cgroup to which the kernel object is charged.
2992 * Similar to mem_cgroup_from_obj(), but faster and not suitable for objects,
2993 * allocated using vmalloc().
2995 * A passed kernel object must be a slab object or a generic kernel page.
2997 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
2998 * cgroup_mutex, etc.
3000 struct mem_cgroup *mem_cgroup_from_slab_obj(void *p)
3002 if (mem_cgroup_disabled())
3005 return mem_cgroup_from_obj_folio(virt_to_folio(p), p);
3008 static struct obj_cgroup *__get_obj_cgroup_from_memcg(struct mem_cgroup *memcg)
3010 struct obj_cgroup *objcg = NULL;
3012 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
3013 objcg = rcu_dereference(memcg->objcg);
3014 if (objcg && obj_cgroup_tryget(objcg))
3021 __always_inline struct obj_cgroup *get_obj_cgroup_from_current(void)
3023 struct obj_cgroup *objcg = NULL;
3024 struct mem_cgroup *memcg;
3026 if (memcg_kmem_bypass())
3030 if (unlikely(active_memcg()))
3031 memcg = active_memcg();
3033 memcg = mem_cgroup_from_task(current);
3034 objcg = __get_obj_cgroup_from_memcg(memcg);
3039 struct obj_cgroup *get_obj_cgroup_from_page(struct page *page)
3041 struct obj_cgroup *objcg;
3043 if (!memcg_kmem_online())
3046 if (PageMemcgKmem(page)) {
3047 objcg = __folio_objcg(page_folio(page));
3048 obj_cgroup_get(objcg);
3050 struct mem_cgroup *memcg;
3053 memcg = __folio_memcg(page_folio(page));
3055 objcg = __get_obj_cgroup_from_memcg(memcg);
3063 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages)
3065 mod_memcg_state(memcg, MEMCG_KMEM, nr_pages);
3066 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
3068 page_counter_charge(&memcg->kmem, nr_pages);
3070 page_counter_uncharge(&memcg->kmem, -nr_pages);
3076 * obj_cgroup_uncharge_pages: uncharge a number of kernel pages from a objcg
3077 * @objcg: object cgroup to uncharge
3078 * @nr_pages: number of pages to uncharge
3080 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
3081 unsigned int nr_pages)
3083 struct mem_cgroup *memcg;
3085 memcg = get_mem_cgroup_from_objcg(objcg);
3087 memcg_account_kmem(memcg, -nr_pages);
3088 refill_stock(memcg, nr_pages);
3090 css_put(&memcg->css);
3094 * obj_cgroup_charge_pages: charge a number of kernel pages to a objcg
3095 * @objcg: object cgroup to charge
3096 * @gfp: reclaim mode
3097 * @nr_pages: number of pages to charge
3099 * Returns 0 on success, an error code on failure.
3101 static int obj_cgroup_charge_pages(struct obj_cgroup *objcg, gfp_t gfp,
3102 unsigned int nr_pages)
3104 struct mem_cgroup *memcg;
3107 memcg = get_mem_cgroup_from_objcg(objcg);
3109 ret = try_charge_memcg(memcg, gfp, nr_pages);
3113 memcg_account_kmem(memcg, nr_pages);
3115 css_put(&memcg->css);
3121 * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup
3122 * @page: page to charge
3123 * @gfp: reclaim mode
3124 * @order: allocation order
3126 * Returns 0 on success, an error code on failure.
3128 int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
3130 struct obj_cgroup *objcg;
3133 objcg = get_obj_cgroup_from_current();
3135 ret = obj_cgroup_charge_pages(objcg, gfp, 1 << order);
3137 page->memcg_data = (unsigned long)objcg |
3141 obj_cgroup_put(objcg);
3147 * __memcg_kmem_uncharge_page: uncharge a kmem page
3148 * @page: page to uncharge
3149 * @order: allocation order
3151 void __memcg_kmem_uncharge_page(struct page *page, int order)
3153 struct folio *folio = page_folio(page);
3154 struct obj_cgroup *objcg;
3155 unsigned int nr_pages = 1 << order;
3157 if (!folio_memcg_kmem(folio))
3160 objcg = __folio_objcg(folio);
3161 obj_cgroup_uncharge_pages(objcg, nr_pages);
3162 folio->memcg_data = 0;
3163 obj_cgroup_put(objcg);
3166 void mod_objcg_state(struct obj_cgroup *objcg, struct pglist_data *pgdat,
3167 enum node_stat_item idx, int nr)
3169 struct memcg_stock_pcp *stock;
3170 struct obj_cgroup *old = NULL;
3171 unsigned long flags;
3174 local_lock_irqsave(&memcg_stock.stock_lock, flags);
3175 stock = this_cpu_ptr(&memcg_stock);
3178 * Save vmstat data in stock and skip vmstat array update unless
3179 * accumulating over a page of vmstat data or when pgdat or idx
3182 if (READ_ONCE(stock->cached_objcg) != objcg) {
3183 old = drain_obj_stock(stock);
3184 obj_cgroup_get(objcg);
3185 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3186 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3187 WRITE_ONCE(stock->cached_objcg, objcg);
3188 stock->cached_pgdat = pgdat;
3189 } else if (stock->cached_pgdat != pgdat) {
3190 /* Flush the existing cached vmstat data */
3191 struct pglist_data *oldpg = stock->cached_pgdat;
3193 if (stock->nr_slab_reclaimable_b) {
3194 mod_objcg_mlstate(objcg, oldpg, NR_SLAB_RECLAIMABLE_B,
3195 stock->nr_slab_reclaimable_b);
3196 stock->nr_slab_reclaimable_b = 0;
3198 if (stock->nr_slab_unreclaimable_b) {
3199 mod_objcg_mlstate(objcg, oldpg, NR_SLAB_UNRECLAIMABLE_B,
3200 stock->nr_slab_unreclaimable_b);
3201 stock->nr_slab_unreclaimable_b = 0;
3203 stock->cached_pgdat = pgdat;
3206 bytes = (idx == NR_SLAB_RECLAIMABLE_B) ? &stock->nr_slab_reclaimable_b
3207 : &stock->nr_slab_unreclaimable_b;
3209 * Even for large object >= PAGE_SIZE, the vmstat data will still be
3210 * cached locally at least once before pushing it out.
3217 if (abs(*bytes) > PAGE_SIZE) {
3225 mod_objcg_mlstate(objcg, pgdat, idx, nr);
3227 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3229 obj_cgroup_put(old);
3232 static bool consume_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes)
3234 struct memcg_stock_pcp *stock;
3235 unsigned long flags;
3238 local_lock_irqsave(&memcg_stock.stock_lock, flags);
3240 stock = this_cpu_ptr(&memcg_stock);
3241 if (objcg == READ_ONCE(stock->cached_objcg) && stock->nr_bytes >= nr_bytes) {
3242 stock->nr_bytes -= nr_bytes;
3246 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3251 static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock)
3253 struct obj_cgroup *old = READ_ONCE(stock->cached_objcg);
3258 if (stock->nr_bytes) {
3259 unsigned int nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3260 unsigned int nr_bytes = stock->nr_bytes & (PAGE_SIZE - 1);
3263 struct mem_cgroup *memcg;
3265 memcg = get_mem_cgroup_from_objcg(old);
3267 memcg_account_kmem(memcg, -nr_pages);
3268 __refill_stock(memcg, nr_pages);
3270 css_put(&memcg->css);
3274 * The leftover is flushed to the centralized per-memcg value.
3275 * On the next attempt to refill obj stock it will be moved
3276 * to a per-cpu stock (probably, on an other CPU), see
3277 * refill_obj_stock().
3279 * How often it's flushed is a trade-off between the memory
3280 * limit enforcement accuracy and potential CPU contention,
3281 * so it might be changed in the future.
3283 atomic_add(nr_bytes, &old->nr_charged_bytes);
3284 stock->nr_bytes = 0;
3288 * Flush the vmstat data in current stock
3290 if (stock->nr_slab_reclaimable_b || stock->nr_slab_unreclaimable_b) {
3291 if (stock->nr_slab_reclaimable_b) {
3292 mod_objcg_mlstate(old, stock->cached_pgdat,
3293 NR_SLAB_RECLAIMABLE_B,
3294 stock->nr_slab_reclaimable_b);
3295 stock->nr_slab_reclaimable_b = 0;
3297 if (stock->nr_slab_unreclaimable_b) {
3298 mod_objcg_mlstate(old, stock->cached_pgdat,
3299 NR_SLAB_UNRECLAIMABLE_B,
3300 stock->nr_slab_unreclaimable_b);
3301 stock->nr_slab_unreclaimable_b = 0;
3303 stock->cached_pgdat = NULL;
3306 WRITE_ONCE(stock->cached_objcg, NULL);
3308 * The `old' objects needs to be released by the caller via
3309 * obj_cgroup_put() outside of memcg_stock_pcp::stock_lock.
3314 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
3315 struct mem_cgroup *root_memcg)
3317 struct obj_cgroup *objcg = READ_ONCE(stock->cached_objcg);
3318 struct mem_cgroup *memcg;
3321 memcg = obj_cgroup_memcg(objcg);
3322 if (memcg && mem_cgroup_is_descendant(memcg, root_memcg))
3329 static void refill_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes,
3330 bool allow_uncharge)
3332 struct memcg_stock_pcp *stock;
3333 struct obj_cgroup *old = NULL;
3334 unsigned long flags;
3335 unsigned int nr_pages = 0;
3337 local_lock_irqsave(&memcg_stock.stock_lock, flags);
3339 stock = this_cpu_ptr(&memcg_stock);
3340 if (READ_ONCE(stock->cached_objcg) != objcg) { /* reset if necessary */
3341 old = drain_obj_stock(stock);
3342 obj_cgroup_get(objcg);
3343 WRITE_ONCE(stock->cached_objcg, objcg);
3344 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3345 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3346 allow_uncharge = true; /* Allow uncharge when objcg changes */
3348 stock->nr_bytes += nr_bytes;
3350 if (allow_uncharge && (stock->nr_bytes > PAGE_SIZE)) {
3351 nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3352 stock->nr_bytes &= (PAGE_SIZE - 1);
3355 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3357 obj_cgroup_put(old);
3360 obj_cgroup_uncharge_pages(objcg, nr_pages);
3363 int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size)
3365 unsigned int nr_pages, nr_bytes;
3368 if (consume_obj_stock(objcg, size))
3372 * In theory, objcg->nr_charged_bytes can have enough
3373 * pre-charged bytes to satisfy the allocation. However,
3374 * flushing objcg->nr_charged_bytes requires two atomic
3375 * operations, and objcg->nr_charged_bytes can't be big.
3376 * The shared objcg->nr_charged_bytes can also become a
3377 * performance bottleneck if all tasks of the same memcg are
3378 * trying to update it. So it's better to ignore it and try
3379 * grab some new pages. The stock's nr_bytes will be flushed to
3380 * objcg->nr_charged_bytes later on when objcg changes.
3382 * The stock's nr_bytes may contain enough pre-charged bytes
3383 * to allow one less page from being charged, but we can't rely
3384 * on the pre-charged bytes not being changed outside of
3385 * consume_obj_stock() or refill_obj_stock(). So ignore those
3386 * pre-charged bytes as well when charging pages. To avoid a
3387 * page uncharge right after a page charge, we set the
3388 * allow_uncharge flag to false when calling refill_obj_stock()
3389 * to temporarily allow the pre-charged bytes to exceed the page
3390 * size limit. The maximum reachable value of the pre-charged
3391 * bytes is (sizeof(object) + PAGE_SIZE - 2) if there is no data
3394 nr_pages = size >> PAGE_SHIFT;
3395 nr_bytes = size & (PAGE_SIZE - 1);
3400 ret = obj_cgroup_charge_pages(objcg, gfp, nr_pages);
3401 if (!ret && nr_bytes)
3402 refill_obj_stock(objcg, PAGE_SIZE - nr_bytes, false);
3407 void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size)
3409 refill_obj_stock(objcg, size, true);
3412 #endif /* CONFIG_MEMCG_KMEM */
3415 * Because page_memcg(head) is not set on tails, set it now.
3417 void split_page_memcg(struct page *head, unsigned int nr)
3419 struct folio *folio = page_folio(head);
3420 struct mem_cgroup *memcg = folio_memcg(folio);
3423 if (mem_cgroup_disabled() || !memcg)
3426 for (i = 1; i < nr; i++)
3427 folio_page(folio, i)->memcg_data = folio->memcg_data;
3429 if (folio_memcg_kmem(folio))
3430 obj_cgroup_get_many(__folio_objcg(folio), nr - 1);
3432 css_get_many(&memcg->css, nr - 1);
3437 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3438 * @entry: swap entry to be moved
3439 * @from: mem_cgroup which the entry is moved from
3440 * @to: mem_cgroup which the entry is moved to
3442 * It succeeds only when the swap_cgroup's record for this entry is the same
3443 * as the mem_cgroup's id of @from.
3445 * Returns 0 on success, -EINVAL on failure.
3447 * The caller must have charged to @to, IOW, called page_counter_charge() about
3448 * both res and memsw, and called css_get().
3450 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3451 struct mem_cgroup *from, struct mem_cgroup *to)
3453 unsigned short old_id, new_id;
3455 old_id = mem_cgroup_id(from);
3456 new_id = mem_cgroup_id(to);
3458 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3459 mod_memcg_state(from, MEMCG_SWAP, -1);
3460 mod_memcg_state(to, MEMCG_SWAP, 1);
3466 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3467 struct mem_cgroup *from, struct mem_cgroup *to)
3473 static DEFINE_MUTEX(memcg_max_mutex);
3475 static int mem_cgroup_resize_max(struct mem_cgroup *memcg,
3476 unsigned long max, bool memsw)
3478 bool enlarge = false;
3479 bool drained = false;
3481 bool limits_invariant;
3482 struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory;
3485 if (signal_pending(current)) {
3490 mutex_lock(&memcg_max_mutex);
3492 * Make sure that the new limit (memsw or memory limit) doesn't
3493 * break our basic invariant rule memory.max <= memsw.max.
3495 limits_invariant = memsw ? max >= READ_ONCE(memcg->memory.max) :
3496 max <= memcg->memsw.max;
3497 if (!limits_invariant) {
3498 mutex_unlock(&memcg_max_mutex);
3502 if (max > counter->max)
3504 ret = page_counter_set_max(counter, max);
3505 mutex_unlock(&memcg_max_mutex);
3511 drain_all_stock(memcg);
3516 if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,
3517 memsw ? 0 : MEMCG_RECLAIM_MAY_SWAP)) {
3523 if (!ret && enlarge)
3524 memcg_oom_recover(memcg);
3529 unsigned long mem_cgroup_soft_limit_reclaim(pg_data_t *pgdat, int order,
3531 unsigned long *total_scanned)
3533 unsigned long nr_reclaimed = 0;
3534 struct mem_cgroup_per_node *mz, *next_mz = NULL;
3535 unsigned long reclaimed;
3537 struct mem_cgroup_tree_per_node *mctz;
3538 unsigned long excess;
3540 if (lru_gen_enabled())
3546 mctz = soft_limit_tree.rb_tree_per_node[pgdat->node_id];
3549 * Do not even bother to check the largest node if the root
3550 * is empty. Do it lockless to prevent lock bouncing. Races
3551 * are acceptable as soft limit is best effort anyway.
3553 if (!mctz || RB_EMPTY_ROOT(&mctz->rb_root))
3557 * This loop can run a while, specially if mem_cgroup's continuously
3558 * keep exceeding their soft limit and putting the system under
3565 mz = mem_cgroup_largest_soft_limit_node(mctz);
3569 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, pgdat,
3570 gfp_mask, total_scanned);
3571 nr_reclaimed += reclaimed;
3572 spin_lock_irq(&mctz->lock);
3575 * If we failed to reclaim anything from this memory cgroup
3576 * it is time to move on to the next cgroup
3580 next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
3582 excess = soft_limit_excess(mz->memcg);
3584 * One school of thought says that we should not add
3585 * back the node to the tree if reclaim returns 0.
3586 * But our reclaim could return 0, simply because due
3587 * to priority we are exposing a smaller subset of
3588 * memory to reclaim from. Consider this as a longer
3591 /* If excess == 0, no tree ops */
3592 __mem_cgroup_insert_exceeded(mz, mctz, excess);
3593 spin_unlock_irq(&mctz->lock);
3594 css_put(&mz->memcg->css);
3597 * Could not reclaim anything and there are no more
3598 * mem cgroups to try or we seem to be looping without
3599 * reclaiming anything.
3601 if (!nr_reclaimed &&
3603 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3605 } while (!nr_reclaimed);
3607 css_put(&next_mz->memcg->css);
3608 return nr_reclaimed;
3612 * Reclaims as many pages from the given memcg as possible.
3614 * Caller is responsible for holding css reference for memcg.
3616 static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
3618 int nr_retries = MAX_RECLAIM_RETRIES;
3620 /* we call try-to-free pages for make this cgroup empty */
3621 lru_add_drain_all();
3623 drain_all_stock(memcg);
3625 /* try to free all pages in this cgroup */
3626 while (nr_retries && page_counter_read(&memcg->memory)) {
3627 if (signal_pending(current))
3630 if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,
3631 MEMCG_RECLAIM_MAY_SWAP))
3638 static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
3639 char *buf, size_t nbytes,
3642 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3644 if (mem_cgroup_is_root(memcg))
3646 return mem_cgroup_force_empty(memcg) ?: nbytes;
3649 static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
3655 static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
3656 struct cftype *cft, u64 val)
3661 pr_warn_once("Non-hierarchical mode is deprecated. "
3662 "Please report your usecase to linux-mm@kvack.org if you "
3663 "depend on this functionality.\n");
3668 static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3672 if (mem_cgroup_is_root(memcg)) {
3674 * Approximate root's usage from global state. This isn't
3675 * perfect, but the root usage was always an approximation.
3677 val = global_node_page_state(NR_FILE_PAGES) +
3678 global_node_page_state(NR_ANON_MAPPED);
3680 val += total_swap_pages - get_nr_swap_pages();
3683 val = page_counter_read(&memcg->memory);
3685 val = page_counter_read(&memcg->memsw);
3698 static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
3701 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3702 struct page_counter *counter;
3704 switch (MEMFILE_TYPE(cft->private)) {
3706 counter = &memcg->memory;
3709 counter = &memcg->memsw;
3712 counter = &memcg->kmem;
3715 counter = &memcg->tcpmem;
3721 switch (MEMFILE_ATTR(cft->private)) {
3723 if (counter == &memcg->memory)
3724 return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
3725 if (counter == &memcg->memsw)
3726 return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
3727 return (u64)page_counter_read(counter) * PAGE_SIZE;
3729 return (u64)counter->max * PAGE_SIZE;
3731 return (u64)counter->watermark * PAGE_SIZE;
3733 return counter->failcnt;
3734 case RES_SOFT_LIMIT:
3735 return (u64)READ_ONCE(memcg->soft_limit) * PAGE_SIZE;
3742 * This function doesn't do anything useful. Its only job is to provide a read
3743 * handler for a file so that cgroup_file_mode() will add read permissions.
3745 static int mem_cgroup_dummy_seq_show(__always_unused struct seq_file *m,
3746 __always_unused void *v)
3751 #ifdef CONFIG_MEMCG_KMEM
3752 static int memcg_online_kmem(struct mem_cgroup *memcg)
3754 struct obj_cgroup *objcg;
3756 if (mem_cgroup_kmem_disabled())
3759 if (unlikely(mem_cgroup_is_root(memcg)))
3762 objcg = obj_cgroup_alloc();
3766 objcg->memcg = memcg;
3767 rcu_assign_pointer(memcg->objcg, objcg);
3769 static_branch_enable(&memcg_kmem_online_key);
3771 memcg->kmemcg_id = memcg->id.id;
3776 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3778 struct mem_cgroup *parent;
3780 if (mem_cgroup_kmem_disabled())
3783 if (unlikely(mem_cgroup_is_root(memcg)))
3786 parent = parent_mem_cgroup(memcg);
3788 parent = root_mem_cgroup;
3790 memcg_reparent_objcgs(memcg, parent);
3793 * After we have finished memcg_reparent_objcgs(), all list_lrus
3794 * corresponding to this cgroup are guaranteed to remain empty.
3795 * The ordering is imposed by list_lru_node->lock taken by
3796 * memcg_reparent_list_lrus().
3798 memcg_reparent_list_lrus(memcg, parent);
3801 static int memcg_online_kmem(struct mem_cgroup *memcg)
3805 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3808 #endif /* CONFIG_MEMCG_KMEM */
3810 static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max)
3814 mutex_lock(&memcg_max_mutex);
3816 ret = page_counter_set_max(&memcg->tcpmem, max);
3820 if (!memcg->tcpmem_active) {
3822 * The active flag needs to be written after the static_key
3823 * update. This is what guarantees that the socket activation
3824 * function is the last one to run. See mem_cgroup_sk_alloc()
3825 * for details, and note that we don't mark any socket as
3826 * belonging to this memcg until that flag is up.
3828 * We need to do this, because static_keys will span multiple
3829 * sites, but we can't control their order. If we mark a socket
3830 * as accounted, but the accounting functions are not patched in
3831 * yet, we'll lose accounting.
3833 * We never race with the readers in mem_cgroup_sk_alloc(),
3834 * because when this value change, the code to process it is not
3837 static_branch_inc(&memcg_sockets_enabled_key);
3838 memcg->tcpmem_active = true;
3841 mutex_unlock(&memcg_max_mutex);
3846 * The user of this function is...
3849 static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
3850 char *buf, size_t nbytes, loff_t off)
3852 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3853 unsigned long nr_pages;
3856 buf = strstrip(buf);
3857 ret = page_counter_memparse(buf, "-1", &nr_pages);
3861 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3863 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3867 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3869 ret = mem_cgroup_resize_max(memcg, nr_pages, false);
3872 ret = mem_cgroup_resize_max(memcg, nr_pages, true);
3875 /* kmem.limit_in_bytes is deprecated. */
3879 ret = memcg_update_tcp_max(memcg, nr_pages);
3883 case RES_SOFT_LIMIT:
3884 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
3887 WRITE_ONCE(memcg->soft_limit, nr_pages);
3892 return ret ?: nbytes;
3895 static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
3896 size_t nbytes, loff_t off)
3898 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3899 struct page_counter *counter;
3901 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3903 counter = &memcg->memory;
3906 counter = &memcg->memsw;
3909 counter = &memcg->kmem;
3912 counter = &memcg->tcpmem;
3918 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3920 page_counter_reset_watermark(counter);
3923 counter->failcnt = 0;
3932 static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
3935 return mem_cgroup_from_css(css)->move_charge_at_immigrate;
3939 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3940 struct cftype *cft, u64 val)
3942 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3944 pr_warn_once("Cgroup memory moving (move_charge_at_immigrate) is deprecated. "
3945 "Please report your usecase to linux-mm@kvack.org if you "
3946 "depend on this functionality.\n");
3948 if (val & ~MOVE_MASK)
3952 * No kind of locking is needed in here, because ->can_attach() will
3953 * check this value once in the beginning of the process, and then carry
3954 * on with stale data. This means that changes to this value will only
3955 * affect task migrations starting after the change.
3957 memcg->move_charge_at_immigrate = val;
3961 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3962 struct cftype *cft, u64 val)
3970 #define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE))
3971 #define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON))
3972 #define LRU_ALL ((1 << NR_LRU_LISTS) - 1)
3974 static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
3975 int nid, unsigned int lru_mask, bool tree)
3977 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
3978 unsigned long nr = 0;
3981 VM_BUG_ON((unsigned)nid >= nr_node_ids);
3984 if (!(BIT(lru) & lru_mask))
3987 nr += lruvec_page_state(lruvec, NR_LRU_BASE + lru);
3989 nr += lruvec_page_state_local(lruvec, NR_LRU_BASE + lru);
3994 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
3995 unsigned int lru_mask,
3998 unsigned long nr = 0;
4002 if (!(BIT(lru) & lru_mask))
4005 nr += memcg_page_state(memcg, NR_LRU_BASE + lru);
4007 nr += memcg_page_state_local(memcg, NR_LRU_BASE + lru);
4012 static int memcg_numa_stat_show(struct seq_file *m, void *v)
4016 unsigned int lru_mask;
4019 static const struct numa_stat stats[] = {
4020 { "total", LRU_ALL },
4021 { "file", LRU_ALL_FILE },
4022 { "anon", LRU_ALL_ANON },
4023 { "unevictable", BIT(LRU_UNEVICTABLE) },
4025 const struct numa_stat *stat;
4027 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
4029 mem_cgroup_flush_stats();
4031 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
4032 seq_printf(m, "%s=%lu", stat->name,
4033 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
4035 for_each_node_state(nid, N_MEMORY)
4036 seq_printf(m, " N%d=%lu", nid,
4037 mem_cgroup_node_nr_lru_pages(memcg, nid,
4038 stat->lru_mask, false));
4042 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
4044 seq_printf(m, "hierarchical_%s=%lu", stat->name,
4045 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
4047 for_each_node_state(nid, N_MEMORY)
4048 seq_printf(m, " N%d=%lu", nid,
4049 mem_cgroup_node_nr_lru_pages(memcg, nid,
4050 stat->lru_mask, true));
4056 #endif /* CONFIG_NUMA */
4058 static const unsigned int memcg1_stats[] = {
4061 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4068 WORKINGSET_REFAULT_ANON,
4069 WORKINGSET_REFAULT_FILE,
4073 static const char *const memcg1_stat_names[] = {
4076 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4083 "workingset_refault_anon",
4084 "workingset_refault_file",
4088 /* Universal VM events cgroup1 shows, original sort order */
4089 static const unsigned int memcg1_events[] = {
4096 static void memcg1_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
4098 unsigned long memory, memsw;
4099 struct mem_cgroup *mi;
4102 BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats));
4104 mem_cgroup_flush_stats();
4106 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
4109 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
4111 nr = memcg_page_state_local(memcg, memcg1_stats[i]);
4112 seq_buf_printf(s, "%s %lu\n", memcg1_stat_names[i],
4113 nr * memcg_page_state_unit(memcg1_stats[i]));
4116 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
4117 seq_buf_printf(s, "%s %lu\n", vm_event_name(memcg1_events[i]),
4118 memcg_events_local(memcg, memcg1_events[i]));
4120 for (i = 0; i < NR_LRU_LISTS; i++)
4121 seq_buf_printf(s, "%s %lu\n", lru_list_name(i),
4122 memcg_page_state_local(memcg, NR_LRU_BASE + i) *
4125 /* Hierarchical information */
4126 memory = memsw = PAGE_COUNTER_MAX;
4127 for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
4128 memory = min(memory, READ_ONCE(mi->memory.max));
4129 memsw = min(memsw, READ_ONCE(mi->memsw.max));
4131 seq_buf_printf(s, "hierarchical_memory_limit %llu\n",
4132 (u64)memory * PAGE_SIZE);
4133 if (do_memsw_account())
4134 seq_buf_printf(s, "hierarchical_memsw_limit %llu\n",
4135 (u64)memsw * PAGE_SIZE);
4137 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
4140 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
4142 nr = memcg_page_state(memcg, memcg1_stats[i]);
4143 seq_buf_printf(s, "total_%s %llu\n", memcg1_stat_names[i],
4144 (u64)nr * memcg_page_state_unit(memcg1_stats[i]));
4147 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
4148 seq_buf_printf(s, "total_%s %llu\n",
4149 vm_event_name(memcg1_events[i]),
4150 (u64)memcg_events(memcg, memcg1_events[i]));
4152 for (i = 0; i < NR_LRU_LISTS; i++)
4153 seq_buf_printf(s, "total_%s %llu\n", lru_list_name(i),
4154 (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
4157 #ifdef CONFIG_DEBUG_VM
4160 struct mem_cgroup_per_node *mz;
4161 unsigned long anon_cost = 0;
4162 unsigned long file_cost = 0;
4164 for_each_online_pgdat(pgdat) {
4165 mz = memcg->nodeinfo[pgdat->node_id];
4167 anon_cost += mz->lruvec.anon_cost;
4168 file_cost += mz->lruvec.file_cost;
4170 seq_buf_printf(s, "anon_cost %lu\n", anon_cost);
4171 seq_buf_printf(s, "file_cost %lu\n", file_cost);
4176 static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
4179 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4181 return mem_cgroup_swappiness(memcg);
4184 static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
4185 struct cftype *cft, u64 val)
4187 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4192 if (!mem_cgroup_is_root(memcg))
4193 WRITE_ONCE(memcg->swappiness, val);
4195 WRITE_ONCE(vm_swappiness, val);
4200 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4202 struct mem_cgroup_threshold_ary *t;
4203 unsigned long usage;
4208 t = rcu_dereference(memcg->thresholds.primary);
4210 t = rcu_dereference(memcg->memsw_thresholds.primary);
4215 usage = mem_cgroup_usage(memcg, swap);
4218 * current_threshold points to threshold just below or equal to usage.
4219 * If it's not true, a threshold was crossed after last
4220 * call of __mem_cgroup_threshold().
4222 i = t->current_threshold;
4225 * Iterate backward over array of thresholds starting from
4226 * current_threshold and check if a threshold is crossed.
4227 * If none of thresholds below usage is crossed, we read
4228 * only one element of the array here.
4230 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4231 eventfd_signal(t->entries[i].eventfd, 1);
4233 /* i = current_threshold + 1 */
4237 * Iterate forward over array of thresholds starting from
4238 * current_threshold+1 and check if a threshold is crossed.
4239 * If none of thresholds above usage is crossed, we read
4240 * only one element of the array here.
4242 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4243 eventfd_signal(t->entries[i].eventfd, 1);
4245 /* Update current_threshold */
4246 t->current_threshold = i - 1;
4251 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4254 __mem_cgroup_threshold(memcg, false);
4255 if (do_memsw_account())
4256 __mem_cgroup_threshold(memcg, true);
4258 memcg = parent_mem_cgroup(memcg);
4262 static int compare_thresholds(const void *a, const void *b)
4264 const struct mem_cgroup_threshold *_a = a;
4265 const struct mem_cgroup_threshold *_b = b;
4267 if (_a->threshold > _b->threshold)
4270 if (_a->threshold < _b->threshold)
4276 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
4278 struct mem_cgroup_eventfd_list *ev;
4280 spin_lock(&memcg_oom_lock);
4282 list_for_each_entry(ev, &memcg->oom_notify, list)
4283 eventfd_signal(ev->eventfd, 1);
4285 spin_unlock(&memcg_oom_lock);
4289 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
4291 struct mem_cgroup *iter;
4293 for_each_mem_cgroup_tree(iter, memcg)
4294 mem_cgroup_oom_notify_cb(iter);
4297 static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4298 struct eventfd_ctx *eventfd, const char *args, enum res_type type)
4300 struct mem_cgroup_thresholds *thresholds;
4301 struct mem_cgroup_threshold_ary *new;
4302 unsigned long threshold;
4303 unsigned long usage;
4306 ret = page_counter_memparse(args, "-1", &threshold);
4310 mutex_lock(&memcg->thresholds_lock);
4313 thresholds = &memcg->thresholds;
4314 usage = mem_cgroup_usage(memcg, false);
4315 } else if (type == _MEMSWAP) {
4316 thresholds = &memcg->memsw_thresholds;
4317 usage = mem_cgroup_usage(memcg, true);
4321 /* Check if a threshold crossed before adding a new one */
4322 if (thresholds->primary)
4323 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4325 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4327 /* Allocate memory for new array of thresholds */
4328 new = kmalloc(struct_size(new, entries, size), GFP_KERNEL);
4335 /* Copy thresholds (if any) to new array */
4336 if (thresholds->primary)
4337 memcpy(new->entries, thresholds->primary->entries,
4338 flex_array_size(new, entries, size - 1));
4340 /* Add new threshold */
4341 new->entries[size - 1].eventfd = eventfd;
4342 new->entries[size - 1].threshold = threshold;
4344 /* Sort thresholds. Registering of new threshold isn't time-critical */
4345 sort(new->entries, size, sizeof(*new->entries),
4346 compare_thresholds, NULL);
4348 /* Find current threshold */
4349 new->current_threshold = -1;
4350 for (i = 0; i < size; i++) {
4351 if (new->entries[i].threshold <= usage) {
4353 * new->current_threshold will not be used until
4354 * rcu_assign_pointer(), so it's safe to increment
4357 ++new->current_threshold;
4362 /* Free old spare buffer and save old primary buffer as spare */
4363 kfree(thresholds->spare);
4364 thresholds->spare = thresholds->primary;
4366 rcu_assign_pointer(thresholds->primary, new);
4368 /* To be sure that nobody uses thresholds */
4372 mutex_unlock(&memcg->thresholds_lock);
4377 static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4378 struct eventfd_ctx *eventfd, const char *args)
4380 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
4383 static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
4384 struct eventfd_ctx *eventfd, const char *args)
4386 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
4389 static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4390 struct eventfd_ctx *eventfd, enum res_type type)
4392 struct mem_cgroup_thresholds *thresholds;
4393 struct mem_cgroup_threshold_ary *new;
4394 unsigned long usage;
4395 int i, j, size, entries;
4397 mutex_lock(&memcg->thresholds_lock);
4400 thresholds = &memcg->thresholds;
4401 usage = mem_cgroup_usage(memcg, false);
4402 } else if (type == _MEMSWAP) {
4403 thresholds = &memcg->memsw_thresholds;
4404 usage = mem_cgroup_usage(memcg, true);
4408 if (!thresholds->primary)
4411 /* Check if a threshold crossed before removing */
4412 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4414 /* Calculate new number of threshold */
4416 for (i = 0; i < thresholds->primary->size; i++) {
4417 if (thresholds->primary->entries[i].eventfd != eventfd)
4423 new = thresholds->spare;
4425 /* If no items related to eventfd have been cleared, nothing to do */
4429 /* Set thresholds array to NULL if we don't have thresholds */
4438 /* Copy thresholds and find current threshold */
4439 new->current_threshold = -1;
4440 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4441 if (thresholds->primary->entries[i].eventfd == eventfd)
4444 new->entries[j] = thresholds->primary->entries[i];
4445 if (new->entries[j].threshold <= usage) {
4447 * new->current_threshold will not be used
4448 * until rcu_assign_pointer(), so it's safe to increment
4451 ++new->current_threshold;
4457 /* Swap primary and spare array */
4458 thresholds->spare = thresholds->primary;
4460 rcu_assign_pointer(thresholds->primary, new);
4462 /* To be sure that nobody uses thresholds */
4465 /* If all events are unregistered, free the spare array */
4467 kfree(thresholds->spare);
4468 thresholds->spare = NULL;
4471 mutex_unlock(&memcg->thresholds_lock);
4474 static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4475 struct eventfd_ctx *eventfd)
4477 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
4480 static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4481 struct eventfd_ctx *eventfd)
4483 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
4486 static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
4487 struct eventfd_ctx *eventfd, const char *args)
4489 struct mem_cgroup_eventfd_list *event;
4491 event = kmalloc(sizeof(*event), GFP_KERNEL);
4495 spin_lock(&memcg_oom_lock);
4497 event->eventfd = eventfd;
4498 list_add(&event->list, &memcg->oom_notify);
4500 /* already in OOM ? */
4501 if (memcg->under_oom)
4502 eventfd_signal(eventfd, 1);
4503 spin_unlock(&memcg_oom_lock);
4508 static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
4509 struct eventfd_ctx *eventfd)
4511 struct mem_cgroup_eventfd_list *ev, *tmp;
4513 spin_lock(&memcg_oom_lock);
4515 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
4516 if (ev->eventfd == eventfd) {
4517 list_del(&ev->list);
4522 spin_unlock(&memcg_oom_lock);
4525 static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
4527 struct mem_cgroup *memcg = mem_cgroup_from_seq(sf);
4529 seq_printf(sf, "oom_kill_disable %d\n", READ_ONCE(memcg->oom_kill_disable));
4530 seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
4531 seq_printf(sf, "oom_kill %lu\n",
4532 atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
4536 static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
4537 struct cftype *cft, u64 val)
4539 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4541 /* cannot set to root cgroup and only 0 and 1 are allowed */
4542 if (mem_cgroup_is_root(memcg) || !((val == 0) || (val == 1)))
4545 WRITE_ONCE(memcg->oom_kill_disable, val);
4547 memcg_oom_recover(memcg);
4552 #ifdef CONFIG_CGROUP_WRITEBACK
4554 #include <trace/events/writeback.h>
4556 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4558 return wb_domain_init(&memcg->cgwb_domain, gfp);
4561 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4563 wb_domain_exit(&memcg->cgwb_domain);
4566 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4568 wb_domain_size_changed(&memcg->cgwb_domain);
4571 struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
4573 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4575 if (!memcg->css.parent)
4578 return &memcg->cgwb_domain;
4582 * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
4583 * @wb: bdi_writeback in question
4584 * @pfilepages: out parameter for number of file pages
4585 * @pheadroom: out parameter for number of allocatable pages according to memcg
4586 * @pdirty: out parameter for number of dirty pages
4587 * @pwriteback: out parameter for number of pages under writeback
4589 * Determine the numbers of file, headroom, dirty, and writeback pages in
4590 * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom
4591 * is a bit more involved.
4593 * A memcg's headroom is "min(max, high) - used". In the hierarchy, the
4594 * headroom is calculated as the lowest headroom of itself and the
4595 * ancestors. Note that this doesn't consider the actual amount of
4596 * available memory in the system. The caller should further cap
4597 * *@pheadroom accordingly.
4599 void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
4600 unsigned long *pheadroom, unsigned long *pdirty,
4601 unsigned long *pwriteback)
4603 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4604 struct mem_cgroup *parent;
4606 mem_cgroup_flush_stats();
4608 *pdirty = memcg_page_state(memcg, NR_FILE_DIRTY);
4609 *pwriteback = memcg_page_state(memcg, NR_WRITEBACK);
4610 *pfilepages = memcg_page_state(memcg, NR_INACTIVE_FILE) +
4611 memcg_page_state(memcg, NR_ACTIVE_FILE);
4613 *pheadroom = PAGE_COUNTER_MAX;
4614 while ((parent = parent_mem_cgroup(memcg))) {
4615 unsigned long ceiling = min(READ_ONCE(memcg->memory.max),
4616 READ_ONCE(memcg->memory.high));
4617 unsigned long used = page_counter_read(&memcg->memory);
4619 *pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
4625 * Foreign dirty flushing
4627 * There's an inherent mismatch between memcg and writeback. The former
4628 * tracks ownership per-page while the latter per-inode. This was a
4629 * deliberate design decision because honoring per-page ownership in the
4630 * writeback path is complicated, may lead to higher CPU and IO overheads
4631 * and deemed unnecessary given that write-sharing an inode across
4632 * different cgroups isn't a common use-case.
4634 * Combined with inode majority-writer ownership switching, this works well
4635 * enough in most cases but there are some pathological cases. For
4636 * example, let's say there are two cgroups A and B which keep writing to
4637 * different but confined parts of the same inode. B owns the inode and
4638 * A's memory is limited far below B's. A's dirty ratio can rise enough to
4639 * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
4640 * triggering background writeback. A will be slowed down without a way to
4641 * make writeback of the dirty pages happen.
4643 * Conditions like the above can lead to a cgroup getting repeatedly and
4644 * severely throttled after making some progress after each
4645 * dirty_expire_interval while the underlying IO device is almost
4648 * Solving this problem completely requires matching the ownership tracking
4649 * granularities between memcg and writeback in either direction. However,
4650 * the more egregious behaviors can be avoided by simply remembering the
4651 * most recent foreign dirtying events and initiating remote flushes on
4652 * them when local writeback isn't enough to keep the memory clean enough.
4654 * The following two functions implement such mechanism. When a foreign
4655 * page - a page whose memcg and writeback ownerships don't match - is
4656 * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
4657 * bdi_writeback on the page owning memcg. When balance_dirty_pages()
4658 * decides that the memcg needs to sleep due to high dirty ratio, it calls
4659 * mem_cgroup_flush_foreign() which queues writeback on the recorded
4660 * foreign bdi_writebacks which haven't expired. Both the numbers of
4661 * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
4662 * limited to MEMCG_CGWB_FRN_CNT.
4664 * The mechanism only remembers IDs and doesn't hold any object references.
4665 * As being wrong occasionally doesn't matter, updates and accesses to the
4666 * records are lockless and racy.
4668 void mem_cgroup_track_foreign_dirty_slowpath(struct folio *folio,
4669 struct bdi_writeback *wb)
4671 struct mem_cgroup *memcg = folio_memcg(folio);
4672 struct memcg_cgwb_frn *frn;
4673 u64 now = get_jiffies_64();
4674 u64 oldest_at = now;
4678 trace_track_foreign_dirty(folio, wb);
4681 * Pick the slot to use. If there is already a slot for @wb, keep
4682 * using it. If not replace the oldest one which isn't being
4685 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4686 frn = &memcg->cgwb_frn[i];
4687 if (frn->bdi_id == wb->bdi->id &&
4688 frn->memcg_id == wb->memcg_css->id)
4690 if (time_before64(frn->at, oldest_at) &&
4691 atomic_read(&frn->done.cnt) == 1) {
4693 oldest_at = frn->at;
4697 if (i < MEMCG_CGWB_FRN_CNT) {
4699 * Re-using an existing one. Update timestamp lazily to
4700 * avoid making the cacheline hot. We want them to be
4701 * reasonably up-to-date and significantly shorter than
4702 * dirty_expire_interval as that's what expires the record.
4703 * Use the shorter of 1s and dirty_expire_interval / 8.
4705 unsigned long update_intv =
4706 min_t(unsigned long, HZ,
4707 msecs_to_jiffies(dirty_expire_interval * 10) / 8);
4709 if (time_before64(frn->at, now - update_intv))
4711 } else if (oldest >= 0) {
4712 /* replace the oldest free one */
4713 frn = &memcg->cgwb_frn[oldest];
4714 frn->bdi_id = wb->bdi->id;
4715 frn->memcg_id = wb->memcg_css->id;
4720 /* issue foreign writeback flushes for recorded foreign dirtying events */
4721 void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
4723 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4724 unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
4725 u64 now = jiffies_64;
4728 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4729 struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
4732 * If the record is older than dirty_expire_interval,
4733 * writeback on it has already started. No need to kick it
4734 * off again. Also, don't start a new one if there's
4735 * already one in flight.
4737 if (time_after64(frn->at, now - intv) &&
4738 atomic_read(&frn->done.cnt) == 1) {
4740 trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
4741 cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id,
4742 WB_REASON_FOREIGN_FLUSH,
4748 #else /* CONFIG_CGROUP_WRITEBACK */
4750 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4755 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4759 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4763 #endif /* CONFIG_CGROUP_WRITEBACK */
4766 * DO NOT USE IN NEW FILES.
4768 * "cgroup.event_control" implementation.
4770 * This is way over-engineered. It tries to support fully configurable
4771 * events for each user. Such level of flexibility is completely
4772 * unnecessary especially in the light of the planned unified hierarchy.
4774 * Please deprecate this and replace with something simpler if at all
4779 * Unregister event and free resources.
4781 * Gets called from workqueue.
4783 static void memcg_event_remove(struct work_struct *work)
4785 struct mem_cgroup_event *event =
4786 container_of(work, struct mem_cgroup_event, remove);
4787 struct mem_cgroup *memcg = event->memcg;
4789 remove_wait_queue(event->wqh, &event->wait);
4791 event->unregister_event(memcg, event->eventfd);
4793 /* Notify userspace the event is going away. */
4794 eventfd_signal(event->eventfd, 1);
4796 eventfd_ctx_put(event->eventfd);
4798 css_put(&memcg->css);
4802 * Gets called on EPOLLHUP on eventfd when user closes it.
4804 * Called with wqh->lock held and interrupts disabled.
4806 static int memcg_event_wake(wait_queue_entry_t *wait, unsigned mode,
4807 int sync, void *key)
4809 struct mem_cgroup_event *event =
4810 container_of(wait, struct mem_cgroup_event, wait);
4811 struct mem_cgroup *memcg = event->memcg;
4812 __poll_t flags = key_to_poll(key);
4814 if (flags & EPOLLHUP) {
4816 * If the event has been detached at cgroup removal, we
4817 * can simply return knowing the other side will cleanup
4820 * We can't race against event freeing since the other
4821 * side will require wqh->lock via remove_wait_queue(),
4824 spin_lock(&memcg->event_list_lock);
4825 if (!list_empty(&event->list)) {
4826 list_del_init(&event->list);
4828 * We are in atomic context, but cgroup_event_remove()
4829 * may sleep, so we have to call it in workqueue.
4831 schedule_work(&event->remove);
4833 spin_unlock(&memcg->event_list_lock);
4839 static void memcg_event_ptable_queue_proc(struct file *file,
4840 wait_queue_head_t *wqh, poll_table *pt)
4842 struct mem_cgroup_event *event =
4843 container_of(pt, struct mem_cgroup_event, pt);
4846 add_wait_queue(wqh, &event->wait);
4850 * DO NOT USE IN NEW FILES.
4852 * Parse input and register new cgroup event handler.
4854 * Input must be in format '<event_fd> <control_fd> <args>'.
4855 * Interpretation of args is defined by control file implementation.
4857 static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
4858 char *buf, size_t nbytes, loff_t off)
4860 struct cgroup_subsys_state *css = of_css(of);
4861 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4862 struct mem_cgroup_event *event;
4863 struct cgroup_subsys_state *cfile_css;
4864 unsigned int efd, cfd;
4867 struct dentry *cdentry;
4872 if (IS_ENABLED(CONFIG_PREEMPT_RT))
4875 buf = strstrip(buf);
4877 efd = simple_strtoul(buf, &endp, 10);
4882 cfd = simple_strtoul(buf, &endp, 10);
4883 if ((*endp != ' ') && (*endp != '\0'))
4887 event = kzalloc(sizeof(*event), GFP_KERNEL);
4891 event->memcg = memcg;
4892 INIT_LIST_HEAD(&event->list);
4893 init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
4894 init_waitqueue_func_entry(&event->wait, memcg_event_wake);
4895 INIT_WORK(&event->remove, memcg_event_remove);
4903 event->eventfd = eventfd_ctx_fileget(efile.file);
4904 if (IS_ERR(event->eventfd)) {
4905 ret = PTR_ERR(event->eventfd);
4912 goto out_put_eventfd;
4915 /* the process need read permission on control file */
4916 /* AV: shouldn't we check that it's been opened for read instead? */
4917 ret = file_permission(cfile.file, MAY_READ);
4922 * The control file must be a regular cgroup1 file. As a regular cgroup
4923 * file can't be renamed, it's safe to access its name afterwards.
4925 cdentry = cfile.file->f_path.dentry;
4926 if (cdentry->d_sb->s_type != &cgroup_fs_type || !d_is_reg(cdentry)) {
4932 * Determine the event callbacks and set them in @event. This used
4933 * to be done via struct cftype but cgroup core no longer knows
4934 * about these events. The following is crude but the whole thing
4935 * is for compatibility anyway.
4937 * DO NOT ADD NEW FILES.
4939 name = cdentry->d_name.name;
4941 if (!strcmp(name, "memory.usage_in_bytes")) {
4942 event->register_event = mem_cgroup_usage_register_event;
4943 event->unregister_event = mem_cgroup_usage_unregister_event;
4944 } else if (!strcmp(name, "memory.oom_control")) {
4945 event->register_event = mem_cgroup_oom_register_event;
4946 event->unregister_event = mem_cgroup_oom_unregister_event;
4947 } else if (!strcmp(name, "memory.pressure_level")) {
4948 event->register_event = vmpressure_register_event;
4949 event->unregister_event = vmpressure_unregister_event;
4950 } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
4951 event->register_event = memsw_cgroup_usage_register_event;
4952 event->unregister_event = memsw_cgroup_usage_unregister_event;
4959 * Verify @cfile should belong to @css. Also, remaining events are
4960 * automatically removed on cgroup destruction but the removal is
4961 * asynchronous, so take an extra ref on @css.
4963 cfile_css = css_tryget_online_from_dir(cdentry->d_parent,
4964 &memory_cgrp_subsys);
4966 if (IS_ERR(cfile_css))
4968 if (cfile_css != css) {
4973 ret = event->register_event(memcg, event->eventfd, buf);
4977 vfs_poll(efile.file, &event->pt);
4979 spin_lock_irq(&memcg->event_list_lock);
4980 list_add(&event->list, &memcg->event_list);
4981 spin_unlock_irq(&memcg->event_list_lock);
4993 eventfd_ctx_put(event->eventfd);
5002 #if defined(CONFIG_MEMCG_KMEM) && (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG))
5003 static int mem_cgroup_slab_show(struct seq_file *m, void *p)
5007 * Please, take a look at tools/cgroup/memcg_slabinfo.py .
5013 static int memory_stat_show(struct seq_file *m, void *v);
5015 static struct cftype mem_cgroup_legacy_files[] = {
5017 .name = "usage_in_bytes",
5018 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
5019 .read_u64 = mem_cgroup_read_u64,
5022 .name = "max_usage_in_bytes",
5023 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
5024 .write = mem_cgroup_reset,
5025 .read_u64 = mem_cgroup_read_u64,
5028 .name = "limit_in_bytes",
5029 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
5030 .write = mem_cgroup_write,
5031 .read_u64 = mem_cgroup_read_u64,
5034 .name = "soft_limit_in_bytes",
5035 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
5036 .write = mem_cgroup_write,
5037 .read_u64 = mem_cgroup_read_u64,
5041 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
5042 .write = mem_cgroup_reset,
5043 .read_u64 = mem_cgroup_read_u64,
5047 .seq_show = memory_stat_show,
5050 .name = "force_empty",
5051 .write = mem_cgroup_force_empty_write,
5054 .name = "use_hierarchy",
5055 .write_u64 = mem_cgroup_hierarchy_write,
5056 .read_u64 = mem_cgroup_hierarchy_read,
5059 .name = "cgroup.event_control", /* XXX: for compat */
5060 .write = memcg_write_event_control,
5061 .flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE,
5064 .name = "swappiness",
5065 .read_u64 = mem_cgroup_swappiness_read,
5066 .write_u64 = mem_cgroup_swappiness_write,
5069 .name = "move_charge_at_immigrate",
5070 .read_u64 = mem_cgroup_move_charge_read,
5071 .write_u64 = mem_cgroup_move_charge_write,
5074 .name = "oom_control",
5075 .seq_show = mem_cgroup_oom_control_read,
5076 .write_u64 = mem_cgroup_oom_control_write,
5079 .name = "pressure_level",
5080 .seq_show = mem_cgroup_dummy_seq_show,
5084 .name = "numa_stat",
5085 .seq_show = memcg_numa_stat_show,
5089 .name = "kmem.limit_in_bytes",
5090 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
5091 .write = mem_cgroup_write,
5092 .read_u64 = mem_cgroup_read_u64,
5095 .name = "kmem.usage_in_bytes",
5096 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
5097 .read_u64 = mem_cgroup_read_u64,
5100 .name = "kmem.failcnt",
5101 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
5102 .write = mem_cgroup_reset,
5103 .read_u64 = mem_cgroup_read_u64,
5106 .name = "kmem.max_usage_in_bytes",
5107 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
5108 .write = mem_cgroup_reset,
5109 .read_u64 = mem_cgroup_read_u64,
5111 #if defined(CONFIG_MEMCG_KMEM) && \
5112 (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG))
5114 .name = "kmem.slabinfo",
5115 .seq_show = mem_cgroup_slab_show,
5119 .name = "kmem.tcp.limit_in_bytes",
5120 .private = MEMFILE_PRIVATE(_TCP, RES_LIMIT),
5121 .write = mem_cgroup_write,
5122 .read_u64 = mem_cgroup_read_u64,
5125 .name = "kmem.tcp.usage_in_bytes",
5126 .private = MEMFILE_PRIVATE(_TCP, RES_USAGE),
5127 .read_u64 = mem_cgroup_read_u64,
5130 .name = "kmem.tcp.failcnt",
5131 .private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT),
5132 .write = mem_cgroup_reset,
5133 .read_u64 = mem_cgroup_read_u64,
5136 .name = "kmem.tcp.max_usage_in_bytes",
5137 .private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE),
5138 .write = mem_cgroup_reset,
5139 .read_u64 = mem_cgroup_read_u64,
5141 { }, /* terminate */
5145 * Private memory cgroup IDR
5147 * Swap-out records and page cache shadow entries need to store memcg
5148 * references in constrained space, so we maintain an ID space that is
5149 * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
5150 * memory-controlled cgroups to 64k.
5152 * However, there usually are many references to the offline CSS after
5153 * the cgroup has been destroyed, such as page cache or reclaimable
5154 * slab objects, that don't need to hang on to the ID. We want to keep
5155 * those dead CSS from occupying IDs, or we might quickly exhaust the
5156 * relatively small ID space and prevent the creation of new cgroups
5157 * even when there are much fewer than 64k cgroups - possibly none.
5159 * Maintain a private 16-bit ID space for memcg, and allow the ID to
5160 * be freed and recycled when it's no longer needed, which is usually
5161 * when the CSS is offlined.
5163 * The only exception to that are records of swapped out tmpfs/shmem
5164 * pages that need to be attributed to live ancestors on swapin. But
5165 * those references are manageable from userspace.
5168 static DEFINE_IDR(mem_cgroup_idr);
5170 static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
5172 if (memcg->id.id > 0) {
5173 idr_remove(&mem_cgroup_idr, memcg->id.id);
5178 static void __maybe_unused mem_cgroup_id_get_many(struct mem_cgroup *memcg,
5181 refcount_add(n, &memcg->id.ref);
5184 static void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
5186 if (refcount_sub_and_test(n, &memcg->id.ref)) {
5187 mem_cgroup_id_remove(memcg);
5189 /* Memcg ID pins CSS */
5190 css_put(&memcg->css);
5194 static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
5196 mem_cgroup_id_put_many(memcg, 1);
5200 * mem_cgroup_from_id - look up a memcg from a memcg id
5201 * @id: the memcg id to look up
5203 * Caller must hold rcu_read_lock().
5205 struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
5207 WARN_ON_ONCE(!rcu_read_lock_held());
5208 return idr_find(&mem_cgroup_idr, id);
5211 #ifdef CONFIG_SHRINKER_DEBUG
5212 struct mem_cgroup *mem_cgroup_get_from_ino(unsigned long ino)
5214 struct cgroup *cgrp;
5215 struct cgroup_subsys_state *css;
5216 struct mem_cgroup *memcg;
5218 cgrp = cgroup_get_from_id(ino);
5220 return ERR_CAST(cgrp);
5222 css = cgroup_get_e_css(cgrp, &memory_cgrp_subsys);
5224 memcg = container_of(css, struct mem_cgroup, css);
5226 memcg = ERR_PTR(-ENOENT);
5234 static int alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5236 struct mem_cgroup_per_node *pn;
5238 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, node);
5242 pn->lruvec_stats_percpu = alloc_percpu_gfp(struct lruvec_stats_percpu,
5243 GFP_KERNEL_ACCOUNT);
5244 if (!pn->lruvec_stats_percpu) {
5249 lruvec_init(&pn->lruvec);
5252 memcg->nodeinfo[node] = pn;
5256 static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5258 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
5263 free_percpu(pn->lruvec_stats_percpu);
5267 static void __mem_cgroup_free(struct mem_cgroup *memcg)
5272 free_mem_cgroup_per_node_info(memcg, node);
5273 kfree(memcg->vmstats);
5274 free_percpu(memcg->vmstats_percpu);
5278 static void mem_cgroup_free(struct mem_cgroup *memcg)
5280 lru_gen_exit_memcg(memcg);
5281 memcg_wb_domain_exit(memcg);
5282 __mem_cgroup_free(memcg);
5285 static struct mem_cgroup *mem_cgroup_alloc(void)
5287 struct mem_cgroup *memcg;
5289 int __maybe_unused i;
5290 long error = -ENOMEM;
5292 memcg = kzalloc(struct_size(memcg, nodeinfo, nr_node_ids), GFP_KERNEL);
5294 return ERR_PTR(error);
5296 memcg->id.id = idr_alloc(&mem_cgroup_idr, NULL,
5297 1, MEM_CGROUP_ID_MAX + 1, GFP_KERNEL);
5298 if (memcg->id.id < 0) {
5299 error = memcg->id.id;
5303 memcg->vmstats = kzalloc(sizeof(struct memcg_vmstats), GFP_KERNEL);
5304 if (!memcg->vmstats)
5307 memcg->vmstats_percpu = alloc_percpu_gfp(struct memcg_vmstats_percpu,
5308 GFP_KERNEL_ACCOUNT);
5309 if (!memcg->vmstats_percpu)
5313 if (alloc_mem_cgroup_per_node_info(memcg, node))
5316 if (memcg_wb_domain_init(memcg, GFP_KERNEL))
5319 INIT_WORK(&memcg->high_work, high_work_func);
5320 INIT_LIST_HEAD(&memcg->oom_notify);
5321 mutex_init(&memcg->thresholds_lock);
5322 spin_lock_init(&memcg->move_lock);
5323 vmpressure_init(&memcg->vmpressure);
5324 INIT_LIST_HEAD(&memcg->event_list);
5325 spin_lock_init(&memcg->event_list_lock);
5326 memcg->socket_pressure = jiffies;
5327 #ifdef CONFIG_MEMCG_KMEM
5328 memcg->kmemcg_id = -1;
5329 INIT_LIST_HEAD(&memcg->objcg_list);
5331 #ifdef CONFIG_CGROUP_WRITEBACK
5332 INIT_LIST_HEAD(&memcg->cgwb_list);
5333 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5334 memcg->cgwb_frn[i].done =
5335 __WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
5337 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5338 spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
5339 INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
5340 memcg->deferred_split_queue.split_queue_len = 0;
5342 idr_replace(&mem_cgroup_idr, memcg, memcg->id.id);
5343 lru_gen_init_memcg(memcg);
5346 mem_cgroup_id_remove(memcg);
5347 __mem_cgroup_free(memcg);
5348 return ERR_PTR(error);
5351 static struct cgroup_subsys_state * __ref
5352 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
5354 struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
5355 struct mem_cgroup *memcg, *old_memcg;
5357 old_memcg = set_active_memcg(parent);
5358 memcg = mem_cgroup_alloc();
5359 set_active_memcg(old_memcg);
5361 return ERR_CAST(memcg);
5363 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5364 WRITE_ONCE(memcg->soft_limit, PAGE_COUNTER_MAX);
5365 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
5366 memcg->zswap_max = PAGE_COUNTER_MAX;
5368 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5370 WRITE_ONCE(memcg->swappiness, mem_cgroup_swappiness(parent));
5371 WRITE_ONCE(memcg->oom_kill_disable, READ_ONCE(parent->oom_kill_disable));
5373 page_counter_init(&memcg->memory, &parent->memory);
5374 page_counter_init(&memcg->swap, &parent->swap);
5375 page_counter_init(&memcg->kmem, &parent->kmem);
5376 page_counter_init(&memcg->tcpmem, &parent->tcpmem);
5378 init_memcg_events();
5379 page_counter_init(&memcg->memory, NULL);
5380 page_counter_init(&memcg->swap, NULL);
5381 page_counter_init(&memcg->kmem, NULL);
5382 page_counter_init(&memcg->tcpmem, NULL);
5384 root_mem_cgroup = memcg;
5388 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5389 static_branch_inc(&memcg_sockets_enabled_key);
5391 #if defined(CONFIG_MEMCG_KMEM)
5392 if (!cgroup_memory_nobpf)
5393 static_branch_inc(&memcg_bpf_enabled_key);
5399 static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
5401 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5403 if (memcg_online_kmem(memcg))
5407 * A memcg must be visible for expand_shrinker_info()
5408 * by the time the maps are allocated. So, we allocate maps
5409 * here, when for_each_mem_cgroup() can't skip it.
5411 if (alloc_shrinker_info(memcg))
5414 /* Online state pins memcg ID, memcg ID pins CSS */
5415 refcount_set(&memcg->id.ref, 1);
5418 if (unlikely(mem_cgroup_is_root(memcg)))
5419 queue_delayed_work(system_unbound_wq, &stats_flush_dwork,
5421 lru_gen_online_memcg(memcg);
5424 memcg_offline_kmem(memcg);
5426 mem_cgroup_id_remove(memcg);
5430 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
5432 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5433 struct mem_cgroup_event *event, *tmp;
5436 * Unregister events and notify userspace.
5437 * Notify userspace about cgroup removing only after rmdir of cgroup
5438 * directory to avoid race between userspace and kernelspace.
5440 spin_lock_irq(&memcg->event_list_lock);
5441 list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
5442 list_del_init(&event->list);
5443 schedule_work(&event->remove);
5445 spin_unlock_irq(&memcg->event_list_lock);
5447 page_counter_set_min(&memcg->memory, 0);
5448 page_counter_set_low(&memcg->memory, 0);
5450 memcg_offline_kmem(memcg);
5451 reparent_shrinker_deferred(memcg);
5452 wb_memcg_offline(memcg);
5453 lru_gen_offline_memcg(memcg);
5455 drain_all_stock(memcg);
5457 mem_cgroup_id_put(memcg);
5460 static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
5462 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5464 invalidate_reclaim_iterators(memcg);
5465 lru_gen_release_memcg(memcg);
5468 static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
5470 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5471 int __maybe_unused i;
5473 #ifdef CONFIG_CGROUP_WRITEBACK
5474 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5475 wb_wait_for_completion(&memcg->cgwb_frn[i].done);
5477 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5478 static_branch_dec(&memcg_sockets_enabled_key);
5480 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg->tcpmem_active)
5481 static_branch_dec(&memcg_sockets_enabled_key);
5483 #if defined(CONFIG_MEMCG_KMEM)
5484 if (!cgroup_memory_nobpf)
5485 static_branch_dec(&memcg_bpf_enabled_key);
5488 vmpressure_cleanup(&memcg->vmpressure);
5489 cancel_work_sync(&memcg->high_work);
5490 mem_cgroup_remove_from_trees(memcg);
5491 free_shrinker_info(memcg);
5492 mem_cgroup_free(memcg);
5496 * mem_cgroup_css_reset - reset the states of a mem_cgroup
5497 * @css: the target css
5499 * Reset the states of the mem_cgroup associated with @css. This is
5500 * invoked when the userland requests disabling on the default hierarchy
5501 * but the memcg is pinned through dependency. The memcg should stop
5502 * applying policies and should revert to the vanilla state as it may be
5503 * made visible again.
5505 * The current implementation only resets the essential configurations.
5506 * This needs to be expanded to cover all the visible parts.
5508 static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
5510 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5512 page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
5513 page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
5514 page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
5515 page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
5516 page_counter_set_min(&memcg->memory, 0);
5517 page_counter_set_low(&memcg->memory, 0);
5518 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5519 WRITE_ONCE(memcg->soft_limit, PAGE_COUNTER_MAX);
5520 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5521 memcg_wb_domain_size_changed(memcg);
5524 static void mem_cgroup_css_rstat_flush(struct cgroup_subsys_state *css, int cpu)
5526 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5527 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
5528 struct memcg_vmstats_percpu *statc;
5532 statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
5534 for (i = 0; i < MEMCG_NR_STAT; i++) {
5536 * Collect the aggregated propagation counts of groups
5537 * below us. We're in a per-cpu loop here and this is
5538 * a global counter, so the first cycle will get them.
5540 delta = memcg->vmstats->state_pending[i];
5542 memcg->vmstats->state_pending[i] = 0;
5544 /* Add CPU changes on this level since the last flush */
5545 v = READ_ONCE(statc->state[i]);
5546 if (v != statc->state_prev[i]) {
5547 delta += v - statc->state_prev[i];
5548 statc->state_prev[i] = v;
5554 /* Aggregate counts on this level and propagate upwards */
5555 memcg->vmstats->state[i] += delta;
5557 parent->vmstats->state_pending[i] += delta;
5560 for (i = 0; i < NR_MEMCG_EVENTS; i++) {
5561 delta = memcg->vmstats->events_pending[i];
5563 memcg->vmstats->events_pending[i] = 0;
5565 v = READ_ONCE(statc->events[i]);
5566 if (v != statc->events_prev[i]) {
5567 delta += v - statc->events_prev[i];
5568 statc->events_prev[i] = v;
5574 memcg->vmstats->events[i] += delta;
5576 parent->vmstats->events_pending[i] += delta;
5579 for_each_node_state(nid, N_MEMORY) {
5580 struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
5581 struct mem_cgroup_per_node *ppn = NULL;
5582 struct lruvec_stats_percpu *lstatc;
5585 ppn = parent->nodeinfo[nid];
5587 lstatc = per_cpu_ptr(pn->lruvec_stats_percpu, cpu);
5589 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++) {
5590 delta = pn->lruvec_stats.state_pending[i];
5592 pn->lruvec_stats.state_pending[i] = 0;
5594 v = READ_ONCE(lstatc->state[i]);
5595 if (v != lstatc->state_prev[i]) {
5596 delta += v - lstatc->state_prev[i];
5597 lstatc->state_prev[i] = v;
5603 pn->lruvec_stats.state[i] += delta;
5605 ppn->lruvec_stats.state_pending[i] += delta;
5611 /* Handlers for move charge at task migration. */
5612 static int mem_cgroup_do_precharge(unsigned long count)
5616 /* Try a single bulk charge without reclaim first, kswapd may wake */
5617 ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count);
5619 mc.precharge += count;
5623 /* Try charges one by one with reclaim, but do not retry */
5625 ret = try_charge(mc.to, GFP_KERNEL | __GFP_NORETRY, 1);
5639 enum mc_target_type {
5646 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5647 unsigned long addr, pte_t ptent)
5649 struct page *page = vm_normal_page(vma, addr, ptent);
5651 if (!page || !page_mapped(page))
5653 if (PageAnon(page)) {
5654 if (!(mc.flags & MOVE_ANON))
5657 if (!(mc.flags & MOVE_FILE))
5660 if (!get_page_unless_zero(page))
5666 #if defined(CONFIG_SWAP) || defined(CONFIG_DEVICE_PRIVATE)
5667 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5668 pte_t ptent, swp_entry_t *entry)
5670 struct page *page = NULL;
5671 swp_entry_t ent = pte_to_swp_entry(ptent);
5673 if (!(mc.flags & MOVE_ANON))
5677 * Handle device private pages that are not accessible by the CPU, but
5678 * stored as special swap entries in the page table.
5680 if (is_device_private_entry(ent)) {
5681 page = pfn_swap_entry_to_page(ent);
5682 if (!get_page_unless_zero(page))
5687 if (non_swap_entry(ent))
5691 * Because swap_cache_get_folio() updates some statistics counter,
5692 * we call find_get_page() with swapper_space directly.
5694 page = find_get_page(swap_address_space(ent), swp_offset(ent));
5695 entry->val = ent.val;
5700 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5701 pte_t ptent, swp_entry_t *entry)
5707 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5708 unsigned long addr, pte_t ptent)
5710 unsigned long index;
5711 struct folio *folio;
5713 if (!vma->vm_file) /* anonymous vma */
5715 if (!(mc.flags & MOVE_FILE))
5718 /* folio is moved even if it's not RSS of this task(page-faulted). */
5719 /* shmem/tmpfs may report page out on swap: account for that too. */
5720 index = linear_page_index(vma, addr);
5721 folio = filemap_get_incore_folio(vma->vm_file->f_mapping, index);
5724 return folio_file_page(folio, index);
5728 * mem_cgroup_move_account - move account of the page
5730 * @compound: charge the page as compound or small page
5731 * @from: mem_cgroup which the page is moved from.
5732 * @to: mem_cgroup which the page is moved to. @from != @to.
5734 * The page must be locked and not on the LRU.
5736 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
5739 static int mem_cgroup_move_account(struct page *page,
5741 struct mem_cgroup *from,
5742 struct mem_cgroup *to)
5744 struct folio *folio = page_folio(page);
5745 struct lruvec *from_vec, *to_vec;
5746 struct pglist_data *pgdat;
5747 unsigned int nr_pages = compound ? folio_nr_pages(folio) : 1;
5750 VM_BUG_ON(from == to);
5751 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
5752 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
5753 VM_BUG_ON(compound && !folio_test_large(folio));
5756 if (folio_memcg(folio) != from)
5759 pgdat = folio_pgdat(folio);
5760 from_vec = mem_cgroup_lruvec(from, pgdat);
5761 to_vec = mem_cgroup_lruvec(to, pgdat);
5763 folio_memcg_lock(folio);
5765 if (folio_test_anon(folio)) {
5766 if (folio_mapped(folio)) {
5767 __mod_lruvec_state(from_vec, NR_ANON_MAPPED, -nr_pages);
5768 __mod_lruvec_state(to_vec, NR_ANON_MAPPED, nr_pages);
5769 if (folio_test_transhuge(folio)) {
5770 __mod_lruvec_state(from_vec, NR_ANON_THPS,
5772 __mod_lruvec_state(to_vec, NR_ANON_THPS,
5777 __mod_lruvec_state(from_vec, NR_FILE_PAGES, -nr_pages);
5778 __mod_lruvec_state(to_vec, NR_FILE_PAGES, nr_pages);
5780 if (folio_test_swapbacked(folio)) {
5781 __mod_lruvec_state(from_vec, NR_SHMEM, -nr_pages);
5782 __mod_lruvec_state(to_vec, NR_SHMEM, nr_pages);
5785 if (folio_mapped(folio)) {
5786 __mod_lruvec_state(from_vec, NR_FILE_MAPPED, -nr_pages);
5787 __mod_lruvec_state(to_vec, NR_FILE_MAPPED, nr_pages);
5790 if (folio_test_dirty(folio)) {
5791 struct address_space *mapping = folio_mapping(folio);
5793 if (mapping_can_writeback(mapping)) {
5794 __mod_lruvec_state(from_vec, NR_FILE_DIRTY,
5796 __mod_lruvec_state(to_vec, NR_FILE_DIRTY,
5803 if (folio_test_swapcache(folio)) {
5804 __mod_lruvec_state(from_vec, NR_SWAPCACHE, -nr_pages);
5805 __mod_lruvec_state(to_vec, NR_SWAPCACHE, nr_pages);
5808 if (folio_test_writeback(folio)) {
5809 __mod_lruvec_state(from_vec, NR_WRITEBACK, -nr_pages);
5810 __mod_lruvec_state(to_vec, NR_WRITEBACK, nr_pages);
5814 * All state has been migrated, let's switch to the new memcg.
5816 * It is safe to change page's memcg here because the page
5817 * is referenced, charged, isolated, and locked: we can't race
5818 * with (un)charging, migration, LRU putback, or anything else
5819 * that would rely on a stable page's memory cgroup.
5821 * Note that folio_memcg_lock is a memcg lock, not a page lock,
5822 * to save space. As soon as we switch page's memory cgroup to a
5823 * new memcg that isn't locked, the above state can change
5824 * concurrently again. Make sure we're truly done with it.
5829 css_put(&from->css);
5831 folio->memcg_data = (unsigned long)to;
5833 __folio_memcg_unlock(from);
5836 nid = folio_nid(folio);
5838 local_irq_disable();
5839 mem_cgroup_charge_statistics(to, nr_pages);
5840 memcg_check_events(to, nid);
5841 mem_cgroup_charge_statistics(from, -nr_pages);
5842 memcg_check_events(from, nid);
5849 * get_mctgt_type - get target type of moving charge
5850 * @vma: the vma the pte to be checked belongs
5851 * @addr: the address corresponding to the pte to be checked
5852 * @ptent: the pte to be checked
5853 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5856 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5857 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5858 * move charge. if @target is not NULL, the page is stored in target->page
5859 * with extra refcnt got(Callers should handle it).
5860 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5861 * target for charge migration. if @target is not NULL, the entry is stored
5863 * 3(MC_TARGET_DEVICE): like MC_TARGET_PAGE but page is device memory and
5864 * thus not on the lru.
5865 * For now we such page is charge like a regular page would be as for all
5866 * intent and purposes it is just special memory taking the place of a
5869 * See Documentations/vm/hmm.txt and include/linux/hmm.h
5871 * Called with pte lock held.
5874 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
5875 unsigned long addr, pte_t ptent, union mc_target *target)
5877 struct page *page = NULL;
5878 enum mc_target_type ret = MC_TARGET_NONE;
5879 swp_entry_t ent = { .val = 0 };
5881 if (pte_present(ptent))
5882 page = mc_handle_present_pte(vma, addr, ptent);
5883 else if (pte_none_mostly(ptent))
5885 * PTE markers should be treated as a none pte here, separated
5886 * from other swap handling below.
5888 page = mc_handle_file_pte(vma, addr, ptent);
5889 else if (is_swap_pte(ptent))
5890 page = mc_handle_swap_pte(vma, ptent, &ent);
5892 if (target && page) {
5893 if (!trylock_page(page)) {
5898 * page_mapped() must be stable during the move. This
5899 * pte is locked, so if it's present, the page cannot
5900 * become unmapped. If it isn't, we have only partial
5901 * control over the mapped state: the page lock will
5902 * prevent new faults against pagecache and swapcache,
5903 * so an unmapped page cannot become mapped. However,
5904 * if the page is already mapped elsewhere, it can
5905 * unmap, and there is nothing we can do about it.
5906 * Alas, skip moving the page in this case.
5908 if (!pte_present(ptent) && page_mapped(page)) {
5915 if (!page && !ent.val)
5919 * Do only loose check w/o serialization.
5920 * mem_cgroup_move_account() checks the page is valid or
5921 * not under LRU exclusion.
5923 if (page_memcg(page) == mc.from) {
5924 ret = MC_TARGET_PAGE;
5925 if (is_device_private_page(page) ||
5926 is_device_coherent_page(page))
5927 ret = MC_TARGET_DEVICE;
5929 target->page = page;
5931 if (!ret || !target) {
5938 * There is a swap entry and a page doesn't exist or isn't charged.
5939 * But we cannot move a tail-page in a THP.
5941 if (ent.val && !ret && (!page || !PageTransCompound(page)) &&
5942 mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
5943 ret = MC_TARGET_SWAP;
5950 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5952 * We don't consider PMD mapped swapping or file mapped pages because THP does
5953 * not support them for now.
5954 * Caller should make sure that pmd_trans_huge(pmd) is true.
5956 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5957 unsigned long addr, pmd_t pmd, union mc_target *target)
5959 struct page *page = NULL;
5960 enum mc_target_type ret = MC_TARGET_NONE;
5962 if (unlikely(is_swap_pmd(pmd))) {
5963 VM_BUG_ON(thp_migration_supported() &&
5964 !is_pmd_migration_entry(pmd));
5967 page = pmd_page(pmd);
5968 VM_BUG_ON_PAGE(!page || !PageHead(page), page);
5969 if (!(mc.flags & MOVE_ANON))
5971 if (page_memcg(page) == mc.from) {
5972 ret = MC_TARGET_PAGE;
5975 if (!trylock_page(page)) {
5977 return MC_TARGET_NONE;
5979 target->page = page;
5985 static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5986 unsigned long addr, pmd_t pmd, union mc_target *target)
5988 return MC_TARGET_NONE;
5992 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5993 unsigned long addr, unsigned long end,
5994 struct mm_walk *walk)
5996 struct vm_area_struct *vma = walk->vma;
6000 ptl = pmd_trans_huge_lock(pmd, vma);
6003 * Note their can not be MC_TARGET_DEVICE for now as we do not
6004 * support transparent huge page with MEMORY_DEVICE_PRIVATE but
6005 * this might change.
6007 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
6008 mc.precharge += HPAGE_PMD_NR;
6013 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6016 for (; addr != end; pte++, addr += PAGE_SIZE)
6017 if (get_mctgt_type(vma, addr, ptep_get(pte), NULL))
6018 mc.precharge++; /* increment precharge temporarily */
6019 pte_unmap_unlock(pte - 1, ptl);
6025 static const struct mm_walk_ops precharge_walk_ops = {
6026 .pmd_entry = mem_cgroup_count_precharge_pte_range,
6029 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
6031 unsigned long precharge;
6034 walk_page_range(mm, 0, ULONG_MAX, &precharge_walk_ops, NULL);
6035 mmap_read_unlock(mm);
6037 precharge = mc.precharge;
6043 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
6045 unsigned long precharge = mem_cgroup_count_precharge(mm);
6047 VM_BUG_ON(mc.moving_task);
6048 mc.moving_task = current;
6049 return mem_cgroup_do_precharge(precharge);
6052 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
6053 static void __mem_cgroup_clear_mc(void)
6055 struct mem_cgroup *from = mc.from;
6056 struct mem_cgroup *to = mc.to;
6058 /* we must uncharge all the leftover precharges from mc.to */
6060 cancel_charge(mc.to, mc.precharge);
6064 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
6065 * we must uncharge here.
6067 if (mc.moved_charge) {
6068 cancel_charge(mc.from, mc.moved_charge);
6069 mc.moved_charge = 0;
6071 /* we must fixup refcnts and charges */
6072 if (mc.moved_swap) {
6073 /* uncharge swap account from the old cgroup */
6074 if (!mem_cgroup_is_root(mc.from))
6075 page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
6077 mem_cgroup_id_put_many(mc.from, mc.moved_swap);
6080 * we charged both to->memory and to->memsw, so we
6081 * should uncharge to->memory.
6083 if (!mem_cgroup_is_root(mc.to))
6084 page_counter_uncharge(&mc.to->memory, mc.moved_swap);
6088 memcg_oom_recover(from);
6089 memcg_oom_recover(to);
6090 wake_up_all(&mc.waitq);
6093 static void mem_cgroup_clear_mc(void)
6095 struct mm_struct *mm = mc.mm;
6098 * we must clear moving_task before waking up waiters at the end of
6101 mc.moving_task = NULL;
6102 __mem_cgroup_clear_mc();
6103 spin_lock(&mc.lock);
6107 spin_unlock(&mc.lock);
6112 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
6114 struct cgroup_subsys_state *css;
6115 struct mem_cgroup *memcg = NULL; /* unneeded init to make gcc happy */
6116 struct mem_cgroup *from;
6117 struct task_struct *leader, *p;
6118 struct mm_struct *mm;
6119 unsigned long move_flags;
6122 /* charge immigration isn't supported on the default hierarchy */
6123 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
6127 * Multi-process migrations only happen on the default hierarchy
6128 * where charge immigration is not used. Perform charge
6129 * immigration if @tset contains a leader and whine if there are
6133 cgroup_taskset_for_each_leader(leader, css, tset) {
6136 memcg = mem_cgroup_from_css(css);
6142 * We are now committed to this value whatever it is. Changes in this
6143 * tunable will only affect upcoming migrations, not the current one.
6144 * So we need to save it, and keep it going.
6146 move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
6150 from = mem_cgroup_from_task(p);
6152 VM_BUG_ON(from == memcg);
6154 mm = get_task_mm(p);
6157 /* We move charges only when we move a owner of the mm */
6158 if (mm->owner == p) {
6161 VM_BUG_ON(mc.precharge);
6162 VM_BUG_ON(mc.moved_charge);
6163 VM_BUG_ON(mc.moved_swap);
6165 spin_lock(&mc.lock);
6169 mc.flags = move_flags;
6170 spin_unlock(&mc.lock);
6171 /* We set mc.moving_task later */
6173 ret = mem_cgroup_precharge_mc(mm);
6175 mem_cgroup_clear_mc();
6182 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6185 mem_cgroup_clear_mc();
6188 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
6189 unsigned long addr, unsigned long end,
6190 struct mm_walk *walk)
6193 struct vm_area_struct *vma = walk->vma;
6196 enum mc_target_type target_type;
6197 union mc_target target;
6200 ptl = pmd_trans_huge_lock(pmd, vma);
6202 if (mc.precharge < HPAGE_PMD_NR) {
6206 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
6207 if (target_type == MC_TARGET_PAGE) {
6209 if (isolate_lru_page(page)) {
6210 if (!mem_cgroup_move_account(page, true,
6212 mc.precharge -= HPAGE_PMD_NR;
6213 mc.moved_charge += HPAGE_PMD_NR;
6215 putback_lru_page(page);
6219 } else if (target_type == MC_TARGET_DEVICE) {
6221 if (!mem_cgroup_move_account(page, true,
6223 mc.precharge -= HPAGE_PMD_NR;
6224 mc.moved_charge += HPAGE_PMD_NR;
6234 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6237 for (; addr != end; addr += PAGE_SIZE) {
6238 pte_t ptent = ptep_get(pte++);
6239 bool device = false;
6245 switch (get_mctgt_type(vma, addr, ptent, &target)) {
6246 case MC_TARGET_DEVICE:
6249 case MC_TARGET_PAGE:
6252 * We can have a part of the split pmd here. Moving it
6253 * can be done but it would be too convoluted so simply
6254 * ignore such a partial THP and keep it in original
6255 * memcg. There should be somebody mapping the head.
6257 if (PageTransCompound(page))
6259 if (!device && !isolate_lru_page(page))
6261 if (!mem_cgroup_move_account(page, false,
6264 /* we uncharge from mc.from later. */
6268 putback_lru_page(page);
6269 put: /* get_mctgt_type() gets & locks the page */
6273 case MC_TARGET_SWAP:
6275 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
6277 mem_cgroup_id_get_many(mc.to, 1);
6278 /* we fixup other refcnts and charges later. */
6286 pte_unmap_unlock(pte - 1, ptl);
6291 * We have consumed all precharges we got in can_attach().
6292 * We try charge one by one, but don't do any additional
6293 * charges to mc.to if we have failed in charge once in attach()
6296 ret = mem_cgroup_do_precharge(1);
6304 static const struct mm_walk_ops charge_walk_ops = {
6305 .pmd_entry = mem_cgroup_move_charge_pte_range,
6308 static void mem_cgroup_move_charge(void)
6310 lru_add_drain_all();
6312 * Signal folio_memcg_lock() to take the memcg's move_lock
6313 * while we're moving its pages to another memcg. Then wait
6314 * for already started RCU-only updates to finish.
6316 atomic_inc(&mc.from->moving_account);
6319 if (unlikely(!mmap_read_trylock(mc.mm))) {
6321 * Someone who are holding the mmap_lock might be waiting in
6322 * waitq. So we cancel all extra charges, wake up all waiters,
6323 * and retry. Because we cancel precharges, we might not be able
6324 * to move enough charges, but moving charge is a best-effort
6325 * feature anyway, so it wouldn't be a big problem.
6327 __mem_cgroup_clear_mc();
6332 * When we have consumed all precharges and failed in doing
6333 * additional charge, the page walk just aborts.
6335 walk_page_range(mc.mm, 0, ULONG_MAX, &charge_walk_ops, NULL);
6336 mmap_read_unlock(mc.mm);
6337 atomic_dec(&mc.from->moving_account);
6340 static void mem_cgroup_move_task(void)
6343 mem_cgroup_move_charge();
6344 mem_cgroup_clear_mc();
6347 #else /* !CONFIG_MMU */
6348 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
6352 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6355 static void mem_cgroup_move_task(void)
6360 #ifdef CONFIG_LRU_GEN
6361 static void mem_cgroup_attach(struct cgroup_taskset *tset)
6363 struct task_struct *task;
6364 struct cgroup_subsys_state *css;
6366 /* find the first leader if there is any */
6367 cgroup_taskset_for_each_leader(task, css, tset)
6374 if (task->mm && READ_ONCE(task->mm->owner) == task)
6375 lru_gen_migrate_mm(task->mm);
6379 static void mem_cgroup_attach(struct cgroup_taskset *tset)
6382 #endif /* CONFIG_LRU_GEN */
6384 static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
6386 if (value == PAGE_COUNTER_MAX)
6387 seq_puts(m, "max\n");
6389 seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
6394 static u64 memory_current_read(struct cgroup_subsys_state *css,
6397 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6399 return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
6402 static u64 memory_peak_read(struct cgroup_subsys_state *css,
6405 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6407 return (u64)memcg->memory.watermark * PAGE_SIZE;
6410 static int memory_min_show(struct seq_file *m, void *v)
6412 return seq_puts_memcg_tunable(m,
6413 READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
6416 static ssize_t memory_min_write(struct kernfs_open_file *of,
6417 char *buf, size_t nbytes, loff_t off)
6419 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6423 buf = strstrip(buf);
6424 err = page_counter_memparse(buf, "max", &min);
6428 page_counter_set_min(&memcg->memory, min);
6433 static int memory_low_show(struct seq_file *m, void *v)
6435 return seq_puts_memcg_tunable(m,
6436 READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
6439 static ssize_t memory_low_write(struct kernfs_open_file *of,
6440 char *buf, size_t nbytes, loff_t off)
6442 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6446 buf = strstrip(buf);
6447 err = page_counter_memparse(buf, "max", &low);
6451 page_counter_set_low(&memcg->memory, low);
6456 static int memory_high_show(struct seq_file *m, void *v)
6458 return seq_puts_memcg_tunable(m,
6459 READ_ONCE(mem_cgroup_from_seq(m)->memory.high));
6462 static ssize_t memory_high_write(struct kernfs_open_file *of,
6463 char *buf, size_t nbytes, loff_t off)
6465 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6466 unsigned int nr_retries = MAX_RECLAIM_RETRIES;
6467 bool drained = false;
6471 buf = strstrip(buf);
6472 err = page_counter_memparse(buf, "max", &high);
6476 page_counter_set_high(&memcg->memory, high);
6479 unsigned long nr_pages = page_counter_read(&memcg->memory);
6480 unsigned long reclaimed;
6482 if (nr_pages <= high)
6485 if (signal_pending(current))
6489 drain_all_stock(memcg);
6494 reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
6495 GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP);
6497 if (!reclaimed && !nr_retries--)
6501 memcg_wb_domain_size_changed(memcg);
6505 static int memory_max_show(struct seq_file *m, void *v)
6507 return seq_puts_memcg_tunable(m,
6508 READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
6511 static ssize_t memory_max_write(struct kernfs_open_file *of,
6512 char *buf, size_t nbytes, loff_t off)
6514 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6515 unsigned int nr_reclaims = MAX_RECLAIM_RETRIES;
6516 bool drained = false;
6520 buf = strstrip(buf);
6521 err = page_counter_memparse(buf, "max", &max);
6525 xchg(&memcg->memory.max, max);
6528 unsigned long nr_pages = page_counter_read(&memcg->memory);
6530 if (nr_pages <= max)
6533 if (signal_pending(current))
6537 drain_all_stock(memcg);
6543 if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
6544 GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP))
6549 memcg_memory_event(memcg, MEMCG_OOM);
6550 if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
6554 memcg_wb_domain_size_changed(memcg);
6558 static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
6560 seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
6561 seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
6562 seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
6563 seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
6564 seq_printf(m, "oom_kill %lu\n",
6565 atomic_long_read(&events[MEMCG_OOM_KILL]));
6566 seq_printf(m, "oom_group_kill %lu\n",
6567 atomic_long_read(&events[MEMCG_OOM_GROUP_KILL]));
6570 static int memory_events_show(struct seq_file *m, void *v)
6572 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6574 __memory_events_show(m, memcg->memory_events);
6578 static int memory_events_local_show(struct seq_file *m, void *v)
6580 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6582 __memory_events_show(m, memcg->memory_events_local);
6586 static int memory_stat_show(struct seq_file *m, void *v)
6588 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6589 char *buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
6594 seq_buf_init(&s, buf, PAGE_SIZE);
6595 memory_stat_format(memcg, &s);
6602 static inline unsigned long lruvec_page_state_output(struct lruvec *lruvec,
6605 return lruvec_page_state(lruvec, item) * memcg_page_state_unit(item);
6608 static int memory_numa_stat_show(struct seq_file *m, void *v)
6611 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6613 mem_cgroup_flush_stats();
6615 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
6618 if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS)
6621 seq_printf(m, "%s", memory_stats[i].name);
6622 for_each_node_state(nid, N_MEMORY) {
6624 struct lruvec *lruvec;
6626 lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
6627 size = lruvec_page_state_output(lruvec,
6628 memory_stats[i].idx);
6629 seq_printf(m, " N%d=%llu", nid, size);
6638 static int memory_oom_group_show(struct seq_file *m, void *v)
6640 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6642 seq_printf(m, "%d\n", READ_ONCE(memcg->oom_group));
6647 static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
6648 char *buf, size_t nbytes, loff_t off)
6650 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6653 buf = strstrip(buf);
6657 ret = kstrtoint(buf, 0, &oom_group);
6661 if (oom_group != 0 && oom_group != 1)
6664 WRITE_ONCE(memcg->oom_group, oom_group);
6669 static ssize_t memory_reclaim(struct kernfs_open_file *of, char *buf,
6670 size_t nbytes, loff_t off)
6672 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6673 unsigned int nr_retries = MAX_RECLAIM_RETRIES;
6674 unsigned long nr_to_reclaim, nr_reclaimed = 0;
6675 unsigned int reclaim_options;
6678 buf = strstrip(buf);
6679 err = page_counter_memparse(buf, "", &nr_to_reclaim);
6683 reclaim_options = MEMCG_RECLAIM_MAY_SWAP | MEMCG_RECLAIM_PROACTIVE;
6684 while (nr_reclaimed < nr_to_reclaim) {
6685 unsigned long reclaimed;
6687 if (signal_pending(current))
6691 * This is the final attempt, drain percpu lru caches in the
6692 * hope of introducing more evictable pages for
6693 * try_to_free_mem_cgroup_pages().
6696 lru_add_drain_all();
6698 reclaimed = try_to_free_mem_cgroup_pages(memcg,
6699 nr_to_reclaim - nr_reclaimed,
6700 GFP_KERNEL, reclaim_options);
6702 if (!reclaimed && !nr_retries--)
6705 nr_reclaimed += reclaimed;
6711 static struct cftype memory_files[] = {
6714 .flags = CFTYPE_NOT_ON_ROOT,
6715 .read_u64 = memory_current_read,
6719 .flags = CFTYPE_NOT_ON_ROOT,
6720 .read_u64 = memory_peak_read,
6724 .flags = CFTYPE_NOT_ON_ROOT,
6725 .seq_show = memory_min_show,
6726 .write = memory_min_write,
6730 .flags = CFTYPE_NOT_ON_ROOT,
6731 .seq_show = memory_low_show,
6732 .write = memory_low_write,
6736 .flags = CFTYPE_NOT_ON_ROOT,
6737 .seq_show = memory_high_show,
6738 .write = memory_high_write,
6742 .flags = CFTYPE_NOT_ON_ROOT,
6743 .seq_show = memory_max_show,
6744 .write = memory_max_write,
6748 .flags = CFTYPE_NOT_ON_ROOT,
6749 .file_offset = offsetof(struct mem_cgroup, events_file),
6750 .seq_show = memory_events_show,
6753 .name = "events.local",
6754 .flags = CFTYPE_NOT_ON_ROOT,
6755 .file_offset = offsetof(struct mem_cgroup, events_local_file),
6756 .seq_show = memory_events_local_show,
6760 .seq_show = memory_stat_show,
6764 .name = "numa_stat",
6765 .seq_show = memory_numa_stat_show,
6769 .name = "oom.group",
6770 .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
6771 .seq_show = memory_oom_group_show,
6772 .write = memory_oom_group_write,
6776 .flags = CFTYPE_NS_DELEGATABLE,
6777 .write = memory_reclaim,
6782 struct cgroup_subsys memory_cgrp_subsys = {
6783 .css_alloc = mem_cgroup_css_alloc,
6784 .css_online = mem_cgroup_css_online,
6785 .css_offline = mem_cgroup_css_offline,
6786 .css_released = mem_cgroup_css_released,
6787 .css_free = mem_cgroup_css_free,
6788 .css_reset = mem_cgroup_css_reset,
6789 .css_rstat_flush = mem_cgroup_css_rstat_flush,
6790 .can_attach = mem_cgroup_can_attach,
6791 .attach = mem_cgroup_attach,
6792 .cancel_attach = mem_cgroup_cancel_attach,
6793 .post_attach = mem_cgroup_move_task,
6794 .dfl_cftypes = memory_files,
6795 .legacy_cftypes = mem_cgroup_legacy_files,
6800 * This function calculates an individual cgroup's effective
6801 * protection which is derived from its own memory.min/low, its
6802 * parent's and siblings' settings, as well as the actual memory
6803 * distribution in the tree.
6805 * The following rules apply to the effective protection values:
6807 * 1. At the first level of reclaim, effective protection is equal to
6808 * the declared protection in memory.min and memory.low.
6810 * 2. To enable safe delegation of the protection configuration, at
6811 * subsequent levels the effective protection is capped to the
6812 * parent's effective protection.
6814 * 3. To make complex and dynamic subtrees easier to configure, the
6815 * user is allowed to overcommit the declared protection at a given
6816 * level. If that is the case, the parent's effective protection is
6817 * distributed to the children in proportion to how much protection
6818 * they have declared and how much of it they are utilizing.
6820 * This makes distribution proportional, but also work-conserving:
6821 * if one cgroup claims much more protection than it uses memory,
6822 * the unused remainder is available to its siblings.
6824 * 4. Conversely, when the declared protection is undercommitted at a
6825 * given level, the distribution of the larger parental protection
6826 * budget is NOT proportional. A cgroup's protection from a sibling
6827 * is capped to its own memory.min/low setting.
6829 * 5. However, to allow protecting recursive subtrees from each other
6830 * without having to declare each individual cgroup's fixed share
6831 * of the ancestor's claim to protection, any unutilized -
6832 * "floating" - protection from up the tree is distributed in
6833 * proportion to each cgroup's *usage*. This makes the protection
6834 * neutral wrt sibling cgroups and lets them compete freely over
6835 * the shared parental protection budget, but it protects the
6836 * subtree as a whole from neighboring subtrees.
6838 * Note that 4. and 5. are not in conflict: 4. is about protecting
6839 * against immediate siblings whereas 5. is about protecting against
6840 * neighboring subtrees.
6842 static unsigned long effective_protection(unsigned long usage,
6843 unsigned long parent_usage,
6844 unsigned long setting,
6845 unsigned long parent_effective,
6846 unsigned long siblings_protected)
6848 unsigned long protected;
6851 protected = min(usage, setting);
6853 * If all cgroups at this level combined claim and use more
6854 * protection than what the parent affords them, distribute
6855 * shares in proportion to utilization.
6857 * We are using actual utilization rather than the statically
6858 * claimed protection in order to be work-conserving: claimed
6859 * but unused protection is available to siblings that would
6860 * otherwise get a smaller chunk than what they claimed.
6862 if (siblings_protected > parent_effective)
6863 return protected * parent_effective / siblings_protected;
6866 * Ok, utilized protection of all children is within what the
6867 * parent affords them, so we know whatever this child claims
6868 * and utilizes is effectively protected.
6870 * If there is unprotected usage beyond this value, reclaim
6871 * will apply pressure in proportion to that amount.
6873 * If there is unutilized protection, the cgroup will be fully
6874 * shielded from reclaim, but we do return a smaller value for
6875 * protection than what the group could enjoy in theory. This
6876 * is okay. With the overcommit distribution above, effective
6877 * protection is always dependent on how memory is actually
6878 * consumed among the siblings anyway.
6883 * If the children aren't claiming (all of) the protection
6884 * afforded to them by the parent, distribute the remainder in
6885 * proportion to the (unprotected) memory of each cgroup. That
6886 * way, cgroups that aren't explicitly prioritized wrt each
6887 * other compete freely over the allowance, but they are
6888 * collectively protected from neighboring trees.
6890 * We're using unprotected memory for the weight so that if
6891 * some cgroups DO claim explicit protection, we don't protect
6892 * the same bytes twice.
6894 * Check both usage and parent_usage against the respective
6895 * protected values. One should imply the other, but they
6896 * aren't read atomically - make sure the division is sane.
6898 if (!(cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT))
6900 if (parent_effective > siblings_protected &&
6901 parent_usage > siblings_protected &&
6902 usage > protected) {
6903 unsigned long unclaimed;
6905 unclaimed = parent_effective - siblings_protected;
6906 unclaimed *= usage - protected;
6907 unclaimed /= parent_usage - siblings_protected;
6916 * mem_cgroup_calculate_protection - check if memory consumption is in the normal range
6917 * @root: the top ancestor of the sub-tree being checked
6918 * @memcg: the memory cgroup to check
6920 * WARNING: This function is not stateless! It can only be used as part
6921 * of a top-down tree iteration, not for isolated queries.
6923 void mem_cgroup_calculate_protection(struct mem_cgroup *root,
6924 struct mem_cgroup *memcg)
6926 unsigned long usage, parent_usage;
6927 struct mem_cgroup *parent;
6929 if (mem_cgroup_disabled())
6933 root = root_mem_cgroup;
6936 * Effective values of the reclaim targets are ignored so they
6937 * can be stale. Have a look at mem_cgroup_protection for more
6939 * TODO: calculation should be more robust so that we do not need
6940 * that special casing.
6945 usage = page_counter_read(&memcg->memory);
6949 parent = parent_mem_cgroup(memcg);
6951 if (parent == root) {
6952 memcg->memory.emin = READ_ONCE(memcg->memory.min);
6953 memcg->memory.elow = READ_ONCE(memcg->memory.low);
6957 parent_usage = page_counter_read(&parent->memory);
6959 WRITE_ONCE(memcg->memory.emin, effective_protection(usage, parent_usage,
6960 READ_ONCE(memcg->memory.min),
6961 READ_ONCE(parent->memory.emin),
6962 atomic_long_read(&parent->memory.children_min_usage)));
6964 WRITE_ONCE(memcg->memory.elow, effective_protection(usage, parent_usage,
6965 READ_ONCE(memcg->memory.low),
6966 READ_ONCE(parent->memory.elow),
6967 atomic_long_read(&parent->memory.children_low_usage)));
6970 static int charge_memcg(struct folio *folio, struct mem_cgroup *memcg,
6973 long nr_pages = folio_nr_pages(folio);
6976 ret = try_charge(memcg, gfp, nr_pages);
6980 css_get(&memcg->css);
6981 commit_charge(folio, memcg);
6983 local_irq_disable();
6984 mem_cgroup_charge_statistics(memcg, nr_pages);
6985 memcg_check_events(memcg, folio_nid(folio));
6991 int __mem_cgroup_charge(struct folio *folio, struct mm_struct *mm, gfp_t gfp)
6993 struct mem_cgroup *memcg;
6996 memcg = get_mem_cgroup_from_mm(mm);
6997 ret = charge_memcg(folio, memcg, gfp);
6998 css_put(&memcg->css);
7004 * mem_cgroup_swapin_charge_folio - Charge a newly allocated folio for swapin.
7005 * @folio: folio to charge.
7006 * @mm: mm context of the victim
7007 * @gfp: reclaim mode
7008 * @entry: swap entry for which the folio is allocated
7010 * This function charges a folio allocated for swapin. Please call this before
7011 * adding the folio to the swapcache.
7013 * Returns 0 on success. Otherwise, an error code is returned.
7015 int mem_cgroup_swapin_charge_folio(struct folio *folio, struct mm_struct *mm,
7016 gfp_t gfp, swp_entry_t entry)
7018 struct mem_cgroup *memcg;
7022 if (mem_cgroup_disabled())
7025 id = lookup_swap_cgroup_id(entry);
7027 memcg = mem_cgroup_from_id(id);
7028 if (!memcg || !css_tryget_online(&memcg->css))
7029 memcg = get_mem_cgroup_from_mm(mm);
7032 ret = charge_memcg(folio, memcg, gfp);
7034 css_put(&memcg->css);
7039 * mem_cgroup_swapin_uncharge_swap - uncharge swap slot
7040 * @entry: swap entry for which the page is charged
7042 * Call this function after successfully adding the charged page to swapcache.
7044 * Note: This function assumes the page for which swap slot is being uncharged
7047 void mem_cgroup_swapin_uncharge_swap(swp_entry_t entry)
7050 * Cgroup1's unified memory+swap counter has been charged with the
7051 * new swapcache page, finish the transfer by uncharging the swap
7052 * slot. The swap slot would also get uncharged when it dies, but
7053 * it can stick around indefinitely and we'd count the page twice
7056 * Cgroup2 has separate resource counters for memory and swap,
7057 * so this is a non-issue here. Memory and swap charge lifetimes
7058 * correspond 1:1 to page and swap slot lifetimes: we charge the
7059 * page to memory here, and uncharge swap when the slot is freed.
7061 if (!mem_cgroup_disabled() && do_memsw_account()) {
7063 * The swap entry might not get freed for a long time,
7064 * let's not wait for it. The page already received a
7065 * memory+swap charge, drop the swap entry duplicate.
7067 mem_cgroup_uncharge_swap(entry, 1);
7071 struct uncharge_gather {
7072 struct mem_cgroup *memcg;
7073 unsigned long nr_memory;
7074 unsigned long pgpgout;
7075 unsigned long nr_kmem;
7079 static inline void uncharge_gather_clear(struct uncharge_gather *ug)
7081 memset(ug, 0, sizeof(*ug));
7084 static void uncharge_batch(const struct uncharge_gather *ug)
7086 unsigned long flags;
7088 if (ug->nr_memory) {
7089 page_counter_uncharge(&ug->memcg->memory, ug->nr_memory);
7090 if (do_memsw_account())
7091 page_counter_uncharge(&ug->memcg->memsw, ug->nr_memory);
7093 memcg_account_kmem(ug->memcg, -ug->nr_kmem);
7094 memcg_oom_recover(ug->memcg);
7097 local_irq_save(flags);
7098 __count_memcg_events(ug->memcg, PGPGOUT, ug->pgpgout);
7099 __this_cpu_add(ug->memcg->vmstats_percpu->nr_page_events, ug->nr_memory);
7100 memcg_check_events(ug->memcg, ug->nid);
7101 local_irq_restore(flags);
7103 /* drop reference from uncharge_folio */
7104 css_put(&ug->memcg->css);
7107 static void uncharge_folio(struct folio *folio, struct uncharge_gather *ug)
7110 struct mem_cgroup *memcg;
7111 struct obj_cgroup *objcg;
7113 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
7116 * Nobody should be changing or seriously looking at
7117 * folio memcg or objcg at this point, we have fully
7118 * exclusive access to the folio.
7120 if (folio_memcg_kmem(folio)) {
7121 objcg = __folio_objcg(folio);
7123 * This get matches the put at the end of the function and
7124 * kmem pages do not hold memcg references anymore.
7126 memcg = get_mem_cgroup_from_objcg(objcg);
7128 memcg = __folio_memcg(folio);
7134 if (ug->memcg != memcg) {
7137 uncharge_gather_clear(ug);
7140 ug->nid = folio_nid(folio);
7142 /* pairs with css_put in uncharge_batch */
7143 css_get(&memcg->css);
7146 nr_pages = folio_nr_pages(folio);
7148 if (folio_memcg_kmem(folio)) {
7149 ug->nr_memory += nr_pages;
7150 ug->nr_kmem += nr_pages;
7152 folio->memcg_data = 0;
7153 obj_cgroup_put(objcg);
7155 /* LRU pages aren't accounted at the root level */
7156 if (!mem_cgroup_is_root(memcg))
7157 ug->nr_memory += nr_pages;
7160 folio->memcg_data = 0;
7163 css_put(&memcg->css);
7166 void __mem_cgroup_uncharge(struct folio *folio)
7168 struct uncharge_gather ug;
7170 /* Don't touch folio->lru of any random page, pre-check: */
7171 if (!folio_memcg(folio))
7174 uncharge_gather_clear(&ug);
7175 uncharge_folio(folio, &ug);
7176 uncharge_batch(&ug);
7180 * __mem_cgroup_uncharge_list - uncharge a list of page
7181 * @page_list: list of pages to uncharge
7183 * Uncharge a list of pages previously charged with
7184 * __mem_cgroup_charge().
7186 void __mem_cgroup_uncharge_list(struct list_head *page_list)
7188 struct uncharge_gather ug;
7189 struct folio *folio;
7191 uncharge_gather_clear(&ug);
7192 list_for_each_entry(folio, page_list, lru)
7193 uncharge_folio(folio, &ug);
7195 uncharge_batch(&ug);
7199 * mem_cgroup_migrate - Charge a folio's replacement.
7200 * @old: Currently circulating folio.
7201 * @new: Replacement folio.
7203 * Charge @new as a replacement folio for @old. @old will
7204 * be uncharged upon free.
7206 * Both folios must be locked, @new->mapping must be set up.
7208 void mem_cgroup_migrate(struct folio *old, struct folio *new)
7210 struct mem_cgroup *memcg;
7211 long nr_pages = folio_nr_pages(new);
7212 unsigned long flags;
7214 VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
7215 VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
7216 VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
7217 VM_BUG_ON_FOLIO(folio_nr_pages(old) != nr_pages, new);
7219 if (mem_cgroup_disabled())
7222 /* Page cache replacement: new folio already charged? */
7223 if (folio_memcg(new))
7226 memcg = folio_memcg(old);
7227 VM_WARN_ON_ONCE_FOLIO(!memcg, old);
7231 /* Force-charge the new page. The old one will be freed soon */
7232 if (!mem_cgroup_is_root(memcg)) {
7233 page_counter_charge(&memcg->memory, nr_pages);
7234 if (do_memsw_account())
7235 page_counter_charge(&memcg->memsw, nr_pages);
7238 css_get(&memcg->css);
7239 commit_charge(new, memcg);
7241 local_irq_save(flags);
7242 mem_cgroup_charge_statistics(memcg, nr_pages);
7243 memcg_check_events(memcg, folio_nid(new));
7244 local_irq_restore(flags);
7247 DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
7248 EXPORT_SYMBOL(memcg_sockets_enabled_key);
7250 void mem_cgroup_sk_alloc(struct sock *sk)
7252 struct mem_cgroup *memcg;
7254 if (!mem_cgroup_sockets_enabled)
7257 /* Do not associate the sock with unrelated interrupted task's memcg. */
7262 memcg = mem_cgroup_from_task(current);
7263 if (mem_cgroup_is_root(memcg))
7265 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg->tcpmem_active)
7267 if (css_tryget(&memcg->css))
7268 sk->sk_memcg = memcg;
7273 void mem_cgroup_sk_free(struct sock *sk)
7276 css_put(&sk->sk_memcg->css);
7280 * mem_cgroup_charge_skmem - charge socket memory
7281 * @memcg: memcg to charge
7282 * @nr_pages: number of pages to charge
7283 * @gfp_mask: reclaim mode
7285 * Charges @nr_pages to @memcg. Returns %true if the charge fit within
7286 * @memcg's configured limit, %false if it doesn't.
7288 bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages,
7291 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
7292 struct page_counter *fail;
7294 if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) {
7295 memcg->tcpmem_pressure = 0;
7298 memcg->tcpmem_pressure = 1;
7299 if (gfp_mask & __GFP_NOFAIL) {
7300 page_counter_charge(&memcg->tcpmem, nr_pages);
7306 if (try_charge(memcg, gfp_mask, nr_pages) == 0) {
7307 mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
7315 * mem_cgroup_uncharge_skmem - uncharge socket memory
7316 * @memcg: memcg to uncharge
7317 * @nr_pages: number of pages to uncharge
7319 void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
7321 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
7322 page_counter_uncharge(&memcg->tcpmem, nr_pages);
7326 mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
7328 refill_stock(memcg, nr_pages);
7331 static int __init cgroup_memory(char *s)
7335 while ((token = strsep(&s, ",")) != NULL) {
7338 if (!strcmp(token, "nosocket"))
7339 cgroup_memory_nosocket = true;
7340 if (!strcmp(token, "nokmem"))
7341 cgroup_memory_nokmem = true;
7342 if (!strcmp(token, "nobpf"))
7343 cgroup_memory_nobpf = true;
7347 __setup("cgroup.memory=", cgroup_memory);
7350 * subsys_initcall() for memory controller.
7352 * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
7353 * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
7354 * basically everything that doesn't depend on a specific mem_cgroup structure
7355 * should be initialized from here.
7357 static int __init mem_cgroup_init(void)
7362 * Currently s32 type (can refer to struct batched_lruvec_stat) is
7363 * used for per-memcg-per-cpu caching of per-node statistics. In order
7364 * to work fine, we should make sure that the overfill threshold can't
7365 * exceed S32_MAX / PAGE_SIZE.
7367 BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE);
7369 cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
7370 memcg_hotplug_cpu_dead);
7372 for_each_possible_cpu(cpu)
7373 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
7376 for_each_node(node) {
7377 struct mem_cgroup_tree_per_node *rtpn;
7379 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, node);
7381 rtpn->rb_root = RB_ROOT;
7382 rtpn->rb_rightmost = NULL;
7383 spin_lock_init(&rtpn->lock);
7384 soft_limit_tree.rb_tree_per_node[node] = rtpn;
7389 subsys_initcall(mem_cgroup_init);
7392 static struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
7394 while (!refcount_inc_not_zero(&memcg->id.ref)) {
7396 * The root cgroup cannot be destroyed, so it's refcount must
7399 if (WARN_ON_ONCE(mem_cgroup_is_root(memcg))) {
7403 memcg = parent_mem_cgroup(memcg);
7405 memcg = root_mem_cgroup;
7411 * mem_cgroup_swapout - transfer a memsw charge to swap
7412 * @folio: folio whose memsw charge to transfer
7413 * @entry: swap entry to move the charge to
7415 * Transfer the memsw charge of @folio to @entry.
7417 void mem_cgroup_swapout(struct folio *folio, swp_entry_t entry)
7419 struct mem_cgroup *memcg, *swap_memcg;
7420 unsigned int nr_entries;
7421 unsigned short oldid;
7423 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
7424 VM_BUG_ON_FOLIO(folio_ref_count(folio), folio);
7426 if (mem_cgroup_disabled())
7429 if (!do_memsw_account())
7432 memcg = folio_memcg(folio);
7434 VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
7439 * In case the memcg owning these pages has been offlined and doesn't
7440 * have an ID allocated to it anymore, charge the closest online
7441 * ancestor for the swap instead and transfer the memory+swap charge.
7443 swap_memcg = mem_cgroup_id_get_online(memcg);
7444 nr_entries = folio_nr_pages(folio);
7445 /* Get references for the tail pages, too */
7447 mem_cgroup_id_get_many(swap_memcg, nr_entries - 1);
7448 oldid = swap_cgroup_record(entry, mem_cgroup_id(swap_memcg),
7450 VM_BUG_ON_FOLIO(oldid, folio);
7451 mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries);
7453 folio->memcg_data = 0;
7455 if (!mem_cgroup_is_root(memcg))
7456 page_counter_uncharge(&memcg->memory, nr_entries);
7458 if (memcg != swap_memcg) {
7459 if (!mem_cgroup_is_root(swap_memcg))
7460 page_counter_charge(&swap_memcg->memsw, nr_entries);
7461 page_counter_uncharge(&memcg->memsw, nr_entries);
7465 * Interrupts should be disabled here because the caller holds the
7466 * i_pages lock which is taken with interrupts-off. It is
7467 * important here to have the interrupts disabled because it is the
7468 * only synchronisation we have for updating the per-CPU variables.
7471 mem_cgroup_charge_statistics(memcg, -nr_entries);
7472 memcg_stats_unlock();
7473 memcg_check_events(memcg, folio_nid(folio));
7475 css_put(&memcg->css);
7479 * __mem_cgroup_try_charge_swap - try charging swap space for a folio
7480 * @folio: folio being added to swap
7481 * @entry: swap entry to charge
7483 * Try to charge @folio's memcg for the swap space at @entry.
7485 * Returns 0 on success, -ENOMEM on failure.
7487 int __mem_cgroup_try_charge_swap(struct folio *folio, swp_entry_t entry)
7489 unsigned int nr_pages = folio_nr_pages(folio);
7490 struct page_counter *counter;
7491 struct mem_cgroup *memcg;
7492 unsigned short oldid;
7494 if (do_memsw_account())
7497 memcg = folio_memcg(folio);
7499 VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
7504 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7508 memcg = mem_cgroup_id_get_online(memcg);
7510 if (!mem_cgroup_is_root(memcg) &&
7511 !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
7512 memcg_memory_event(memcg, MEMCG_SWAP_MAX);
7513 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7514 mem_cgroup_id_put(memcg);
7518 /* Get references for the tail pages, too */
7520 mem_cgroup_id_get_many(memcg, nr_pages - 1);
7521 oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg), nr_pages);
7522 VM_BUG_ON_FOLIO(oldid, folio);
7523 mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
7529 * __mem_cgroup_uncharge_swap - uncharge swap space
7530 * @entry: swap entry to uncharge
7531 * @nr_pages: the amount of swap space to uncharge
7533 void __mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
7535 struct mem_cgroup *memcg;
7538 if (mem_cgroup_disabled())
7541 id = swap_cgroup_record(entry, 0, nr_pages);
7543 memcg = mem_cgroup_from_id(id);
7545 if (!mem_cgroup_is_root(memcg)) {
7546 if (do_memsw_account())
7547 page_counter_uncharge(&memcg->memsw, nr_pages);
7549 page_counter_uncharge(&memcg->swap, nr_pages);
7551 mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
7552 mem_cgroup_id_put_many(memcg, nr_pages);
7557 long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
7559 long nr_swap_pages = get_nr_swap_pages();
7561 if (mem_cgroup_disabled() || do_memsw_account())
7562 return nr_swap_pages;
7563 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg))
7564 nr_swap_pages = min_t(long, nr_swap_pages,
7565 READ_ONCE(memcg->swap.max) -
7566 page_counter_read(&memcg->swap));
7567 return nr_swap_pages;
7570 bool mem_cgroup_swap_full(struct folio *folio)
7572 struct mem_cgroup *memcg;
7574 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
7578 if (do_memsw_account())
7581 memcg = folio_memcg(folio);
7585 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
7586 unsigned long usage = page_counter_read(&memcg->swap);
7588 if (usage * 2 >= READ_ONCE(memcg->swap.high) ||
7589 usage * 2 >= READ_ONCE(memcg->swap.max))
7596 static int __init setup_swap_account(char *s)
7598 pr_warn_once("The swapaccount= commandline option is deprecated. "
7599 "Please report your usecase to linux-mm@kvack.org if you "
7600 "depend on this functionality.\n");
7603 __setup("swapaccount=", setup_swap_account);
7605 static u64 swap_current_read(struct cgroup_subsys_state *css,
7608 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7610 return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
7613 static u64 swap_peak_read(struct cgroup_subsys_state *css,
7616 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7618 return (u64)memcg->swap.watermark * PAGE_SIZE;
7621 static int swap_high_show(struct seq_file *m, void *v)
7623 return seq_puts_memcg_tunable(m,
7624 READ_ONCE(mem_cgroup_from_seq(m)->swap.high));
7627 static ssize_t swap_high_write(struct kernfs_open_file *of,
7628 char *buf, size_t nbytes, loff_t off)
7630 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7634 buf = strstrip(buf);
7635 err = page_counter_memparse(buf, "max", &high);
7639 page_counter_set_high(&memcg->swap, high);
7644 static int swap_max_show(struct seq_file *m, void *v)
7646 return seq_puts_memcg_tunable(m,
7647 READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
7650 static ssize_t swap_max_write(struct kernfs_open_file *of,
7651 char *buf, size_t nbytes, loff_t off)
7653 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7657 buf = strstrip(buf);
7658 err = page_counter_memparse(buf, "max", &max);
7662 xchg(&memcg->swap.max, max);
7667 static int swap_events_show(struct seq_file *m, void *v)
7669 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
7671 seq_printf(m, "high %lu\n",
7672 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH]));
7673 seq_printf(m, "max %lu\n",
7674 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
7675 seq_printf(m, "fail %lu\n",
7676 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
7681 static struct cftype swap_files[] = {
7683 .name = "swap.current",
7684 .flags = CFTYPE_NOT_ON_ROOT,
7685 .read_u64 = swap_current_read,
7688 .name = "swap.high",
7689 .flags = CFTYPE_NOT_ON_ROOT,
7690 .seq_show = swap_high_show,
7691 .write = swap_high_write,
7695 .flags = CFTYPE_NOT_ON_ROOT,
7696 .seq_show = swap_max_show,
7697 .write = swap_max_write,
7700 .name = "swap.peak",
7701 .flags = CFTYPE_NOT_ON_ROOT,
7702 .read_u64 = swap_peak_read,
7705 .name = "swap.events",
7706 .flags = CFTYPE_NOT_ON_ROOT,
7707 .file_offset = offsetof(struct mem_cgroup, swap_events_file),
7708 .seq_show = swap_events_show,
7713 static struct cftype memsw_files[] = {
7715 .name = "memsw.usage_in_bytes",
7716 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
7717 .read_u64 = mem_cgroup_read_u64,
7720 .name = "memsw.max_usage_in_bytes",
7721 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
7722 .write = mem_cgroup_reset,
7723 .read_u64 = mem_cgroup_read_u64,
7726 .name = "memsw.limit_in_bytes",
7727 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
7728 .write = mem_cgroup_write,
7729 .read_u64 = mem_cgroup_read_u64,
7732 .name = "memsw.failcnt",
7733 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
7734 .write = mem_cgroup_reset,
7735 .read_u64 = mem_cgroup_read_u64,
7737 { }, /* terminate */
7740 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
7742 * obj_cgroup_may_zswap - check if this cgroup can zswap
7743 * @objcg: the object cgroup
7745 * Check if the hierarchical zswap limit has been reached.
7747 * This doesn't check for specific headroom, and it is not atomic
7748 * either. But with zswap, the size of the allocation is only known
7749 * once compression has occured, and this optimistic pre-check avoids
7750 * spending cycles on compression when there is already no room left
7751 * or zswap is disabled altogether somewhere in the hierarchy.
7753 bool obj_cgroup_may_zswap(struct obj_cgroup *objcg)
7755 struct mem_cgroup *memcg, *original_memcg;
7758 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
7761 original_memcg = get_mem_cgroup_from_objcg(objcg);
7762 for (memcg = original_memcg; !mem_cgroup_is_root(memcg);
7763 memcg = parent_mem_cgroup(memcg)) {
7764 unsigned long max = READ_ONCE(memcg->zswap_max);
7765 unsigned long pages;
7767 if (max == PAGE_COUNTER_MAX)
7774 cgroup_rstat_flush(memcg->css.cgroup);
7775 pages = memcg_page_state(memcg, MEMCG_ZSWAP_B) / PAGE_SIZE;
7781 mem_cgroup_put(original_memcg);
7786 * obj_cgroup_charge_zswap - charge compression backend memory
7787 * @objcg: the object cgroup
7788 * @size: size of compressed object
7790 * This forces the charge after obj_cgroup_may_swap() allowed
7791 * compression and storage in zwap for this cgroup to go ahead.
7793 void obj_cgroup_charge_zswap(struct obj_cgroup *objcg, size_t size)
7795 struct mem_cgroup *memcg;
7797 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
7800 VM_WARN_ON_ONCE(!(current->flags & PF_MEMALLOC));
7802 /* PF_MEMALLOC context, charging must succeed */
7803 if (obj_cgroup_charge(objcg, GFP_KERNEL, size))
7807 memcg = obj_cgroup_memcg(objcg);
7808 mod_memcg_state(memcg, MEMCG_ZSWAP_B, size);
7809 mod_memcg_state(memcg, MEMCG_ZSWAPPED, 1);
7814 * obj_cgroup_uncharge_zswap - uncharge compression backend memory
7815 * @objcg: the object cgroup
7816 * @size: size of compressed object
7818 * Uncharges zswap memory on page in.
7820 void obj_cgroup_uncharge_zswap(struct obj_cgroup *objcg, size_t size)
7822 struct mem_cgroup *memcg;
7824 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
7827 obj_cgroup_uncharge(objcg, size);
7830 memcg = obj_cgroup_memcg(objcg);
7831 mod_memcg_state(memcg, MEMCG_ZSWAP_B, -size);
7832 mod_memcg_state(memcg, MEMCG_ZSWAPPED, -1);
7836 static u64 zswap_current_read(struct cgroup_subsys_state *css,
7839 cgroup_rstat_flush(css->cgroup);
7840 return memcg_page_state(mem_cgroup_from_css(css), MEMCG_ZSWAP_B);
7843 static int zswap_max_show(struct seq_file *m, void *v)
7845 return seq_puts_memcg_tunable(m,
7846 READ_ONCE(mem_cgroup_from_seq(m)->zswap_max));
7849 static ssize_t zswap_max_write(struct kernfs_open_file *of,
7850 char *buf, size_t nbytes, loff_t off)
7852 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7856 buf = strstrip(buf);
7857 err = page_counter_memparse(buf, "max", &max);
7861 xchg(&memcg->zswap_max, max);
7866 static struct cftype zswap_files[] = {
7868 .name = "zswap.current",
7869 .flags = CFTYPE_NOT_ON_ROOT,
7870 .read_u64 = zswap_current_read,
7873 .name = "zswap.max",
7874 .flags = CFTYPE_NOT_ON_ROOT,
7875 .seq_show = zswap_max_show,
7876 .write = zswap_max_write,
7880 #endif /* CONFIG_MEMCG_KMEM && CONFIG_ZSWAP */
7882 static int __init mem_cgroup_swap_init(void)
7884 if (mem_cgroup_disabled())
7887 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files));
7888 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files));
7889 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
7890 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, zswap_files));
7894 subsys_initcall(mem_cgroup_swap_init);
7896 #endif /* CONFIG_SWAP */