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>
72 #include <linux/uaccess.h>
74 #include <trace/events/vmscan.h>
76 struct cgroup_subsys memory_cgrp_subsys __read_mostly;
77 EXPORT_SYMBOL(memory_cgrp_subsys);
79 struct mem_cgroup *root_mem_cgroup __read_mostly;
81 /* Active memory cgroup to use from an interrupt context */
82 DEFINE_PER_CPU(struct mem_cgroup *, int_active_memcg);
83 EXPORT_PER_CPU_SYMBOL_GPL(int_active_memcg);
85 /* Socket memory accounting disabled? */
86 static bool cgroup_memory_nosocket __ro_after_init;
88 /* Kernel memory accounting disabled? */
89 static bool cgroup_memory_nokmem __ro_after_init;
91 #ifdef CONFIG_CGROUP_WRITEBACK
92 static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq);
95 /* Whether legacy memory+swap accounting is active */
96 static bool do_memsw_account(void)
98 return !cgroup_subsys_on_dfl(memory_cgrp_subsys);
101 #define THRESHOLDS_EVENTS_TARGET 128
102 #define SOFTLIMIT_EVENTS_TARGET 1024
105 * Cgroups above their limits are maintained in a RB-Tree, independent of
106 * their hierarchy representation
109 struct mem_cgroup_tree_per_node {
110 struct rb_root rb_root;
111 struct rb_node *rb_rightmost;
115 struct mem_cgroup_tree {
116 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
119 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
122 struct mem_cgroup_eventfd_list {
123 struct list_head list;
124 struct eventfd_ctx *eventfd;
128 * cgroup_event represents events which userspace want to receive.
130 struct mem_cgroup_event {
132 * memcg which the event belongs to.
134 struct mem_cgroup *memcg;
136 * eventfd to signal userspace about the event.
138 struct eventfd_ctx *eventfd;
140 * Each of these stored in a list by the cgroup.
142 struct list_head list;
144 * register_event() callback will be used to add new userspace
145 * waiter for changes related to this event. Use eventfd_signal()
146 * on eventfd to send notification to userspace.
148 int (*register_event)(struct mem_cgroup *memcg,
149 struct eventfd_ctx *eventfd, const char *args);
151 * unregister_event() callback will be called when userspace closes
152 * the eventfd or on cgroup removing. This callback must be set,
153 * if you want provide notification functionality.
155 void (*unregister_event)(struct mem_cgroup *memcg,
156 struct eventfd_ctx *eventfd);
158 * All fields below needed to unregister event when
159 * userspace closes eventfd.
162 wait_queue_head_t *wqh;
163 wait_queue_entry_t wait;
164 struct work_struct remove;
167 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
168 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
170 /* Stuffs for move charges at task migration. */
172 * Types of charges to be moved.
174 #define MOVE_ANON 0x1U
175 #define MOVE_FILE 0x2U
176 #define MOVE_MASK (MOVE_ANON | MOVE_FILE)
178 /* "mc" and its members are protected by cgroup_mutex */
179 static struct move_charge_struct {
180 spinlock_t lock; /* for from, to */
181 struct mm_struct *mm;
182 struct mem_cgroup *from;
183 struct mem_cgroup *to;
185 unsigned long precharge;
186 unsigned long moved_charge;
187 unsigned long moved_swap;
188 struct task_struct *moving_task; /* a task moving charges */
189 wait_queue_head_t waitq; /* a waitq for other context */
191 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
192 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
196 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
197 * limit reclaim to prevent infinite loops, if they ever occur.
199 #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
200 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
202 /* for encoding cft->private value on file */
210 #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
211 #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
212 #define MEMFILE_ATTR(val) ((val) & 0xffff)
215 * Iteration constructs for visiting all cgroups (under a tree). If
216 * loops are exited prematurely (break), mem_cgroup_iter_break() must
217 * be used for reference counting.
219 #define for_each_mem_cgroup_tree(iter, root) \
220 for (iter = mem_cgroup_iter(root, NULL, NULL); \
222 iter = mem_cgroup_iter(root, iter, NULL))
224 #define for_each_mem_cgroup(iter) \
225 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
227 iter = mem_cgroup_iter(NULL, iter, NULL))
229 static inline bool task_is_dying(void)
231 return tsk_is_oom_victim(current) || fatal_signal_pending(current) ||
232 (current->flags & PF_EXITING);
235 /* Some nice accessors for the vmpressure. */
236 struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
239 memcg = root_mem_cgroup;
240 return &memcg->vmpressure;
243 struct mem_cgroup *vmpressure_to_memcg(struct vmpressure *vmpr)
245 return container_of(vmpr, struct mem_cgroup, vmpressure);
248 #ifdef CONFIG_MEMCG_KMEM
249 static DEFINE_SPINLOCK(objcg_lock);
251 bool mem_cgroup_kmem_disabled(void)
253 return cgroup_memory_nokmem;
256 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
257 unsigned int nr_pages);
259 static void obj_cgroup_release(struct percpu_ref *ref)
261 struct obj_cgroup *objcg = container_of(ref, struct obj_cgroup, refcnt);
262 unsigned int nr_bytes;
263 unsigned int nr_pages;
267 * At this point all allocated objects are freed, and
268 * objcg->nr_charged_bytes can't have an arbitrary byte value.
269 * However, it can be PAGE_SIZE or (x * PAGE_SIZE).
271 * The following sequence can lead to it:
272 * 1) CPU0: objcg == stock->cached_objcg
273 * 2) CPU1: we do a small allocation (e.g. 92 bytes),
274 * PAGE_SIZE bytes are charged
275 * 3) CPU1: a process from another memcg is allocating something,
276 * the stock if flushed,
277 * objcg->nr_charged_bytes = PAGE_SIZE - 92
278 * 5) CPU0: we do release this object,
279 * 92 bytes are added to stock->nr_bytes
280 * 6) CPU0: stock is flushed,
281 * 92 bytes are added to objcg->nr_charged_bytes
283 * In the result, nr_charged_bytes == PAGE_SIZE.
284 * This page will be uncharged in obj_cgroup_release().
286 nr_bytes = atomic_read(&objcg->nr_charged_bytes);
287 WARN_ON_ONCE(nr_bytes & (PAGE_SIZE - 1));
288 nr_pages = nr_bytes >> PAGE_SHIFT;
291 obj_cgroup_uncharge_pages(objcg, nr_pages);
293 spin_lock_irqsave(&objcg_lock, flags);
294 list_del(&objcg->list);
295 spin_unlock_irqrestore(&objcg_lock, flags);
297 percpu_ref_exit(ref);
298 kfree_rcu(objcg, rcu);
301 static struct obj_cgroup *obj_cgroup_alloc(void)
303 struct obj_cgroup *objcg;
306 objcg = kzalloc(sizeof(struct obj_cgroup), GFP_KERNEL);
310 ret = percpu_ref_init(&objcg->refcnt, obj_cgroup_release, 0,
316 INIT_LIST_HEAD(&objcg->list);
320 static void memcg_reparent_objcgs(struct mem_cgroup *memcg,
321 struct mem_cgroup *parent)
323 struct obj_cgroup *objcg, *iter;
325 objcg = rcu_replace_pointer(memcg->objcg, NULL, true);
327 spin_lock_irq(&objcg_lock);
329 /* 1) Ready to reparent active objcg. */
330 list_add(&objcg->list, &memcg->objcg_list);
331 /* 2) Reparent active objcg and already reparented objcgs to parent. */
332 list_for_each_entry(iter, &memcg->objcg_list, list)
333 WRITE_ONCE(iter->memcg, parent);
334 /* 3) Move already reparented objcgs to the parent's list */
335 list_splice(&memcg->objcg_list, &parent->objcg_list);
337 spin_unlock_irq(&objcg_lock);
339 percpu_ref_kill(&objcg->refcnt);
343 * A lot of the calls to the cache allocation functions are expected to be
344 * inlined by the compiler. Since the calls to memcg_slab_pre_alloc_hook() are
345 * conditional to this static branch, we'll have to allow modules that does
346 * kmem_cache_alloc and the such to see this symbol as well
348 DEFINE_STATIC_KEY_FALSE(memcg_kmem_enabled_key);
349 EXPORT_SYMBOL(memcg_kmem_enabled_key);
353 * mem_cgroup_css_from_page - css of the memcg associated with a page
354 * @page: page of interest
356 * If memcg is bound to the default hierarchy, css of the memcg associated
357 * with @page is returned. The returned css remains associated with @page
358 * until it is released.
360 * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
363 struct cgroup_subsys_state *mem_cgroup_css_from_page(struct page *page)
365 struct mem_cgroup *memcg;
367 memcg = page_memcg(page);
369 if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
370 memcg = root_mem_cgroup;
376 * page_cgroup_ino - return inode number of the memcg a page is charged to
379 * Look up the closest online ancestor of the memory cgroup @page is charged to
380 * and return its inode number or 0 if @page is not charged to any cgroup. It
381 * is safe to call this function without holding a reference to @page.
383 * Note, this function is inherently racy, because there is nothing to prevent
384 * the cgroup inode from getting torn down and potentially reallocated a moment
385 * after page_cgroup_ino() returns, so it only should be used by callers that
386 * do not care (such as procfs interfaces).
388 ino_t page_cgroup_ino(struct page *page)
390 struct mem_cgroup *memcg;
391 unsigned long ino = 0;
394 memcg = page_memcg_check(page);
396 while (memcg && !(memcg->css.flags & CSS_ONLINE))
397 memcg = parent_mem_cgroup(memcg);
399 ino = cgroup_ino(memcg->css.cgroup);
404 static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_node *mz,
405 struct mem_cgroup_tree_per_node *mctz,
406 unsigned long new_usage_in_excess)
408 struct rb_node **p = &mctz->rb_root.rb_node;
409 struct rb_node *parent = NULL;
410 struct mem_cgroup_per_node *mz_node;
411 bool rightmost = true;
416 mz->usage_in_excess = new_usage_in_excess;
417 if (!mz->usage_in_excess)
421 mz_node = rb_entry(parent, struct mem_cgroup_per_node,
423 if (mz->usage_in_excess < mz_node->usage_in_excess) {
432 mctz->rb_rightmost = &mz->tree_node;
434 rb_link_node(&mz->tree_node, parent, p);
435 rb_insert_color(&mz->tree_node, &mctz->rb_root);
439 static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
440 struct mem_cgroup_tree_per_node *mctz)
445 if (&mz->tree_node == mctz->rb_rightmost)
446 mctz->rb_rightmost = rb_prev(&mz->tree_node);
448 rb_erase(&mz->tree_node, &mctz->rb_root);
452 static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
453 struct mem_cgroup_tree_per_node *mctz)
457 spin_lock_irqsave(&mctz->lock, flags);
458 __mem_cgroup_remove_exceeded(mz, mctz);
459 spin_unlock_irqrestore(&mctz->lock, flags);
462 static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
464 unsigned long nr_pages = page_counter_read(&memcg->memory);
465 unsigned long soft_limit = READ_ONCE(memcg->soft_limit);
466 unsigned long excess = 0;
468 if (nr_pages > soft_limit)
469 excess = nr_pages - soft_limit;
474 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, int nid)
476 unsigned long excess;
477 struct mem_cgroup_per_node *mz;
478 struct mem_cgroup_tree_per_node *mctz;
480 mctz = soft_limit_tree.rb_tree_per_node[nid];
484 * Necessary to update all ancestors when hierarchy is used.
485 * because their event counter is not touched.
487 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
488 mz = memcg->nodeinfo[nid];
489 excess = soft_limit_excess(memcg);
491 * We have to update the tree if mz is on RB-tree or
492 * mem is over its softlimit.
494 if (excess || mz->on_tree) {
497 spin_lock_irqsave(&mctz->lock, flags);
498 /* if on-tree, remove it */
500 __mem_cgroup_remove_exceeded(mz, mctz);
502 * Insert again. mz->usage_in_excess will be updated.
503 * If excess is 0, no tree ops.
505 __mem_cgroup_insert_exceeded(mz, mctz, excess);
506 spin_unlock_irqrestore(&mctz->lock, flags);
511 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
513 struct mem_cgroup_tree_per_node *mctz;
514 struct mem_cgroup_per_node *mz;
518 mz = memcg->nodeinfo[nid];
519 mctz = soft_limit_tree.rb_tree_per_node[nid];
521 mem_cgroup_remove_exceeded(mz, mctz);
525 static struct mem_cgroup_per_node *
526 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
528 struct mem_cgroup_per_node *mz;
532 if (!mctz->rb_rightmost)
533 goto done; /* Nothing to reclaim from */
535 mz = rb_entry(mctz->rb_rightmost,
536 struct mem_cgroup_per_node, tree_node);
538 * Remove the node now but someone else can add it back,
539 * we will to add it back at the end of reclaim to its correct
540 * position in the tree.
542 __mem_cgroup_remove_exceeded(mz, mctz);
543 if (!soft_limit_excess(mz->memcg) ||
544 !css_tryget(&mz->memcg->css))
550 static struct mem_cgroup_per_node *
551 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
553 struct mem_cgroup_per_node *mz;
555 spin_lock_irq(&mctz->lock);
556 mz = __mem_cgroup_largest_soft_limit_node(mctz);
557 spin_unlock_irq(&mctz->lock);
562 * memcg and lruvec stats flushing
564 * Many codepaths leading to stats update or read are performance sensitive and
565 * adding stats flushing in such codepaths is not desirable. So, to optimize the
566 * flushing the kernel does:
568 * 1) Periodically and asynchronously flush the stats every 2 seconds to not let
569 * rstat update tree grow unbounded.
571 * 2) Flush the stats synchronously on reader side only when there are more than
572 * (MEMCG_CHARGE_BATCH * nr_cpus) update events. Though this optimization
573 * will let stats be out of sync by atmost (MEMCG_CHARGE_BATCH * nr_cpus) but
574 * only for 2 seconds due to (1).
576 static void flush_memcg_stats_dwork(struct work_struct *w);
577 static DECLARE_DEFERRABLE_WORK(stats_flush_dwork, flush_memcg_stats_dwork);
578 static DEFINE_SPINLOCK(stats_flush_lock);
579 static DEFINE_PER_CPU(unsigned int, stats_updates);
580 static atomic_t stats_flush_threshold = ATOMIC_INIT(0);
581 static u64 flush_next_time;
583 #define FLUSH_TIME (2UL*HZ)
586 * Accessors to ensure that preemption is disabled on PREEMPT_RT because it can
587 * not rely on this as part of an acquired spinlock_t lock. These functions are
588 * never used in hardirq context on PREEMPT_RT and therefore disabling preemtion
591 static void memcg_stats_lock(void)
593 #ifdef CONFIG_PREEMPT_RT
596 VM_BUG_ON(!irqs_disabled());
600 static void __memcg_stats_lock(void)
602 #ifdef CONFIG_PREEMPT_RT
607 static void memcg_stats_unlock(void)
609 #ifdef CONFIG_PREEMPT_RT
614 static inline void memcg_rstat_updated(struct mem_cgroup *memcg, int val)
618 cgroup_rstat_updated(memcg->css.cgroup, smp_processor_id());
620 x = __this_cpu_add_return(stats_updates, abs(val));
621 if (x > MEMCG_CHARGE_BATCH) {
623 * If stats_flush_threshold exceeds the threshold
624 * (>num_online_cpus()), cgroup stats update will be triggered
625 * in __mem_cgroup_flush_stats(). Increasing this var further
626 * is redundant and simply adds overhead in atomic update.
628 if (atomic_read(&stats_flush_threshold) <= num_online_cpus())
629 atomic_add(x / MEMCG_CHARGE_BATCH, &stats_flush_threshold);
630 __this_cpu_write(stats_updates, 0);
634 static void __mem_cgroup_flush_stats(void)
638 if (!spin_trylock_irqsave(&stats_flush_lock, flag))
641 flush_next_time = jiffies_64 + 2*FLUSH_TIME;
642 cgroup_rstat_flush_irqsafe(root_mem_cgroup->css.cgroup);
643 atomic_set(&stats_flush_threshold, 0);
644 spin_unlock_irqrestore(&stats_flush_lock, flag);
647 void mem_cgroup_flush_stats(void)
649 if (atomic_read(&stats_flush_threshold) > num_online_cpus())
650 __mem_cgroup_flush_stats();
653 void mem_cgroup_flush_stats_delayed(void)
655 if (time_after64(jiffies_64, flush_next_time))
656 mem_cgroup_flush_stats();
659 static void flush_memcg_stats_dwork(struct work_struct *w)
661 __mem_cgroup_flush_stats();
662 queue_delayed_work(system_unbound_wq, &stats_flush_dwork, FLUSH_TIME);
665 /* Subset of vm_event_item to report for memcg event stats */
666 static const unsigned int memcg_vm_event_stat[] = {
680 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
684 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
690 #define NR_MEMCG_EVENTS ARRAY_SIZE(memcg_vm_event_stat)
691 static int mem_cgroup_events_index[NR_VM_EVENT_ITEMS] __read_mostly;
693 static void init_memcg_events(void)
697 for (i = 0; i < NR_MEMCG_EVENTS; ++i)
698 mem_cgroup_events_index[memcg_vm_event_stat[i]] = i + 1;
701 static inline int memcg_events_index(enum vm_event_item idx)
703 return mem_cgroup_events_index[idx] - 1;
706 struct memcg_vmstats_percpu {
707 /* Local (CPU and cgroup) page state & events */
708 long state[MEMCG_NR_STAT];
709 unsigned long events[NR_MEMCG_EVENTS];
711 /* Delta calculation for lockless upward propagation */
712 long state_prev[MEMCG_NR_STAT];
713 unsigned long events_prev[NR_MEMCG_EVENTS];
715 /* Cgroup1: threshold notifications & softlimit tree updates */
716 unsigned long nr_page_events;
717 unsigned long targets[MEM_CGROUP_NTARGETS];
720 struct memcg_vmstats {
721 /* Aggregated (CPU and subtree) page state & events */
722 long state[MEMCG_NR_STAT];
723 unsigned long events[NR_MEMCG_EVENTS];
725 /* Pending child counts during tree propagation */
726 long state_pending[MEMCG_NR_STAT];
727 unsigned long events_pending[NR_MEMCG_EVENTS];
730 unsigned long memcg_page_state(struct mem_cgroup *memcg, int idx)
732 long x = READ_ONCE(memcg->vmstats->state[idx]);
741 * __mod_memcg_state - update cgroup memory statistics
742 * @memcg: the memory cgroup
743 * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item
744 * @val: delta to add to the counter, can be negative
746 void __mod_memcg_state(struct mem_cgroup *memcg, int idx, int val)
748 if (mem_cgroup_disabled())
751 __this_cpu_add(memcg->vmstats_percpu->state[idx], val);
752 memcg_rstat_updated(memcg, val);
755 /* idx can be of type enum memcg_stat_item or node_stat_item. */
756 static unsigned long memcg_page_state_local(struct mem_cgroup *memcg, int idx)
761 for_each_possible_cpu(cpu)
762 x += per_cpu(memcg->vmstats_percpu->state[idx], cpu);
770 void __mod_memcg_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
773 struct mem_cgroup_per_node *pn;
774 struct mem_cgroup *memcg;
776 pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
780 * The caller from rmap relay on disabled preemption becase they never
781 * update their counter from in-interrupt context. For these two
782 * counters we check that the update is never performed from an
783 * interrupt context while other caller need to have disabled interrupt.
785 __memcg_stats_lock();
786 if (IS_ENABLED(CONFIG_DEBUG_VM) && !IS_ENABLED(CONFIG_PREEMPT_RT)) {
791 case NR_SHMEM_PMDMAPPED:
792 case NR_FILE_PMDMAPPED:
793 WARN_ON_ONCE(!in_task());
796 WARN_ON_ONCE(!irqs_disabled());
801 __this_cpu_add(memcg->vmstats_percpu->state[idx], val);
804 __this_cpu_add(pn->lruvec_stats_percpu->state[idx], val);
806 memcg_rstat_updated(memcg, val);
807 memcg_stats_unlock();
811 * __mod_lruvec_state - update lruvec memory statistics
812 * @lruvec: the lruvec
813 * @idx: the stat item
814 * @val: delta to add to the counter, can be negative
816 * The lruvec is the intersection of the NUMA node and a cgroup. This
817 * function updates the all three counters that are affected by a
818 * change of state at this level: per-node, per-cgroup, per-lruvec.
820 void __mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
824 __mod_node_page_state(lruvec_pgdat(lruvec), idx, val);
826 /* Update memcg and lruvec */
827 if (!mem_cgroup_disabled())
828 __mod_memcg_lruvec_state(lruvec, idx, val);
831 void __mod_lruvec_page_state(struct page *page, enum node_stat_item idx,
834 struct page *head = compound_head(page); /* rmap on tail pages */
835 struct mem_cgroup *memcg;
836 pg_data_t *pgdat = page_pgdat(page);
837 struct lruvec *lruvec;
840 memcg = page_memcg(head);
841 /* Untracked pages have no memcg, no lruvec. Update only the node */
844 __mod_node_page_state(pgdat, idx, val);
848 lruvec = mem_cgroup_lruvec(memcg, pgdat);
849 __mod_lruvec_state(lruvec, idx, val);
852 EXPORT_SYMBOL(__mod_lruvec_page_state);
854 void __mod_lruvec_kmem_state(void *p, enum node_stat_item idx, int val)
856 pg_data_t *pgdat = page_pgdat(virt_to_page(p));
857 struct mem_cgroup *memcg;
858 struct lruvec *lruvec;
861 memcg = mem_cgroup_from_slab_obj(p);
864 * Untracked pages have no memcg, no lruvec. Update only the
865 * node. If we reparent the slab objects to the root memcg,
866 * when we free the slab object, we need to update the per-memcg
867 * vmstats to keep it correct for the root memcg.
870 __mod_node_page_state(pgdat, idx, val);
872 lruvec = mem_cgroup_lruvec(memcg, pgdat);
873 __mod_lruvec_state(lruvec, idx, val);
879 * __count_memcg_events - account VM events in a cgroup
880 * @memcg: the memory cgroup
881 * @idx: the event item
882 * @count: the number of events that occurred
884 void __count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx,
887 int index = memcg_events_index(idx);
889 if (mem_cgroup_disabled() || index < 0)
893 __this_cpu_add(memcg->vmstats_percpu->events[index], count);
894 memcg_rstat_updated(memcg, count);
895 memcg_stats_unlock();
898 static unsigned long memcg_events(struct mem_cgroup *memcg, int event)
900 int index = memcg_events_index(event);
904 return READ_ONCE(memcg->vmstats->events[index]);
907 static unsigned long memcg_events_local(struct mem_cgroup *memcg, int event)
911 int index = memcg_events_index(event);
916 for_each_possible_cpu(cpu)
917 x += per_cpu(memcg->vmstats_percpu->events[index], cpu);
921 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
924 /* pagein of a big page is an event. So, ignore page size */
926 __count_memcg_events(memcg, PGPGIN, 1);
928 __count_memcg_events(memcg, PGPGOUT, 1);
929 nr_pages = -nr_pages; /* for event */
932 __this_cpu_add(memcg->vmstats_percpu->nr_page_events, nr_pages);
935 static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
936 enum mem_cgroup_events_target target)
938 unsigned long val, next;
940 val = __this_cpu_read(memcg->vmstats_percpu->nr_page_events);
941 next = __this_cpu_read(memcg->vmstats_percpu->targets[target]);
942 /* from time_after() in jiffies.h */
943 if ((long)(next - val) < 0) {
945 case MEM_CGROUP_TARGET_THRESH:
946 next = val + THRESHOLDS_EVENTS_TARGET;
948 case MEM_CGROUP_TARGET_SOFTLIMIT:
949 next = val + SOFTLIMIT_EVENTS_TARGET;
954 __this_cpu_write(memcg->vmstats_percpu->targets[target], next);
961 * Check events in order.
964 static void memcg_check_events(struct mem_cgroup *memcg, int nid)
966 if (IS_ENABLED(CONFIG_PREEMPT_RT))
969 /* threshold event is triggered in finer grain than soft limit */
970 if (unlikely(mem_cgroup_event_ratelimit(memcg,
971 MEM_CGROUP_TARGET_THRESH))) {
974 do_softlimit = mem_cgroup_event_ratelimit(memcg,
975 MEM_CGROUP_TARGET_SOFTLIMIT);
976 mem_cgroup_threshold(memcg);
977 if (unlikely(do_softlimit))
978 mem_cgroup_update_tree(memcg, nid);
982 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
985 * mm_update_next_owner() may clear mm->owner to NULL
986 * if it races with swapoff, page migration, etc.
987 * So this can be called with p == NULL.
992 return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
994 EXPORT_SYMBOL(mem_cgroup_from_task);
996 static __always_inline struct mem_cgroup *active_memcg(void)
999 return this_cpu_read(int_active_memcg);
1001 return current->active_memcg;
1005 * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
1006 * @mm: mm from which memcg should be extracted. It can be NULL.
1008 * Obtain a reference on mm->memcg and returns it if successful. If mm
1009 * is NULL, then the memcg is chosen as follows:
1010 * 1) The active memcg, if set.
1011 * 2) current->mm->memcg, if available
1013 * If mem_cgroup is disabled, NULL is returned.
1015 struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
1017 struct mem_cgroup *memcg;
1019 if (mem_cgroup_disabled())
1023 * Page cache insertions can happen without an
1024 * actual mm context, e.g. during disk probing
1025 * on boot, loopback IO, acct() writes etc.
1027 * No need to css_get on root memcg as the reference
1028 * counting is disabled on the root level in the
1029 * cgroup core. See CSS_NO_REF.
1031 if (unlikely(!mm)) {
1032 memcg = active_memcg();
1033 if (unlikely(memcg)) {
1034 /* remote memcg must hold a ref */
1035 css_get(&memcg->css);
1040 return root_mem_cgroup;
1045 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1046 if (unlikely(!memcg))
1047 memcg = root_mem_cgroup;
1048 } while (!css_tryget(&memcg->css));
1052 EXPORT_SYMBOL(get_mem_cgroup_from_mm);
1054 static __always_inline bool memcg_kmem_bypass(void)
1056 /* Allow remote memcg charging from any context. */
1057 if (unlikely(active_memcg()))
1060 /* Memcg to charge can't be determined. */
1061 if (!in_task() || !current->mm || (current->flags & PF_KTHREAD))
1068 * mem_cgroup_iter - iterate over memory cgroup hierarchy
1069 * @root: hierarchy root
1070 * @prev: previously returned memcg, NULL on first invocation
1071 * @reclaim: cookie for shared reclaim walks, NULL for full walks
1073 * Returns references to children of the hierarchy below @root, or
1074 * @root itself, or %NULL after a full round-trip.
1076 * Caller must pass the return value in @prev on subsequent
1077 * invocations for reference counting, or use mem_cgroup_iter_break()
1078 * to cancel a hierarchy walk before the round-trip is complete.
1080 * Reclaimers can specify a node in @reclaim to divide up the memcgs
1081 * in the hierarchy among all concurrent reclaimers operating on the
1084 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
1085 struct mem_cgroup *prev,
1086 struct mem_cgroup_reclaim_cookie *reclaim)
1088 struct mem_cgroup_reclaim_iter *iter;
1089 struct cgroup_subsys_state *css = NULL;
1090 struct mem_cgroup *memcg = NULL;
1091 struct mem_cgroup *pos = NULL;
1093 if (mem_cgroup_disabled())
1097 root = root_mem_cgroup;
1102 struct mem_cgroup_per_node *mz;
1104 mz = root->nodeinfo[reclaim->pgdat->node_id];
1108 * On start, join the current reclaim iteration cycle.
1109 * Exit when a concurrent walker completes it.
1112 reclaim->generation = iter->generation;
1113 else if (reclaim->generation != iter->generation)
1117 pos = READ_ONCE(iter->position);
1118 if (!pos || css_tryget(&pos->css))
1121 * css reference reached zero, so iter->position will
1122 * be cleared by ->css_released. However, we should not
1123 * rely on this happening soon, because ->css_released
1124 * is called from a work queue, and by busy-waiting we
1125 * might block it. So we clear iter->position right
1128 (void)cmpxchg(&iter->position, pos, NULL);
1138 css = css_next_descendant_pre(css, &root->css);
1141 * Reclaimers share the hierarchy walk, and a
1142 * new one might jump in right at the end of
1143 * the hierarchy - make sure they see at least
1144 * one group and restart from the beginning.
1152 * Verify the css and acquire a reference. The root
1153 * is provided by the caller, so we know it's alive
1154 * and kicking, and don't take an extra reference.
1156 if (css == &root->css || css_tryget(css)) {
1157 memcg = mem_cgroup_from_css(css);
1164 * The position could have already been updated by a competing
1165 * thread, so check that the value hasn't changed since we read
1166 * it to avoid reclaiming from the same cgroup twice.
1168 (void)cmpxchg(&iter->position, pos, memcg);
1179 if (prev && prev != root)
1180 css_put(&prev->css);
1186 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1187 * @root: hierarchy root
1188 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1190 void mem_cgroup_iter_break(struct mem_cgroup *root,
1191 struct mem_cgroup *prev)
1194 root = root_mem_cgroup;
1195 if (prev && prev != root)
1196 css_put(&prev->css);
1199 static void __invalidate_reclaim_iterators(struct mem_cgroup *from,
1200 struct mem_cgroup *dead_memcg)
1202 struct mem_cgroup_reclaim_iter *iter;
1203 struct mem_cgroup_per_node *mz;
1206 for_each_node(nid) {
1207 mz = from->nodeinfo[nid];
1209 cmpxchg(&iter->position, dead_memcg, NULL);
1213 static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
1215 struct mem_cgroup *memcg = dead_memcg;
1216 struct mem_cgroup *last;
1219 __invalidate_reclaim_iterators(memcg, dead_memcg);
1221 } while ((memcg = parent_mem_cgroup(memcg)));
1224 * When cgroup1 non-hierarchy mode is used,
1225 * parent_mem_cgroup() does not walk all the way up to the
1226 * cgroup root (root_mem_cgroup). So we have to handle
1227 * dead_memcg from cgroup root separately.
1229 if (last != root_mem_cgroup)
1230 __invalidate_reclaim_iterators(root_mem_cgroup,
1235 * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
1236 * @memcg: hierarchy root
1237 * @fn: function to call for each task
1238 * @arg: argument passed to @fn
1240 * This function iterates over tasks attached to @memcg or to any of its
1241 * descendants and calls @fn for each task. If @fn returns a non-zero
1242 * value, the function breaks the iteration loop and returns the value.
1243 * Otherwise, it will iterate over all tasks and return 0.
1245 * This function must not be called for the root memory cgroup.
1247 int mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
1248 int (*fn)(struct task_struct *, void *), void *arg)
1250 struct mem_cgroup *iter;
1253 BUG_ON(memcg == root_mem_cgroup);
1255 for_each_mem_cgroup_tree(iter, memcg) {
1256 struct css_task_iter it;
1257 struct task_struct *task;
1259 css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it);
1260 while (!ret && (task = css_task_iter_next(&it)))
1261 ret = fn(task, arg);
1262 css_task_iter_end(&it);
1264 mem_cgroup_iter_break(memcg, iter);
1271 #ifdef CONFIG_DEBUG_VM
1272 void lruvec_memcg_debug(struct lruvec *lruvec, struct folio *folio)
1274 struct mem_cgroup *memcg;
1276 if (mem_cgroup_disabled())
1279 memcg = folio_memcg(folio);
1282 VM_BUG_ON_FOLIO(lruvec_memcg(lruvec) != root_mem_cgroup, folio);
1284 VM_BUG_ON_FOLIO(lruvec_memcg(lruvec) != memcg, folio);
1289 * folio_lruvec_lock - Lock the lruvec for a folio.
1290 * @folio: Pointer to the folio.
1292 * These functions are safe to use under any of the following conditions:
1294 * - folio_test_lru false
1295 * - folio_memcg_lock()
1296 * - folio frozen (refcount of 0)
1298 * Return: The lruvec this folio is on with its lock held.
1300 struct lruvec *folio_lruvec_lock(struct folio *folio)
1302 struct lruvec *lruvec = folio_lruvec(folio);
1304 spin_lock(&lruvec->lru_lock);
1305 lruvec_memcg_debug(lruvec, folio);
1311 * folio_lruvec_lock_irq - Lock the lruvec for a folio.
1312 * @folio: Pointer to the folio.
1314 * These functions are safe to use under any of the following conditions:
1316 * - folio_test_lru false
1317 * - folio_memcg_lock()
1318 * - folio frozen (refcount of 0)
1320 * Return: The lruvec this folio is on with its lock held and interrupts
1323 struct lruvec *folio_lruvec_lock_irq(struct folio *folio)
1325 struct lruvec *lruvec = folio_lruvec(folio);
1327 spin_lock_irq(&lruvec->lru_lock);
1328 lruvec_memcg_debug(lruvec, folio);
1334 * folio_lruvec_lock_irqsave - Lock the lruvec for a folio.
1335 * @folio: Pointer to the folio.
1336 * @flags: Pointer to irqsave flags.
1338 * These functions are safe to use under any of the following conditions:
1340 * - folio_test_lru false
1341 * - folio_memcg_lock()
1342 * - folio frozen (refcount of 0)
1344 * Return: The lruvec this folio is on with its lock held and interrupts
1347 struct lruvec *folio_lruvec_lock_irqsave(struct folio *folio,
1348 unsigned long *flags)
1350 struct lruvec *lruvec = folio_lruvec(folio);
1352 spin_lock_irqsave(&lruvec->lru_lock, *flags);
1353 lruvec_memcg_debug(lruvec, folio);
1359 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1360 * @lruvec: mem_cgroup per zone lru vector
1361 * @lru: index of lru list the page is sitting on
1362 * @zid: zone id of the accounted pages
1363 * @nr_pages: positive when adding or negative when removing
1365 * This function must be called under lru_lock, just before a page is added
1366 * to or just after a page is removed from an lru list.
1368 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1369 int zid, int nr_pages)
1371 struct mem_cgroup_per_node *mz;
1372 unsigned long *lru_size;
1375 if (mem_cgroup_disabled())
1378 mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
1379 lru_size = &mz->lru_zone_size[zid][lru];
1382 *lru_size += nr_pages;
1385 if (WARN_ONCE(size < 0,
1386 "%s(%p, %d, %d): lru_size %ld\n",
1387 __func__, lruvec, lru, nr_pages, size)) {
1393 *lru_size += nr_pages;
1397 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1398 * @memcg: the memory cgroup
1400 * Returns the maximum amount of memory @mem can be charged with, in
1403 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1405 unsigned long margin = 0;
1406 unsigned long count;
1407 unsigned long limit;
1409 count = page_counter_read(&memcg->memory);
1410 limit = READ_ONCE(memcg->memory.max);
1412 margin = limit - count;
1414 if (do_memsw_account()) {
1415 count = page_counter_read(&memcg->memsw);
1416 limit = READ_ONCE(memcg->memsw.max);
1418 margin = min(margin, limit - count);
1427 * A routine for checking "mem" is under move_account() or not.
1429 * Checking a cgroup is mc.from or mc.to or under hierarchy of
1430 * moving cgroups. This is for waiting at high-memory pressure
1433 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1435 struct mem_cgroup *from;
1436 struct mem_cgroup *to;
1439 * Unlike task_move routines, we access mc.to, mc.from not under
1440 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1442 spin_lock(&mc.lock);
1448 ret = mem_cgroup_is_descendant(from, memcg) ||
1449 mem_cgroup_is_descendant(to, memcg);
1451 spin_unlock(&mc.lock);
1455 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1457 if (mc.moving_task && current != mc.moving_task) {
1458 if (mem_cgroup_under_move(memcg)) {
1460 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1461 /* moving charge context might have finished. */
1464 finish_wait(&mc.waitq, &wait);
1471 struct memory_stat {
1476 static const struct memory_stat memory_stats[] = {
1477 { "anon", NR_ANON_MAPPED },
1478 { "file", NR_FILE_PAGES },
1479 { "kernel", MEMCG_KMEM },
1480 { "kernel_stack", NR_KERNEL_STACK_KB },
1481 { "pagetables", NR_PAGETABLE },
1482 { "percpu", MEMCG_PERCPU_B },
1483 { "sock", MEMCG_SOCK },
1484 { "vmalloc", MEMCG_VMALLOC },
1485 { "shmem", NR_SHMEM },
1486 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
1487 { "zswap", MEMCG_ZSWAP_B },
1488 { "zswapped", MEMCG_ZSWAPPED },
1490 { "file_mapped", NR_FILE_MAPPED },
1491 { "file_dirty", NR_FILE_DIRTY },
1492 { "file_writeback", NR_WRITEBACK },
1494 { "swapcached", NR_SWAPCACHE },
1496 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1497 { "anon_thp", NR_ANON_THPS },
1498 { "file_thp", NR_FILE_THPS },
1499 { "shmem_thp", NR_SHMEM_THPS },
1501 { "inactive_anon", NR_INACTIVE_ANON },
1502 { "active_anon", NR_ACTIVE_ANON },
1503 { "inactive_file", NR_INACTIVE_FILE },
1504 { "active_file", NR_ACTIVE_FILE },
1505 { "unevictable", NR_UNEVICTABLE },
1506 { "slab_reclaimable", NR_SLAB_RECLAIMABLE_B },
1507 { "slab_unreclaimable", NR_SLAB_UNRECLAIMABLE_B },
1509 /* The memory events */
1510 { "workingset_refault_anon", WORKINGSET_REFAULT_ANON },
1511 { "workingset_refault_file", WORKINGSET_REFAULT_FILE },
1512 { "workingset_activate_anon", WORKINGSET_ACTIVATE_ANON },
1513 { "workingset_activate_file", WORKINGSET_ACTIVATE_FILE },
1514 { "workingset_restore_anon", WORKINGSET_RESTORE_ANON },
1515 { "workingset_restore_file", WORKINGSET_RESTORE_FILE },
1516 { "workingset_nodereclaim", WORKINGSET_NODERECLAIM },
1519 /* Translate stat items to the correct unit for memory.stat output */
1520 static int memcg_page_state_unit(int item)
1523 case MEMCG_PERCPU_B:
1525 case NR_SLAB_RECLAIMABLE_B:
1526 case NR_SLAB_UNRECLAIMABLE_B:
1527 case WORKINGSET_REFAULT_ANON:
1528 case WORKINGSET_REFAULT_FILE:
1529 case WORKINGSET_ACTIVATE_ANON:
1530 case WORKINGSET_ACTIVATE_FILE:
1531 case WORKINGSET_RESTORE_ANON:
1532 case WORKINGSET_RESTORE_FILE:
1533 case WORKINGSET_NODERECLAIM:
1535 case NR_KERNEL_STACK_KB:
1542 static inline unsigned long memcg_page_state_output(struct mem_cgroup *memcg,
1545 return memcg_page_state(memcg, item) * memcg_page_state_unit(item);
1548 static void memory_stat_format(struct mem_cgroup *memcg, char *buf, int bufsize)
1553 seq_buf_init(&s, buf, bufsize);
1556 * Provide statistics on the state of the memory subsystem as
1557 * well as cumulative event counters that show past behavior.
1559 * This list is ordered following a combination of these gradients:
1560 * 1) generic big picture -> specifics and details
1561 * 2) reflecting userspace activity -> reflecting kernel heuristics
1563 * Current memory state:
1565 mem_cgroup_flush_stats();
1567 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
1570 size = memcg_page_state_output(memcg, memory_stats[i].idx);
1571 seq_buf_printf(&s, "%s %llu\n", memory_stats[i].name, size);
1573 if (unlikely(memory_stats[i].idx == NR_SLAB_UNRECLAIMABLE_B)) {
1574 size += memcg_page_state_output(memcg,
1575 NR_SLAB_RECLAIMABLE_B);
1576 seq_buf_printf(&s, "slab %llu\n", size);
1580 /* Accumulated memory events */
1581 seq_buf_printf(&s, "pgscan %lu\n",
1582 memcg_events(memcg, PGSCAN_KSWAPD) +
1583 memcg_events(memcg, PGSCAN_DIRECT));
1584 seq_buf_printf(&s, "pgsteal %lu\n",
1585 memcg_events(memcg, PGSTEAL_KSWAPD) +
1586 memcg_events(memcg, PGSTEAL_DIRECT));
1588 for (i = 0; i < ARRAY_SIZE(memcg_vm_event_stat); i++) {
1589 if (memcg_vm_event_stat[i] == PGPGIN ||
1590 memcg_vm_event_stat[i] == PGPGOUT)
1593 seq_buf_printf(&s, "%s %lu\n",
1594 vm_event_name(memcg_vm_event_stat[i]),
1595 memcg_events(memcg, memcg_vm_event_stat[i]));
1598 /* The above should easily fit into one page */
1599 WARN_ON_ONCE(seq_buf_has_overflowed(&s));
1602 #define K(x) ((x) << (PAGE_SHIFT-10))
1604 * mem_cgroup_print_oom_context: Print OOM information relevant to
1605 * memory controller.
1606 * @memcg: The memory cgroup that went over limit
1607 * @p: Task that is going to be killed
1609 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1612 void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p)
1617 pr_cont(",oom_memcg=");
1618 pr_cont_cgroup_path(memcg->css.cgroup);
1620 pr_cont(",global_oom");
1622 pr_cont(",task_memcg=");
1623 pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
1629 * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
1630 * memory controller.
1631 * @memcg: The memory cgroup that went over limit
1633 void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
1635 /* Use static buffer, for the caller is holding oom_lock. */
1636 static char buf[PAGE_SIZE];
1638 lockdep_assert_held(&oom_lock);
1640 pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1641 K((u64)page_counter_read(&memcg->memory)),
1642 K((u64)READ_ONCE(memcg->memory.max)), memcg->memory.failcnt);
1643 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1644 pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n",
1645 K((u64)page_counter_read(&memcg->swap)),
1646 K((u64)READ_ONCE(memcg->swap.max)), memcg->swap.failcnt);
1648 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1649 K((u64)page_counter_read(&memcg->memsw)),
1650 K((u64)memcg->memsw.max), memcg->memsw.failcnt);
1651 pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1652 K((u64)page_counter_read(&memcg->kmem)),
1653 K((u64)memcg->kmem.max), memcg->kmem.failcnt);
1656 pr_info("Memory cgroup stats for ");
1657 pr_cont_cgroup_path(memcg->css.cgroup);
1659 memory_stat_format(memcg, buf, sizeof(buf));
1664 * Return the memory (and swap, if configured) limit for a memcg.
1666 unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg)
1668 unsigned long max = READ_ONCE(memcg->memory.max);
1670 if (do_memsw_account()) {
1671 if (mem_cgroup_swappiness(memcg)) {
1672 /* Calculate swap excess capacity from memsw limit */
1673 unsigned long swap = READ_ONCE(memcg->memsw.max) - max;
1675 max += min(swap, (unsigned long)total_swap_pages);
1678 if (mem_cgroup_swappiness(memcg))
1679 max += min(READ_ONCE(memcg->swap.max),
1680 (unsigned long)total_swap_pages);
1685 unsigned long mem_cgroup_size(struct mem_cgroup *memcg)
1687 return page_counter_read(&memcg->memory);
1690 static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1693 struct oom_control oc = {
1697 .gfp_mask = gfp_mask,
1702 if (mutex_lock_killable(&oom_lock))
1705 if (mem_cgroup_margin(memcg) >= (1 << order))
1709 * A few threads which were not waiting at mutex_lock_killable() can
1710 * fail to bail out. Therefore, check again after holding oom_lock.
1712 ret = task_is_dying() || out_of_memory(&oc);
1715 mutex_unlock(&oom_lock);
1719 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
1722 unsigned long *total_scanned)
1724 struct mem_cgroup *victim = NULL;
1727 unsigned long excess;
1728 unsigned long nr_scanned;
1729 struct mem_cgroup_reclaim_cookie reclaim = {
1733 excess = soft_limit_excess(root_memcg);
1736 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1741 * If we have not been able to reclaim
1742 * anything, it might because there are
1743 * no reclaimable pages under this hierarchy
1748 * We want to do more targeted reclaim.
1749 * excess >> 2 is not to excessive so as to
1750 * reclaim too much, nor too less that we keep
1751 * coming back to reclaim from this cgroup
1753 if (total >= (excess >> 2) ||
1754 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1759 total += mem_cgroup_shrink_node(victim, gfp_mask, false,
1760 pgdat, &nr_scanned);
1761 *total_scanned += nr_scanned;
1762 if (!soft_limit_excess(root_memcg))
1765 mem_cgroup_iter_break(root_memcg, victim);
1769 #ifdef CONFIG_LOCKDEP
1770 static struct lockdep_map memcg_oom_lock_dep_map = {
1771 .name = "memcg_oom_lock",
1775 static DEFINE_SPINLOCK(memcg_oom_lock);
1778 * Check OOM-Killer is already running under our hierarchy.
1779 * If someone is running, return false.
1781 static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
1783 struct mem_cgroup *iter, *failed = NULL;
1785 spin_lock(&memcg_oom_lock);
1787 for_each_mem_cgroup_tree(iter, memcg) {
1788 if (iter->oom_lock) {
1790 * this subtree of our hierarchy is already locked
1791 * so we cannot give a lock.
1794 mem_cgroup_iter_break(memcg, iter);
1797 iter->oom_lock = true;
1802 * OK, we failed to lock the whole subtree so we have
1803 * to clean up what we set up to the failing subtree
1805 for_each_mem_cgroup_tree(iter, memcg) {
1806 if (iter == failed) {
1807 mem_cgroup_iter_break(memcg, iter);
1810 iter->oom_lock = false;
1813 mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
1815 spin_unlock(&memcg_oom_lock);
1820 static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1822 struct mem_cgroup *iter;
1824 spin_lock(&memcg_oom_lock);
1825 mutex_release(&memcg_oom_lock_dep_map, _RET_IP_);
1826 for_each_mem_cgroup_tree(iter, memcg)
1827 iter->oom_lock = false;
1828 spin_unlock(&memcg_oom_lock);
1831 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1833 struct mem_cgroup *iter;
1835 spin_lock(&memcg_oom_lock);
1836 for_each_mem_cgroup_tree(iter, memcg)
1838 spin_unlock(&memcg_oom_lock);
1841 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1843 struct mem_cgroup *iter;
1846 * Be careful about under_oom underflows because a child memcg
1847 * could have been added after mem_cgroup_mark_under_oom.
1849 spin_lock(&memcg_oom_lock);
1850 for_each_mem_cgroup_tree(iter, memcg)
1851 if (iter->under_oom > 0)
1853 spin_unlock(&memcg_oom_lock);
1856 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1858 struct oom_wait_info {
1859 struct mem_cgroup *memcg;
1860 wait_queue_entry_t wait;
1863 static int memcg_oom_wake_function(wait_queue_entry_t *wait,
1864 unsigned mode, int sync, void *arg)
1866 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
1867 struct mem_cgroup *oom_wait_memcg;
1868 struct oom_wait_info *oom_wait_info;
1870 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1871 oom_wait_memcg = oom_wait_info->memcg;
1873 if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
1874 !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
1876 return autoremove_wake_function(wait, mode, sync, arg);
1879 static void memcg_oom_recover(struct mem_cgroup *memcg)
1882 * For the following lockless ->under_oom test, the only required
1883 * guarantee is that it must see the state asserted by an OOM when
1884 * this function is called as a result of userland actions
1885 * triggered by the notification of the OOM. This is trivially
1886 * achieved by invoking mem_cgroup_mark_under_oom() before
1887 * triggering notification.
1889 if (memcg && memcg->under_oom)
1890 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
1894 * Returns true if successfully killed one or more processes. Though in some
1895 * corner cases it can return true even without killing any process.
1897 static bool mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
1901 if (order > PAGE_ALLOC_COSTLY_ORDER)
1904 memcg_memory_event(memcg, MEMCG_OOM);
1907 * We are in the middle of the charge context here, so we
1908 * don't want to block when potentially sitting on a callstack
1909 * that holds all kinds of filesystem and mm locks.
1911 * cgroup1 allows disabling the OOM killer and waiting for outside
1912 * handling until the charge can succeed; remember the context and put
1913 * the task to sleep at the end of the page fault when all locks are
1916 * On the other hand, in-kernel OOM killer allows for an async victim
1917 * memory reclaim (oom_reaper) and that means that we are not solely
1918 * relying on the oom victim to make a forward progress and we can
1919 * invoke the oom killer here.
1921 * Please note that mem_cgroup_out_of_memory might fail to find a
1922 * victim and then we have to bail out from the charge path.
1924 if (memcg->oom_kill_disable) {
1925 if (current->in_user_fault) {
1926 css_get(&memcg->css);
1927 current->memcg_in_oom = memcg;
1928 current->memcg_oom_gfp_mask = mask;
1929 current->memcg_oom_order = order;
1934 mem_cgroup_mark_under_oom(memcg);
1936 locked = mem_cgroup_oom_trylock(memcg);
1939 mem_cgroup_oom_notify(memcg);
1941 mem_cgroup_unmark_under_oom(memcg);
1942 ret = mem_cgroup_out_of_memory(memcg, mask, order);
1945 mem_cgroup_oom_unlock(memcg);
1951 * mem_cgroup_oom_synchronize - complete memcg OOM handling
1952 * @handle: actually kill/wait or just clean up the OOM state
1954 * This has to be called at the end of a page fault if the memcg OOM
1955 * handler was enabled.
1957 * Memcg supports userspace OOM handling where failed allocations must
1958 * sleep on a waitqueue until the userspace task resolves the
1959 * situation. Sleeping directly in the charge context with all kinds
1960 * of locks held is not a good idea, instead we remember an OOM state
1961 * in the task and mem_cgroup_oom_synchronize() has to be called at
1962 * the end of the page fault to complete the OOM handling.
1964 * Returns %true if an ongoing memcg OOM situation was detected and
1965 * completed, %false otherwise.
1967 bool mem_cgroup_oom_synchronize(bool handle)
1969 struct mem_cgroup *memcg = current->memcg_in_oom;
1970 struct oom_wait_info owait;
1973 /* OOM is global, do not handle */
1980 owait.memcg = memcg;
1981 owait.wait.flags = 0;
1982 owait.wait.func = memcg_oom_wake_function;
1983 owait.wait.private = current;
1984 INIT_LIST_HEAD(&owait.wait.entry);
1986 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
1987 mem_cgroup_mark_under_oom(memcg);
1989 locked = mem_cgroup_oom_trylock(memcg);
1992 mem_cgroup_oom_notify(memcg);
1994 if (locked && !memcg->oom_kill_disable) {
1995 mem_cgroup_unmark_under_oom(memcg);
1996 finish_wait(&memcg_oom_waitq, &owait.wait);
1997 mem_cgroup_out_of_memory(memcg, current->memcg_oom_gfp_mask,
1998 current->memcg_oom_order);
2001 mem_cgroup_unmark_under_oom(memcg);
2002 finish_wait(&memcg_oom_waitq, &owait.wait);
2006 mem_cgroup_oom_unlock(memcg);
2008 * There is no guarantee that an OOM-lock contender
2009 * sees the wakeups triggered by the OOM kill
2010 * uncharges. Wake any sleepers explicitly.
2012 memcg_oom_recover(memcg);
2015 current->memcg_in_oom = NULL;
2016 css_put(&memcg->css);
2021 * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
2022 * @victim: task to be killed by the OOM killer
2023 * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
2025 * Returns a pointer to a memory cgroup, which has to be cleaned up
2026 * by killing all belonging OOM-killable tasks.
2028 * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
2030 struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim,
2031 struct mem_cgroup *oom_domain)
2033 struct mem_cgroup *oom_group = NULL;
2034 struct mem_cgroup *memcg;
2036 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
2040 oom_domain = root_mem_cgroup;
2044 memcg = mem_cgroup_from_task(victim);
2045 if (memcg == root_mem_cgroup)
2049 * If the victim task has been asynchronously moved to a different
2050 * memory cgroup, we might end up killing tasks outside oom_domain.
2051 * In this case it's better to ignore memory.group.oom.
2053 if (unlikely(!mem_cgroup_is_descendant(memcg, oom_domain)))
2057 * Traverse the memory cgroup hierarchy from the victim task's
2058 * cgroup up to the OOMing cgroup (or root) to find the
2059 * highest-level memory cgroup with oom.group set.
2061 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
2062 if (memcg->oom_group)
2065 if (memcg == oom_domain)
2070 css_get(&oom_group->css);
2077 void mem_cgroup_print_oom_group(struct mem_cgroup *memcg)
2079 pr_info("Tasks in ");
2080 pr_cont_cgroup_path(memcg->css.cgroup);
2081 pr_cont(" are going to be killed due to memory.oom.group set\n");
2085 * folio_memcg_lock - Bind a folio to its memcg.
2086 * @folio: The folio.
2088 * This function prevents unlocked LRU folios from being moved to
2091 * It ensures lifetime of the bound memcg. The caller is responsible
2092 * for the lifetime of the folio.
2094 void folio_memcg_lock(struct folio *folio)
2096 struct mem_cgroup *memcg;
2097 unsigned long flags;
2100 * The RCU lock is held throughout the transaction. The fast
2101 * path can get away without acquiring the memcg->move_lock
2102 * because page moving starts with an RCU grace period.
2106 if (mem_cgroup_disabled())
2109 memcg = folio_memcg(folio);
2110 if (unlikely(!memcg))
2113 #ifdef CONFIG_PROVE_LOCKING
2114 local_irq_save(flags);
2115 might_lock(&memcg->move_lock);
2116 local_irq_restore(flags);
2119 if (atomic_read(&memcg->moving_account) <= 0)
2122 spin_lock_irqsave(&memcg->move_lock, flags);
2123 if (memcg != folio_memcg(folio)) {
2124 spin_unlock_irqrestore(&memcg->move_lock, flags);
2129 * When charge migration first begins, we can have multiple
2130 * critical sections holding the fast-path RCU lock and one
2131 * holding the slowpath move_lock. Track the task who has the
2132 * move_lock for unlock_page_memcg().
2134 memcg->move_lock_task = current;
2135 memcg->move_lock_flags = flags;
2138 void lock_page_memcg(struct page *page)
2140 folio_memcg_lock(page_folio(page));
2143 static void __folio_memcg_unlock(struct mem_cgroup *memcg)
2145 if (memcg && memcg->move_lock_task == current) {
2146 unsigned long flags = memcg->move_lock_flags;
2148 memcg->move_lock_task = NULL;
2149 memcg->move_lock_flags = 0;
2151 spin_unlock_irqrestore(&memcg->move_lock, flags);
2158 * folio_memcg_unlock - Release the binding between a folio and its memcg.
2159 * @folio: The folio.
2161 * This releases the binding created by folio_memcg_lock(). This does
2162 * not change the accounting of this folio to its memcg, but it does
2163 * permit others to change it.
2165 void folio_memcg_unlock(struct folio *folio)
2167 __folio_memcg_unlock(folio_memcg(folio));
2170 void unlock_page_memcg(struct page *page)
2172 folio_memcg_unlock(page_folio(page));
2175 struct memcg_stock_pcp {
2176 local_lock_t stock_lock;
2177 struct mem_cgroup *cached; /* this never be root cgroup */
2178 unsigned int nr_pages;
2180 #ifdef CONFIG_MEMCG_KMEM
2181 struct obj_cgroup *cached_objcg;
2182 struct pglist_data *cached_pgdat;
2183 unsigned int nr_bytes;
2184 int nr_slab_reclaimable_b;
2185 int nr_slab_unreclaimable_b;
2188 struct work_struct work;
2189 unsigned long flags;
2190 #define FLUSHING_CACHED_CHARGE 0
2192 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock) = {
2193 .stock_lock = INIT_LOCAL_LOCK(stock_lock),
2195 static DEFINE_MUTEX(percpu_charge_mutex);
2197 #ifdef CONFIG_MEMCG_KMEM
2198 static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock);
2199 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2200 struct mem_cgroup *root_memcg);
2201 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages);
2204 static inline struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock)
2208 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2209 struct mem_cgroup *root_memcg)
2213 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages)
2219 * consume_stock: Try to consume stocked charge on this cpu.
2220 * @memcg: memcg to consume from.
2221 * @nr_pages: how many pages to charge.
2223 * The charges will only happen if @memcg matches the current cpu's memcg
2224 * stock, and at least @nr_pages are available in that stock. Failure to
2225 * service an allocation will refill the stock.
2227 * returns true if successful, false otherwise.
2229 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2231 struct memcg_stock_pcp *stock;
2232 unsigned long flags;
2235 if (nr_pages > MEMCG_CHARGE_BATCH)
2238 local_lock_irqsave(&memcg_stock.stock_lock, flags);
2240 stock = this_cpu_ptr(&memcg_stock);
2241 if (memcg == stock->cached && stock->nr_pages >= nr_pages) {
2242 stock->nr_pages -= nr_pages;
2246 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2252 * Returns stocks cached in percpu and reset cached information.
2254 static void drain_stock(struct memcg_stock_pcp *stock)
2256 struct mem_cgroup *old = stock->cached;
2261 if (stock->nr_pages) {
2262 page_counter_uncharge(&old->memory, stock->nr_pages);
2263 if (do_memsw_account())
2264 page_counter_uncharge(&old->memsw, stock->nr_pages);
2265 stock->nr_pages = 0;
2269 stock->cached = NULL;
2272 static void drain_local_stock(struct work_struct *dummy)
2274 struct memcg_stock_pcp *stock;
2275 struct obj_cgroup *old = NULL;
2276 unsigned long flags;
2279 * The only protection from cpu hotplug (memcg_hotplug_cpu_dead) vs.
2280 * drain_stock races is that we always operate on local CPU stock
2281 * here with IRQ disabled
2283 local_lock_irqsave(&memcg_stock.stock_lock, flags);
2285 stock = this_cpu_ptr(&memcg_stock);
2286 old = drain_obj_stock(stock);
2288 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2290 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2292 obj_cgroup_put(old);
2296 * Cache charges(val) to local per_cpu area.
2297 * This will be consumed by consume_stock() function, later.
2299 static void __refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2301 struct memcg_stock_pcp *stock;
2303 stock = this_cpu_ptr(&memcg_stock);
2304 if (stock->cached != memcg) { /* reset if necessary */
2306 css_get(&memcg->css);
2307 stock->cached = memcg;
2309 stock->nr_pages += nr_pages;
2311 if (stock->nr_pages > MEMCG_CHARGE_BATCH)
2315 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2317 unsigned long flags;
2319 local_lock_irqsave(&memcg_stock.stock_lock, flags);
2320 __refill_stock(memcg, nr_pages);
2321 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2325 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2326 * of the hierarchy under it.
2328 static void drain_all_stock(struct mem_cgroup *root_memcg)
2332 /* If someone's already draining, avoid adding running more workers. */
2333 if (!mutex_trylock(&percpu_charge_mutex))
2336 * Notify other cpus that system-wide "drain" is running
2337 * We do not care about races with the cpu hotplug because cpu down
2338 * as well as workers from this path always operate on the local
2339 * per-cpu data. CPU up doesn't touch memcg_stock at all.
2342 curcpu = smp_processor_id();
2343 for_each_online_cpu(cpu) {
2344 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2345 struct mem_cgroup *memcg;
2349 memcg = stock->cached;
2350 if (memcg && stock->nr_pages &&
2351 mem_cgroup_is_descendant(memcg, root_memcg))
2353 else if (obj_stock_flush_required(stock, root_memcg))
2358 !test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2360 drain_local_stock(&stock->work);
2362 schedule_work_on(cpu, &stock->work);
2366 mutex_unlock(&percpu_charge_mutex);
2369 static int memcg_hotplug_cpu_dead(unsigned int cpu)
2371 struct memcg_stock_pcp *stock;
2373 stock = &per_cpu(memcg_stock, cpu);
2379 static unsigned long reclaim_high(struct mem_cgroup *memcg,
2380 unsigned int nr_pages,
2383 unsigned long nr_reclaimed = 0;
2386 unsigned long pflags;
2388 if (page_counter_read(&memcg->memory) <=
2389 READ_ONCE(memcg->memory.high))
2392 memcg_memory_event(memcg, MEMCG_HIGH);
2394 psi_memstall_enter(&pflags);
2395 nr_reclaimed += try_to_free_mem_cgroup_pages(memcg, nr_pages,
2397 MEMCG_RECLAIM_MAY_SWAP);
2398 psi_memstall_leave(&pflags);
2399 } while ((memcg = parent_mem_cgroup(memcg)) &&
2400 !mem_cgroup_is_root(memcg));
2402 return nr_reclaimed;
2405 static void high_work_func(struct work_struct *work)
2407 struct mem_cgroup *memcg;
2409 memcg = container_of(work, struct mem_cgroup, high_work);
2410 reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
2414 * Clamp the maximum sleep time per allocation batch to 2 seconds. This is
2415 * enough to still cause a significant slowdown in most cases, while still
2416 * allowing diagnostics and tracing to proceed without becoming stuck.
2418 #define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ)
2421 * When calculating the delay, we use these either side of the exponentiation to
2422 * maintain precision and scale to a reasonable number of jiffies (see the table
2425 * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the
2426 * overage ratio to a delay.
2427 * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down the
2428 * proposed penalty in order to reduce to a reasonable number of jiffies, and
2429 * to produce a reasonable delay curve.
2431 * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a
2432 * reasonable delay curve compared to precision-adjusted overage, not
2433 * penalising heavily at first, but still making sure that growth beyond the
2434 * limit penalises misbehaviour cgroups by slowing them down exponentially. For
2435 * example, with a high of 100 megabytes:
2437 * +-------+------------------------+
2438 * | usage | time to allocate in ms |
2439 * +-------+------------------------+
2461 * +-------+------------------------+
2463 #define MEMCG_DELAY_PRECISION_SHIFT 20
2464 #define MEMCG_DELAY_SCALING_SHIFT 14
2466 static u64 calculate_overage(unsigned long usage, unsigned long high)
2474 * Prevent division by 0 in overage calculation by acting as if
2475 * it was a threshold of 1 page
2477 high = max(high, 1UL);
2479 overage = usage - high;
2480 overage <<= MEMCG_DELAY_PRECISION_SHIFT;
2481 return div64_u64(overage, high);
2484 static u64 mem_find_max_overage(struct mem_cgroup *memcg)
2486 u64 overage, max_overage = 0;
2489 overage = calculate_overage(page_counter_read(&memcg->memory),
2490 READ_ONCE(memcg->memory.high));
2491 max_overage = max(overage, max_overage);
2492 } while ((memcg = parent_mem_cgroup(memcg)) &&
2493 !mem_cgroup_is_root(memcg));
2498 static u64 swap_find_max_overage(struct mem_cgroup *memcg)
2500 u64 overage, max_overage = 0;
2503 overage = calculate_overage(page_counter_read(&memcg->swap),
2504 READ_ONCE(memcg->swap.high));
2506 memcg_memory_event(memcg, MEMCG_SWAP_HIGH);
2507 max_overage = max(overage, max_overage);
2508 } while ((memcg = parent_mem_cgroup(memcg)) &&
2509 !mem_cgroup_is_root(memcg));
2515 * Get the number of jiffies that we should penalise a mischievous cgroup which
2516 * is exceeding its memory.high by checking both it and its ancestors.
2518 static unsigned long calculate_high_delay(struct mem_cgroup *memcg,
2519 unsigned int nr_pages,
2522 unsigned long penalty_jiffies;
2528 * We use overage compared to memory.high to calculate the number of
2529 * jiffies to sleep (penalty_jiffies). Ideally this value should be
2530 * fairly lenient on small overages, and increasingly harsh when the
2531 * memcg in question makes it clear that it has no intention of stopping
2532 * its crazy behaviour, so we exponentially increase the delay based on
2535 penalty_jiffies = max_overage * max_overage * HZ;
2536 penalty_jiffies >>= MEMCG_DELAY_PRECISION_SHIFT;
2537 penalty_jiffies >>= MEMCG_DELAY_SCALING_SHIFT;
2540 * Factor in the task's own contribution to the overage, such that four
2541 * N-sized allocations are throttled approximately the same as one
2542 * 4N-sized allocation.
2544 * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or
2545 * larger the current charge patch is than that.
2547 return penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH;
2551 * Scheduled by try_charge() to be executed from the userland return path
2552 * and reclaims memory over the high limit.
2554 void mem_cgroup_handle_over_high(void)
2556 unsigned long penalty_jiffies;
2557 unsigned long pflags;
2558 unsigned long nr_reclaimed;
2559 unsigned int nr_pages = current->memcg_nr_pages_over_high;
2560 int nr_retries = MAX_RECLAIM_RETRIES;
2561 struct mem_cgroup *memcg;
2562 bool in_retry = false;
2564 if (likely(!nr_pages))
2567 memcg = get_mem_cgroup_from_mm(current->mm);
2568 current->memcg_nr_pages_over_high = 0;
2572 * The allocating task should reclaim at least the batch size, but for
2573 * subsequent retries we only want to do what's necessary to prevent oom
2574 * or breaching resource isolation.
2576 * This is distinct from memory.max or page allocator behaviour because
2577 * memory.high is currently batched, whereas memory.max and the page
2578 * allocator run every time an allocation is made.
2580 nr_reclaimed = reclaim_high(memcg,
2581 in_retry ? SWAP_CLUSTER_MAX : nr_pages,
2585 * memory.high is breached and reclaim is unable to keep up. Throttle
2586 * allocators proactively to slow down excessive growth.
2588 penalty_jiffies = calculate_high_delay(memcg, nr_pages,
2589 mem_find_max_overage(memcg));
2591 penalty_jiffies += calculate_high_delay(memcg, nr_pages,
2592 swap_find_max_overage(memcg));
2595 * Clamp the max delay per usermode return so as to still keep the
2596 * application moving forwards and also permit diagnostics, albeit
2599 penalty_jiffies = min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES);
2602 * Don't sleep if the amount of jiffies this memcg owes us is so low
2603 * that it's not even worth doing, in an attempt to be nice to those who
2604 * go only a small amount over their memory.high value and maybe haven't
2605 * been aggressively reclaimed enough yet.
2607 if (penalty_jiffies <= HZ / 100)
2611 * If reclaim is making forward progress but we're still over
2612 * memory.high, we want to encourage that rather than doing allocator
2615 if (nr_reclaimed || nr_retries--) {
2621 * If we exit early, we're guaranteed to die (since
2622 * schedule_timeout_killable sets TASK_KILLABLE). This means we don't
2623 * need to account for any ill-begotten jiffies to pay them off later.
2625 psi_memstall_enter(&pflags);
2626 schedule_timeout_killable(penalty_jiffies);
2627 psi_memstall_leave(&pflags);
2630 css_put(&memcg->css);
2633 static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask,
2634 unsigned int nr_pages)
2636 unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
2637 int nr_retries = MAX_RECLAIM_RETRIES;
2638 struct mem_cgroup *mem_over_limit;
2639 struct page_counter *counter;
2640 unsigned long nr_reclaimed;
2641 bool passed_oom = false;
2642 unsigned int reclaim_options = MEMCG_RECLAIM_MAY_SWAP;
2643 bool drained = false;
2644 bool raised_max_event = false;
2645 unsigned long pflags;
2648 if (consume_stock(memcg, nr_pages))
2651 if (!do_memsw_account() ||
2652 page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2653 if (page_counter_try_charge(&memcg->memory, batch, &counter))
2655 if (do_memsw_account())
2656 page_counter_uncharge(&memcg->memsw, batch);
2657 mem_over_limit = mem_cgroup_from_counter(counter, memory);
2659 mem_over_limit = mem_cgroup_from_counter(counter, memsw);
2660 reclaim_options &= ~MEMCG_RECLAIM_MAY_SWAP;
2663 if (batch > nr_pages) {
2669 * Prevent unbounded recursion when reclaim operations need to
2670 * allocate memory. This might exceed the limits temporarily,
2671 * but we prefer facilitating memory reclaim and getting back
2672 * under the limit over triggering OOM kills in these cases.
2674 if (unlikely(current->flags & PF_MEMALLOC))
2677 if (unlikely(task_in_memcg_oom(current)))
2680 if (!gfpflags_allow_blocking(gfp_mask))
2683 memcg_memory_event(mem_over_limit, MEMCG_MAX);
2684 raised_max_event = true;
2686 psi_memstall_enter(&pflags);
2687 nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
2688 gfp_mask, reclaim_options);
2689 psi_memstall_leave(&pflags);
2691 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2695 drain_all_stock(mem_over_limit);
2700 if (gfp_mask & __GFP_NORETRY)
2703 * Even though the limit is exceeded at this point, reclaim
2704 * may have been able to free some pages. Retry the charge
2705 * before killing the task.
2707 * Only for regular pages, though: huge pages are rather
2708 * unlikely to succeed so close to the limit, and we fall back
2709 * to regular pages anyway in case of failure.
2711 if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
2714 * At task move, charge accounts can be doubly counted. So, it's
2715 * better to wait until the end of task_move if something is going on.
2717 if (mem_cgroup_wait_acct_move(mem_over_limit))
2723 if (gfp_mask & __GFP_RETRY_MAYFAIL)
2726 /* Avoid endless loop for tasks bypassed by the oom killer */
2727 if (passed_oom && task_is_dying())
2731 * keep retrying as long as the memcg oom killer is able to make
2732 * a forward progress or bypass the charge if the oom killer
2733 * couldn't make any progress.
2735 if (mem_cgroup_oom(mem_over_limit, gfp_mask,
2736 get_order(nr_pages * PAGE_SIZE))) {
2738 nr_retries = MAX_RECLAIM_RETRIES;
2743 * Memcg doesn't have a dedicated reserve for atomic
2744 * allocations. But like the global atomic pool, we need to
2745 * put the burden of reclaim on regular allocation requests
2746 * and let these go through as privileged allocations.
2748 if (!(gfp_mask & (__GFP_NOFAIL | __GFP_HIGH)))
2752 * If the allocation has to be enforced, don't forget to raise
2753 * a MEMCG_MAX event.
2755 if (!raised_max_event)
2756 memcg_memory_event(mem_over_limit, MEMCG_MAX);
2759 * The allocation either can't fail or will lead to more memory
2760 * being freed very soon. Allow memory usage go over the limit
2761 * temporarily by force charging it.
2763 page_counter_charge(&memcg->memory, nr_pages);
2764 if (do_memsw_account())
2765 page_counter_charge(&memcg->memsw, nr_pages);
2770 if (batch > nr_pages)
2771 refill_stock(memcg, batch - nr_pages);
2774 * If the hierarchy is above the normal consumption range, schedule
2775 * reclaim on returning to userland. We can perform reclaim here
2776 * if __GFP_RECLAIM but let's always punt for simplicity and so that
2777 * GFP_KERNEL can consistently be used during reclaim. @memcg is
2778 * not recorded as it most likely matches current's and won't
2779 * change in the meantime. As high limit is checked again before
2780 * reclaim, the cost of mismatch is negligible.
2783 bool mem_high, swap_high;
2785 mem_high = page_counter_read(&memcg->memory) >
2786 READ_ONCE(memcg->memory.high);
2787 swap_high = page_counter_read(&memcg->swap) >
2788 READ_ONCE(memcg->swap.high);
2790 /* Don't bother a random interrupted task */
2793 schedule_work(&memcg->high_work);
2799 if (mem_high || swap_high) {
2801 * The allocating tasks in this cgroup will need to do
2802 * reclaim or be throttled to prevent further growth
2803 * of the memory or swap footprints.
2805 * Target some best-effort fairness between the tasks,
2806 * and distribute reclaim work and delay penalties
2807 * based on how much each task is actually allocating.
2809 current->memcg_nr_pages_over_high += batch;
2810 set_notify_resume(current);
2813 } while ((memcg = parent_mem_cgroup(memcg)));
2815 if (current->memcg_nr_pages_over_high > MEMCG_CHARGE_BATCH &&
2816 !(current->flags & PF_MEMALLOC) &&
2817 gfpflags_allow_blocking(gfp_mask)) {
2818 mem_cgroup_handle_over_high();
2823 static inline int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2824 unsigned int nr_pages)
2826 if (mem_cgroup_is_root(memcg))
2829 return try_charge_memcg(memcg, gfp_mask, nr_pages);
2832 static inline void cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
2834 if (mem_cgroup_is_root(memcg))
2837 page_counter_uncharge(&memcg->memory, nr_pages);
2838 if (do_memsw_account())
2839 page_counter_uncharge(&memcg->memsw, nr_pages);
2842 static void commit_charge(struct folio *folio, struct mem_cgroup *memcg)
2844 VM_BUG_ON_FOLIO(folio_memcg(folio), folio);
2846 * Any of the following ensures page's memcg stability:
2850 * - lock_page_memcg()
2851 * - exclusive reference
2852 * - mem_cgroup_trylock_pages()
2854 folio->memcg_data = (unsigned long)memcg;
2857 #ifdef CONFIG_MEMCG_KMEM
2859 * The allocated objcg pointers array is not accounted directly.
2860 * Moreover, it should not come from DMA buffer and is not readily
2861 * reclaimable. So those GFP bits should be masked off.
2863 #define OBJCGS_CLEAR_MASK (__GFP_DMA | __GFP_RECLAIMABLE | __GFP_ACCOUNT)
2866 * mod_objcg_mlstate() may be called with irq enabled, so
2867 * mod_memcg_lruvec_state() should be used.
2869 static inline void mod_objcg_mlstate(struct obj_cgroup *objcg,
2870 struct pglist_data *pgdat,
2871 enum node_stat_item idx, int nr)
2873 struct mem_cgroup *memcg;
2874 struct lruvec *lruvec;
2877 memcg = obj_cgroup_memcg(objcg);
2878 lruvec = mem_cgroup_lruvec(memcg, pgdat);
2879 mod_memcg_lruvec_state(lruvec, idx, nr);
2883 int memcg_alloc_slab_cgroups(struct slab *slab, struct kmem_cache *s,
2884 gfp_t gfp, bool new_slab)
2886 unsigned int objects = objs_per_slab(s, slab);
2887 unsigned long memcg_data;
2890 gfp &= ~OBJCGS_CLEAR_MASK;
2891 vec = kcalloc_node(objects, sizeof(struct obj_cgroup *), gfp,
2896 memcg_data = (unsigned long) vec | MEMCG_DATA_OBJCGS;
2899 * If the slab is brand new and nobody can yet access its
2900 * memcg_data, no synchronization is required and memcg_data can
2901 * be simply assigned.
2903 slab->memcg_data = memcg_data;
2904 } else if (cmpxchg(&slab->memcg_data, 0, memcg_data)) {
2906 * If the slab is already in use, somebody can allocate and
2907 * assign obj_cgroups in parallel. In this case the existing
2908 * objcg vector should be reused.
2914 kmemleak_not_leak(vec);
2918 static __always_inline
2919 struct mem_cgroup *mem_cgroup_from_obj_folio(struct folio *folio, void *p)
2922 * Slab objects are accounted individually, not per-page.
2923 * Memcg membership data for each individual object is saved in
2926 if (folio_test_slab(folio)) {
2927 struct obj_cgroup **objcgs;
2931 slab = folio_slab(folio);
2932 objcgs = slab_objcgs(slab);
2936 off = obj_to_index(slab->slab_cache, slab, p);
2938 return obj_cgroup_memcg(objcgs[off]);
2944 * page_memcg_check() is used here, because in theory we can encounter
2945 * a folio where the slab flag has been cleared already, but
2946 * slab->memcg_data has not been freed yet
2947 * page_memcg_check(page) will guarantee that a proper memory
2948 * cgroup pointer or NULL will be returned.
2950 return page_memcg_check(folio_page(folio, 0));
2954 * Returns a pointer to the memory cgroup to which the kernel object is charged.
2956 * A passed kernel object can be a slab object, vmalloc object or a generic
2957 * kernel page, so different mechanisms for getting the memory cgroup pointer
2960 * In certain cases (e.g. kernel stacks or large kmallocs with SLUB) the caller
2961 * can not know for sure how the kernel object is implemented.
2962 * mem_cgroup_from_obj() can be safely used in such cases.
2964 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
2965 * cgroup_mutex, etc.
2967 struct mem_cgroup *mem_cgroup_from_obj(void *p)
2969 struct folio *folio;
2971 if (mem_cgroup_disabled())
2974 if (unlikely(is_vmalloc_addr(p)))
2975 folio = page_folio(vmalloc_to_page(p));
2977 folio = virt_to_folio(p);
2979 return mem_cgroup_from_obj_folio(folio, p);
2983 * Returns a pointer to the memory cgroup to which the kernel object is charged.
2984 * Similar to mem_cgroup_from_obj(), but faster and not suitable for objects,
2985 * allocated using vmalloc().
2987 * A passed kernel object must be a slab object or a generic kernel page.
2989 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
2990 * cgroup_mutex, etc.
2992 struct mem_cgroup *mem_cgroup_from_slab_obj(void *p)
2994 if (mem_cgroup_disabled())
2997 return mem_cgroup_from_obj_folio(virt_to_folio(p), p);
3000 static struct obj_cgroup *__get_obj_cgroup_from_memcg(struct mem_cgroup *memcg)
3002 struct obj_cgroup *objcg = NULL;
3004 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg)) {
3005 objcg = rcu_dereference(memcg->objcg);
3006 if (objcg && obj_cgroup_tryget(objcg))
3013 __always_inline struct obj_cgroup *get_obj_cgroup_from_current(void)
3015 struct obj_cgroup *objcg = NULL;
3016 struct mem_cgroup *memcg;
3018 if (memcg_kmem_bypass())
3022 if (unlikely(active_memcg()))
3023 memcg = active_memcg();
3025 memcg = mem_cgroup_from_task(current);
3026 objcg = __get_obj_cgroup_from_memcg(memcg);
3031 struct obj_cgroup *get_obj_cgroup_from_page(struct page *page)
3033 struct obj_cgroup *objcg;
3035 if (!memcg_kmem_enabled() || memcg_kmem_bypass())
3038 if (PageMemcgKmem(page)) {
3039 objcg = __folio_objcg(page_folio(page));
3040 obj_cgroup_get(objcg);
3042 struct mem_cgroup *memcg;
3045 memcg = __folio_memcg(page_folio(page));
3047 objcg = __get_obj_cgroup_from_memcg(memcg);
3055 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages)
3057 mod_memcg_state(memcg, MEMCG_KMEM, nr_pages);
3058 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
3060 page_counter_charge(&memcg->kmem, nr_pages);
3062 page_counter_uncharge(&memcg->kmem, -nr_pages);
3068 * obj_cgroup_uncharge_pages: uncharge a number of kernel pages from a objcg
3069 * @objcg: object cgroup to uncharge
3070 * @nr_pages: number of pages to uncharge
3072 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
3073 unsigned int nr_pages)
3075 struct mem_cgroup *memcg;
3077 memcg = get_mem_cgroup_from_objcg(objcg);
3079 memcg_account_kmem(memcg, -nr_pages);
3080 refill_stock(memcg, nr_pages);
3082 css_put(&memcg->css);
3086 * obj_cgroup_charge_pages: charge a number of kernel pages to a objcg
3087 * @objcg: object cgroup to charge
3088 * @gfp: reclaim mode
3089 * @nr_pages: number of pages to charge
3091 * Returns 0 on success, an error code on failure.
3093 static int obj_cgroup_charge_pages(struct obj_cgroup *objcg, gfp_t gfp,
3094 unsigned int nr_pages)
3096 struct mem_cgroup *memcg;
3099 memcg = get_mem_cgroup_from_objcg(objcg);
3101 ret = try_charge_memcg(memcg, gfp, nr_pages);
3105 memcg_account_kmem(memcg, nr_pages);
3107 css_put(&memcg->css);
3113 * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup
3114 * @page: page to charge
3115 * @gfp: reclaim mode
3116 * @order: allocation order
3118 * Returns 0 on success, an error code on failure.
3120 int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
3122 struct obj_cgroup *objcg;
3125 objcg = get_obj_cgroup_from_current();
3127 ret = obj_cgroup_charge_pages(objcg, gfp, 1 << order);
3129 page->memcg_data = (unsigned long)objcg |
3133 obj_cgroup_put(objcg);
3139 * __memcg_kmem_uncharge_page: uncharge a kmem page
3140 * @page: page to uncharge
3141 * @order: allocation order
3143 void __memcg_kmem_uncharge_page(struct page *page, int order)
3145 struct folio *folio = page_folio(page);
3146 struct obj_cgroup *objcg;
3147 unsigned int nr_pages = 1 << order;
3149 if (!folio_memcg_kmem(folio))
3152 objcg = __folio_objcg(folio);
3153 obj_cgroup_uncharge_pages(objcg, nr_pages);
3154 folio->memcg_data = 0;
3155 obj_cgroup_put(objcg);
3158 void mod_objcg_state(struct obj_cgroup *objcg, struct pglist_data *pgdat,
3159 enum node_stat_item idx, int nr)
3161 struct memcg_stock_pcp *stock;
3162 struct obj_cgroup *old = NULL;
3163 unsigned long flags;
3166 local_lock_irqsave(&memcg_stock.stock_lock, flags);
3167 stock = this_cpu_ptr(&memcg_stock);
3170 * Save vmstat data in stock and skip vmstat array update unless
3171 * accumulating over a page of vmstat data or when pgdat or idx
3174 if (stock->cached_objcg != objcg) {
3175 old = drain_obj_stock(stock);
3176 obj_cgroup_get(objcg);
3177 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3178 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3179 stock->cached_objcg = objcg;
3180 stock->cached_pgdat = pgdat;
3181 } else if (stock->cached_pgdat != pgdat) {
3182 /* Flush the existing cached vmstat data */
3183 struct pglist_data *oldpg = stock->cached_pgdat;
3185 if (stock->nr_slab_reclaimable_b) {
3186 mod_objcg_mlstate(objcg, oldpg, NR_SLAB_RECLAIMABLE_B,
3187 stock->nr_slab_reclaimable_b);
3188 stock->nr_slab_reclaimable_b = 0;
3190 if (stock->nr_slab_unreclaimable_b) {
3191 mod_objcg_mlstate(objcg, oldpg, NR_SLAB_UNRECLAIMABLE_B,
3192 stock->nr_slab_unreclaimable_b);
3193 stock->nr_slab_unreclaimable_b = 0;
3195 stock->cached_pgdat = pgdat;
3198 bytes = (idx == NR_SLAB_RECLAIMABLE_B) ? &stock->nr_slab_reclaimable_b
3199 : &stock->nr_slab_unreclaimable_b;
3201 * Even for large object >= PAGE_SIZE, the vmstat data will still be
3202 * cached locally at least once before pushing it out.
3209 if (abs(*bytes) > PAGE_SIZE) {
3217 mod_objcg_mlstate(objcg, pgdat, idx, nr);
3219 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3221 obj_cgroup_put(old);
3224 static bool consume_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes)
3226 struct memcg_stock_pcp *stock;
3227 unsigned long flags;
3230 local_lock_irqsave(&memcg_stock.stock_lock, flags);
3232 stock = this_cpu_ptr(&memcg_stock);
3233 if (objcg == stock->cached_objcg && stock->nr_bytes >= nr_bytes) {
3234 stock->nr_bytes -= nr_bytes;
3238 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3243 static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock)
3245 struct obj_cgroup *old = stock->cached_objcg;
3250 if (stock->nr_bytes) {
3251 unsigned int nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3252 unsigned int nr_bytes = stock->nr_bytes & (PAGE_SIZE - 1);
3255 struct mem_cgroup *memcg;
3257 memcg = get_mem_cgroup_from_objcg(old);
3259 memcg_account_kmem(memcg, -nr_pages);
3260 __refill_stock(memcg, nr_pages);
3262 css_put(&memcg->css);
3266 * The leftover is flushed to the centralized per-memcg value.
3267 * On the next attempt to refill obj stock it will be moved
3268 * to a per-cpu stock (probably, on an other CPU), see
3269 * refill_obj_stock().
3271 * How often it's flushed is a trade-off between the memory
3272 * limit enforcement accuracy and potential CPU contention,
3273 * so it might be changed in the future.
3275 atomic_add(nr_bytes, &old->nr_charged_bytes);
3276 stock->nr_bytes = 0;
3280 * Flush the vmstat data in current stock
3282 if (stock->nr_slab_reclaimable_b || stock->nr_slab_unreclaimable_b) {
3283 if (stock->nr_slab_reclaimable_b) {
3284 mod_objcg_mlstate(old, stock->cached_pgdat,
3285 NR_SLAB_RECLAIMABLE_B,
3286 stock->nr_slab_reclaimable_b);
3287 stock->nr_slab_reclaimable_b = 0;
3289 if (stock->nr_slab_unreclaimable_b) {
3290 mod_objcg_mlstate(old, stock->cached_pgdat,
3291 NR_SLAB_UNRECLAIMABLE_B,
3292 stock->nr_slab_unreclaimable_b);
3293 stock->nr_slab_unreclaimable_b = 0;
3295 stock->cached_pgdat = NULL;
3298 stock->cached_objcg = NULL;
3300 * The `old' objects needs to be released by the caller via
3301 * obj_cgroup_put() outside of memcg_stock_pcp::stock_lock.
3306 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
3307 struct mem_cgroup *root_memcg)
3309 struct mem_cgroup *memcg;
3311 if (stock->cached_objcg) {
3312 memcg = obj_cgroup_memcg(stock->cached_objcg);
3313 if (memcg && mem_cgroup_is_descendant(memcg, root_memcg))
3320 static void refill_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes,
3321 bool allow_uncharge)
3323 struct memcg_stock_pcp *stock;
3324 struct obj_cgroup *old = NULL;
3325 unsigned long flags;
3326 unsigned int nr_pages = 0;
3328 local_lock_irqsave(&memcg_stock.stock_lock, flags);
3330 stock = this_cpu_ptr(&memcg_stock);
3331 if (stock->cached_objcg != objcg) { /* reset if necessary */
3332 old = drain_obj_stock(stock);
3333 obj_cgroup_get(objcg);
3334 stock->cached_objcg = objcg;
3335 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3336 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3337 allow_uncharge = true; /* Allow uncharge when objcg changes */
3339 stock->nr_bytes += nr_bytes;
3341 if (allow_uncharge && (stock->nr_bytes > PAGE_SIZE)) {
3342 nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3343 stock->nr_bytes &= (PAGE_SIZE - 1);
3346 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3348 obj_cgroup_put(old);
3351 obj_cgroup_uncharge_pages(objcg, nr_pages);
3354 int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size)
3356 unsigned int nr_pages, nr_bytes;
3359 if (consume_obj_stock(objcg, size))
3363 * In theory, objcg->nr_charged_bytes can have enough
3364 * pre-charged bytes to satisfy the allocation. However,
3365 * flushing objcg->nr_charged_bytes requires two atomic
3366 * operations, and objcg->nr_charged_bytes can't be big.
3367 * The shared objcg->nr_charged_bytes can also become a
3368 * performance bottleneck if all tasks of the same memcg are
3369 * trying to update it. So it's better to ignore it and try
3370 * grab some new pages. The stock's nr_bytes will be flushed to
3371 * objcg->nr_charged_bytes later on when objcg changes.
3373 * The stock's nr_bytes may contain enough pre-charged bytes
3374 * to allow one less page from being charged, but we can't rely
3375 * on the pre-charged bytes not being changed outside of
3376 * consume_obj_stock() or refill_obj_stock(). So ignore those
3377 * pre-charged bytes as well when charging pages. To avoid a
3378 * page uncharge right after a page charge, we set the
3379 * allow_uncharge flag to false when calling refill_obj_stock()
3380 * to temporarily allow the pre-charged bytes to exceed the page
3381 * size limit. The maximum reachable value of the pre-charged
3382 * bytes is (sizeof(object) + PAGE_SIZE - 2) if there is no data
3385 nr_pages = size >> PAGE_SHIFT;
3386 nr_bytes = size & (PAGE_SIZE - 1);
3391 ret = obj_cgroup_charge_pages(objcg, gfp, nr_pages);
3392 if (!ret && nr_bytes)
3393 refill_obj_stock(objcg, PAGE_SIZE - nr_bytes, false);
3398 void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size)
3400 refill_obj_stock(objcg, size, true);
3403 #endif /* CONFIG_MEMCG_KMEM */
3406 * Because page_memcg(head) is not set on tails, set it now.
3408 void split_page_memcg(struct page *head, unsigned int nr)
3410 struct folio *folio = page_folio(head);
3411 struct mem_cgroup *memcg = folio_memcg(folio);
3414 if (mem_cgroup_disabled() || !memcg)
3417 for (i = 1; i < nr; i++)
3418 folio_page(folio, i)->memcg_data = folio->memcg_data;
3420 if (folio_memcg_kmem(folio))
3421 obj_cgroup_get_many(__folio_objcg(folio), nr - 1);
3423 css_get_many(&memcg->css, nr - 1);
3428 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3429 * @entry: swap entry to be moved
3430 * @from: mem_cgroup which the entry is moved from
3431 * @to: mem_cgroup which the entry is moved to
3433 * It succeeds only when the swap_cgroup's record for this entry is the same
3434 * as the mem_cgroup's id of @from.
3436 * Returns 0 on success, -EINVAL on failure.
3438 * The caller must have charged to @to, IOW, called page_counter_charge() about
3439 * both res and memsw, and called css_get().
3441 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3442 struct mem_cgroup *from, struct mem_cgroup *to)
3444 unsigned short old_id, new_id;
3446 old_id = mem_cgroup_id(from);
3447 new_id = mem_cgroup_id(to);
3449 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3450 mod_memcg_state(from, MEMCG_SWAP, -1);
3451 mod_memcg_state(to, MEMCG_SWAP, 1);
3457 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3458 struct mem_cgroup *from, struct mem_cgroup *to)
3464 static DEFINE_MUTEX(memcg_max_mutex);
3466 static int mem_cgroup_resize_max(struct mem_cgroup *memcg,
3467 unsigned long max, bool memsw)
3469 bool enlarge = false;
3470 bool drained = false;
3472 bool limits_invariant;
3473 struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory;
3476 if (signal_pending(current)) {
3481 mutex_lock(&memcg_max_mutex);
3483 * Make sure that the new limit (memsw or memory limit) doesn't
3484 * break our basic invariant rule memory.max <= memsw.max.
3486 limits_invariant = memsw ? max >= READ_ONCE(memcg->memory.max) :
3487 max <= memcg->memsw.max;
3488 if (!limits_invariant) {
3489 mutex_unlock(&memcg_max_mutex);
3493 if (max > counter->max)
3495 ret = page_counter_set_max(counter, max);
3496 mutex_unlock(&memcg_max_mutex);
3502 drain_all_stock(memcg);
3507 if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,
3508 memsw ? 0 : MEMCG_RECLAIM_MAY_SWAP)) {
3514 if (!ret && enlarge)
3515 memcg_oom_recover(memcg);
3520 unsigned long mem_cgroup_soft_limit_reclaim(pg_data_t *pgdat, int order,
3522 unsigned long *total_scanned)
3524 unsigned long nr_reclaimed = 0;
3525 struct mem_cgroup_per_node *mz, *next_mz = NULL;
3526 unsigned long reclaimed;
3528 struct mem_cgroup_tree_per_node *mctz;
3529 unsigned long excess;
3534 mctz = soft_limit_tree.rb_tree_per_node[pgdat->node_id];
3537 * Do not even bother to check the largest node if the root
3538 * is empty. Do it lockless to prevent lock bouncing. Races
3539 * are acceptable as soft limit is best effort anyway.
3541 if (!mctz || RB_EMPTY_ROOT(&mctz->rb_root))
3545 * This loop can run a while, specially if mem_cgroup's continuously
3546 * keep exceeding their soft limit and putting the system under
3553 mz = mem_cgroup_largest_soft_limit_node(mctz);
3557 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, pgdat,
3558 gfp_mask, total_scanned);
3559 nr_reclaimed += reclaimed;
3560 spin_lock_irq(&mctz->lock);
3563 * If we failed to reclaim anything from this memory cgroup
3564 * it is time to move on to the next cgroup
3568 next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
3570 excess = soft_limit_excess(mz->memcg);
3572 * One school of thought says that we should not add
3573 * back the node to the tree if reclaim returns 0.
3574 * But our reclaim could return 0, simply because due
3575 * to priority we are exposing a smaller subset of
3576 * memory to reclaim from. Consider this as a longer
3579 /* If excess == 0, no tree ops */
3580 __mem_cgroup_insert_exceeded(mz, mctz, excess);
3581 spin_unlock_irq(&mctz->lock);
3582 css_put(&mz->memcg->css);
3585 * Could not reclaim anything and there are no more
3586 * mem cgroups to try or we seem to be looping without
3587 * reclaiming anything.
3589 if (!nr_reclaimed &&
3591 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3593 } while (!nr_reclaimed);
3595 css_put(&next_mz->memcg->css);
3596 return nr_reclaimed;
3600 * Reclaims as many pages from the given memcg as possible.
3602 * Caller is responsible for holding css reference for memcg.
3604 static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
3606 int nr_retries = MAX_RECLAIM_RETRIES;
3608 /* we call try-to-free pages for make this cgroup empty */
3609 lru_add_drain_all();
3611 drain_all_stock(memcg);
3613 /* try to free all pages in this cgroup */
3614 while (nr_retries && page_counter_read(&memcg->memory)) {
3615 if (signal_pending(current))
3618 if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,
3619 MEMCG_RECLAIM_MAY_SWAP))
3626 static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
3627 char *buf, size_t nbytes,
3630 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3632 if (mem_cgroup_is_root(memcg))
3634 return mem_cgroup_force_empty(memcg) ?: nbytes;
3637 static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
3643 static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
3644 struct cftype *cft, u64 val)
3649 pr_warn_once("Non-hierarchical mode is deprecated. "
3650 "Please report your usecase to linux-mm@kvack.org if you "
3651 "depend on this functionality.\n");
3656 static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3660 if (mem_cgroup_is_root(memcg)) {
3661 mem_cgroup_flush_stats();
3662 val = memcg_page_state(memcg, NR_FILE_PAGES) +
3663 memcg_page_state(memcg, NR_ANON_MAPPED);
3665 val += memcg_page_state(memcg, MEMCG_SWAP);
3668 val = page_counter_read(&memcg->memory);
3670 val = page_counter_read(&memcg->memsw);
3683 static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
3686 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3687 struct page_counter *counter;
3689 switch (MEMFILE_TYPE(cft->private)) {
3691 counter = &memcg->memory;
3694 counter = &memcg->memsw;
3697 counter = &memcg->kmem;
3700 counter = &memcg->tcpmem;
3706 switch (MEMFILE_ATTR(cft->private)) {
3708 if (counter == &memcg->memory)
3709 return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
3710 if (counter == &memcg->memsw)
3711 return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
3712 return (u64)page_counter_read(counter) * PAGE_SIZE;
3714 return (u64)counter->max * PAGE_SIZE;
3716 return (u64)counter->watermark * PAGE_SIZE;
3718 return counter->failcnt;
3719 case RES_SOFT_LIMIT:
3720 return (u64)memcg->soft_limit * PAGE_SIZE;
3726 #ifdef CONFIG_MEMCG_KMEM
3727 static int memcg_online_kmem(struct mem_cgroup *memcg)
3729 struct obj_cgroup *objcg;
3731 if (mem_cgroup_kmem_disabled())
3734 if (unlikely(mem_cgroup_is_root(memcg)))
3737 objcg = obj_cgroup_alloc();
3741 objcg->memcg = memcg;
3742 rcu_assign_pointer(memcg->objcg, objcg);
3744 static_branch_enable(&memcg_kmem_enabled_key);
3746 memcg->kmemcg_id = memcg->id.id;
3751 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3753 struct mem_cgroup *parent;
3755 if (mem_cgroup_kmem_disabled())
3758 if (unlikely(mem_cgroup_is_root(memcg)))
3761 parent = parent_mem_cgroup(memcg);
3763 parent = root_mem_cgroup;
3765 memcg_reparent_objcgs(memcg, parent);
3768 * After we have finished memcg_reparent_objcgs(), all list_lrus
3769 * corresponding to this cgroup are guaranteed to remain empty.
3770 * The ordering is imposed by list_lru_node->lock taken by
3771 * memcg_reparent_list_lrus().
3773 memcg_reparent_list_lrus(memcg, parent);
3776 static int memcg_online_kmem(struct mem_cgroup *memcg)
3780 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3783 #endif /* CONFIG_MEMCG_KMEM */
3785 static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max)
3789 mutex_lock(&memcg_max_mutex);
3791 ret = page_counter_set_max(&memcg->tcpmem, max);
3795 if (!memcg->tcpmem_active) {
3797 * The active flag needs to be written after the static_key
3798 * update. This is what guarantees that the socket activation
3799 * function is the last one to run. See mem_cgroup_sk_alloc()
3800 * for details, and note that we don't mark any socket as
3801 * belonging to this memcg until that flag is up.
3803 * We need to do this, because static_keys will span multiple
3804 * sites, but we can't control their order. If we mark a socket
3805 * as accounted, but the accounting functions are not patched in
3806 * yet, we'll lose accounting.
3808 * We never race with the readers in mem_cgroup_sk_alloc(),
3809 * because when this value change, the code to process it is not
3812 static_branch_inc(&memcg_sockets_enabled_key);
3813 memcg->tcpmem_active = true;
3816 mutex_unlock(&memcg_max_mutex);
3821 * The user of this function is...
3824 static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
3825 char *buf, size_t nbytes, loff_t off)
3827 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3828 unsigned long nr_pages;
3831 buf = strstrip(buf);
3832 ret = page_counter_memparse(buf, "-1", &nr_pages);
3836 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3838 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3842 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3844 ret = mem_cgroup_resize_max(memcg, nr_pages, false);
3847 ret = mem_cgroup_resize_max(memcg, nr_pages, true);
3850 /* kmem.limit_in_bytes is deprecated. */
3854 ret = memcg_update_tcp_max(memcg, nr_pages);
3858 case RES_SOFT_LIMIT:
3859 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
3862 memcg->soft_limit = nr_pages;
3867 return ret ?: nbytes;
3870 static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
3871 size_t nbytes, loff_t off)
3873 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3874 struct page_counter *counter;
3876 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3878 counter = &memcg->memory;
3881 counter = &memcg->memsw;
3884 counter = &memcg->kmem;
3887 counter = &memcg->tcpmem;
3893 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3895 page_counter_reset_watermark(counter);
3898 counter->failcnt = 0;
3907 static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
3910 return mem_cgroup_from_css(css)->move_charge_at_immigrate;
3914 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3915 struct cftype *cft, u64 val)
3917 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3919 if (val & ~MOVE_MASK)
3923 * No kind of locking is needed in here, because ->can_attach() will
3924 * check this value once in the beginning of the process, and then carry
3925 * on with stale data. This means that changes to this value will only
3926 * affect task migrations starting after the change.
3928 memcg->move_charge_at_immigrate = val;
3932 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3933 struct cftype *cft, u64 val)
3941 #define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE))
3942 #define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON))
3943 #define LRU_ALL ((1 << NR_LRU_LISTS) - 1)
3945 static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
3946 int nid, unsigned int lru_mask, bool tree)
3948 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
3949 unsigned long nr = 0;
3952 VM_BUG_ON((unsigned)nid >= nr_node_ids);
3955 if (!(BIT(lru) & lru_mask))
3958 nr += lruvec_page_state(lruvec, NR_LRU_BASE + lru);
3960 nr += lruvec_page_state_local(lruvec, NR_LRU_BASE + lru);
3965 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
3966 unsigned int lru_mask,
3969 unsigned long nr = 0;
3973 if (!(BIT(lru) & lru_mask))
3976 nr += memcg_page_state(memcg, NR_LRU_BASE + lru);
3978 nr += memcg_page_state_local(memcg, NR_LRU_BASE + lru);
3983 static int memcg_numa_stat_show(struct seq_file *m, void *v)
3987 unsigned int lru_mask;
3990 static const struct numa_stat stats[] = {
3991 { "total", LRU_ALL },
3992 { "file", LRU_ALL_FILE },
3993 { "anon", LRU_ALL_ANON },
3994 { "unevictable", BIT(LRU_UNEVICTABLE) },
3996 const struct numa_stat *stat;
3998 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
4000 mem_cgroup_flush_stats();
4002 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
4003 seq_printf(m, "%s=%lu", stat->name,
4004 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
4006 for_each_node_state(nid, N_MEMORY)
4007 seq_printf(m, " N%d=%lu", nid,
4008 mem_cgroup_node_nr_lru_pages(memcg, nid,
4009 stat->lru_mask, false));
4013 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
4015 seq_printf(m, "hierarchical_%s=%lu", stat->name,
4016 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
4018 for_each_node_state(nid, N_MEMORY)
4019 seq_printf(m, " N%d=%lu", nid,
4020 mem_cgroup_node_nr_lru_pages(memcg, nid,
4021 stat->lru_mask, true));
4027 #endif /* CONFIG_NUMA */
4029 static const unsigned int memcg1_stats[] = {
4032 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4039 WORKINGSET_REFAULT_ANON,
4040 WORKINGSET_REFAULT_FILE,
4044 static const char *const memcg1_stat_names[] = {
4047 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4054 "workingset_refault_anon",
4055 "workingset_refault_file",
4059 /* Universal VM events cgroup1 shows, original sort order */
4060 static const unsigned int memcg1_events[] = {
4067 static int memcg_stat_show(struct seq_file *m, void *v)
4069 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
4070 unsigned long memory, memsw;
4071 struct mem_cgroup *mi;
4074 BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats));
4076 mem_cgroup_flush_stats();
4078 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
4081 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
4083 nr = memcg_page_state_local(memcg, memcg1_stats[i]);
4084 seq_printf(m, "%s %lu\n", memcg1_stat_names[i],
4085 nr * memcg_page_state_unit(memcg1_stats[i]));
4088 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
4089 seq_printf(m, "%s %lu\n", vm_event_name(memcg1_events[i]),
4090 memcg_events_local(memcg, memcg1_events[i]));
4092 for (i = 0; i < NR_LRU_LISTS; i++)
4093 seq_printf(m, "%s %lu\n", lru_list_name(i),
4094 memcg_page_state_local(memcg, NR_LRU_BASE + i) *
4097 /* Hierarchical information */
4098 memory = memsw = PAGE_COUNTER_MAX;
4099 for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
4100 memory = min(memory, READ_ONCE(mi->memory.max));
4101 memsw = min(memsw, READ_ONCE(mi->memsw.max));
4103 seq_printf(m, "hierarchical_memory_limit %llu\n",
4104 (u64)memory * PAGE_SIZE);
4105 if (do_memsw_account())
4106 seq_printf(m, "hierarchical_memsw_limit %llu\n",
4107 (u64)memsw * PAGE_SIZE);
4109 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
4112 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
4114 nr = memcg_page_state(memcg, memcg1_stats[i]);
4115 seq_printf(m, "total_%s %llu\n", memcg1_stat_names[i],
4116 (u64)nr * memcg_page_state_unit(memcg1_stats[i]));
4119 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
4120 seq_printf(m, "total_%s %llu\n",
4121 vm_event_name(memcg1_events[i]),
4122 (u64)memcg_events(memcg, memcg1_events[i]));
4124 for (i = 0; i < NR_LRU_LISTS; i++)
4125 seq_printf(m, "total_%s %llu\n", lru_list_name(i),
4126 (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
4129 #ifdef CONFIG_DEBUG_VM
4132 struct mem_cgroup_per_node *mz;
4133 unsigned long anon_cost = 0;
4134 unsigned long file_cost = 0;
4136 for_each_online_pgdat(pgdat) {
4137 mz = memcg->nodeinfo[pgdat->node_id];
4139 anon_cost += mz->lruvec.anon_cost;
4140 file_cost += mz->lruvec.file_cost;
4142 seq_printf(m, "anon_cost %lu\n", anon_cost);
4143 seq_printf(m, "file_cost %lu\n", file_cost);
4150 static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
4153 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4155 return mem_cgroup_swappiness(memcg);
4158 static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
4159 struct cftype *cft, u64 val)
4161 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4166 if (!mem_cgroup_is_root(memcg))
4167 memcg->swappiness = val;
4169 vm_swappiness = val;
4174 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4176 struct mem_cgroup_threshold_ary *t;
4177 unsigned long usage;
4182 t = rcu_dereference(memcg->thresholds.primary);
4184 t = rcu_dereference(memcg->memsw_thresholds.primary);
4189 usage = mem_cgroup_usage(memcg, swap);
4192 * current_threshold points to threshold just below or equal to usage.
4193 * If it's not true, a threshold was crossed after last
4194 * call of __mem_cgroup_threshold().
4196 i = t->current_threshold;
4199 * Iterate backward over array of thresholds starting from
4200 * current_threshold and check if a threshold is crossed.
4201 * If none of thresholds below usage is crossed, we read
4202 * only one element of the array here.
4204 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4205 eventfd_signal(t->entries[i].eventfd, 1);
4207 /* i = current_threshold + 1 */
4211 * Iterate forward over array of thresholds starting from
4212 * current_threshold+1 and check if a threshold is crossed.
4213 * If none of thresholds above usage is crossed, we read
4214 * only one element of the array here.
4216 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4217 eventfd_signal(t->entries[i].eventfd, 1);
4219 /* Update current_threshold */
4220 t->current_threshold = i - 1;
4225 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4228 __mem_cgroup_threshold(memcg, false);
4229 if (do_memsw_account())
4230 __mem_cgroup_threshold(memcg, true);
4232 memcg = parent_mem_cgroup(memcg);
4236 static int compare_thresholds(const void *a, const void *b)
4238 const struct mem_cgroup_threshold *_a = a;
4239 const struct mem_cgroup_threshold *_b = b;
4241 if (_a->threshold > _b->threshold)
4244 if (_a->threshold < _b->threshold)
4250 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
4252 struct mem_cgroup_eventfd_list *ev;
4254 spin_lock(&memcg_oom_lock);
4256 list_for_each_entry(ev, &memcg->oom_notify, list)
4257 eventfd_signal(ev->eventfd, 1);
4259 spin_unlock(&memcg_oom_lock);
4263 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
4265 struct mem_cgroup *iter;
4267 for_each_mem_cgroup_tree(iter, memcg)
4268 mem_cgroup_oom_notify_cb(iter);
4271 static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4272 struct eventfd_ctx *eventfd, const char *args, enum res_type type)
4274 struct mem_cgroup_thresholds *thresholds;
4275 struct mem_cgroup_threshold_ary *new;
4276 unsigned long threshold;
4277 unsigned long usage;
4280 ret = page_counter_memparse(args, "-1", &threshold);
4284 mutex_lock(&memcg->thresholds_lock);
4287 thresholds = &memcg->thresholds;
4288 usage = mem_cgroup_usage(memcg, false);
4289 } else if (type == _MEMSWAP) {
4290 thresholds = &memcg->memsw_thresholds;
4291 usage = mem_cgroup_usage(memcg, true);
4295 /* Check if a threshold crossed before adding a new one */
4296 if (thresholds->primary)
4297 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4299 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4301 /* Allocate memory for new array of thresholds */
4302 new = kmalloc(struct_size(new, entries, size), GFP_KERNEL);
4309 /* Copy thresholds (if any) to new array */
4310 if (thresholds->primary)
4311 memcpy(new->entries, thresholds->primary->entries,
4312 flex_array_size(new, entries, size - 1));
4314 /* Add new threshold */
4315 new->entries[size - 1].eventfd = eventfd;
4316 new->entries[size - 1].threshold = threshold;
4318 /* Sort thresholds. Registering of new threshold isn't time-critical */
4319 sort(new->entries, size, sizeof(*new->entries),
4320 compare_thresholds, NULL);
4322 /* Find current threshold */
4323 new->current_threshold = -1;
4324 for (i = 0; i < size; i++) {
4325 if (new->entries[i].threshold <= usage) {
4327 * new->current_threshold will not be used until
4328 * rcu_assign_pointer(), so it's safe to increment
4331 ++new->current_threshold;
4336 /* Free old spare buffer and save old primary buffer as spare */
4337 kfree(thresholds->spare);
4338 thresholds->spare = thresholds->primary;
4340 rcu_assign_pointer(thresholds->primary, new);
4342 /* To be sure that nobody uses thresholds */
4346 mutex_unlock(&memcg->thresholds_lock);
4351 static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4352 struct eventfd_ctx *eventfd, const char *args)
4354 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
4357 static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
4358 struct eventfd_ctx *eventfd, const char *args)
4360 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
4363 static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4364 struct eventfd_ctx *eventfd, enum res_type type)
4366 struct mem_cgroup_thresholds *thresholds;
4367 struct mem_cgroup_threshold_ary *new;
4368 unsigned long usage;
4369 int i, j, size, entries;
4371 mutex_lock(&memcg->thresholds_lock);
4374 thresholds = &memcg->thresholds;
4375 usage = mem_cgroup_usage(memcg, false);
4376 } else if (type == _MEMSWAP) {
4377 thresholds = &memcg->memsw_thresholds;
4378 usage = mem_cgroup_usage(memcg, true);
4382 if (!thresholds->primary)
4385 /* Check if a threshold crossed before removing */
4386 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4388 /* Calculate new number of threshold */
4390 for (i = 0; i < thresholds->primary->size; i++) {
4391 if (thresholds->primary->entries[i].eventfd != eventfd)
4397 new = thresholds->spare;
4399 /* If no items related to eventfd have been cleared, nothing to do */
4403 /* Set thresholds array to NULL if we don't have thresholds */
4412 /* Copy thresholds and find current threshold */
4413 new->current_threshold = -1;
4414 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4415 if (thresholds->primary->entries[i].eventfd == eventfd)
4418 new->entries[j] = thresholds->primary->entries[i];
4419 if (new->entries[j].threshold <= usage) {
4421 * new->current_threshold will not be used
4422 * until rcu_assign_pointer(), so it's safe to increment
4425 ++new->current_threshold;
4431 /* Swap primary and spare array */
4432 thresholds->spare = thresholds->primary;
4434 rcu_assign_pointer(thresholds->primary, new);
4436 /* To be sure that nobody uses thresholds */
4439 /* If all events are unregistered, free the spare array */
4441 kfree(thresholds->spare);
4442 thresholds->spare = NULL;
4445 mutex_unlock(&memcg->thresholds_lock);
4448 static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4449 struct eventfd_ctx *eventfd)
4451 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
4454 static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4455 struct eventfd_ctx *eventfd)
4457 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
4460 static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
4461 struct eventfd_ctx *eventfd, const char *args)
4463 struct mem_cgroup_eventfd_list *event;
4465 event = kmalloc(sizeof(*event), GFP_KERNEL);
4469 spin_lock(&memcg_oom_lock);
4471 event->eventfd = eventfd;
4472 list_add(&event->list, &memcg->oom_notify);
4474 /* already in OOM ? */
4475 if (memcg->under_oom)
4476 eventfd_signal(eventfd, 1);
4477 spin_unlock(&memcg_oom_lock);
4482 static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
4483 struct eventfd_ctx *eventfd)
4485 struct mem_cgroup_eventfd_list *ev, *tmp;
4487 spin_lock(&memcg_oom_lock);
4489 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
4490 if (ev->eventfd == eventfd) {
4491 list_del(&ev->list);
4496 spin_unlock(&memcg_oom_lock);
4499 static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
4501 struct mem_cgroup *memcg = mem_cgroup_from_seq(sf);
4503 seq_printf(sf, "oom_kill_disable %d\n", memcg->oom_kill_disable);
4504 seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
4505 seq_printf(sf, "oom_kill %lu\n",
4506 atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
4510 static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
4511 struct cftype *cft, u64 val)
4513 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4515 /* cannot set to root cgroup and only 0 and 1 are allowed */
4516 if (mem_cgroup_is_root(memcg) || !((val == 0) || (val == 1)))
4519 memcg->oom_kill_disable = val;
4521 memcg_oom_recover(memcg);
4526 #ifdef CONFIG_CGROUP_WRITEBACK
4528 #include <trace/events/writeback.h>
4530 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4532 return wb_domain_init(&memcg->cgwb_domain, gfp);
4535 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4537 wb_domain_exit(&memcg->cgwb_domain);
4540 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4542 wb_domain_size_changed(&memcg->cgwb_domain);
4545 struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
4547 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4549 if (!memcg->css.parent)
4552 return &memcg->cgwb_domain;
4556 * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
4557 * @wb: bdi_writeback in question
4558 * @pfilepages: out parameter for number of file pages
4559 * @pheadroom: out parameter for number of allocatable pages according to memcg
4560 * @pdirty: out parameter for number of dirty pages
4561 * @pwriteback: out parameter for number of pages under writeback
4563 * Determine the numbers of file, headroom, dirty, and writeback pages in
4564 * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom
4565 * is a bit more involved.
4567 * A memcg's headroom is "min(max, high) - used". In the hierarchy, the
4568 * headroom is calculated as the lowest headroom of itself and the
4569 * ancestors. Note that this doesn't consider the actual amount of
4570 * available memory in the system. The caller should further cap
4571 * *@pheadroom accordingly.
4573 void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
4574 unsigned long *pheadroom, unsigned long *pdirty,
4575 unsigned long *pwriteback)
4577 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4578 struct mem_cgroup *parent;
4580 mem_cgroup_flush_stats();
4582 *pdirty = memcg_page_state(memcg, NR_FILE_DIRTY);
4583 *pwriteback = memcg_page_state(memcg, NR_WRITEBACK);
4584 *pfilepages = memcg_page_state(memcg, NR_INACTIVE_FILE) +
4585 memcg_page_state(memcg, NR_ACTIVE_FILE);
4587 *pheadroom = PAGE_COUNTER_MAX;
4588 while ((parent = parent_mem_cgroup(memcg))) {
4589 unsigned long ceiling = min(READ_ONCE(memcg->memory.max),
4590 READ_ONCE(memcg->memory.high));
4591 unsigned long used = page_counter_read(&memcg->memory);
4593 *pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
4599 * Foreign dirty flushing
4601 * There's an inherent mismatch between memcg and writeback. The former
4602 * tracks ownership per-page while the latter per-inode. This was a
4603 * deliberate design decision because honoring per-page ownership in the
4604 * writeback path is complicated, may lead to higher CPU and IO overheads
4605 * and deemed unnecessary given that write-sharing an inode across
4606 * different cgroups isn't a common use-case.
4608 * Combined with inode majority-writer ownership switching, this works well
4609 * enough in most cases but there are some pathological cases. For
4610 * example, let's say there are two cgroups A and B which keep writing to
4611 * different but confined parts of the same inode. B owns the inode and
4612 * A's memory is limited far below B's. A's dirty ratio can rise enough to
4613 * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
4614 * triggering background writeback. A will be slowed down without a way to
4615 * make writeback of the dirty pages happen.
4617 * Conditions like the above can lead to a cgroup getting repeatedly and
4618 * severely throttled after making some progress after each
4619 * dirty_expire_interval while the underlying IO device is almost
4622 * Solving this problem completely requires matching the ownership tracking
4623 * granularities between memcg and writeback in either direction. However,
4624 * the more egregious behaviors can be avoided by simply remembering the
4625 * most recent foreign dirtying events and initiating remote flushes on
4626 * them when local writeback isn't enough to keep the memory clean enough.
4628 * The following two functions implement such mechanism. When a foreign
4629 * page - a page whose memcg and writeback ownerships don't match - is
4630 * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
4631 * bdi_writeback on the page owning memcg. When balance_dirty_pages()
4632 * decides that the memcg needs to sleep due to high dirty ratio, it calls
4633 * mem_cgroup_flush_foreign() which queues writeback on the recorded
4634 * foreign bdi_writebacks which haven't expired. Both the numbers of
4635 * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
4636 * limited to MEMCG_CGWB_FRN_CNT.
4638 * The mechanism only remembers IDs and doesn't hold any object references.
4639 * As being wrong occasionally doesn't matter, updates and accesses to the
4640 * records are lockless and racy.
4642 void mem_cgroup_track_foreign_dirty_slowpath(struct folio *folio,
4643 struct bdi_writeback *wb)
4645 struct mem_cgroup *memcg = folio_memcg(folio);
4646 struct memcg_cgwb_frn *frn;
4647 u64 now = get_jiffies_64();
4648 u64 oldest_at = now;
4652 trace_track_foreign_dirty(folio, wb);
4655 * Pick the slot to use. If there is already a slot for @wb, keep
4656 * using it. If not replace the oldest one which isn't being
4659 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4660 frn = &memcg->cgwb_frn[i];
4661 if (frn->bdi_id == wb->bdi->id &&
4662 frn->memcg_id == wb->memcg_css->id)
4664 if (time_before64(frn->at, oldest_at) &&
4665 atomic_read(&frn->done.cnt) == 1) {
4667 oldest_at = frn->at;
4671 if (i < MEMCG_CGWB_FRN_CNT) {
4673 * Re-using an existing one. Update timestamp lazily to
4674 * avoid making the cacheline hot. We want them to be
4675 * reasonably up-to-date and significantly shorter than
4676 * dirty_expire_interval as that's what expires the record.
4677 * Use the shorter of 1s and dirty_expire_interval / 8.
4679 unsigned long update_intv =
4680 min_t(unsigned long, HZ,
4681 msecs_to_jiffies(dirty_expire_interval * 10) / 8);
4683 if (time_before64(frn->at, now - update_intv))
4685 } else if (oldest >= 0) {
4686 /* replace the oldest free one */
4687 frn = &memcg->cgwb_frn[oldest];
4688 frn->bdi_id = wb->bdi->id;
4689 frn->memcg_id = wb->memcg_css->id;
4694 /* issue foreign writeback flushes for recorded foreign dirtying events */
4695 void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
4697 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4698 unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
4699 u64 now = jiffies_64;
4702 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4703 struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
4706 * If the record is older than dirty_expire_interval,
4707 * writeback on it has already started. No need to kick it
4708 * off again. Also, don't start a new one if there's
4709 * already one in flight.
4711 if (time_after64(frn->at, now - intv) &&
4712 atomic_read(&frn->done.cnt) == 1) {
4714 trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
4715 cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id,
4716 WB_REASON_FOREIGN_FLUSH,
4722 #else /* CONFIG_CGROUP_WRITEBACK */
4724 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4729 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4733 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4737 #endif /* CONFIG_CGROUP_WRITEBACK */
4740 * DO NOT USE IN NEW FILES.
4742 * "cgroup.event_control" implementation.
4744 * This is way over-engineered. It tries to support fully configurable
4745 * events for each user. Such level of flexibility is completely
4746 * unnecessary especially in the light of the planned unified hierarchy.
4748 * Please deprecate this and replace with something simpler if at all
4753 * Unregister event and free resources.
4755 * Gets called from workqueue.
4757 static void memcg_event_remove(struct work_struct *work)
4759 struct mem_cgroup_event *event =
4760 container_of(work, struct mem_cgroup_event, remove);
4761 struct mem_cgroup *memcg = event->memcg;
4763 remove_wait_queue(event->wqh, &event->wait);
4765 event->unregister_event(memcg, event->eventfd);
4767 /* Notify userspace the event is going away. */
4768 eventfd_signal(event->eventfd, 1);
4770 eventfd_ctx_put(event->eventfd);
4772 css_put(&memcg->css);
4776 * Gets called on EPOLLHUP on eventfd when user closes it.
4778 * Called with wqh->lock held and interrupts disabled.
4780 static int memcg_event_wake(wait_queue_entry_t *wait, unsigned mode,
4781 int sync, void *key)
4783 struct mem_cgroup_event *event =
4784 container_of(wait, struct mem_cgroup_event, wait);
4785 struct mem_cgroup *memcg = event->memcg;
4786 __poll_t flags = key_to_poll(key);
4788 if (flags & EPOLLHUP) {
4790 * If the event has been detached at cgroup removal, we
4791 * can simply return knowing the other side will cleanup
4794 * We can't race against event freeing since the other
4795 * side will require wqh->lock via remove_wait_queue(),
4798 spin_lock(&memcg->event_list_lock);
4799 if (!list_empty(&event->list)) {
4800 list_del_init(&event->list);
4802 * We are in atomic context, but cgroup_event_remove()
4803 * may sleep, so we have to call it in workqueue.
4805 schedule_work(&event->remove);
4807 spin_unlock(&memcg->event_list_lock);
4813 static void memcg_event_ptable_queue_proc(struct file *file,
4814 wait_queue_head_t *wqh, poll_table *pt)
4816 struct mem_cgroup_event *event =
4817 container_of(pt, struct mem_cgroup_event, pt);
4820 add_wait_queue(wqh, &event->wait);
4824 * DO NOT USE IN NEW FILES.
4826 * Parse input and register new cgroup event handler.
4828 * Input must be in format '<event_fd> <control_fd> <args>'.
4829 * Interpretation of args is defined by control file implementation.
4831 static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
4832 char *buf, size_t nbytes, loff_t off)
4834 struct cgroup_subsys_state *css = of_css(of);
4835 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4836 struct mem_cgroup_event *event;
4837 struct cgroup_subsys_state *cfile_css;
4838 unsigned int efd, cfd;
4845 if (IS_ENABLED(CONFIG_PREEMPT_RT))
4848 buf = strstrip(buf);
4850 efd = simple_strtoul(buf, &endp, 10);
4855 cfd = simple_strtoul(buf, &endp, 10);
4856 if ((*endp != ' ') && (*endp != '\0'))
4860 event = kzalloc(sizeof(*event), GFP_KERNEL);
4864 event->memcg = memcg;
4865 INIT_LIST_HEAD(&event->list);
4866 init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
4867 init_waitqueue_func_entry(&event->wait, memcg_event_wake);
4868 INIT_WORK(&event->remove, memcg_event_remove);
4876 event->eventfd = eventfd_ctx_fileget(efile.file);
4877 if (IS_ERR(event->eventfd)) {
4878 ret = PTR_ERR(event->eventfd);
4885 goto out_put_eventfd;
4888 /* the process need read permission on control file */
4889 /* AV: shouldn't we check that it's been opened for read instead? */
4890 ret = file_permission(cfile.file, MAY_READ);
4895 * Determine the event callbacks and set them in @event. This used
4896 * to be done via struct cftype but cgroup core no longer knows
4897 * about these events. The following is crude but the whole thing
4898 * is for compatibility anyway.
4900 * DO NOT ADD NEW FILES.
4902 name = cfile.file->f_path.dentry->d_name.name;
4904 if (!strcmp(name, "memory.usage_in_bytes")) {
4905 event->register_event = mem_cgroup_usage_register_event;
4906 event->unregister_event = mem_cgroup_usage_unregister_event;
4907 } else if (!strcmp(name, "memory.oom_control")) {
4908 event->register_event = mem_cgroup_oom_register_event;
4909 event->unregister_event = mem_cgroup_oom_unregister_event;
4910 } else if (!strcmp(name, "memory.pressure_level")) {
4911 event->register_event = vmpressure_register_event;
4912 event->unregister_event = vmpressure_unregister_event;
4913 } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
4914 event->register_event = memsw_cgroup_usage_register_event;
4915 event->unregister_event = memsw_cgroup_usage_unregister_event;
4922 * Verify @cfile should belong to @css. Also, remaining events are
4923 * automatically removed on cgroup destruction but the removal is
4924 * asynchronous, so take an extra ref on @css.
4926 cfile_css = css_tryget_online_from_dir(cfile.file->f_path.dentry->d_parent,
4927 &memory_cgrp_subsys);
4929 if (IS_ERR(cfile_css))
4931 if (cfile_css != css) {
4936 ret = event->register_event(memcg, event->eventfd, buf);
4940 vfs_poll(efile.file, &event->pt);
4942 spin_lock_irq(&memcg->event_list_lock);
4943 list_add(&event->list, &memcg->event_list);
4944 spin_unlock_irq(&memcg->event_list_lock);
4956 eventfd_ctx_put(event->eventfd);
4965 #if defined(CONFIG_MEMCG_KMEM) && (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG))
4966 static int mem_cgroup_slab_show(struct seq_file *m, void *p)
4970 * Please, take a look at tools/cgroup/memcg_slabinfo.py .
4976 static struct cftype mem_cgroup_legacy_files[] = {
4978 .name = "usage_in_bytes",
4979 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
4980 .read_u64 = mem_cgroup_read_u64,
4983 .name = "max_usage_in_bytes",
4984 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
4985 .write = mem_cgroup_reset,
4986 .read_u64 = mem_cgroup_read_u64,
4989 .name = "limit_in_bytes",
4990 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
4991 .write = mem_cgroup_write,
4992 .read_u64 = mem_cgroup_read_u64,
4995 .name = "soft_limit_in_bytes",
4996 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
4997 .write = mem_cgroup_write,
4998 .read_u64 = mem_cgroup_read_u64,
5002 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
5003 .write = mem_cgroup_reset,
5004 .read_u64 = mem_cgroup_read_u64,
5008 .seq_show = memcg_stat_show,
5011 .name = "force_empty",
5012 .write = mem_cgroup_force_empty_write,
5015 .name = "use_hierarchy",
5016 .write_u64 = mem_cgroup_hierarchy_write,
5017 .read_u64 = mem_cgroup_hierarchy_read,
5020 .name = "cgroup.event_control", /* XXX: for compat */
5021 .write = memcg_write_event_control,
5022 .flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE,
5025 .name = "swappiness",
5026 .read_u64 = mem_cgroup_swappiness_read,
5027 .write_u64 = mem_cgroup_swappiness_write,
5030 .name = "move_charge_at_immigrate",
5031 .read_u64 = mem_cgroup_move_charge_read,
5032 .write_u64 = mem_cgroup_move_charge_write,
5035 .name = "oom_control",
5036 .seq_show = mem_cgroup_oom_control_read,
5037 .write_u64 = mem_cgroup_oom_control_write,
5040 .name = "pressure_level",
5044 .name = "numa_stat",
5045 .seq_show = memcg_numa_stat_show,
5049 .name = "kmem.limit_in_bytes",
5050 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
5051 .write = mem_cgroup_write,
5052 .read_u64 = mem_cgroup_read_u64,
5055 .name = "kmem.usage_in_bytes",
5056 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
5057 .read_u64 = mem_cgroup_read_u64,
5060 .name = "kmem.failcnt",
5061 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
5062 .write = mem_cgroup_reset,
5063 .read_u64 = mem_cgroup_read_u64,
5066 .name = "kmem.max_usage_in_bytes",
5067 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
5068 .write = mem_cgroup_reset,
5069 .read_u64 = mem_cgroup_read_u64,
5071 #if defined(CONFIG_MEMCG_KMEM) && \
5072 (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG))
5074 .name = "kmem.slabinfo",
5075 .seq_show = mem_cgroup_slab_show,
5079 .name = "kmem.tcp.limit_in_bytes",
5080 .private = MEMFILE_PRIVATE(_TCP, RES_LIMIT),
5081 .write = mem_cgroup_write,
5082 .read_u64 = mem_cgroup_read_u64,
5085 .name = "kmem.tcp.usage_in_bytes",
5086 .private = MEMFILE_PRIVATE(_TCP, RES_USAGE),
5087 .read_u64 = mem_cgroup_read_u64,
5090 .name = "kmem.tcp.failcnt",
5091 .private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT),
5092 .write = mem_cgroup_reset,
5093 .read_u64 = mem_cgroup_read_u64,
5096 .name = "kmem.tcp.max_usage_in_bytes",
5097 .private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE),
5098 .write = mem_cgroup_reset,
5099 .read_u64 = mem_cgroup_read_u64,
5101 { }, /* terminate */
5105 * Private memory cgroup IDR
5107 * Swap-out records and page cache shadow entries need to store memcg
5108 * references in constrained space, so we maintain an ID space that is
5109 * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
5110 * memory-controlled cgroups to 64k.
5112 * However, there usually are many references to the offline CSS after
5113 * the cgroup has been destroyed, such as page cache or reclaimable
5114 * slab objects, that don't need to hang on to the ID. We want to keep
5115 * those dead CSS from occupying IDs, or we might quickly exhaust the
5116 * relatively small ID space and prevent the creation of new cgroups
5117 * even when there are much fewer than 64k cgroups - possibly none.
5119 * Maintain a private 16-bit ID space for memcg, and allow the ID to
5120 * be freed and recycled when it's no longer needed, which is usually
5121 * when the CSS is offlined.
5123 * The only exception to that are records of swapped out tmpfs/shmem
5124 * pages that need to be attributed to live ancestors on swapin. But
5125 * those references are manageable from userspace.
5128 static DEFINE_IDR(mem_cgroup_idr);
5130 static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
5132 if (memcg->id.id > 0) {
5133 idr_remove(&mem_cgroup_idr, memcg->id.id);
5138 static void __maybe_unused mem_cgroup_id_get_many(struct mem_cgroup *memcg,
5141 refcount_add(n, &memcg->id.ref);
5144 static void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
5146 if (refcount_sub_and_test(n, &memcg->id.ref)) {
5147 mem_cgroup_id_remove(memcg);
5149 /* Memcg ID pins CSS */
5150 css_put(&memcg->css);
5154 static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
5156 mem_cgroup_id_put_many(memcg, 1);
5160 * mem_cgroup_from_id - look up a memcg from a memcg id
5161 * @id: the memcg id to look up
5163 * Caller must hold rcu_read_lock().
5165 struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
5167 WARN_ON_ONCE(!rcu_read_lock_held());
5168 return idr_find(&mem_cgroup_idr, id);
5171 #ifdef CONFIG_SHRINKER_DEBUG
5172 struct mem_cgroup *mem_cgroup_get_from_ino(unsigned long ino)
5174 struct cgroup *cgrp;
5175 struct cgroup_subsys_state *css;
5176 struct mem_cgroup *memcg;
5178 cgrp = cgroup_get_from_id(ino);
5180 return ERR_PTR(-ENOENT);
5182 css = cgroup_get_e_css(cgrp, &memory_cgrp_subsys);
5184 memcg = container_of(css, struct mem_cgroup, css);
5186 memcg = ERR_PTR(-ENOENT);
5194 static int alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5196 struct mem_cgroup_per_node *pn;
5198 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, node);
5202 pn->lruvec_stats_percpu = alloc_percpu_gfp(struct lruvec_stats_percpu,
5203 GFP_KERNEL_ACCOUNT);
5204 if (!pn->lruvec_stats_percpu) {
5209 lruvec_init(&pn->lruvec);
5212 memcg->nodeinfo[node] = pn;
5216 static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5218 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
5223 free_percpu(pn->lruvec_stats_percpu);
5227 static void __mem_cgroup_free(struct mem_cgroup *memcg)
5232 free_mem_cgroup_per_node_info(memcg, node);
5233 kfree(memcg->vmstats);
5234 free_percpu(memcg->vmstats_percpu);
5238 static void mem_cgroup_free(struct mem_cgroup *memcg)
5240 lru_gen_exit_memcg(memcg);
5241 memcg_wb_domain_exit(memcg);
5242 __mem_cgroup_free(memcg);
5245 static struct mem_cgroup *mem_cgroup_alloc(void)
5247 struct mem_cgroup *memcg;
5249 int __maybe_unused i;
5250 long error = -ENOMEM;
5252 memcg = kzalloc(struct_size(memcg, nodeinfo, nr_node_ids), GFP_KERNEL);
5254 return ERR_PTR(error);
5256 memcg->id.id = idr_alloc(&mem_cgroup_idr, NULL,
5257 1, MEM_CGROUP_ID_MAX + 1, GFP_KERNEL);
5258 if (memcg->id.id < 0) {
5259 error = memcg->id.id;
5263 memcg->vmstats = kzalloc(sizeof(struct memcg_vmstats), GFP_KERNEL);
5264 if (!memcg->vmstats)
5267 memcg->vmstats_percpu = alloc_percpu_gfp(struct memcg_vmstats_percpu,
5268 GFP_KERNEL_ACCOUNT);
5269 if (!memcg->vmstats_percpu)
5273 if (alloc_mem_cgroup_per_node_info(memcg, node))
5276 if (memcg_wb_domain_init(memcg, GFP_KERNEL))
5279 INIT_WORK(&memcg->high_work, high_work_func);
5280 INIT_LIST_HEAD(&memcg->oom_notify);
5281 mutex_init(&memcg->thresholds_lock);
5282 spin_lock_init(&memcg->move_lock);
5283 vmpressure_init(&memcg->vmpressure);
5284 INIT_LIST_HEAD(&memcg->event_list);
5285 spin_lock_init(&memcg->event_list_lock);
5286 memcg->socket_pressure = jiffies;
5287 #ifdef CONFIG_MEMCG_KMEM
5288 memcg->kmemcg_id = -1;
5289 INIT_LIST_HEAD(&memcg->objcg_list);
5291 #ifdef CONFIG_CGROUP_WRITEBACK
5292 INIT_LIST_HEAD(&memcg->cgwb_list);
5293 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5294 memcg->cgwb_frn[i].done =
5295 __WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
5297 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5298 spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
5299 INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
5300 memcg->deferred_split_queue.split_queue_len = 0;
5302 idr_replace(&mem_cgroup_idr, memcg, memcg->id.id);
5303 lru_gen_init_memcg(memcg);
5306 mem_cgroup_id_remove(memcg);
5307 __mem_cgroup_free(memcg);
5308 return ERR_PTR(error);
5311 static struct cgroup_subsys_state * __ref
5312 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
5314 struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
5315 struct mem_cgroup *memcg, *old_memcg;
5317 old_memcg = set_active_memcg(parent);
5318 memcg = mem_cgroup_alloc();
5319 set_active_memcg(old_memcg);
5321 return ERR_CAST(memcg);
5323 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5324 memcg->soft_limit = PAGE_COUNTER_MAX;
5325 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
5326 memcg->zswap_max = PAGE_COUNTER_MAX;
5328 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5330 memcg->swappiness = mem_cgroup_swappiness(parent);
5331 memcg->oom_kill_disable = parent->oom_kill_disable;
5333 page_counter_init(&memcg->memory, &parent->memory);
5334 page_counter_init(&memcg->swap, &parent->swap);
5335 page_counter_init(&memcg->kmem, &parent->kmem);
5336 page_counter_init(&memcg->tcpmem, &parent->tcpmem);
5338 init_memcg_events();
5339 page_counter_init(&memcg->memory, NULL);
5340 page_counter_init(&memcg->swap, NULL);
5341 page_counter_init(&memcg->kmem, NULL);
5342 page_counter_init(&memcg->tcpmem, NULL);
5344 root_mem_cgroup = memcg;
5348 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5349 static_branch_inc(&memcg_sockets_enabled_key);
5354 static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
5356 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5358 if (memcg_online_kmem(memcg))
5362 * A memcg must be visible for expand_shrinker_info()
5363 * by the time the maps are allocated. So, we allocate maps
5364 * here, when for_each_mem_cgroup() can't skip it.
5366 if (alloc_shrinker_info(memcg))
5369 /* Online state pins memcg ID, memcg ID pins CSS */
5370 refcount_set(&memcg->id.ref, 1);
5373 if (unlikely(mem_cgroup_is_root(memcg)))
5374 queue_delayed_work(system_unbound_wq, &stats_flush_dwork,
5378 memcg_offline_kmem(memcg);
5380 mem_cgroup_id_remove(memcg);
5384 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
5386 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5387 struct mem_cgroup_event *event, *tmp;
5390 * Unregister events and notify userspace.
5391 * Notify userspace about cgroup removing only after rmdir of cgroup
5392 * directory to avoid race between userspace and kernelspace.
5394 spin_lock_irq(&memcg->event_list_lock);
5395 list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
5396 list_del_init(&event->list);
5397 schedule_work(&event->remove);
5399 spin_unlock_irq(&memcg->event_list_lock);
5401 page_counter_set_min(&memcg->memory, 0);
5402 page_counter_set_low(&memcg->memory, 0);
5404 memcg_offline_kmem(memcg);
5405 reparent_shrinker_deferred(memcg);
5406 wb_memcg_offline(memcg);
5408 drain_all_stock(memcg);
5410 mem_cgroup_id_put(memcg);
5413 static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
5415 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5417 invalidate_reclaim_iterators(memcg);
5420 static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
5422 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5423 int __maybe_unused i;
5425 #ifdef CONFIG_CGROUP_WRITEBACK
5426 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5427 wb_wait_for_completion(&memcg->cgwb_frn[i].done);
5429 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5430 static_branch_dec(&memcg_sockets_enabled_key);
5432 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg->tcpmem_active)
5433 static_branch_dec(&memcg_sockets_enabled_key);
5435 vmpressure_cleanup(&memcg->vmpressure);
5436 cancel_work_sync(&memcg->high_work);
5437 mem_cgroup_remove_from_trees(memcg);
5438 free_shrinker_info(memcg);
5439 mem_cgroup_free(memcg);
5443 * mem_cgroup_css_reset - reset the states of a mem_cgroup
5444 * @css: the target css
5446 * Reset the states of the mem_cgroup associated with @css. This is
5447 * invoked when the userland requests disabling on the default hierarchy
5448 * but the memcg is pinned through dependency. The memcg should stop
5449 * applying policies and should revert to the vanilla state as it may be
5450 * made visible again.
5452 * The current implementation only resets the essential configurations.
5453 * This needs to be expanded to cover all the visible parts.
5455 static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
5457 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5459 page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
5460 page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
5461 page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
5462 page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
5463 page_counter_set_min(&memcg->memory, 0);
5464 page_counter_set_low(&memcg->memory, 0);
5465 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5466 memcg->soft_limit = PAGE_COUNTER_MAX;
5467 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5468 memcg_wb_domain_size_changed(memcg);
5471 static void mem_cgroup_css_rstat_flush(struct cgroup_subsys_state *css, int cpu)
5473 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5474 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
5475 struct memcg_vmstats_percpu *statc;
5479 statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
5481 for (i = 0; i < MEMCG_NR_STAT; i++) {
5483 * Collect the aggregated propagation counts of groups
5484 * below us. We're in a per-cpu loop here and this is
5485 * a global counter, so the first cycle will get them.
5487 delta = memcg->vmstats->state_pending[i];
5489 memcg->vmstats->state_pending[i] = 0;
5491 /* Add CPU changes on this level since the last flush */
5492 v = READ_ONCE(statc->state[i]);
5493 if (v != statc->state_prev[i]) {
5494 delta += v - statc->state_prev[i];
5495 statc->state_prev[i] = v;
5501 /* Aggregate counts on this level and propagate upwards */
5502 memcg->vmstats->state[i] += delta;
5504 parent->vmstats->state_pending[i] += delta;
5507 for (i = 0; i < NR_MEMCG_EVENTS; i++) {
5508 delta = memcg->vmstats->events_pending[i];
5510 memcg->vmstats->events_pending[i] = 0;
5512 v = READ_ONCE(statc->events[i]);
5513 if (v != statc->events_prev[i]) {
5514 delta += v - statc->events_prev[i];
5515 statc->events_prev[i] = v;
5521 memcg->vmstats->events[i] += delta;
5523 parent->vmstats->events_pending[i] += delta;
5526 for_each_node_state(nid, N_MEMORY) {
5527 struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
5528 struct mem_cgroup_per_node *ppn = NULL;
5529 struct lruvec_stats_percpu *lstatc;
5532 ppn = parent->nodeinfo[nid];
5534 lstatc = per_cpu_ptr(pn->lruvec_stats_percpu, cpu);
5536 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++) {
5537 delta = pn->lruvec_stats.state_pending[i];
5539 pn->lruvec_stats.state_pending[i] = 0;
5541 v = READ_ONCE(lstatc->state[i]);
5542 if (v != lstatc->state_prev[i]) {
5543 delta += v - lstatc->state_prev[i];
5544 lstatc->state_prev[i] = v;
5550 pn->lruvec_stats.state[i] += delta;
5552 ppn->lruvec_stats.state_pending[i] += delta;
5558 /* Handlers for move charge at task migration. */
5559 static int mem_cgroup_do_precharge(unsigned long count)
5563 /* Try a single bulk charge without reclaim first, kswapd may wake */
5564 ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count);
5566 mc.precharge += count;
5570 /* Try charges one by one with reclaim, but do not retry */
5572 ret = try_charge(mc.to, GFP_KERNEL | __GFP_NORETRY, 1);
5586 enum mc_target_type {
5593 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5594 unsigned long addr, pte_t ptent)
5596 struct page *page = vm_normal_page(vma, addr, ptent);
5598 if (!page || !page_mapped(page))
5600 if (PageAnon(page)) {
5601 if (!(mc.flags & MOVE_ANON))
5604 if (!(mc.flags & MOVE_FILE))
5607 if (!get_page_unless_zero(page))
5613 #if defined(CONFIG_SWAP) || defined(CONFIG_DEVICE_PRIVATE)
5614 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5615 pte_t ptent, swp_entry_t *entry)
5617 struct page *page = NULL;
5618 swp_entry_t ent = pte_to_swp_entry(ptent);
5620 if (!(mc.flags & MOVE_ANON))
5624 * Handle device private pages that are not accessible by the CPU, but
5625 * stored as special swap entries in the page table.
5627 if (is_device_private_entry(ent)) {
5628 page = pfn_swap_entry_to_page(ent);
5629 if (!get_page_unless_zero(page))
5634 if (non_swap_entry(ent))
5638 * Because swap_cache_get_folio() updates some statistics counter,
5639 * we call find_get_page() with swapper_space directly.
5641 page = find_get_page(swap_address_space(ent), swp_offset(ent));
5642 entry->val = ent.val;
5647 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5648 pte_t ptent, swp_entry_t *entry)
5654 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5655 unsigned long addr, pte_t ptent)
5657 if (!vma->vm_file) /* anonymous vma */
5659 if (!(mc.flags & MOVE_FILE))
5662 /* page is moved even if it's not RSS of this task(page-faulted). */
5663 /* shmem/tmpfs may report page out on swap: account for that too. */
5664 return find_get_incore_page(vma->vm_file->f_mapping,
5665 linear_page_index(vma, addr));
5669 * mem_cgroup_move_account - move account of the page
5671 * @compound: charge the page as compound or small page
5672 * @from: mem_cgroup which the page is moved from.
5673 * @to: mem_cgroup which the page is moved to. @from != @to.
5675 * The caller must make sure the page is not on LRU (isolate_page() is useful.)
5677 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
5680 static int mem_cgroup_move_account(struct page *page,
5682 struct mem_cgroup *from,
5683 struct mem_cgroup *to)
5685 struct folio *folio = page_folio(page);
5686 struct lruvec *from_vec, *to_vec;
5687 struct pglist_data *pgdat;
5688 unsigned int nr_pages = compound ? folio_nr_pages(folio) : 1;
5691 VM_BUG_ON(from == to);
5692 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
5693 VM_BUG_ON(compound && !folio_test_large(folio));
5696 * Prevent mem_cgroup_migrate() from looking at
5697 * page's memory cgroup of its source page while we change it.
5700 if (!folio_trylock(folio))
5704 if (folio_memcg(folio) != from)
5707 pgdat = folio_pgdat(folio);
5708 from_vec = mem_cgroup_lruvec(from, pgdat);
5709 to_vec = mem_cgroup_lruvec(to, pgdat);
5711 folio_memcg_lock(folio);
5713 if (folio_test_anon(folio)) {
5714 if (folio_mapped(folio)) {
5715 __mod_lruvec_state(from_vec, NR_ANON_MAPPED, -nr_pages);
5716 __mod_lruvec_state(to_vec, NR_ANON_MAPPED, nr_pages);
5717 if (folio_test_transhuge(folio)) {
5718 __mod_lruvec_state(from_vec, NR_ANON_THPS,
5720 __mod_lruvec_state(to_vec, NR_ANON_THPS,
5725 __mod_lruvec_state(from_vec, NR_FILE_PAGES, -nr_pages);
5726 __mod_lruvec_state(to_vec, NR_FILE_PAGES, nr_pages);
5728 if (folio_test_swapbacked(folio)) {
5729 __mod_lruvec_state(from_vec, NR_SHMEM, -nr_pages);
5730 __mod_lruvec_state(to_vec, NR_SHMEM, nr_pages);
5733 if (folio_mapped(folio)) {
5734 __mod_lruvec_state(from_vec, NR_FILE_MAPPED, -nr_pages);
5735 __mod_lruvec_state(to_vec, NR_FILE_MAPPED, nr_pages);
5738 if (folio_test_dirty(folio)) {
5739 struct address_space *mapping = folio_mapping(folio);
5741 if (mapping_can_writeback(mapping)) {
5742 __mod_lruvec_state(from_vec, NR_FILE_DIRTY,
5744 __mod_lruvec_state(to_vec, NR_FILE_DIRTY,
5750 if (folio_test_writeback(folio)) {
5751 __mod_lruvec_state(from_vec, NR_WRITEBACK, -nr_pages);
5752 __mod_lruvec_state(to_vec, NR_WRITEBACK, nr_pages);
5756 * All state has been migrated, let's switch to the new memcg.
5758 * It is safe to change page's memcg here because the page
5759 * is referenced, charged, isolated, and locked: we can't race
5760 * with (un)charging, migration, LRU putback, or anything else
5761 * that would rely on a stable page's memory cgroup.
5763 * Note that lock_page_memcg is a memcg lock, not a page lock,
5764 * to save space. As soon as we switch page's memory cgroup to a
5765 * new memcg that isn't locked, the above state can change
5766 * concurrently again. Make sure we're truly done with it.
5771 css_put(&from->css);
5773 folio->memcg_data = (unsigned long)to;
5775 __folio_memcg_unlock(from);
5778 nid = folio_nid(folio);
5780 local_irq_disable();
5781 mem_cgroup_charge_statistics(to, nr_pages);
5782 memcg_check_events(to, nid);
5783 mem_cgroup_charge_statistics(from, -nr_pages);
5784 memcg_check_events(from, nid);
5787 folio_unlock(folio);
5793 * get_mctgt_type - get target type of moving charge
5794 * @vma: the vma the pte to be checked belongs
5795 * @addr: the address corresponding to the pte to be checked
5796 * @ptent: the pte to be checked
5797 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5800 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5801 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5802 * move charge. if @target is not NULL, the page is stored in target->page
5803 * with extra refcnt got(Callers should handle it).
5804 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5805 * target for charge migration. if @target is not NULL, the entry is stored
5807 * 3(MC_TARGET_DEVICE): like MC_TARGET_PAGE but page is device memory and
5808 * thus not on the lru.
5809 * For now we such page is charge like a regular page would be as for all
5810 * intent and purposes it is just special memory taking the place of a
5813 * See Documentations/vm/hmm.txt and include/linux/hmm.h
5815 * Called with pte lock held.
5818 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
5819 unsigned long addr, pte_t ptent, union mc_target *target)
5821 struct page *page = NULL;
5822 enum mc_target_type ret = MC_TARGET_NONE;
5823 swp_entry_t ent = { .val = 0 };
5825 if (pte_present(ptent))
5826 page = mc_handle_present_pte(vma, addr, ptent);
5827 else if (pte_none_mostly(ptent))
5829 * PTE markers should be treated as a none pte here, separated
5830 * from other swap handling below.
5832 page = mc_handle_file_pte(vma, addr, ptent);
5833 else if (is_swap_pte(ptent))
5834 page = mc_handle_swap_pte(vma, ptent, &ent);
5836 if (!page && !ent.val)
5840 * Do only loose check w/o serialization.
5841 * mem_cgroup_move_account() checks the page is valid or
5842 * not under LRU exclusion.
5844 if (page_memcg(page) == mc.from) {
5845 ret = MC_TARGET_PAGE;
5846 if (is_device_private_page(page) ||
5847 is_device_coherent_page(page))
5848 ret = MC_TARGET_DEVICE;
5850 target->page = page;
5852 if (!ret || !target)
5856 * There is a swap entry and a page doesn't exist or isn't charged.
5857 * But we cannot move a tail-page in a THP.
5859 if (ent.val && !ret && (!page || !PageTransCompound(page)) &&
5860 mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
5861 ret = MC_TARGET_SWAP;
5868 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5870 * We don't consider PMD mapped swapping or file mapped pages because THP does
5871 * not support them for now.
5872 * Caller should make sure that pmd_trans_huge(pmd) is true.
5874 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5875 unsigned long addr, pmd_t pmd, union mc_target *target)
5877 struct page *page = NULL;
5878 enum mc_target_type ret = MC_TARGET_NONE;
5880 if (unlikely(is_swap_pmd(pmd))) {
5881 VM_BUG_ON(thp_migration_supported() &&
5882 !is_pmd_migration_entry(pmd));
5885 page = pmd_page(pmd);
5886 VM_BUG_ON_PAGE(!page || !PageHead(page), page);
5887 if (!(mc.flags & MOVE_ANON))
5889 if (page_memcg(page) == mc.from) {
5890 ret = MC_TARGET_PAGE;
5893 target->page = page;
5899 static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5900 unsigned long addr, pmd_t pmd, union mc_target *target)
5902 return MC_TARGET_NONE;
5906 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5907 unsigned long addr, unsigned long end,
5908 struct mm_walk *walk)
5910 struct vm_area_struct *vma = walk->vma;
5914 ptl = pmd_trans_huge_lock(pmd, vma);
5917 * Note their can not be MC_TARGET_DEVICE for now as we do not
5918 * support transparent huge page with MEMORY_DEVICE_PRIVATE but
5919 * this might change.
5921 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
5922 mc.precharge += HPAGE_PMD_NR;
5927 if (pmd_trans_unstable(pmd))
5929 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5930 for (; addr != end; pte++, addr += PAGE_SIZE)
5931 if (get_mctgt_type(vma, addr, *pte, NULL))
5932 mc.precharge++; /* increment precharge temporarily */
5933 pte_unmap_unlock(pte - 1, ptl);
5939 static const struct mm_walk_ops precharge_walk_ops = {
5940 .pmd_entry = mem_cgroup_count_precharge_pte_range,
5943 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5945 unsigned long precharge;
5948 walk_page_range(mm, 0, ULONG_MAX, &precharge_walk_ops, NULL);
5949 mmap_read_unlock(mm);
5951 precharge = mc.precharge;
5957 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5959 unsigned long precharge = mem_cgroup_count_precharge(mm);
5961 VM_BUG_ON(mc.moving_task);
5962 mc.moving_task = current;
5963 return mem_cgroup_do_precharge(precharge);
5966 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5967 static void __mem_cgroup_clear_mc(void)
5969 struct mem_cgroup *from = mc.from;
5970 struct mem_cgroup *to = mc.to;
5972 /* we must uncharge all the leftover precharges from mc.to */
5974 cancel_charge(mc.to, mc.precharge);
5978 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5979 * we must uncharge here.
5981 if (mc.moved_charge) {
5982 cancel_charge(mc.from, mc.moved_charge);
5983 mc.moved_charge = 0;
5985 /* we must fixup refcnts and charges */
5986 if (mc.moved_swap) {
5987 /* uncharge swap account from the old cgroup */
5988 if (!mem_cgroup_is_root(mc.from))
5989 page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
5991 mem_cgroup_id_put_many(mc.from, mc.moved_swap);
5994 * we charged both to->memory and to->memsw, so we
5995 * should uncharge to->memory.
5997 if (!mem_cgroup_is_root(mc.to))
5998 page_counter_uncharge(&mc.to->memory, mc.moved_swap);
6002 memcg_oom_recover(from);
6003 memcg_oom_recover(to);
6004 wake_up_all(&mc.waitq);
6007 static void mem_cgroup_clear_mc(void)
6009 struct mm_struct *mm = mc.mm;
6012 * we must clear moving_task before waking up waiters at the end of
6015 mc.moving_task = NULL;
6016 __mem_cgroup_clear_mc();
6017 spin_lock(&mc.lock);
6021 spin_unlock(&mc.lock);
6026 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
6028 struct cgroup_subsys_state *css;
6029 struct mem_cgroup *memcg = NULL; /* unneeded init to make gcc happy */
6030 struct mem_cgroup *from;
6031 struct task_struct *leader, *p;
6032 struct mm_struct *mm;
6033 unsigned long move_flags;
6036 /* charge immigration isn't supported on the default hierarchy */
6037 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
6041 * Multi-process migrations only happen on the default hierarchy
6042 * where charge immigration is not used. Perform charge
6043 * immigration if @tset contains a leader and whine if there are
6047 cgroup_taskset_for_each_leader(leader, css, tset) {
6050 memcg = mem_cgroup_from_css(css);
6056 * We are now committed to this value whatever it is. Changes in this
6057 * tunable will only affect upcoming migrations, not the current one.
6058 * So we need to save it, and keep it going.
6060 move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
6064 from = mem_cgroup_from_task(p);
6066 VM_BUG_ON(from == memcg);
6068 mm = get_task_mm(p);
6071 /* We move charges only when we move a owner of the mm */
6072 if (mm->owner == p) {
6075 VM_BUG_ON(mc.precharge);
6076 VM_BUG_ON(mc.moved_charge);
6077 VM_BUG_ON(mc.moved_swap);
6079 spin_lock(&mc.lock);
6083 mc.flags = move_flags;
6084 spin_unlock(&mc.lock);
6085 /* We set mc.moving_task later */
6087 ret = mem_cgroup_precharge_mc(mm);
6089 mem_cgroup_clear_mc();
6096 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6099 mem_cgroup_clear_mc();
6102 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
6103 unsigned long addr, unsigned long end,
6104 struct mm_walk *walk)
6107 struct vm_area_struct *vma = walk->vma;
6110 enum mc_target_type target_type;
6111 union mc_target target;
6114 ptl = pmd_trans_huge_lock(pmd, vma);
6116 if (mc.precharge < HPAGE_PMD_NR) {
6120 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
6121 if (target_type == MC_TARGET_PAGE) {
6123 if (!isolate_lru_page(page)) {
6124 if (!mem_cgroup_move_account(page, true,
6126 mc.precharge -= HPAGE_PMD_NR;
6127 mc.moved_charge += HPAGE_PMD_NR;
6129 putback_lru_page(page);
6132 } else if (target_type == MC_TARGET_DEVICE) {
6134 if (!mem_cgroup_move_account(page, true,
6136 mc.precharge -= HPAGE_PMD_NR;
6137 mc.moved_charge += HPAGE_PMD_NR;
6145 if (pmd_trans_unstable(pmd))
6148 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6149 for (; addr != end; addr += PAGE_SIZE) {
6150 pte_t ptent = *(pte++);
6151 bool device = false;
6157 switch (get_mctgt_type(vma, addr, ptent, &target)) {
6158 case MC_TARGET_DEVICE:
6161 case MC_TARGET_PAGE:
6164 * We can have a part of the split pmd here. Moving it
6165 * can be done but it would be too convoluted so simply
6166 * ignore such a partial THP and keep it in original
6167 * memcg. There should be somebody mapping the head.
6169 if (PageTransCompound(page))
6171 if (!device && isolate_lru_page(page))
6173 if (!mem_cgroup_move_account(page, false,
6176 /* we uncharge from mc.from later. */
6180 putback_lru_page(page);
6181 put: /* get_mctgt_type() gets the page */
6184 case MC_TARGET_SWAP:
6186 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
6188 mem_cgroup_id_get_many(mc.to, 1);
6189 /* we fixup other refcnts and charges later. */
6197 pte_unmap_unlock(pte - 1, ptl);
6202 * We have consumed all precharges we got in can_attach().
6203 * We try charge one by one, but don't do any additional
6204 * charges to mc.to if we have failed in charge once in attach()
6207 ret = mem_cgroup_do_precharge(1);
6215 static const struct mm_walk_ops charge_walk_ops = {
6216 .pmd_entry = mem_cgroup_move_charge_pte_range,
6219 static void mem_cgroup_move_charge(void)
6221 lru_add_drain_all();
6223 * Signal lock_page_memcg() to take the memcg's move_lock
6224 * while we're moving its pages to another memcg. Then wait
6225 * for already started RCU-only updates to finish.
6227 atomic_inc(&mc.from->moving_account);
6230 if (unlikely(!mmap_read_trylock(mc.mm))) {
6232 * Someone who are holding the mmap_lock might be waiting in
6233 * waitq. So we cancel all extra charges, wake up all waiters,
6234 * and retry. Because we cancel precharges, we might not be able
6235 * to move enough charges, but moving charge is a best-effort
6236 * feature anyway, so it wouldn't be a big problem.
6238 __mem_cgroup_clear_mc();
6243 * When we have consumed all precharges and failed in doing
6244 * additional charge, the page walk just aborts.
6246 walk_page_range(mc.mm, 0, ULONG_MAX, &charge_walk_ops, NULL);
6247 mmap_read_unlock(mc.mm);
6248 atomic_dec(&mc.from->moving_account);
6251 static void mem_cgroup_move_task(void)
6254 mem_cgroup_move_charge();
6255 mem_cgroup_clear_mc();
6258 #else /* !CONFIG_MMU */
6259 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
6263 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6266 static void mem_cgroup_move_task(void)
6271 #ifdef CONFIG_LRU_GEN
6272 static void mem_cgroup_attach(struct cgroup_taskset *tset)
6274 struct task_struct *task;
6275 struct cgroup_subsys_state *css;
6277 /* find the first leader if there is any */
6278 cgroup_taskset_for_each_leader(task, css, tset)
6285 if (task->mm && READ_ONCE(task->mm->owner) == task)
6286 lru_gen_migrate_mm(task->mm);
6290 static void mem_cgroup_attach(struct cgroup_taskset *tset)
6293 #endif /* CONFIG_LRU_GEN */
6295 static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
6297 if (value == PAGE_COUNTER_MAX)
6298 seq_puts(m, "max\n");
6300 seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
6305 static u64 memory_current_read(struct cgroup_subsys_state *css,
6308 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6310 return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
6313 static u64 memory_peak_read(struct cgroup_subsys_state *css,
6316 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6318 return (u64)memcg->memory.watermark * PAGE_SIZE;
6321 static int memory_min_show(struct seq_file *m, void *v)
6323 return seq_puts_memcg_tunable(m,
6324 READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
6327 static ssize_t memory_min_write(struct kernfs_open_file *of,
6328 char *buf, size_t nbytes, loff_t off)
6330 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6334 buf = strstrip(buf);
6335 err = page_counter_memparse(buf, "max", &min);
6339 page_counter_set_min(&memcg->memory, min);
6344 static int memory_low_show(struct seq_file *m, void *v)
6346 return seq_puts_memcg_tunable(m,
6347 READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
6350 static ssize_t memory_low_write(struct kernfs_open_file *of,
6351 char *buf, size_t nbytes, loff_t off)
6353 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6357 buf = strstrip(buf);
6358 err = page_counter_memparse(buf, "max", &low);
6362 page_counter_set_low(&memcg->memory, low);
6367 static int memory_high_show(struct seq_file *m, void *v)
6369 return seq_puts_memcg_tunable(m,
6370 READ_ONCE(mem_cgroup_from_seq(m)->memory.high));
6373 static ssize_t memory_high_write(struct kernfs_open_file *of,
6374 char *buf, size_t nbytes, loff_t off)
6376 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6377 unsigned int nr_retries = MAX_RECLAIM_RETRIES;
6378 bool drained = false;
6382 buf = strstrip(buf);
6383 err = page_counter_memparse(buf, "max", &high);
6387 page_counter_set_high(&memcg->memory, high);
6390 unsigned long nr_pages = page_counter_read(&memcg->memory);
6391 unsigned long reclaimed;
6393 if (nr_pages <= high)
6396 if (signal_pending(current))
6400 drain_all_stock(memcg);
6405 reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
6406 GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP);
6408 if (!reclaimed && !nr_retries--)
6412 memcg_wb_domain_size_changed(memcg);
6416 static int memory_max_show(struct seq_file *m, void *v)
6418 return seq_puts_memcg_tunable(m,
6419 READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
6422 static ssize_t memory_max_write(struct kernfs_open_file *of,
6423 char *buf, size_t nbytes, loff_t off)
6425 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6426 unsigned int nr_reclaims = MAX_RECLAIM_RETRIES;
6427 bool drained = false;
6431 buf = strstrip(buf);
6432 err = page_counter_memparse(buf, "max", &max);
6436 xchg(&memcg->memory.max, max);
6439 unsigned long nr_pages = page_counter_read(&memcg->memory);
6441 if (nr_pages <= max)
6444 if (signal_pending(current))
6448 drain_all_stock(memcg);
6454 if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
6455 GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP))
6460 memcg_memory_event(memcg, MEMCG_OOM);
6461 if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
6465 memcg_wb_domain_size_changed(memcg);
6469 static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
6471 seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
6472 seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
6473 seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
6474 seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
6475 seq_printf(m, "oom_kill %lu\n",
6476 atomic_long_read(&events[MEMCG_OOM_KILL]));
6477 seq_printf(m, "oom_group_kill %lu\n",
6478 atomic_long_read(&events[MEMCG_OOM_GROUP_KILL]));
6481 static int memory_events_show(struct seq_file *m, void *v)
6483 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6485 __memory_events_show(m, memcg->memory_events);
6489 static int memory_events_local_show(struct seq_file *m, void *v)
6491 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6493 __memory_events_show(m, memcg->memory_events_local);
6497 static int memory_stat_show(struct seq_file *m, void *v)
6499 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6500 char *buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
6504 memory_stat_format(memcg, buf, PAGE_SIZE);
6511 static inline unsigned long lruvec_page_state_output(struct lruvec *lruvec,
6514 return lruvec_page_state(lruvec, item) * memcg_page_state_unit(item);
6517 static int memory_numa_stat_show(struct seq_file *m, void *v)
6520 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6522 mem_cgroup_flush_stats();
6524 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
6527 if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS)
6530 seq_printf(m, "%s", memory_stats[i].name);
6531 for_each_node_state(nid, N_MEMORY) {
6533 struct lruvec *lruvec;
6535 lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
6536 size = lruvec_page_state_output(lruvec,
6537 memory_stats[i].idx);
6538 seq_printf(m, " N%d=%llu", nid, size);
6547 static int memory_oom_group_show(struct seq_file *m, void *v)
6549 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6551 seq_printf(m, "%d\n", memcg->oom_group);
6556 static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
6557 char *buf, size_t nbytes, loff_t off)
6559 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6562 buf = strstrip(buf);
6566 ret = kstrtoint(buf, 0, &oom_group);
6570 if (oom_group != 0 && oom_group != 1)
6573 memcg->oom_group = oom_group;
6578 static ssize_t memory_reclaim(struct kernfs_open_file *of, char *buf,
6579 size_t nbytes, loff_t off)
6581 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6582 unsigned int nr_retries = MAX_RECLAIM_RETRIES;
6583 unsigned long nr_to_reclaim, nr_reclaimed = 0;
6584 unsigned int reclaim_options;
6587 buf = strstrip(buf);
6588 err = page_counter_memparse(buf, "", &nr_to_reclaim);
6592 reclaim_options = MEMCG_RECLAIM_MAY_SWAP | MEMCG_RECLAIM_PROACTIVE;
6593 while (nr_reclaimed < nr_to_reclaim) {
6594 unsigned long reclaimed;
6596 if (signal_pending(current))
6600 * This is the final attempt, drain percpu lru caches in the
6601 * hope of introducing more evictable pages for
6602 * try_to_free_mem_cgroup_pages().
6605 lru_add_drain_all();
6607 reclaimed = try_to_free_mem_cgroup_pages(memcg,
6608 nr_to_reclaim - nr_reclaimed,
6609 GFP_KERNEL, reclaim_options);
6611 if (!reclaimed && !nr_retries--)
6614 nr_reclaimed += reclaimed;
6620 static struct cftype memory_files[] = {
6623 .flags = CFTYPE_NOT_ON_ROOT,
6624 .read_u64 = memory_current_read,
6628 .flags = CFTYPE_NOT_ON_ROOT,
6629 .read_u64 = memory_peak_read,
6633 .flags = CFTYPE_NOT_ON_ROOT,
6634 .seq_show = memory_min_show,
6635 .write = memory_min_write,
6639 .flags = CFTYPE_NOT_ON_ROOT,
6640 .seq_show = memory_low_show,
6641 .write = memory_low_write,
6645 .flags = CFTYPE_NOT_ON_ROOT,
6646 .seq_show = memory_high_show,
6647 .write = memory_high_write,
6651 .flags = CFTYPE_NOT_ON_ROOT,
6652 .seq_show = memory_max_show,
6653 .write = memory_max_write,
6657 .flags = CFTYPE_NOT_ON_ROOT,
6658 .file_offset = offsetof(struct mem_cgroup, events_file),
6659 .seq_show = memory_events_show,
6662 .name = "events.local",
6663 .flags = CFTYPE_NOT_ON_ROOT,
6664 .file_offset = offsetof(struct mem_cgroup, events_local_file),
6665 .seq_show = memory_events_local_show,
6669 .seq_show = memory_stat_show,
6673 .name = "numa_stat",
6674 .seq_show = memory_numa_stat_show,
6678 .name = "oom.group",
6679 .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
6680 .seq_show = memory_oom_group_show,
6681 .write = memory_oom_group_write,
6685 .flags = CFTYPE_NS_DELEGATABLE,
6686 .write = memory_reclaim,
6691 struct cgroup_subsys memory_cgrp_subsys = {
6692 .css_alloc = mem_cgroup_css_alloc,
6693 .css_online = mem_cgroup_css_online,
6694 .css_offline = mem_cgroup_css_offline,
6695 .css_released = mem_cgroup_css_released,
6696 .css_free = mem_cgroup_css_free,
6697 .css_reset = mem_cgroup_css_reset,
6698 .css_rstat_flush = mem_cgroup_css_rstat_flush,
6699 .can_attach = mem_cgroup_can_attach,
6700 .attach = mem_cgroup_attach,
6701 .cancel_attach = mem_cgroup_cancel_attach,
6702 .post_attach = mem_cgroup_move_task,
6703 .dfl_cftypes = memory_files,
6704 .legacy_cftypes = mem_cgroup_legacy_files,
6709 * This function calculates an individual cgroup's effective
6710 * protection which is derived from its own memory.min/low, its
6711 * parent's and siblings' settings, as well as the actual memory
6712 * distribution in the tree.
6714 * The following rules apply to the effective protection values:
6716 * 1. At the first level of reclaim, effective protection is equal to
6717 * the declared protection in memory.min and memory.low.
6719 * 2. To enable safe delegation of the protection configuration, at
6720 * subsequent levels the effective protection is capped to the
6721 * parent's effective protection.
6723 * 3. To make complex and dynamic subtrees easier to configure, the
6724 * user is allowed to overcommit the declared protection at a given
6725 * level. If that is the case, the parent's effective protection is
6726 * distributed to the children in proportion to how much protection
6727 * they have declared and how much of it they are utilizing.
6729 * This makes distribution proportional, but also work-conserving:
6730 * if one cgroup claims much more protection than it uses memory,
6731 * the unused remainder is available to its siblings.
6733 * 4. Conversely, when the declared protection is undercommitted at a
6734 * given level, the distribution of the larger parental protection
6735 * budget is NOT proportional. A cgroup's protection from a sibling
6736 * is capped to its own memory.min/low setting.
6738 * 5. However, to allow protecting recursive subtrees from each other
6739 * without having to declare each individual cgroup's fixed share
6740 * of the ancestor's claim to protection, any unutilized -
6741 * "floating" - protection from up the tree is distributed in
6742 * proportion to each cgroup's *usage*. This makes the protection
6743 * neutral wrt sibling cgroups and lets them compete freely over
6744 * the shared parental protection budget, but it protects the
6745 * subtree as a whole from neighboring subtrees.
6747 * Note that 4. and 5. are not in conflict: 4. is about protecting
6748 * against immediate siblings whereas 5. is about protecting against
6749 * neighboring subtrees.
6751 static unsigned long effective_protection(unsigned long usage,
6752 unsigned long parent_usage,
6753 unsigned long setting,
6754 unsigned long parent_effective,
6755 unsigned long siblings_protected)
6757 unsigned long protected;
6760 protected = min(usage, setting);
6762 * If all cgroups at this level combined claim and use more
6763 * protection then what the parent affords them, distribute
6764 * shares in proportion to utilization.
6766 * We are using actual utilization rather than the statically
6767 * claimed protection in order to be work-conserving: claimed
6768 * but unused protection is available to siblings that would
6769 * otherwise get a smaller chunk than what they claimed.
6771 if (siblings_protected > parent_effective)
6772 return protected * parent_effective / siblings_protected;
6775 * Ok, utilized protection of all children is within what the
6776 * parent affords them, so we know whatever this child claims
6777 * and utilizes is effectively protected.
6779 * If there is unprotected usage beyond this value, reclaim
6780 * will apply pressure in proportion to that amount.
6782 * If there is unutilized protection, the cgroup will be fully
6783 * shielded from reclaim, but we do return a smaller value for
6784 * protection than what the group could enjoy in theory. This
6785 * is okay. With the overcommit distribution above, effective
6786 * protection is always dependent on how memory is actually
6787 * consumed among the siblings anyway.
6792 * If the children aren't claiming (all of) the protection
6793 * afforded to them by the parent, distribute the remainder in
6794 * proportion to the (unprotected) memory of each cgroup. That
6795 * way, cgroups that aren't explicitly prioritized wrt each
6796 * other compete freely over the allowance, but they are
6797 * collectively protected from neighboring trees.
6799 * We're using unprotected memory for the weight so that if
6800 * some cgroups DO claim explicit protection, we don't protect
6801 * the same bytes twice.
6803 * Check both usage and parent_usage against the respective
6804 * protected values. One should imply the other, but they
6805 * aren't read atomically - make sure the division is sane.
6807 if (!(cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT))
6809 if (parent_effective > siblings_protected &&
6810 parent_usage > siblings_protected &&
6811 usage > protected) {
6812 unsigned long unclaimed;
6814 unclaimed = parent_effective - siblings_protected;
6815 unclaimed *= usage - protected;
6816 unclaimed /= parent_usage - siblings_protected;
6825 * mem_cgroup_calculate_protection - check if memory consumption is in the normal range
6826 * @root: the top ancestor of the sub-tree being checked
6827 * @memcg: the memory cgroup to check
6829 * WARNING: This function is not stateless! It can only be used as part
6830 * of a top-down tree iteration, not for isolated queries.
6832 void mem_cgroup_calculate_protection(struct mem_cgroup *root,
6833 struct mem_cgroup *memcg)
6835 unsigned long usage, parent_usage;
6836 struct mem_cgroup *parent;
6838 if (mem_cgroup_disabled())
6842 root = root_mem_cgroup;
6845 * Effective values of the reclaim targets are ignored so they
6846 * can be stale. Have a look at mem_cgroup_protection for more
6848 * TODO: calculation should be more robust so that we do not need
6849 * that special casing.
6854 usage = page_counter_read(&memcg->memory);
6858 parent = parent_mem_cgroup(memcg);
6860 if (parent == root) {
6861 memcg->memory.emin = READ_ONCE(memcg->memory.min);
6862 memcg->memory.elow = READ_ONCE(memcg->memory.low);
6866 parent_usage = page_counter_read(&parent->memory);
6868 WRITE_ONCE(memcg->memory.emin, effective_protection(usage, parent_usage,
6869 READ_ONCE(memcg->memory.min),
6870 READ_ONCE(parent->memory.emin),
6871 atomic_long_read(&parent->memory.children_min_usage)));
6873 WRITE_ONCE(memcg->memory.elow, effective_protection(usage, parent_usage,
6874 READ_ONCE(memcg->memory.low),
6875 READ_ONCE(parent->memory.elow),
6876 atomic_long_read(&parent->memory.children_low_usage)));
6879 static int charge_memcg(struct folio *folio, struct mem_cgroup *memcg,
6882 long nr_pages = folio_nr_pages(folio);
6885 ret = try_charge(memcg, gfp, nr_pages);
6889 css_get(&memcg->css);
6890 commit_charge(folio, memcg);
6892 local_irq_disable();
6893 mem_cgroup_charge_statistics(memcg, nr_pages);
6894 memcg_check_events(memcg, folio_nid(folio));
6900 int __mem_cgroup_charge(struct folio *folio, struct mm_struct *mm, gfp_t gfp)
6902 struct mem_cgroup *memcg;
6905 memcg = get_mem_cgroup_from_mm(mm);
6906 ret = charge_memcg(folio, memcg, gfp);
6907 css_put(&memcg->css);
6913 * mem_cgroup_swapin_charge_folio - Charge a newly allocated folio for swapin.
6914 * @folio: folio to charge.
6915 * @mm: mm context of the victim
6916 * @gfp: reclaim mode
6917 * @entry: swap entry for which the folio is allocated
6919 * This function charges a folio allocated for swapin. Please call this before
6920 * adding the folio to the swapcache.
6922 * Returns 0 on success. Otherwise, an error code is returned.
6924 int mem_cgroup_swapin_charge_folio(struct folio *folio, struct mm_struct *mm,
6925 gfp_t gfp, swp_entry_t entry)
6927 struct mem_cgroup *memcg;
6931 if (mem_cgroup_disabled())
6934 id = lookup_swap_cgroup_id(entry);
6936 memcg = mem_cgroup_from_id(id);
6937 if (!memcg || !css_tryget_online(&memcg->css))
6938 memcg = get_mem_cgroup_from_mm(mm);
6941 ret = charge_memcg(folio, memcg, gfp);
6943 css_put(&memcg->css);
6948 * mem_cgroup_swapin_uncharge_swap - uncharge swap slot
6949 * @entry: swap entry for which the page is charged
6951 * Call this function after successfully adding the charged page to swapcache.
6953 * Note: This function assumes the page for which swap slot is being uncharged
6956 void mem_cgroup_swapin_uncharge_swap(swp_entry_t entry)
6959 * Cgroup1's unified memory+swap counter has been charged with the
6960 * new swapcache page, finish the transfer by uncharging the swap
6961 * slot. The swap slot would also get uncharged when it dies, but
6962 * it can stick around indefinitely and we'd count the page twice
6965 * Cgroup2 has separate resource counters for memory and swap,
6966 * so this is a non-issue here. Memory and swap charge lifetimes
6967 * correspond 1:1 to page and swap slot lifetimes: we charge the
6968 * page to memory here, and uncharge swap when the slot is freed.
6970 if (!mem_cgroup_disabled() && do_memsw_account()) {
6972 * The swap entry might not get freed for a long time,
6973 * let's not wait for it. The page already received a
6974 * memory+swap charge, drop the swap entry duplicate.
6976 mem_cgroup_uncharge_swap(entry, 1);
6980 struct uncharge_gather {
6981 struct mem_cgroup *memcg;
6982 unsigned long nr_memory;
6983 unsigned long pgpgout;
6984 unsigned long nr_kmem;
6988 static inline void uncharge_gather_clear(struct uncharge_gather *ug)
6990 memset(ug, 0, sizeof(*ug));
6993 static void uncharge_batch(const struct uncharge_gather *ug)
6995 unsigned long flags;
6997 if (ug->nr_memory) {
6998 page_counter_uncharge(&ug->memcg->memory, ug->nr_memory);
6999 if (do_memsw_account())
7000 page_counter_uncharge(&ug->memcg->memsw, ug->nr_memory);
7002 memcg_account_kmem(ug->memcg, -ug->nr_kmem);
7003 memcg_oom_recover(ug->memcg);
7006 local_irq_save(flags);
7007 __count_memcg_events(ug->memcg, PGPGOUT, ug->pgpgout);
7008 __this_cpu_add(ug->memcg->vmstats_percpu->nr_page_events, ug->nr_memory);
7009 memcg_check_events(ug->memcg, ug->nid);
7010 local_irq_restore(flags);
7012 /* drop reference from uncharge_folio */
7013 css_put(&ug->memcg->css);
7016 static void uncharge_folio(struct folio *folio, struct uncharge_gather *ug)
7019 struct mem_cgroup *memcg;
7020 struct obj_cgroup *objcg;
7022 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
7025 * Nobody should be changing or seriously looking at
7026 * folio memcg or objcg at this point, we have fully
7027 * exclusive access to the folio.
7029 if (folio_memcg_kmem(folio)) {
7030 objcg = __folio_objcg(folio);
7032 * This get matches the put at the end of the function and
7033 * kmem pages do not hold memcg references anymore.
7035 memcg = get_mem_cgroup_from_objcg(objcg);
7037 memcg = __folio_memcg(folio);
7043 if (ug->memcg != memcg) {
7046 uncharge_gather_clear(ug);
7049 ug->nid = folio_nid(folio);
7051 /* pairs with css_put in uncharge_batch */
7052 css_get(&memcg->css);
7055 nr_pages = folio_nr_pages(folio);
7057 if (folio_memcg_kmem(folio)) {
7058 ug->nr_memory += nr_pages;
7059 ug->nr_kmem += nr_pages;
7061 folio->memcg_data = 0;
7062 obj_cgroup_put(objcg);
7064 /* LRU pages aren't accounted at the root level */
7065 if (!mem_cgroup_is_root(memcg))
7066 ug->nr_memory += nr_pages;
7069 folio->memcg_data = 0;
7072 css_put(&memcg->css);
7075 void __mem_cgroup_uncharge(struct folio *folio)
7077 struct uncharge_gather ug;
7079 /* Don't touch folio->lru of any random page, pre-check: */
7080 if (!folio_memcg(folio))
7083 uncharge_gather_clear(&ug);
7084 uncharge_folio(folio, &ug);
7085 uncharge_batch(&ug);
7089 * __mem_cgroup_uncharge_list - uncharge a list of page
7090 * @page_list: list of pages to uncharge
7092 * Uncharge a list of pages previously charged with
7093 * __mem_cgroup_charge().
7095 void __mem_cgroup_uncharge_list(struct list_head *page_list)
7097 struct uncharge_gather ug;
7098 struct folio *folio;
7100 uncharge_gather_clear(&ug);
7101 list_for_each_entry(folio, page_list, lru)
7102 uncharge_folio(folio, &ug);
7104 uncharge_batch(&ug);
7108 * mem_cgroup_migrate - Charge a folio's replacement.
7109 * @old: Currently circulating folio.
7110 * @new: Replacement folio.
7112 * Charge @new as a replacement folio for @old. @old will
7113 * be uncharged upon free.
7115 * Both folios must be locked, @new->mapping must be set up.
7117 void mem_cgroup_migrate(struct folio *old, struct folio *new)
7119 struct mem_cgroup *memcg;
7120 long nr_pages = folio_nr_pages(new);
7121 unsigned long flags;
7123 VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
7124 VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
7125 VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
7126 VM_BUG_ON_FOLIO(folio_nr_pages(old) != nr_pages, new);
7128 if (mem_cgroup_disabled())
7131 /* Page cache replacement: new folio already charged? */
7132 if (folio_memcg(new))
7135 memcg = folio_memcg(old);
7136 VM_WARN_ON_ONCE_FOLIO(!memcg, old);
7140 /* Force-charge the new page. The old one will be freed soon */
7141 if (!mem_cgroup_is_root(memcg)) {
7142 page_counter_charge(&memcg->memory, nr_pages);
7143 if (do_memsw_account())
7144 page_counter_charge(&memcg->memsw, nr_pages);
7147 css_get(&memcg->css);
7148 commit_charge(new, memcg);
7150 local_irq_save(flags);
7151 mem_cgroup_charge_statistics(memcg, nr_pages);
7152 memcg_check_events(memcg, folio_nid(new));
7153 local_irq_restore(flags);
7156 DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
7157 EXPORT_SYMBOL(memcg_sockets_enabled_key);
7159 void mem_cgroup_sk_alloc(struct sock *sk)
7161 struct mem_cgroup *memcg;
7163 if (!mem_cgroup_sockets_enabled)
7166 /* Do not associate the sock with unrelated interrupted task's memcg. */
7171 memcg = mem_cgroup_from_task(current);
7172 if (memcg == root_mem_cgroup)
7174 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg->tcpmem_active)
7176 if (css_tryget(&memcg->css))
7177 sk->sk_memcg = memcg;
7182 void mem_cgroup_sk_free(struct sock *sk)
7185 css_put(&sk->sk_memcg->css);
7189 * mem_cgroup_charge_skmem - charge socket memory
7190 * @memcg: memcg to charge
7191 * @nr_pages: number of pages to charge
7192 * @gfp_mask: reclaim mode
7194 * Charges @nr_pages to @memcg. Returns %true if the charge fit within
7195 * @memcg's configured limit, %false if it doesn't.
7197 bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages,
7200 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
7201 struct page_counter *fail;
7203 if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) {
7204 memcg->tcpmem_pressure = 0;
7207 memcg->tcpmem_pressure = 1;
7208 if (gfp_mask & __GFP_NOFAIL) {
7209 page_counter_charge(&memcg->tcpmem, nr_pages);
7215 if (try_charge(memcg, gfp_mask, nr_pages) == 0) {
7216 mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
7224 * mem_cgroup_uncharge_skmem - uncharge socket memory
7225 * @memcg: memcg to uncharge
7226 * @nr_pages: number of pages to uncharge
7228 void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
7230 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
7231 page_counter_uncharge(&memcg->tcpmem, nr_pages);
7235 mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
7237 refill_stock(memcg, nr_pages);
7240 static int __init cgroup_memory(char *s)
7244 while ((token = strsep(&s, ",")) != NULL) {
7247 if (!strcmp(token, "nosocket"))
7248 cgroup_memory_nosocket = true;
7249 if (!strcmp(token, "nokmem"))
7250 cgroup_memory_nokmem = true;
7254 __setup("cgroup.memory=", cgroup_memory);
7257 * subsys_initcall() for memory controller.
7259 * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
7260 * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
7261 * basically everything that doesn't depend on a specific mem_cgroup structure
7262 * should be initialized from here.
7264 static int __init mem_cgroup_init(void)
7269 * Currently s32 type (can refer to struct batched_lruvec_stat) is
7270 * used for per-memcg-per-cpu caching of per-node statistics. In order
7271 * to work fine, we should make sure that the overfill threshold can't
7272 * exceed S32_MAX / PAGE_SIZE.
7274 BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE);
7276 cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
7277 memcg_hotplug_cpu_dead);
7279 for_each_possible_cpu(cpu)
7280 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
7283 for_each_node(node) {
7284 struct mem_cgroup_tree_per_node *rtpn;
7286 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL,
7287 node_online(node) ? node : NUMA_NO_NODE);
7289 rtpn->rb_root = RB_ROOT;
7290 rtpn->rb_rightmost = NULL;
7291 spin_lock_init(&rtpn->lock);
7292 soft_limit_tree.rb_tree_per_node[node] = rtpn;
7297 subsys_initcall(mem_cgroup_init);
7300 static struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
7302 while (!refcount_inc_not_zero(&memcg->id.ref)) {
7304 * The root cgroup cannot be destroyed, so it's refcount must
7307 if (WARN_ON_ONCE(memcg == root_mem_cgroup)) {
7311 memcg = parent_mem_cgroup(memcg);
7313 memcg = root_mem_cgroup;
7319 * mem_cgroup_swapout - transfer a memsw charge to swap
7320 * @folio: folio whose memsw charge to transfer
7321 * @entry: swap entry to move the charge to
7323 * Transfer the memsw charge of @folio to @entry.
7325 void mem_cgroup_swapout(struct folio *folio, swp_entry_t entry)
7327 struct mem_cgroup *memcg, *swap_memcg;
7328 unsigned int nr_entries;
7329 unsigned short oldid;
7331 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
7332 VM_BUG_ON_FOLIO(folio_ref_count(folio), folio);
7334 if (mem_cgroup_disabled())
7337 if (!do_memsw_account())
7340 memcg = folio_memcg(folio);
7342 VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
7347 * In case the memcg owning these pages has been offlined and doesn't
7348 * have an ID allocated to it anymore, charge the closest online
7349 * ancestor for the swap instead and transfer the memory+swap charge.
7351 swap_memcg = mem_cgroup_id_get_online(memcg);
7352 nr_entries = folio_nr_pages(folio);
7353 /* Get references for the tail pages, too */
7355 mem_cgroup_id_get_many(swap_memcg, nr_entries - 1);
7356 oldid = swap_cgroup_record(entry, mem_cgroup_id(swap_memcg),
7358 VM_BUG_ON_FOLIO(oldid, folio);
7359 mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries);
7361 folio->memcg_data = 0;
7363 if (!mem_cgroup_is_root(memcg))
7364 page_counter_uncharge(&memcg->memory, nr_entries);
7366 if (memcg != swap_memcg) {
7367 if (!mem_cgroup_is_root(swap_memcg))
7368 page_counter_charge(&swap_memcg->memsw, nr_entries);
7369 page_counter_uncharge(&memcg->memsw, nr_entries);
7373 * Interrupts should be disabled here because the caller holds the
7374 * i_pages lock which is taken with interrupts-off. It is
7375 * important here to have the interrupts disabled because it is the
7376 * only synchronisation we have for updating the per-CPU variables.
7379 mem_cgroup_charge_statistics(memcg, -nr_entries);
7380 memcg_stats_unlock();
7381 memcg_check_events(memcg, folio_nid(folio));
7383 css_put(&memcg->css);
7387 * __mem_cgroup_try_charge_swap - try charging swap space for a folio
7388 * @folio: folio being added to swap
7389 * @entry: swap entry to charge
7391 * Try to charge @folio's memcg for the swap space at @entry.
7393 * Returns 0 on success, -ENOMEM on failure.
7395 int __mem_cgroup_try_charge_swap(struct folio *folio, swp_entry_t entry)
7397 unsigned int nr_pages = folio_nr_pages(folio);
7398 struct page_counter *counter;
7399 struct mem_cgroup *memcg;
7400 unsigned short oldid;
7402 if (do_memsw_account())
7405 memcg = folio_memcg(folio);
7407 VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
7412 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7416 memcg = mem_cgroup_id_get_online(memcg);
7418 if (!mem_cgroup_is_root(memcg) &&
7419 !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
7420 memcg_memory_event(memcg, MEMCG_SWAP_MAX);
7421 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7422 mem_cgroup_id_put(memcg);
7426 /* Get references for the tail pages, too */
7428 mem_cgroup_id_get_many(memcg, nr_pages - 1);
7429 oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg), nr_pages);
7430 VM_BUG_ON_FOLIO(oldid, folio);
7431 mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
7437 * __mem_cgroup_uncharge_swap - uncharge swap space
7438 * @entry: swap entry to uncharge
7439 * @nr_pages: the amount of swap space to uncharge
7441 void __mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
7443 struct mem_cgroup *memcg;
7446 if (mem_cgroup_disabled())
7449 id = swap_cgroup_record(entry, 0, nr_pages);
7451 memcg = mem_cgroup_from_id(id);
7453 if (!mem_cgroup_is_root(memcg)) {
7454 if (do_memsw_account())
7455 page_counter_uncharge(&memcg->memsw, nr_pages);
7457 page_counter_uncharge(&memcg->swap, nr_pages);
7459 mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
7460 mem_cgroup_id_put_many(memcg, nr_pages);
7465 long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
7467 long nr_swap_pages = get_nr_swap_pages();
7469 if (mem_cgroup_disabled() || do_memsw_account())
7470 return nr_swap_pages;
7471 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg))
7472 nr_swap_pages = min_t(long, nr_swap_pages,
7473 READ_ONCE(memcg->swap.max) -
7474 page_counter_read(&memcg->swap));
7475 return nr_swap_pages;
7478 bool mem_cgroup_swap_full(struct folio *folio)
7480 struct mem_cgroup *memcg;
7482 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
7486 if (do_memsw_account())
7489 memcg = folio_memcg(folio);
7493 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg)) {
7494 unsigned long usage = page_counter_read(&memcg->swap);
7496 if (usage * 2 >= READ_ONCE(memcg->swap.high) ||
7497 usage * 2 >= READ_ONCE(memcg->swap.max))
7504 static int __init setup_swap_account(char *s)
7506 pr_warn_once("The swapaccount= commandline option is deprecated. "
7507 "Please report your usecase to linux-mm@kvack.org if you "
7508 "depend on this functionality.\n");
7511 __setup("swapaccount=", setup_swap_account);
7513 static u64 swap_current_read(struct cgroup_subsys_state *css,
7516 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7518 return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
7521 static int swap_high_show(struct seq_file *m, void *v)
7523 return seq_puts_memcg_tunable(m,
7524 READ_ONCE(mem_cgroup_from_seq(m)->swap.high));
7527 static ssize_t swap_high_write(struct kernfs_open_file *of,
7528 char *buf, size_t nbytes, loff_t off)
7530 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7534 buf = strstrip(buf);
7535 err = page_counter_memparse(buf, "max", &high);
7539 page_counter_set_high(&memcg->swap, high);
7544 static int swap_max_show(struct seq_file *m, void *v)
7546 return seq_puts_memcg_tunable(m,
7547 READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
7550 static ssize_t swap_max_write(struct kernfs_open_file *of,
7551 char *buf, size_t nbytes, loff_t off)
7553 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7557 buf = strstrip(buf);
7558 err = page_counter_memparse(buf, "max", &max);
7562 xchg(&memcg->swap.max, max);
7567 static int swap_events_show(struct seq_file *m, void *v)
7569 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
7571 seq_printf(m, "high %lu\n",
7572 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH]));
7573 seq_printf(m, "max %lu\n",
7574 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
7575 seq_printf(m, "fail %lu\n",
7576 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
7581 static struct cftype swap_files[] = {
7583 .name = "swap.current",
7584 .flags = CFTYPE_NOT_ON_ROOT,
7585 .read_u64 = swap_current_read,
7588 .name = "swap.high",
7589 .flags = CFTYPE_NOT_ON_ROOT,
7590 .seq_show = swap_high_show,
7591 .write = swap_high_write,
7595 .flags = CFTYPE_NOT_ON_ROOT,
7596 .seq_show = swap_max_show,
7597 .write = swap_max_write,
7600 .name = "swap.events",
7601 .flags = CFTYPE_NOT_ON_ROOT,
7602 .file_offset = offsetof(struct mem_cgroup, swap_events_file),
7603 .seq_show = swap_events_show,
7608 static struct cftype memsw_files[] = {
7610 .name = "memsw.usage_in_bytes",
7611 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
7612 .read_u64 = mem_cgroup_read_u64,
7615 .name = "memsw.max_usage_in_bytes",
7616 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
7617 .write = mem_cgroup_reset,
7618 .read_u64 = mem_cgroup_read_u64,
7621 .name = "memsw.limit_in_bytes",
7622 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
7623 .write = mem_cgroup_write,
7624 .read_u64 = mem_cgroup_read_u64,
7627 .name = "memsw.failcnt",
7628 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
7629 .write = mem_cgroup_reset,
7630 .read_u64 = mem_cgroup_read_u64,
7632 { }, /* terminate */
7635 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
7637 * obj_cgroup_may_zswap - check if this cgroup can zswap
7638 * @objcg: the object cgroup
7640 * Check if the hierarchical zswap limit has been reached.
7642 * This doesn't check for specific headroom, and it is not atomic
7643 * either. But with zswap, the size of the allocation is only known
7644 * once compression has occured, and this optimistic pre-check avoids
7645 * spending cycles on compression when there is already no room left
7646 * or zswap is disabled altogether somewhere in the hierarchy.
7648 bool obj_cgroup_may_zswap(struct obj_cgroup *objcg)
7650 struct mem_cgroup *memcg, *original_memcg;
7653 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
7656 original_memcg = get_mem_cgroup_from_objcg(objcg);
7657 for (memcg = original_memcg; memcg != root_mem_cgroup;
7658 memcg = parent_mem_cgroup(memcg)) {
7659 unsigned long max = READ_ONCE(memcg->zswap_max);
7660 unsigned long pages;
7662 if (max == PAGE_COUNTER_MAX)
7669 cgroup_rstat_flush(memcg->css.cgroup);
7670 pages = memcg_page_state(memcg, MEMCG_ZSWAP_B) / PAGE_SIZE;
7676 mem_cgroup_put(original_memcg);
7681 * obj_cgroup_charge_zswap - charge compression backend memory
7682 * @objcg: the object cgroup
7683 * @size: size of compressed object
7685 * This forces the charge after obj_cgroup_may_swap() allowed
7686 * compression and storage in zwap for this cgroup to go ahead.
7688 void obj_cgroup_charge_zswap(struct obj_cgroup *objcg, size_t size)
7690 struct mem_cgroup *memcg;
7692 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
7695 VM_WARN_ON_ONCE(!(current->flags & PF_MEMALLOC));
7697 /* PF_MEMALLOC context, charging must succeed */
7698 if (obj_cgroup_charge(objcg, GFP_KERNEL, size))
7702 memcg = obj_cgroup_memcg(objcg);
7703 mod_memcg_state(memcg, MEMCG_ZSWAP_B, size);
7704 mod_memcg_state(memcg, MEMCG_ZSWAPPED, 1);
7709 * obj_cgroup_uncharge_zswap - uncharge compression backend memory
7710 * @objcg: the object cgroup
7711 * @size: size of compressed object
7713 * Uncharges zswap memory on page in.
7715 void obj_cgroup_uncharge_zswap(struct obj_cgroup *objcg, size_t size)
7717 struct mem_cgroup *memcg;
7719 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
7722 obj_cgroup_uncharge(objcg, size);
7725 memcg = obj_cgroup_memcg(objcg);
7726 mod_memcg_state(memcg, MEMCG_ZSWAP_B, -size);
7727 mod_memcg_state(memcg, MEMCG_ZSWAPPED, -1);
7731 static u64 zswap_current_read(struct cgroup_subsys_state *css,
7734 cgroup_rstat_flush(css->cgroup);
7735 return memcg_page_state(mem_cgroup_from_css(css), MEMCG_ZSWAP_B);
7738 static int zswap_max_show(struct seq_file *m, void *v)
7740 return seq_puts_memcg_tunable(m,
7741 READ_ONCE(mem_cgroup_from_seq(m)->zswap_max));
7744 static ssize_t zswap_max_write(struct kernfs_open_file *of,
7745 char *buf, size_t nbytes, loff_t off)
7747 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7751 buf = strstrip(buf);
7752 err = page_counter_memparse(buf, "max", &max);
7756 xchg(&memcg->zswap_max, max);
7761 static struct cftype zswap_files[] = {
7763 .name = "zswap.current",
7764 .flags = CFTYPE_NOT_ON_ROOT,
7765 .read_u64 = zswap_current_read,
7768 .name = "zswap.max",
7769 .flags = CFTYPE_NOT_ON_ROOT,
7770 .seq_show = zswap_max_show,
7771 .write = zswap_max_write,
7775 #endif /* CONFIG_MEMCG_KMEM && CONFIG_ZSWAP */
7777 static int __init mem_cgroup_swap_init(void)
7779 if (mem_cgroup_disabled())
7782 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files));
7783 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files));
7784 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
7785 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, zswap_files));
7789 subsys_initcall(mem_cgroup_swap_init);
7791 #endif /* CONFIG_SWAP */