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>
71 #include <linux/uaccess.h>
73 #include <trace/events/vmscan.h>
75 struct cgroup_subsys memory_cgrp_subsys __read_mostly;
76 EXPORT_SYMBOL(memory_cgrp_subsys);
78 struct mem_cgroup *root_mem_cgroup __read_mostly;
80 /* Active memory cgroup to use from an interrupt context */
81 DEFINE_PER_CPU(struct mem_cgroup *, int_active_memcg);
82 EXPORT_PER_CPU_SYMBOL_GPL(int_active_memcg);
84 /* Socket memory accounting disabled? */
85 static bool cgroup_memory_nosocket __ro_after_init;
87 /* Kernel memory accounting disabled? */
88 static bool cgroup_memory_nokmem __ro_after_init;
90 /* Whether the swap controller is active */
91 #ifdef CONFIG_MEMCG_SWAP
92 bool cgroup_memory_noswap __ro_after_init;
94 #define cgroup_memory_noswap 1
97 #ifdef CONFIG_CGROUP_WRITEBACK
98 static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq);
101 /* Whether legacy memory+swap accounting is active */
102 static bool do_memsw_account(void)
104 return !cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_noswap;
107 #define THRESHOLDS_EVENTS_TARGET 128
108 #define SOFTLIMIT_EVENTS_TARGET 1024
111 * Cgroups above their limits are maintained in a RB-Tree, independent of
112 * their hierarchy representation
115 struct mem_cgroup_tree_per_node {
116 struct rb_root rb_root;
117 struct rb_node *rb_rightmost;
121 struct mem_cgroup_tree {
122 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
125 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
128 struct mem_cgroup_eventfd_list {
129 struct list_head list;
130 struct eventfd_ctx *eventfd;
134 * cgroup_event represents events which userspace want to receive.
136 struct mem_cgroup_event {
138 * memcg which the event belongs to.
140 struct mem_cgroup *memcg;
142 * eventfd to signal userspace about the event.
144 struct eventfd_ctx *eventfd;
146 * Each of these stored in a list by the cgroup.
148 struct list_head list;
150 * register_event() callback will be used to add new userspace
151 * waiter for changes related to this event. Use eventfd_signal()
152 * on eventfd to send notification to userspace.
154 int (*register_event)(struct mem_cgroup *memcg,
155 struct eventfd_ctx *eventfd, const char *args);
157 * unregister_event() callback will be called when userspace closes
158 * the eventfd or on cgroup removing. This callback must be set,
159 * if you want provide notification functionality.
161 void (*unregister_event)(struct mem_cgroup *memcg,
162 struct eventfd_ctx *eventfd);
164 * All fields below needed to unregister event when
165 * userspace closes eventfd.
168 wait_queue_head_t *wqh;
169 wait_queue_entry_t wait;
170 struct work_struct remove;
173 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
174 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
176 /* Stuffs for move charges at task migration. */
178 * Types of charges to be moved.
180 #define MOVE_ANON 0x1U
181 #define MOVE_FILE 0x2U
182 #define MOVE_MASK (MOVE_ANON | MOVE_FILE)
184 /* "mc" and its members are protected by cgroup_mutex */
185 static struct move_charge_struct {
186 spinlock_t lock; /* for from, to */
187 struct mm_struct *mm;
188 struct mem_cgroup *from;
189 struct mem_cgroup *to;
191 unsigned long precharge;
192 unsigned long moved_charge;
193 unsigned long moved_swap;
194 struct task_struct *moving_task; /* a task moving charges */
195 wait_queue_head_t waitq; /* a waitq for other context */
197 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
198 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
202 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
203 * limit reclaim to prevent infinite loops, if they ever occur.
205 #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
206 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
208 /* for encoding cft->private value on file */
217 #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
218 #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
219 #define MEMFILE_ATTR(val) ((val) & 0xffff)
220 /* Used for OOM notifier */
221 #define OOM_CONTROL (0)
224 * Iteration constructs for visiting all cgroups (under a tree). If
225 * loops are exited prematurely (break), mem_cgroup_iter_break() must
226 * be used for reference counting.
228 #define for_each_mem_cgroup_tree(iter, root) \
229 for (iter = mem_cgroup_iter(root, NULL, NULL); \
231 iter = mem_cgroup_iter(root, iter, NULL))
233 #define for_each_mem_cgroup(iter) \
234 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
236 iter = mem_cgroup_iter(NULL, iter, NULL))
238 static inline bool task_is_dying(void)
240 return tsk_is_oom_victim(current) || fatal_signal_pending(current) ||
241 (current->flags & PF_EXITING);
244 /* Some nice accessors for the vmpressure. */
245 struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
248 memcg = root_mem_cgroup;
249 return &memcg->vmpressure;
252 struct mem_cgroup *vmpressure_to_memcg(struct vmpressure *vmpr)
254 return container_of(vmpr, struct mem_cgroup, vmpressure);
257 #ifdef CONFIG_MEMCG_KMEM
258 static DEFINE_SPINLOCK(objcg_lock);
260 bool mem_cgroup_kmem_disabled(void)
262 return cgroup_memory_nokmem;
265 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
266 unsigned int nr_pages);
268 static void obj_cgroup_release(struct percpu_ref *ref)
270 struct obj_cgroup *objcg = container_of(ref, struct obj_cgroup, refcnt);
271 unsigned int nr_bytes;
272 unsigned int nr_pages;
276 * At this point all allocated objects are freed, and
277 * objcg->nr_charged_bytes can't have an arbitrary byte value.
278 * However, it can be PAGE_SIZE or (x * PAGE_SIZE).
280 * The following sequence can lead to it:
281 * 1) CPU0: objcg == stock->cached_objcg
282 * 2) CPU1: we do a small allocation (e.g. 92 bytes),
283 * PAGE_SIZE bytes are charged
284 * 3) CPU1: a process from another memcg is allocating something,
285 * the stock if flushed,
286 * objcg->nr_charged_bytes = PAGE_SIZE - 92
287 * 5) CPU0: we do release this object,
288 * 92 bytes are added to stock->nr_bytes
289 * 6) CPU0: stock is flushed,
290 * 92 bytes are added to objcg->nr_charged_bytes
292 * In the result, nr_charged_bytes == PAGE_SIZE.
293 * This page will be uncharged in obj_cgroup_release().
295 nr_bytes = atomic_read(&objcg->nr_charged_bytes);
296 WARN_ON_ONCE(nr_bytes & (PAGE_SIZE - 1));
297 nr_pages = nr_bytes >> PAGE_SHIFT;
300 obj_cgroup_uncharge_pages(objcg, nr_pages);
302 spin_lock_irqsave(&objcg_lock, flags);
303 list_del(&objcg->list);
304 spin_unlock_irqrestore(&objcg_lock, flags);
306 percpu_ref_exit(ref);
307 kfree_rcu(objcg, rcu);
310 static struct obj_cgroup *obj_cgroup_alloc(void)
312 struct obj_cgroup *objcg;
315 objcg = kzalloc(sizeof(struct obj_cgroup), GFP_KERNEL);
319 ret = percpu_ref_init(&objcg->refcnt, obj_cgroup_release, 0,
325 INIT_LIST_HEAD(&objcg->list);
329 static void memcg_reparent_objcgs(struct mem_cgroup *memcg,
330 struct mem_cgroup *parent)
332 struct obj_cgroup *objcg, *iter;
334 objcg = rcu_replace_pointer(memcg->objcg, NULL, true);
336 spin_lock_irq(&objcg_lock);
338 /* 1) Ready to reparent active objcg. */
339 list_add(&objcg->list, &memcg->objcg_list);
340 /* 2) Reparent active objcg and already reparented objcgs to parent. */
341 list_for_each_entry(iter, &memcg->objcg_list, list)
342 WRITE_ONCE(iter->memcg, parent);
343 /* 3) Move already reparented objcgs to the parent's list */
344 list_splice(&memcg->objcg_list, &parent->objcg_list);
346 spin_unlock_irq(&objcg_lock);
348 percpu_ref_kill(&objcg->refcnt);
352 * A lot of the calls to the cache allocation functions are expected to be
353 * inlined by the compiler. Since the calls to memcg_slab_pre_alloc_hook() are
354 * conditional to this static branch, we'll have to allow modules that does
355 * kmem_cache_alloc and the such to see this symbol as well
357 DEFINE_STATIC_KEY_FALSE(memcg_kmem_enabled_key);
358 EXPORT_SYMBOL(memcg_kmem_enabled_key);
362 * mem_cgroup_css_from_page - css of the memcg associated with a page
363 * @page: page of interest
365 * If memcg is bound to the default hierarchy, css of the memcg associated
366 * with @page is returned. The returned css remains associated with @page
367 * until it is released.
369 * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
372 struct cgroup_subsys_state *mem_cgroup_css_from_page(struct page *page)
374 struct mem_cgroup *memcg;
376 memcg = page_memcg(page);
378 if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
379 memcg = root_mem_cgroup;
385 * page_cgroup_ino - return inode number of the memcg a page is charged to
388 * Look up the closest online ancestor of the memory cgroup @page is charged to
389 * and return its inode number or 0 if @page is not charged to any cgroup. It
390 * is safe to call this function without holding a reference to @page.
392 * Note, this function is inherently racy, because there is nothing to prevent
393 * the cgroup inode from getting torn down and potentially reallocated a moment
394 * after page_cgroup_ino() returns, so it only should be used by callers that
395 * do not care (such as procfs interfaces).
397 ino_t page_cgroup_ino(struct page *page)
399 struct mem_cgroup *memcg;
400 unsigned long ino = 0;
403 memcg = page_memcg_check(page);
405 while (memcg && !(memcg->css.flags & CSS_ONLINE))
406 memcg = parent_mem_cgroup(memcg);
408 ino = cgroup_ino(memcg->css.cgroup);
413 static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_node *mz,
414 struct mem_cgroup_tree_per_node *mctz,
415 unsigned long new_usage_in_excess)
417 struct rb_node **p = &mctz->rb_root.rb_node;
418 struct rb_node *parent = NULL;
419 struct mem_cgroup_per_node *mz_node;
420 bool rightmost = true;
425 mz->usage_in_excess = new_usage_in_excess;
426 if (!mz->usage_in_excess)
430 mz_node = rb_entry(parent, struct mem_cgroup_per_node,
432 if (mz->usage_in_excess < mz_node->usage_in_excess) {
441 mctz->rb_rightmost = &mz->tree_node;
443 rb_link_node(&mz->tree_node, parent, p);
444 rb_insert_color(&mz->tree_node, &mctz->rb_root);
448 static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
449 struct mem_cgroup_tree_per_node *mctz)
454 if (&mz->tree_node == mctz->rb_rightmost)
455 mctz->rb_rightmost = rb_prev(&mz->tree_node);
457 rb_erase(&mz->tree_node, &mctz->rb_root);
461 static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
462 struct mem_cgroup_tree_per_node *mctz)
466 spin_lock_irqsave(&mctz->lock, flags);
467 __mem_cgroup_remove_exceeded(mz, mctz);
468 spin_unlock_irqrestore(&mctz->lock, flags);
471 static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
473 unsigned long nr_pages = page_counter_read(&memcg->memory);
474 unsigned long soft_limit = READ_ONCE(memcg->soft_limit);
475 unsigned long excess = 0;
477 if (nr_pages > soft_limit)
478 excess = nr_pages - soft_limit;
483 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, int nid)
485 unsigned long excess;
486 struct mem_cgroup_per_node *mz;
487 struct mem_cgroup_tree_per_node *mctz;
489 mctz = soft_limit_tree.rb_tree_per_node[nid];
493 * Necessary to update all ancestors when hierarchy is used.
494 * because their event counter is not touched.
496 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
497 mz = memcg->nodeinfo[nid];
498 excess = soft_limit_excess(memcg);
500 * We have to update the tree if mz is on RB-tree or
501 * mem is over its softlimit.
503 if (excess || mz->on_tree) {
506 spin_lock_irqsave(&mctz->lock, flags);
507 /* if on-tree, remove it */
509 __mem_cgroup_remove_exceeded(mz, mctz);
511 * Insert again. mz->usage_in_excess will be updated.
512 * If excess is 0, no tree ops.
514 __mem_cgroup_insert_exceeded(mz, mctz, excess);
515 spin_unlock_irqrestore(&mctz->lock, flags);
520 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
522 struct mem_cgroup_tree_per_node *mctz;
523 struct mem_cgroup_per_node *mz;
527 mz = memcg->nodeinfo[nid];
528 mctz = soft_limit_tree.rb_tree_per_node[nid];
530 mem_cgroup_remove_exceeded(mz, mctz);
534 static struct mem_cgroup_per_node *
535 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
537 struct mem_cgroup_per_node *mz;
541 if (!mctz->rb_rightmost)
542 goto done; /* Nothing to reclaim from */
544 mz = rb_entry(mctz->rb_rightmost,
545 struct mem_cgroup_per_node, tree_node);
547 * Remove the node now but someone else can add it back,
548 * we will to add it back at the end of reclaim to its correct
549 * position in the tree.
551 __mem_cgroup_remove_exceeded(mz, mctz);
552 if (!soft_limit_excess(mz->memcg) ||
553 !css_tryget(&mz->memcg->css))
559 static struct mem_cgroup_per_node *
560 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
562 struct mem_cgroup_per_node *mz;
564 spin_lock_irq(&mctz->lock);
565 mz = __mem_cgroup_largest_soft_limit_node(mctz);
566 spin_unlock_irq(&mctz->lock);
571 * memcg and lruvec stats flushing
573 * Many codepaths leading to stats update or read are performance sensitive and
574 * adding stats flushing in such codepaths is not desirable. So, to optimize the
575 * flushing the kernel does:
577 * 1) Periodically and asynchronously flush the stats every 2 seconds to not let
578 * rstat update tree grow unbounded.
580 * 2) Flush the stats synchronously on reader side only when there are more than
581 * (MEMCG_CHARGE_BATCH * nr_cpus) update events. Though this optimization
582 * will let stats be out of sync by atmost (MEMCG_CHARGE_BATCH * nr_cpus) but
583 * only for 2 seconds due to (1).
585 static void flush_memcg_stats_dwork(struct work_struct *w);
586 static DECLARE_DEFERRABLE_WORK(stats_flush_dwork, flush_memcg_stats_dwork);
587 static DEFINE_SPINLOCK(stats_flush_lock);
588 static DEFINE_PER_CPU(unsigned int, stats_updates);
589 static atomic_t stats_flush_threshold = ATOMIC_INIT(0);
592 * Accessors to ensure that preemption is disabled on PREEMPT_RT because it can
593 * not rely on this as part of an acquired spinlock_t lock. These functions are
594 * never used in hardirq context on PREEMPT_RT and therefore disabling preemtion
597 static void memcg_stats_lock(void)
599 #ifdef CONFIG_PREEMPT_RT
602 VM_BUG_ON(!irqs_disabled());
606 static void __memcg_stats_lock(void)
608 #ifdef CONFIG_PREEMPT_RT
613 static void memcg_stats_unlock(void)
615 #ifdef CONFIG_PREEMPT_RT
620 static inline void memcg_rstat_updated(struct mem_cgroup *memcg, int val)
624 cgroup_rstat_updated(memcg->css.cgroup, smp_processor_id());
626 x = __this_cpu_add_return(stats_updates, abs(val));
627 if (x > MEMCG_CHARGE_BATCH) {
628 atomic_add(x / MEMCG_CHARGE_BATCH, &stats_flush_threshold);
629 __this_cpu_write(stats_updates, 0);
633 static void __mem_cgroup_flush_stats(void)
637 if (!spin_trylock_irqsave(&stats_flush_lock, flag))
640 cgroup_rstat_flush_irqsafe(root_mem_cgroup->css.cgroup);
641 atomic_set(&stats_flush_threshold, 0);
642 spin_unlock_irqrestore(&stats_flush_lock, flag);
645 void mem_cgroup_flush_stats(void)
647 if (atomic_read(&stats_flush_threshold) > num_online_cpus())
648 __mem_cgroup_flush_stats();
651 static void flush_memcg_stats_dwork(struct work_struct *w)
653 __mem_cgroup_flush_stats();
654 queue_delayed_work(system_unbound_wq, &stats_flush_dwork, 2UL*HZ);
658 * __mod_memcg_state - update cgroup memory statistics
659 * @memcg: the memory cgroup
660 * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item
661 * @val: delta to add to the counter, can be negative
663 void __mod_memcg_state(struct mem_cgroup *memcg, int idx, int val)
665 if (mem_cgroup_disabled())
668 __this_cpu_add(memcg->vmstats_percpu->state[idx], val);
669 memcg_rstat_updated(memcg, val);
672 /* idx can be of type enum memcg_stat_item or node_stat_item. */
673 static unsigned long memcg_page_state_local(struct mem_cgroup *memcg, int idx)
678 for_each_possible_cpu(cpu)
679 x += per_cpu(memcg->vmstats_percpu->state[idx], cpu);
687 void __mod_memcg_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
690 struct mem_cgroup_per_node *pn;
691 struct mem_cgroup *memcg;
693 pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
697 * The caller from rmap relay on disabled preemption becase they never
698 * update their counter from in-interrupt context. For these two
699 * counters we check that the update is never performed from an
700 * interrupt context while other caller need to have disabled interrupt.
702 __memcg_stats_lock();
703 if (IS_ENABLED(CONFIG_DEBUG_VM) && !IS_ENABLED(CONFIG_PREEMPT_RT)) {
708 case NR_SHMEM_PMDMAPPED:
709 case NR_FILE_PMDMAPPED:
710 WARN_ON_ONCE(!in_task());
713 WARN_ON_ONCE(!irqs_disabled());
718 __this_cpu_add(memcg->vmstats_percpu->state[idx], val);
721 __this_cpu_add(pn->lruvec_stats_percpu->state[idx], val);
723 memcg_rstat_updated(memcg, val);
724 memcg_stats_unlock();
728 * __mod_lruvec_state - update lruvec memory statistics
729 * @lruvec: the lruvec
730 * @idx: the stat item
731 * @val: delta to add to the counter, can be negative
733 * The lruvec is the intersection of the NUMA node and a cgroup. This
734 * function updates the all three counters that are affected by a
735 * change of state at this level: per-node, per-cgroup, per-lruvec.
737 void __mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
741 __mod_node_page_state(lruvec_pgdat(lruvec), idx, val);
743 /* Update memcg and lruvec */
744 if (!mem_cgroup_disabled())
745 __mod_memcg_lruvec_state(lruvec, idx, val);
748 void __mod_lruvec_page_state(struct page *page, enum node_stat_item idx,
751 struct page *head = compound_head(page); /* rmap on tail pages */
752 struct mem_cgroup *memcg;
753 pg_data_t *pgdat = page_pgdat(page);
754 struct lruvec *lruvec;
757 memcg = page_memcg(head);
758 /* Untracked pages have no memcg, no lruvec. Update only the node */
761 __mod_node_page_state(pgdat, idx, val);
765 lruvec = mem_cgroup_lruvec(memcg, pgdat);
766 __mod_lruvec_state(lruvec, idx, val);
769 EXPORT_SYMBOL(__mod_lruvec_page_state);
771 void __mod_lruvec_kmem_state(void *p, enum node_stat_item idx, int val)
773 pg_data_t *pgdat = page_pgdat(virt_to_page(p));
774 struct mem_cgroup *memcg;
775 struct lruvec *lruvec;
778 memcg = mem_cgroup_from_obj(p);
781 * Untracked pages have no memcg, no lruvec. Update only the
782 * node. If we reparent the slab objects to the root memcg,
783 * when we free the slab object, we need to update the per-memcg
784 * vmstats to keep it correct for the root memcg.
787 __mod_node_page_state(pgdat, idx, val);
789 lruvec = mem_cgroup_lruvec(memcg, pgdat);
790 __mod_lruvec_state(lruvec, idx, val);
796 * __count_memcg_events - account VM events in a cgroup
797 * @memcg: the memory cgroup
798 * @idx: the event item
799 * @count: the number of events that occurred
801 void __count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx,
804 if (mem_cgroup_disabled())
808 __this_cpu_add(memcg->vmstats_percpu->events[idx], count);
809 memcg_rstat_updated(memcg, count);
810 memcg_stats_unlock();
813 static unsigned long memcg_events(struct mem_cgroup *memcg, int event)
815 return READ_ONCE(memcg->vmstats.events[event]);
818 static unsigned long memcg_events_local(struct mem_cgroup *memcg, int event)
823 for_each_possible_cpu(cpu)
824 x += per_cpu(memcg->vmstats_percpu->events[event], cpu);
828 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
831 /* pagein of a big page is an event. So, ignore page size */
833 __count_memcg_events(memcg, PGPGIN, 1);
835 __count_memcg_events(memcg, PGPGOUT, 1);
836 nr_pages = -nr_pages; /* for event */
839 __this_cpu_add(memcg->vmstats_percpu->nr_page_events, nr_pages);
842 static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
843 enum mem_cgroup_events_target target)
845 unsigned long val, next;
847 val = __this_cpu_read(memcg->vmstats_percpu->nr_page_events);
848 next = __this_cpu_read(memcg->vmstats_percpu->targets[target]);
849 /* from time_after() in jiffies.h */
850 if ((long)(next - val) < 0) {
852 case MEM_CGROUP_TARGET_THRESH:
853 next = val + THRESHOLDS_EVENTS_TARGET;
855 case MEM_CGROUP_TARGET_SOFTLIMIT:
856 next = val + SOFTLIMIT_EVENTS_TARGET;
861 __this_cpu_write(memcg->vmstats_percpu->targets[target], next);
868 * Check events in order.
871 static void memcg_check_events(struct mem_cgroup *memcg, int nid)
873 if (IS_ENABLED(CONFIG_PREEMPT_RT))
876 /* threshold event is triggered in finer grain than soft limit */
877 if (unlikely(mem_cgroup_event_ratelimit(memcg,
878 MEM_CGROUP_TARGET_THRESH))) {
881 do_softlimit = mem_cgroup_event_ratelimit(memcg,
882 MEM_CGROUP_TARGET_SOFTLIMIT);
883 mem_cgroup_threshold(memcg);
884 if (unlikely(do_softlimit))
885 mem_cgroup_update_tree(memcg, nid);
889 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
892 * mm_update_next_owner() may clear mm->owner to NULL
893 * if it races with swapoff, page migration, etc.
894 * So this can be called with p == NULL.
899 return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
901 EXPORT_SYMBOL(mem_cgroup_from_task);
903 static __always_inline struct mem_cgroup *active_memcg(void)
906 return this_cpu_read(int_active_memcg);
908 return current->active_memcg;
912 * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
913 * @mm: mm from which memcg should be extracted. It can be NULL.
915 * Obtain a reference on mm->memcg and returns it if successful. If mm
916 * is NULL, then the memcg is chosen as follows:
917 * 1) The active memcg, if set.
918 * 2) current->mm->memcg, if available
920 * If mem_cgroup is disabled, NULL is returned.
922 struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
924 struct mem_cgroup *memcg;
926 if (mem_cgroup_disabled())
930 * Page cache insertions can happen without an
931 * actual mm context, e.g. during disk probing
932 * on boot, loopback IO, acct() writes etc.
934 * No need to css_get on root memcg as the reference
935 * counting is disabled on the root level in the
936 * cgroup core. See CSS_NO_REF.
939 memcg = active_memcg();
940 if (unlikely(memcg)) {
941 /* remote memcg must hold a ref */
942 css_get(&memcg->css);
947 return root_mem_cgroup;
952 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
953 if (unlikely(!memcg))
954 memcg = root_mem_cgroup;
955 } while (!css_tryget(&memcg->css));
959 EXPORT_SYMBOL(get_mem_cgroup_from_mm);
961 static __always_inline bool memcg_kmem_bypass(void)
963 /* Allow remote memcg charging from any context. */
964 if (unlikely(active_memcg()))
967 /* Memcg to charge can't be determined. */
968 if (!in_task() || !current->mm || (current->flags & PF_KTHREAD))
975 * mem_cgroup_iter - iterate over memory cgroup hierarchy
976 * @root: hierarchy root
977 * @prev: previously returned memcg, NULL on first invocation
978 * @reclaim: cookie for shared reclaim walks, NULL for full walks
980 * Returns references to children of the hierarchy below @root, or
981 * @root itself, or %NULL after a full round-trip.
983 * Caller must pass the return value in @prev on subsequent
984 * invocations for reference counting, or use mem_cgroup_iter_break()
985 * to cancel a hierarchy walk before the round-trip is complete.
987 * Reclaimers can specify a node in @reclaim to divide up the memcgs
988 * in the hierarchy among all concurrent reclaimers operating on the
991 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
992 struct mem_cgroup *prev,
993 struct mem_cgroup_reclaim_cookie *reclaim)
995 struct mem_cgroup_reclaim_iter *iter;
996 struct cgroup_subsys_state *css = NULL;
997 struct mem_cgroup *memcg = NULL;
998 struct mem_cgroup *pos = NULL;
1000 if (mem_cgroup_disabled())
1004 root = root_mem_cgroup;
1006 if (prev && !reclaim)
1012 struct mem_cgroup_per_node *mz;
1014 mz = root->nodeinfo[reclaim->pgdat->node_id];
1017 if (prev && reclaim->generation != iter->generation)
1021 pos = READ_ONCE(iter->position);
1022 if (!pos || css_tryget(&pos->css))
1025 * css reference reached zero, so iter->position will
1026 * be cleared by ->css_released. However, we should not
1027 * rely on this happening soon, because ->css_released
1028 * is called from a work queue, and by busy-waiting we
1029 * might block it. So we clear iter->position right
1032 (void)cmpxchg(&iter->position, pos, NULL);
1040 css = css_next_descendant_pre(css, &root->css);
1043 * Reclaimers share the hierarchy walk, and a
1044 * new one might jump in right at the end of
1045 * the hierarchy - make sure they see at least
1046 * one group and restart from the beginning.
1054 * Verify the css and acquire a reference. The root
1055 * is provided by the caller, so we know it's alive
1056 * and kicking, and don't take an extra reference.
1058 memcg = mem_cgroup_from_css(css);
1060 if (css == &root->css)
1063 if (css_tryget(css))
1071 * The position could have already been updated by a competing
1072 * thread, so check that the value hasn't changed since we read
1073 * it to avoid reclaiming from the same cgroup twice.
1075 (void)cmpxchg(&iter->position, pos, memcg);
1083 reclaim->generation = iter->generation;
1088 if (prev && prev != root)
1089 css_put(&prev->css);
1095 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1096 * @root: hierarchy root
1097 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1099 void mem_cgroup_iter_break(struct mem_cgroup *root,
1100 struct mem_cgroup *prev)
1103 root = root_mem_cgroup;
1104 if (prev && prev != root)
1105 css_put(&prev->css);
1108 static void __invalidate_reclaim_iterators(struct mem_cgroup *from,
1109 struct mem_cgroup *dead_memcg)
1111 struct mem_cgroup_reclaim_iter *iter;
1112 struct mem_cgroup_per_node *mz;
1115 for_each_node(nid) {
1116 mz = from->nodeinfo[nid];
1118 cmpxchg(&iter->position, dead_memcg, NULL);
1122 static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
1124 struct mem_cgroup *memcg = dead_memcg;
1125 struct mem_cgroup *last;
1128 __invalidate_reclaim_iterators(memcg, dead_memcg);
1130 } while ((memcg = parent_mem_cgroup(memcg)));
1133 * When cgruop1 non-hierarchy mode is used,
1134 * parent_mem_cgroup() does not walk all the way up to the
1135 * cgroup root (root_mem_cgroup). So we have to handle
1136 * dead_memcg from cgroup root separately.
1138 if (last != root_mem_cgroup)
1139 __invalidate_reclaim_iterators(root_mem_cgroup,
1144 * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
1145 * @memcg: hierarchy root
1146 * @fn: function to call for each task
1147 * @arg: argument passed to @fn
1149 * This function iterates over tasks attached to @memcg or to any of its
1150 * descendants and calls @fn for each task. If @fn returns a non-zero
1151 * value, the function breaks the iteration loop and returns the value.
1152 * Otherwise, it will iterate over all tasks and return 0.
1154 * This function must not be called for the root memory cgroup.
1156 int mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
1157 int (*fn)(struct task_struct *, void *), void *arg)
1159 struct mem_cgroup *iter;
1162 BUG_ON(memcg == root_mem_cgroup);
1164 for_each_mem_cgroup_tree(iter, memcg) {
1165 struct css_task_iter it;
1166 struct task_struct *task;
1168 css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it);
1169 while (!ret && (task = css_task_iter_next(&it)))
1170 ret = fn(task, arg);
1171 css_task_iter_end(&it);
1173 mem_cgroup_iter_break(memcg, iter);
1180 #ifdef CONFIG_DEBUG_VM
1181 void lruvec_memcg_debug(struct lruvec *lruvec, struct folio *folio)
1183 struct mem_cgroup *memcg;
1185 if (mem_cgroup_disabled())
1188 memcg = folio_memcg(folio);
1191 VM_BUG_ON_FOLIO(lruvec_memcg(lruvec) != root_mem_cgroup, folio);
1193 VM_BUG_ON_FOLIO(lruvec_memcg(lruvec) != memcg, folio);
1198 * folio_lruvec_lock - Lock the lruvec for a folio.
1199 * @folio: Pointer to the folio.
1201 * These functions are safe to use under any of the following conditions:
1203 * - folio_test_lru false
1204 * - folio_memcg_lock()
1205 * - folio frozen (refcount of 0)
1207 * Return: The lruvec this folio is on with its lock held.
1209 struct lruvec *folio_lruvec_lock(struct folio *folio)
1211 struct lruvec *lruvec = folio_lruvec(folio);
1213 spin_lock(&lruvec->lru_lock);
1214 lruvec_memcg_debug(lruvec, folio);
1220 * folio_lruvec_lock_irq - Lock the lruvec for a folio.
1221 * @folio: Pointer to the folio.
1223 * These functions are safe to use under any of the following conditions:
1225 * - folio_test_lru false
1226 * - folio_memcg_lock()
1227 * - folio frozen (refcount of 0)
1229 * Return: The lruvec this folio is on with its lock held and interrupts
1232 struct lruvec *folio_lruvec_lock_irq(struct folio *folio)
1234 struct lruvec *lruvec = folio_lruvec(folio);
1236 spin_lock_irq(&lruvec->lru_lock);
1237 lruvec_memcg_debug(lruvec, folio);
1243 * folio_lruvec_lock_irqsave - Lock the lruvec for a folio.
1244 * @folio: Pointer to the folio.
1245 * @flags: Pointer to irqsave flags.
1247 * These functions are safe to use under any of the following conditions:
1249 * - folio_test_lru false
1250 * - folio_memcg_lock()
1251 * - folio frozen (refcount of 0)
1253 * Return: The lruvec this folio is on with its lock held and interrupts
1256 struct lruvec *folio_lruvec_lock_irqsave(struct folio *folio,
1257 unsigned long *flags)
1259 struct lruvec *lruvec = folio_lruvec(folio);
1261 spin_lock_irqsave(&lruvec->lru_lock, *flags);
1262 lruvec_memcg_debug(lruvec, folio);
1268 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1269 * @lruvec: mem_cgroup per zone lru vector
1270 * @lru: index of lru list the page is sitting on
1271 * @zid: zone id of the accounted pages
1272 * @nr_pages: positive when adding or negative when removing
1274 * This function must be called under lru_lock, just before a page is added
1275 * to or just after a page is removed from an lru list.
1277 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1278 int zid, int nr_pages)
1280 struct mem_cgroup_per_node *mz;
1281 unsigned long *lru_size;
1284 if (mem_cgroup_disabled())
1287 mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
1288 lru_size = &mz->lru_zone_size[zid][lru];
1291 *lru_size += nr_pages;
1294 if (WARN_ONCE(size < 0,
1295 "%s(%p, %d, %d): lru_size %ld\n",
1296 __func__, lruvec, lru, nr_pages, size)) {
1302 *lru_size += nr_pages;
1306 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1307 * @memcg: the memory cgroup
1309 * Returns the maximum amount of memory @mem can be charged with, in
1312 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1314 unsigned long margin = 0;
1315 unsigned long count;
1316 unsigned long limit;
1318 count = page_counter_read(&memcg->memory);
1319 limit = READ_ONCE(memcg->memory.max);
1321 margin = limit - count;
1323 if (do_memsw_account()) {
1324 count = page_counter_read(&memcg->memsw);
1325 limit = READ_ONCE(memcg->memsw.max);
1327 margin = min(margin, limit - count);
1336 * A routine for checking "mem" is under move_account() or not.
1338 * Checking a cgroup is mc.from or mc.to or under hierarchy of
1339 * moving cgroups. This is for waiting at high-memory pressure
1342 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1344 struct mem_cgroup *from;
1345 struct mem_cgroup *to;
1348 * Unlike task_move routines, we access mc.to, mc.from not under
1349 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1351 spin_lock(&mc.lock);
1357 ret = mem_cgroup_is_descendant(from, memcg) ||
1358 mem_cgroup_is_descendant(to, memcg);
1360 spin_unlock(&mc.lock);
1364 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1366 if (mc.moving_task && current != mc.moving_task) {
1367 if (mem_cgroup_under_move(memcg)) {
1369 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1370 /* moving charge context might have finished. */
1373 finish_wait(&mc.waitq, &wait);
1380 struct memory_stat {
1385 static const struct memory_stat memory_stats[] = {
1386 { "anon", NR_ANON_MAPPED },
1387 { "file", NR_FILE_PAGES },
1388 { "kernel", MEMCG_KMEM },
1389 { "kernel_stack", NR_KERNEL_STACK_KB },
1390 { "pagetables", NR_PAGETABLE },
1391 { "percpu", MEMCG_PERCPU_B },
1392 { "sock", MEMCG_SOCK },
1393 { "vmalloc", MEMCG_VMALLOC },
1394 { "shmem", NR_SHMEM },
1395 { "file_mapped", NR_FILE_MAPPED },
1396 { "file_dirty", NR_FILE_DIRTY },
1397 { "file_writeback", NR_WRITEBACK },
1399 { "swapcached", NR_SWAPCACHE },
1401 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1402 { "anon_thp", NR_ANON_THPS },
1403 { "file_thp", NR_FILE_THPS },
1404 { "shmem_thp", NR_SHMEM_THPS },
1406 { "inactive_anon", NR_INACTIVE_ANON },
1407 { "active_anon", NR_ACTIVE_ANON },
1408 { "inactive_file", NR_INACTIVE_FILE },
1409 { "active_file", NR_ACTIVE_FILE },
1410 { "unevictable", NR_UNEVICTABLE },
1411 { "slab_reclaimable", NR_SLAB_RECLAIMABLE_B },
1412 { "slab_unreclaimable", NR_SLAB_UNRECLAIMABLE_B },
1414 /* The memory events */
1415 { "workingset_refault_anon", WORKINGSET_REFAULT_ANON },
1416 { "workingset_refault_file", WORKINGSET_REFAULT_FILE },
1417 { "workingset_activate_anon", WORKINGSET_ACTIVATE_ANON },
1418 { "workingset_activate_file", WORKINGSET_ACTIVATE_FILE },
1419 { "workingset_restore_anon", WORKINGSET_RESTORE_ANON },
1420 { "workingset_restore_file", WORKINGSET_RESTORE_FILE },
1421 { "workingset_nodereclaim", WORKINGSET_NODERECLAIM },
1424 /* Translate stat items to the correct unit for memory.stat output */
1425 static int memcg_page_state_unit(int item)
1428 case MEMCG_PERCPU_B:
1429 case NR_SLAB_RECLAIMABLE_B:
1430 case NR_SLAB_UNRECLAIMABLE_B:
1431 case WORKINGSET_REFAULT_ANON:
1432 case WORKINGSET_REFAULT_FILE:
1433 case WORKINGSET_ACTIVATE_ANON:
1434 case WORKINGSET_ACTIVATE_FILE:
1435 case WORKINGSET_RESTORE_ANON:
1436 case WORKINGSET_RESTORE_FILE:
1437 case WORKINGSET_NODERECLAIM:
1439 case NR_KERNEL_STACK_KB:
1446 static inline unsigned long memcg_page_state_output(struct mem_cgroup *memcg,
1449 return memcg_page_state(memcg, item) * memcg_page_state_unit(item);
1452 static char *memory_stat_format(struct mem_cgroup *memcg)
1457 seq_buf_init(&s, kmalloc(PAGE_SIZE, GFP_KERNEL), PAGE_SIZE);
1462 * Provide statistics on the state of the memory subsystem as
1463 * well as cumulative event counters that show past behavior.
1465 * This list is ordered following a combination of these gradients:
1466 * 1) generic big picture -> specifics and details
1467 * 2) reflecting userspace activity -> reflecting kernel heuristics
1469 * Current memory state:
1471 mem_cgroup_flush_stats();
1473 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
1476 size = memcg_page_state_output(memcg, memory_stats[i].idx);
1477 seq_buf_printf(&s, "%s %llu\n", memory_stats[i].name, size);
1479 if (unlikely(memory_stats[i].idx == NR_SLAB_UNRECLAIMABLE_B)) {
1480 size += memcg_page_state_output(memcg,
1481 NR_SLAB_RECLAIMABLE_B);
1482 seq_buf_printf(&s, "slab %llu\n", size);
1486 /* Accumulated memory events */
1488 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGFAULT),
1489 memcg_events(memcg, PGFAULT));
1490 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGMAJFAULT),
1491 memcg_events(memcg, PGMAJFAULT));
1492 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGREFILL),
1493 memcg_events(memcg, PGREFILL));
1494 seq_buf_printf(&s, "pgscan %lu\n",
1495 memcg_events(memcg, PGSCAN_KSWAPD) +
1496 memcg_events(memcg, PGSCAN_DIRECT));
1497 seq_buf_printf(&s, "pgsteal %lu\n",
1498 memcg_events(memcg, PGSTEAL_KSWAPD) +
1499 memcg_events(memcg, PGSTEAL_DIRECT));
1500 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGACTIVATE),
1501 memcg_events(memcg, PGACTIVATE));
1502 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGDEACTIVATE),
1503 memcg_events(memcg, PGDEACTIVATE));
1504 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGLAZYFREE),
1505 memcg_events(memcg, PGLAZYFREE));
1506 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGLAZYFREED),
1507 memcg_events(memcg, PGLAZYFREED));
1509 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1510 seq_buf_printf(&s, "%s %lu\n", vm_event_name(THP_FAULT_ALLOC),
1511 memcg_events(memcg, THP_FAULT_ALLOC));
1512 seq_buf_printf(&s, "%s %lu\n", vm_event_name(THP_COLLAPSE_ALLOC),
1513 memcg_events(memcg, THP_COLLAPSE_ALLOC));
1514 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
1516 /* The above should easily fit into one page */
1517 WARN_ON_ONCE(seq_buf_has_overflowed(&s));
1522 #define K(x) ((x) << (PAGE_SHIFT-10))
1524 * mem_cgroup_print_oom_context: Print OOM information relevant to
1525 * memory controller.
1526 * @memcg: The memory cgroup that went over limit
1527 * @p: Task that is going to be killed
1529 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1532 void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p)
1537 pr_cont(",oom_memcg=");
1538 pr_cont_cgroup_path(memcg->css.cgroup);
1540 pr_cont(",global_oom");
1542 pr_cont(",task_memcg=");
1543 pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
1549 * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
1550 * memory controller.
1551 * @memcg: The memory cgroup that went over limit
1553 void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
1557 pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1558 K((u64)page_counter_read(&memcg->memory)),
1559 K((u64)READ_ONCE(memcg->memory.max)), memcg->memory.failcnt);
1560 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1561 pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n",
1562 K((u64)page_counter_read(&memcg->swap)),
1563 K((u64)READ_ONCE(memcg->swap.max)), memcg->swap.failcnt);
1565 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1566 K((u64)page_counter_read(&memcg->memsw)),
1567 K((u64)memcg->memsw.max), memcg->memsw.failcnt);
1568 pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1569 K((u64)page_counter_read(&memcg->kmem)),
1570 K((u64)memcg->kmem.max), memcg->kmem.failcnt);
1573 pr_info("Memory cgroup stats for ");
1574 pr_cont_cgroup_path(memcg->css.cgroup);
1576 buf = memory_stat_format(memcg);
1584 * Return the memory (and swap, if configured) limit for a memcg.
1586 unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg)
1588 unsigned long max = READ_ONCE(memcg->memory.max);
1590 if (cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
1591 if (mem_cgroup_swappiness(memcg))
1592 max += min(READ_ONCE(memcg->swap.max),
1593 (unsigned long)total_swap_pages);
1595 if (mem_cgroup_swappiness(memcg)) {
1596 /* Calculate swap excess capacity from memsw limit */
1597 unsigned long swap = READ_ONCE(memcg->memsw.max) - max;
1599 max += min(swap, (unsigned long)total_swap_pages);
1605 unsigned long mem_cgroup_size(struct mem_cgroup *memcg)
1607 return page_counter_read(&memcg->memory);
1610 static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1613 struct oom_control oc = {
1617 .gfp_mask = gfp_mask,
1622 if (mutex_lock_killable(&oom_lock))
1625 if (mem_cgroup_margin(memcg) >= (1 << order))
1629 * A few threads which were not waiting at mutex_lock_killable() can
1630 * fail to bail out. Therefore, check again after holding oom_lock.
1632 ret = task_is_dying() || out_of_memory(&oc);
1635 mutex_unlock(&oom_lock);
1639 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
1642 unsigned long *total_scanned)
1644 struct mem_cgroup *victim = NULL;
1647 unsigned long excess;
1648 unsigned long nr_scanned;
1649 struct mem_cgroup_reclaim_cookie reclaim = {
1653 excess = soft_limit_excess(root_memcg);
1656 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1661 * If we have not been able to reclaim
1662 * anything, it might because there are
1663 * no reclaimable pages under this hierarchy
1668 * We want to do more targeted reclaim.
1669 * excess >> 2 is not to excessive so as to
1670 * reclaim too much, nor too less that we keep
1671 * coming back to reclaim from this cgroup
1673 if (total >= (excess >> 2) ||
1674 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1679 total += mem_cgroup_shrink_node(victim, gfp_mask, false,
1680 pgdat, &nr_scanned);
1681 *total_scanned += nr_scanned;
1682 if (!soft_limit_excess(root_memcg))
1685 mem_cgroup_iter_break(root_memcg, victim);
1689 #ifdef CONFIG_LOCKDEP
1690 static struct lockdep_map memcg_oom_lock_dep_map = {
1691 .name = "memcg_oom_lock",
1695 static DEFINE_SPINLOCK(memcg_oom_lock);
1698 * Check OOM-Killer is already running under our hierarchy.
1699 * If someone is running, return false.
1701 static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
1703 struct mem_cgroup *iter, *failed = NULL;
1705 spin_lock(&memcg_oom_lock);
1707 for_each_mem_cgroup_tree(iter, memcg) {
1708 if (iter->oom_lock) {
1710 * this subtree of our hierarchy is already locked
1711 * so we cannot give a lock.
1714 mem_cgroup_iter_break(memcg, iter);
1717 iter->oom_lock = true;
1722 * OK, we failed to lock the whole subtree so we have
1723 * to clean up what we set up to the failing subtree
1725 for_each_mem_cgroup_tree(iter, memcg) {
1726 if (iter == failed) {
1727 mem_cgroup_iter_break(memcg, iter);
1730 iter->oom_lock = false;
1733 mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
1735 spin_unlock(&memcg_oom_lock);
1740 static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1742 struct mem_cgroup *iter;
1744 spin_lock(&memcg_oom_lock);
1745 mutex_release(&memcg_oom_lock_dep_map, _RET_IP_);
1746 for_each_mem_cgroup_tree(iter, memcg)
1747 iter->oom_lock = false;
1748 spin_unlock(&memcg_oom_lock);
1751 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1753 struct mem_cgroup *iter;
1755 spin_lock(&memcg_oom_lock);
1756 for_each_mem_cgroup_tree(iter, memcg)
1758 spin_unlock(&memcg_oom_lock);
1761 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1763 struct mem_cgroup *iter;
1766 * Be careful about under_oom underflows because a child memcg
1767 * could have been added after mem_cgroup_mark_under_oom.
1769 spin_lock(&memcg_oom_lock);
1770 for_each_mem_cgroup_tree(iter, memcg)
1771 if (iter->under_oom > 0)
1773 spin_unlock(&memcg_oom_lock);
1776 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1778 struct oom_wait_info {
1779 struct mem_cgroup *memcg;
1780 wait_queue_entry_t wait;
1783 static int memcg_oom_wake_function(wait_queue_entry_t *wait,
1784 unsigned mode, int sync, void *arg)
1786 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
1787 struct mem_cgroup *oom_wait_memcg;
1788 struct oom_wait_info *oom_wait_info;
1790 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1791 oom_wait_memcg = oom_wait_info->memcg;
1793 if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
1794 !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
1796 return autoremove_wake_function(wait, mode, sync, arg);
1799 static void memcg_oom_recover(struct mem_cgroup *memcg)
1802 * For the following lockless ->under_oom test, the only required
1803 * guarantee is that it must see the state asserted by an OOM when
1804 * this function is called as a result of userland actions
1805 * triggered by the notification of the OOM. This is trivially
1806 * achieved by invoking mem_cgroup_mark_under_oom() before
1807 * triggering notification.
1809 if (memcg && memcg->under_oom)
1810 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
1814 * Returns true if successfully killed one or more processes. Though in some
1815 * corner cases it can return true even without killing any process.
1817 static bool mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
1821 if (order > PAGE_ALLOC_COSTLY_ORDER)
1824 memcg_memory_event(memcg, MEMCG_OOM);
1827 * We are in the middle of the charge context here, so we
1828 * don't want to block when potentially sitting on a callstack
1829 * that holds all kinds of filesystem and mm locks.
1831 * cgroup1 allows disabling the OOM killer and waiting for outside
1832 * handling until the charge can succeed; remember the context and put
1833 * the task to sleep at the end of the page fault when all locks are
1836 * On the other hand, in-kernel OOM killer allows for an async victim
1837 * memory reclaim (oom_reaper) and that means that we are not solely
1838 * relying on the oom victim to make a forward progress and we can
1839 * invoke the oom killer here.
1841 * Please note that mem_cgroup_out_of_memory might fail to find a
1842 * victim and then we have to bail out from the charge path.
1844 if (memcg->oom_kill_disable) {
1845 if (current->in_user_fault) {
1846 css_get(&memcg->css);
1847 current->memcg_in_oom = memcg;
1848 current->memcg_oom_gfp_mask = mask;
1849 current->memcg_oom_order = order;
1854 mem_cgroup_mark_under_oom(memcg);
1856 locked = mem_cgroup_oom_trylock(memcg);
1859 mem_cgroup_oom_notify(memcg);
1861 mem_cgroup_unmark_under_oom(memcg);
1862 ret = mem_cgroup_out_of_memory(memcg, mask, order);
1865 mem_cgroup_oom_unlock(memcg);
1871 * mem_cgroup_oom_synchronize - complete memcg OOM handling
1872 * @handle: actually kill/wait or just clean up the OOM state
1874 * This has to be called at the end of a page fault if the memcg OOM
1875 * handler was enabled.
1877 * Memcg supports userspace OOM handling where failed allocations must
1878 * sleep on a waitqueue until the userspace task resolves the
1879 * situation. Sleeping directly in the charge context with all kinds
1880 * of locks held is not a good idea, instead we remember an OOM state
1881 * in the task and mem_cgroup_oom_synchronize() has to be called at
1882 * the end of the page fault to complete the OOM handling.
1884 * Returns %true if an ongoing memcg OOM situation was detected and
1885 * completed, %false otherwise.
1887 bool mem_cgroup_oom_synchronize(bool handle)
1889 struct mem_cgroup *memcg = current->memcg_in_oom;
1890 struct oom_wait_info owait;
1893 /* OOM is global, do not handle */
1900 owait.memcg = memcg;
1901 owait.wait.flags = 0;
1902 owait.wait.func = memcg_oom_wake_function;
1903 owait.wait.private = current;
1904 INIT_LIST_HEAD(&owait.wait.entry);
1906 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
1907 mem_cgroup_mark_under_oom(memcg);
1909 locked = mem_cgroup_oom_trylock(memcg);
1912 mem_cgroup_oom_notify(memcg);
1914 if (locked && !memcg->oom_kill_disable) {
1915 mem_cgroup_unmark_under_oom(memcg);
1916 finish_wait(&memcg_oom_waitq, &owait.wait);
1917 mem_cgroup_out_of_memory(memcg, current->memcg_oom_gfp_mask,
1918 current->memcg_oom_order);
1921 mem_cgroup_unmark_under_oom(memcg);
1922 finish_wait(&memcg_oom_waitq, &owait.wait);
1926 mem_cgroup_oom_unlock(memcg);
1928 * There is no guarantee that an OOM-lock contender
1929 * sees the wakeups triggered by the OOM kill
1930 * uncharges. Wake any sleepers explicitly.
1932 memcg_oom_recover(memcg);
1935 current->memcg_in_oom = NULL;
1936 css_put(&memcg->css);
1941 * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
1942 * @victim: task to be killed by the OOM killer
1943 * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
1945 * Returns a pointer to a memory cgroup, which has to be cleaned up
1946 * by killing all belonging OOM-killable tasks.
1948 * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
1950 struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim,
1951 struct mem_cgroup *oom_domain)
1953 struct mem_cgroup *oom_group = NULL;
1954 struct mem_cgroup *memcg;
1956 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
1960 oom_domain = root_mem_cgroup;
1964 memcg = mem_cgroup_from_task(victim);
1965 if (memcg == root_mem_cgroup)
1969 * If the victim task has been asynchronously moved to a different
1970 * memory cgroup, we might end up killing tasks outside oom_domain.
1971 * In this case it's better to ignore memory.group.oom.
1973 if (unlikely(!mem_cgroup_is_descendant(memcg, oom_domain)))
1977 * Traverse the memory cgroup hierarchy from the victim task's
1978 * cgroup up to the OOMing cgroup (or root) to find the
1979 * highest-level memory cgroup with oom.group set.
1981 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
1982 if (memcg->oom_group)
1985 if (memcg == oom_domain)
1990 css_get(&oom_group->css);
1997 void mem_cgroup_print_oom_group(struct mem_cgroup *memcg)
1999 pr_info("Tasks in ");
2000 pr_cont_cgroup_path(memcg->css.cgroup);
2001 pr_cont(" are going to be killed due to memory.oom.group set\n");
2005 * folio_memcg_lock - Bind a folio to its memcg.
2006 * @folio: The folio.
2008 * This function prevents unlocked LRU folios from being moved to
2011 * It ensures lifetime of the bound memcg. The caller is responsible
2012 * for the lifetime of the folio.
2014 void folio_memcg_lock(struct folio *folio)
2016 struct mem_cgroup *memcg;
2017 unsigned long flags;
2020 * The RCU lock is held throughout the transaction. The fast
2021 * path can get away without acquiring the memcg->move_lock
2022 * because page moving starts with an RCU grace period.
2026 if (mem_cgroup_disabled())
2029 memcg = folio_memcg(folio);
2030 if (unlikely(!memcg))
2033 #ifdef CONFIG_PROVE_LOCKING
2034 local_irq_save(flags);
2035 might_lock(&memcg->move_lock);
2036 local_irq_restore(flags);
2039 if (atomic_read(&memcg->moving_account) <= 0)
2042 spin_lock_irqsave(&memcg->move_lock, flags);
2043 if (memcg != folio_memcg(folio)) {
2044 spin_unlock_irqrestore(&memcg->move_lock, flags);
2049 * When charge migration first begins, we can have multiple
2050 * critical sections holding the fast-path RCU lock and one
2051 * holding the slowpath move_lock. Track the task who has the
2052 * move_lock for unlock_page_memcg().
2054 memcg->move_lock_task = current;
2055 memcg->move_lock_flags = flags;
2058 void lock_page_memcg(struct page *page)
2060 folio_memcg_lock(page_folio(page));
2063 static void __folio_memcg_unlock(struct mem_cgroup *memcg)
2065 if (memcg && memcg->move_lock_task == current) {
2066 unsigned long flags = memcg->move_lock_flags;
2068 memcg->move_lock_task = NULL;
2069 memcg->move_lock_flags = 0;
2071 spin_unlock_irqrestore(&memcg->move_lock, flags);
2078 * folio_memcg_unlock - Release the binding between a folio and its memcg.
2079 * @folio: The folio.
2081 * This releases the binding created by folio_memcg_lock(). This does
2082 * not change the accounting of this folio to its memcg, but it does
2083 * permit others to change it.
2085 void folio_memcg_unlock(struct folio *folio)
2087 __folio_memcg_unlock(folio_memcg(folio));
2090 void unlock_page_memcg(struct page *page)
2092 folio_memcg_unlock(page_folio(page));
2095 struct memcg_stock_pcp {
2096 local_lock_t stock_lock;
2097 struct mem_cgroup *cached; /* this never be root cgroup */
2098 unsigned int nr_pages;
2100 #ifdef CONFIG_MEMCG_KMEM
2101 struct obj_cgroup *cached_objcg;
2102 struct pglist_data *cached_pgdat;
2103 unsigned int nr_bytes;
2104 int nr_slab_reclaimable_b;
2105 int nr_slab_unreclaimable_b;
2108 struct work_struct work;
2109 unsigned long flags;
2110 #define FLUSHING_CACHED_CHARGE 0
2112 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock) = {
2113 .stock_lock = INIT_LOCAL_LOCK(stock_lock),
2115 static DEFINE_MUTEX(percpu_charge_mutex);
2117 #ifdef CONFIG_MEMCG_KMEM
2118 static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock);
2119 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2120 struct mem_cgroup *root_memcg);
2121 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages);
2124 static inline struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock)
2128 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2129 struct mem_cgroup *root_memcg)
2133 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages)
2139 * consume_stock: Try to consume stocked charge on this cpu.
2140 * @memcg: memcg to consume from.
2141 * @nr_pages: how many pages to charge.
2143 * The charges will only happen if @memcg matches the current cpu's memcg
2144 * stock, and at least @nr_pages are available in that stock. Failure to
2145 * service an allocation will refill the stock.
2147 * returns true if successful, false otherwise.
2149 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2151 struct memcg_stock_pcp *stock;
2152 unsigned long flags;
2155 if (nr_pages > MEMCG_CHARGE_BATCH)
2158 local_lock_irqsave(&memcg_stock.stock_lock, flags);
2160 stock = this_cpu_ptr(&memcg_stock);
2161 if (memcg == stock->cached && stock->nr_pages >= nr_pages) {
2162 stock->nr_pages -= nr_pages;
2166 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2172 * Returns stocks cached in percpu and reset cached information.
2174 static void drain_stock(struct memcg_stock_pcp *stock)
2176 struct mem_cgroup *old = stock->cached;
2181 if (stock->nr_pages) {
2182 page_counter_uncharge(&old->memory, stock->nr_pages);
2183 if (do_memsw_account())
2184 page_counter_uncharge(&old->memsw, stock->nr_pages);
2185 stock->nr_pages = 0;
2189 stock->cached = NULL;
2192 static void drain_local_stock(struct work_struct *dummy)
2194 struct memcg_stock_pcp *stock;
2195 struct obj_cgroup *old = NULL;
2196 unsigned long flags;
2199 * The only protection from cpu hotplug (memcg_hotplug_cpu_dead) vs.
2200 * drain_stock races is that we always operate on local CPU stock
2201 * here with IRQ disabled
2203 local_lock_irqsave(&memcg_stock.stock_lock, flags);
2205 stock = this_cpu_ptr(&memcg_stock);
2206 old = drain_obj_stock(stock);
2208 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2210 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2212 obj_cgroup_put(old);
2216 * Cache charges(val) to local per_cpu area.
2217 * This will be consumed by consume_stock() function, later.
2219 static void __refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2221 struct memcg_stock_pcp *stock;
2223 stock = this_cpu_ptr(&memcg_stock);
2224 if (stock->cached != memcg) { /* reset if necessary */
2226 css_get(&memcg->css);
2227 stock->cached = memcg;
2229 stock->nr_pages += nr_pages;
2231 if (stock->nr_pages > MEMCG_CHARGE_BATCH)
2235 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2237 unsigned long flags;
2239 local_lock_irqsave(&memcg_stock.stock_lock, flags);
2240 __refill_stock(memcg, nr_pages);
2241 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2245 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2246 * of the hierarchy under it.
2248 static void drain_all_stock(struct mem_cgroup *root_memcg)
2252 /* If someone's already draining, avoid adding running more workers. */
2253 if (!mutex_trylock(&percpu_charge_mutex))
2256 * Notify other cpus that system-wide "drain" is running
2257 * We do not care about races with the cpu hotplug because cpu down
2258 * as well as workers from this path always operate on the local
2259 * per-cpu data. CPU up doesn't touch memcg_stock at all.
2262 curcpu = smp_processor_id();
2263 for_each_online_cpu(cpu) {
2264 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2265 struct mem_cgroup *memcg;
2269 memcg = stock->cached;
2270 if (memcg && stock->nr_pages &&
2271 mem_cgroup_is_descendant(memcg, root_memcg))
2273 else if (obj_stock_flush_required(stock, root_memcg))
2278 !test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2280 drain_local_stock(&stock->work);
2282 schedule_work_on(cpu, &stock->work);
2286 mutex_unlock(&percpu_charge_mutex);
2289 static int memcg_hotplug_cpu_dead(unsigned int cpu)
2291 struct memcg_stock_pcp *stock;
2293 stock = &per_cpu(memcg_stock, cpu);
2299 static unsigned long reclaim_high(struct mem_cgroup *memcg,
2300 unsigned int nr_pages,
2303 unsigned long nr_reclaimed = 0;
2306 unsigned long pflags;
2308 if (page_counter_read(&memcg->memory) <=
2309 READ_ONCE(memcg->memory.high))
2312 memcg_memory_event(memcg, MEMCG_HIGH);
2314 psi_memstall_enter(&pflags);
2315 nr_reclaimed += try_to_free_mem_cgroup_pages(memcg, nr_pages,
2317 psi_memstall_leave(&pflags);
2318 } while ((memcg = parent_mem_cgroup(memcg)) &&
2319 !mem_cgroup_is_root(memcg));
2321 return nr_reclaimed;
2324 static void high_work_func(struct work_struct *work)
2326 struct mem_cgroup *memcg;
2328 memcg = container_of(work, struct mem_cgroup, high_work);
2329 reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
2333 * Clamp the maximum sleep time per allocation batch to 2 seconds. This is
2334 * enough to still cause a significant slowdown in most cases, while still
2335 * allowing diagnostics and tracing to proceed without becoming stuck.
2337 #define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ)
2340 * When calculating the delay, we use these either side of the exponentiation to
2341 * maintain precision and scale to a reasonable number of jiffies (see the table
2344 * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the
2345 * overage ratio to a delay.
2346 * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down the
2347 * proposed penalty in order to reduce to a reasonable number of jiffies, and
2348 * to produce a reasonable delay curve.
2350 * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a
2351 * reasonable delay curve compared to precision-adjusted overage, not
2352 * penalising heavily at first, but still making sure that growth beyond the
2353 * limit penalises misbehaviour cgroups by slowing them down exponentially. For
2354 * example, with a high of 100 megabytes:
2356 * +-------+------------------------+
2357 * | usage | time to allocate in ms |
2358 * +-------+------------------------+
2380 * +-------+------------------------+
2382 #define MEMCG_DELAY_PRECISION_SHIFT 20
2383 #define MEMCG_DELAY_SCALING_SHIFT 14
2385 static u64 calculate_overage(unsigned long usage, unsigned long high)
2393 * Prevent division by 0 in overage calculation by acting as if
2394 * it was a threshold of 1 page
2396 high = max(high, 1UL);
2398 overage = usage - high;
2399 overage <<= MEMCG_DELAY_PRECISION_SHIFT;
2400 return div64_u64(overage, high);
2403 static u64 mem_find_max_overage(struct mem_cgroup *memcg)
2405 u64 overage, max_overage = 0;
2408 overage = calculate_overage(page_counter_read(&memcg->memory),
2409 READ_ONCE(memcg->memory.high));
2410 max_overage = max(overage, max_overage);
2411 } while ((memcg = parent_mem_cgroup(memcg)) &&
2412 !mem_cgroup_is_root(memcg));
2417 static u64 swap_find_max_overage(struct mem_cgroup *memcg)
2419 u64 overage, max_overage = 0;
2422 overage = calculate_overage(page_counter_read(&memcg->swap),
2423 READ_ONCE(memcg->swap.high));
2425 memcg_memory_event(memcg, MEMCG_SWAP_HIGH);
2426 max_overage = max(overage, max_overage);
2427 } while ((memcg = parent_mem_cgroup(memcg)) &&
2428 !mem_cgroup_is_root(memcg));
2434 * Get the number of jiffies that we should penalise a mischievous cgroup which
2435 * is exceeding its memory.high by checking both it and its ancestors.
2437 static unsigned long calculate_high_delay(struct mem_cgroup *memcg,
2438 unsigned int nr_pages,
2441 unsigned long penalty_jiffies;
2447 * We use overage compared to memory.high to calculate the number of
2448 * jiffies to sleep (penalty_jiffies). Ideally this value should be
2449 * fairly lenient on small overages, and increasingly harsh when the
2450 * memcg in question makes it clear that it has no intention of stopping
2451 * its crazy behaviour, so we exponentially increase the delay based on
2454 penalty_jiffies = max_overage * max_overage * HZ;
2455 penalty_jiffies >>= MEMCG_DELAY_PRECISION_SHIFT;
2456 penalty_jiffies >>= MEMCG_DELAY_SCALING_SHIFT;
2459 * Factor in the task's own contribution to the overage, such that four
2460 * N-sized allocations are throttled approximately the same as one
2461 * 4N-sized allocation.
2463 * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or
2464 * larger the current charge patch is than that.
2466 return penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH;
2470 * Scheduled by try_charge() to be executed from the userland return path
2471 * and reclaims memory over the high limit.
2473 void mem_cgroup_handle_over_high(void)
2475 unsigned long penalty_jiffies;
2476 unsigned long pflags;
2477 unsigned long nr_reclaimed;
2478 unsigned int nr_pages = current->memcg_nr_pages_over_high;
2479 int nr_retries = MAX_RECLAIM_RETRIES;
2480 struct mem_cgroup *memcg;
2481 bool in_retry = false;
2483 if (likely(!nr_pages))
2486 memcg = get_mem_cgroup_from_mm(current->mm);
2487 current->memcg_nr_pages_over_high = 0;
2491 * The allocating task should reclaim at least the batch size, but for
2492 * subsequent retries we only want to do what's necessary to prevent oom
2493 * or breaching resource isolation.
2495 * This is distinct from memory.max or page allocator behaviour because
2496 * memory.high is currently batched, whereas memory.max and the page
2497 * allocator run every time an allocation is made.
2499 nr_reclaimed = reclaim_high(memcg,
2500 in_retry ? SWAP_CLUSTER_MAX : nr_pages,
2504 * memory.high is breached and reclaim is unable to keep up. Throttle
2505 * allocators proactively to slow down excessive growth.
2507 penalty_jiffies = calculate_high_delay(memcg, nr_pages,
2508 mem_find_max_overage(memcg));
2510 penalty_jiffies += calculate_high_delay(memcg, nr_pages,
2511 swap_find_max_overage(memcg));
2514 * Clamp the max delay per usermode return so as to still keep the
2515 * application moving forwards and also permit diagnostics, albeit
2518 penalty_jiffies = min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES);
2521 * Don't sleep if the amount of jiffies this memcg owes us is so low
2522 * that it's not even worth doing, in an attempt to be nice to those who
2523 * go only a small amount over their memory.high value and maybe haven't
2524 * been aggressively reclaimed enough yet.
2526 if (penalty_jiffies <= HZ / 100)
2530 * If reclaim is making forward progress but we're still over
2531 * memory.high, we want to encourage that rather than doing allocator
2534 if (nr_reclaimed || nr_retries--) {
2540 * If we exit early, we're guaranteed to die (since
2541 * schedule_timeout_killable sets TASK_KILLABLE). This means we don't
2542 * need to account for any ill-begotten jiffies to pay them off later.
2544 psi_memstall_enter(&pflags);
2545 schedule_timeout_killable(penalty_jiffies);
2546 psi_memstall_leave(&pflags);
2549 css_put(&memcg->css);
2552 static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask,
2553 unsigned int nr_pages)
2555 unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
2556 int nr_retries = MAX_RECLAIM_RETRIES;
2557 struct mem_cgroup *mem_over_limit;
2558 struct page_counter *counter;
2559 unsigned long nr_reclaimed;
2560 bool passed_oom = false;
2561 bool may_swap = true;
2562 bool drained = false;
2563 unsigned long pflags;
2566 if (consume_stock(memcg, nr_pages))
2569 if (!do_memsw_account() ||
2570 page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2571 if (page_counter_try_charge(&memcg->memory, batch, &counter))
2573 if (do_memsw_account())
2574 page_counter_uncharge(&memcg->memsw, batch);
2575 mem_over_limit = mem_cgroup_from_counter(counter, memory);
2577 mem_over_limit = mem_cgroup_from_counter(counter, memsw);
2581 if (batch > nr_pages) {
2587 * Prevent unbounded recursion when reclaim operations need to
2588 * allocate memory. This might exceed the limits temporarily,
2589 * but we prefer facilitating memory reclaim and getting back
2590 * under the limit over triggering OOM kills in these cases.
2592 if (unlikely(current->flags & PF_MEMALLOC))
2595 if (unlikely(task_in_memcg_oom(current)))
2598 if (!gfpflags_allow_blocking(gfp_mask))
2601 memcg_memory_event(mem_over_limit, MEMCG_MAX);
2603 psi_memstall_enter(&pflags);
2604 nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
2605 gfp_mask, may_swap);
2606 psi_memstall_leave(&pflags);
2608 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2612 drain_all_stock(mem_over_limit);
2617 if (gfp_mask & __GFP_NORETRY)
2620 * Even though the limit is exceeded at this point, reclaim
2621 * may have been able to free some pages. Retry the charge
2622 * before killing the task.
2624 * Only for regular pages, though: huge pages are rather
2625 * unlikely to succeed so close to the limit, and we fall back
2626 * to regular pages anyway in case of failure.
2628 if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
2631 * At task move, charge accounts can be doubly counted. So, it's
2632 * better to wait until the end of task_move if something is going on.
2634 if (mem_cgroup_wait_acct_move(mem_over_limit))
2640 if (gfp_mask & __GFP_RETRY_MAYFAIL)
2643 /* Avoid endless loop for tasks bypassed by the oom killer */
2644 if (passed_oom && task_is_dying())
2648 * keep retrying as long as the memcg oom killer is able to make
2649 * a forward progress or bypass the charge if the oom killer
2650 * couldn't make any progress.
2652 if (mem_cgroup_oom(mem_over_limit, gfp_mask,
2653 get_order(nr_pages * PAGE_SIZE))) {
2655 nr_retries = MAX_RECLAIM_RETRIES;
2660 * Memcg doesn't have a dedicated reserve for atomic
2661 * allocations. But like the global atomic pool, we need to
2662 * put the burden of reclaim on regular allocation requests
2663 * and let these go through as privileged allocations.
2665 if (!(gfp_mask & (__GFP_NOFAIL | __GFP_HIGH)))
2669 * The allocation either can't fail or will lead to more memory
2670 * being freed very soon. Allow memory usage go over the limit
2671 * temporarily by force charging it.
2673 page_counter_charge(&memcg->memory, nr_pages);
2674 if (do_memsw_account())
2675 page_counter_charge(&memcg->memsw, nr_pages);
2680 if (batch > nr_pages)
2681 refill_stock(memcg, batch - nr_pages);
2684 * If the hierarchy is above the normal consumption range, schedule
2685 * reclaim on returning to userland. We can perform reclaim here
2686 * if __GFP_RECLAIM but let's always punt for simplicity and so that
2687 * GFP_KERNEL can consistently be used during reclaim. @memcg is
2688 * not recorded as it most likely matches current's and won't
2689 * change in the meantime. As high limit is checked again before
2690 * reclaim, the cost of mismatch is negligible.
2693 bool mem_high, swap_high;
2695 mem_high = page_counter_read(&memcg->memory) >
2696 READ_ONCE(memcg->memory.high);
2697 swap_high = page_counter_read(&memcg->swap) >
2698 READ_ONCE(memcg->swap.high);
2700 /* Don't bother a random interrupted task */
2703 schedule_work(&memcg->high_work);
2709 if (mem_high || swap_high) {
2711 * The allocating tasks in this cgroup will need to do
2712 * reclaim or be throttled to prevent further growth
2713 * of the memory or swap footprints.
2715 * Target some best-effort fairness between the tasks,
2716 * and distribute reclaim work and delay penalties
2717 * based on how much each task is actually allocating.
2719 current->memcg_nr_pages_over_high += batch;
2720 set_notify_resume(current);
2723 } while ((memcg = parent_mem_cgroup(memcg)));
2725 if (current->memcg_nr_pages_over_high > MEMCG_CHARGE_BATCH &&
2726 !(current->flags & PF_MEMALLOC) &&
2727 gfpflags_allow_blocking(gfp_mask)) {
2728 mem_cgroup_handle_over_high();
2733 static inline int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2734 unsigned int nr_pages)
2736 if (mem_cgroup_is_root(memcg))
2739 return try_charge_memcg(memcg, gfp_mask, nr_pages);
2742 static inline void cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
2744 if (mem_cgroup_is_root(memcg))
2747 page_counter_uncharge(&memcg->memory, nr_pages);
2748 if (do_memsw_account())
2749 page_counter_uncharge(&memcg->memsw, nr_pages);
2752 static void commit_charge(struct folio *folio, struct mem_cgroup *memcg)
2754 VM_BUG_ON_FOLIO(folio_memcg(folio), folio);
2756 * Any of the following ensures page's memcg stability:
2760 * - lock_page_memcg()
2761 * - exclusive reference
2763 folio->memcg_data = (unsigned long)memcg;
2766 #ifdef CONFIG_MEMCG_KMEM
2768 * The allocated objcg pointers array is not accounted directly.
2769 * Moreover, it should not come from DMA buffer and is not readily
2770 * reclaimable. So those GFP bits should be masked off.
2772 #define OBJCGS_CLEAR_MASK (__GFP_DMA | __GFP_RECLAIMABLE | __GFP_ACCOUNT)
2775 * mod_objcg_mlstate() may be called with irq enabled, so
2776 * mod_memcg_lruvec_state() should be used.
2778 static inline void mod_objcg_mlstate(struct obj_cgroup *objcg,
2779 struct pglist_data *pgdat,
2780 enum node_stat_item idx, int nr)
2782 struct mem_cgroup *memcg;
2783 struct lruvec *lruvec;
2786 memcg = obj_cgroup_memcg(objcg);
2787 lruvec = mem_cgroup_lruvec(memcg, pgdat);
2788 mod_memcg_lruvec_state(lruvec, idx, nr);
2792 int memcg_alloc_slab_cgroups(struct slab *slab, struct kmem_cache *s,
2793 gfp_t gfp, bool new_slab)
2795 unsigned int objects = objs_per_slab(s, slab);
2796 unsigned long memcg_data;
2799 gfp &= ~OBJCGS_CLEAR_MASK;
2800 vec = kcalloc_node(objects, sizeof(struct obj_cgroup *), gfp,
2805 memcg_data = (unsigned long) vec | MEMCG_DATA_OBJCGS;
2808 * If the slab is brand new and nobody can yet access its
2809 * memcg_data, no synchronization is required and memcg_data can
2810 * be simply assigned.
2812 slab->memcg_data = memcg_data;
2813 } else if (cmpxchg(&slab->memcg_data, 0, memcg_data)) {
2815 * If the slab is already in use, somebody can allocate and
2816 * assign obj_cgroups in parallel. In this case the existing
2817 * objcg vector should be reused.
2823 kmemleak_not_leak(vec);
2828 * Returns a pointer to the memory cgroup to which the kernel object is charged.
2830 * A passed kernel object can be a slab object or a generic kernel page, so
2831 * different mechanisms for getting the memory cgroup pointer should be used.
2832 * In certain cases (e.g. kernel stacks or large kmallocs with SLUB) the caller
2833 * can not know for sure how the kernel object is implemented.
2834 * mem_cgroup_from_obj() can be safely used in such cases.
2836 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
2837 * cgroup_mutex, etc.
2839 struct mem_cgroup *mem_cgroup_from_obj(void *p)
2841 struct folio *folio;
2843 if (mem_cgroup_disabled())
2846 folio = virt_to_folio(p);
2849 * Slab objects are accounted individually, not per-page.
2850 * Memcg membership data for each individual object is saved in
2853 if (folio_test_slab(folio)) {
2854 struct obj_cgroup **objcgs;
2858 slab = folio_slab(folio);
2859 objcgs = slab_objcgs(slab);
2863 off = obj_to_index(slab->slab_cache, slab, p);
2865 return obj_cgroup_memcg(objcgs[off]);
2871 * page_memcg_check() is used here, because in theory we can encounter
2872 * a folio where the slab flag has been cleared already, but
2873 * slab->memcg_data has not been freed yet
2874 * page_memcg_check(page) will guarantee that a proper memory
2875 * cgroup pointer or NULL will be returned.
2877 return page_memcg_check(folio_page(folio, 0));
2880 __always_inline struct obj_cgroup *get_obj_cgroup_from_current(void)
2882 struct obj_cgroup *objcg = NULL;
2883 struct mem_cgroup *memcg;
2885 if (memcg_kmem_bypass())
2889 if (unlikely(active_memcg()))
2890 memcg = active_memcg();
2892 memcg = mem_cgroup_from_task(current);
2894 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg)) {
2895 objcg = rcu_dereference(memcg->objcg);
2896 if (objcg && obj_cgroup_tryget(objcg))
2905 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages)
2907 mod_memcg_state(memcg, MEMCG_KMEM, nr_pages);
2908 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
2910 page_counter_charge(&memcg->kmem, nr_pages);
2912 page_counter_uncharge(&memcg->kmem, -nr_pages);
2918 * obj_cgroup_uncharge_pages: uncharge a number of kernel pages from a objcg
2919 * @objcg: object cgroup to uncharge
2920 * @nr_pages: number of pages to uncharge
2922 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
2923 unsigned int nr_pages)
2925 struct mem_cgroup *memcg;
2927 memcg = get_mem_cgroup_from_objcg(objcg);
2929 memcg_account_kmem(memcg, -nr_pages);
2930 refill_stock(memcg, nr_pages);
2932 css_put(&memcg->css);
2936 * obj_cgroup_charge_pages: charge a number of kernel pages to a objcg
2937 * @objcg: object cgroup to charge
2938 * @gfp: reclaim mode
2939 * @nr_pages: number of pages to charge
2941 * Returns 0 on success, an error code on failure.
2943 static int obj_cgroup_charge_pages(struct obj_cgroup *objcg, gfp_t gfp,
2944 unsigned int nr_pages)
2946 struct mem_cgroup *memcg;
2949 memcg = get_mem_cgroup_from_objcg(objcg);
2951 ret = try_charge_memcg(memcg, gfp, nr_pages);
2955 memcg_account_kmem(memcg, nr_pages);
2957 css_put(&memcg->css);
2963 * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup
2964 * @page: page to charge
2965 * @gfp: reclaim mode
2966 * @order: allocation order
2968 * Returns 0 on success, an error code on failure.
2970 int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
2972 struct obj_cgroup *objcg;
2975 objcg = get_obj_cgroup_from_current();
2977 ret = obj_cgroup_charge_pages(objcg, gfp, 1 << order);
2979 page->memcg_data = (unsigned long)objcg |
2983 obj_cgroup_put(objcg);
2989 * __memcg_kmem_uncharge_page: uncharge a kmem page
2990 * @page: page to uncharge
2991 * @order: allocation order
2993 void __memcg_kmem_uncharge_page(struct page *page, int order)
2995 struct folio *folio = page_folio(page);
2996 struct obj_cgroup *objcg;
2997 unsigned int nr_pages = 1 << order;
2999 if (!folio_memcg_kmem(folio))
3002 objcg = __folio_objcg(folio);
3003 obj_cgroup_uncharge_pages(objcg, nr_pages);
3004 folio->memcg_data = 0;
3005 obj_cgroup_put(objcg);
3008 void mod_objcg_state(struct obj_cgroup *objcg, struct pglist_data *pgdat,
3009 enum node_stat_item idx, int nr)
3011 struct memcg_stock_pcp *stock;
3012 struct obj_cgroup *old = NULL;
3013 unsigned long flags;
3016 local_lock_irqsave(&memcg_stock.stock_lock, flags);
3017 stock = this_cpu_ptr(&memcg_stock);
3020 * Save vmstat data in stock and skip vmstat array update unless
3021 * accumulating over a page of vmstat data or when pgdat or idx
3024 if (stock->cached_objcg != objcg) {
3025 old = drain_obj_stock(stock);
3026 obj_cgroup_get(objcg);
3027 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3028 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3029 stock->cached_objcg = objcg;
3030 stock->cached_pgdat = pgdat;
3031 } else if (stock->cached_pgdat != pgdat) {
3032 /* Flush the existing cached vmstat data */
3033 struct pglist_data *oldpg = stock->cached_pgdat;
3035 if (stock->nr_slab_reclaimable_b) {
3036 mod_objcg_mlstate(objcg, oldpg, NR_SLAB_RECLAIMABLE_B,
3037 stock->nr_slab_reclaimable_b);
3038 stock->nr_slab_reclaimable_b = 0;
3040 if (stock->nr_slab_unreclaimable_b) {
3041 mod_objcg_mlstate(objcg, oldpg, NR_SLAB_UNRECLAIMABLE_B,
3042 stock->nr_slab_unreclaimable_b);
3043 stock->nr_slab_unreclaimable_b = 0;
3045 stock->cached_pgdat = pgdat;
3048 bytes = (idx == NR_SLAB_RECLAIMABLE_B) ? &stock->nr_slab_reclaimable_b
3049 : &stock->nr_slab_unreclaimable_b;
3051 * Even for large object >= PAGE_SIZE, the vmstat data will still be
3052 * cached locally at least once before pushing it out.
3059 if (abs(*bytes) > PAGE_SIZE) {
3067 mod_objcg_mlstate(objcg, pgdat, idx, nr);
3069 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3071 obj_cgroup_put(old);
3074 static bool consume_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes)
3076 struct memcg_stock_pcp *stock;
3077 unsigned long flags;
3080 local_lock_irqsave(&memcg_stock.stock_lock, flags);
3082 stock = this_cpu_ptr(&memcg_stock);
3083 if (objcg == stock->cached_objcg && stock->nr_bytes >= nr_bytes) {
3084 stock->nr_bytes -= nr_bytes;
3088 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3093 static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock)
3095 struct obj_cgroup *old = stock->cached_objcg;
3100 if (stock->nr_bytes) {
3101 unsigned int nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3102 unsigned int nr_bytes = stock->nr_bytes & (PAGE_SIZE - 1);
3105 struct mem_cgroup *memcg;
3107 memcg = get_mem_cgroup_from_objcg(old);
3109 memcg_account_kmem(memcg, -nr_pages);
3110 __refill_stock(memcg, nr_pages);
3112 css_put(&memcg->css);
3116 * The leftover is flushed to the centralized per-memcg value.
3117 * On the next attempt to refill obj stock it will be moved
3118 * to a per-cpu stock (probably, on an other CPU), see
3119 * refill_obj_stock().
3121 * How often it's flushed is a trade-off between the memory
3122 * limit enforcement accuracy and potential CPU contention,
3123 * so it might be changed in the future.
3125 atomic_add(nr_bytes, &old->nr_charged_bytes);
3126 stock->nr_bytes = 0;
3130 * Flush the vmstat data in current stock
3132 if (stock->nr_slab_reclaimable_b || stock->nr_slab_unreclaimable_b) {
3133 if (stock->nr_slab_reclaimable_b) {
3134 mod_objcg_mlstate(old, stock->cached_pgdat,
3135 NR_SLAB_RECLAIMABLE_B,
3136 stock->nr_slab_reclaimable_b);
3137 stock->nr_slab_reclaimable_b = 0;
3139 if (stock->nr_slab_unreclaimable_b) {
3140 mod_objcg_mlstate(old, stock->cached_pgdat,
3141 NR_SLAB_UNRECLAIMABLE_B,
3142 stock->nr_slab_unreclaimable_b);
3143 stock->nr_slab_unreclaimable_b = 0;
3145 stock->cached_pgdat = NULL;
3148 stock->cached_objcg = NULL;
3150 * The `old' objects needs to be released by the caller via
3151 * obj_cgroup_put() outside of memcg_stock_pcp::stock_lock.
3156 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
3157 struct mem_cgroup *root_memcg)
3159 struct mem_cgroup *memcg;
3161 if (stock->cached_objcg) {
3162 memcg = obj_cgroup_memcg(stock->cached_objcg);
3163 if (memcg && mem_cgroup_is_descendant(memcg, root_memcg))
3170 static void refill_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes,
3171 bool allow_uncharge)
3173 struct memcg_stock_pcp *stock;
3174 struct obj_cgroup *old = NULL;
3175 unsigned long flags;
3176 unsigned int nr_pages = 0;
3178 local_lock_irqsave(&memcg_stock.stock_lock, flags);
3180 stock = this_cpu_ptr(&memcg_stock);
3181 if (stock->cached_objcg != objcg) { /* reset if necessary */
3182 old = drain_obj_stock(stock);
3183 obj_cgroup_get(objcg);
3184 stock->cached_objcg = objcg;
3185 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3186 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3187 allow_uncharge = true; /* Allow uncharge when objcg changes */
3189 stock->nr_bytes += nr_bytes;
3191 if (allow_uncharge && (stock->nr_bytes > PAGE_SIZE)) {
3192 nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3193 stock->nr_bytes &= (PAGE_SIZE - 1);
3196 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3198 obj_cgroup_put(old);
3201 obj_cgroup_uncharge_pages(objcg, nr_pages);
3204 int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size)
3206 unsigned int nr_pages, nr_bytes;
3209 if (consume_obj_stock(objcg, size))
3213 * In theory, objcg->nr_charged_bytes can have enough
3214 * pre-charged bytes to satisfy the allocation. However,
3215 * flushing objcg->nr_charged_bytes requires two atomic
3216 * operations, and objcg->nr_charged_bytes can't be big.
3217 * The shared objcg->nr_charged_bytes can also become a
3218 * performance bottleneck if all tasks of the same memcg are
3219 * trying to update it. So it's better to ignore it and try
3220 * grab some new pages. The stock's nr_bytes will be flushed to
3221 * objcg->nr_charged_bytes later on when objcg changes.
3223 * The stock's nr_bytes may contain enough pre-charged bytes
3224 * to allow one less page from being charged, but we can't rely
3225 * on the pre-charged bytes not being changed outside of
3226 * consume_obj_stock() or refill_obj_stock(). So ignore those
3227 * pre-charged bytes as well when charging pages. To avoid a
3228 * page uncharge right after a page charge, we set the
3229 * allow_uncharge flag to false when calling refill_obj_stock()
3230 * to temporarily allow the pre-charged bytes to exceed the page
3231 * size limit. The maximum reachable value of the pre-charged
3232 * bytes is (sizeof(object) + PAGE_SIZE - 2) if there is no data
3235 nr_pages = size >> PAGE_SHIFT;
3236 nr_bytes = size & (PAGE_SIZE - 1);
3241 ret = obj_cgroup_charge_pages(objcg, gfp, nr_pages);
3242 if (!ret && nr_bytes)
3243 refill_obj_stock(objcg, PAGE_SIZE - nr_bytes, false);
3248 void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size)
3250 refill_obj_stock(objcg, size, true);
3253 #endif /* CONFIG_MEMCG_KMEM */
3256 * Because page_memcg(head) is not set on tails, set it now.
3258 void split_page_memcg(struct page *head, unsigned int nr)
3260 struct folio *folio = page_folio(head);
3261 struct mem_cgroup *memcg = folio_memcg(folio);
3264 if (mem_cgroup_disabled() || !memcg)
3267 for (i = 1; i < nr; i++)
3268 folio_page(folio, i)->memcg_data = folio->memcg_data;
3270 if (folio_memcg_kmem(folio))
3271 obj_cgroup_get_many(__folio_objcg(folio), nr - 1);
3273 css_get_many(&memcg->css, nr - 1);
3276 #ifdef CONFIG_MEMCG_SWAP
3278 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3279 * @entry: swap entry to be moved
3280 * @from: mem_cgroup which the entry is moved from
3281 * @to: mem_cgroup which the entry is moved to
3283 * It succeeds only when the swap_cgroup's record for this entry is the same
3284 * as the mem_cgroup's id of @from.
3286 * Returns 0 on success, -EINVAL on failure.
3288 * The caller must have charged to @to, IOW, called page_counter_charge() about
3289 * both res and memsw, and called css_get().
3291 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3292 struct mem_cgroup *from, struct mem_cgroup *to)
3294 unsigned short old_id, new_id;
3296 old_id = mem_cgroup_id(from);
3297 new_id = mem_cgroup_id(to);
3299 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3300 mod_memcg_state(from, MEMCG_SWAP, -1);
3301 mod_memcg_state(to, MEMCG_SWAP, 1);
3307 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3308 struct mem_cgroup *from, struct mem_cgroup *to)
3314 static DEFINE_MUTEX(memcg_max_mutex);
3316 static int mem_cgroup_resize_max(struct mem_cgroup *memcg,
3317 unsigned long max, bool memsw)
3319 bool enlarge = false;
3320 bool drained = false;
3322 bool limits_invariant;
3323 struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory;
3326 if (signal_pending(current)) {
3331 mutex_lock(&memcg_max_mutex);
3333 * Make sure that the new limit (memsw or memory limit) doesn't
3334 * break our basic invariant rule memory.max <= memsw.max.
3336 limits_invariant = memsw ? max >= READ_ONCE(memcg->memory.max) :
3337 max <= memcg->memsw.max;
3338 if (!limits_invariant) {
3339 mutex_unlock(&memcg_max_mutex);
3343 if (max > counter->max)
3345 ret = page_counter_set_max(counter, max);
3346 mutex_unlock(&memcg_max_mutex);
3352 drain_all_stock(memcg);
3357 if (!try_to_free_mem_cgroup_pages(memcg, 1,
3358 GFP_KERNEL, !memsw)) {
3364 if (!ret && enlarge)
3365 memcg_oom_recover(memcg);
3370 unsigned long mem_cgroup_soft_limit_reclaim(pg_data_t *pgdat, int order,
3372 unsigned long *total_scanned)
3374 unsigned long nr_reclaimed = 0;
3375 struct mem_cgroup_per_node *mz, *next_mz = NULL;
3376 unsigned long reclaimed;
3378 struct mem_cgroup_tree_per_node *mctz;
3379 unsigned long excess;
3380 unsigned long nr_scanned;
3385 mctz = soft_limit_tree.rb_tree_per_node[pgdat->node_id];
3388 * Do not even bother to check the largest node if the root
3389 * is empty. Do it lockless to prevent lock bouncing. Races
3390 * are acceptable as soft limit is best effort anyway.
3392 if (!mctz || RB_EMPTY_ROOT(&mctz->rb_root))
3396 * This loop can run a while, specially if mem_cgroup's continuously
3397 * keep exceeding their soft limit and putting the system under
3404 mz = mem_cgroup_largest_soft_limit_node(mctz);
3409 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, pgdat,
3410 gfp_mask, &nr_scanned);
3411 nr_reclaimed += reclaimed;
3412 *total_scanned += nr_scanned;
3413 spin_lock_irq(&mctz->lock);
3414 __mem_cgroup_remove_exceeded(mz, mctz);
3417 * If we failed to reclaim anything from this memory cgroup
3418 * it is time to move on to the next cgroup
3422 next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
3424 excess = soft_limit_excess(mz->memcg);
3426 * One school of thought says that we should not add
3427 * back the node to the tree if reclaim returns 0.
3428 * But our reclaim could return 0, simply because due
3429 * to priority we are exposing a smaller subset of
3430 * memory to reclaim from. Consider this as a longer
3433 /* If excess == 0, no tree ops */
3434 __mem_cgroup_insert_exceeded(mz, mctz, excess);
3435 spin_unlock_irq(&mctz->lock);
3436 css_put(&mz->memcg->css);
3439 * Could not reclaim anything and there are no more
3440 * mem cgroups to try or we seem to be looping without
3441 * reclaiming anything.
3443 if (!nr_reclaimed &&
3445 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3447 } while (!nr_reclaimed);
3449 css_put(&next_mz->memcg->css);
3450 return nr_reclaimed;
3454 * Reclaims as many pages from the given memcg as possible.
3456 * Caller is responsible for holding css reference for memcg.
3458 static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
3460 int nr_retries = MAX_RECLAIM_RETRIES;
3462 /* we call try-to-free pages for make this cgroup empty */
3463 lru_add_drain_all();
3465 drain_all_stock(memcg);
3467 /* try to free all pages in this cgroup */
3468 while (nr_retries && page_counter_read(&memcg->memory)) {
3469 if (signal_pending(current))
3472 if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL, true))
3479 static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
3480 char *buf, size_t nbytes,
3483 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3485 if (mem_cgroup_is_root(memcg))
3487 return mem_cgroup_force_empty(memcg) ?: nbytes;
3490 static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
3496 static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
3497 struct cftype *cft, u64 val)
3502 pr_warn_once("Non-hierarchical mode is deprecated. "
3503 "Please report your usecase to linux-mm@kvack.org if you "
3504 "depend on this functionality.\n");
3509 static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3513 if (mem_cgroup_is_root(memcg)) {
3514 mem_cgroup_flush_stats();
3515 val = memcg_page_state(memcg, NR_FILE_PAGES) +
3516 memcg_page_state(memcg, NR_ANON_MAPPED);
3518 val += memcg_page_state(memcg, MEMCG_SWAP);
3521 val = page_counter_read(&memcg->memory);
3523 val = page_counter_read(&memcg->memsw);
3536 static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
3539 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3540 struct page_counter *counter;
3542 switch (MEMFILE_TYPE(cft->private)) {
3544 counter = &memcg->memory;
3547 counter = &memcg->memsw;
3550 counter = &memcg->kmem;
3553 counter = &memcg->tcpmem;
3559 switch (MEMFILE_ATTR(cft->private)) {
3561 if (counter == &memcg->memory)
3562 return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
3563 if (counter == &memcg->memsw)
3564 return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
3565 return (u64)page_counter_read(counter) * PAGE_SIZE;
3567 return (u64)counter->max * PAGE_SIZE;
3569 return (u64)counter->watermark * PAGE_SIZE;
3571 return counter->failcnt;
3572 case RES_SOFT_LIMIT:
3573 return (u64)memcg->soft_limit * PAGE_SIZE;
3579 #ifdef CONFIG_MEMCG_KMEM
3580 static int memcg_online_kmem(struct mem_cgroup *memcg)
3582 struct obj_cgroup *objcg;
3584 if (cgroup_memory_nokmem)
3587 if (unlikely(mem_cgroup_is_root(memcg)))
3590 objcg = obj_cgroup_alloc();
3594 objcg->memcg = memcg;
3595 rcu_assign_pointer(memcg->objcg, objcg);
3597 static_branch_enable(&memcg_kmem_enabled_key);
3599 memcg->kmemcg_id = memcg->id.id;
3604 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3606 struct mem_cgroup *parent;
3608 if (cgroup_memory_nokmem)
3611 if (unlikely(mem_cgroup_is_root(memcg)))
3614 parent = parent_mem_cgroup(memcg);
3616 parent = root_mem_cgroup;
3618 memcg_reparent_objcgs(memcg, parent);
3621 * After we have finished memcg_reparent_objcgs(), all list_lrus
3622 * corresponding to this cgroup are guaranteed to remain empty.
3623 * The ordering is imposed by list_lru_node->lock taken by
3624 * memcg_reparent_list_lrus().
3626 memcg_reparent_list_lrus(memcg, parent);
3629 static int memcg_online_kmem(struct mem_cgroup *memcg)
3633 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3636 #endif /* CONFIG_MEMCG_KMEM */
3638 static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max)
3642 mutex_lock(&memcg_max_mutex);
3644 ret = page_counter_set_max(&memcg->tcpmem, max);
3648 if (!memcg->tcpmem_active) {
3650 * The active flag needs to be written after the static_key
3651 * update. This is what guarantees that the socket activation
3652 * function is the last one to run. See mem_cgroup_sk_alloc()
3653 * for details, and note that we don't mark any socket as
3654 * belonging to this memcg until that flag is up.
3656 * We need to do this, because static_keys will span multiple
3657 * sites, but we can't control their order. If we mark a socket
3658 * as accounted, but the accounting functions are not patched in
3659 * yet, we'll lose accounting.
3661 * We never race with the readers in mem_cgroup_sk_alloc(),
3662 * because when this value change, the code to process it is not
3665 static_branch_inc(&memcg_sockets_enabled_key);
3666 memcg->tcpmem_active = true;
3669 mutex_unlock(&memcg_max_mutex);
3674 * The user of this function is...
3677 static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
3678 char *buf, size_t nbytes, loff_t off)
3680 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3681 unsigned long nr_pages;
3684 buf = strstrip(buf);
3685 ret = page_counter_memparse(buf, "-1", &nr_pages);
3689 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3691 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3695 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3697 ret = mem_cgroup_resize_max(memcg, nr_pages, false);
3700 ret = mem_cgroup_resize_max(memcg, nr_pages, true);
3703 /* kmem.limit_in_bytes is deprecated. */
3707 ret = memcg_update_tcp_max(memcg, nr_pages);
3711 case RES_SOFT_LIMIT:
3712 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
3715 memcg->soft_limit = nr_pages;
3720 return ret ?: nbytes;
3723 static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
3724 size_t nbytes, loff_t off)
3726 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3727 struct page_counter *counter;
3729 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3731 counter = &memcg->memory;
3734 counter = &memcg->memsw;
3737 counter = &memcg->kmem;
3740 counter = &memcg->tcpmem;
3746 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3748 page_counter_reset_watermark(counter);
3751 counter->failcnt = 0;
3760 static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
3763 return mem_cgroup_from_css(css)->move_charge_at_immigrate;
3767 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3768 struct cftype *cft, u64 val)
3770 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3772 if (val & ~MOVE_MASK)
3776 * No kind of locking is needed in here, because ->can_attach() will
3777 * check this value once in the beginning of the process, and then carry
3778 * on with stale data. This means that changes to this value will only
3779 * affect task migrations starting after the change.
3781 memcg->move_charge_at_immigrate = val;
3785 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3786 struct cftype *cft, u64 val)
3794 #define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE))
3795 #define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON))
3796 #define LRU_ALL ((1 << NR_LRU_LISTS) - 1)
3798 static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
3799 int nid, unsigned int lru_mask, bool tree)
3801 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
3802 unsigned long nr = 0;
3805 VM_BUG_ON((unsigned)nid >= nr_node_ids);
3808 if (!(BIT(lru) & lru_mask))
3811 nr += lruvec_page_state(lruvec, NR_LRU_BASE + lru);
3813 nr += lruvec_page_state_local(lruvec, NR_LRU_BASE + lru);
3818 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
3819 unsigned int lru_mask,
3822 unsigned long nr = 0;
3826 if (!(BIT(lru) & lru_mask))
3829 nr += memcg_page_state(memcg, NR_LRU_BASE + lru);
3831 nr += memcg_page_state_local(memcg, NR_LRU_BASE + lru);
3836 static int memcg_numa_stat_show(struct seq_file *m, void *v)
3840 unsigned int lru_mask;
3843 static const struct numa_stat stats[] = {
3844 { "total", LRU_ALL },
3845 { "file", LRU_ALL_FILE },
3846 { "anon", LRU_ALL_ANON },
3847 { "unevictable", BIT(LRU_UNEVICTABLE) },
3849 const struct numa_stat *stat;
3851 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
3853 mem_cgroup_flush_stats();
3855 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
3856 seq_printf(m, "%s=%lu", stat->name,
3857 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
3859 for_each_node_state(nid, N_MEMORY)
3860 seq_printf(m, " N%d=%lu", nid,
3861 mem_cgroup_node_nr_lru_pages(memcg, nid,
3862 stat->lru_mask, false));
3866 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
3868 seq_printf(m, "hierarchical_%s=%lu", stat->name,
3869 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
3871 for_each_node_state(nid, N_MEMORY)
3872 seq_printf(m, " N%d=%lu", nid,
3873 mem_cgroup_node_nr_lru_pages(memcg, nid,
3874 stat->lru_mask, true));
3880 #endif /* CONFIG_NUMA */
3882 static const unsigned int memcg1_stats[] = {
3885 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3895 static const char *const memcg1_stat_names[] = {
3898 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3908 /* Universal VM events cgroup1 shows, original sort order */
3909 static const unsigned int memcg1_events[] = {
3916 static int memcg_stat_show(struct seq_file *m, void *v)
3918 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
3919 unsigned long memory, memsw;
3920 struct mem_cgroup *mi;
3923 BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats));
3925 mem_cgroup_flush_stats();
3927 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
3930 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
3932 nr = memcg_page_state_local(memcg, memcg1_stats[i]);
3933 seq_printf(m, "%s %lu\n", memcg1_stat_names[i], nr * PAGE_SIZE);
3936 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
3937 seq_printf(m, "%s %lu\n", vm_event_name(memcg1_events[i]),
3938 memcg_events_local(memcg, memcg1_events[i]));
3940 for (i = 0; i < NR_LRU_LISTS; i++)
3941 seq_printf(m, "%s %lu\n", lru_list_name(i),
3942 memcg_page_state_local(memcg, NR_LRU_BASE + i) *
3945 /* Hierarchical information */
3946 memory = memsw = PAGE_COUNTER_MAX;
3947 for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
3948 memory = min(memory, READ_ONCE(mi->memory.max));
3949 memsw = min(memsw, READ_ONCE(mi->memsw.max));
3951 seq_printf(m, "hierarchical_memory_limit %llu\n",
3952 (u64)memory * PAGE_SIZE);
3953 if (do_memsw_account())
3954 seq_printf(m, "hierarchical_memsw_limit %llu\n",
3955 (u64)memsw * PAGE_SIZE);
3957 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
3960 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
3962 nr = memcg_page_state(memcg, memcg1_stats[i]);
3963 seq_printf(m, "total_%s %llu\n", memcg1_stat_names[i],
3964 (u64)nr * PAGE_SIZE);
3967 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
3968 seq_printf(m, "total_%s %llu\n",
3969 vm_event_name(memcg1_events[i]),
3970 (u64)memcg_events(memcg, memcg1_events[i]));
3972 for (i = 0; i < NR_LRU_LISTS; i++)
3973 seq_printf(m, "total_%s %llu\n", lru_list_name(i),
3974 (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
3977 #ifdef CONFIG_DEBUG_VM
3980 struct mem_cgroup_per_node *mz;
3981 unsigned long anon_cost = 0;
3982 unsigned long file_cost = 0;
3984 for_each_online_pgdat(pgdat) {
3985 mz = memcg->nodeinfo[pgdat->node_id];
3987 anon_cost += mz->lruvec.anon_cost;
3988 file_cost += mz->lruvec.file_cost;
3990 seq_printf(m, "anon_cost %lu\n", anon_cost);
3991 seq_printf(m, "file_cost %lu\n", file_cost);
3998 static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
4001 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4003 return mem_cgroup_swappiness(memcg);
4006 static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
4007 struct cftype *cft, u64 val)
4009 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4014 if (!mem_cgroup_is_root(memcg))
4015 memcg->swappiness = val;
4017 vm_swappiness = val;
4022 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4024 struct mem_cgroup_threshold_ary *t;
4025 unsigned long usage;
4030 t = rcu_dereference(memcg->thresholds.primary);
4032 t = rcu_dereference(memcg->memsw_thresholds.primary);
4037 usage = mem_cgroup_usage(memcg, swap);
4040 * current_threshold points to threshold just below or equal to usage.
4041 * If it's not true, a threshold was crossed after last
4042 * call of __mem_cgroup_threshold().
4044 i = t->current_threshold;
4047 * Iterate backward over array of thresholds starting from
4048 * current_threshold and check if a threshold is crossed.
4049 * If none of thresholds below usage is crossed, we read
4050 * only one element of the array here.
4052 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4053 eventfd_signal(t->entries[i].eventfd, 1);
4055 /* i = current_threshold + 1 */
4059 * Iterate forward over array of thresholds starting from
4060 * current_threshold+1 and check if a threshold is crossed.
4061 * If none of thresholds above usage is crossed, we read
4062 * only one element of the array here.
4064 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4065 eventfd_signal(t->entries[i].eventfd, 1);
4067 /* Update current_threshold */
4068 t->current_threshold = i - 1;
4073 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4076 __mem_cgroup_threshold(memcg, false);
4077 if (do_memsw_account())
4078 __mem_cgroup_threshold(memcg, true);
4080 memcg = parent_mem_cgroup(memcg);
4084 static int compare_thresholds(const void *a, const void *b)
4086 const struct mem_cgroup_threshold *_a = a;
4087 const struct mem_cgroup_threshold *_b = b;
4089 if (_a->threshold > _b->threshold)
4092 if (_a->threshold < _b->threshold)
4098 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
4100 struct mem_cgroup_eventfd_list *ev;
4102 spin_lock(&memcg_oom_lock);
4104 list_for_each_entry(ev, &memcg->oom_notify, list)
4105 eventfd_signal(ev->eventfd, 1);
4107 spin_unlock(&memcg_oom_lock);
4111 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
4113 struct mem_cgroup *iter;
4115 for_each_mem_cgroup_tree(iter, memcg)
4116 mem_cgroup_oom_notify_cb(iter);
4119 static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4120 struct eventfd_ctx *eventfd, const char *args, enum res_type type)
4122 struct mem_cgroup_thresholds *thresholds;
4123 struct mem_cgroup_threshold_ary *new;
4124 unsigned long threshold;
4125 unsigned long usage;
4128 ret = page_counter_memparse(args, "-1", &threshold);
4132 mutex_lock(&memcg->thresholds_lock);
4135 thresholds = &memcg->thresholds;
4136 usage = mem_cgroup_usage(memcg, false);
4137 } else if (type == _MEMSWAP) {
4138 thresholds = &memcg->memsw_thresholds;
4139 usage = mem_cgroup_usage(memcg, true);
4143 /* Check if a threshold crossed before adding a new one */
4144 if (thresholds->primary)
4145 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4147 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4149 /* Allocate memory for new array of thresholds */
4150 new = kmalloc(struct_size(new, entries, size), GFP_KERNEL);
4157 /* Copy thresholds (if any) to new array */
4158 if (thresholds->primary)
4159 memcpy(new->entries, thresholds->primary->entries,
4160 flex_array_size(new, entries, size - 1));
4162 /* Add new threshold */
4163 new->entries[size - 1].eventfd = eventfd;
4164 new->entries[size - 1].threshold = threshold;
4166 /* Sort thresholds. Registering of new threshold isn't time-critical */
4167 sort(new->entries, size, sizeof(*new->entries),
4168 compare_thresholds, NULL);
4170 /* Find current threshold */
4171 new->current_threshold = -1;
4172 for (i = 0; i < size; i++) {
4173 if (new->entries[i].threshold <= usage) {
4175 * new->current_threshold will not be used until
4176 * rcu_assign_pointer(), so it's safe to increment
4179 ++new->current_threshold;
4184 /* Free old spare buffer and save old primary buffer as spare */
4185 kfree(thresholds->spare);
4186 thresholds->spare = thresholds->primary;
4188 rcu_assign_pointer(thresholds->primary, new);
4190 /* To be sure that nobody uses thresholds */
4194 mutex_unlock(&memcg->thresholds_lock);
4199 static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4200 struct eventfd_ctx *eventfd, const char *args)
4202 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
4205 static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
4206 struct eventfd_ctx *eventfd, const char *args)
4208 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
4211 static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4212 struct eventfd_ctx *eventfd, enum res_type type)
4214 struct mem_cgroup_thresholds *thresholds;
4215 struct mem_cgroup_threshold_ary *new;
4216 unsigned long usage;
4217 int i, j, size, entries;
4219 mutex_lock(&memcg->thresholds_lock);
4222 thresholds = &memcg->thresholds;
4223 usage = mem_cgroup_usage(memcg, false);
4224 } else if (type == _MEMSWAP) {
4225 thresholds = &memcg->memsw_thresholds;
4226 usage = mem_cgroup_usage(memcg, true);
4230 if (!thresholds->primary)
4233 /* Check if a threshold crossed before removing */
4234 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4236 /* Calculate new number of threshold */
4238 for (i = 0; i < thresholds->primary->size; i++) {
4239 if (thresholds->primary->entries[i].eventfd != eventfd)
4245 new = thresholds->spare;
4247 /* If no items related to eventfd have been cleared, nothing to do */
4251 /* Set thresholds array to NULL if we don't have thresholds */
4260 /* Copy thresholds and find current threshold */
4261 new->current_threshold = -1;
4262 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4263 if (thresholds->primary->entries[i].eventfd == eventfd)
4266 new->entries[j] = thresholds->primary->entries[i];
4267 if (new->entries[j].threshold <= usage) {
4269 * new->current_threshold will not be used
4270 * until rcu_assign_pointer(), so it's safe to increment
4273 ++new->current_threshold;
4279 /* Swap primary and spare array */
4280 thresholds->spare = thresholds->primary;
4282 rcu_assign_pointer(thresholds->primary, new);
4284 /* To be sure that nobody uses thresholds */
4287 /* If all events are unregistered, free the spare array */
4289 kfree(thresholds->spare);
4290 thresholds->spare = NULL;
4293 mutex_unlock(&memcg->thresholds_lock);
4296 static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4297 struct eventfd_ctx *eventfd)
4299 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
4302 static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4303 struct eventfd_ctx *eventfd)
4305 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
4308 static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
4309 struct eventfd_ctx *eventfd, const char *args)
4311 struct mem_cgroup_eventfd_list *event;
4313 event = kmalloc(sizeof(*event), GFP_KERNEL);
4317 spin_lock(&memcg_oom_lock);
4319 event->eventfd = eventfd;
4320 list_add(&event->list, &memcg->oom_notify);
4322 /* already in OOM ? */
4323 if (memcg->under_oom)
4324 eventfd_signal(eventfd, 1);
4325 spin_unlock(&memcg_oom_lock);
4330 static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
4331 struct eventfd_ctx *eventfd)
4333 struct mem_cgroup_eventfd_list *ev, *tmp;
4335 spin_lock(&memcg_oom_lock);
4337 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
4338 if (ev->eventfd == eventfd) {
4339 list_del(&ev->list);
4344 spin_unlock(&memcg_oom_lock);
4347 static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
4349 struct mem_cgroup *memcg = mem_cgroup_from_seq(sf);
4351 seq_printf(sf, "oom_kill_disable %d\n", memcg->oom_kill_disable);
4352 seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
4353 seq_printf(sf, "oom_kill %lu\n",
4354 atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
4358 static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
4359 struct cftype *cft, u64 val)
4361 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4363 /* cannot set to root cgroup and only 0 and 1 are allowed */
4364 if (mem_cgroup_is_root(memcg) || !((val == 0) || (val == 1)))
4367 memcg->oom_kill_disable = val;
4369 memcg_oom_recover(memcg);
4374 #ifdef CONFIG_CGROUP_WRITEBACK
4376 #include <trace/events/writeback.h>
4378 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4380 return wb_domain_init(&memcg->cgwb_domain, gfp);
4383 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4385 wb_domain_exit(&memcg->cgwb_domain);
4388 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4390 wb_domain_size_changed(&memcg->cgwb_domain);
4393 struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
4395 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4397 if (!memcg->css.parent)
4400 return &memcg->cgwb_domain;
4404 * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
4405 * @wb: bdi_writeback in question
4406 * @pfilepages: out parameter for number of file pages
4407 * @pheadroom: out parameter for number of allocatable pages according to memcg
4408 * @pdirty: out parameter for number of dirty pages
4409 * @pwriteback: out parameter for number of pages under writeback
4411 * Determine the numbers of file, headroom, dirty, and writeback pages in
4412 * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom
4413 * is a bit more involved.
4415 * A memcg's headroom is "min(max, high) - used". In the hierarchy, the
4416 * headroom is calculated as the lowest headroom of itself and the
4417 * ancestors. Note that this doesn't consider the actual amount of
4418 * available memory in the system. The caller should further cap
4419 * *@pheadroom accordingly.
4421 void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
4422 unsigned long *pheadroom, unsigned long *pdirty,
4423 unsigned long *pwriteback)
4425 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4426 struct mem_cgroup *parent;
4428 mem_cgroup_flush_stats();
4430 *pdirty = memcg_page_state(memcg, NR_FILE_DIRTY);
4431 *pwriteback = memcg_page_state(memcg, NR_WRITEBACK);
4432 *pfilepages = memcg_page_state(memcg, NR_INACTIVE_FILE) +
4433 memcg_page_state(memcg, NR_ACTIVE_FILE);
4435 *pheadroom = PAGE_COUNTER_MAX;
4436 while ((parent = parent_mem_cgroup(memcg))) {
4437 unsigned long ceiling = min(READ_ONCE(memcg->memory.max),
4438 READ_ONCE(memcg->memory.high));
4439 unsigned long used = page_counter_read(&memcg->memory);
4441 *pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
4447 * Foreign dirty flushing
4449 * There's an inherent mismatch between memcg and writeback. The former
4450 * tracks ownership per-page while the latter per-inode. This was a
4451 * deliberate design decision because honoring per-page ownership in the
4452 * writeback path is complicated, may lead to higher CPU and IO overheads
4453 * and deemed unnecessary given that write-sharing an inode across
4454 * different cgroups isn't a common use-case.
4456 * Combined with inode majority-writer ownership switching, this works well
4457 * enough in most cases but there are some pathological cases. For
4458 * example, let's say there are two cgroups A and B which keep writing to
4459 * different but confined parts of the same inode. B owns the inode and
4460 * A's memory is limited far below B's. A's dirty ratio can rise enough to
4461 * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
4462 * triggering background writeback. A will be slowed down without a way to
4463 * make writeback of the dirty pages happen.
4465 * Conditions like the above can lead to a cgroup getting repeatedly and
4466 * severely throttled after making some progress after each
4467 * dirty_expire_interval while the underlying IO device is almost
4470 * Solving this problem completely requires matching the ownership tracking
4471 * granularities between memcg and writeback in either direction. However,
4472 * the more egregious behaviors can be avoided by simply remembering the
4473 * most recent foreign dirtying events and initiating remote flushes on
4474 * them when local writeback isn't enough to keep the memory clean enough.
4476 * The following two functions implement such mechanism. When a foreign
4477 * page - a page whose memcg and writeback ownerships don't match - is
4478 * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
4479 * bdi_writeback on the page owning memcg. When balance_dirty_pages()
4480 * decides that the memcg needs to sleep due to high dirty ratio, it calls
4481 * mem_cgroup_flush_foreign() which queues writeback on the recorded
4482 * foreign bdi_writebacks which haven't expired. Both the numbers of
4483 * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
4484 * limited to MEMCG_CGWB_FRN_CNT.
4486 * The mechanism only remembers IDs and doesn't hold any object references.
4487 * As being wrong occasionally doesn't matter, updates and accesses to the
4488 * records are lockless and racy.
4490 void mem_cgroup_track_foreign_dirty_slowpath(struct folio *folio,
4491 struct bdi_writeback *wb)
4493 struct mem_cgroup *memcg = folio_memcg(folio);
4494 struct memcg_cgwb_frn *frn;
4495 u64 now = get_jiffies_64();
4496 u64 oldest_at = now;
4500 trace_track_foreign_dirty(folio, wb);
4503 * Pick the slot to use. If there is already a slot for @wb, keep
4504 * using it. If not replace the oldest one which isn't being
4507 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4508 frn = &memcg->cgwb_frn[i];
4509 if (frn->bdi_id == wb->bdi->id &&
4510 frn->memcg_id == wb->memcg_css->id)
4512 if (time_before64(frn->at, oldest_at) &&
4513 atomic_read(&frn->done.cnt) == 1) {
4515 oldest_at = frn->at;
4519 if (i < MEMCG_CGWB_FRN_CNT) {
4521 * Re-using an existing one. Update timestamp lazily to
4522 * avoid making the cacheline hot. We want them to be
4523 * reasonably up-to-date and significantly shorter than
4524 * dirty_expire_interval as that's what expires the record.
4525 * Use the shorter of 1s and dirty_expire_interval / 8.
4527 unsigned long update_intv =
4528 min_t(unsigned long, HZ,
4529 msecs_to_jiffies(dirty_expire_interval * 10) / 8);
4531 if (time_before64(frn->at, now - update_intv))
4533 } else if (oldest >= 0) {
4534 /* replace the oldest free one */
4535 frn = &memcg->cgwb_frn[oldest];
4536 frn->bdi_id = wb->bdi->id;
4537 frn->memcg_id = wb->memcg_css->id;
4542 /* issue foreign writeback flushes for recorded foreign dirtying events */
4543 void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
4545 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4546 unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
4547 u64 now = jiffies_64;
4550 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4551 struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
4554 * If the record is older than dirty_expire_interval,
4555 * writeback on it has already started. No need to kick it
4556 * off again. Also, don't start a new one if there's
4557 * already one in flight.
4559 if (time_after64(frn->at, now - intv) &&
4560 atomic_read(&frn->done.cnt) == 1) {
4562 trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
4563 cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id,
4564 WB_REASON_FOREIGN_FLUSH,
4570 #else /* CONFIG_CGROUP_WRITEBACK */
4572 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4577 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4581 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4585 #endif /* CONFIG_CGROUP_WRITEBACK */
4588 * DO NOT USE IN NEW FILES.
4590 * "cgroup.event_control" implementation.
4592 * This is way over-engineered. It tries to support fully configurable
4593 * events for each user. Such level of flexibility is completely
4594 * unnecessary especially in the light of the planned unified hierarchy.
4596 * Please deprecate this and replace with something simpler if at all
4601 * Unregister event and free resources.
4603 * Gets called from workqueue.
4605 static void memcg_event_remove(struct work_struct *work)
4607 struct mem_cgroup_event *event =
4608 container_of(work, struct mem_cgroup_event, remove);
4609 struct mem_cgroup *memcg = event->memcg;
4611 remove_wait_queue(event->wqh, &event->wait);
4613 event->unregister_event(memcg, event->eventfd);
4615 /* Notify userspace the event is going away. */
4616 eventfd_signal(event->eventfd, 1);
4618 eventfd_ctx_put(event->eventfd);
4620 css_put(&memcg->css);
4624 * Gets called on EPOLLHUP on eventfd when user closes it.
4626 * Called with wqh->lock held and interrupts disabled.
4628 static int memcg_event_wake(wait_queue_entry_t *wait, unsigned mode,
4629 int sync, void *key)
4631 struct mem_cgroup_event *event =
4632 container_of(wait, struct mem_cgroup_event, wait);
4633 struct mem_cgroup *memcg = event->memcg;
4634 __poll_t flags = key_to_poll(key);
4636 if (flags & EPOLLHUP) {
4638 * If the event has been detached at cgroup removal, we
4639 * can simply return knowing the other side will cleanup
4642 * We can't race against event freeing since the other
4643 * side will require wqh->lock via remove_wait_queue(),
4646 spin_lock(&memcg->event_list_lock);
4647 if (!list_empty(&event->list)) {
4648 list_del_init(&event->list);
4650 * We are in atomic context, but cgroup_event_remove()
4651 * may sleep, so we have to call it in workqueue.
4653 schedule_work(&event->remove);
4655 spin_unlock(&memcg->event_list_lock);
4661 static void memcg_event_ptable_queue_proc(struct file *file,
4662 wait_queue_head_t *wqh, poll_table *pt)
4664 struct mem_cgroup_event *event =
4665 container_of(pt, struct mem_cgroup_event, pt);
4668 add_wait_queue(wqh, &event->wait);
4672 * DO NOT USE IN NEW FILES.
4674 * Parse input and register new cgroup event handler.
4676 * Input must be in format '<event_fd> <control_fd> <args>'.
4677 * Interpretation of args is defined by control file implementation.
4679 static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
4680 char *buf, size_t nbytes, loff_t off)
4682 struct cgroup_subsys_state *css = of_css(of);
4683 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4684 struct mem_cgroup_event *event;
4685 struct cgroup_subsys_state *cfile_css;
4686 unsigned int efd, cfd;
4693 if (IS_ENABLED(CONFIG_PREEMPT_RT))
4696 buf = strstrip(buf);
4698 efd = simple_strtoul(buf, &endp, 10);
4703 cfd = simple_strtoul(buf, &endp, 10);
4704 if ((*endp != ' ') && (*endp != '\0'))
4708 event = kzalloc(sizeof(*event), GFP_KERNEL);
4712 event->memcg = memcg;
4713 INIT_LIST_HEAD(&event->list);
4714 init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
4715 init_waitqueue_func_entry(&event->wait, memcg_event_wake);
4716 INIT_WORK(&event->remove, memcg_event_remove);
4724 event->eventfd = eventfd_ctx_fileget(efile.file);
4725 if (IS_ERR(event->eventfd)) {
4726 ret = PTR_ERR(event->eventfd);
4733 goto out_put_eventfd;
4736 /* the process need read permission on control file */
4737 /* AV: shouldn't we check that it's been opened for read instead? */
4738 ret = file_permission(cfile.file, MAY_READ);
4743 * Determine the event callbacks and set them in @event. This used
4744 * to be done via struct cftype but cgroup core no longer knows
4745 * about these events. The following is crude but the whole thing
4746 * is for compatibility anyway.
4748 * DO NOT ADD NEW FILES.
4750 name = cfile.file->f_path.dentry->d_name.name;
4752 if (!strcmp(name, "memory.usage_in_bytes")) {
4753 event->register_event = mem_cgroup_usage_register_event;
4754 event->unregister_event = mem_cgroup_usage_unregister_event;
4755 } else if (!strcmp(name, "memory.oom_control")) {
4756 event->register_event = mem_cgroup_oom_register_event;
4757 event->unregister_event = mem_cgroup_oom_unregister_event;
4758 } else if (!strcmp(name, "memory.pressure_level")) {
4759 event->register_event = vmpressure_register_event;
4760 event->unregister_event = vmpressure_unregister_event;
4761 } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
4762 event->register_event = memsw_cgroup_usage_register_event;
4763 event->unregister_event = memsw_cgroup_usage_unregister_event;
4770 * Verify @cfile should belong to @css. Also, remaining events are
4771 * automatically removed on cgroup destruction but the removal is
4772 * asynchronous, so take an extra ref on @css.
4774 cfile_css = css_tryget_online_from_dir(cfile.file->f_path.dentry->d_parent,
4775 &memory_cgrp_subsys);
4777 if (IS_ERR(cfile_css))
4779 if (cfile_css != css) {
4784 ret = event->register_event(memcg, event->eventfd, buf);
4788 vfs_poll(efile.file, &event->pt);
4790 spin_lock_irq(&memcg->event_list_lock);
4791 list_add(&event->list, &memcg->event_list);
4792 spin_unlock_irq(&memcg->event_list_lock);
4804 eventfd_ctx_put(event->eventfd);
4813 #if defined(CONFIG_MEMCG_KMEM) && (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG))
4814 static int mem_cgroup_slab_show(struct seq_file *m, void *p)
4818 * Please, take a look at tools/cgroup/slabinfo.py .
4824 static struct cftype mem_cgroup_legacy_files[] = {
4826 .name = "usage_in_bytes",
4827 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
4828 .read_u64 = mem_cgroup_read_u64,
4831 .name = "max_usage_in_bytes",
4832 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
4833 .write = mem_cgroup_reset,
4834 .read_u64 = mem_cgroup_read_u64,
4837 .name = "limit_in_bytes",
4838 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
4839 .write = mem_cgroup_write,
4840 .read_u64 = mem_cgroup_read_u64,
4843 .name = "soft_limit_in_bytes",
4844 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
4845 .write = mem_cgroup_write,
4846 .read_u64 = mem_cgroup_read_u64,
4850 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
4851 .write = mem_cgroup_reset,
4852 .read_u64 = mem_cgroup_read_u64,
4856 .seq_show = memcg_stat_show,
4859 .name = "force_empty",
4860 .write = mem_cgroup_force_empty_write,
4863 .name = "use_hierarchy",
4864 .write_u64 = mem_cgroup_hierarchy_write,
4865 .read_u64 = mem_cgroup_hierarchy_read,
4868 .name = "cgroup.event_control", /* XXX: for compat */
4869 .write = memcg_write_event_control,
4870 .flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE,
4873 .name = "swappiness",
4874 .read_u64 = mem_cgroup_swappiness_read,
4875 .write_u64 = mem_cgroup_swappiness_write,
4878 .name = "move_charge_at_immigrate",
4879 .read_u64 = mem_cgroup_move_charge_read,
4880 .write_u64 = mem_cgroup_move_charge_write,
4883 .name = "oom_control",
4884 .seq_show = mem_cgroup_oom_control_read,
4885 .write_u64 = mem_cgroup_oom_control_write,
4886 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
4889 .name = "pressure_level",
4893 .name = "numa_stat",
4894 .seq_show = memcg_numa_stat_show,
4898 .name = "kmem.limit_in_bytes",
4899 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
4900 .write = mem_cgroup_write,
4901 .read_u64 = mem_cgroup_read_u64,
4904 .name = "kmem.usage_in_bytes",
4905 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
4906 .read_u64 = mem_cgroup_read_u64,
4909 .name = "kmem.failcnt",
4910 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
4911 .write = mem_cgroup_reset,
4912 .read_u64 = mem_cgroup_read_u64,
4915 .name = "kmem.max_usage_in_bytes",
4916 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
4917 .write = mem_cgroup_reset,
4918 .read_u64 = mem_cgroup_read_u64,
4920 #if defined(CONFIG_MEMCG_KMEM) && \
4921 (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG))
4923 .name = "kmem.slabinfo",
4924 .seq_show = mem_cgroup_slab_show,
4928 .name = "kmem.tcp.limit_in_bytes",
4929 .private = MEMFILE_PRIVATE(_TCP, RES_LIMIT),
4930 .write = mem_cgroup_write,
4931 .read_u64 = mem_cgroup_read_u64,
4934 .name = "kmem.tcp.usage_in_bytes",
4935 .private = MEMFILE_PRIVATE(_TCP, RES_USAGE),
4936 .read_u64 = mem_cgroup_read_u64,
4939 .name = "kmem.tcp.failcnt",
4940 .private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT),
4941 .write = mem_cgroup_reset,
4942 .read_u64 = mem_cgroup_read_u64,
4945 .name = "kmem.tcp.max_usage_in_bytes",
4946 .private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE),
4947 .write = mem_cgroup_reset,
4948 .read_u64 = mem_cgroup_read_u64,
4950 { }, /* terminate */
4954 * Private memory cgroup IDR
4956 * Swap-out records and page cache shadow entries need to store memcg
4957 * references in constrained space, so we maintain an ID space that is
4958 * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
4959 * memory-controlled cgroups to 64k.
4961 * However, there usually are many references to the offline CSS after
4962 * the cgroup has been destroyed, such as page cache or reclaimable
4963 * slab objects, that don't need to hang on to the ID. We want to keep
4964 * those dead CSS from occupying IDs, or we might quickly exhaust the
4965 * relatively small ID space and prevent the creation of new cgroups
4966 * even when there are much fewer than 64k cgroups - possibly none.
4968 * Maintain a private 16-bit ID space for memcg, and allow the ID to
4969 * be freed and recycled when it's no longer needed, which is usually
4970 * when the CSS is offlined.
4972 * The only exception to that are records of swapped out tmpfs/shmem
4973 * pages that need to be attributed to live ancestors on swapin. But
4974 * those references are manageable from userspace.
4977 static DEFINE_IDR(mem_cgroup_idr);
4979 static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
4981 if (memcg->id.id > 0) {
4982 idr_remove(&mem_cgroup_idr, memcg->id.id);
4987 static void __maybe_unused mem_cgroup_id_get_many(struct mem_cgroup *memcg,
4990 refcount_add(n, &memcg->id.ref);
4993 static void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
4995 if (refcount_sub_and_test(n, &memcg->id.ref)) {
4996 mem_cgroup_id_remove(memcg);
4998 /* Memcg ID pins CSS */
4999 css_put(&memcg->css);
5003 static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
5005 mem_cgroup_id_put_many(memcg, 1);
5009 * mem_cgroup_from_id - look up a memcg from a memcg id
5010 * @id: the memcg id to look up
5012 * Caller must hold rcu_read_lock().
5014 struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
5016 WARN_ON_ONCE(!rcu_read_lock_held());
5017 return idr_find(&mem_cgroup_idr, id);
5020 static int alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5022 struct mem_cgroup_per_node *pn;
5024 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, node);
5028 pn->lruvec_stats_percpu = alloc_percpu_gfp(struct lruvec_stats_percpu,
5029 GFP_KERNEL_ACCOUNT);
5030 if (!pn->lruvec_stats_percpu) {
5035 lruvec_init(&pn->lruvec);
5038 memcg->nodeinfo[node] = pn;
5042 static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5044 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
5049 free_percpu(pn->lruvec_stats_percpu);
5053 static void __mem_cgroup_free(struct mem_cgroup *memcg)
5058 free_mem_cgroup_per_node_info(memcg, node);
5059 free_percpu(memcg->vmstats_percpu);
5063 static void mem_cgroup_free(struct mem_cgroup *memcg)
5065 memcg_wb_domain_exit(memcg);
5066 __mem_cgroup_free(memcg);
5069 static struct mem_cgroup *mem_cgroup_alloc(void)
5071 struct mem_cgroup *memcg;
5073 int __maybe_unused i;
5074 long error = -ENOMEM;
5076 memcg = kzalloc(struct_size(memcg, nodeinfo, nr_node_ids), GFP_KERNEL);
5078 return ERR_PTR(error);
5080 memcg->id.id = idr_alloc(&mem_cgroup_idr, NULL,
5081 1, MEM_CGROUP_ID_MAX + 1, GFP_KERNEL);
5082 if (memcg->id.id < 0) {
5083 error = memcg->id.id;
5087 memcg->vmstats_percpu = alloc_percpu_gfp(struct memcg_vmstats_percpu,
5088 GFP_KERNEL_ACCOUNT);
5089 if (!memcg->vmstats_percpu)
5093 if (alloc_mem_cgroup_per_node_info(memcg, node))
5096 if (memcg_wb_domain_init(memcg, GFP_KERNEL))
5099 INIT_WORK(&memcg->high_work, high_work_func);
5100 INIT_LIST_HEAD(&memcg->oom_notify);
5101 mutex_init(&memcg->thresholds_lock);
5102 spin_lock_init(&memcg->move_lock);
5103 vmpressure_init(&memcg->vmpressure);
5104 INIT_LIST_HEAD(&memcg->event_list);
5105 spin_lock_init(&memcg->event_list_lock);
5106 memcg->socket_pressure = jiffies;
5107 #ifdef CONFIG_MEMCG_KMEM
5108 memcg->kmemcg_id = -1;
5109 INIT_LIST_HEAD(&memcg->objcg_list);
5111 #ifdef CONFIG_CGROUP_WRITEBACK
5112 INIT_LIST_HEAD(&memcg->cgwb_list);
5113 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5114 memcg->cgwb_frn[i].done =
5115 __WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
5117 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5118 spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
5119 INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
5120 memcg->deferred_split_queue.split_queue_len = 0;
5122 idr_replace(&mem_cgroup_idr, memcg, memcg->id.id);
5125 mem_cgroup_id_remove(memcg);
5126 __mem_cgroup_free(memcg);
5127 return ERR_PTR(error);
5130 static struct cgroup_subsys_state * __ref
5131 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
5133 struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
5134 struct mem_cgroup *memcg, *old_memcg;
5136 old_memcg = set_active_memcg(parent);
5137 memcg = mem_cgroup_alloc();
5138 set_active_memcg(old_memcg);
5140 return ERR_CAST(memcg);
5142 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5143 memcg->soft_limit = PAGE_COUNTER_MAX;
5144 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5146 memcg->swappiness = mem_cgroup_swappiness(parent);
5147 memcg->oom_kill_disable = parent->oom_kill_disable;
5149 page_counter_init(&memcg->memory, &parent->memory);
5150 page_counter_init(&memcg->swap, &parent->swap);
5151 page_counter_init(&memcg->kmem, &parent->kmem);
5152 page_counter_init(&memcg->tcpmem, &parent->tcpmem);
5154 page_counter_init(&memcg->memory, NULL);
5155 page_counter_init(&memcg->swap, NULL);
5156 page_counter_init(&memcg->kmem, NULL);
5157 page_counter_init(&memcg->tcpmem, NULL);
5159 root_mem_cgroup = memcg;
5163 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5164 static_branch_inc(&memcg_sockets_enabled_key);
5169 static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
5171 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5173 if (memcg_online_kmem(memcg))
5177 * A memcg must be visible for expand_shrinker_info()
5178 * by the time the maps are allocated. So, we allocate maps
5179 * here, when for_each_mem_cgroup() can't skip it.
5181 if (alloc_shrinker_info(memcg))
5184 /* Online state pins memcg ID, memcg ID pins CSS */
5185 refcount_set(&memcg->id.ref, 1);
5188 if (unlikely(mem_cgroup_is_root(memcg)))
5189 queue_delayed_work(system_unbound_wq, &stats_flush_dwork,
5193 memcg_offline_kmem(memcg);
5195 mem_cgroup_id_remove(memcg);
5199 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
5201 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5202 struct mem_cgroup_event *event, *tmp;
5205 * Unregister events and notify userspace.
5206 * Notify userspace about cgroup removing only after rmdir of cgroup
5207 * directory to avoid race between userspace and kernelspace.
5209 spin_lock_irq(&memcg->event_list_lock);
5210 list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
5211 list_del_init(&event->list);
5212 schedule_work(&event->remove);
5214 spin_unlock_irq(&memcg->event_list_lock);
5216 page_counter_set_min(&memcg->memory, 0);
5217 page_counter_set_low(&memcg->memory, 0);
5219 memcg_offline_kmem(memcg);
5220 reparent_shrinker_deferred(memcg);
5221 wb_memcg_offline(memcg);
5223 drain_all_stock(memcg);
5225 mem_cgroup_id_put(memcg);
5228 static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
5230 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5232 invalidate_reclaim_iterators(memcg);
5235 static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
5237 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5238 int __maybe_unused i;
5240 #ifdef CONFIG_CGROUP_WRITEBACK
5241 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5242 wb_wait_for_completion(&memcg->cgwb_frn[i].done);
5244 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5245 static_branch_dec(&memcg_sockets_enabled_key);
5247 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg->tcpmem_active)
5248 static_branch_dec(&memcg_sockets_enabled_key);
5250 vmpressure_cleanup(&memcg->vmpressure);
5251 cancel_work_sync(&memcg->high_work);
5252 mem_cgroup_remove_from_trees(memcg);
5253 free_shrinker_info(memcg);
5254 mem_cgroup_free(memcg);
5258 * mem_cgroup_css_reset - reset the states of a mem_cgroup
5259 * @css: the target css
5261 * Reset the states of the mem_cgroup associated with @css. This is
5262 * invoked when the userland requests disabling on the default hierarchy
5263 * but the memcg is pinned through dependency. The memcg should stop
5264 * applying policies and should revert to the vanilla state as it may be
5265 * made visible again.
5267 * The current implementation only resets the essential configurations.
5268 * This needs to be expanded to cover all the visible parts.
5270 static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
5272 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5274 page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
5275 page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
5276 page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
5277 page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
5278 page_counter_set_min(&memcg->memory, 0);
5279 page_counter_set_low(&memcg->memory, 0);
5280 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5281 memcg->soft_limit = PAGE_COUNTER_MAX;
5282 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5283 memcg_wb_domain_size_changed(memcg);
5286 static void mem_cgroup_css_rstat_flush(struct cgroup_subsys_state *css, int cpu)
5288 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5289 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
5290 struct memcg_vmstats_percpu *statc;
5294 statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
5296 for (i = 0; i < MEMCG_NR_STAT; i++) {
5298 * Collect the aggregated propagation counts of groups
5299 * below us. We're in a per-cpu loop here and this is
5300 * a global counter, so the first cycle will get them.
5302 delta = memcg->vmstats.state_pending[i];
5304 memcg->vmstats.state_pending[i] = 0;
5306 /* Add CPU changes on this level since the last flush */
5307 v = READ_ONCE(statc->state[i]);
5308 if (v != statc->state_prev[i]) {
5309 delta += v - statc->state_prev[i];
5310 statc->state_prev[i] = v;
5316 /* Aggregate counts on this level and propagate upwards */
5317 memcg->vmstats.state[i] += delta;
5319 parent->vmstats.state_pending[i] += delta;
5322 for (i = 0; i < NR_VM_EVENT_ITEMS; i++) {
5323 delta = memcg->vmstats.events_pending[i];
5325 memcg->vmstats.events_pending[i] = 0;
5327 v = READ_ONCE(statc->events[i]);
5328 if (v != statc->events_prev[i]) {
5329 delta += v - statc->events_prev[i];
5330 statc->events_prev[i] = v;
5336 memcg->vmstats.events[i] += delta;
5338 parent->vmstats.events_pending[i] += delta;
5341 for_each_node_state(nid, N_MEMORY) {
5342 struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
5343 struct mem_cgroup_per_node *ppn = NULL;
5344 struct lruvec_stats_percpu *lstatc;
5347 ppn = parent->nodeinfo[nid];
5349 lstatc = per_cpu_ptr(pn->lruvec_stats_percpu, cpu);
5351 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++) {
5352 delta = pn->lruvec_stats.state_pending[i];
5354 pn->lruvec_stats.state_pending[i] = 0;
5356 v = READ_ONCE(lstatc->state[i]);
5357 if (v != lstatc->state_prev[i]) {
5358 delta += v - lstatc->state_prev[i];
5359 lstatc->state_prev[i] = v;
5365 pn->lruvec_stats.state[i] += delta;
5367 ppn->lruvec_stats.state_pending[i] += delta;
5373 /* Handlers for move charge at task migration. */
5374 static int mem_cgroup_do_precharge(unsigned long count)
5378 /* Try a single bulk charge without reclaim first, kswapd may wake */
5379 ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count);
5381 mc.precharge += count;
5385 /* Try charges one by one with reclaim, but do not retry */
5387 ret = try_charge(mc.to, GFP_KERNEL | __GFP_NORETRY, 1);
5401 enum mc_target_type {
5408 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5409 unsigned long addr, pte_t ptent)
5411 struct page *page = vm_normal_page(vma, addr, ptent);
5413 if (!page || !page_mapped(page))
5415 if (PageAnon(page)) {
5416 if (!(mc.flags & MOVE_ANON))
5419 if (!(mc.flags & MOVE_FILE))
5422 if (!get_page_unless_zero(page))
5428 #if defined(CONFIG_SWAP) || defined(CONFIG_DEVICE_PRIVATE)
5429 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5430 pte_t ptent, swp_entry_t *entry)
5432 struct page *page = NULL;
5433 swp_entry_t ent = pte_to_swp_entry(ptent);
5435 if (!(mc.flags & MOVE_ANON))
5439 * Handle device private pages that are not accessible by the CPU, but
5440 * stored as special swap entries in the page table.
5442 if (is_device_private_entry(ent)) {
5443 page = pfn_swap_entry_to_page(ent);
5444 if (!get_page_unless_zero(page))
5449 if (non_swap_entry(ent))
5453 * Because lookup_swap_cache() updates some statistics counter,
5454 * we call find_get_page() with swapper_space directly.
5456 page = find_get_page(swap_address_space(ent), swp_offset(ent));
5457 entry->val = ent.val;
5462 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5463 pte_t ptent, swp_entry_t *entry)
5469 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5470 unsigned long addr, pte_t ptent)
5472 if (!vma->vm_file) /* anonymous vma */
5474 if (!(mc.flags & MOVE_FILE))
5477 /* page is moved even if it's not RSS of this task(page-faulted). */
5478 /* shmem/tmpfs may report page out on swap: account for that too. */
5479 return find_get_incore_page(vma->vm_file->f_mapping,
5480 linear_page_index(vma, addr));
5484 * mem_cgroup_move_account - move account of the page
5486 * @compound: charge the page as compound or small page
5487 * @from: mem_cgroup which the page is moved from.
5488 * @to: mem_cgroup which the page is moved to. @from != @to.
5490 * The caller must make sure the page is not on LRU (isolate_page() is useful.)
5492 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
5495 static int mem_cgroup_move_account(struct page *page,
5497 struct mem_cgroup *from,
5498 struct mem_cgroup *to)
5500 struct folio *folio = page_folio(page);
5501 struct lruvec *from_vec, *to_vec;
5502 struct pglist_data *pgdat;
5503 unsigned int nr_pages = compound ? folio_nr_pages(folio) : 1;
5506 VM_BUG_ON(from == to);
5507 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
5508 VM_BUG_ON(compound && !folio_test_large(folio));
5511 * Prevent mem_cgroup_migrate() from looking at
5512 * page's memory cgroup of its source page while we change it.
5515 if (!folio_trylock(folio))
5519 if (folio_memcg(folio) != from)
5522 pgdat = folio_pgdat(folio);
5523 from_vec = mem_cgroup_lruvec(from, pgdat);
5524 to_vec = mem_cgroup_lruvec(to, pgdat);
5526 folio_memcg_lock(folio);
5528 if (folio_test_anon(folio)) {
5529 if (folio_mapped(folio)) {
5530 __mod_lruvec_state(from_vec, NR_ANON_MAPPED, -nr_pages);
5531 __mod_lruvec_state(to_vec, NR_ANON_MAPPED, nr_pages);
5532 if (folio_test_transhuge(folio)) {
5533 __mod_lruvec_state(from_vec, NR_ANON_THPS,
5535 __mod_lruvec_state(to_vec, NR_ANON_THPS,
5540 __mod_lruvec_state(from_vec, NR_FILE_PAGES, -nr_pages);
5541 __mod_lruvec_state(to_vec, NR_FILE_PAGES, nr_pages);
5543 if (folio_test_swapbacked(folio)) {
5544 __mod_lruvec_state(from_vec, NR_SHMEM, -nr_pages);
5545 __mod_lruvec_state(to_vec, NR_SHMEM, nr_pages);
5548 if (folio_mapped(folio)) {
5549 __mod_lruvec_state(from_vec, NR_FILE_MAPPED, -nr_pages);
5550 __mod_lruvec_state(to_vec, NR_FILE_MAPPED, nr_pages);
5553 if (folio_test_dirty(folio)) {
5554 struct address_space *mapping = folio_mapping(folio);
5556 if (mapping_can_writeback(mapping)) {
5557 __mod_lruvec_state(from_vec, NR_FILE_DIRTY,
5559 __mod_lruvec_state(to_vec, NR_FILE_DIRTY,
5565 if (folio_test_writeback(folio)) {
5566 __mod_lruvec_state(from_vec, NR_WRITEBACK, -nr_pages);
5567 __mod_lruvec_state(to_vec, NR_WRITEBACK, nr_pages);
5571 * All state has been migrated, let's switch to the new memcg.
5573 * It is safe to change page's memcg here because the page
5574 * is referenced, charged, isolated, and locked: we can't race
5575 * with (un)charging, migration, LRU putback, or anything else
5576 * that would rely on a stable page's memory cgroup.
5578 * Note that lock_page_memcg is a memcg lock, not a page lock,
5579 * to save space. As soon as we switch page's memory cgroup to a
5580 * new memcg that isn't locked, the above state can change
5581 * concurrently again. Make sure we're truly done with it.
5586 css_put(&from->css);
5588 folio->memcg_data = (unsigned long)to;
5590 __folio_memcg_unlock(from);
5593 nid = folio_nid(folio);
5595 local_irq_disable();
5596 mem_cgroup_charge_statistics(to, nr_pages);
5597 memcg_check_events(to, nid);
5598 mem_cgroup_charge_statistics(from, -nr_pages);
5599 memcg_check_events(from, nid);
5602 folio_unlock(folio);
5608 * get_mctgt_type - get target type of moving charge
5609 * @vma: the vma the pte to be checked belongs
5610 * @addr: the address corresponding to the pte to be checked
5611 * @ptent: the pte to be checked
5612 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5615 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5616 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5617 * move charge. if @target is not NULL, the page is stored in target->page
5618 * with extra refcnt got(Callers should handle it).
5619 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5620 * target for charge migration. if @target is not NULL, the entry is stored
5622 * 3(MC_TARGET_DEVICE): like MC_TARGET_PAGE but page is MEMORY_DEVICE_PRIVATE
5623 * (so ZONE_DEVICE page and thus not on the lru).
5624 * For now we such page is charge like a regular page would be as for all
5625 * intent and purposes it is just special memory taking the place of a
5628 * See Documentations/vm/hmm.txt and include/linux/hmm.h
5630 * Called with pte lock held.
5633 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
5634 unsigned long addr, pte_t ptent, union mc_target *target)
5636 struct page *page = NULL;
5637 enum mc_target_type ret = MC_TARGET_NONE;
5638 swp_entry_t ent = { .val = 0 };
5640 if (pte_present(ptent))
5641 page = mc_handle_present_pte(vma, addr, ptent);
5642 else if (is_swap_pte(ptent))
5643 page = mc_handle_swap_pte(vma, ptent, &ent);
5644 else if (pte_none(ptent))
5645 page = mc_handle_file_pte(vma, addr, ptent);
5647 if (!page && !ent.val)
5651 * Do only loose check w/o serialization.
5652 * mem_cgroup_move_account() checks the page is valid or
5653 * not under LRU exclusion.
5655 if (page_memcg(page) == mc.from) {
5656 ret = MC_TARGET_PAGE;
5657 if (is_device_private_page(page))
5658 ret = MC_TARGET_DEVICE;
5660 target->page = page;
5662 if (!ret || !target)
5666 * There is a swap entry and a page doesn't exist or isn't charged.
5667 * But we cannot move a tail-page in a THP.
5669 if (ent.val && !ret && (!page || !PageTransCompound(page)) &&
5670 mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
5671 ret = MC_TARGET_SWAP;
5678 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5680 * We don't consider PMD mapped swapping or file mapped pages because THP does
5681 * not support them for now.
5682 * Caller should make sure that pmd_trans_huge(pmd) is true.
5684 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5685 unsigned long addr, pmd_t pmd, union mc_target *target)
5687 struct page *page = NULL;
5688 enum mc_target_type ret = MC_TARGET_NONE;
5690 if (unlikely(is_swap_pmd(pmd))) {
5691 VM_BUG_ON(thp_migration_supported() &&
5692 !is_pmd_migration_entry(pmd));
5695 page = pmd_page(pmd);
5696 VM_BUG_ON_PAGE(!page || !PageHead(page), page);
5697 if (!(mc.flags & MOVE_ANON))
5699 if (page_memcg(page) == mc.from) {
5700 ret = MC_TARGET_PAGE;
5703 target->page = page;
5709 static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5710 unsigned long addr, pmd_t pmd, union mc_target *target)
5712 return MC_TARGET_NONE;
5716 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5717 unsigned long addr, unsigned long end,
5718 struct mm_walk *walk)
5720 struct vm_area_struct *vma = walk->vma;
5724 ptl = pmd_trans_huge_lock(pmd, vma);
5727 * Note their can not be MC_TARGET_DEVICE for now as we do not
5728 * support transparent huge page with MEMORY_DEVICE_PRIVATE but
5729 * this might change.
5731 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
5732 mc.precharge += HPAGE_PMD_NR;
5737 if (pmd_trans_unstable(pmd))
5739 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5740 for (; addr != end; pte++, addr += PAGE_SIZE)
5741 if (get_mctgt_type(vma, addr, *pte, NULL))
5742 mc.precharge++; /* increment precharge temporarily */
5743 pte_unmap_unlock(pte - 1, ptl);
5749 static const struct mm_walk_ops precharge_walk_ops = {
5750 .pmd_entry = mem_cgroup_count_precharge_pte_range,
5753 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5755 unsigned long precharge;
5758 walk_page_range(mm, 0, mm->highest_vm_end, &precharge_walk_ops, NULL);
5759 mmap_read_unlock(mm);
5761 precharge = mc.precharge;
5767 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5769 unsigned long precharge = mem_cgroup_count_precharge(mm);
5771 VM_BUG_ON(mc.moving_task);
5772 mc.moving_task = current;
5773 return mem_cgroup_do_precharge(precharge);
5776 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5777 static void __mem_cgroup_clear_mc(void)
5779 struct mem_cgroup *from = mc.from;
5780 struct mem_cgroup *to = mc.to;
5782 /* we must uncharge all the leftover precharges from mc.to */
5784 cancel_charge(mc.to, mc.precharge);
5788 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5789 * we must uncharge here.
5791 if (mc.moved_charge) {
5792 cancel_charge(mc.from, mc.moved_charge);
5793 mc.moved_charge = 0;
5795 /* we must fixup refcnts and charges */
5796 if (mc.moved_swap) {
5797 /* uncharge swap account from the old cgroup */
5798 if (!mem_cgroup_is_root(mc.from))
5799 page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
5801 mem_cgroup_id_put_many(mc.from, mc.moved_swap);
5804 * we charged both to->memory and to->memsw, so we
5805 * should uncharge to->memory.
5807 if (!mem_cgroup_is_root(mc.to))
5808 page_counter_uncharge(&mc.to->memory, mc.moved_swap);
5812 memcg_oom_recover(from);
5813 memcg_oom_recover(to);
5814 wake_up_all(&mc.waitq);
5817 static void mem_cgroup_clear_mc(void)
5819 struct mm_struct *mm = mc.mm;
5822 * we must clear moving_task before waking up waiters at the end of
5825 mc.moving_task = NULL;
5826 __mem_cgroup_clear_mc();
5827 spin_lock(&mc.lock);
5831 spin_unlock(&mc.lock);
5836 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
5838 struct cgroup_subsys_state *css;
5839 struct mem_cgroup *memcg = NULL; /* unneeded init to make gcc happy */
5840 struct mem_cgroup *from;
5841 struct task_struct *leader, *p;
5842 struct mm_struct *mm;
5843 unsigned long move_flags;
5846 /* charge immigration isn't supported on the default hierarchy */
5847 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
5851 * Multi-process migrations only happen on the default hierarchy
5852 * where charge immigration is not used. Perform charge
5853 * immigration if @tset contains a leader and whine if there are
5857 cgroup_taskset_for_each_leader(leader, css, tset) {
5860 memcg = mem_cgroup_from_css(css);
5866 * We are now committed to this value whatever it is. Changes in this
5867 * tunable will only affect upcoming migrations, not the current one.
5868 * So we need to save it, and keep it going.
5870 move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
5874 from = mem_cgroup_from_task(p);
5876 VM_BUG_ON(from == memcg);
5878 mm = get_task_mm(p);
5881 /* We move charges only when we move a owner of the mm */
5882 if (mm->owner == p) {
5885 VM_BUG_ON(mc.precharge);
5886 VM_BUG_ON(mc.moved_charge);
5887 VM_BUG_ON(mc.moved_swap);
5889 spin_lock(&mc.lock);
5893 mc.flags = move_flags;
5894 spin_unlock(&mc.lock);
5895 /* We set mc.moving_task later */
5897 ret = mem_cgroup_precharge_mc(mm);
5899 mem_cgroup_clear_mc();
5906 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
5909 mem_cgroup_clear_mc();
5912 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
5913 unsigned long addr, unsigned long end,
5914 struct mm_walk *walk)
5917 struct vm_area_struct *vma = walk->vma;
5920 enum mc_target_type target_type;
5921 union mc_target target;
5924 ptl = pmd_trans_huge_lock(pmd, vma);
5926 if (mc.precharge < HPAGE_PMD_NR) {
5930 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
5931 if (target_type == MC_TARGET_PAGE) {
5933 if (!isolate_lru_page(page)) {
5934 if (!mem_cgroup_move_account(page, true,
5936 mc.precharge -= HPAGE_PMD_NR;
5937 mc.moved_charge += HPAGE_PMD_NR;
5939 putback_lru_page(page);
5942 } else if (target_type == MC_TARGET_DEVICE) {
5944 if (!mem_cgroup_move_account(page, true,
5946 mc.precharge -= HPAGE_PMD_NR;
5947 mc.moved_charge += HPAGE_PMD_NR;
5955 if (pmd_trans_unstable(pmd))
5958 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5959 for (; addr != end; addr += PAGE_SIZE) {
5960 pte_t ptent = *(pte++);
5961 bool device = false;
5967 switch (get_mctgt_type(vma, addr, ptent, &target)) {
5968 case MC_TARGET_DEVICE:
5971 case MC_TARGET_PAGE:
5974 * We can have a part of the split pmd here. Moving it
5975 * can be done but it would be too convoluted so simply
5976 * ignore such a partial THP and keep it in original
5977 * memcg. There should be somebody mapping the head.
5979 if (PageTransCompound(page))
5981 if (!device && isolate_lru_page(page))
5983 if (!mem_cgroup_move_account(page, false,
5986 /* we uncharge from mc.from later. */
5990 putback_lru_page(page);
5991 put: /* get_mctgt_type() gets the page */
5994 case MC_TARGET_SWAP:
5996 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
5998 mem_cgroup_id_get_many(mc.to, 1);
5999 /* we fixup other refcnts and charges later. */
6007 pte_unmap_unlock(pte - 1, ptl);
6012 * We have consumed all precharges we got in can_attach().
6013 * We try charge one by one, but don't do any additional
6014 * charges to mc.to if we have failed in charge once in attach()
6017 ret = mem_cgroup_do_precharge(1);
6025 static const struct mm_walk_ops charge_walk_ops = {
6026 .pmd_entry = mem_cgroup_move_charge_pte_range,
6029 static void mem_cgroup_move_charge(void)
6031 lru_add_drain_all();
6033 * Signal lock_page_memcg() to take the memcg's move_lock
6034 * while we're moving its pages to another memcg. Then wait
6035 * for already started RCU-only updates to finish.
6037 atomic_inc(&mc.from->moving_account);
6040 if (unlikely(!mmap_read_trylock(mc.mm))) {
6042 * Someone who are holding the mmap_lock might be waiting in
6043 * waitq. So we cancel all extra charges, wake up all waiters,
6044 * and retry. Because we cancel precharges, we might not be able
6045 * to move enough charges, but moving charge is a best-effort
6046 * feature anyway, so it wouldn't be a big problem.
6048 __mem_cgroup_clear_mc();
6053 * When we have consumed all precharges and failed in doing
6054 * additional charge, the page walk just aborts.
6056 walk_page_range(mc.mm, 0, mc.mm->highest_vm_end, &charge_walk_ops,
6059 mmap_read_unlock(mc.mm);
6060 atomic_dec(&mc.from->moving_account);
6063 static void mem_cgroup_move_task(void)
6066 mem_cgroup_move_charge();
6067 mem_cgroup_clear_mc();
6070 #else /* !CONFIG_MMU */
6071 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
6075 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6078 static void mem_cgroup_move_task(void)
6083 static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
6085 if (value == PAGE_COUNTER_MAX)
6086 seq_puts(m, "max\n");
6088 seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
6093 static u64 memory_current_read(struct cgroup_subsys_state *css,
6096 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6098 return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
6101 static int memory_min_show(struct seq_file *m, void *v)
6103 return seq_puts_memcg_tunable(m,
6104 READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
6107 static ssize_t memory_min_write(struct kernfs_open_file *of,
6108 char *buf, size_t nbytes, loff_t off)
6110 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6114 buf = strstrip(buf);
6115 err = page_counter_memparse(buf, "max", &min);
6119 page_counter_set_min(&memcg->memory, min);
6124 static int memory_low_show(struct seq_file *m, void *v)
6126 return seq_puts_memcg_tunable(m,
6127 READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
6130 static ssize_t memory_low_write(struct kernfs_open_file *of,
6131 char *buf, size_t nbytes, loff_t off)
6133 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6137 buf = strstrip(buf);
6138 err = page_counter_memparse(buf, "max", &low);
6142 page_counter_set_low(&memcg->memory, low);
6147 static int memory_high_show(struct seq_file *m, void *v)
6149 return seq_puts_memcg_tunable(m,
6150 READ_ONCE(mem_cgroup_from_seq(m)->memory.high));
6153 static ssize_t memory_high_write(struct kernfs_open_file *of,
6154 char *buf, size_t nbytes, loff_t off)
6156 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6157 unsigned int nr_retries = MAX_RECLAIM_RETRIES;
6158 bool drained = false;
6162 buf = strstrip(buf);
6163 err = page_counter_memparse(buf, "max", &high);
6167 page_counter_set_high(&memcg->memory, high);
6170 unsigned long nr_pages = page_counter_read(&memcg->memory);
6171 unsigned long reclaimed;
6173 if (nr_pages <= high)
6176 if (signal_pending(current))
6180 drain_all_stock(memcg);
6185 reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
6188 if (!reclaimed && !nr_retries--)
6192 memcg_wb_domain_size_changed(memcg);
6196 static int memory_max_show(struct seq_file *m, void *v)
6198 return seq_puts_memcg_tunable(m,
6199 READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
6202 static ssize_t memory_max_write(struct kernfs_open_file *of,
6203 char *buf, size_t nbytes, loff_t off)
6205 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6206 unsigned int nr_reclaims = MAX_RECLAIM_RETRIES;
6207 bool drained = false;
6211 buf = strstrip(buf);
6212 err = page_counter_memparse(buf, "max", &max);
6216 xchg(&memcg->memory.max, max);
6219 unsigned long nr_pages = page_counter_read(&memcg->memory);
6221 if (nr_pages <= max)
6224 if (signal_pending(current))
6228 drain_all_stock(memcg);
6234 if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
6240 memcg_memory_event(memcg, MEMCG_OOM);
6241 if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
6245 memcg_wb_domain_size_changed(memcg);
6249 static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
6251 seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
6252 seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
6253 seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
6254 seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
6255 seq_printf(m, "oom_kill %lu\n",
6256 atomic_long_read(&events[MEMCG_OOM_KILL]));
6257 seq_printf(m, "oom_group_kill %lu\n",
6258 atomic_long_read(&events[MEMCG_OOM_GROUP_KILL]));
6261 static int memory_events_show(struct seq_file *m, void *v)
6263 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6265 __memory_events_show(m, memcg->memory_events);
6269 static int memory_events_local_show(struct seq_file *m, void *v)
6271 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6273 __memory_events_show(m, memcg->memory_events_local);
6277 static int memory_stat_show(struct seq_file *m, void *v)
6279 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6282 buf = memory_stat_format(memcg);
6291 static inline unsigned long lruvec_page_state_output(struct lruvec *lruvec,
6294 return lruvec_page_state(lruvec, item) * memcg_page_state_unit(item);
6297 static int memory_numa_stat_show(struct seq_file *m, void *v)
6300 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6302 mem_cgroup_flush_stats();
6304 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
6307 if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS)
6310 seq_printf(m, "%s", memory_stats[i].name);
6311 for_each_node_state(nid, N_MEMORY) {
6313 struct lruvec *lruvec;
6315 lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
6316 size = lruvec_page_state_output(lruvec,
6317 memory_stats[i].idx);
6318 seq_printf(m, " N%d=%llu", nid, size);
6327 static int memory_oom_group_show(struct seq_file *m, void *v)
6329 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6331 seq_printf(m, "%d\n", memcg->oom_group);
6336 static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
6337 char *buf, size_t nbytes, loff_t off)
6339 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6342 buf = strstrip(buf);
6346 ret = kstrtoint(buf, 0, &oom_group);
6350 if (oom_group != 0 && oom_group != 1)
6353 memcg->oom_group = oom_group;
6358 static struct cftype memory_files[] = {
6361 .flags = CFTYPE_NOT_ON_ROOT,
6362 .read_u64 = memory_current_read,
6366 .flags = CFTYPE_NOT_ON_ROOT,
6367 .seq_show = memory_min_show,
6368 .write = memory_min_write,
6372 .flags = CFTYPE_NOT_ON_ROOT,
6373 .seq_show = memory_low_show,
6374 .write = memory_low_write,
6378 .flags = CFTYPE_NOT_ON_ROOT,
6379 .seq_show = memory_high_show,
6380 .write = memory_high_write,
6384 .flags = CFTYPE_NOT_ON_ROOT,
6385 .seq_show = memory_max_show,
6386 .write = memory_max_write,
6390 .flags = CFTYPE_NOT_ON_ROOT,
6391 .file_offset = offsetof(struct mem_cgroup, events_file),
6392 .seq_show = memory_events_show,
6395 .name = "events.local",
6396 .flags = CFTYPE_NOT_ON_ROOT,
6397 .file_offset = offsetof(struct mem_cgroup, events_local_file),
6398 .seq_show = memory_events_local_show,
6402 .seq_show = memory_stat_show,
6406 .name = "numa_stat",
6407 .seq_show = memory_numa_stat_show,
6411 .name = "oom.group",
6412 .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
6413 .seq_show = memory_oom_group_show,
6414 .write = memory_oom_group_write,
6419 struct cgroup_subsys memory_cgrp_subsys = {
6420 .css_alloc = mem_cgroup_css_alloc,
6421 .css_online = mem_cgroup_css_online,
6422 .css_offline = mem_cgroup_css_offline,
6423 .css_released = mem_cgroup_css_released,
6424 .css_free = mem_cgroup_css_free,
6425 .css_reset = mem_cgroup_css_reset,
6426 .css_rstat_flush = mem_cgroup_css_rstat_flush,
6427 .can_attach = mem_cgroup_can_attach,
6428 .cancel_attach = mem_cgroup_cancel_attach,
6429 .post_attach = mem_cgroup_move_task,
6430 .dfl_cftypes = memory_files,
6431 .legacy_cftypes = mem_cgroup_legacy_files,
6436 * This function calculates an individual cgroup's effective
6437 * protection which is derived from its own memory.min/low, its
6438 * parent's and siblings' settings, as well as the actual memory
6439 * distribution in the tree.
6441 * The following rules apply to the effective protection values:
6443 * 1. At the first level of reclaim, effective protection is equal to
6444 * the declared protection in memory.min and memory.low.
6446 * 2. To enable safe delegation of the protection configuration, at
6447 * subsequent levels the effective protection is capped to the
6448 * parent's effective protection.
6450 * 3. To make complex and dynamic subtrees easier to configure, the
6451 * user is allowed to overcommit the declared protection at a given
6452 * level. If that is the case, the parent's effective protection is
6453 * distributed to the children in proportion to how much protection
6454 * they have declared and how much of it they are utilizing.
6456 * This makes distribution proportional, but also work-conserving:
6457 * if one cgroup claims much more protection than it uses memory,
6458 * the unused remainder is available to its siblings.
6460 * 4. Conversely, when the declared protection is undercommitted at a
6461 * given level, the distribution of the larger parental protection
6462 * budget is NOT proportional. A cgroup's protection from a sibling
6463 * is capped to its own memory.min/low setting.
6465 * 5. However, to allow protecting recursive subtrees from each other
6466 * without having to declare each individual cgroup's fixed share
6467 * of the ancestor's claim to protection, any unutilized -
6468 * "floating" - protection from up the tree is distributed in
6469 * proportion to each cgroup's *usage*. This makes the protection
6470 * neutral wrt sibling cgroups and lets them compete freely over
6471 * the shared parental protection budget, but it protects the
6472 * subtree as a whole from neighboring subtrees.
6474 * Note that 4. and 5. are not in conflict: 4. is about protecting
6475 * against immediate siblings whereas 5. is about protecting against
6476 * neighboring subtrees.
6478 static unsigned long effective_protection(unsigned long usage,
6479 unsigned long parent_usage,
6480 unsigned long setting,
6481 unsigned long parent_effective,
6482 unsigned long siblings_protected)
6484 unsigned long protected;
6487 protected = min(usage, setting);
6489 * If all cgroups at this level combined claim and use more
6490 * protection then what the parent affords them, distribute
6491 * shares in proportion to utilization.
6493 * We are using actual utilization rather than the statically
6494 * claimed protection in order to be work-conserving: claimed
6495 * but unused protection is available to siblings that would
6496 * otherwise get a smaller chunk than what they claimed.
6498 if (siblings_protected > parent_effective)
6499 return protected * parent_effective / siblings_protected;
6502 * Ok, utilized protection of all children is within what the
6503 * parent affords them, so we know whatever this child claims
6504 * and utilizes is effectively protected.
6506 * If there is unprotected usage beyond this value, reclaim
6507 * will apply pressure in proportion to that amount.
6509 * If there is unutilized protection, the cgroup will be fully
6510 * shielded from reclaim, but we do return a smaller value for
6511 * protection than what the group could enjoy in theory. This
6512 * is okay. With the overcommit distribution above, effective
6513 * protection is always dependent on how memory is actually
6514 * consumed among the siblings anyway.
6519 * If the children aren't claiming (all of) the protection
6520 * afforded to them by the parent, distribute the remainder in
6521 * proportion to the (unprotected) memory of each cgroup. That
6522 * way, cgroups that aren't explicitly prioritized wrt each
6523 * other compete freely over the allowance, but they are
6524 * collectively protected from neighboring trees.
6526 * We're using unprotected memory for the weight so that if
6527 * some cgroups DO claim explicit protection, we don't protect
6528 * the same bytes twice.
6530 * Check both usage and parent_usage against the respective
6531 * protected values. One should imply the other, but they
6532 * aren't read atomically - make sure the division is sane.
6534 if (!(cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT))
6536 if (parent_effective > siblings_protected &&
6537 parent_usage > siblings_protected &&
6538 usage > protected) {
6539 unsigned long unclaimed;
6541 unclaimed = parent_effective - siblings_protected;
6542 unclaimed *= usage - protected;
6543 unclaimed /= parent_usage - siblings_protected;
6552 * mem_cgroup_calculate_protection - check if memory consumption is in the normal range
6553 * @root: the top ancestor of the sub-tree being checked
6554 * @memcg: the memory cgroup to check
6556 * WARNING: This function is not stateless! It can only be used as part
6557 * of a top-down tree iteration, not for isolated queries.
6559 void mem_cgroup_calculate_protection(struct mem_cgroup *root,
6560 struct mem_cgroup *memcg)
6562 unsigned long usage, parent_usage;
6563 struct mem_cgroup *parent;
6565 if (mem_cgroup_disabled())
6569 root = root_mem_cgroup;
6572 * Effective values of the reclaim targets are ignored so they
6573 * can be stale. Have a look at mem_cgroup_protection for more
6575 * TODO: calculation should be more robust so that we do not need
6576 * that special casing.
6581 usage = page_counter_read(&memcg->memory);
6585 parent = parent_mem_cgroup(memcg);
6586 /* No parent means a non-hierarchical mode on v1 memcg */
6590 if (parent == root) {
6591 memcg->memory.emin = READ_ONCE(memcg->memory.min);
6592 memcg->memory.elow = READ_ONCE(memcg->memory.low);
6596 parent_usage = page_counter_read(&parent->memory);
6598 WRITE_ONCE(memcg->memory.emin, effective_protection(usage, parent_usage,
6599 READ_ONCE(memcg->memory.min),
6600 READ_ONCE(parent->memory.emin),
6601 atomic_long_read(&parent->memory.children_min_usage)));
6603 WRITE_ONCE(memcg->memory.elow, effective_protection(usage, parent_usage,
6604 READ_ONCE(memcg->memory.low),
6605 READ_ONCE(parent->memory.elow),
6606 atomic_long_read(&parent->memory.children_low_usage)));
6609 static int charge_memcg(struct folio *folio, struct mem_cgroup *memcg,
6612 long nr_pages = folio_nr_pages(folio);
6615 ret = try_charge(memcg, gfp, nr_pages);
6619 css_get(&memcg->css);
6620 commit_charge(folio, memcg);
6622 local_irq_disable();
6623 mem_cgroup_charge_statistics(memcg, nr_pages);
6624 memcg_check_events(memcg, folio_nid(folio));
6630 int __mem_cgroup_charge(struct folio *folio, struct mm_struct *mm, gfp_t gfp)
6632 struct mem_cgroup *memcg;
6635 memcg = get_mem_cgroup_from_mm(mm);
6636 ret = charge_memcg(folio, memcg, gfp);
6637 css_put(&memcg->css);
6643 * mem_cgroup_swapin_charge_page - charge a newly allocated page for swapin
6644 * @page: page to charge
6645 * @mm: mm context of the victim
6646 * @gfp: reclaim mode
6647 * @entry: swap entry for which the page is allocated
6649 * This function charges a page allocated for swapin. Please call this before
6650 * adding the page to the swapcache.
6652 * Returns 0 on success. Otherwise, an error code is returned.
6654 int mem_cgroup_swapin_charge_page(struct page *page, struct mm_struct *mm,
6655 gfp_t gfp, swp_entry_t entry)
6657 struct folio *folio = page_folio(page);
6658 struct mem_cgroup *memcg;
6662 if (mem_cgroup_disabled())
6665 id = lookup_swap_cgroup_id(entry);
6667 memcg = mem_cgroup_from_id(id);
6668 if (!memcg || !css_tryget_online(&memcg->css))
6669 memcg = get_mem_cgroup_from_mm(mm);
6672 ret = charge_memcg(folio, memcg, gfp);
6674 css_put(&memcg->css);
6679 * mem_cgroup_swapin_uncharge_swap - uncharge swap slot
6680 * @entry: swap entry for which the page is charged
6682 * Call this function after successfully adding the charged page to swapcache.
6684 * Note: This function assumes the page for which swap slot is being uncharged
6687 void mem_cgroup_swapin_uncharge_swap(swp_entry_t entry)
6690 * Cgroup1's unified memory+swap counter has been charged with the
6691 * new swapcache page, finish the transfer by uncharging the swap
6692 * slot. The swap slot would also get uncharged when it dies, but
6693 * it can stick around indefinitely and we'd count the page twice
6696 * Cgroup2 has separate resource counters for memory and swap,
6697 * so this is a non-issue here. Memory and swap charge lifetimes
6698 * correspond 1:1 to page and swap slot lifetimes: we charge the
6699 * page to memory here, and uncharge swap when the slot is freed.
6701 if (!mem_cgroup_disabled() && do_memsw_account()) {
6703 * The swap entry might not get freed for a long time,
6704 * let's not wait for it. The page already received a
6705 * memory+swap charge, drop the swap entry duplicate.
6707 mem_cgroup_uncharge_swap(entry, 1);
6711 struct uncharge_gather {
6712 struct mem_cgroup *memcg;
6713 unsigned long nr_memory;
6714 unsigned long pgpgout;
6715 unsigned long nr_kmem;
6719 static inline void uncharge_gather_clear(struct uncharge_gather *ug)
6721 memset(ug, 0, sizeof(*ug));
6724 static void uncharge_batch(const struct uncharge_gather *ug)
6726 unsigned long flags;
6728 if (ug->nr_memory) {
6729 page_counter_uncharge(&ug->memcg->memory, ug->nr_memory);
6730 if (do_memsw_account())
6731 page_counter_uncharge(&ug->memcg->memsw, ug->nr_memory);
6733 memcg_account_kmem(ug->memcg, -ug->nr_kmem);
6734 memcg_oom_recover(ug->memcg);
6737 local_irq_save(flags);
6738 __count_memcg_events(ug->memcg, PGPGOUT, ug->pgpgout);
6739 __this_cpu_add(ug->memcg->vmstats_percpu->nr_page_events, ug->nr_memory);
6740 memcg_check_events(ug->memcg, ug->nid);
6741 local_irq_restore(flags);
6743 /* drop reference from uncharge_folio */
6744 css_put(&ug->memcg->css);
6747 static void uncharge_folio(struct folio *folio, struct uncharge_gather *ug)
6750 struct mem_cgroup *memcg;
6751 struct obj_cgroup *objcg;
6753 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
6756 * Nobody should be changing or seriously looking at
6757 * folio memcg or objcg at this point, we have fully
6758 * exclusive access to the folio.
6760 if (folio_memcg_kmem(folio)) {
6761 objcg = __folio_objcg(folio);
6763 * This get matches the put at the end of the function and
6764 * kmem pages do not hold memcg references anymore.
6766 memcg = get_mem_cgroup_from_objcg(objcg);
6768 memcg = __folio_memcg(folio);
6774 if (ug->memcg != memcg) {
6777 uncharge_gather_clear(ug);
6780 ug->nid = folio_nid(folio);
6782 /* pairs with css_put in uncharge_batch */
6783 css_get(&memcg->css);
6786 nr_pages = folio_nr_pages(folio);
6788 if (folio_memcg_kmem(folio)) {
6789 ug->nr_memory += nr_pages;
6790 ug->nr_kmem += nr_pages;
6792 folio->memcg_data = 0;
6793 obj_cgroup_put(objcg);
6795 /* LRU pages aren't accounted at the root level */
6796 if (!mem_cgroup_is_root(memcg))
6797 ug->nr_memory += nr_pages;
6800 folio->memcg_data = 0;
6803 css_put(&memcg->css);
6806 void __mem_cgroup_uncharge(struct folio *folio)
6808 struct uncharge_gather ug;
6810 /* Don't touch folio->lru of any random page, pre-check: */
6811 if (!folio_memcg(folio))
6814 uncharge_gather_clear(&ug);
6815 uncharge_folio(folio, &ug);
6816 uncharge_batch(&ug);
6820 * __mem_cgroup_uncharge_list - uncharge a list of page
6821 * @page_list: list of pages to uncharge
6823 * Uncharge a list of pages previously charged with
6824 * __mem_cgroup_charge().
6826 void __mem_cgroup_uncharge_list(struct list_head *page_list)
6828 struct uncharge_gather ug;
6829 struct folio *folio;
6831 uncharge_gather_clear(&ug);
6832 list_for_each_entry(folio, page_list, lru)
6833 uncharge_folio(folio, &ug);
6835 uncharge_batch(&ug);
6839 * mem_cgroup_migrate - Charge a folio's replacement.
6840 * @old: Currently circulating folio.
6841 * @new: Replacement folio.
6843 * Charge @new as a replacement folio for @old. @old will
6844 * be uncharged upon free.
6846 * Both folios must be locked, @new->mapping must be set up.
6848 void mem_cgroup_migrate(struct folio *old, struct folio *new)
6850 struct mem_cgroup *memcg;
6851 long nr_pages = folio_nr_pages(new);
6852 unsigned long flags;
6854 VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
6855 VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
6856 VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
6857 VM_BUG_ON_FOLIO(folio_nr_pages(old) != nr_pages, new);
6859 if (mem_cgroup_disabled())
6862 /* Page cache replacement: new folio already charged? */
6863 if (folio_memcg(new))
6866 memcg = folio_memcg(old);
6867 VM_WARN_ON_ONCE_FOLIO(!memcg, old);
6871 /* Force-charge the new page. The old one will be freed soon */
6872 if (!mem_cgroup_is_root(memcg)) {
6873 page_counter_charge(&memcg->memory, nr_pages);
6874 if (do_memsw_account())
6875 page_counter_charge(&memcg->memsw, nr_pages);
6878 css_get(&memcg->css);
6879 commit_charge(new, memcg);
6881 local_irq_save(flags);
6882 mem_cgroup_charge_statistics(memcg, nr_pages);
6883 memcg_check_events(memcg, folio_nid(new));
6884 local_irq_restore(flags);
6887 DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
6888 EXPORT_SYMBOL(memcg_sockets_enabled_key);
6890 void mem_cgroup_sk_alloc(struct sock *sk)
6892 struct mem_cgroup *memcg;
6894 if (!mem_cgroup_sockets_enabled)
6897 /* Do not associate the sock with unrelated interrupted task's memcg. */
6902 memcg = mem_cgroup_from_task(current);
6903 if (memcg == root_mem_cgroup)
6905 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg->tcpmem_active)
6907 if (css_tryget(&memcg->css))
6908 sk->sk_memcg = memcg;
6913 void mem_cgroup_sk_free(struct sock *sk)
6916 css_put(&sk->sk_memcg->css);
6920 * mem_cgroup_charge_skmem - charge socket memory
6921 * @memcg: memcg to charge
6922 * @nr_pages: number of pages to charge
6923 * @gfp_mask: reclaim mode
6925 * Charges @nr_pages to @memcg. Returns %true if the charge fit within
6926 * @memcg's configured limit, %false if it doesn't.
6928 bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages,
6931 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
6932 struct page_counter *fail;
6934 if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) {
6935 memcg->tcpmem_pressure = 0;
6938 memcg->tcpmem_pressure = 1;
6939 if (gfp_mask & __GFP_NOFAIL) {
6940 page_counter_charge(&memcg->tcpmem, nr_pages);
6946 if (try_charge(memcg, gfp_mask, nr_pages) == 0) {
6947 mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
6955 * mem_cgroup_uncharge_skmem - uncharge socket memory
6956 * @memcg: memcg to uncharge
6957 * @nr_pages: number of pages to uncharge
6959 void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
6961 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
6962 page_counter_uncharge(&memcg->tcpmem, nr_pages);
6966 mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
6968 refill_stock(memcg, nr_pages);
6971 static int __init cgroup_memory(char *s)
6975 while ((token = strsep(&s, ",")) != NULL) {
6978 if (!strcmp(token, "nosocket"))
6979 cgroup_memory_nosocket = true;
6980 if (!strcmp(token, "nokmem"))
6981 cgroup_memory_nokmem = true;
6985 __setup("cgroup.memory=", cgroup_memory);
6988 * subsys_initcall() for memory controller.
6990 * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
6991 * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
6992 * basically everything that doesn't depend on a specific mem_cgroup structure
6993 * should be initialized from here.
6995 static int __init mem_cgroup_init(void)
7000 * Currently s32 type (can refer to struct batched_lruvec_stat) is
7001 * used for per-memcg-per-cpu caching of per-node statistics. In order
7002 * to work fine, we should make sure that the overfill threshold can't
7003 * exceed S32_MAX / PAGE_SIZE.
7005 BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE);
7007 cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
7008 memcg_hotplug_cpu_dead);
7010 for_each_possible_cpu(cpu)
7011 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
7014 for_each_node(node) {
7015 struct mem_cgroup_tree_per_node *rtpn;
7017 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL,
7018 node_online(node) ? node : NUMA_NO_NODE);
7020 rtpn->rb_root = RB_ROOT;
7021 rtpn->rb_rightmost = NULL;
7022 spin_lock_init(&rtpn->lock);
7023 soft_limit_tree.rb_tree_per_node[node] = rtpn;
7028 subsys_initcall(mem_cgroup_init);
7030 #ifdef CONFIG_MEMCG_SWAP
7031 static struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
7033 while (!refcount_inc_not_zero(&memcg->id.ref)) {
7035 * The root cgroup cannot be destroyed, so it's refcount must
7038 if (WARN_ON_ONCE(memcg == root_mem_cgroup)) {
7042 memcg = parent_mem_cgroup(memcg);
7044 memcg = root_mem_cgroup;
7050 * mem_cgroup_swapout - transfer a memsw charge to swap
7051 * @folio: folio whose memsw charge to transfer
7052 * @entry: swap entry to move the charge to
7054 * Transfer the memsw charge of @folio to @entry.
7056 void mem_cgroup_swapout(struct folio *folio, swp_entry_t entry)
7058 struct mem_cgroup *memcg, *swap_memcg;
7059 unsigned int nr_entries;
7060 unsigned short oldid;
7062 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
7063 VM_BUG_ON_FOLIO(folio_ref_count(folio), folio);
7065 if (mem_cgroup_disabled())
7068 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
7071 memcg = folio_memcg(folio);
7073 VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
7078 * In case the memcg owning these pages has been offlined and doesn't
7079 * have an ID allocated to it anymore, charge the closest online
7080 * ancestor for the swap instead and transfer the memory+swap charge.
7082 swap_memcg = mem_cgroup_id_get_online(memcg);
7083 nr_entries = folio_nr_pages(folio);
7084 /* Get references for the tail pages, too */
7086 mem_cgroup_id_get_many(swap_memcg, nr_entries - 1);
7087 oldid = swap_cgroup_record(entry, mem_cgroup_id(swap_memcg),
7089 VM_BUG_ON_FOLIO(oldid, folio);
7090 mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries);
7092 folio->memcg_data = 0;
7094 if (!mem_cgroup_is_root(memcg))
7095 page_counter_uncharge(&memcg->memory, nr_entries);
7097 if (!cgroup_memory_noswap && memcg != swap_memcg) {
7098 if (!mem_cgroup_is_root(swap_memcg))
7099 page_counter_charge(&swap_memcg->memsw, nr_entries);
7100 page_counter_uncharge(&memcg->memsw, nr_entries);
7104 * Interrupts should be disabled here because the caller holds the
7105 * i_pages lock which is taken with interrupts-off. It is
7106 * important here to have the interrupts disabled because it is the
7107 * only synchronisation we have for updating the per-CPU variables.
7110 mem_cgroup_charge_statistics(memcg, -nr_entries);
7111 memcg_stats_unlock();
7112 memcg_check_events(memcg, folio_nid(folio));
7114 css_put(&memcg->css);
7118 * __mem_cgroup_try_charge_swap - try charging swap space for a page
7119 * @page: page being added to swap
7120 * @entry: swap entry to charge
7122 * Try to charge @page's memcg for the swap space at @entry.
7124 * Returns 0 on success, -ENOMEM on failure.
7126 int __mem_cgroup_try_charge_swap(struct page *page, swp_entry_t entry)
7128 unsigned int nr_pages = thp_nr_pages(page);
7129 struct page_counter *counter;
7130 struct mem_cgroup *memcg;
7131 unsigned short oldid;
7133 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
7136 memcg = page_memcg(page);
7138 VM_WARN_ON_ONCE_PAGE(!memcg, page);
7143 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7147 memcg = mem_cgroup_id_get_online(memcg);
7149 if (!cgroup_memory_noswap && !mem_cgroup_is_root(memcg) &&
7150 !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
7151 memcg_memory_event(memcg, MEMCG_SWAP_MAX);
7152 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7153 mem_cgroup_id_put(memcg);
7157 /* Get references for the tail pages, too */
7159 mem_cgroup_id_get_many(memcg, nr_pages - 1);
7160 oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg), nr_pages);
7161 VM_BUG_ON_PAGE(oldid, page);
7162 mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
7168 * __mem_cgroup_uncharge_swap - uncharge swap space
7169 * @entry: swap entry to uncharge
7170 * @nr_pages: the amount of swap space to uncharge
7172 void __mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
7174 struct mem_cgroup *memcg;
7177 id = swap_cgroup_record(entry, 0, nr_pages);
7179 memcg = mem_cgroup_from_id(id);
7181 if (!cgroup_memory_noswap && !mem_cgroup_is_root(memcg)) {
7182 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
7183 page_counter_uncharge(&memcg->swap, nr_pages);
7185 page_counter_uncharge(&memcg->memsw, nr_pages);
7187 mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
7188 mem_cgroup_id_put_many(memcg, nr_pages);
7193 long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
7195 long nr_swap_pages = get_nr_swap_pages();
7197 if (cgroup_memory_noswap || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
7198 return nr_swap_pages;
7199 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg))
7200 nr_swap_pages = min_t(long, nr_swap_pages,
7201 READ_ONCE(memcg->swap.max) -
7202 page_counter_read(&memcg->swap));
7203 return nr_swap_pages;
7206 bool mem_cgroup_swap_full(struct page *page)
7208 struct mem_cgroup *memcg;
7210 VM_BUG_ON_PAGE(!PageLocked(page), page);
7214 if (cgroup_memory_noswap || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
7217 memcg = page_memcg(page);
7221 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg)) {
7222 unsigned long usage = page_counter_read(&memcg->swap);
7224 if (usage * 2 >= READ_ONCE(memcg->swap.high) ||
7225 usage * 2 >= READ_ONCE(memcg->swap.max))
7232 static int __init setup_swap_account(char *s)
7234 if (!strcmp(s, "1"))
7235 cgroup_memory_noswap = false;
7236 else if (!strcmp(s, "0"))
7237 cgroup_memory_noswap = true;
7240 __setup("swapaccount=", setup_swap_account);
7242 static u64 swap_current_read(struct cgroup_subsys_state *css,
7245 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7247 return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
7250 static int swap_high_show(struct seq_file *m, void *v)
7252 return seq_puts_memcg_tunable(m,
7253 READ_ONCE(mem_cgroup_from_seq(m)->swap.high));
7256 static ssize_t swap_high_write(struct kernfs_open_file *of,
7257 char *buf, size_t nbytes, loff_t off)
7259 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7263 buf = strstrip(buf);
7264 err = page_counter_memparse(buf, "max", &high);
7268 page_counter_set_high(&memcg->swap, high);
7273 static int swap_max_show(struct seq_file *m, void *v)
7275 return seq_puts_memcg_tunable(m,
7276 READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
7279 static ssize_t swap_max_write(struct kernfs_open_file *of,
7280 char *buf, size_t nbytes, loff_t off)
7282 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7286 buf = strstrip(buf);
7287 err = page_counter_memparse(buf, "max", &max);
7291 xchg(&memcg->swap.max, max);
7296 static int swap_events_show(struct seq_file *m, void *v)
7298 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
7300 seq_printf(m, "high %lu\n",
7301 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH]));
7302 seq_printf(m, "max %lu\n",
7303 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
7304 seq_printf(m, "fail %lu\n",
7305 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
7310 static struct cftype swap_files[] = {
7312 .name = "swap.current",
7313 .flags = CFTYPE_NOT_ON_ROOT,
7314 .read_u64 = swap_current_read,
7317 .name = "swap.high",
7318 .flags = CFTYPE_NOT_ON_ROOT,
7319 .seq_show = swap_high_show,
7320 .write = swap_high_write,
7324 .flags = CFTYPE_NOT_ON_ROOT,
7325 .seq_show = swap_max_show,
7326 .write = swap_max_write,
7329 .name = "swap.events",
7330 .flags = CFTYPE_NOT_ON_ROOT,
7331 .file_offset = offsetof(struct mem_cgroup, swap_events_file),
7332 .seq_show = swap_events_show,
7337 static struct cftype memsw_files[] = {
7339 .name = "memsw.usage_in_bytes",
7340 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
7341 .read_u64 = mem_cgroup_read_u64,
7344 .name = "memsw.max_usage_in_bytes",
7345 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
7346 .write = mem_cgroup_reset,
7347 .read_u64 = mem_cgroup_read_u64,
7350 .name = "memsw.limit_in_bytes",
7351 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
7352 .write = mem_cgroup_write,
7353 .read_u64 = mem_cgroup_read_u64,
7356 .name = "memsw.failcnt",
7357 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
7358 .write = mem_cgroup_reset,
7359 .read_u64 = mem_cgroup_read_u64,
7361 { }, /* terminate */
7365 * If mem_cgroup_swap_init() is implemented as a subsys_initcall()
7366 * instead of a core_initcall(), this could mean cgroup_memory_noswap still
7367 * remains set to false even when memcg is disabled via "cgroup_disable=memory"
7368 * boot parameter. This may result in premature OOPS inside
7369 * mem_cgroup_get_nr_swap_pages() function in corner cases.
7371 static int __init mem_cgroup_swap_init(void)
7373 /* No memory control -> no swap control */
7374 if (mem_cgroup_disabled())
7375 cgroup_memory_noswap = true;
7377 if (cgroup_memory_noswap)
7380 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files));
7381 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files));
7385 core_initcall(mem_cgroup_swap_init);
7387 #endif /* CONFIG_MEMCG_SWAP */