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 /* Whether the swap controller is active */
92 #ifdef CONFIG_MEMCG_SWAP
93 static bool cgroup_memory_noswap __ro_after_init;
95 #define cgroup_memory_noswap 1
98 #ifdef CONFIG_CGROUP_WRITEBACK
99 static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq);
102 /* Whether legacy memory+swap accounting is active */
103 static bool do_memsw_account(void)
105 return !cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_noswap;
108 #define THRESHOLDS_EVENTS_TARGET 128
109 #define SOFTLIMIT_EVENTS_TARGET 1024
112 * Cgroups above their limits are maintained in a RB-Tree, independent of
113 * their hierarchy representation
116 struct mem_cgroup_tree_per_node {
117 struct rb_root rb_root;
118 struct rb_node *rb_rightmost;
122 struct mem_cgroup_tree {
123 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
126 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
129 struct mem_cgroup_eventfd_list {
130 struct list_head list;
131 struct eventfd_ctx *eventfd;
135 * cgroup_event represents events which userspace want to receive.
137 struct mem_cgroup_event {
139 * memcg which the event belongs to.
141 struct mem_cgroup *memcg;
143 * eventfd to signal userspace about the event.
145 struct eventfd_ctx *eventfd;
147 * Each of these stored in a list by the cgroup.
149 struct list_head list;
151 * register_event() callback will be used to add new userspace
152 * waiter for changes related to this event. Use eventfd_signal()
153 * on eventfd to send notification to userspace.
155 int (*register_event)(struct mem_cgroup *memcg,
156 struct eventfd_ctx *eventfd, const char *args);
158 * unregister_event() callback will be called when userspace closes
159 * the eventfd or on cgroup removing. This callback must be set,
160 * if you want provide notification functionality.
162 void (*unregister_event)(struct mem_cgroup *memcg,
163 struct eventfd_ctx *eventfd);
165 * All fields below needed to unregister event when
166 * userspace closes eventfd.
169 wait_queue_head_t *wqh;
170 wait_queue_entry_t wait;
171 struct work_struct remove;
174 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
175 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
177 /* Stuffs for move charges at task migration. */
179 * Types of charges to be moved.
181 #define MOVE_ANON 0x1U
182 #define MOVE_FILE 0x2U
183 #define MOVE_MASK (MOVE_ANON | MOVE_FILE)
185 /* "mc" and its members are protected by cgroup_mutex */
186 static struct move_charge_struct {
187 spinlock_t lock; /* for from, to */
188 struct mm_struct *mm;
189 struct mem_cgroup *from;
190 struct mem_cgroup *to;
192 unsigned long precharge;
193 unsigned long moved_charge;
194 unsigned long moved_swap;
195 struct task_struct *moving_task; /* a task moving charges */
196 wait_queue_head_t waitq; /* a waitq for other context */
198 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
199 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
203 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
204 * limit reclaim to prevent infinite loops, if they ever occur.
206 #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
207 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
209 /* for encoding cft->private value on file */
217 #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
218 #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
219 #define MEMFILE_ATTR(val) ((val) & 0xffff)
222 * Iteration constructs for visiting all cgroups (under a tree). If
223 * loops are exited prematurely (break), mem_cgroup_iter_break() must
224 * be used for reference counting.
226 #define for_each_mem_cgroup_tree(iter, root) \
227 for (iter = mem_cgroup_iter(root, NULL, NULL); \
229 iter = mem_cgroup_iter(root, iter, NULL))
231 #define for_each_mem_cgroup(iter) \
232 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
234 iter = mem_cgroup_iter(NULL, iter, NULL))
236 static inline bool task_is_dying(void)
238 return tsk_is_oom_victim(current) || fatal_signal_pending(current) ||
239 (current->flags & PF_EXITING);
242 /* Some nice accessors for the vmpressure. */
243 struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
246 memcg = root_mem_cgroup;
247 return &memcg->vmpressure;
250 struct mem_cgroup *vmpressure_to_memcg(struct vmpressure *vmpr)
252 return container_of(vmpr, struct mem_cgroup, vmpressure);
255 #ifdef CONFIG_MEMCG_KMEM
256 static DEFINE_SPINLOCK(objcg_lock);
258 bool mem_cgroup_kmem_disabled(void)
260 return cgroup_memory_nokmem;
263 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
264 unsigned int nr_pages);
266 static void obj_cgroup_release(struct percpu_ref *ref)
268 struct obj_cgroup *objcg = container_of(ref, struct obj_cgroup, refcnt);
269 unsigned int nr_bytes;
270 unsigned int nr_pages;
274 * At this point all allocated objects are freed, and
275 * objcg->nr_charged_bytes can't have an arbitrary byte value.
276 * However, it can be PAGE_SIZE or (x * PAGE_SIZE).
278 * The following sequence can lead to it:
279 * 1) CPU0: objcg == stock->cached_objcg
280 * 2) CPU1: we do a small allocation (e.g. 92 bytes),
281 * PAGE_SIZE bytes are charged
282 * 3) CPU1: a process from another memcg is allocating something,
283 * the stock if flushed,
284 * objcg->nr_charged_bytes = PAGE_SIZE - 92
285 * 5) CPU0: we do release this object,
286 * 92 bytes are added to stock->nr_bytes
287 * 6) CPU0: stock is flushed,
288 * 92 bytes are added to objcg->nr_charged_bytes
290 * In the result, nr_charged_bytes == PAGE_SIZE.
291 * This page will be uncharged in obj_cgroup_release().
293 nr_bytes = atomic_read(&objcg->nr_charged_bytes);
294 WARN_ON_ONCE(nr_bytes & (PAGE_SIZE - 1));
295 nr_pages = nr_bytes >> PAGE_SHIFT;
298 obj_cgroup_uncharge_pages(objcg, nr_pages);
300 spin_lock_irqsave(&objcg_lock, flags);
301 list_del(&objcg->list);
302 spin_unlock_irqrestore(&objcg_lock, flags);
304 percpu_ref_exit(ref);
305 kfree_rcu(objcg, rcu);
308 static struct obj_cgroup *obj_cgroup_alloc(void)
310 struct obj_cgroup *objcg;
313 objcg = kzalloc(sizeof(struct obj_cgroup), GFP_KERNEL);
317 ret = percpu_ref_init(&objcg->refcnt, obj_cgroup_release, 0,
323 INIT_LIST_HEAD(&objcg->list);
327 static void memcg_reparent_objcgs(struct mem_cgroup *memcg,
328 struct mem_cgroup *parent)
330 struct obj_cgroup *objcg, *iter;
332 objcg = rcu_replace_pointer(memcg->objcg, NULL, true);
334 spin_lock_irq(&objcg_lock);
336 /* 1) Ready to reparent active objcg. */
337 list_add(&objcg->list, &memcg->objcg_list);
338 /* 2) Reparent active objcg and already reparented objcgs to parent. */
339 list_for_each_entry(iter, &memcg->objcg_list, list)
340 WRITE_ONCE(iter->memcg, parent);
341 /* 3) Move already reparented objcgs to the parent's list */
342 list_splice(&memcg->objcg_list, &parent->objcg_list);
344 spin_unlock_irq(&objcg_lock);
346 percpu_ref_kill(&objcg->refcnt);
350 * A lot of the calls to the cache allocation functions are expected to be
351 * inlined by the compiler. Since the calls to memcg_slab_pre_alloc_hook() are
352 * conditional to this static branch, we'll have to allow modules that does
353 * kmem_cache_alloc and the such to see this symbol as well
355 DEFINE_STATIC_KEY_FALSE(memcg_kmem_enabled_key);
356 EXPORT_SYMBOL(memcg_kmem_enabled_key);
360 * mem_cgroup_css_from_page - css of the memcg associated with a page
361 * @page: page of interest
363 * If memcg is bound to the default hierarchy, css of the memcg associated
364 * with @page is returned. The returned css remains associated with @page
365 * until it is released.
367 * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
370 struct cgroup_subsys_state *mem_cgroup_css_from_page(struct page *page)
372 struct mem_cgroup *memcg;
374 memcg = page_memcg(page);
376 if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
377 memcg = root_mem_cgroup;
383 * page_cgroup_ino - return inode number of the memcg a page is charged to
386 * Look up the closest online ancestor of the memory cgroup @page is charged to
387 * and return its inode number or 0 if @page is not charged to any cgroup. It
388 * is safe to call this function without holding a reference to @page.
390 * Note, this function is inherently racy, because there is nothing to prevent
391 * the cgroup inode from getting torn down and potentially reallocated a moment
392 * after page_cgroup_ino() returns, so it only should be used by callers that
393 * do not care (such as procfs interfaces).
395 ino_t page_cgroup_ino(struct page *page)
397 struct mem_cgroup *memcg;
398 unsigned long ino = 0;
401 memcg = page_memcg_check(page);
403 while (memcg && !(memcg->css.flags & CSS_ONLINE))
404 memcg = parent_mem_cgroup(memcg);
406 ino = cgroup_ino(memcg->css.cgroup);
411 static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_node *mz,
412 struct mem_cgroup_tree_per_node *mctz,
413 unsigned long new_usage_in_excess)
415 struct rb_node **p = &mctz->rb_root.rb_node;
416 struct rb_node *parent = NULL;
417 struct mem_cgroup_per_node *mz_node;
418 bool rightmost = true;
423 mz->usage_in_excess = new_usage_in_excess;
424 if (!mz->usage_in_excess)
428 mz_node = rb_entry(parent, struct mem_cgroup_per_node,
430 if (mz->usage_in_excess < mz_node->usage_in_excess) {
439 mctz->rb_rightmost = &mz->tree_node;
441 rb_link_node(&mz->tree_node, parent, p);
442 rb_insert_color(&mz->tree_node, &mctz->rb_root);
446 static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
447 struct mem_cgroup_tree_per_node *mctz)
452 if (&mz->tree_node == mctz->rb_rightmost)
453 mctz->rb_rightmost = rb_prev(&mz->tree_node);
455 rb_erase(&mz->tree_node, &mctz->rb_root);
459 static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
460 struct mem_cgroup_tree_per_node *mctz)
464 spin_lock_irqsave(&mctz->lock, flags);
465 __mem_cgroup_remove_exceeded(mz, mctz);
466 spin_unlock_irqrestore(&mctz->lock, flags);
469 static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
471 unsigned long nr_pages = page_counter_read(&memcg->memory);
472 unsigned long soft_limit = READ_ONCE(memcg->soft_limit);
473 unsigned long excess = 0;
475 if (nr_pages > soft_limit)
476 excess = nr_pages - soft_limit;
481 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, int nid)
483 unsigned long excess;
484 struct mem_cgroup_per_node *mz;
485 struct mem_cgroup_tree_per_node *mctz;
487 mctz = soft_limit_tree.rb_tree_per_node[nid];
491 * Necessary to update all ancestors when hierarchy is used.
492 * because their event counter is not touched.
494 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
495 mz = memcg->nodeinfo[nid];
496 excess = soft_limit_excess(memcg);
498 * We have to update the tree if mz is on RB-tree or
499 * mem is over its softlimit.
501 if (excess || mz->on_tree) {
504 spin_lock_irqsave(&mctz->lock, flags);
505 /* if on-tree, remove it */
507 __mem_cgroup_remove_exceeded(mz, mctz);
509 * Insert again. mz->usage_in_excess will be updated.
510 * If excess is 0, no tree ops.
512 __mem_cgroup_insert_exceeded(mz, mctz, excess);
513 spin_unlock_irqrestore(&mctz->lock, flags);
518 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
520 struct mem_cgroup_tree_per_node *mctz;
521 struct mem_cgroup_per_node *mz;
525 mz = memcg->nodeinfo[nid];
526 mctz = soft_limit_tree.rb_tree_per_node[nid];
528 mem_cgroup_remove_exceeded(mz, mctz);
532 static struct mem_cgroup_per_node *
533 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
535 struct mem_cgroup_per_node *mz;
539 if (!mctz->rb_rightmost)
540 goto done; /* Nothing to reclaim from */
542 mz = rb_entry(mctz->rb_rightmost,
543 struct mem_cgroup_per_node, tree_node);
545 * Remove the node now but someone else can add it back,
546 * we will to add it back at the end of reclaim to its correct
547 * position in the tree.
549 __mem_cgroup_remove_exceeded(mz, mctz);
550 if (!soft_limit_excess(mz->memcg) ||
551 !css_tryget(&mz->memcg->css))
557 static struct mem_cgroup_per_node *
558 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
560 struct mem_cgroup_per_node *mz;
562 spin_lock_irq(&mctz->lock);
563 mz = __mem_cgroup_largest_soft_limit_node(mctz);
564 spin_unlock_irq(&mctz->lock);
569 * memcg and lruvec stats flushing
571 * Many codepaths leading to stats update or read are performance sensitive and
572 * adding stats flushing in such codepaths is not desirable. So, to optimize the
573 * flushing the kernel does:
575 * 1) Periodically and asynchronously flush the stats every 2 seconds to not let
576 * rstat update tree grow unbounded.
578 * 2) Flush the stats synchronously on reader side only when there are more than
579 * (MEMCG_CHARGE_BATCH * nr_cpus) update events. Though this optimization
580 * will let stats be out of sync by atmost (MEMCG_CHARGE_BATCH * nr_cpus) but
581 * only for 2 seconds due to (1).
583 static void flush_memcg_stats_dwork(struct work_struct *w);
584 static DECLARE_DEFERRABLE_WORK(stats_flush_dwork, flush_memcg_stats_dwork);
585 static DEFINE_SPINLOCK(stats_flush_lock);
586 static DEFINE_PER_CPU(unsigned int, stats_updates);
587 static atomic_t stats_flush_threshold = ATOMIC_INIT(0);
588 static u64 flush_next_time;
590 #define FLUSH_TIME (2UL*HZ)
593 * Accessors to ensure that preemption is disabled on PREEMPT_RT because it can
594 * not rely on this as part of an acquired spinlock_t lock. These functions are
595 * never used in hardirq context on PREEMPT_RT and therefore disabling preemtion
598 static void memcg_stats_lock(void)
600 #ifdef CONFIG_PREEMPT_RT
603 VM_BUG_ON(!irqs_disabled());
607 static void __memcg_stats_lock(void)
609 #ifdef CONFIG_PREEMPT_RT
614 static void memcg_stats_unlock(void)
616 #ifdef CONFIG_PREEMPT_RT
621 static inline void memcg_rstat_updated(struct mem_cgroup *memcg, int val)
625 cgroup_rstat_updated(memcg->css.cgroup, smp_processor_id());
627 x = __this_cpu_add_return(stats_updates, abs(val));
628 if (x > MEMCG_CHARGE_BATCH) {
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);
666 * __mod_memcg_state - update cgroup memory statistics
667 * @memcg: the memory cgroup
668 * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item
669 * @val: delta to add to the counter, can be negative
671 void __mod_memcg_state(struct mem_cgroup *memcg, int idx, int val)
673 if (mem_cgroup_disabled())
676 __this_cpu_add(memcg->vmstats_percpu->state[idx], val);
677 memcg_rstat_updated(memcg, val);
680 /* idx can be of type enum memcg_stat_item or node_stat_item. */
681 static unsigned long memcg_page_state_local(struct mem_cgroup *memcg, int idx)
686 for_each_possible_cpu(cpu)
687 x += per_cpu(memcg->vmstats_percpu->state[idx], cpu);
695 void __mod_memcg_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
698 struct mem_cgroup_per_node *pn;
699 struct mem_cgroup *memcg;
701 pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
705 * The caller from rmap relay on disabled preemption becase they never
706 * update their counter from in-interrupt context. For these two
707 * counters we check that the update is never performed from an
708 * interrupt context while other caller need to have disabled interrupt.
710 __memcg_stats_lock();
711 if (IS_ENABLED(CONFIG_DEBUG_VM) && !IS_ENABLED(CONFIG_PREEMPT_RT)) {
716 case NR_SHMEM_PMDMAPPED:
717 case NR_FILE_PMDMAPPED:
718 WARN_ON_ONCE(!in_task());
721 WARN_ON_ONCE(!irqs_disabled());
726 __this_cpu_add(memcg->vmstats_percpu->state[idx], val);
729 __this_cpu_add(pn->lruvec_stats_percpu->state[idx], val);
731 memcg_rstat_updated(memcg, val);
732 memcg_stats_unlock();
736 * __mod_lruvec_state - update lruvec memory statistics
737 * @lruvec: the lruvec
738 * @idx: the stat item
739 * @val: delta to add to the counter, can be negative
741 * The lruvec is the intersection of the NUMA node and a cgroup. This
742 * function updates the all three counters that are affected by a
743 * change of state at this level: per-node, per-cgroup, per-lruvec.
745 void __mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
749 __mod_node_page_state(lruvec_pgdat(lruvec), idx, val);
751 /* Update memcg and lruvec */
752 if (!mem_cgroup_disabled())
753 __mod_memcg_lruvec_state(lruvec, idx, val);
756 void __mod_lruvec_page_state(struct page *page, enum node_stat_item idx,
759 struct page *head = compound_head(page); /* rmap on tail pages */
760 struct mem_cgroup *memcg;
761 pg_data_t *pgdat = page_pgdat(page);
762 struct lruvec *lruvec;
765 memcg = page_memcg(head);
766 /* Untracked pages have no memcg, no lruvec. Update only the node */
769 __mod_node_page_state(pgdat, idx, val);
773 lruvec = mem_cgroup_lruvec(memcg, pgdat);
774 __mod_lruvec_state(lruvec, idx, val);
777 EXPORT_SYMBOL(__mod_lruvec_page_state);
779 void __mod_lruvec_kmem_state(void *p, enum node_stat_item idx, int val)
781 pg_data_t *pgdat = page_pgdat(virt_to_page(p));
782 struct mem_cgroup *memcg;
783 struct lruvec *lruvec;
786 memcg = mem_cgroup_from_slab_obj(p);
789 * Untracked pages have no memcg, no lruvec. Update only the
790 * node. If we reparent the slab objects to the root memcg,
791 * when we free the slab object, we need to update the per-memcg
792 * vmstats to keep it correct for the root memcg.
795 __mod_node_page_state(pgdat, idx, val);
797 lruvec = mem_cgroup_lruvec(memcg, pgdat);
798 __mod_lruvec_state(lruvec, idx, val);
804 * __count_memcg_events - account VM events in a cgroup
805 * @memcg: the memory cgroup
806 * @idx: the event item
807 * @count: the number of events that occurred
809 void __count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx,
812 if (mem_cgroup_disabled())
816 __this_cpu_add(memcg->vmstats_percpu->events[idx], count);
817 memcg_rstat_updated(memcg, count);
818 memcg_stats_unlock();
821 static unsigned long memcg_events(struct mem_cgroup *memcg, int event)
823 return READ_ONCE(memcg->vmstats.events[event]);
826 static unsigned long memcg_events_local(struct mem_cgroup *memcg, int event)
831 for_each_possible_cpu(cpu)
832 x += per_cpu(memcg->vmstats_percpu->events[event], cpu);
836 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
839 /* pagein of a big page is an event. So, ignore page size */
841 __count_memcg_events(memcg, PGPGIN, 1);
843 __count_memcg_events(memcg, PGPGOUT, 1);
844 nr_pages = -nr_pages; /* for event */
847 __this_cpu_add(memcg->vmstats_percpu->nr_page_events, nr_pages);
850 static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
851 enum mem_cgroup_events_target target)
853 unsigned long val, next;
855 val = __this_cpu_read(memcg->vmstats_percpu->nr_page_events);
856 next = __this_cpu_read(memcg->vmstats_percpu->targets[target]);
857 /* from time_after() in jiffies.h */
858 if ((long)(next - val) < 0) {
860 case MEM_CGROUP_TARGET_THRESH:
861 next = val + THRESHOLDS_EVENTS_TARGET;
863 case MEM_CGROUP_TARGET_SOFTLIMIT:
864 next = val + SOFTLIMIT_EVENTS_TARGET;
869 __this_cpu_write(memcg->vmstats_percpu->targets[target], next);
876 * Check events in order.
879 static void memcg_check_events(struct mem_cgroup *memcg, int nid)
881 if (IS_ENABLED(CONFIG_PREEMPT_RT))
884 /* threshold event is triggered in finer grain than soft limit */
885 if (unlikely(mem_cgroup_event_ratelimit(memcg,
886 MEM_CGROUP_TARGET_THRESH))) {
889 do_softlimit = mem_cgroup_event_ratelimit(memcg,
890 MEM_CGROUP_TARGET_SOFTLIMIT);
891 mem_cgroup_threshold(memcg);
892 if (unlikely(do_softlimit))
893 mem_cgroup_update_tree(memcg, nid);
897 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
900 * mm_update_next_owner() may clear mm->owner to NULL
901 * if it races with swapoff, page migration, etc.
902 * So this can be called with p == NULL.
907 return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
909 EXPORT_SYMBOL(mem_cgroup_from_task);
911 static __always_inline struct mem_cgroup *active_memcg(void)
914 return this_cpu_read(int_active_memcg);
916 return current->active_memcg;
920 * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
921 * @mm: mm from which memcg should be extracted. It can be NULL.
923 * Obtain a reference on mm->memcg and returns it if successful. If mm
924 * is NULL, then the memcg is chosen as follows:
925 * 1) The active memcg, if set.
926 * 2) current->mm->memcg, if available
928 * If mem_cgroup is disabled, NULL is returned.
930 struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
932 struct mem_cgroup *memcg;
934 if (mem_cgroup_disabled())
938 * Page cache insertions can happen without an
939 * actual mm context, e.g. during disk probing
940 * on boot, loopback IO, acct() writes etc.
942 * No need to css_get on root memcg as the reference
943 * counting is disabled on the root level in the
944 * cgroup core. See CSS_NO_REF.
947 memcg = active_memcg();
948 if (unlikely(memcg)) {
949 /* remote memcg must hold a ref */
950 css_get(&memcg->css);
955 return root_mem_cgroup;
960 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
961 if (unlikely(!memcg))
962 memcg = root_mem_cgroup;
963 } while (!css_tryget(&memcg->css));
967 EXPORT_SYMBOL(get_mem_cgroup_from_mm);
969 static __always_inline bool memcg_kmem_bypass(void)
971 /* Allow remote memcg charging from any context. */
972 if (unlikely(active_memcg()))
975 /* Memcg to charge can't be determined. */
976 if (!in_task() || !current->mm || (current->flags & PF_KTHREAD))
983 * mem_cgroup_iter - iterate over memory cgroup hierarchy
984 * @root: hierarchy root
985 * @prev: previously returned memcg, NULL on first invocation
986 * @reclaim: cookie for shared reclaim walks, NULL for full walks
988 * Returns references to children of the hierarchy below @root, or
989 * @root itself, or %NULL after a full round-trip.
991 * Caller must pass the return value in @prev on subsequent
992 * invocations for reference counting, or use mem_cgroup_iter_break()
993 * to cancel a hierarchy walk before the round-trip is complete.
995 * Reclaimers can specify a node in @reclaim to divide up the memcgs
996 * in the hierarchy among all concurrent reclaimers operating on the
999 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
1000 struct mem_cgroup *prev,
1001 struct mem_cgroup_reclaim_cookie *reclaim)
1003 struct mem_cgroup_reclaim_iter *iter;
1004 struct cgroup_subsys_state *css = NULL;
1005 struct mem_cgroup *memcg = NULL;
1006 struct mem_cgroup *pos = NULL;
1008 if (mem_cgroup_disabled())
1012 root = root_mem_cgroup;
1017 struct mem_cgroup_per_node *mz;
1019 mz = root->nodeinfo[reclaim->pgdat->node_id];
1023 * On start, join the current reclaim iteration cycle.
1024 * Exit when a concurrent walker completes it.
1027 reclaim->generation = iter->generation;
1028 else if (reclaim->generation != iter->generation)
1032 pos = READ_ONCE(iter->position);
1033 if (!pos || css_tryget(&pos->css))
1036 * css reference reached zero, so iter->position will
1037 * be cleared by ->css_released. However, we should not
1038 * rely on this happening soon, because ->css_released
1039 * is called from a work queue, and by busy-waiting we
1040 * might block it. So we clear iter->position right
1043 (void)cmpxchg(&iter->position, pos, NULL);
1053 css = css_next_descendant_pre(css, &root->css);
1056 * Reclaimers share the hierarchy walk, and a
1057 * new one might jump in right at the end of
1058 * the hierarchy - make sure they see at least
1059 * one group and restart from the beginning.
1067 * Verify the css and acquire a reference. The root
1068 * is provided by the caller, so we know it's alive
1069 * and kicking, and don't take an extra reference.
1071 if (css == &root->css || css_tryget(css)) {
1072 memcg = mem_cgroup_from_css(css);
1079 * The position could have already been updated by a competing
1080 * thread, so check that the value hasn't changed since we read
1081 * it to avoid reclaiming from the same cgroup twice.
1083 (void)cmpxchg(&iter->position, pos, memcg);
1094 if (prev && prev != root)
1095 css_put(&prev->css);
1101 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1102 * @root: hierarchy root
1103 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1105 void mem_cgroup_iter_break(struct mem_cgroup *root,
1106 struct mem_cgroup *prev)
1109 root = root_mem_cgroup;
1110 if (prev && prev != root)
1111 css_put(&prev->css);
1114 static void __invalidate_reclaim_iterators(struct mem_cgroup *from,
1115 struct mem_cgroup *dead_memcg)
1117 struct mem_cgroup_reclaim_iter *iter;
1118 struct mem_cgroup_per_node *mz;
1121 for_each_node(nid) {
1122 mz = from->nodeinfo[nid];
1124 cmpxchg(&iter->position, dead_memcg, NULL);
1128 static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
1130 struct mem_cgroup *memcg = dead_memcg;
1131 struct mem_cgroup *last;
1134 __invalidate_reclaim_iterators(memcg, dead_memcg);
1136 } while ((memcg = parent_mem_cgroup(memcg)));
1139 * When cgruop1 non-hierarchy mode is used,
1140 * parent_mem_cgroup() does not walk all the way up to the
1141 * cgroup root (root_mem_cgroup). So we have to handle
1142 * dead_memcg from cgroup root separately.
1144 if (last != root_mem_cgroup)
1145 __invalidate_reclaim_iterators(root_mem_cgroup,
1150 * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
1151 * @memcg: hierarchy root
1152 * @fn: function to call for each task
1153 * @arg: argument passed to @fn
1155 * This function iterates over tasks attached to @memcg or to any of its
1156 * descendants and calls @fn for each task. If @fn returns a non-zero
1157 * value, the function breaks the iteration loop and returns the value.
1158 * Otherwise, it will iterate over all tasks and return 0.
1160 * This function must not be called for the root memory cgroup.
1162 int mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
1163 int (*fn)(struct task_struct *, void *), void *arg)
1165 struct mem_cgroup *iter;
1168 BUG_ON(memcg == root_mem_cgroup);
1170 for_each_mem_cgroup_tree(iter, memcg) {
1171 struct css_task_iter it;
1172 struct task_struct *task;
1174 css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it);
1175 while (!ret && (task = css_task_iter_next(&it)))
1176 ret = fn(task, arg);
1177 css_task_iter_end(&it);
1179 mem_cgroup_iter_break(memcg, iter);
1186 #ifdef CONFIG_DEBUG_VM
1187 void lruvec_memcg_debug(struct lruvec *lruvec, struct folio *folio)
1189 struct mem_cgroup *memcg;
1191 if (mem_cgroup_disabled())
1194 memcg = folio_memcg(folio);
1197 VM_BUG_ON_FOLIO(lruvec_memcg(lruvec) != root_mem_cgroup, folio);
1199 VM_BUG_ON_FOLIO(lruvec_memcg(lruvec) != memcg, folio);
1204 * folio_lruvec_lock - Lock the lruvec for a folio.
1205 * @folio: Pointer to the folio.
1207 * These functions are safe to use under any of the following conditions:
1209 * - folio_test_lru false
1210 * - folio_memcg_lock()
1211 * - folio frozen (refcount of 0)
1213 * Return: The lruvec this folio is on with its lock held.
1215 struct lruvec *folio_lruvec_lock(struct folio *folio)
1217 struct lruvec *lruvec = folio_lruvec(folio);
1219 spin_lock(&lruvec->lru_lock);
1220 lruvec_memcg_debug(lruvec, folio);
1226 * folio_lruvec_lock_irq - Lock the lruvec for a folio.
1227 * @folio: Pointer to the folio.
1229 * These functions are safe to use under any of the following conditions:
1231 * - folio_test_lru false
1232 * - folio_memcg_lock()
1233 * - folio frozen (refcount of 0)
1235 * Return: The lruvec this folio is on with its lock held and interrupts
1238 struct lruvec *folio_lruvec_lock_irq(struct folio *folio)
1240 struct lruvec *lruvec = folio_lruvec(folio);
1242 spin_lock_irq(&lruvec->lru_lock);
1243 lruvec_memcg_debug(lruvec, folio);
1249 * folio_lruvec_lock_irqsave - Lock the lruvec for a folio.
1250 * @folio: Pointer to the folio.
1251 * @flags: Pointer to irqsave flags.
1253 * These functions are safe to use under any of the following conditions:
1255 * - folio_test_lru false
1256 * - folio_memcg_lock()
1257 * - folio frozen (refcount of 0)
1259 * Return: The lruvec this folio is on with its lock held and interrupts
1262 struct lruvec *folio_lruvec_lock_irqsave(struct folio *folio,
1263 unsigned long *flags)
1265 struct lruvec *lruvec = folio_lruvec(folio);
1267 spin_lock_irqsave(&lruvec->lru_lock, *flags);
1268 lruvec_memcg_debug(lruvec, folio);
1274 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1275 * @lruvec: mem_cgroup per zone lru vector
1276 * @lru: index of lru list the page is sitting on
1277 * @zid: zone id of the accounted pages
1278 * @nr_pages: positive when adding or negative when removing
1280 * This function must be called under lru_lock, just before a page is added
1281 * to or just after a page is removed from an lru list.
1283 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1284 int zid, int nr_pages)
1286 struct mem_cgroup_per_node *mz;
1287 unsigned long *lru_size;
1290 if (mem_cgroup_disabled())
1293 mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
1294 lru_size = &mz->lru_zone_size[zid][lru];
1297 *lru_size += nr_pages;
1300 if (WARN_ONCE(size < 0,
1301 "%s(%p, %d, %d): lru_size %ld\n",
1302 __func__, lruvec, lru, nr_pages, size)) {
1308 *lru_size += nr_pages;
1312 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1313 * @memcg: the memory cgroup
1315 * Returns the maximum amount of memory @mem can be charged with, in
1318 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1320 unsigned long margin = 0;
1321 unsigned long count;
1322 unsigned long limit;
1324 count = page_counter_read(&memcg->memory);
1325 limit = READ_ONCE(memcg->memory.max);
1327 margin = limit - count;
1329 if (do_memsw_account()) {
1330 count = page_counter_read(&memcg->memsw);
1331 limit = READ_ONCE(memcg->memsw.max);
1333 margin = min(margin, limit - count);
1342 * A routine for checking "mem" is under move_account() or not.
1344 * Checking a cgroup is mc.from or mc.to or under hierarchy of
1345 * moving cgroups. This is for waiting at high-memory pressure
1348 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1350 struct mem_cgroup *from;
1351 struct mem_cgroup *to;
1354 * Unlike task_move routines, we access mc.to, mc.from not under
1355 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1357 spin_lock(&mc.lock);
1363 ret = mem_cgroup_is_descendant(from, memcg) ||
1364 mem_cgroup_is_descendant(to, memcg);
1366 spin_unlock(&mc.lock);
1370 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1372 if (mc.moving_task && current != mc.moving_task) {
1373 if (mem_cgroup_under_move(memcg)) {
1375 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1376 /* moving charge context might have finished. */
1379 finish_wait(&mc.waitq, &wait);
1386 struct memory_stat {
1391 static const struct memory_stat memory_stats[] = {
1392 { "anon", NR_ANON_MAPPED },
1393 { "file", NR_FILE_PAGES },
1394 { "kernel", MEMCG_KMEM },
1395 { "kernel_stack", NR_KERNEL_STACK_KB },
1396 { "pagetables", NR_PAGETABLE },
1397 { "percpu", MEMCG_PERCPU_B },
1398 { "sock", MEMCG_SOCK },
1399 { "vmalloc", MEMCG_VMALLOC },
1400 { "shmem", NR_SHMEM },
1401 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
1402 { "zswap", MEMCG_ZSWAP_B },
1403 { "zswapped", MEMCG_ZSWAPPED },
1405 { "file_mapped", NR_FILE_MAPPED },
1406 { "file_dirty", NR_FILE_DIRTY },
1407 { "file_writeback", NR_WRITEBACK },
1409 { "swapcached", NR_SWAPCACHE },
1411 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1412 { "anon_thp", NR_ANON_THPS },
1413 { "file_thp", NR_FILE_THPS },
1414 { "shmem_thp", NR_SHMEM_THPS },
1416 { "inactive_anon", NR_INACTIVE_ANON },
1417 { "active_anon", NR_ACTIVE_ANON },
1418 { "inactive_file", NR_INACTIVE_FILE },
1419 { "active_file", NR_ACTIVE_FILE },
1420 { "unevictable", NR_UNEVICTABLE },
1421 { "slab_reclaimable", NR_SLAB_RECLAIMABLE_B },
1422 { "slab_unreclaimable", NR_SLAB_UNRECLAIMABLE_B },
1424 /* The memory events */
1425 { "workingset_refault_anon", WORKINGSET_REFAULT_ANON },
1426 { "workingset_refault_file", WORKINGSET_REFAULT_FILE },
1427 { "workingset_activate_anon", WORKINGSET_ACTIVATE_ANON },
1428 { "workingset_activate_file", WORKINGSET_ACTIVATE_FILE },
1429 { "workingset_restore_anon", WORKINGSET_RESTORE_ANON },
1430 { "workingset_restore_file", WORKINGSET_RESTORE_FILE },
1431 { "workingset_nodereclaim", WORKINGSET_NODERECLAIM },
1434 /* Translate stat items to the correct unit for memory.stat output */
1435 static int memcg_page_state_unit(int item)
1438 case MEMCG_PERCPU_B:
1440 case NR_SLAB_RECLAIMABLE_B:
1441 case NR_SLAB_UNRECLAIMABLE_B:
1442 case WORKINGSET_REFAULT_ANON:
1443 case WORKINGSET_REFAULT_FILE:
1444 case WORKINGSET_ACTIVATE_ANON:
1445 case WORKINGSET_ACTIVATE_FILE:
1446 case WORKINGSET_RESTORE_ANON:
1447 case WORKINGSET_RESTORE_FILE:
1448 case WORKINGSET_NODERECLAIM:
1450 case NR_KERNEL_STACK_KB:
1457 static inline unsigned long memcg_page_state_output(struct mem_cgroup *memcg,
1460 return memcg_page_state(memcg, item) * memcg_page_state_unit(item);
1463 /* Subset of vm_event_item to report for memcg event stats */
1464 static const unsigned int memcg_vm_event_stat[] = {
1476 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
1480 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1486 static char *memory_stat_format(struct mem_cgroup *memcg)
1491 seq_buf_init(&s, kmalloc(PAGE_SIZE, GFP_KERNEL), PAGE_SIZE);
1496 * Provide statistics on the state of the memory subsystem as
1497 * well as cumulative event counters that show past behavior.
1499 * This list is ordered following a combination of these gradients:
1500 * 1) generic big picture -> specifics and details
1501 * 2) reflecting userspace activity -> reflecting kernel heuristics
1503 * Current memory state:
1505 mem_cgroup_flush_stats();
1507 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
1510 size = memcg_page_state_output(memcg, memory_stats[i].idx);
1511 seq_buf_printf(&s, "%s %llu\n", memory_stats[i].name, size);
1513 if (unlikely(memory_stats[i].idx == NR_SLAB_UNRECLAIMABLE_B)) {
1514 size += memcg_page_state_output(memcg,
1515 NR_SLAB_RECLAIMABLE_B);
1516 seq_buf_printf(&s, "slab %llu\n", size);
1520 /* Accumulated memory events */
1521 seq_buf_printf(&s, "pgscan %lu\n",
1522 memcg_events(memcg, PGSCAN_KSWAPD) +
1523 memcg_events(memcg, PGSCAN_DIRECT));
1524 seq_buf_printf(&s, "pgsteal %lu\n",
1525 memcg_events(memcg, PGSTEAL_KSWAPD) +
1526 memcg_events(memcg, PGSTEAL_DIRECT));
1528 for (i = 0; i < ARRAY_SIZE(memcg_vm_event_stat); i++)
1529 seq_buf_printf(&s, "%s %lu\n",
1530 vm_event_name(memcg_vm_event_stat[i]),
1531 memcg_events(memcg, memcg_vm_event_stat[i]));
1533 /* The above should easily fit into one page */
1534 WARN_ON_ONCE(seq_buf_has_overflowed(&s));
1539 #define K(x) ((x) << (PAGE_SHIFT-10))
1541 * mem_cgroup_print_oom_context: Print OOM information relevant to
1542 * memory controller.
1543 * @memcg: The memory cgroup that went over limit
1544 * @p: Task that is going to be killed
1546 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1549 void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p)
1554 pr_cont(",oom_memcg=");
1555 pr_cont_cgroup_path(memcg->css.cgroup);
1557 pr_cont(",global_oom");
1559 pr_cont(",task_memcg=");
1560 pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
1566 * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
1567 * memory controller.
1568 * @memcg: The memory cgroup that went over limit
1570 void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
1574 pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1575 K((u64)page_counter_read(&memcg->memory)),
1576 K((u64)READ_ONCE(memcg->memory.max)), memcg->memory.failcnt);
1577 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1578 pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n",
1579 K((u64)page_counter_read(&memcg->swap)),
1580 K((u64)READ_ONCE(memcg->swap.max)), memcg->swap.failcnt);
1582 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1583 K((u64)page_counter_read(&memcg->memsw)),
1584 K((u64)memcg->memsw.max), memcg->memsw.failcnt);
1585 pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1586 K((u64)page_counter_read(&memcg->kmem)),
1587 K((u64)memcg->kmem.max), memcg->kmem.failcnt);
1590 pr_info("Memory cgroup stats for ");
1591 pr_cont_cgroup_path(memcg->css.cgroup);
1593 buf = memory_stat_format(memcg);
1601 * Return the memory (and swap, if configured) limit for a memcg.
1603 unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg)
1605 unsigned long max = READ_ONCE(memcg->memory.max);
1607 if (cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
1608 if (mem_cgroup_swappiness(memcg))
1609 max += min(READ_ONCE(memcg->swap.max),
1610 (unsigned long)total_swap_pages);
1612 if (mem_cgroup_swappiness(memcg)) {
1613 /* Calculate swap excess capacity from memsw limit */
1614 unsigned long swap = READ_ONCE(memcg->memsw.max) - max;
1616 max += min(swap, (unsigned long)total_swap_pages);
1622 unsigned long mem_cgroup_size(struct mem_cgroup *memcg)
1624 return page_counter_read(&memcg->memory);
1627 static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1630 struct oom_control oc = {
1634 .gfp_mask = gfp_mask,
1639 if (mutex_lock_killable(&oom_lock))
1642 if (mem_cgroup_margin(memcg) >= (1 << order))
1646 * A few threads which were not waiting at mutex_lock_killable() can
1647 * fail to bail out. Therefore, check again after holding oom_lock.
1649 ret = task_is_dying() || out_of_memory(&oc);
1652 mutex_unlock(&oom_lock);
1656 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
1659 unsigned long *total_scanned)
1661 struct mem_cgroup *victim = NULL;
1664 unsigned long excess;
1665 unsigned long nr_scanned;
1666 struct mem_cgroup_reclaim_cookie reclaim = {
1670 excess = soft_limit_excess(root_memcg);
1673 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1678 * If we have not been able to reclaim
1679 * anything, it might because there are
1680 * no reclaimable pages under this hierarchy
1685 * We want to do more targeted reclaim.
1686 * excess >> 2 is not to excessive so as to
1687 * reclaim too much, nor too less that we keep
1688 * coming back to reclaim from this cgroup
1690 if (total >= (excess >> 2) ||
1691 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1696 total += mem_cgroup_shrink_node(victim, gfp_mask, false,
1697 pgdat, &nr_scanned);
1698 *total_scanned += nr_scanned;
1699 if (!soft_limit_excess(root_memcg))
1702 mem_cgroup_iter_break(root_memcg, victim);
1706 #ifdef CONFIG_LOCKDEP
1707 static struct lockdep_map memcg_oom_lock_dep_map = {
1708 .name = "memcg_oom_lock",
1712 static DEFINE_SPINLOCK(memcg_oom_lock);
1715 * Check OOM-Killer is already running under our hierarchy.
1716 * If someone is running, return false.
1718 static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
1720 struct mem_cgroup *iter, *failed = NULL;
1722 spin_lock(&memcg_oom_lock);
1724 for_each_mem_cgroup_tree(iter, memcg) {
1725 if (iter->oom_lock) {
1727 * this subtree of our hierarchy is already locked
1728 * so we cannot give a lock.
1731 mem_cgroup_iter_break(memcg, iter);
1734 iter->oom_lock = true;
1739 * OK, we failed to lock the whole subtree so we have
1740 * to clean up what we set up to the failing subtree
1742 for_each_mem_cgroup_tree(iter, memcg) {
1743 if (iter == failed) {
1744 mem_cgroup_iter_break(memcg, iter);
1747 iter->oom_lock = false;
1750 mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
1752 spin_unlock(&memcg_oom_lock);
1757 static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1759 struct mem_cgroup *iter;
1761 spin_lock(&memcg_oom_lock);
1762 mutex_release(&memcg_oom_lock_dep_map, _RET_IP_);
1763 for_each_mem_cgroup_tree(iter, memcg)
1764 iter->oom_lock = false;
1765 spin_unlock(&memcg_oom_lock);
1768 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1770 struct mem_cgroup *iter;
1772 spin_lock(&memcg_oom_lock);
1773 for_each_mem_cgroup_tree(iter, memcg)
1775 spin_unlock(&memcg_oom_lock);
1778 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1780 struct mem_cgroup *iter;
1783 * Be careful about under_oom underflows because a child memcg
1784 * could have been added after mem_cgroup_mark_under_oom.
1786 spin_lock(&memcg_oom_lock);
1787 for_each_mem_cgroup_tree(iter, memcg)
1788 if (iter->under_oom > 0)
1790 spin_unlock(&memcg_oom_lock);
1793 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1795 struct oom_wait_info {
1796 struct mem_cgroup *memcg;
1797 wait_queue_entry_t wait;
1800 static int memcg_oom_wake_function(wait_queue_entry_t *wait,
1801 unsigned mode, int sync, void *arg)
1803 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
1804 struct mem_cgroup *oom_wait_memcg;
1805 struct oom_wait_info *oom_wait_info;
1807 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1808 oom_wait_memcg = oom_wait_info->memcg;
1810 if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
1811 !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
1813 return autoremove_wake_function(wait, mode, sync, arg);
1816 static void memcg_oom_recover(struct mem_cgroup *memcg)
1819 * For the following lockless ->under_oom test, the only required
1820 * guarantee is that it must see the state asserted by an OOM when
1821 * this function is called as a result of userland actions
1822 * triggered by the notification of the OOM. This is trivially
1823 * achieved by invoking mem_cgroup_mark_under_oom() before
1824 * triggering notification.
1826 if (memcg && memcg->under_oom)
1827 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
1831 * Returns true if successfully killed one or more processes. Though in some
1832 * corner cases it can return true even without killing any process.
1834 static bool mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
1838 if (order > PAGE_ALLOC_COSTLY_ORDER)
1841 memcg_memory_event(memcg, MEMCG_OOM);
1844 * We are in the middle of the charge context here, so we
1845 * don't want to block when potentially sitting on a callstack
1846 * that holds all kinds of filesystem and mm locks.
1848 * cgroup1 allows disabling the OOM killer and waiting for outside
1849 * handling until the charge can succeed; remember the context and put
1850 * the task to sleep at the end of the page fault when all locks are
1853 * On the other hand, in-kernel OOM killer allows for an async victim
1854 * memory reclaim (oom_reaper) and that means that we are not solely
1855 * relying on the oom victim to make a forward progress and we can
1856 * invoke the oom killer here.
1858 * Please note that mem_cgroup_out_of_memory might fail to find a
1859 * victim and then we have to bail out from the charge path.
1861 if (memcg->oom_kill_disable) {
1862 if (current->in_user_fault) {
1863 css_get(&memcg->css);
1864 current->memcg_in_oom = memcg;
1865 current->memcg_oom_gfp_mask = mask;
1866 current->memcg_oom_order = order;
1871 mem_cgroup_mark_under_oom(memcg);
1873 locked = mem_cgroup_oom_trylock(memcg);
1876 mem_cgroup_oom_notify(memcg);
1878 mem_cgroup_unmark_under_oom(memcg);
1879 ret = mem_cgroup_out_of_memory(memcg, mask, order);
1882 mem_cgroup_oom_unlock(memcg);
1888 * mem_cgroup_oom_synchronize - complete memcg OOM handling
1889 * @handle: actually kill/wait or just clean up the OOM state
1891 * This has to be called at the end of a page fault if the memcg OOM
1892 * handler was enabled.
1894 * Memcg supports userspace OOM handling where failed allocations must
1895 * sleep on a waitqueue until the userspace task resolves the
1896 * situation. Sleeping directly in the charge context with all kinds
1897 * of locks held is not a good idea, instead we remember an OOM state
1898 * in the task and mem_cgroup_oom_synchronize() has to be called at
1899 * the end of the page fault to complete the OOM handling.
1901 * Returns %true if an ongoing memcg OOM situation was detected and
1902 * completed, %false otherwise.
1904 bool mem_cgroup_oom_synchronize(bool handle)
1906 struct mem_cgroup *memcg = current->memcg_in_oom;
1907 struct oom_wait_info owait;
1910 /* OOM is global, do not handle */
1917 owait.memcg = memcg;
1918 owait.wait.flags = 0;
1919 owait.wait.func = memcg_oom_wake_function;
1920 owait.wait.private = current;
1921 INIT_LIST_HEAD(&owait.wait.entry);
1923 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
1924 mem_cgroup_mark_under_oom(memcg);
1926 locked = mem_cgroup_oom_trylock(memcg);
1929 mem_cgroup_oom_notify(memcg);
1931 if (locked && !memcg->oom_kill_disable) {
1932 mem_cgroup_unmark_under_oom(memcg);
1933 finish_wait(&memcg_oom_waitq, &owait.wait);
1934 mem_cgroup_out_of_memory(memcg, current->memcg_oom_gfp_mask,
1935 current->memcg_oom_order);
1938 mem_cgroup_unmark_under_oom(memcg);
1939 finish_wait(&memcg_oom_waitq, &owait.wait);
1943 mem_cgroup_oom_unlock(memcg);
1945 * There is no guarantee that an OOM-lock contender
1946 * sees the wakeups triggered by the OOM kill
1947 * uncharges. Wake any sleepers explicitly.
1949 memcg_oom_recover(memcg);
1952 current->memcg_in_oom = NULL;
1953 css_put(&memcg->css);
1958 * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
1959 * @victim: task to be killed by the OOM killer
1960 * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
1962 * Returns a pointer to a memory cgroup, which has to be cleaned up
1963 * by killing all belonging OOM-killable tasks.
1965 * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
1967 struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim,
1968 struct mem_cgroup *oom_domain)
1970 struct mem_cgroup *oom_group = NULL;
1971 struct mem_cgroup *memcg;
1973 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
1977 oom_domain = root_mem_cgroup;
1981 memcg = mem_cgroup_from_task(victim);
1982 if (memcg == root_mem_cgroup)
1986 * If the victim task has been asynchronously moved to a different
1987 * memory cgroup, we might end up killing tasks outside oom_domain.
1988 * In this case it's better to ignore memory.group.oom.
1990 if (unlikely(!mem_cgroup_is_descendant(memcg, oom_domain)))
1994 * Traverse the memory cgroup hierarchy from the victim task's
1995 * cgroup up to the OOMing cgroup (or root) to find the
1996 * highest-level memory cgroup with oom.group set.
1998 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
1999 if (memcg->oom_group)
2002 if (memcg == oom_domain)
2007 css_get(&oom_group->css);
2014 void mem_cgroup_print_oom_group(struct mem_cgroup *memcg)
2016 pr_info("Tasks in ");
2017 pr_cont_cgroup_path(memcg->css.cgroup);
2018 pr_cont(" are going to be killed due to memory.oom.group set\n");
2022 * folio_memcg_lock - Bind a folio to its memcg.
2023 * @folio: The folio.
2025 * This function prevents unlocked LRU folios from being moved to
2028 * It ensures lifetime of the bound memcg. The caller is responsible
2029 * for the lifetime of the folio.
2031 void folio_memcg_lock(struct folio *folio)
2033 struct mem_cgroup *memcg;
2034 unsigned long flags;
2037 * The RCU lock is held throughout the transaction. The fast
2038 * path can get away without acquiring the memcg->move_lock
2039 * because page moving starts with an RCU grace period.
2043 if (mem_cgroup_disabled())
2046 memcg = folio_memcg(folio);
2047 if (unlikely(!memcg))
2050 #ifdef CONFIG_PROVE_LOCKING
2051 local_irq_save(flags);
2052 might_lock(&memcg->move_lock);
2053 local_irq_restore(flags);
2056 if (atomic_read(&memcg->moving_account) <= 0)
2059 spin_lock_irqsave(&memcg->move_lock, flags);
2060 if (memcg != folio_memcg(folio)) {
2061 spin_unlock_irqrestore(&memcg->move_lock, flags);
2066 * When charge migration first begins, we can have multiple
2067 * critical sections holding the fast-path RCU lock and one
2068 * holding the slowpath move_lock. Track the task who has the
2069 * move_lock for unlock_page_memcg().
2071 memcg->move_lock_task = current;
2072 memcg->move_lock_flags = flags;
2075 void lock_page_memcg(struct page *page)
2077 folio_memcg_lock(page_folio(page));
2080 static void __folio_memcg_unlock(struct mem_cgroup *memcg)
2082 if (memcg && memcg->move_lock_task == current) {
2083 unsigned long flags = memcg->move_lock_flags;
2085 memcg->move_lock_task = NULL;
2086 memcg->move_lock_flags = 0;
2088 spin_unlock_irqrestore(&memcg->move_lock, flags);
2095 * folio_memcg_unlock - Release the binding between a folio and its memcg.
2096 * @folio: The folio.
2098 * This releases the binding created by folio_memcg_lock(). This does
2099 * not change the accounting of this folio to its memcg, but it does
2100 * permit others to change it.
2102 void folio_memcg_unlock(struct folio *folio)
2104 __folio_memcg_unlock(folio_memcg(folio));
2107 void unlock_page_memcg(struct page *page)
2109 folio_memcg_unlock(page_folio(page));
2112 struct memcg_stock_pcp {
2113 local_lock_t stock_lock;
2114 struct mem_cgroup *cached; /* this never be root cgroup */
2115 unsigned int nr_pages;
2117 #ifdef CONFIG_MEMCG_KMEM
2118 struct obj_cgroup *cached_objcg;
2119 struct pglist_data *cached_pgdat;
2120 unsigned int nr_bytes;
2121 int nr_slab_reclaimable_b;
2122 int nr_slab_unreclaimable_b;
2125 struct work_struct work;
2126 unsigned long flags;
2127 #define FLUSHING_CACHED_CHARGE 0
2129 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock) = {
2130 .stock_lock = INIT_LOCAL_LOCK(stock_lock),
2132 static DEFINE_MUTEX(percpu_charge_mutex);
2134 #ifdef CONFIG_MEMCG_KMEM
2135 static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock);
2136 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2137 struct mem_cgroup *root_memcg);
2138 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages);
2141 static inline struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock)
2145 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2146 struct mem_cgroup *root_memcg)
2150 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages)
2156 * consume_stock: Try to consume stocked charge on this cpu.
2157 * @memcg: memcg to consume from.
2158 * @nr_pages: how many pages to charge.
2160 * The charges will only happen if @memcg matches the current cpu's memcg
2161 * stock, and at least @nr_pages are available in that stock. Failure to
2162 * service an allocation will refill the stock.
2164 * returns true if successful, false otherwise.
2166 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2168 struct memcg_stock_pcp *stock;
2169 unsigned long flags;
2172 if (nr_pages > MEMCG_CHARGE_BATCH)
2175 local_lock_irqsave(&memcg_stock.stock_lock, flags);
2177 stock = this_cpu_ptr(&memcg_stock);
2178 if (memcg == stock->cached && stock->nr_pages >= nr_pages) {
2179 stock->nr_pages -= nr_pages;
2183 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2189 * Returns stocks cached in percpu and reset cached information.
2191 static void drain_stock(struct memcg_stock_pcp *stock)
2193 struct mem_cgroup *old = stock->cached;
2198 if (stock->nr_pages) {
2199 page_counter_uncharge(&old->memory, stock->nr_pages);
2200 if (do_memsw_account())
2201 page_counter_uncharge(&old->memsw, stock->nr_pages);
2202 stock->nr_pages = 0;
2206 stock->cached = NULL;
2209 static void drain_local_stock(struct work_struct *dummy)
2211 struct memcg_stock_pcp *stock;
2212 struct obj_cgroup *old = NULL;
2213 unsigned long flags;
2216 * The only protection from cpu hotplug (memcg_hotplug_cpu_dead) vs.
2217 * drain_stock races is that we always operate on local CPU stock
2218 * here with IRQ disabled
2220 local_lock_irqsave(&memcg_stock.stock_lock, flags);
2222 stock = this_cpu_ptr(&memcg_stock);
2223 old = drain_obj_stock(stock);
2225 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2227 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2229 obj_cgroup_put(old);
2233 * Cache charges(val) to local per_cpu area.
2234 * This will be consumed by consume_stock() function, later.
2236 static void __refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2238 struct memcg_stock_pcp *stock;
2240 stock = this_cpu_ptr(&memcg_stock);
2241 if (stock->cached != memcg) { /* reset if necessary */
2243 css_get(&memcg->css);
2244 stock->cached = memcg;
2246 stock->nr_pages += nr_pages;
2248 if (stock->nr_pages > MEMCG_CHARGE_BATCH)
2252 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2254 unsigned long flags;
2256 local_lock_irqsave(&memcg_stock.stock_lock, flags);
2257 __refill_stock(memcg, nr_pages);
2258 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2262 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2263 * of the hierarchy under it.
2265 static void drain_all_stock(struct mem_cgroup *root_memcg)
2269 /* If someone's already draining, avoid adding running more workers. */
2270 if (!mutex_trylock(&percpu_charge_mutex))
2273 * Notify other cpus that system-wide "drain" is running
2274 * We do not care about races with the cpu hotplug because cpu down
2275 * as well as workers from this path always operate on the local
2276 * per-cpu data. CPU up doesn't touch memcg_stock at all.
2279 curcpu = smp_processor_id();
2280 for_each_online_cpu(cpu) {
2281 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2282 struct mem_cgroup *memcg;
2286 memcg = stock->cached;
2287 if (memcg && stock->nr_pages &&
2288 mem_cgroup_is_descendant(memcg, root_memcg))
2290 else if (obj_stock_flush_required(stock, root_memcg))
2295 !test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2297 drain_local_stock(&stock->work);
2299 schedule_work_on(cpu, &stock->work);
2303 mutex_unlock(&percpu_charge_mutex);
2306 static int memcg_hotplug_cpu_dead(unsigned int cpu)
2308 struct memcg_stock_pcp *stock;
2310 stock = &per_cpu(memcg_stock, cpu);
2316 static unsigned long reclaim_high(struct mem_cgroup *memcg,
2317 unsigned int nr_pages,
2320 unsigned long nr_reclaimed = 0;
2323 unsigned long pflags;
2325 if (page_counter_read(&memcg->memory) <=
2326 READ_ONCE(memcg->memory.high))
2329 memcg_memory_event(memcg, MEMCG_HIGH);
2331 psi_memstall_enter(&pflags);
2332 nr_reclaimed += try_to_free_mem_cgroup_pages(memcg, nr_pages,
2334 psi_memstall_leave(&pflags);
2335 } while ((memcg = parent_mem_cgroup(memcg)) &&
2336 !mem_cgroup_is_root(memcg));
2338 return nr_reclaimed;
2341 static void high_work_func(struct work_struct *work)
2343 struct mem_cgroup *memcg;
2345 memcg = container_of(work, struct mem_cgroup, high_work);
2346 reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
2350 * Clamp the maximum sleep time per allocation batch to 2 seconds. This is
2351 * enough to still cause a significant slowdown in most cases, while still
2352 * allowing diagnostics and tracing to proceed without becoming stuck.
2354 #define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ)
2357 * When calculating the delay, we use these either side of the exponentiation to
2358 * maintain precision and scale to a reasonable number of jiffies (see the table
2361 * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the
2362 * overage ratio to a delay.
2363 * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down the
2364 * proposed penalty in order to reduce to a reasonable number of jiffies, and
2365 * to produce a reasonable delay curve.
2367 * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a
2368 * reasonable delay curve compared to precision-adjusted overage, not
2369 * penalising heavily at first, but still making sure that growth beyond the
2370 * limit penalises misbehaviour cgroups by slowing them down exponentially. For
2371 * example, with a high of 100 megabytes:
2373 * +-------+------------------------+
2374 * | usage | time to allocate in ms |
2375 * +-------+------------------------+
2397 * +-------+------------------------+
2399 #define MEMCG_DELAY_PRECISION_SHIFT 20
2400 #define MEMCG_DELAY_SCALING_SHIFT 14
2402 static u64 calculate_overage(unsigned long usage, unsigned long high)
2410 * Prevent division by 0 in overage calculation by acting as if
2411 * it was a threshold of 1 page
2413 high = max(high, 1UL);
2415 overage = usage - high;
2416 overage <<= MEMCG_DELAY_PRECISION_SHIFT;
2417 return div64_u64(overage, high);
2420 static u64 mem_find_max_overage(struct mem_cgroup *memcg)
2422 u64 overage, max_overage = 0;
2425 overage = calculate_overage(page_counter_read(&memcg->memory),
2426 READ_ONCE(memcg->memory.high));
2427 max_overage = max(overage, max_overage);
2428 } while ((memcg = parent_mem_cgroup(memcg)) &&
2429 !mem_cgroup_is_root(memcg));
2434 static u64 swap_find_max_overage(struct mem_cgroup *memcg)
2436 u64 overage, max_overage = 0;
2439 overage = calculate_overage(page_counter_read(&memcg->swap),
2440 READ_ONCE(memcg->swap.high));
2442 memcg_memory_event(memcg, MEMCG_SWAP_HIGH);
2443 max_overage = max(overage, max_overage);
2444 } while ((memcg = parent_mem_cgroup(memcg)) &&
2445 !mem_cgroup_is_root(memcg));
2451 * Get the number of jiffies that we should penalise a mischievous cgroup which
2452 * is exceeding its memory.high by checking both it and its ancestors.
2454 static unsigned long calculate_high_delay(struct mem_cgroup *memcg,
2455 unsigned int nr_pages,
2458 unsigned long penalty_jiffies;
2464 * We use overage compared to memory.high to calculate the number of
2465 * jiffies to sleep (penalty_jiffies). Ideally this value should be
2466 * fairly lenient on small overages, and increasingly harsh when the
2467 * memcg in question makes it clear that it has no intention of stopping
2468 * its crazy behaviour, so we exponentially increase the delay based on
2471 penalty_jiffies = max_overage * max_overage * HZ;
2472 penalty_jiffies >>= MEMCG_DELAY_PRECISION_SHIFT;
2473 penalty_jiffies >>= MEMCG_DELAY_SCALING_SHIFT;
2476 * Factor in the task's own contribution to the overage, such that four
2477 * N-sized allocations are throttled approximately the same as one
2478 * 4N-sized allocation.
2480 * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or
2481 * larger the current charge patch is than that.
2483 return penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH;
2487 * Scheduled by try_charge() to be executed from the userland return path
2488 * and reclaims memory over the high limit.
2490 void mem_cgroup_handle_over_high(void)
2492 unsigned long penalty_jiffies;
2493 unsigned long pflags;
2494 unsigned long nr_reclaimed;
2495 unsigned int nr_pages = current->memcg_nr_pages_over_high;
2496 int nr_retries = MAX_RECLAIM_RETRIES;
2497 struct mem_cgroup *memcg;
2498 bool in_retry = false;
2500 if (likely(!nr_pages))
2503 memcg = get_mem_cgroup_from_mm(current->mm);
2504 current->memcg_nr_pages_over_high = 0;
2508 * The allocating task should reclaim at least the batch size, but for
2509 * subsequent retries we only want to do what's necessary to prevent oom
2510 * or breaching resource isolation.
2512 * This is distinct from memory.max or page allocator behaviour because
2513 * memory.high is currently batched, whereas memory.max and the page
2514 * allocator run every time an allocation is made.
2516 nr_reclaimed = reclaim_high(memcg,
2517 in_retry ? SWAP_CLUSTER_MAX : nr_pages,
2521 * memory.high is breached and reclaim is unable to keep up. Throttle
2522 * allocators proactively to slow down excessive growth.
2524 penalty_jiffies = calculate_high_delay(memcg, nr_pages,
2525 mem_find_max_overage(memcg));
2527 penalty_jiffies += calculate_high_delay(memcg, nr_pages,
2528 swap_find_max_overage(memcg));
2531 * Clamp the max delay per usermode return so as to still keep the
2532 * application moving forwards and also permit diagnostics, albeit
2535 penalty_jiffies = min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES);
2538 * Don't sleep if the amount of jiffies this memcg owes us is so low
2539 * that it's not even worth doing, in an attempt to be nice to those who
2540 * go only a small amount over their memory.high value and maybe haven't
2541 * been aggressively reclaimed enough yet.
2543 if (penalty_jiffies <= HZ / 100)
2547 * If reclaim is making forward progress but we're still over
2548 * memory.high, we want to encourage that rather than doing allocator
2551 if (nr_reclaimed || nr_retries--) {
2557 * If we exit early, we're guaranteed to die (since
2558 * schedule_timeout_killable sets TASK_KILLABLE). This means we don't
2559 * need to account for any ill-begotten jiffies to pay them off later.
2561 psi_memstall_enter(&pflags);
2562 schedule_timeout_killable(penalty_jiffies);
2563 psi_memstall_leave(&pflags);
2566 css_put(&memcg->css);
2569 static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask,
2570 unsigned int nr_pages)
2572 unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
2573 int nr_retries = MAX_RECLAIM_RETRIES;
2574 struct mem_cgroup *mem_over_limit;
2575 struct page_counter *counter;
2576 unsigned long nr_reclaimed;
2577 bool passed_oom = false;
2578 bool may_swap = true;
2579 bool drained = false;
2580 unsigned long pflags;
2583 if (consume_stock(memcg, nr_pages))
2586 if (!do_memsw_account() ||
2587 page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2588 if (page_counter_try_charge(&memcg->memory, batch, &counter))
2590 if (do_memsw_account())
2591 page_counter_uncharge(&memcg->memsw, batch);
2592 mem_over_limit = mem_cgroup_from_counter(counter, memory);
2594 mem_over_limit = mem_cgroup_from_counter(counter, memsw);
2598 if (batch > nr_pages) {
2604 * Prevent unbounded recursion when reclaim operations need to
2605 * allocate memory. This might exceed the limits temporarily,
2606 * but we prefer facilitating memory reclaim and getting back
2607 * under the limit over triggering OOM kills in these cases.
2609 if (unlikely(current->flags & PF_MEMALLOC))
2612 if (unlikely(task_in_memcg_oom(current)))
2615 if (!gfpflags_allow_blocking(gfp_mask))
2618 memcg_memory_event(mem_over_limit, MEMCG_MAX);
2620 psi_memstall_enter(&pflags);
2621 nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
2622 gfp_mask, may_swap);
2623 psi_memstall_leave(&pflags);
2625 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2629 drain_all_stock(mem_over_limit);
2634 if (gfp_mask & __GFP_NORETRY)
2637 * Even though the limit is exceeded at this point, reclaim
2638 * may have been able to free some pages. Retry the charge
2639 * before killing the task.
2641 * Only for regular pages, though: huge pages are rather
2642 * unlikely to succeed so close to the limit, and we fall back
2643 * to regular pages anyway in case of failure.
2645 if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
2648 * At task move, charge accounts can be doubly counted. So, it's
2649 * better to wait until the end of task_move if something is going on.
2651 if (mem_cgroup_wait_acct_move(mem_over_limit))
2657 if (gfp_mask & __GFP_RETRY_MAYFAIL)
2660 /* Avoid endless loop for tasks bypassed by the oom killer */
2661 if (passed_oom && task_is_dying())
2665 * keep retrying as long as the memcg oom killer is able to make
2666 * a forward progress or bypass the charge if the oom killer
2667 * couldn't make any progress.
2669 if (mem_cgroup_oom(mem_over_limit, gfp_mask,
2670 get_order(nr_pages * PAGE_SIZE))) {
2672 nr_retries = MAX_RECLAIM_RETRIES;
2677 * Memcg doesn't have a dedicated reserve for atomic
2678 * allocations. But like the global atomic pool, we need to
2679 * put the burden of reclaim on regular allocation requests
2680 * and let these go through as privileged allocations.
2682 if (!(gfp_mask & (__GFP_NOFAIL | __GFP_HIGH)))
2686 * The allocation either can't fail or will lead to more memory
2687 * being freed very soon. Allow memory usage go over the limit
2688 * temporarily by force charging it.
2690 page_counter_charge(&memcg->memory, nr_pages);
2691 if (do_memsw_account())
2692 page_counter_charge(&memcg->memsw, nr_pages);
2697 if (batch > nr_pages)
2698 refill_stock(memcg, batch - nr_pages);
2701 * If the hierarchy is above the normal consumption range, schedule
2702 * reclaim on returning to userland. We can perform reclaim here
2703 * if __GFP_RECLAIM but let's always punt for simplicity and so that
2704 * GFP_KERNEL can consistently be used during reclaim. @memcg is
2705 * not recorded as it most likely matches current's and won't
2706 * change in the meantime. As high limit is checked again before
2707 * reclaim, the cost of mismatch is negligible.
2710 bool mem_high, swap_high;
2712 mem_high = page_counter_read(&memcg->memory) >
2713 READ_ONCE(memcg->memory.high);
2714 swap_high = page_counter_read(&memcg->swap) >
2715 READ_ONCE(memcg->swap.high);
2717 /* Don't bother a random interrupted task */
2720 schedule_work(&memcg->high_work);
2726 if (mem_high || swap_high) {
2728 * The allocating tasks in this cgroup will need to do
2729 * reclaim or be throttled to prevent further growth
2730 * of the memory or swap footprints.
2732 * Target some best-effort fairness between the tasks,
2733 * and distribute reclaim work and delay penalties
2734 * based on how much each task is actually allocating.
2736 current->memcg_nr_pages_over_high += batch;
2737 set_notify_resume(current);
2740 } while ((memcg = parent_mem_cgroup(memcg)));
2742 if (current->memcg_nr_pages_over_high > MEMCG_CHARGE_BATCH &&
2743 !(current->flags & PF_MEMALLOC) &&
2744 gfpflags_allow_blocking(gfp_mask)) {
2745 mem_cgroup_handle_over_high();
2750 static inline int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2751 unsigned int nr_pages)
2753 if (mem_cgroup_is_root(memcg))
2756 return try_charge_memcg(memcg, gfp_mask, nr_pages);
2759 static inline void cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
2761 if (mem_cgroup_is_root(memcg))
2764 page_counter_uncharge(&memcg->memory, nr_pages);
2765 if (do_memsw_account())
2766 page_counter_uncharge(&memcg->memsw, nr_pages);
2769 static void commit_charge(struct folio *folio, struct mem_cgroup *memcg)
2771 VM_BUG_ON_FOLIO(folio_memcg(folio), folio);
2773 * Any of the following ensures page's memcg stability:
2777 * - lock_page_memcg()
2778 * - exclusive reference
2780 folio->memcg_data = (unsigned long)memcg;
2783 #ifdef CONFIG_MEMCG_KMEM
2785 * The allocated objcg pointers array is not accounted directly.
2786 * Moreover, it should not come from DMA buffer and is not readily
2787 * reclaimable. So those GFP bits should be masked off.
2789 #define OBJCGS_CLEAR_MASK (__GFP_DMA | __GFP_RECLAIMABLE | __GFP_ACCOUNT)
2792 * mod_objcg_mlstate() may be called with irq enabled, so
2793 * mod_memcg_lruvec_state() should be used.
2795 static inline void mod_objcg_mlstate(struct obj_cgroup *objcg,
2796 struct pglist_data *pgdat,
2797 enum node_stat_item idx, int nr)
2799 struct mem_cgroup *memcg;
2800 struct lruvec *lruvec;
2803 memcg = obj_cgroup_memcg(objcg);
2804 lruvec = mem_cgroup_lruvec(memcg, pgdat);
2805 mod_memcg_lruvec_state(lruvec, idx, nr);
2809 int memcg_alloc_slab_cgroups(struct slab *slab, struct kmem_cache *s,
2810 gfp_t gfp, bool new_slab)
2812 unsigned int objects = objs_per_slab(s, slab);
2813 unsigned long memcg_data;
2816 gfp &= ~OBJCGS_CLEAR_MASK;
2817 vec = kcalloc_node(objects, sizeof(struct obj_cgroup *), gfp,
2822 memcg_data = (unsigned long) vec | MEMCG_DATA_OBJCGS;
2825 * If the slab is brand new and nobody can yet access its
2826 * memcg_data, no synchronization is required and memcg_data can
2827 * be simply assigned.
2829 slab->memcg_data = memcg_data;
2830 } else if (cmpxchg(&slab->memcg_data, 0, memcg_data)) {
2832 * If the slab is already in use, somebody can allocate and
2833 * assign obj_cgroups in parallel. In this case the existing
2834 * objcg vector should be reused.
2840 kmemleak_not_leak(vec);
2844 static __always_inline
2845 struct mem_cgroup *mem_cgroup_from_obj_folio(struct folio *folio, void *p)
2848 * Slab objects are accounted individually, not per-page.
2849 * Memcg membership data for each individual object is saved in
2852 if (folio_test_slab(folio)) {
2853 struct obj_cgroup **objcgs;
2857 slab = folio_slab(folio);
2858 objcgs = slab_objcgs(slab);
2862 off = obj_to_index(slab->slab_cache, slab, p);
2864 return obj_cgroup_memcg(objcgs[off]);
2870 * page_memcg_check() is used here, because in theory we can encounter
2871 * a folio where the slab flag has been cleared already, but
2872 * slab->memcg_data has not been freed yet
2873 * page_memcg_check(page) will guarantee that a proper memory
2874 * cgroup pointer or NULL will be returned.
2876 return page_memcg_check(folio_page(folio, 0));
2880 * Returns a pointer to the memory cgroup to which the kernel object is charged.
2882 * A passed kernel object can be a slab object, vmalloc object or a generic
2883 * kernel page, so different mechanisms for getting the memory cgroup pointer
2886 * In certain cases (e.g. kernel stacks or large kmallocs with SLUB) the caller
2887 * can not know for sure how the kernel object is implemented.
2888 * mem_cgroup_from_obj() can be safely used in such cases.
2890 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
2891 * cgroup_mutex, etc.
2893 struct mem_cgroup *mem_cgroup_from_obj(void *p)
2895 struct folio *folio;
2897 if (mem_cgroup_disabled())
2900 if (unlikely(is_vmalloc_addr(p)))
2901 folio = page_folio(vmalloc_to_page(p));
2903 folio = virt_to_folio(p);
2905 return mem_cgroup_from_obj_folio(folio, p);
2909 * Returns a pointer to the memory cgroup to which the kernel object is charged.
2910 * Similar to mem_cgroup_from_obj(), but faster and not suitable for objects,
2911 * allocated using vmalloc().
2913 * A passed kernel object must be a slab object or a generic kernel page.
2915 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
2916 * cgroup_mutex, etc.
2918 struct mem_cgroup *mem_cgroup_from_slab_obj(void *p)
2920 if (mem_cgroup_disabled())
2923 return mem_cgroup_from_obj_folio(virt_to_folio(p), p);
2926 static struct obj_cgroup *__get_obj_cgroup_from_memcg(struct mem_cgroup *memcg)
2928 struct obj_cgroup *objcg = NULL;
2930 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg)) {
2931 objcg = rcu_dereference(memcg->objcg);
2932 if (objcg && obj_cgroup_tryget(objcg))
2939 __always_inline struct obj_cgroup *get_obj_cgroup_from_current(void)
2941 struct obj_cgroup *objcg = NULL;
2942 struct mem_cgroup *memcg;
2944 if (memcg_kmem_bypass())
2948 if (unlikely(active_memcg()))
2949 memcg = active_memcg();
2951 memcg = mem_cgroup_from_task(current);
2952 objcg = __get_obj_cgroup_from_memcg(memcg);
2957 struct obj_cgroup *get_obj_cgroup_from_page(struct page *page)
2959 struct obj_cgroup *objcg;
2961 if (!memcg_kmem_enabled() || memcg_kmem_bypass())
2964 if (PageMemcgKmem(page)) {
2965 objcg = __folio_objcg(page_folio(page));
2966 obj_cgroup_get(objcg);
2968 struct mem_cgroup *memcg;
2971 memcg = __folio_memcg(page_folio(page));
2973 objcg = __get_obj_cgroup_from_memcg(memcg);
2981 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages)
2983 mod_memcg_state(memcg, MEMCG_KMEM, nr_pages);
2984 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
2986 page_counter_charge(&memcg->kmem, nr_pages);
2988 page_counter_uncharge(&memcg->kmem, -nr_pages);
2994 * obj_cgroup_uncharge_pages: uncharge a number of kernel pages from a objcg
2995 * @objcg: object cgroup to uncharge
2996 * @nr_pages: number of pages to uncharge
2998 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
2999 unsigned int nr_pages)
3001 struct mem_cgroup *memcg;
3003 memcg = get_mem_cgroup_from_objcg(objcg);
3005 memcg_account_kmem(memcg, -nr_pages);
3006 refill_stock(memcg, nr_pages);
3008 css_put(&memcg->css);
3012 * obj_cgroup_charge_pages: charge a number of kernel pages to a objcg
3013 * @objcg: object cgroup to charge
3014 * @gfp: reclaim mode
3015 * @nr_pages: number of pages to charge
3017 * Returns 0 on success, an error code on failure.
3019 static int obj_cgroup_charge_pages(struct obj_cgroup *objcg, gfp_t gfp,
3020 unsigned int nr_pages)
3022 struct mem_cgroup *memcg;
3025 memcg = get_mem_cgroup_from_objcg(objcg);
3027 ret = try_charge_memcg(memcg, gfp, nr_pages);
3031 memcg_account_kmem(memcg, nr_pages);
3033 css_put(&memcg->css);
3039 * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup
3040 * @page: page to charge
3041 * @gfp: reclaim mode
3042 * @order: allocation order
3044 * Returns 0 on success, an error code on failure.
3046 int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
3048 struct obj_cgroup *objcg;
3051 objcg = get_obj_cgroup_from_current();
3053 ret = obj_cgroup_charge_pages(objcg, gfp, 1 << order);
3055 page->memcg_data = (unsigned long)objcg |
3059 obj_cgroup_put(objcg);
3065 * __memcg_kmem_uncharge_page: uncharge a kmem page
3066 * @page: page to uncharge
3067 * @order: allocation order
3069 void __memcg_kmem_uncharge_page(struct page *page, int order)
3071 struct folio *folio = page_folio(page);
3072 struct obj_cgroup *objcg;
3073 unsigned int nr_pages = 1 << order;
3075 if (!folio_memcg_kmem(folio))
3078 objcg = __folio_objcg(folio);
3079 obj_cgroup_uncharge_pages(objcg, nr_pages);
3080 folio->memcg_data = 0;
3081 obj_cgroup_put(objcg);
3084 void mod_objcg_state(struct obj_cgroup *objcg, struct pglist_data *pgdat,
3085 enum node_stat_item idx, int nr)
3087 struct memcg_stock_pcp *stock;
3088 struct obj_cgroup *old = NULL;
3089 unsigned long flags;
3092 local_lock_irqsave(&memcg_stock.stock_lock, flags);
3093 stock = this_cpu_ptr(&memcg_stock);
3096 * Save vmstat data in stock and skip vmstat array update unless
3097 * accumulating over a page of vmstat data or when pgdat or idx
3100 if (stock->cached_objcg != objcg) {
3101 old = drain_obj_stock(stock);
3102 obj_cgroup_get(objcg);
3103 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3104 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3105 stock->cached_objcg = objcg;
3106 stock->cached_pgdat = pgdat;
3107 } else if (stock->cached_pgdat != pgdat) {
3108 /* Flush the existing cached vmstat data */
3109 struct pglist_data *oldpg = stock->cached_pgdat;
3111 if (stock->nr_slab_reclaimable_b) {
3112 mod_objcg_mlstate(objcg, oldpg, NR_SLAB_RECLAIMABLE_B,
3113 stock->nr_slab_reclaimable_b);
3114 stock->nr_slab_reclaimable_b = 0;
3116 if (stock->nr_slab_unreclaimable_b) {
3117 mod_objcg_mlstate(objcg, oldpg, NR_SLAB_UNRECLAIMABLE_B,
3118 stock->nr_slab_unreclaimable_b);
3119 stock->nr_slab_unreclaimable_b = 0;
3121 stock->cached_pgdat = pgdat;
3124 bytes = (idx == NR_SLAB_RECLAIMABLE_B) ? &stock->nr_slab_reclaimable_b
3125 : &stock->nr_slab_unreclaimable_b;
3127 * Even for large object >= PAGE_SIZE, the vmstat data will still be
3128 * cached locally at least once before pushing it out.
3135 if (abs(*bytes) > PAGE_SIZE) {
3143 mod_objcg_mlstate(objcg, pgdat, idx, nr);
3145 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3147 obj_cgroup_put(old);
3150 static bool consume_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes)
3152 struct memcg_stock_pcp *stock;
3153 unsigned long flags;
3156 local_lock_irqsave(&memcg_stock.stock_lock, flags);
3158 stock = this_cpu_ptr(&memcg_stock);
3159 if (objcg == stock->cached_objcg && stock->nr_bytes >= nr_bytes) {
3160 stock->nr_bytes -= nr_bytes;
3164 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3169 static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock)
3171 struct obj_cgroup *old = stock->cached_objcg;
3176 if (stock->nr_bytes) {
3177 unsigned int nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3178 unsigned int nr_bytes = stock->nr_bytes & (PAGE_SIZE - 1);
3181 struct mem_cgroup *memcg;
3183 memcg = get_mem_cgroup_from_objcg(old);
3185 memcg_account_kmem(memcg, -nr_pages);
3186 __refill_stock(memcg, nr_pages);
3188 css_put(&memcg->css);
3192 * The leftover is flushed to the centralized per-memcg value.
3193 * On the next attempt to refill obj stock it will be moved
3194 * to a per-cpu stock (probably, on an other CPU), see
3195 * refill_obj_stock().
3197 * How often it's flushed is a trade-off between the memory
3198 * limit enforcement accuracy and potential CPU contention,
3199 * so it might be changed in the future.
3201 atomic_add(nr_bytes, &old->nr_charged_bytes);
3202 stock->nr_bytes = 0;
3206 * Flush the vmstat data in current stock
3208 if (stock->nr_slab_reclaimable_b || stock->nr_slab_unreclaimable_b) {
3209 if (stock->nr_slab_reclaimable_b) {
3210 mod_objcg_mlstate(old, stock->cached_pgdat,
3211 NR_SLAB_RECLAIMABLE_B,
3212 stock->nr_slab_reclaimable_b);
3213 stock->nr_slab_reclaimable_b = 0;
3215 if (stock->nr_slab_unreclaimable_b) {
3216 mod_objcg_mlstate(old, stock->cached_pgdat,
3217 NR_SLAB_UNRECLAIMABLE_B,
3218 stock->nr_slab_unreclaimable_b);
3219 stock->nr_slab_unreclaimable_b = 0;
3221 stock->cached_pgdat = NULL;
3224 stock->cached_objcg = NULL;
3226 * The `old' objects needs to be released by the caller via
3227 * obj_cgroup_put() outside of memcg_stock_pcp::stock_lock.
3232 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
3233 struct mem_cgroup *root_memcg)
3235 struct mem_cgroup *memcg;
3237 if (stock->cached_objcg) {
3238 memcg = obj_cgroup_memcg(stock->cached_objcg);
3239 if (memcg && mem_cgroup_is_descendant(memcg, root_memcg))
3246 static void refill_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes,
3247 bool allow_uncharge)
3249 struct memcg_stock_pcp *stock;
3250 struct obj_cgroup *old = NULL;
3251 unsigned long flags;
3252 unsigned int nr_pages = 0;
3254 local_lock_irqsave(&memcg_stock.stock_lock, flags);
3256 stock = this_cpu_ptr(&memcg_stock);
3257 if (stock->cached_objcg != objcg) { /* reset if necessary */
3258 old = drain_obj_stock(stock);
3259 obj_cgroup_get(objcg);
3260 stock->cached_objcg = objcg;
3261 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3262 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3263 allow_uncharge = true; /* Allow uncharge when objcg changes */
3265 stock->nr_bytes += nr_bytes;
3267 if (allow_uncharge && (stock->nr_bytes > PAGE_SIZE)) {
3268 nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3269 stock->nr_bytes &= (PAGE_SIZE - 1);
3272 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3274 obj_cgroup_put(old);
3277 obj_cgroup_uncharge_pages(objcg, nr_pages);
3280 int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size)
3282 unsigned int nr_pages, nr_bytes;
3285 if (consume_obj_stock(objcg, size))
3289 * In theory, objcg->nr_charged_bytes can have enough
3290 * pre-charged bytes to satisfy the allocation. However,
3291 * flushing objcg->nr_charged_bytes requires two atomic
3292 * operations, and objcg->nr_charged_bytes can't be big.
3293 * The shared objcg->nr_charged_bytes can also become a
3294 * performance bottleneck if all tasks of the same memcg are
3295 * trying to update it. So it's better to ignore it and try
3296 * grab some new pages. The stock's nr_bytes will be flushed to
3297 * objcg->nr_charged_bytes later on when objcg changes.
3299 * The stock's nr_bytes may contain enough pre-charged bytes
3300 * to allow one less page from being charged, but we can't rely
3301 * on the pre-charged bytes not being changed outside of
3302 * consume_obj_stock() or refill_obj_stock(). So ignore those
3303 * pre-charged bytes as well when charging pages. To avoid a
3304 * page uncharge right after a page charge, we set the
3305 * allow_uncharge flag to false when calling refill_obj_stock()
3306 * to temporarily allow the pre-charged bytes to exceed the page
3307 * size limit. The maximum reachable value of the pre-charged
3308 * bytes is (sizeof(object) + PAGE_SIZE - 2) if there is no data
3311 nr_pages = size >> PAGE_SHIFT;
3312 nr_bytes = size & (PAGE_SIZE - 1);
3317 ret = obj_cgroup_charge_pages(objcg, gfp, nr_pages);
3318 if (!ret && nr_bytes)
3319 refill_obj_stock(objcg, PAGE_SIZE - nr_bytes, false);
3324 void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size)
3326 refill_obj_stock(objcg, size, true);
3329 #endif /* CONFIG_MEMCG_KMEM */
3332 * Because page_memcg(head) is not set on tails, set it now.
3334 void split_page_memcg(struct page *head, unsigned int nr)
3336 struct folio *folio = page_folio(head);
3337 struct mem_cgroup *memcg = folio_memcg(folio);
3340 if (mem_cgroup_disabled() || !memcg)
3343 for (i = 1; i < nr; i++)
3344 folio_page(folio, i)->memcg_data = folio->memcg_data;
3346 if (folio_memcg_kmem(folio))
3347 obj_cgroup_get_many(__folio_objcg(folio), nr - 1);
3349 css_get_many(&memcg->css, nr - 1);
3352 #ifdef CONFIG_MEMCG_SWAP
3354 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3355 * @entry: swap entry to be moved
3356 * @from: mem_cgroup which the entry is moved from
3357 * @to: mem_cgroup which the entry is moved to
3359 * It succeeds only when the swap_cgroup's record for this entry is the same
3360 * as the mem_cgroup's id of @from.
3362 * Returns 0 on success, -EINVAL on failure.
3364 * The caller must have charged to @to, IOW, called page_counter_charge() about
3365 * both res and memsw, and called css_get().
3367 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3368 struct mem_cgroup *from, struct mem_cgroup *to)
3370 unsigned short old_id, new_id;
3372 old_id = mem_cgroup_id(from);
3373 new_id = mem_cgroup_id(to);
3375 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3376 mod_memcg_state(from, MEMCG_SWAP, -1);
3377 mod_memcg_state(to, MEMCG_SWAP, 1);
3383 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3384 struct mem_cgroup *from, struct mem_cgroup *to)
3390 static DEFINE_MUTEX(memcg_max_mutex);
3392 static int mem_cgroup_resize_max(struct mem_cgroup *memcg,
3393 unsigned long max, bool memsw)
3395 bool enlarge = false;
3396 bool drained = false;
3398 bool limits_invariant;
3399 struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory;
3402 if (signal_pending(current)) {
3407 mutex_lock(&memcg_max_mutex);
3409 * Make sure that the new limit (memsw or memory limit) doesn't
3410 * break our basic invariant rule memory.max <= memsw.max.
3412 limits_invariant = memsw ? max >= READ_ONCE(memcg->memory.max) :
3413 max <= memcg->memsw.max;
3414 if (!limits_invariant) {
3415 mutex_unlock(&memcg_max_mutex);
3419 if (max > counter->max)
3421 ret = page_counter_set_max(counter, max);
3422 mutex_unlock(&memcg_max_mutex);
3428 drain_all_stock(memcg);
3433 if (!try_to_free_mem_cgroup_pages(memcg, 1,
3434 GFP_KERNEL, !memsw)) {
3440 if (!ret && enlarge)
3441 memcg_oom_recover(memcg);
3446 unsigned long mem_cgroup_soft_limit_reclaim(pg_data_t *pgdat, int order,
3448 unsigned long *total_scanned)
3450 unsigned long nr_reclaimed = 0;
3451 struct mem_cgroup_per_node *mz, *next_mz = NULL;
3452 unsigned long reclaimed;
3454 struct mem_cgroup_tree_per_node *mctz;
3455 unsigned long excess;
3460 mctz = soft_limit_tree.rb_tree_per_node[pgdat->node_id];
3463 * Do not even bother to check the largest node if the root
3464 * is empty. Do it lockless to prevent lock bouncing. Races
3465 * are acceptable as soft limit is best effort anyway.
3467 if (!mctz || RB_EMPTY_ROOT(&mctz->rb_root))
3471 * This loop can run a while, specially if mem_cgroup's continuously
3472 * keep exceeding their soft limit and putting the system under
3479 mz = mem_cgroup_largest_soft_limit_node(mctz);
3483 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, pgdat,
3484 gfp_mask, total_scanned);
3485 nr_reclaimed += reclaimed;
3486 spin_lock_irq(&mctz->lock);
3489 * If we failed to reclaim anything from this memory cgroup
3490 * it is time to move on to the next cgroup
3494 next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
3496 excess = soft_limit_excess(mz->memcg);
3498 * One school of thought says that we should not add
3499 * back the node to the tree if reclaim returns 0.
3500 * But our reclaim could return 0, simply because due
3501 * to priority we are exposing a smaller subset of
3502 * memory to reclaim from. Consider this as a longer
3505 /* If excess == 0, no tree ops */
3506 __mem_cgroup_insert_exceeded(mz, mctz, excess);
3507 spin_unlock_irq(&mctz->lock);
3508 css_put(&mz->memcg->css);
3511 * Could not reclaim anything and there are no more
3512 * mem cgroups to try or we seem to be looping without
3513 * reclaiming anything.
3515 if (!nr_reclaimed &&
3517 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3519 } while (!nr_reclaimed);
3521 css_put(&next_mz->memcg->css);
3522 return nr_reclaimed;
3526 * Reclaims as many pages from the given memcg as possible.
3528 * Caller is responsible for holding css reference for memcg.
3530 static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
3532 int nr_retries = MAX_RECLAIM_RETRIES;
3534 /* we call try-to-free pages for make this cgroup empty */
3535 lru_add_drain_all();
3537 drain_all_stock(memcg);
3539 /* try to free all pages in this cgroup */
3540 while (nr_retries && page_counter_read(&memcg->memory)) {
3541 if (signal_pending(current))
3544 if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL, true))
3551 static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
3552 char *buf, size_t nbytes,
3555 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3557 if (mem_cgroup_is_root(memcg))
3559 return mem_cgroup_force_empty(memcg) ?: nbytes;
3562 static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
3568 static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
3569 struct cftype *cft, u64 val)
3574 pr_warn_once("Non-hierarchical mode is deprecated. "
3575 "Please report your usecase to linux-mm@kvack.org if you "
3576 "depend on this functionality.\n");
3581 static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3585 if (mem_cgroup_is_root(memcg)) {
3586 mem_cgroup_flush_stats();
3587 val = memcg_page_state(memcg, NR_FILE_PAGES) +
3588 memcg_page_state(memcg, NR_ANON_MAPPED);
3590 val += memcg_page_state(memcg, MEMCG_SWAP);
3593 val = page_counter_read(&memcg->memory);
3595 val = page_counter_read(&memcg->memsw);
3608 static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
3611 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3612 struct page_counter *counter;
3614 switch (MEMFILE_TYPE(cft->private)) {
3616 counter = &memcg->memory;
3619 counter = &memcg->memsw;
3622 counter = &memcg->kmem;
3625 counter = &memcg->tcpmem;
3631 switch (MEMFILE_ATTR(cft->private)) {
3633 if (counter == &memcg->memory)
3634 return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
3635 if (counter == &memcg->memsw)
3636 return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
3637 return (u64)page_counter_read(counter) * PAGE_SIZE;
3639 return (u64)counter->max * PAGE_SIZE;
3641 return (u64)counter->watermark * PAGE_SIZE;
3643 return counter->failcnt;
3644 case RES_SOFT_LIMIT:
3645 return (u64)memcg->soft_limit * PAGE_SIZE;
3651 #ifdef CONFIG_MEMCG_KMEM
3652 static int memcg_online_kmem(struct mem_cgroup *memcg)
3654 struct obj_cgroup *objcg;
3656 if (mem_cgroup_kmem_disabled())
3659 if (unlikely(mem_cgroup_is_root(memcg)))
3662 objcg = obj_cgroup_alloc();
3666 objcg->memcg = memcg;
3667 rcu_assign_pointer(memcg->objcg, objcg);
3669 static_branch_enable(&memcg_kmem_enabled_key);
3671 memcg->kmemcg_id = memcg->id.id;
3676 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3678 struct mem_cgroup *parent;
3680 if (mem_cgroup_kmem_disabled())
3683 if (unlikely(mem_cgroup_is_root(memcg)))
3686 parent = parent_mem_cgroup(memcg);
3688 parent = root_mem_cgroup;
3690 memcg_reparent_objcgs(memcg, parent);
3693 * After we have finished memcg_reparent_objcgs(), all list_lrus
3694 * corresponding to this cgroup are guaranteed to remain empty.
3695 * The ordering is imposed by list_lru_node->lock taken by
3696 * memcg_reparent_list_lrus().
3698 memcg_reparent_list_lrus(memcg, parent);
3701 static int memcg_online_kmem(struct mem_cgroup *memcg)
3705 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3708 #endif /* CONFIG_MEMCG_KMEM */
3710 static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max)
3714 mutex_lock(&memcg_max_mutex);
3716 ret = page_counter_set_max(&memcg->tcpmem, max);
3720 if (!memcg->tcpmem_active) {
3722 * The active flag needs to be written after the static_key
3723 * update. This is what guarantees that the socket activation
3724 * function is the last one to run. See mem_cgroup_sk_alloc()
3725 * for details, and note that we don't mark any socket as
3726 * belonging to this memcg until that flag is up.
3728 * We need to do this, because static_keys will span multiple
3729 * sites, but we can't control their order. If we mark a socket
3730 * as accounted, but the accounting functions are not patched in
3731 * yet, we'll lose accounting.
3733 * We never race with the readers in mem_cgroup_sk_alloc(),
3734 * because when this value change, the code to process it is not
3737 static_branch_inc(&memcg_sockets_enabled_key);
3738 memcg->tcpmem_active = true;
3741 mutex_unlock(&memcg_max_mutex);
3746 * The user of this function is...
3749 static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
3750 char *buf, size_t nbytes, loff_t off)
3752 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3753 unsigned long nr_pages;
3756 buf = strstrip(buf);
3757 ret = page_counter_memparse(buf, "-1", &nr_pages);
3761 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3763 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3767 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3769 ret = mem_cgroup_resize_max(memcg, nr_pages, false);
3772 ret = mem_cgroup_resize_max(memcg, nr_pages, true);
3775 /* kmem.limit_in_bytes is deprecated. */
3779 ret = memcg_update_tcp_max(memcg, nr_pages);
3783 case RES_SOFT_LIMIT:
3784 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
3787 memcg->soft_limit = nr_pages;
3792 return ret ?: nbytes;
3795 static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
3796 size_t nbytes, loff_t off)
3798 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3799 struct page_counter *counter;
3801 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3803 counter = &memcg->memory;
3806 counter = &memcg->memsw;
3809 counter = &memcg->kmem;
3812 counter = &memcg->tcpmem;
3818 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3820 page_counter_reset_watermark(counter);
3823 counter->failcnt = 0;
3832 static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
3835 return mem_cgroup_from_css(css)->move_charge_at_immigrate;
3839 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3840 struct cftype *cft, u64 val)
3842 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3844 if (val & ~MOVE_MASK)
3848 * No kind of locking is needed in here, because ->can_attach() will
3849 * check this value once in the beginning of the process, and then carry
3850 * on with stale data. This means that changes to this value will only
3851 * affect task migrations starting after the change.
3853 memcg->move_charge_at_immigrate = val;
3857 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3858 struct cftype *cft, u64 val)
3866 #define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE))
3867 #define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON))
3868 #define LRU_ALL ((1 << NR_LRU_LISTS) - 1)
3870 static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
3871 int nid, unsigned int lru_mask, bool tree)
3873 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
3874 unsigned long nr = 0;
3877 VM_BUG_ON((unsigned)nid >= nr_node_ids);
3880 if (!(BIT(lru) & lru_mask))
3883 nr += lruvec_page_state(lruvec, NR_LRU_BASE + lru);
3885 nr += lruvec_page_state_local(lruvec, NR_LRU_BASE + lru);
3890 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
3891 unsigned int lru_mask,
3894 unsigned long nr = 0;
3898 if (!(BIT(lru) & lru_mask))
3901 nr += memcg_page_state(memcg, NR_LRU_BASE + lru);
3903 nr += memcg_page_state_local(memcg, NR_LRU_BASE + lru);
3908 static int memcg_numa_stat_show(struct seq_file *m, void *v)
3912 unsigned int lru_mask;
3915 static const struct numa_stat stats[] = {
3916 { "total", LRU_ALL },
3917 { "file", LRU_ALL_FILE },
3918 { "anon", LRU_ALL_ANON },
3919 { "unevictable", BIT(LRU_UNEVICTABLE) },
3921 const struct numa_stat *stat;
3923 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
3925 mem_cgroup_flush_stats();
3927 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
3928 seq_printf(m, "%s=%lu", stat->name,
3929 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
3931 for_each_node_state(nid, N_MEMORY)
3932 seq_printf(m, " N%d=%lu", nid,
3933 mem_cgroup_node_nr_lru_pages(memcg, nid,
3934 stat->lru_mask, false));
3938 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
3940 seq_printf(m, "hierarchical_%s=%lu", stat->name,
3941 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
3943 for_each_node_state(nid, N_MEMORY)
3944 seq_printf(m, " N%d=%lu", nid,
3945 mem_cgroup_node_nr_lru_pages(memcg, nid,
3946 stat->lru_mask, true));
3952 #endif /* CONFIG_NUMA */
3954 static const unsigned int memcg1_stats[] = {
3957 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3967 static const char *const memcg1_stat_names[] = {
3970 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3980 /* Universal VM events cgroup1 shows, original sort order */
3981 static const unsigned int memcg1_events[] = {
3988 static int memcg_stat_show(struct seq_file *m, void *v)
3990 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
3991 unsigned long memory, memsw;
3992 struct mem_cgroup *mi;
3995 BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats));
3997 mem_cgroup_flush_stats();
3999 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
4002 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
4004 nr = memcg_page_state_local(memcg, memcg1_stats[i]);
4005 seq_printf(m, "%s %lu\n", memcg1_stat_names[i], nr * PAGE_SIZE);
4008 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
4009 seq_printf(m, "%s %lu\n", vm_event_name(memcg1_events[i]),
4010 memcg_events_local(memcg, memcg1_events[i]));
4012 for (i = 0; i < NR_LRU_LISTS; i++)
4013 seq_printf(m, "%s %lu\n", lru_list_name(i),
4014 memcg_page_state_local(memcg, NR_LRU_BASE + i) *
4017 /* Hierarchical information */
4018 memory = memsw = PAGE_COUNTER_MAX;
4019 for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
4020 memory = min(memory, READ_ONCE(mi->memory.max));
4021 memsw = min(memsw, READ_ONCE(mi->memsw.max));
4023 seq_printf(m, "hierarchical_memory_limit %llu\n",
4024 (u64)memory * PAGE_SIZE);
4025 if (do_memsw_account())
4026 seq_printf(m, "hierarchical_memsw_limit %llu\n",
4027 (u64)memsw * PAGE_SIZE);
4029 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
4032 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
4034 nr = memcg_page_state(memcg, memcg1_stats[i]);
4035 seq_printf(m, "total_%s %llu\n", memcg1_stat_names[i],
4036 (u64)nr * PAGE_SIZE);
4039 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
4040 seq_printf(m, "total_%s %llu\n",
4041 vm_event_name(memcg1_events[i]),
4042 (u64)memcg_events(memcg, memcg1_events[i]));
4044 for (i = 0; i < NR_LRU_LISTS; i++)
4045 seq_printf(m, "total_%s %llu\n", lru_list_name(i),
4046 (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
4049 #ifdef CONFIG_DEBUG_VM
4052 struct mem_cgroup_per_node *mz;
4053 unsigned long anon_cost = 0;
4054 unsigned long file_cost = 0;
4056 for_each_online_pgdat(pgdat) {
4057 mz = memcg->nodeinfo[pgdat->node_id];
4059 anon_cost += mz->lruvec.anon_cost;
4060 file_cost += mz->lruvec.file_cost;
4062 seq_printf(m, "anon_cost %lu\n", anon_cost);
4063 seq_printf(m, "file_cost %lu\n", file_cost);
4070 static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
4073 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4075 return mem_cgroup_swappiness(memcg);
4078 static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
4079 struct cftype *cft, u64 val)
4081 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4086 if (!mem_cgroup_is_root(memcg))
4087 memcg->swappiness = val;
4089 vm_swappiness = val;
4094 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4096 struct mem_cgroup_threshold_ary *t;
4097 unsigned long usage;
4102 t = rcu_dereference(memcg->thresholds.primary);
4104 t = rcu_dereference(memcg->memsw_thresholds.primary);
4109 usage = mem_cgroup_usage(memcg, swap);
4112 * current_threshold points to threshold just below or equal to usage.
4113 * If it's not true, a threshold was crossed after last
4114 * call of __mem_cgroup_threshold().
4116 i = t->current_threshold;
4119 * Iterate backward over array of thresholds starting from
4120 * current_threshold and check if a threshold is crossed.
4121 * If none of thresholds below usage is crossed, we read
4122 * only one element of the array here.
4124 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4125 eventfd_signal(t->entries[i].eventfd, 1);
4127 /* i = current_threshold + 1 */
4131 * Iterate forward over array of thresholds starting from
4132 * current_threshold+1 and check if a threshold is crossed.
4133 * If none of thresholds above usage is crossed, we read
4134 * only one element of the array here.
4136 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4137 eventfd_signal(t->entries[i].eventfd, 1);
4139 /* Update current_threshold */
4140 t->current_threshold = i - 1;
4145 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4148 __mem_cgroup_threshold(memcg, false);
4149 if (do_memsw_account())
4150 __mem_cgroup_threshold(memcg, true);
4152 memcg = parent_mem_cgroup(memcg);
4156 static int compare_thresholds(const void *a, const void *b)
4158 const struct mem_cgroup_threshold *_a = a;
4159 const struct mem_cgroup_threshold *_b = b;
4161 if (_a->threshold > _b->threshold)
4164 if (_a->threshold < _b->threshold)
4170 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
4172 struct mem_cgroup_eventfd_list *ev;
4174 spin_lock(&memcg_oom_lock);
4176 list_for_each_entry(ev, &memcg->oom_notify, list)
4177 eventfd_signal(ev->eventfd, 1);
4179 spin_unlock(&memcg_oom_lock);
4183 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
4185 struct mem_cgroup *iter;
4187 for_each_mem_cgroup_tree(iter, memcg)
4188 mem_cgroup_oom_notify_cb(iter);
4191 static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4192 struct eventfd_ctx *eventfd, const char *args, enum res_type type)
4194 struct mem_cgroup_thresholds *thresholds;
4195 struct mem_cgroup_threshold_ary *new;
4196 unsigned long threshold;
4197 unsigned long usage;
4200 ret = page_counter_memparse(args, "-1", &threshold);
4204 mutex_lock(&memcg->thresholds_lock);
4207 thresholds = &memcg->thresholds;
4208 usage = mem_cgroup_usage(memcg, false);
4209 } else if (type == _MEMSWAP) {
4210 thresholds = &memcg->memsw_thresholds;
4211 usage = mem_cgroup_usage(memcg, true);
4215 /* Check if a threshold crossed before adding a new one */
4216 if (thresholds->primary)
4217 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4219 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4221 /* Allocate memory for new array of thresholds */
4222 new = kmalloc(struct_size(new, entries, size), GFP_KERNEL);
4229 /* Copy thresholds (if any) to new array */
4230 if (thresholds->primary)
4231 memcpy(new->entries, thresholds->primary->entries,
4232 flex_array_size(new, entries, size - 1));
4234 /* Add new threshold */
4235 new->entries[size - 1].eventfd = eventfd;
4236 new->entries[size - 1].threshold = threshold;
4238 /* Sort thresholds. Registering of new threshold isn't time-critical */
4239 sort(new->entries, size, sizeof(*new->entries),
4240 compare_thresholds, NULL);
4242 /* Find current threshold */
4243 new->current_threshold = -1;
4244 for (i = 0; i < size; i++) {
4245 if (new->entries[i].threshold <= usage) {
4247 * new->current_threshold will not be used until
4248 * rcu_assign_pointer(), so it's safe to increment
4251 ++new->current_threshold;
4256 /* Free old spare buffer and save old primary buffer as spare */
4257 kfree(thresholds->spare);
4258 thresholds->spare = thresholds->primary;
4260 rcu_assign_pointer(thresholds->primary, new);
4262 /* To be sure that nobody uses thresholds */
4266 mutex_unlock(&memcg->thresholds_lock);
4271 static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4272 struct eventfd_ctx *eventfd, const char *args)
4274 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
4277 static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
4278 struct eventfd_ctx *eventfd, const char *args)
4280 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
4283 static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4284 struct eventfd_ctx *eventfd, enum res_type type)
4286 struct mem_cgroup_thresholds *thresholds;
4287 struct mem_cgroup_threshold_ary *new;
4288 unsigned long usage;
4289 int i, j, size, entries;
4291 mutex_lock(&memcg->thresholds_lock);
4294 thresholds = &memcg->thresholds;
4295 usage = mem_cgroup_usage(memcg, false);
4296 } else if (type == _MEMSWAP) {
4297 thresholds = &memcg->memsw_thresholds;
4298 usage = mem_cgroup_usage(memcg, true);
4302 if (!thresholds->primary)
4305 /* Check if a threshold crossed before removing */
4306 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4308 /* Calculate new number of threshold */
4310 for (i = 0; i < thresholds->primary->size; i++) {
4311 if (thresholds->primary->entries[i].eventfd != eventfd)
4317 new = thresholds->spare;
4319 /* If no items related to eventfd have been cleared, nothing to do */
4323 /* Set thresholds array to NULL if we don't have thresholds */
4332 /* Copy thresholds and find current threshold */
4333 new->current_threshold = -1;
4334 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4335 if (thresholds->primary->entries[i].eventfd == eventfd)
4338 new->entries[j] = thresholds->primary->entries[i];
4339 if (new->entries[j].threshold <= usage) {
4341 * new->current_threshold will not be used
4342 * until rcu_assign_pointer(), so it's safe to increment
4345 ++new->current_threshold;
4351 /* Swap primary and spare array */
4352 thresholds->spare = thresholds->primary;
4354 rcu_assign_pointer(thresholds->primary, new);
4356 /* To be sure that nobody uses thresholds */
4359 /* If all events are unregistered, free the spare array */
4361 kfree(thresholds->spare);
4362 thresholds->spare = NULL;
4365 mutex_unlock(&memcg->thresholds_lock);
4368 static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4369 struct eventfd_ctx *eventfd)
4371 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
4374 static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4375 struct eventfd_ctx *eventfd)
4377 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
4380 static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
4381 struct eventfd_ctx *eventfd, const char *args)
4383 struct mem_cgroup_eventfd_list *event;
4385 event = kmalloc(sizeof(*event), GFP_KERNEL);
4389 spin_lock(&memcg_oom_lock);
4391 event->eventfd = eventfd;
4392 list_add(&event->list, &memcg->oom_notify);
4394 /* already in OOM ? */
4395 if (memcg->under_oom)
4396 eventfd_signal(eventfd, 1);
4397 spin_unlock(&memcg_oom_lock);
4402 static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
4403 struct eventfd_ctx *eventfd)
4405 struct mem_cgroup_eventfd_list *ev, *tmp;
4407 spin_lock(&memcg_oom_lock);
4409 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
4410 if (ev->eventfd == eventfd) {
4411 list_del(&ev->list);
4416 spin_unlock(&memcg_oom_lock);
4419 static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
4421 struct mem_cgroup *memcg = mem_cgroup_from_seq(sf);
4423 seq_printf(sf, "oom_kill_disable %d\n", memcg->oom_kill_disable);
4424 seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
4425 seq_printf(sf, "oom_kill %lu\n",
4426 atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
4430 static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
4431 struct cftype *cft, u64 val)
4433 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4435 /* cannot set to root cgroup and only 0 and 1 are allowed */
4436 if (mem_cgroup_is_root(memcg) || !((val == 0) || (val == 1)))
4439 memcg->oom_kill_disable = val;
4441 memcg_oom_recover(memcg);
4446 #ifdef CONFIG_CGROUP_WRITEBACK
4448 #include <trace/events/writeback.h>
4450 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4452 return wb_domain_init(&memcg->cgwb_domain, gfp);
4455 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4457 wb_domain_exit(&memcg->cgwb_domain);
4460 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4462 wb_domain_size_changed(&memcg->cgwb_domain);
4465 struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
4467 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4469 if (!memcg->css.parent)
4472 return &memcg->cgwb_domain;
4476 * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
4477 * @wb: bdi_writeback in question
4478 * @pfilepages: out parameter for number of file pages
4479 * @pheadroom: out parameter for number of allocatable pages according to memcg
4480 * @pdirty: out parameter for number of dirty pages
4481 * @pwriteback: out parameter for number of pages under writeback
4483 * Determine the numbers of file, headroom, dirty, and writeback pages in
4484 * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom
4485 * is a bit more involved.
4487 * A memcg's headroom is "min(max, high) - used". In the hierarchy, the
4488 * headroom is calculated as the lowest headroom of itself and the
4489 * ancestors. Note that this doesn't consider the actual amount of
4490 * available memory in the system. The caller should further cap
4491 * *@pheadroom accordingly.
4493 void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
4494 unsigned long *pheadroom, unsigned long *pdirty,
4495 unsigned long *pwriteback)
4497 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4498 struct mem_cgroup *parent;
4500 mem_cgroup_flush_stats();
4502 *pdirty = memcg_page_state(memcg, NR_FILE_DIRTY);
4503 *pwriteback = memcg_page_state(memcg, NR_WRITEBACK);
4504 *pfilepages = memcg_page_state(memcg, NR_INACTIVE_FILE) +
4505 memcg_page_state(memcg, NR_ACTIVE_FILE);
4507 *pheadroom = PAGE_COUNTER_MAX;
4508 while ((parent = parent_mem_cgroup(memcg))) {
4509 unsigned long ceiling = min(READ_ONCE(memcg->memory.max),
4510 READ_ONCE(memcg->memory.high));
4511 unsigned long used = page_counter_read(&memcg->memory);
4513 *pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
4519 * Foreign dirty flushing
4521 * There's an inherent mismatch between memcg and writeback. The former
4522 * tracks ownership per-page while the latter per-inode. This was a
4523 * deliberate design decision because honoring per-page ownership in the
4524 * writeback path is complicated, may lead to higher CPU and IO overheads
4525 * and deemed unnecessary given that write-sharing an inode across
4526 * different cgroups isn't a common use-case.
4528 * Combined with inode majority-writer ownership switching, this works well
4529 * enough in most cases but there are some pathological cases. For
4530 * example, let's say there are two cgroups A and B which keep writing to
4531 * different but confined parts of the same inode. B owns the inode and
4532 * A's memory is limited far below B's. A's dirty ratio can rise enough to
4533 * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
4534 * triggering background writeback. A will be slowed down without a way to
4535 * make writeback of the dirty pages happen.
4537 * Conditions like the above can lead to a cgroup getting repeatedly and
4538 * severely throttled after making some progress after each
4539 * dirty_expire_interval while the underlying IO device is almost
4542 * Solving this problem completely requires matching the ownership tracking
4543 * granularities between memcg and writeback in either direction. However,
4544 * the more egregious behaviors can be avoided by simply remembering the
4545 * most recent foreign dirtying events and initiating remote flushes on
4546 * them when local writeback isn't enough to keep the memory clean enough.
4548 * The following two functions implement such mechanism. When a foreign
4549 * page - a page whose memcg and writeback ownerships don't match - is
4550 * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
4551 * bdi_writeback on the page owning memcg. When balance_dirty_pages()
4552 * decides that the memcg needs to sleep due to high dirty ratio, it calls
4553 * mem_cgroup_flush_foreign() which queues writeback on the recorded
4554 * foreign bdi_writebacks which haven't expired. Both the numbers of
4555 * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
4556 * limited to MEMCG_CGWB_FRN_CNT.
4558 * The mechanism only remembers IDs and doesn't hold any object references.
4559 * As being wrong occasionally doesn't matter, updates and accesses to the
4560 * records are lockless and racy.
4562 void mem_cgroup_track_foreign_dirty_slowpath(struct folio *folio,
4563 struct bdi_writeback *wb)
4565 struct mem_cgroup *memcg = folio_memcg(folio);
4566 struct memcg_cgwb_frn *frn;
4567 u64 now = get_jiffies_64();
4568 u64 oldest_at = now;
4572 trace_track_foreign_dirty(folio, wb);
4575 * Pick the slot to use. If there is already a slot for @wb, keep
4576 * using it. If not replace the oldest one which isn't being
4579 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4580 frn = &memcg->cgwb_frn[i];
4581 if (frn->bdi_id == wb->bdi->id &&
4582 frn->memcg_id == wb->memcg_css->id)
4584 if (time_before64(frn->at, oldest_at) &&
4585 atomic_read(&frn->done.cnt) == 1) {
4587 oldest_at = frn->at;
4591 if (i < MEMCG_CGWB_FRN_CNT) {
4593 * Re-using an existing one. Update timestamp lazily to
4594 * avoid making the cacheline hot. We want them to be
4595 * reasonably up-to-date and significantly shorter than
4596 * dirty_expire_interval as that's what expires the record.
4597 * Use the shorter of 1s and dirty_expire_interval / 8.
4599 unsigned long update_intv =
4600 min_t(unsigned long, HZ,
4601 msecs_to_jiffies(dirty_expire_interval * 10) / 8);
4603 if (time_before64(frn->at, now - update_intv))
4605 } else if (oldest >= 0) {
4606 /* replace the oldest free one */
4607 frn = &memcg->cgwb_frn[oldest];
4608 frn->bdi_id = wb->bdi->id;
4609 frn->memcg_id = wb->memcg_css->id;
4614 /* issue foreign writeback flushes for recorded foreign dirtying events */
4615 void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
4617 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4618 unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
4619 u64 now = jiffies_64;
4622 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4623 struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
4626 * If the record is older than dirty_expire_interval,
4627 * writeback on it has already started. No need to kick it
4628 * off again. Also, don't start a new one if there's
4629 * already one in flight.
4631 if (time_after64(frn->at, now - intv) &&
4632 atomic_read(&frn->done.cnt) == 1) {
4634 trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
4635 cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id,
4636 WB_REASON_FOREIGN_FLUSH,
4642 #else /* CONFIG_CGROUP_WRITEBACK */
4644 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4649 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4653 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4657 #endif /* CONFIG_CGROUP_WRITEBACK */
4660 * DO NOT USE IN NEW FILES.
4662 * "cgroup.event_control" implementation.
4664 * This is way over-engineered. It tries to support fully configurable
4665 * events for each user. Such level of flexibility is completely
4666 * unnecessary especially in the light of the planned unified hierarchy.
4668 * Please deprecate this and replace with something simpler if at all
4673 * Unregister event and free resources.
4675 * Gets called from workqueue.
4677 static void memcg_event_remove(struct work_struct *work)
4679 struct mem_cgroup_event *event =
4680 container_of(work, struct mem_cgroup_event, remove);
4681 struct mem_cgroup *memcg = event->memcg;
4683 remove_wait_queue(event->wqh, &event->wait);
4685 event->unregister_event(memcg, event->eventfd);
4687 /* Notify userspace the event is going away. */
4688 eventfd_signal(event->eventfd, 1);
4690 eventfd_ctx_put(event->eventfd);
4692 css_put(&memcg->css);
4696 * Gets called on EPOLLHUP on eventfd when user closes it.
4698 * Called with wqh->lock held and interrupts disabled.
4700 static int memcg_event_wake(wait_queue_entry_t *wait, unsigned mode,
4701 int sync, void *key)
4703 struct mem_cgroup_event *event =
4704 container_of(wait, struct mem_cgroup_event, wait);
4705 struct mem_cgroup *memcg = event->memcg;
4706 __poll_t flags = key_to_poll(key);
4708 if (flags & EPOLLHUP) {
4710 * If the event has been detached at cgroup removal, we
4711 * can simply return knowing the other side will cleanup
4714 * We can't race against event freeing since the other
4715 * side will require wqh->lock via remove_wait_queue(),
4718 spin_lock(&memcg->event_list_lock);
4719 if (!list_empty(&event->list)) {
4720 list_del_init(&event->list);
4722 * We are in atomic context, but cgroup_event_remove()
4723 * may sleep, so we have to call it in workqueue.
4725 schedule_work(&event->remove);
4727 spin_unlock(&memcg->event_list_lock);
4733 static void memcg_event_ptable_queue_proc(struct file *file,
4734 wait_queue_head_t *wqh, poll_table *pt)
4736 struct mem_cgroup_event *event =
4737 container_of(pt, struct mem_cgroup_event, pt);
4740 add_wait_queue(wqh, &event->wait);
4744 * DO NOT USE IN NEW FILES.
4746 * Parse input and register new cgroup event handler.
4748 * Input must be in format '<event_fd> <control_fd> <args>'.
4749 * Interpretation of args is defined by control file implementation.
4751 static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
4752 char *buf, size_t nbytes, loff_t off)
4754 struct cgroup_subsys_state *css = of_css(of);
4755 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4756 struct mem_cgroup_event *event;
4757 struct cgroup_subsys_state *cfile_css;
4758 unsigned int efd, cfd;
4765 if (IS_ENABLED(CONFIG_PREEMPT_RT))
4768 buf = strstrip(buf);
4770 efd = simple_strtoul(buf, &endp, 10);
4775 cfd = simple_strtoul(buf, &endp, 10);
4776 if ((*endp != ' ') && (*endp != '\0'))
4780 event = kzalloc(sizeof(*event), GFP_KERNEL);
4784 event->memcg = memcg;
4785 INIT_LIST_HEAD(&event->list);
4786 init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
4787 init_waitqueue_func_entry(&event->wait, memcg_event_wake);
4788 INIT_WORK(&event->remove, memcg_event_remove);
4796 event->eventfd = eventfd_ctx_fileget(efile.file);
4797 if (IS_ERR(event->eventfd)) {
4798 ret = PTR_ERR(event->eventfd);
4805 goto out_put_eventfd;
4808 /* the process need read permission on control file */
4809 /* AV: shouldn't we check that it's been opened for read instead? */
4810 ret = file_permission(cfile.file, MAY_READ);
4815 * Determine the event callbacks and set them in @event. This used
4816 * to be done via struct cftype but cgroup core no longer knows
4817 * about these events. The following is crude but the whole thing
4818 * is for compatibility anyway.
4820 * DO NOT ADD NEW FILES.
4822 name = cfile.file->f_path.dentry->d_name.name;
4824 if (!strcmp(name, "memory.usage_in_bytes")) {
4825 event->register_event = mem_cgroup_usage_register_event;
4826 event->unregister_event = mem_cgroup_usage_unregister_event;
4827 } else if (!strcmp(name, "memory.oom_control")) {
4828 event->register_event = mem_cgroup_oom_register_event;
4829 event->unregister_event = mem_cgroup_oom_unregister_event;
4830 } else if (!strcmp(name, "memory.pressure_level")) {
4831 event->register_event = vmpressure_register_event;
4832 event->unregister_event = vmpressure_unregister_event;
4833 } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
4834 event->register_event = memsw_cgroup_usage_register_event;
4835 event->unregister_event = memsw_cgroup_usage_unregister_event;
4842 * Verify @cfile should belong to @css. Also, remaining events are
4843 * automatically removed on cgroup destruction but the removal is
4844 * asynchronous, so take an extra ref on @css.
4846 cfile_css = css_tryget_online_from_dir(cfile.file->f_path.dentry->d_parent,
4847 &memory_cgrp_subsys);
4849 if (IS_ERR(cfile_css))
4851 if (cfile_css != css) {
4856 ret = event->register_event(memcg, event->eventfd, buf);
4860 vfs_poll(efile.file, &event->pt);
4862 spin_lock_irq(&memcg->event_list_lock);
4863 list_add(&event->list, &memcg->event_list);
4864 spin_unlock_irq(&memcg->event_list_lock);
4876 eventfd_ctx_put(event->eventfd);
4885 #if defined(CONFIG_MEMCG_KMEM) && (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG))
4886 static int mem_cgroup_slab_show(struct seq_file *m, void *p)
4890 * Please, take a look at tools/cgroup/memcg_slabinfo.py .
4896 static struct cftype mem_cgroup_legacy_files[] = {
4898 .name = "usage_in_bytes",
4899 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
4900 .read_u64 = mem_cgroup_read_u64,
4903 .name = "max_usage_in_bytes",
4904 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
4905 .write = mem_cgroup_reset,
4906 .read_u64 = mem_cgroup_read_u64,
4909 .name = "limit_in_bytes",
4910 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
4911 .write = mem_cgroup_write,
4912 .read_u64 = mem_cgroup_read_u64,
4915 .name = "soft_limit_in_bytes",
4916 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
4917 .write = mem_cgroup_write,
4918 .read_u64 = mem_cgroup_read_u64,
4922 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
4923 .write = mem_cgroup_reset,
4924 .read_u64 = mem_cgroup_read_u64,
4928 .seq_show = memcg_stat_show,
4931 .name = "force_empty",
4932 .write = mem_cgroup_force_empty_write,
4935 .name = "use_hierarchy",
4936 .write_u64 = mem_cgroup_hierarchy_write,
4937 .read_u64 = mem_cgroup_hierarchy_read,
4940 .name = "cgroup.event_control", /* XXX: for compat */
4941 .write = memcg_write_event_control,
4942 .flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE,
4945 .name = "swappiness",
4946 .read_u64 = mem_cgroup_swappiness_read,
4947 .write_u64 = mem_cgroup_swappiness_write,
4950 .name = "move_charge_at_immigrate",
4951 .read_u64 = mem_cgroup_move_charge_read,
4952 .write_u64 = mem_cgroup_move_charge_write,
4955 .name = "oom_control",
4956 .seq_show = mem_cgroup_oom_control_read,
4957 .write_u64 = mem_cgroup_oom_control_write,
4960 .name = "pressure_level",
4964 .name = "numa_stat",
4965 .seq_show = memcg_numa_stat_show,
4969 .name = "kmem.limit_in_bytes",
4970 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
4971 .write = mem_cgroup_write,
4972 .read_u64 = mem_cgroup_read_u64,
4975 .name = "kmem.usage_in_bytes",
4976 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
4977 .read_u64 = mem_cgroup_read_u64,
4980 .name = "kmem.failcnt",
4981 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
4982 .write = mem_cgroup_reset,
4983 .read_u64 = mem_cgroup_read_u64,
4986 .name = "kmem.max_usage_in_bytes",
4987 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
4988 .write = mem_cgroup_reset,
4989 .read_u64 = mem_cgroup_read_u64,
4991 #if defined(CONFIG_MEMCG_KMEM) && \
4992 (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG))
4994 .name = "kmem.slabinfo",
4995 .seq_show = mem_cgroup_slab_show,
4999 .name = "kmem.tcp.limit_in_bytes",
5000 .private = MEMFILE_PRIVATE(_TCP, RES_LIMIT),
5001 .write = mem_cgroup_write,
5002 .read_u64 = mem_cgroup_read_u64,
5005 .name = "kmem.tcp.usage_in_bytes",
5006 .private = MEMFILE_PRIVATE(_TCP, RES_USAGE),
5007 .read_u64 = mem_cgroup_read_u64,
5010 .name = "kmem.tcp.failcnt",
5011 .private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT),
5012 .write = mem_cgroup_reset,
5013 .read_u64 = mem_cgroup_read_u64,
5016 .name = "kmem.tcp.max_usage_in_bytes",
5017 .private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE),
5018 .write = mem_cgroup_reset,
5019 .read_u64 = mem_cgroup_read_u64,
5021 { }, /* terminate */
5025 * Private memory cgroup IDR
5027 * Swap-out records and page cache shadow entries need to store memcg
5028 * references in constrained space, so we maintain an ID space that is
5029 * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
5030 * memory-controlled cgroups to 64k.
5032 * However, there usually are many references to the offline CSS after
5033 * the cgroup has been destroyed, such as page cache or reclaimable
5034 * slab objects, that don't need to hang on to the ID. We want to keep
5035 * those dead CSS from occupying IDs, or we might quickly exhaust the
5036 * relatively small ID space and prevent the creation of new cgroups
5037 * even when there are much fewer than 64k cgroups - possibly none.
5039 * Maintain a private 16-bit ID space for memcg, and allow the ID to
5040 * be freed and recycled when it's no longer needed, which is usually
5041 * when the CSS is offlined.
5043 * The only exception to that are records of swapped out tmpfs/shmem
5044 * pages that need to be attributed to live ancestors on swapin. But
5045 * those references are manageable from userspace.
5048 static DEFINE_IDR(mem_cgroup_idr);
5050 static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
5052 if (memcg->id.id > 0) {
5053 idr_remove(&mem_cgroup_idr, memcg->id.id);
5058 static void __maybe_unused mem_cgroup_id_get_many(struct mem_cgroup *memcg,
5061 refcount_add(n, &memcg->id.ref);
5064 static void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
5066 if (refcount_sub_and_test(n, &memcg->id.ref)) {
5067 mem_cgroup_id_remove(memcg);
5069 /* Memcg ID pins CSS */
5070 css_put(&memcg->css);
5074 static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
5076 mem_cgroup_id_put_many(memcg, 1);
5080 * mem_cgroup_from_id - look up a memcg from a memcg id
5081 * @id: the memcg id to look up
5083 * Caller must hold rcu_read_lock().
5085 struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
5087 WARN_ON_ONCE(!rcu_read_lock_held());
5088 return idr_find(&mem_cgroup_idr, id);
5091 #ifdef CONFIG_SHRINKER_DEBUG
5092 struct mem_cgroup *mem_cgroup_get_from_ino(unsigned long ino)
5094 struct cgroup *cgrp;
5095 struct cgroup_subsys_state *css;
5096 struct mem_cgroup *memcg;
5098 cgrp = cgroup_get_from_id(ino);
5100 return ERR_PTR(-ENOENT);
5102 css = cgroup_get_e_css(cgrp, &memory_cgrp_subsys);
5104 memcg = container_of(css, struct mem_cgroup, css);
5106 memcg = ERR_PTR(-ENOENT);
5114 static int alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5116 struct mem_cgroup_per_node *pn;
5118 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, node);
5122 pn->lruvec_stats_percpu = alloc_percpu_gfp(struct lruvec_stats_percpu,
5123 GFP_KERNEL_ACCOUNT);
5124 if (!pn->lruvec_stats_percpu) {
5129 lruvec_init(&pn->lruvec);
5132 memcg->nodeinfo[node] = pn;
5136 static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5138 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
5143 free_percpu(pn->lruvec_stats_percpu);
5147 static void __mem_cgroup_free(struct mem_cgroup *memcg)
5152 free_mem_cgroup_per_node_info(memcg, node);
5153 free_percpu(memcg->vmstats_percpu);
5157 static void mem_cgroup_free(struct mem_cgroup *memcg)
5159 memcg_wb_domain_exit(memcg);
5160 __mem_cgroup_free(memcg);
5163 static struct mem_cgroup *mem_cgroup_alloc(void)
5165 struct mem_cgroup *memcg;
5167 int __maybe_unused i;
5168 long error = -ENOMEM;
5170 memcg = kzalloc(struct_size(memcg, nodeinfo, nr_node_ids), GFP_KERNEL);
5172 return ERR_PTR(error);
5174 memcg->id.id = idr_alloc(&mem_cgroup_idr, NULL,
5175 1, MEM_CGROUP_ID_MAX + 1, GFP_KERNEL);
5176 if (memcg->id.id < 0) {
5177 error = memcg->id.id;
5181 memcg->vmstats_percpu = alloc_percpu_gfp(struct memcg_vmstats_percpu,
5182 GFP_KERNEL_ACCOUNT);
5183 if (!memcg->vmstats_percpu)
5187 if (alloc_mem_cgroup_per_node_info(memcg, node))
5190 if (memcg_wb_domain_init(memcg, GFP_KERNEL))
5193 INIT_WORK(&memcg->high_work, high_work_func);
5194 INIT_LIST_HEAD(&memcg->oom_notify);
5195 mutex_init(&memcg->thresholds_lock);
5196 spin_lock_init(&memcg->move_lock);
5197 vmpressure_init(&memcg->vmpressure);
5198 INIT_LIST_HEAD(&memcg->event_list);
5199 spin_lock_init(&memcg->event_list_lock);
5200 memcg->socket_pressure = jiffies;
5201 #ifdef CONFIG_MEMCG_KMEM
5202 memcg->kmemcg_id = -1;
5203 INIT_LIST_HEAD(&memcg->objcg_list);
5205 #ifdef CONFIG_CGROUP_WRITEBACK
5206 INIT_LIST_HEAD(&memcg->cgwb_list);
5207 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5208 memcg->cgwb_frn[i].done =
5209 __WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
5211 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5212 spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
5213 INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
5214 memcg->deferred_split_queue.split_queue_len = 0;
5216 idr_replace(&mem_cgroup_idr, memcg, memcg->id.id);
5219 mem_cgroup_id_remove(memcg);
5220 __mem_cgroup_free(memcg);
5221 return ERR_PTR(error);
5224 static struct cgroup_subsys_state * __ref
5225 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
5227 struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
5228 struct mem_cgroup *memcg, *old_memcg;
5230 old_memcg = set_active_memcg(parent);
5231 memcg = mem_cgroup_alloc();
5232 set_active_memcg(old_memcg);
5234 return ERR_CAST(memcg);
5236 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5237 memcg->soft_limit = PAGE_COUNTER_MAX;
5238 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
5239 memcg->zswap_max = PAGE_COUNTER_MAX;
5241 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5243 memcg->swappiness = mem_cgroup_swappiness(parent);
5244 memcg->oom_kill_disable = parent->oom_kill_disable;
5246 page_counter_init(&memcg->memory, &parent->memory);
5247 page_counter_init(&memcg->swap, &parent->swap);
5248 page_counter_init(&memcg->kmem, &parent->kmem);
5249 page_counter_init(&memcg->tcpmem, &parent->tcpmem);
5251 page_counter_init(&memcg->memory, NULL);
5252 page_counter_init(&memcg->swap, NULL);
5253 page_counter_init(&memcg->kmem, NULL);
5254 page_counter_init(&memcg->tcpmem, NULL);
5256 root_mem_cgroup = memcg;
5260 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5261 static_branch_inc(&memcg_sockets_enabled_key);
5266 static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
5268 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5270 if (memcg_online_kmem(memcg))
5274 * A memcg must be visible for expand_shrinker_info()
5275 * by the time the maps are allocated. So, we allocate maps
5276 * here, when for_each_mem_cgroup() can't skip it.
5278 if (alloc_shrinker_info(memcg))
5281 /* Online state pins memcg ID, memcg ID pins CSS */
5282 refcount_set(&memcg->id.ref, 1);
5285 if (unlikely(mem_cgroup_is_root(memcg)))
5286 queue_delayed_work(system_unbound_wq, &stats_flush_dwork,
5290 memcg_offline_kmem(memcg);
5292 mem_cgroup_id_remove(memcg);
5296 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
5298 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5299 struct mem_cgroup_event *event, *tmp;
5302 * Unregister events and notify userspace.
5303 * Notify userspace about cgroup removing only after rmdir of cgroup
5304 * directory to avoid race between userspace and kernelspace.
5306 spin_lock_irq(&memcg->event_list_lock);
5307 list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
5308 list_del_init(&event->list);
5309 schedule_work(&event->remove);
5311 spin_unlock_irq(&memcg->event_list_lock);
5313 page_counter_set_min(&memcg->memory, 0);
5314 page_counter_set_low(&memcg->memory, 0);
5316 memcg_offline_kmem(memcg);
5317 reparent_shrinker_deferred(memcg);
5318 wb_memcg_offline(memcg);
5320 drain_all_stock(memcg);
5322 mem_cgroup_id_put(memcg);
5325 static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
5327 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5329 invalidate_reclaim_iterators(memcg);
5332 static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
5334 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5335 int __maybe_unused i;
5337 #ifdef CONFIG_CGROUP_WRITEBACK
5338 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5339 wb_wait_for_completion(&memcg->cgwb_frn[i].done);
5341 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5342 static_branch_dec(&memcg_sockets_enabled_key);
5344 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg->tcpmem_active)
5345 static_branch_dec(&memcg_sockets_enabled_key);
5347 vmpressure_cleanup(&memcg->vmpressure);
5348 cancel_work_sync(&memcg->high_work);
5349 mem_cgroup_remove_from_trees(memcg);
5350 free_shrinker_info(memcg);
5351 mem_cgroup_free(memcg);
5355 * mem_cgroup_css_reset - reset the states of a mem_cgroup
5356 * @css: the target css
5358 * Reset the states of the mem_cgroup associated with @css. This is
5359 * invoked when the userland requests disabling on the default hierarchy
5360 * but the memcg is pinned through dependency. The memcg should stop
5361 * applying policies and should revert to the vanilla state as it may be
5362 * made visible again.
5364 * The current implementation only resets the essential configurations.
5365 * This needs to be expanded to cover all the visible parts.
5367 static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
5369 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5371 page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
5372 page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
5373 page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
5374 page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
5375 page_counter_set_min(&memcg->memory, 0);
5376 page_counter_set_low(&memcg->memory, 0);
5377 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5378 memcg->soft_limit = PAGE_COUNTER_MAX;
5379 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5380 memcg_wb_domain_size_changed(memcg);
5383 static void mem_cgroup_css_rstat_flush(struct cgroup_subsys_state *css, int cpu)
5385 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5386 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
5387 struct memcg_vmstats_percpu *statc;
5391 statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
5393 for (i = 0; i < MEMCG_NR_STAT; i++) {
5395 * Collect the aggregated propagation counts of groups
5396 * below us. We're in a per-cpu loop here and this is
5397 * a global counter, so the first cycle will get them.
5399 delta = memcg->vmstats.state_pending[i];
5401 memcg->vmstats.state_pending[i] = 0;
5403 /* Add CPU changes on this level since the last flush */
5404 v = READ_ONCE(statc->state[i]);
5405 if (v != statc->state_prev[i]) {
5406 delta += v - statc->state_prev[i];
5407 statc->state_prev[i] = v;
5413 /* Aggregate counts on this level and propagate upwards */
5414 memcg->vmstats.state[i] += delta;
5416 parent->vmstats.state_pending[i] += delta;
5419 for (i = 0; i < NR_VM_EVENT_ITEMS; i++) {
5420 delta = memcg->vmstats.events_pending[i];
5422 memcg->vmstats.events_pending[i] = 0;
5424 v = READ_ONCE(statc->events[i]);
5425 if (v != statc->events_prev[i]) {
5426 delta += v - statc->events_prev[i];
5427 statc->events_prev[i] = v;
5433 memcg->vmstats.events[i] += delta;
5435 parent->vmstats.events_pending[i] += delta;
5438 for_each_node_state(nid, N_MEMORY) {
5439 struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
5440 struct mem_cgroup_per_node *ppn = NULL;
5441 struct lruvec_stats_percpu *lstatc;
5444 ppn = parent->nodeinfo[nid];
5446 lstatc = per_cpu_ptr(pn->lruvec_stats_percpu, cpu);
5448 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++) {
5449 delta = pn->lruvec_stats.state_pending[i];
5451 pn->lruvec_stats.state_pending[i] = 0;
5453 v = READ_ONCE(lstatc->state[i]);
5454 if (v != lstatc->state_prev[i]) {
5455 delta += v - lstatc->state_prev[i];
5456 lstatc->state_prev[i] = v;
5462 pn->lruvec_stats.state[i] += delta;
5464 ppn->lruvec_stats.state_pending[i] += delta;
5470 /* Handlers for move charge at task migration. */
5471 static int mem_cgroup_do_precharge(unsigned long count)
5475 /* Try a single bulk charge without reclaim first, kswapd may wake */
5476 ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count);
5478 mc.precharge += count;
5482 /* Try charges one by one with reclaim, but do not retry */
5484 ret = try_charge(mc.to, GFP_KERNEL | __GFP_NORETRY, 1);
5498 enum mc_target_type {
5505 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5506 unsigned long addr, pte_t ptent)
5508 struct page *page = vm_normal_page(vma, addr, ptent);
5510 if (!page || !page_mapped(page))
5512 if (PageAnon(page)) {
5513 if (!(mc.flags & MOVE_ANON))
5516 if (!(mc.flags & MOVE_FILE))
5519 if (!get_page_unless_zero(page))
5525 #if defined(CONFIG_SWAP) || defined(CONFIG_DEVICE_PRIVATE)
5526 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5527 pte_t ptent, swp_entry_t *entry)
5529 struct page *page = NULL;
5530 swp_entry_t ent = pte_to_swp_entry(ptent);
5532 if (!(mc.flags & MOVE_ANON))
5536 * Handle device private pages that are not accessible by the CPU, but
5537 * stored as special swap entries in the page table.
5539 if (is_device_private_entry(ent)) {
5540 page = pfn_swap_entry_to_page(ent);
5541 if (!get_page_unless_zero(page))
5546 if (non_swap_entry(ent))
5550 * Because lookup_swap_cache() updates some statistics counter,
5551 * we call find_get_page() with swapper_space directly.
5553 page = find_get_page(swap_address_space(ent), swp_offset(ent));
5554 entry->val = ent.val;
5559 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5560 pte_t ptent, swp_entry_t *entry)
5566 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5567 unsigned long addr, pte_t ptent)
5569 if (!vma->vm_file) /* anonymous vma */
5571 if (!(mc.flags & MOVE_FILE))
5574 /* page is moved even if it's not RSS of this task(page-faulted). */
5575 /* shmem/tmpfs may report page out on swap: account for that too. */
5576 return find_get_incore_page(vma->vm_file->f_mapping,
5577 linear_page_index(vma, addr));
5581 * mem_cgroup_move_account - move account of the page
5583 * @compound: charge the page as compound or small page
5584 * @from: mem_cgroup which the page is moved from.
5585 * @to: mem_cgroup which the page is moved to. @from != @to.
5587 * The caller must make sure the page is not on LRU (isolate_page() is useful.)
5589 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
5592 static int mem_cgroup_move_account(struct page *page,
5594 struct mem_cgroup *from,
5595 struct mem_cgroup *to)
5597 struct folio *folio = page_folio(page);
5598 struct lruvec *from_vec, *to_vec;
5599 struct pglist_data *pgdat;
5600 unsigned int nr_pages = compound ? folio_nr_pages(folio) : 1;
5603 VM_BUG_ON(from == to);
5604 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
5605 VM_BUG_ON(compound && !folio_test_large(folio));
5608 * Prevent mem_cgroup_migrate() from looking at
5609 * page's memory cgroup of its source page while we change it.
5612 if (!folio_trylock(folio))
5616 if (folio_memcg(folio) != from)
5619 pgdat = folio_pgdat(folio);
5620 from_vec = mem_cgroup_lruvec(from, pgdat);
5621 to_vec = mem_cgroup_lruvec(to, pgdat);
5623 folio_memcg_lock(folio);
5625 if (folio_test_anon(folio)) {
5626 if (folio_mapped(folio)) {
5627 __mod_lruvec_state(from_vec, NR_ANON_MAPPED, -nr_pages);
5628 __mod_lruvec_state(to_vec, NR_ANON_MAPPED, nr_pages);
5629 if (folio_test_transhuge(folio)) {
5630 __mod_lruvec_state(from_vec, NR_ANON_THPS,
5632 __mod_lruvec_state(to_vec, NR_ANON_THPS,
5637 __mod_lruvec_state(from_vec, NR_FILE_PAGES, -nr_pages);
5638 __mod_lruvec_state(to_vec, NR_FILE_PAGES, nr_pages);
5640 if (folio_test_swapbacked(folio)) {
5641 __mod_lruvec_state(from_vec, NR_SHMEM, -nr_pages);
5642 __mod_lruvec_state(to_vec, NR_SHMEM, nr_pages);
5645 if (folio_mapped(folio)) {
5646 __mod_lruvec_state(from_vec, NR_FILE_MAPPED, -nr_pages);
5647 __mod_lruvec_state(to_vec, NR_FILE_MAPPED, nr_pages);
5650 if (folio_test_dirty(folio)) {
5651 struct address_space *mapping = folio_mapping(folio);
5653 if (mapping_can_writeback(mapping)) {
5654 __mod_lruvec_state(from_vec, NR_FILE_DIRTY,
5656 __mod_lruvec_state(to_vec, NR_FILE_DIRTY,
5662 if (folio_test_writeback(folio)) {
5663 __mod_lruvec_state(from_vec, NR_WRITEBACK, -nr_pages);
5664 __mod_lruvec_state(to_vec, NR_WRITEBACK, nr_pages);
5668 * All state has been migrated, let's switch to the new memcg.
5670 * It is safe to change page's memcg here because the page
5671 * is referenced, charged, isolated, and locked: we can't race
5672 * with (un)charging, migration, LRU putback, or anything else
5673 * that would rely on a stable page's memory cgroup.
5675 * Note that lock_page_memcg is a memcg lock, not a page lock,
5676 * to save space. As soon as we switch page's memory cgroup to a
5677 * new memcg that isn't locked, the above state can change
5678 * concurrently again. Make sure we're truly done with it.
5683 css_put(&from->css);
5685 folio->memcg_data = (unsigned long)to;
5687 __folio_memcg_unlock(from);
5690 nid = folio_nid(folio);
5692 local_irq_disable();
5693 mem_cgroup_charge_statistics(to, nr_pages);
5694 memcg_check_events(to, nid);
5695 mem_cgroup_charge_statistics(from, -nr_pages);
5696 memcg_check_events(from, nid);
5699 folio_unlock(folio);
5705 * get_mctgt_type - get target type of moving charge
5706 * @vma: the vma the pte to be checked belongs
5707 * @addr: the address corresponding to the pte to be checked
5708 * @ptent: the pte to be checked
5709 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5712 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5713 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5714 * move charge. if @target is not NULL, the page is stored in target->page
5715 * with extra refcnt got(Callers should handle it).
5716 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5717 * target for charge migration. if @target is not NULL, the entry is stored
5719 * 3(MC_TARGET_DEVICE): like MC_TARGET_PAGE but page is device memory and
5720 * thus not on the lru.
5721 * For now we such page is charge like a regular page would be as for all
5722 * intent and purposes it is just special memory taking the place of a
5725 * See Documentations/vm/hmm.txt and include/linux/hmm.h
5727 * Called with pte lock held.
5730 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
5731 unsigned long addr, pte_t ptent, union mc_target *target)
5733 struct page *page = NULL;
5734 enum mc_target_type ret = MC_TARGET_NONE;
5735 swp_entry_t ent = { .val = 0 };
5737 if (pte_present(ptent))
5738 page = mc_handle_present_pte(vma, addr, ptent);
5739 else if (pte_none_mostly(ptent))
5741 * PTE markers should be treated as a none pte here, separated
5742 * from other swap handling below.
5744 page = mc_handle_file_pte(vma, addr, ptent);
5745 else if (is_swap_pte(ptent))
5746 page = mc_handle_swap_pte(vma, ptent, &ent);
5748 if (!page && !ent.val)
5752 * Do only loose check w/o serialization.
5753 * mem_cgroup_move_account() checks the page is valid or
5754 * not under LRU exclusion.
5756 if (page_memcg(page) == mc.from) {
5757 ret = MC_TARGET_PAGE;
5758 if (is_device_private_page(page) ||
5759 is_device_coherent_page(page))
5760 ret = MC_TARGET_DEVICE;
5762 target->page = page;
5764 if (!ret || !target)
5768 * There is a swap entry and a page doesn't exist or isn't charged.
5769 * But we cannot move a tail-page in a THP.
5771 if (ent.val && !ret && (!page || !PageTransCompound(page)) &&
5772 mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
5773 ret = MC_TARGET_SWAP;
5780 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5782 * We don't consider PMD mapped swapping or file mapped pages because THP does
5783 * not support them for now.
5784 * Caller should make sure that pmd_trans_huge(pmd) is true.
5786 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5787 unsigned long addr, pmd_t pmd, union mc_target *target)
5789 struct page *page = NULL;
5790 enum mc_target_type ret = MC_TARGET_NONE;
5792 if (unlikely(is_swap_pmd(pmd))) {
5793 VM_BUG_ON(thp_migration_supported() &&
5794 !is_pmd_migration_entry(pmd));
5797 page = pmd_page(pmd);
5798 VM_BUG_ON_PAGE(!page || !PageHead(page), page);
5799 if (!(mc.flags & MOVE_ANON))
5801 if (page_memcg(page) == mc.from) {
5802 ret = MC_TARGET_PAGE;
5805 target->page = page;
5811 static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5812 unsigned long addr, pmd_t pmd, union mc_target *target)
5814 return MC_TARGET_NONE;
5818 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5819 unsigned long addr, unsigned long end,
5820 struct mm_walk *walk)
5822 struct vm_area_struct *vma = walk->vma;
5826 ptl = pmd_trans_huge_lock(pmd, vma);
5829 * Note their can not be MC_TARGET_DEVICE for now as we do not
5830 * support transparent huge page with MEMORY_DEVICE_PRIVATE but
5831 * this might change.
5833 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
5834 mc.precharge += HPAGE_PMD_NR;
5839 if (pmd_trans_unstable(pmd))
5841 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5842 for (; addr != end; pte++, addr += PAGE_SIZE)
5843 if (get_mctgt_type(vma, addr, *pte, NULL))
5844 mc.precharge++; /* increment precharge temporarily */
5845 pte_unmap_unlock(pte - 1, ptl);
5851 static const struct mm_walk_ops precharge_walk_ops = {
5852 .pmd_entry = mem_cgroup_count_precharge_pte_range,
5855 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5857 unsigned long precharge;
5860 walk_page_range(mm, 0, mm->highest_vm_end, &precharge_walk_ops, NULL);
5861 mmap_read_unlock(mm);
5863 precharge = mc.precharge;
5869 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5871 unsigned long precharge = mem_cgroup_count_precharge(mm);
5873 VM_BUG_ON(mc.moving_task);
5874 mc.moving_task = current;
5875 return mem_cgroup_do_precharge(precharge);
5878 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5879 static void __mem_cgroup_clear_mc(void)
5881 struct mem_cgroup *from = mc.from;
5882 struct mem_cgroup *to = mc.to;
5884 /* we must uncharge all the leftover precharges from mc.to */
5886 cancel_charge(mc.to, mc.precharge);
5890 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5891 * we must uncharge here.
5893 if (mc.moved_charge) {
5894 cancel_charge(mc.from, mc.moved_charge);
5895 mc.moved_charge = 0;
5897 /* we must fixup refcnts and charges */
5898 if (mc.moved_swap) {
5899 /* uncharge swap account from the old cgroup */
5900 if (!mem_cgroup_is_root(mc.from))
5901 page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
5903 mem_cgroup_id_put_many(mc.from, mc.moved_swap);
5906 * we charged both to->memory and to->memsw, so we
5907 * should uncharge to->memory.
5909 if (!mem_cgroup_is_root(mc.to))
5910 page_counter_uncharge(&mc.to->memory, mc.moved_swap);
5914 memcg_oom_recover(from);
5915 memcg_oom_recover(to);
5916 wake_up_all(&mc.waitq);
5919 static void mem_cgroup_clear_mc(void)
5921 struct mm_struct *mm = mc.mm;
5924 * we must clear moving_task before waking up waiters at the end of
5927 mc.moving_task = NULL;
5928 __mem_cgroup_clear_mc();
5929 spin_lock(&mc.lock);
5933 spin_unlock(&mc.lock);
5938 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
5940 struct cgroup_subsys_state *css;
5941 struct mem_cgroup *memcg = NULL; /* unneeded init to make gcc happy */
5942 struct mem_cgroup *from;
5943 struct task_struct *leader, *p;
5944 struct mm_struct *mm;
5945 unsigned long move_flags;
5948 /* charge immigration isn't supported on the default hierarchy */
5949 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
5953 * Multi-process migrations only happen on the default hierarchy
5954 * where charge immigration is not used. Perform charge
5955 * immigration if @tset contains a leader and whine if there are
5959 cgroup_taskset_for_each_leader(leader, css, tset) {
5962 memcg = mem_cgroup_from_css(css);
5968 * We are now committed to this value whatever it is. Changes in this
5969 * tunable will only affect upcoming migrations, not the current one.
5970 * So we need to save it, and keep it going.
5972 move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
5976 from = mem_cgroup_from_task(p);
5978 VM_BUG_ON(from == memcg);
5980 mm = get_task_mm(p);
5983 /* We move charges only when we move a owner of the mm */
5984 if (mm->owner == p) {
5987 VM_BUG_ON(mc.precharge);
5988 VM_BUG_ON(mc.moved_charge);
5989 VM_BUG_ON(mc.moved_swap);
5991 spin_lock(&mc.lock);
5995 mc.flags = move_flags;
5996 spin_unlock(&mc.lock);
5997 /* We set mc.moving_task later */
5999 ret = mem_cgroup_precharge_mc(mm);
6001 mem_cgroup_clear_mc();
6008 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6011 mem_cgroup_clear_mc();
6014 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
6015 unsigned long addr, unsigned long end,
6016 struct mm_walk *walk)
6019 struct vm_area_struct *vma = walk->vma;
6022 enum mc_target_type target_type;
6023 union mc_target target;
6026 ptl = pmd_trans_huge_lock(pmd, vma);
6028 if (mc.precharge < HPAGE_PMD_NR) {
6032 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
6033 if (target_type == MC_TARGET_PAGE) {
6035 if (!isolate_lru_page(page)) {
6036 if (!mem_cgroup_move_account(page, true,
6038 mc.precharge -= HPAGE_PMD_NR;
6039 mc.moved_charge += HPAGE_PMD_NR;
6041 putback_lru_page(page);
6044 } else if (target_type == MC_TARGET_DEVICE) {
6046 if (!mem_cgroup_move_account(page, true,
6048 mc.precharge -= HPAGE_PMD_NR;
6049 mc.moved_charge += HPAGE_PMD_NR;
6057 if (pmd_trans_unstable(pmd))
6060 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6061 for (; addr != end; addr += PAGE_SIZE) {
6062 pte_t ptent = *(pte++);
6063 bool device = false;
6069 switch (get_mctgt_type(vma, addr, ptent, &target)) {
6070 case MC_TARGET_DEVICE:
6073 case MC_TARGET_PAGE:
6076 * We can have a part of the split pmd here. Moving it
6077 * can be done but it would be too convoluted so simply
6078 * ignore such a partial THP and keep it in original
6079 * memcg. There should be somebody mapping the head.
6081 if (PageTransCompound(page))
6083 if (!device && isolate_lru_page(page))
6085 if (!mem_cgroup_move_account(page, false,
6088 /* we uncharge from mc.from later. */
6092 putback_lru_page(page);
6093 put: /* get_mctgt_type() gets the page */
6096 case MC_TARGET_SWAP:
6098 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
6100 mem_cgroup_id_get_many(mc.to, 1);
6101 /* we fixup other refcnts and charges later. */
6109 pte_unmap_unlock(pte - 1, ptl);
6114 * We have consumed all precharges we got in can_attach().
6115 * We try charge one by one, but don't do any additional
6116 * charges to mc.to if we have failed in charge once in attach()
6119 ret = mem_cgroup_do_precharge(1);
6127 static const struct mm_walk_ops charge_walk_ops = {
6128 .pmd_entry = mem_cgroup_move_charge_pte_range,
6131 static void mem_cgroup_move_charge(void)
6133 lru_add_drain_all();
6135 * Signal lock_page_memcg() to take the memcg's move_lock
6136 * while we're moving its pages to another memcg. Then wait
6137 * for already started RCU-only updates to finish.
6139 atomic_inc(&mc.from->moving_account);
6142 if (unlikely(!mmap_read_trylock(mc.mm))) {
6144 * Someone who are holding the mmap_lock might be waiting in
6145 * waitq. So we cancel all extra charges, wake up all waiters,
6146 * and retry. Because we cancel precharges, we might not be able
6147 * to move enough charges, but moving charge is a best-effort
6148 * feature anyway, so it wouldn't be a big problem.
6150 __mem_cgroup_clear_mc();
6155 * When we have consumed all precharges and failed in doing
6156 * additional charge, the page walk just aborts.
6158 walk_page_range(mc.mm, 0, mc.mm->highest_vm_end, &charge_walk_ops,
6161 mmap_read_unlock(mc.mm);
6162 atomic_dec(&mc.from->moving_account);
6165 static void mem_cgroup_move_task(void)
6168 mem_cgroup_move_charge();
6169 mem_cgroup_clear_mc();
6172 #else /* !CONFIG_MMU */
6173 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
6177 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6180 static void mem_cgroup_move_task(void)
6185 static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
6187 if (value == PAGE_COUNTER_MAX)
6188 seq_puts(m, "max\n");
6190 seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
6195 static u64 memory_current_read(struct cgroup_subsys_state *css,
6198 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6200 return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
6203 static u64 memory_peak_read(struct cgroup_subsys_state *css,
6206 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6208 return (u64)memcg->memory.watermark * PAGE_SIZE;
6211 static int memory_min_show(struct seq_file *m, void *v)
6213 return seq_puts_memcg_tunable(m,
6214 READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
6217 static ssize_t memory_min_write(struct kernfs_open_file *of,
6218 char *buf, size_t nbytes, loff_t off)
6220 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6224 buf = strstrip(buf);
6225 err = page_counter_memparse(buf, "max", &min);
6229 page_counter_set_min(&memcg->memory, min);
6234 static int memory_low_show(struct seq_file *m, void *v)
6236 return seq_puts_memcg_tunable(m,
6237 READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
6240 static ssize_t memory_low_write(struct kernfs_open_file *of,
6241 char *buf, size_t nbytes, loff_t off)
6243 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6247 buf = strstrip(buf);
6248 err = page_counter_memparse(buf, "max", &low);
6252 page_counter_set_low(&memcg->memory, low);
6257 static int memory_high_show(struct seq_file *m, void *v)
6259 return seq_puts_memcg_tunable(m,
6260 READ_ONCE(mem_cgroup_from_seq(m)->memory.high));
6263 static ssize_t memory_high_write(struct kernfs_open_file *of,
6264 char *buf, size_t nbytes, loff_t off)
6266 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6267 unsigned int nr_retries = MAX_RECLAIM_RETRIES;
6268 bool drained = false;
6272 buf = strstrip(buf);
6273 err = page_counter_memparse(buf, "max", &high);
6277 page_counter_set_high(&memcg->memory, high);
6280 unsigned long nr_pages = page_counter_read(&memcg->memory);
6281 unsigned long reclaimed;
6283 if (nr_pages <= high)
6286 if (signal_pending(current))
6290 drain_all_stock(memcg);
6295 reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
6298 if (!reclaimed && !nr_retries--)
6302 memcg_wb_domain_size_changed(memcg);
6306 static int memory_max_show(struct seq_file *m, void *v)
6308 return seq_puts_memcg_tunable(m,
6309 READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
6312 static ssize_t memory_max_write(struct kernfs_open_file *of,
6313 char *buf, size_t nbytes, loff_t off)
6315 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6316 unsigned int nr_reclaims = MAX_RECLAIM_RETRIES;
6317 bool drained = false;
6321 buf = strstrip(buf);
6322 err = page_counter_memparse(buf, "max", &max);
6326 xchg(&memcg->memory.max, max);
6329 unsigned long nr_pages = page_counter_read(&memcg->memory);
6331 if (nr_pages <= max)
6334 if (signal_pending(current))
6338 drain_all_stock(memcg);
6344 if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
6350 memcg_memory_event(memcg, MEMCG_OOM);
6351 if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
6355 memcg_wb_domain_size_changed(memcg);
6359 static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
6361 seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
6362 seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
6363 seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
6364 seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
6365 seq_printf(m, "oom_kill %lu\n",
6366 atomic_long_read(&events[MEMCG_OOM_KILL]));
6367 seq_printf(m, "oom_group_kill %lu\n",
6368 atomic_long_read(&events[MEMCG_OOM_GROUP_KILL]));
6371 static int memory_events_show(struct seq_file *m, void *v)
6373 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6375 __memory_events_show(m, memcg->memory_events);
6379 static int memory_events_local_show(struct seq_file *m, void *v)
6381 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6383 __memory_events_show(m, memcg->memory_events_local);
6387 static int memory_stat_show(struct seq_file *m, void *v)
6389 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6392 buf = memory_stat_format(memcg);
6401 static inline unsigned long lruvec_page_state_output(struct lruvec *lruvec,
6404 return lruvec_page_state(lruvec, item) * memcg_page_state_unit(item);
6407 static int memory_numa_stat_show(struct seq_file *m, void *v)
6410 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6412 mem_cgroup_flush_stats();
6414 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
6417 if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS)
6420 seq_printf(m, "%s", memory_stats[i].name);
6421 for_each_node_state(nid, N_MEMORY) {
6423 struct lruvec *lruvec;
6425 lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
6426 size = lruvec_page_state_output(lruvec,
6427 memory_stats[i].idx);
6428 seq_printf(m, " N%d=%llu", nid, size);
6437 static int memory_oom_group_show(struct seq_file *m, void *v)
6439 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6441 seq_printf(m, "%d\n", memcg->oom_group);
6446 static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
6447 char *buf, size_t nbytes, loff_t off)
6449 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6452 buf = strstrip(buf);
6456 ret = kstrtoint(buf, 0, &oom_group);
6460 if (oom_group != 0 && oom_group != 1)
6463 memcg->oom_group = oom_group;
6468 static ssize_t memory_reclaim(struct kernfs_open_file *of, char *buf,
6469 size_t nbytes, loff_t off)
6471 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6472 unsigned int nr_retries = MAX_RECLAIM_RETRIES;
6473 unsigned long nr_to_reclaim, nr_reclaimed = 0;
6476 buf = strstrip(buf);
6477 err = page_counter_memparse(buf, "", &nr_to_reclaim);
6481 while (nr_reclaimed < nr_to_reclaim) {
6482 unsigned long reclaimed;
6484 if (signal_pending(current))
6488 * This is the final attempt, drain percpu lru caches in the
6489 * hope of introducing more evictable pages for
6490 * try_to_free_mem_cgroup_pages().
6493 lru_add_drain_all();
6495 reclaimed = try_to_free_mem_cgroup_pages(memcg,
6496 nr_to_reclaim - nr_reclaimed,
6499 if (!reclaimed && !nr_retries--)
6502 nr_reclaimed += reclaimed;
6508 static struct cftype memory_files[] = {
6511 .flags = CFTYPE_NOT_ON_ROOT,
6512 .read_u64 = memory_current_read,
6516 .flags = CFTYPE_NOT_ON_ROOT,
6517 .read_u64 = memory_peak_read,
6521 .flags = CFTYPE_NOT_ON_ROOT,
6522 .seq_show = memory_min_show,
6523 .write = memory_min_write,
6527 .flags = CFTYPE_NOT_ON_ROOT,
6528 .seq_show = memory_low_show,
6529 .write = memory_low_write,
6533 .flags = CFTYPE_NOT_ON_ROOT,
6534 .seq_show = memory_high_show,
6535 .write = memory_high_write,
6539 .flags = CFTYPE_NOT_ON_ROOT,
6540 .seq_show = memory_max_show,
6541 .write = memory_max_write,
6545 .flags = CFTYPE_NOT_ON_ROOT,
6546 .file_offset = offsetof(struct mem_cgroup, events_file),
6547 .seq_show = memory_events_show,
6550 .name = "events.local",
6551 .flags = CFTYPE_NOT_ON_ROOT,
6552 .file_offset = offsetof(struct mem_cgroup, events_local_file),
6553 .seq_show = memory_events_local_show,
6557 .seq_show = memory_stat_show,
6561 .name = "numa_stat",
6562 .seq_show = memory_numa_stat_show,
6566 .name = "oom.group",
6567 .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
6568 .seq_show = memory_oom_group_show,
6569 .write = memory_oom_group_write,
6573 .flags = CFTYPE_NS_DELEGATABLE,
6574 .write = memory_reclaim,
6579 struct cgroup_subsys memory_cgrp_subsys = {
6580 .css_alloc = mem_cgroup_css_alloc,
6581 .css_online = mem_cgroup_css_online,
6582 .css_offline = mem_cgroup_css_offline,
6583 .css_released = mem_cgroup_css_released,
6584 .css_free = mem_cgroup_css_free,
6585 .css_reset = mem_cgroup_css_reset,
6586 .css_rstat_flush = mem_cgroup_css_rstat_flush,
6587 .can_attach = mem_cgroup_can_attach,
6588 .cancel_attach = mem_cgroup_cancel_attach,
6589 .post_attach = mem_cgroup_move_task,
6590 .dfl_cftypes = memory_files,
6591 .legacy_cftypes = mem_cgroup_legacy_files,
6596 * This function calculates an individual cgroup's effective
6597 * protection which is derived from its own memory.min/low, its
6598 * parent's and siblings' settings, as well as the actual memory
6599 * distribution in the tree.
6601 * The following rules apply to the effective protection values:
6603 * 1. At the first level of reclaim, effective protection is equal to
6604 * the declared protection in memory.min and memory.low.
6606 * 2. To enable safe delegation of the protection configuration, at
6607 * subsequent levels the effective protection is capped to the
6608 * parent's effective protection.
6610 * 3. To make complex and dynamic subtrees easier to configure, the
6611 * user is allowed to overcommit the declared protection at a given
6612 * level. If that is the case, the parent's effective protection is
6613 * distributed to the children in proportion to how much protection
6614 * they have declared and how much of it they are utilizing.
6616 * This makes distribution proportional, but also work-conserving:
6617 * if one cgroup claims much more protection than it uses memory,
6618 * the unused remainder is available to its siblings.
6620 * 4. Conversely, when the declared protection is undercommitted at a
6621 * given level, the distribution of the larger parental protection
6622 * budget is NOT proportional. A cgroup's protection from a sibling
6623 * is capped to its own memory.min/low setting.
6625 * 5. However, to allow protecting recursive subtrees from each other
6626 * without having to declare each individual cgroup's fixed share
6627 * of the ancestor's claim to protection, any unutilized -
6628 * "floating" - protection from up the tree is distributed in
6629 * proportion to each cgroup's *usage*. This makes the protection
6630 * neutral wrt sibling cgroups and lets them compete freely over
6631 * the shared parental protection budget, but it protects the
6632 * subtree as a whole from neighboring subtrees.
6634 * Note that 4. and 5. are not in conflict: 4. is about protecting
6635 * against immediate siblings whereas 5. is about protecting against
6636 * neighboring subtrees.
6638 static unsigned long effective_protection(unsigned long usage,
6639 unsigned long parent_usage,
6640 unsigned long setting,
6641 unsigned long parent_effective,
6642 unsigned long siblings_protected)
6644 unsigned long protected;
6647 protected = min(usage, setting);
6649 * If all cgroups at this level combined claim and use more
6650 * protection then what the parent affords them, distribute
6651 * shares in proportion to utilization.
6653 * We are using actual utilization rather than the statically
6654 * claimed protection in order to be work-conserving: claimed
6655 * but unused protection is available to siblings that would
6656 * otherwise get a smaller chunk than what they claimed.
6658 if (siblings_protected > parent_effective)
6659 return protected * parent_effective / siblings_protected;
6662 * Ok, utilized protection of all children is within what the
6663 * parent affords them, so we know whatever this child claims
6664 * and utilizes is effectively protected.
6666 * If there is unprotected usage beyond this value, reclaim
6667 * will apply pressure in proportion to that amount.
6669 * If there is unutilized protection, the cgroup will be fully
6670 * shielded from reclaim, but we do return a smaller value for
6671 * protection than what the group could enjoy in theory. This
6672 * is okay. With the overcommit distribution above, effective
6673 * protection is always dependent on how memory is actually
6674 * consumed among the siblings anyway.
6679 * If the children aren't claiming (all of) the protection
6680 * afforded to them by the parent, distribute the remainder in
6681 * proportion to the (unprotected) memory of each cgroup. That
6682 * way, cgroups that aren't explicitly prioritized wrt each
6683 * other compete freely over the allowance, but they are
6684 * collectively protected from neighboring trees.
6686 * We're using unprotected memory for the weight so that if
6687 * some cgroups DO claim explicit protection, we don't protect
6688 * the same bytes twice.
6690 * Check both usage and parent_usage against the respective
6691 * protected values. One should imply the other, but they
6692 * aren't read atomically - make sure the division is sane.
6694 if (!(cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT))
6696 if (parent_effective > siblings_protected &&
6697 parent_usage > siblings_protected &&
6698 usage > protected) {
6699 unsigned long unclaimed;
6701 unclaimed = parent_effective - siblings_protected;
6702 unclaimed *= usage - protected;
6703 unclaimed /= parent_usage - siblings_protected;
6712 * mem_cgroup_calculate_protection - check if memory consumption is in the normal range
6713 * @root: the top ancestor of the sub-tree being checked
6714 * @memcg: the memory cgroup to check
6716 * WARNING: This function is not stateless! It can only be used as part
6717 * of a top-down tree iteration, not for isolated queries.
6719 void mem_cgroup_calculate_protection(struct mem_cgroup *root,
6720 struct mem_cgroup *memcg)
6722 unsigned long usage, parent_usage;
6723 struct mem_cgroup *parent;
6725 if (mem_cgroup_disabled())
6729 root = root_mem_cgroup;
6732 * Effective values of the reclaim targets are ignored so they
6733 * can be stale. Have a look at mem_cgroup_protection for more
6735 * TODO: calculation should be more robust so that we do not need
6736 * that special casing.
6741 usage = page_counter_read(&memcg->memory);
6745 parent = parent_mem_cgroup(memcg);
6747 if (parent == root) {
6748 memcg->memory.emin = READ_ONCE(memcg->memory.min);
6749 memcg->memory.elow = READ_ONCE(memcg->memory.low);
6753 parent_usage = page_counter_read(&parent->memory);
6755 WRITE_ONCE(memcg->memory.emin, effective_protection(usage, parent_usage,
6756 READ_ONCE(memcg->memory.min),
6757 READ_ONCE(parent->memory.emin),
6758 atomic_long_read(&parent->memory.children_min_usage)));
6760 WRITE_ONCE(memcg->memory.elow, effective_protection(usage, parent_usage,
6761 READ_ONCE(memcg->memory.low),
6762 READ_ONCE(parent->memory.elow),
6763 atomic_long_read(&parent->memory.children_low_usage)));
6766 static int charge_memcg(struct folio *folio, struct mem_cgroup *memcg,
6769 long nr_pages = folio_nr_pages(folio);
6772 ret = try_charge(memcg, gfp, nr_pages);
6776 css_get(&memcg->css);
6777 commit_charge(folio, memcg);
6779 local_irq_disable();
6780 mem_cgroup_charge_statistics(memcg, nr_pages);
6781 memcg_check_events(memcg, folio_nid(folio));
6787 int __mem_cgroup_charge(struct folio *folio, struct mm_struct *mm, gfp_t gfp)
6789 struct mem_cgroup *memcg;
6792 memcg = get_mem_cgroup_from_mm(mm);
6793 ret = charge_memcg(folio, memcg, gfp);
6794 css_put(&memcg->css);
6800 * mem_cgroup_swapin_charge_page - charge a newly allocated page for swapin
6801 * @page: page to charge
6802 * @mm: mm context of the victim
6803 * @gfp: reclaim mode
6804 * @entry: swap entry for which the page is allocated
6806 * This function charges a page allocated for swapin. Please call this before
6807 * adding the page to the swapcache.
6809 * Returns 0 on success. Otherwise, an error code is returned.
6811 int mem_cgroup_swapin_charge_page(struct page *page, struct mm_struct *mm,
6812 gfp_t gfp, swp_entry_t entry)
6814 struct folio *folio = page_folio(page);
6815 struct mem_cgroup *memcg;
6819 if (mem_cgroup_disabled())
6822 id = lookup_swap_cgroup_id(entry);
6824 memcg = mem_cgroup_from_id(id);
6825 if (!memcg || !css_tryget_online(&memcg->css))
6826 memcg = get_mem_cgroup_from_mm(mm);
6829 ret = charge_memcg(folio, memcg, gfp);
6831 css_put(&memcg->css);
6836 * mem_cgroup_swapin_uncharge_swap - uncharge swap slot
6837 * @entry: swap entry for which the page is charged
6839 * Call this function after successfully adding the charged page to swapcache.
6841 * Note: This function assumes the page for which swap slot is being uncharged
6844 void mem_cgroup_swapin_uncharge_swap(swp_entry_t entry)
6847 * Cgroup1's unified memory+swap counter has been charged with the
6848 * new swapcache page, finish the transfer by uncharging the swap
6849 * slot. The swap slot would also get uncharged when it dies, but
6850 * it can stick around indefinitely and we'd count the page twice
6853 * Cgroup2 has separate resource counters for memory and swap,
6854 * so this is a non-issue here. Memory and swap charge lifetimes
6855 * correspond 1:1 to page and swap slot lifetimes: we charge the
6856 * page to memory here, and uncharge swap when the slot is freed.
6858 if (!mem_cgroup_disabled() && do_memsw_account()) {
6860 * The swap entry might not get freed for a long time,
6861 * let's not wait for it. The page already received a
6862 * memory+swap charge, drop the swap entry duplicate.
6864 mem_cgroup_uncharge_swap(entry, 1);
6868 struct uncharge_gather {
6869 struct mem_cgroup *memcg;
6870 unsigned long nr_memory;
6871 unsigned long pgpgout;
6872 unsigned long nr_kmem;
6876 static inline void uncharge_gather_clear(struct uncharge_gather *ug)
6878 memset(ug, 0, sizeof(*ug));
6881 static void uncharge_batch(const struct uncharge_gather *ug)
6883 unsigned long flags;
6885 if (ug->nr_memory) {
6886 page_counter_uncharge(&ug->memcg->memory, ug->nr_memory);
6887 if (do_memsw_account())
6888 page_counter_uncharge(&ug->memcg->memsw, ug->nr_memory);
6890 memcg_account_kmem(ug->memcg, -ug->nr_kmem);
6891 memcg_oom_recover(ug->memcg);
6894 local_irq_save(flags);
6895 __count_memcg_events(ug->memcg, PGPGOUT, ug->pgpgout);
6896 __this_cpu_add(ug->memcg->vmstats_percpu->nr_page_events, ug->nr_memory);
6897 memcg_check_events(ug->memcg, ug->nid);
6898 local_irq_restore(flags);
6900 /* drop reference from uncharge_folio */
6901 css_put(&ug->memcg->css);
6904 static void uncharge_folio(struct folio *folio, struct uncharge_gather *ug)
6907 struct mem_cgroup *memcg;
6908 struct obj_cgroup *objcg;
6910 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
6913 * Nobody should be changing or seriously looking at
6914 * folio memcg or objcg at this point, we have fully
6915 * exclusive access to the folio.
6917 if (folio_memcg_kmem(folio)) {
6918 objcg = __folio_objcg(folio);
6920 * This get matches the put at the end of the function and
6921 * kmem pages do not hold memcg references anymore.
6923 memcg = get_mem_cgroup_from_objcg(objcg);
6925 memcg = __folio_memcg(folio);
6931 if (ug->memcg != memcg) {
6934 uncharge_gather_clear(ug);
6937 ug->nid = folio_nid(folio);
6939 /* pairs with css_put in uncharge_batch */
6940 css_get(&memcg->css);
6943 nr_pages = folio_nr_pages(folio);
6945 if (folio_memcg_kmem(folio)) {
6946 ug->nr_memory += nr_pages;
6947 ug->nr_kmem += nr_pages;
6949 folio->memcg_data = 0;
6950 obj_cgroup_put(objcg);
6952 /* LRU pages aren't accounted at the root level */
6953 if (!mem_cgroup_is_root(memcg))
6954 ug->nr_memory += nr_pages;
6957 folio->memcg_data = 0;
6960 css_put(&memcg->css);
6963 void __mem_cgroup_uncharge(struct folio *folio)
6965 struct uncharge_gather ug;
6967 /* Don't touch folio->lru of any random page, pre-check: */
6968 if (!folio_memcg(folio))
6971 uncharge_gather_clear(&ug);
6972 uncharge_folio(folio, &ug);
6973 uncharge_batch(&ug);
6977 * __mem_cgroup_uncharge_list - uncharge a list of page
6978 * @page_list: list of pages to uncharge
6980 * Uncharge a list of pages previously charged with
6981 * __mem_cgroup_charge().
6983 void __mem_cgroup_uncharge_list(struct list_head *page_list)
6985 struct uncharge_gather ug;
6986 struct folio *folio;
6988 uncharge_gather_clear(&ug);
6989 list_for_each_entry(folio, page_list, lru)
6990 uncharge_folio(folio, &ug);
6992 uncharge_batch(&ug);
6996 * mem_cgroup_migrate - Charge a folio's replacement.
6997 * @old: Currently circulating folio.
6998 * @new: Replacement folio.
7000 * Charge @new as a replacement folio for @old. @old will
7001 * be uncharged upon free.
7003 * Both folios must be locked, @new->mapping must be set up.
7005 void mem_cgroup_migrate(struct folio *old, struct folio *new)
7007 struct mem_cgroup *memcg;
7008 long nr_pages = folio_nr_pages(new);
7009 unsigned long flags;
7011 VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
7012 VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
7013 VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
7014 VM_BUG_ON_FOLIO(folio_nr_pages(old) != nr_pages, new);
7016 if (mem_cgroup_disabled())
7019 /* Page cache replacement: new folio already charged? */
7020 if (folio_memcg(new))
7023 memcg = folio_memcg(old);
7024 VM_WARN_ON_ONCE_FOLIO(!memcg, old);
7028 /* Force-charge the new page. The old one will be freed soon */
7029 if (!mem_cgroup_is_root(memcg)) {
7030 page_counter_charge(&memcg->memory, nr_pages);
7031 if (do_memsw_account())
7032 page_counter_charge(&memcg->memsw, nr_pages);
7035 css_get(&memcg->css);
7036 commit_charge(new, memcg);
7038 local_irq_save(flags);
7039 mem_cgroup_charge_statistics(memcg, nr_pages);
7040 memcg_check_events(memcg, folio_nid(new));
7041 local_irq_restore(flags);
7044 DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
7045 EXPORT_SYMBOL(memcg_sockets_enabled_key);
7047 void mem_cgroup_sk_alloc(struct sock *sk)
7049 struct mem_cgroup *memcg;
7051 if (!mem_cgroup_sockets_enabled)
7054 /* Do not associate the sock with unrelated interrupted task's memcg. */
7059 memcg = mem_cgroup_from_task(current);
7060 if (memcg == root_mem_cgroup)
7062 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg->tcpmem_active)
7064 if (css_tryget(&memcg->css))
7065 sk->sk_memcg = memcg;
7070 void mem_cgroup_sk_free(struct sock *sk)
7073 css_put(&sk->sk_memcg->css);
7077 * mem_cgroup_charge_skmem - charge socket memory
7078 * @memcg: memcg to charge
7079 * @nr_pages: number of pages to charge
7080 * @gfp_mask: reclaim mode
7082 * Charges @nr_pages to @memcg. Returns %true if the charge fit within
7083 * @memcg's configured limit, %false if it doesn't.
7085 bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages,
7088 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
7089 struct page_counter *fail;
7091 if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) {
7092 memcg->tcpmem_pressure = 0;
7095 memcg->tcpmem_pressure = 1;
7096 if (gfp_mask & __GFP_NOFAIL) {
7097 page_counter_charge(&memcg->tcpmem, nr_pages);
7103 if (try_charge(memcg, gfp_mask, nr_pages) == 0) {
7104 mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
7112 * mem_cgroup_uncharge_skmem - uncharge socket memory
7113 * @memcg: memcg to uncharge
7114 * @nr_pages: number of pages to uncharge
7116 void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
7118 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
7119 page_counter_uncharge(&memcg->tcpmem, nr_pages);
7123 mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
7125 refill_stock(memcg, nr_pages);
7128 static int __init cgroup_memory(char *s)
7132 while ((token = strsep(&s, ",")) != NULL) {
7135 if (!strcmp(token, "nosocket"))
7136 cgroup_memory_nosocket = true;
7137 if (!strcmp(token, "nokmem"))
7138 cgroup_memory_nokmem = true;
7142 __setup("cgroup.memory=", cgroup_memory);
7145 * subsys_initcall() for memory controller.
7147 * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
7148 * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
7149 * basically everything that doesn't depend on a specific mem_cgroup structure
7150 * should be initialized from here.
7152 static int __init mem_cgroup_init(void)
7157 * Currently s32 type (can refer to struct batched_lruvec_stat) is
7158 * used for per-memcg-per-cpu caching of per-node statistics. In order
7159 * to work fine, we should make sure that the overfill threshold can't
7160 * exceed S32_MAX / PAGE_SIZE.
7162 BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE);
7164 cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
7165 memcg_hotplug_cpu_dead);
7167 for_each_possible_cpu(cpu)
7168 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
7171 for_each_node(node) {
7172 struct mem_cgroup_tree_per_node *rtpn;
7174 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL,
7175 node_online(node) ? node : NUMA_NO_NODE);
7177 rtpn->rb_root = RB_ROOT;
7178 rtpn->rb_rightmost = NULL;
7179 spin_lock_init(&rtpn->lock);
7180 soft_limit_tree.rb_tree_per_node[node] = rtpn;
7185 subsys_initcall(mem_cgroup_init);
7187 #ifdef CONFIG_MEMCG_SWAP
7188 static struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
7190 while (!refcount_inc_not_zero(&memcg->id.ref)) {
7192 * The root cgroup cannot be destroyed, so it's refcount must
7195 if (WARN_ON_ONCE(memcg == root_mem_cgroup)) {
7199 memcg = parent_mem_cgroup(memcg);
7201 memcg = root_mem_cgroup;
7207 * mem_cgroup_swapout - transfer a memsw charge to swap
7208 * @folio: folio whose memsw charge to transfer
7209 * @entry: swap entry to move the charge to
7211 * Transfer the memsw charge of @folio to @entry.
7213 void mem_cgroup_swapout(struct folio *folio, swp_entry_t entry)
7215 struct mem_cgroup *memcg, *swap_memcg;
7216 unsigned int nr_entries;
7217 unsigned short oldid;
7219 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
7220 VM_BUG_ON_FOLIO(folio_ref_count(folio), folio);
7222 if (mem_cgroup_disabled())
7225 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
7228 memcg = folio_memcg(folio);
7230 VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
7235 * In case the memcg owning these pages has been offlined and doesn't
7236 * have an ID allocated to it anymore, charge the closest online
7237 * ancestor for the swap instead and transfer the memory+swap charge.
7239 swap_memcg = mem_cgroup_id_get_online(memcg);
7240 nr_entries = folio_nr_pages(folio);
7241 /* Get references for the tail pages, too */
7243 mem_cgroup_id_get_many(swap_memcg, nr_entries - 1);
7244 oldid = swap_cgroup_record(entry, mem_cgroup_id(swap_memcg),
7246 VM_BUG_ON_FOLIO(oldid, folio);
7247 mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries);
7249 folio->memcg_data = 0;
7251 if (!mem_cgroup_is_root(memcg))
7252 page_counter_uncharge(&memcg->memory, nr_entries);
7254 if (!cgroup_memory_noswap && memcg != swap_memcg) {
7255 if (!mem_cgroup_is_root(swap_memcg))
7256 page_counter_charge(&swap_memcg->memsw, nr_entries);
7257 page_counter_uncharge(&memcg->memsw, nr_entries);
7261 * Interrupts should be disabled here because the caller holds the
7262 * i_pages lock which is taken with interrupts-off. It is
7263 * important here to have the interrupts disabled because it is the
7264 * only synchronisation we have for updating the per-CPU variables.
7267 mem_cgroup_charge_statistics(memcg, -nr_entries);
7268 memcg_stats_unlock();
7269 memcg_check_events(memcg, folio_nid(folio));
7271 css_put(&memcg->css);
7275 * __mem_cgroup_try_charge_swap - try charging swap space for a folio
7276 * @folio: folio being added to swap
7277 * @entry: swap entry to charge
7279 * Try to charge @folio's memcg for the swap space at @entry.
7281 * Returns 0 on success, -ENOMEM on failure.
7283 int __mem_cgroup_try_charge_swap(struct folio *folio, swp_entry_t entry)
7285 unsigned int nr_pages = folio_nr_pages(folio);
7286 struct page_counter *counter;
7287 struct mem_cgroup *memcg;
7288 unsigned short oldid;
7290 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
7293 memcg = folio_memcg(folio);
7295 VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
7300 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7304 memcg = mem_cgroup_id_get_online(memcg);
7306 if (!cgroup_memory_noswap && !mem_cgroup_is_root(memcg) &&
7307 !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
7308 memcg_memory_event(memcg, MEMCG_SWAP_MAX);
7309 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7310 mem_cgroup_id_put(memcg);
7314 /* Get references for the tail pages, too */
7316 mem_cgroup_id_get_many(memcg, nr_pages - 1);
7317 oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg), nr_pages);
7318 VM_BUG_ON_FOLIO(oldid, folio);
7319 mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
7325 * __mem_cgroup_uncharge_swap - uncharge swap space
7326 * @entry: swap entry to uncharge
7327 * @nr_pages: the amount of swap space to uncharge
7329 void __mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
7331 struct mem_cgroup *memcg;
7334 id = swap_cgroup_record(entry, 0, nr_pages);
7336 memcg = mem_cgroup_from_id(id);
7338 if (!cgroup_memory_noswap && !mem_cgroup_is_root(memcg)) {
7339 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
7340 page_counter_uncharge(&memcg->swap, nr_pages);
7342 page_counter_uncharge(&memcg->memsw, nr_pages);
7344 mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
7345 mem_cgroup_id_put_many(memcg, nr_pages);
7350 long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
7352 long nr_swap_pages = get_nr_swap_pages();
7354 if (cgroup_memory_noswap || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
7355 return nr_swap_pages;
7356 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg))
7357 nr_swap_pages = min_t(long, nr_swap_pages,
7358 READ_ONCE(memcg->swap.max) -
7359 page_counter_read(&memcg->swap));
7360 return nr_swap_pages;
7363 bool mem_cgroup_swap_full(struct page *page)
7365 struct mem_cgroup *memcg;
7367 VM_BUG_ON_PAGE(!PageLocked(page), page);
7371 if (cgroup_memory_noswap || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
7374 memcg = page_memcg(page);
7378 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg)) {
7379 unsigned long usage = page_counter_read(&memcg->swap);
7381 if (usage * 2 >= READ_ONCE(memcg->swap.high) ||
7382 usage * 2 >= READ_ONCE(memcg->swap.max))
7389 static int __init setup_swap_account(char *s)
7391 if (!strcmp(s, "1"))
7392 cgroup_memory_noswap = false;
7393 else if (!strcmp(s, "0"))
7394 cgroup_memory_noswap = true;
7397 __setup("swapaccount=", setup_swap_account);
7399 static u64 swap_current_read(struct cgroup_subsys_state *css,
7402 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7404 return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
7407 static int swap_high_show(struct seq_file *m, void *v)
7409 return seq_puts_memcg_tunable(m,
7410 READ_ONCE(mem_cgroup_from_seq(m)->swap.high));
7413 static ssize_t swap_high_write(struct kernfs_open_file *of,
7414 char *buf, size_t nbytes, loff_t off)
7416 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7420 buf = strstrip(buf);
7421 err = page_counter_memparse(buf, "max", &high);
7425 page_counter_set_high(&memcg->swap, high);
7430 static int swap_max_show(struct seq_file *m, void *v)
7432 return seq_puts_memcg_tunable(m,
7433 READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
7436 static ssize_t swap_max_write(struct kernfs_open_file *of,
7437 char *buf, size_t nbytes, loff_t off)
7439 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7443 buf = strstrip(buf);
7444 err = page_counter_memparse(buf, "max", &max);
7448 xchg(&memcg->swap.max, max);
7453 static int swap_events_show(struct seq_file *m, void *v)
7455 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
7457 seq_printf(m, "high %lu\n",
7458 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH]));
7459 seq_printf(m, "max %lu\n",
7460 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
7461 seq_printf(m, "fail %lu\n",
7462 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
7467 static struct cftype swap_files[] = {
7469 .name = "swap.current",
7470 .flags = CFTYPE_NOT_ON_ROOT,
7471 .read_u64 = swap_current_read,
7474 .name = "swap.high",
7475 .flags = CFTYPE_NOT_ON_ROOT,
7476 .seq_show = swap_high_show,
7477 .write = swap_high_write,
7481 .flags = CFTYPE_NOT_ON_ROOT,
7482 .seq_show = swap_max_show,
7483 .write = swap_max_write,
7486 .name = "swap.events",
7487 .flags = CFTYPE_NOT_ON_ROOT,
7488 .file_offset = offsetof(struct mem_cgroup, swap_events_file),
7489 .seq_show = swap_events_show,
7494 static struct cftype memsw_files[] = {
7496 .name = "memsw.usage_in_bytes",
7497 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
7498 .read_u64 = mem_cgroup_read_u64,
7501 .name = "memsw.max_usage_in_bytes",
7502 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
7503 .write = mem_cgroup_reset,
7504 .read_u64 = mem_cgroup_read_u64,
7507 .name = "memsw.limit_in_bytes",
7508 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
7509 .write = mem_cgroup_write,
7510 .read_u64 = mem_cgroup_read_u64,
7513 .name = "memsw.failcnt",
7514 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
7515 .write = mem_cgroup_reset,
7516 .read_u64 = mem_cgroup_read_u64,
7518 { }, /* terminate */
7521 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
7523 * obj_cgroup_may_zswap - check if this cgroup can zswap
7524 * @objcg: the object cgroup
7526 * Check if the hierarchical zswap limit has been reached.
7528 * This doesn't check for specific headroom, and it is not atomic
7529 * either. But with zswap, the size of the allocation is only known
7530 * once compression has occured, and this optimistic pre-check avoids
7531 * spending cycles on compression when there is already no room left
7532 * or zswap is disabled altogether somewhere in the hierarchy.
7534 bool obj_cgroup_may_zswap(struct obj_cgroup *objcg)
7536 struct mem_cgroup *memcg, *original_memcg;
7539 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
7542 original_memcg = get_mem_cgroup_from_objcg(objcg);
7543 for (memcg = original_memcg; memcg != root_mem_cgroup;
7544 memcg = parent_mem_cgroup(memcg)) {
7545 unsigned long max = READ_ONCE(memcg->zswap_max);
7546 unsigned long pages;
7548 if (max == PAGE_COUNTER_MAX)
7555 cgroup_rstat_flush(memcg->css.cgroup);
7556 pages = memcg_page_state(memcg, MEMCG_ZSWAP_B) / PAGE_SIZE;
7562 mem_cgroup_put(original_memcg);
7567 * obj_cgroup_charge_zswap - charge compression backend memory
7568 * @objcg: the object cgroup
7569 * @size: size of compressed object
7571 * This forces the charge after obj_cgroup_may_swap() allowed
7572 * compression and storage in zwap for this cgroup to go ahead.
7574 void obj_cgroup_charge_zswap(struct obj_cgroup *objcg, size_t size)
7576 struct mem_cgroup *memcg;
7578 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
7581 VM_WARN_ON_ONCE(!(current->flags & PF_MEMALLOC));
7583 /* PF_MEMALLOC context, charging must succeed */
7584 if (obj_cgroup_charge(objcg, GFP_KERNEL, size))
7588 memcg = obj_cgroup_memcg(objcg);
7589 mod_memcg_state(memcg, MEMCG_ZSWAP_B, size);
7590 mod_memcg_state(memcg, MEMCG_ZSWAPPED, 1);
7595 * obj_cgroup_uncharge_zswap - uncharge compression backend memory
7596 * @objcg: the object cgroup
7597 * @size: size of compressed object
7599 * Uncharges zswap memory on page in.
7601 void obj_cgroup_uncharge_zswap(struct obj_cgroup *objcg, size_t size)
7603 struct mem_cgroup *memcg;
7605 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
7608 obj_cgroup_uncharge(objcg, size);
7611 memcg = obj_cgroup_memcg(objcg);
7612 mod_memcg_state(memcg, MEMCG_ZSWAP_B, -size);
7613 mod_memcg_state(memcg, MEMCG_ZSWAPPED, -1);
7617 static u64 zswap_current_read(struct cgroup_subsys_state *css,
7620 cgroup_rstat_flush(css->cgroup);
7621 return memcg_page_state(mem_cgroup_from_css(css), MEMCG_ZSWAP_B);
7624 static int zswap_max_show(struct seq_file *m, void *v)
7626 return seq_puts_memcg_tunable(m,
7627 READ_ONCE(mem_cgroup_from_seq(m)->zswap_max));
7630 static ssize_t zswap_max_write(struct kernfs_open_file *of,
7631 char *buf, size_t nbytes, loff_t off)
7633 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7637 buf = strstrip(buf);
7638 err = page_counter_memparse(buf, "max", &max);
7642 xchg(&memcg->zswap_max, max);
7647 static struct cftype zswap_files[] = {
7649 .name = "zswap.current",
7650 .flags = CFTYPE_NOT_ON_ROOT,
7651 .read_u64 = zswap_current_read,
7654 .name = "zswap.max",
7655 .flags = CFTYPE_NOT_ON_ROOT,
7656 .seq_show = zswap_max_show,
7657 .write = zswap_max_write,
7661 #endif /* CONFIG_MEMCG_KMEM && CONFIG_ZSWAP */
7664 * If mem_cgroup_swap_init() is implemented as a subsys_initcall()
7665 * instead of a core_initcall(), this could mean cgroup_memory_noswap still
7666 * remains set to false even when memcg is disabled via "cgroup_disable=memory"
7667 * boot parameter. This may result in premature OOPS inside
7668 * mem_cgroup_get_nr_swap_pages() function in corner cases.
7670 static int __init mem_cgroup_swap_init(void)
7672 /* No memory control -> no swap control */
7673 if (mem_cgroup_disabled())
7674 cgroup_memory_noswap = true;
7676 if (cgroup_memory_noswap)
7679 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files));
7680 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files));
7681 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
7682 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, zswap_files));
7686 core_initcall(mem_cgroup_swap_init);
7688 #endif /* CONFIG_MEMCG_SWAP */