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/mm_inline.h>
57 #include <linux/swap_cgroup.h>
58 #include <linux/cpu.h>
59 #include <linux/oom.h>
60 #include <linux/lockdep.h>
61 #include <linux/file.h>
62 #include <linux/tracehook.h>
63 #include <linux/psi.h>
64 #include <linux/seq_buf.h>
70 #include <linux/uaccess.h>
72 #include <trace/events/vmscan.h>
74 struct cgroup_subsys memory_cgrp_subsys __read_mostly;
75 EXPORT_SYMBOL(memory_cgrp_subsys);
77 struct mem_cgroup *root_mem_cgroup __read_mostly;
79 /* Active memory cgroup to use from an interrupt context */
80 DEFINE_PER_CPU(struct mem_cgroup *, int_active_memcg);
81 EXPORT_PER_CPU_SYMBOL_GPL(int_active_memcg);
83 /* Socket memory accounting disabled? */
84 static bool cgroup_memory_nosocket __ro_after_init;
86 /* Kernel memory accounting disabled? */
87 static bool cgroup_memory_nokmem __ro_after_init;
89 /* Whether the swap controller is active */
90 #ifdef CONFIG_MEMCG_SWAP
91 bool cgroup_memory_noswap __ro_after_init;
93 #define cgroup_memory_noswap 1
96 #ifdef CONFIG_CGROUP_WRITEBACK
97 static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq);
100 /* Whether legacy memory+swap accounting is active */
101 static bool do_memsw_account(void)
103 return !cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_noswap;
106 #define THRESHOLDS_EVENTS_TARGET 128
107 #define SOFTLIMIT_EVENTS_TARGET 1024
110 * Cgroups above their limits are maintained in a RB-Tree, independent of
111 * their hierarchy representation
114 struct mem_cgroup_tree_per_node {
115 struct rb_root rb_root;
116 struct rb_node *rb_rightmost;
120 struct mem_cgroup_tree {
121 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
124 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
127 struct mem_cgroup_eventfd_list {
128 struct list_head list;
129 struct eventfd_ctx *eventfd;
133 * cgroup_event represents events which userspace want to receive.
135 struct mem_cgroup_event {
137 * memcg which the event belongs to.
139 struct mem_cgroup *memcg;
141 * eventfd to signal userspace about the event.
143 struct eventfd_ctx *eventfd;
145 * Each of these stored in a list by the cgroup.
147 struct list_head list;
149 * register_event() callback will be used to add new userspace
150 * waiter for changes related to this event. Use eventfd_signal()
151 * on eventfd to send notification to userspace.
153 int (*register_event)(struct mem_cgroup *memcg,
154 struct eventfd_ctx *eventfd, const char *args);
156 * unregister_event() callback will be called when userspace closes
157 * the eventfd or on cgroup removing. This callback must be set,
158 * if you want provide notification functionality.
160 void (*unregister_event)(struct mem_cgroup *memcg,
161 struct eventfd_ctx *eventfd);
163 * All fields below needed to unregister event when
164 * userspace closes eventfd.
167 wait_queue_head_t *wqh;
168 wait_queue_entry_t wait;
169 struct work_struct remove;
172 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
173 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
175 /* Stuffs for move charges at task migration. */
177 * Types of charges to be moved.
179 #define MOVE_ANON 0x1U
180 #define MOVE_FILE 0x2U
181 #define MOVE_MASK (MOVE_ANON | MOVE_FILE)
183 /* "mc" and its members are protected by cgroup_mutex */
184 static struct move_charge_struct {
185 spinlock_t lock; /* for from, to */
186 struct mm_struct *mm;
187 struct mem_cgroup *from;
188 struct mem_cgroup *to;
190 unsigned long precharge;
191 unsigned long moved_charge;
192 unsigned long moved_swap;
193 struct task_struct *moving_task; /* a task moving charges */
194 wait_queue_head_t waitq; /* a waitq for other context */
196 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
197 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
201 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
202 * limit reclaim to prevent infinite loops, if they ever occur.
204 #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
205 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
207 /* for encoding cft->private value on file */
216 #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
217 #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
218 #define MEMFILE_ATTR(val) ((val) & 0xffff)
219 /* Used for OOM notifier */
220 #define OOM_CONTROL (0)
223 * Iteration constructs for visiting all cgroups (under a tree). If
224 * loops are exited prematurely (break), mem_cgroup_iter_break() must
225 * be used for reference counting.
227 #define for_each_mem_cgroup_tree(iter, root) \
228 for (iter = mem_cgroup_iter(root, NULL, NULL); \
230 iter = mem_cgroup_iter(root, iter, NULL))
232 #define for_each_mem_cgroup(iter) \
233 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
235 iter = mem_cgroup_iter(NULL, iter, NULL))
237 static inline bool task_is_dying(void)
239 return tsk_is_oom_victim(current) || fatal_signal_pending(current) ||
240 (current->flags & PF_EXITING);
243 /* Some nice accessors for the vmpressure. */
244 struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
247 memcg = root_mem_cgroup;
248 return &memcg->vmpressure;
251 struct mem_cgroup *vmpressure_to_memcg(struct vmpressure *vmpr)
253 return container_of(vmpr, struct mem_cgroup, vmpressure);
256 #ifdef CONFIG_MEMCG_KMEM
257 static DEFINE_SPINLOCK(objcg_lock);
259 bool mem_cgroup_kmem_disabled(void)
261 return cgroup_memory_nokmem;
264 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
265 unsigned int nr_pages);
267 static void obj_cgroup_release(struct percpu_ref *ref)
269 struct obj_cgroup *objcg = container_of(ref, struct obj_cgroup, refcnt);
270 unsigned int nr_bytes;
271 unsigned int nr_pages;
275 * At this point all allocated objects are freed, and
276 * objcg->nr_charged_bytes can't have an arbitrary byte value.
277 * However, it can be PAGE_SIZE or (x * PAGE_SIZE).
279 * The following sequence can lead to it:
280 * 1) CPU0: objcg == stock->cached_objcg
281 * 2) CPU1: we do a small allocation (e.g. 92 bytes),
282 * PAGE_SIZE bytes are charged
283 * 3) CPU1: a process from another memcg is allocating something,
284 * the stock if flushed,
285 * objcg->nr_charged_bytes = PAGE_SIZE - 92
286 * 5) CPU0: we do release this object,
287 * 92 bytes are added to stock->nr_bytes
288 * 6) CPU0: stock is flushed,
289 * 92 bytes are added to objcg->nr_charged_bytes
291 * In the result, nr_charged_bytes == PAGE_SIZE.
292 * This page will be uncharged in obj_cgroup_release().
294 nr_bytes = atomic_read(&objcg->nr_charged_bytes);
295 WARN_ON_ONCE(nr_bytes & (PAGE_SIZE - 1));
296 nr_pages = nr_bytes >> PAGE_SHIFT;
299 obj_cgroup_uncharge_pages(objcg, nr_pages);
301 spin_lock_irqsave(&objcg_lock, flags);
302 list_del(&objcg->list);
303 spin_unlock_irqrestore(&objcg_lock, flags);
305 percpu_ref_exit(ref);
306 kfree_rcu(objcg, rcu);
309 static struct obj_cgroup *obj_cgroup_alloc(void)
311 struct obj_cgroup *objcg;
314 objcg = kzalloc(sizeof(struct obj_cgroup), GFP_KERNEL);
318 ret = percpu_ref_init(&objcg->refcnt, obj_cgroup_release, 0,
324 INIT_LIST_HEAD(&objcg->list);
328 static void memcg_reparent_objcgs(struct mem_cgroup *memcg,
329 struct mem_cgroup *parent)
331 struct obj_cgroup *objcg, *iter;
333 objcg = rcu_replace_pointer(memcg->objcg, NULL, true);
335 spin_lock_irq(&objcg_lock);
337 /* 1) Ready to reparent active objcg. */
338 list_add(&objcg->list, &memcg->objcg_list);
339 /* 2) Reparent active objcg and already reparented objcgs to parent. */
340 list_for_each_entry(iter, &memcg->objcg_list, list)
341 WRITE_ONCE(iter->memcg, parent);
342 /* 3) Move already reparented objcgs to the parent's list */
343 list_splice(&memcg->objcg_list, &parent->objcg_list);
345 spin_unlock_irq(&objcg_lock);
347 percpu_ref_kill(&objcg->refcnt);
351 * This will be used as a shrinker list's index.
352 * The main reason for not using cgroup id for this:
353 * this works better in sparse environments, where we have a lot of memcgs,
354 * but only a few kmem-limited. Or also, if we have, for instance, 200
355 * memcgs, and none but the 200th is kmem-limited, we'd have to have a
356 * 200 entry array for that.
358 * The current size of the caches array is stored in memcg_nr_cache_ids. It
359 * will double each time we have to increase it.
361 static DEFINE_IDA(memcg_cache_ida);
362 int memcg_nr_cache_ids;
364 /* Protects memcg_nr_cache_ids */
365 static DECLARE_RWSEM(memcg_cache_ids_sem);
367 void memcg_get_cache_ids(void)
369 down_read(&memcg_cache_ids_sem);
372 void memcg_put_cache_ids(void)
374 up_read(&memcg_cache_ids_sem);
378 * MIN_SIZE is different than 1, because we would like to avoid going through
379 * the alloc/free process all the time. In a small machine, 4 kmem-limited
380 * cgroups is a reasonable guess. In the future, it could be a parameter or
381 * tunable, but that is strictly not necessary.
383 * MAX_SIZE should be as large as the number of cgrp_ids. Ideally, we could get
384 * this constant directly from cgroup, but it is understandable that this is
385 * better kept as an internal representation in cgroup.c. In any case, the
386 * cgrp_id space is not getting any smaller, and we don't have to necessarily
387 * increase ours as well if it increases.
389 #define MEMCG_CACHES_MIN_SIZE 4
390 #define MEMCG_CACHES_MAX_SIZE MEM_CGROUP_ID_MAX
393 * A lot of the calls to the cache allocation functions are expected to be
394 * inlined by the compiler. Since the calls to memcg_slab_pre_alloc_hook() are
395 * conditional to this static branch, we'll have to allow modules that does
396 * kmem_cache_alloc and the such to see this symbol as well
398 DEFINE_STATIC_KEY_FALSE(memcg_kmem_enabled_key);
399 EXPORT_SYMBOL(memcg_kmem_enabled_key);
403 * mem_cgroup_css_from_page - css of the memcg associated with a page
404 * @page: page of interest
406 * If memcg is bound to the default hierarchy, css of the memcg associated
407 * with @page is returned. The returned css remains associated with @page
408 * until it is released.
410 * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
413 struct cgroup_subsys_state *mem_cgroup_css_from_page(struct page *page)
415 struct mem_cgroup *memcg;
417 memcg = page_memcg(page);
419 if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
420 memcg = root_mem_cgroup;
426 * page_cgroup_ino - return inode number of the memcg a page is charged to
429 * Look up the closest online ancestor of the memory cgroup @page is charged to
430 * and return its inode number or 0 if @page is not charged to any cgroup. It
431 * is safe to call this function without holding a reference to @page.
433 * Note, this function is inherently racy, because there is nothing to prevent
434 * the cgroup inode from getting torn down and potentially reallocated a moment
435 * after page_cgroup_ino() returns, so it only should be used by callers that
436 * do not care (such as procfs interfaces).
438 ino_t page_cgroup_ino(struct page *page)
440 struct mem_cgroup *memcg;
441 unsigned long ino = 0;
444 memcg = page_memcg_check(page);
446 while (memcg && !(memcg->css.flags & CSS_ONLINE))
447 memcg = parent_mem_cgroup(memcg);
449 ino = cgroup_ino(memcg->css.cgroup);
454 static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_node *mz,
455 struct mem_cgroup_tree_per_node *mctz,
456 unsigned long new_usage_in_excess)
458 struct rb_node **p = &mctz->rb_root.rb_node;
459 struct rb_node *parent = NULL;
460 struct mem_cgroup_per_node *mz_node;
461 bool rightmost = true;
466 mz->usage_in_excess = new_usage_in_excess;
467 if (!mz->usage_in_excess)
471 mz_node = rb_entry(parent, struct mem_cgroup_per_node,
473 if (mz->usage_in_excess < mz_node->usage_in_excess) {
482 mctz->rb_rightmost = &mz->tree_node;
484 rb_link_node(&mz->tree_node, parent, p);
485 rb_insert_color(&mz->tree_node, &mctz->rb_root);
489 static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
490 struct mem_cgroup_tree_per_node *mctz)
495 if (&mz->tree_node == mctz->rb_rightmost)
496 mctz->rb_rightmost = rb_prev(&mz->tree_node);
498 rb_erase(&mz->tree_node, &mctz->rb_root);
502 static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
503 struct mem_cgroup_tree_per_node *mctz)
507 spin_lock_irqsave(&mctz->lock, flags);
508 __mem_cgroup_remove_exceeded(mz, mctz);
509 spin_unlock_irqrestore(&mctz->lock, flags);
512 static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
514 unsigned long nr_pages = page_counter_read(&memcg->memory);
515 unsigned long soft_limit = READ_ONCE(memcg->soft_limit);
516 unsigned long excess = 0;
518 if (nr_pages > soft_limit)
519 excess = nr_pages - soft_limit;
524 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, int nid)
526 unsigned long excess;
527 struct mem_cgroup_per_node *mz;
528 struct mem_cgroup_tree_per_node *mctz;
530 mctz = soft_limit_tree.rb_tree_per_node[nid];
534 * Necessary to update all ancestors when hierarchy is used.
535 * because their event counter is not touched.
537 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
538 mz = memcg->nodeinfo[nid];
539 excess = soft_limit_excess(memcg);
541 * We have to update the tree if mz is on RB-tree or
542 * mem is over its softlimit.
544 if (excess || mz->on_tree) {
547 spin_lock_irqsave(&mctz->lock, flags);
548 /* if on-tree, remove it */
550 __mem_cgroup_remove_exceeded(mz, mctz);
552 * Insert again. mz->usage_in_excess will be updated.
553 * If excess is 0, no tree ops.
555 __mem_cgroup_insert_exceeded(mz, mctz, excess);
556 spin_unlock_irqrestore(&mctz->lock, flags);
561 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
563 struct mem_cgroup_tree_per_node *mctz;
564 struct mem_cgroup_per_node *mz;
568 mz = memcg->nodeinfo[nid];
569 mctz = soft_limit_tree.rb_tree_per_node[nid];
571 mem_cgroup_remove_exceeded(mz, mctz);
575 static struct mem_cgroup_per_node *
576 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
578 struct mem_cgroup_per_node *mz;
582 if (!mctz->rb_rightmost)
583 goto done; /* Nothing to reclaim from */
585 mz = rb_entry(mctz->rb_rightmost,
586 struct mem_cgroup_per_node, tree_node);
588 * Remove the node now but someone else can add it back,
589 * we will to add it back at the end of reclaim to its correct
590 * position in the tree.
592 __mem_cgroup_remove_exceeded(mz, mctz);
593 if (!soft_limit_excess(mz->memcg) ||
594 !css_tryget(&mz->memcg->css))
600 static struct mem_cgroup_per_node *
601 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
603 struct mem_cgroup_per_node *mz;
605 spin_lock_irq(&mctz->lock);
606 mz = __mem_cgroup_largest_soft_limit_node(mctz);
607 spin_unlock_irq(&mctz->lock);
612 * memcg and lruvec stats flushing
614 * Many codepaths leading to stats update or read are performance sensitive and
615 * adding stats flushing in such codepaths is not desirable. So, to optimize the
616 * flushing the kernel does:
618 * 1) Periodically and asynchronously flush the stats every 2 seconds to not let
619 * rstat update tree grow unbounded.
621 * 2) Flush the stats synchronously on reader side only when there are more than
622 * (MEMCG_CHARGE_BATCH * nr_cpus) update events. Though this optimization
623 * will let stats be out of sync by atmost (MEMCG_CHARGE_BATCH * nr_cpus) but
624 * only for 2 seconds due to (1).
626 static void flush_memcg_stats_dwork(struct work_struct *w);
627 static DECLARE_DEFERRABLE_WORK(stats_flush_dwork, flush_memcg_stats_dwork);
628 static DEFINE_SPINLOCK(stats_flush_lock);
629 static DEFINE_PER_CPU(unsigned int, stats_updates);
630 static atomic_t stats_flush_threshold = ATOMIC_INIT(0);
632 static inline void memcg_rstat_updated(struct mem_cgroup *memcg, int val)
636 cgroup_rstat_updated(memcg->css.cgroup, smp_processor_id());
638 x = __this_cpu_add_return(stats_updates, abs(val));
639 if (x > MEMCG_CHARGE_BATCH) {
640 atomic_add(x / MEMCG_CHARGE_BATCH, &stats_flush_threshold);
641 __this_cpu_write(stats_updates, 0);
645 static void __mem_cgroup_flush_stats(void)
649 if (!spin_trylock_irqsave(&stats_flush_lock, flag))
652 cgroup_rstat_flush_irqsafe(root_mem_cgroup->css.cgroup);
653 atomic_set(&stats_flush_threshold, 0);
654 spin_unlock_irqrestore(&stats_flush_lock, flag);
657 void mem_cgroup_flush_stats(void)
659 if (atomic_read(&stats_flush_threshold) > num_online_cpus())
660 __mem_cgroup_flush_stats();
663 static void flush_memcg_stats_dwork(struct work_struct *w)
665 __mem_cgroup_flush_stats();
666 queue_delayed_work(system_unbound_wq, &stats_flush_dwork, 2UL*HZ);
670 * __mod_memcg_state - update cgroup memory statistics
671 * @memcg: the memory cgroup
672 * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item
673 * @val: delta to add to the counter, can be negative
675 void __mod_memcg_state(struct mem_cgroup *memcg, int idx, int val)
677 if (mem_cgroup_disabled())
680 __this_cpu_add(memcg->vmstats_percpu->state[idx], val);
681 memcg_rstat_updated(memcg, val);
684 /* idx can be of type enum memcg_stat_item or node_stat_item. */
685 static unsigned long memcg_page_state_local(struct mem_cgroup *memcg, int idx)
690 for_each_possible_cpu(cpu)
691 x += per_cpu(memcg->vmstats_percpu->state[idx], cpu);
699 void __mod_memcg_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
702 struct mem_cgroup_per_node *pn;
703 struct mem_cgroup *memcg;
705 pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
709 __this_cpu_add(memcg->vmstats_percpu->state[idx], val);
712 __this_cpu_add(pn->lruvec_stats_percpu->state[idx], val);
714 memcg_rstat_updated(memcg, val);
718 * __mod_lruvec_state - update lruvec memory statistics
719 * @lruvec: the lruvec
720 * @idx: the stat item
721 * @val: delta to add to the counter, can be negative
723 * The lruvec is the intersection of the NUMA node and a cgroup. This
724 * function updates the all three counters that are affected by a
725 * change of state at this level: per-node, per-cgroup, per-lruvec.
727 void __mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
731 __mod_node_page_state(lruvec_pgdat(lruvec), idx, val);
733 /* Update memcg and lruvec */
734 if (!mem_cgroup_disabled())
735 __mod_memcg_lruvec_state(lruvec, idx, val);
738 void __mod_lruvec_page_state(struct page *page, enum node_stat_item idx,
741 struct page *head = compound_head(page); /* rmap on tail pages */
742 struct mem_cgroup *memcg;
743 pg_data_t *pgdat = page_pgdat(page);
744 struct lruvec *lruvec;
747 memcg = page_memcg(head);
748 /* Untracked pages have no memcg, no lruvec. Update only the node */
751 __mod_node_page_state(pgdat, idx, val);
755 lruvec = mem_cgroup_lruvec(memcg, pgdat);
756 __mod_lruvec_state(lruvec, idx, val);
759 EXPORT_SYMBOL(__mod_lruvec_page_state);
761 void __mod_lruvec_kmem_state(void *p, enum node_stat_item idx, int val)
763 pg_data_t *pgdat = page_pgdat(virt_to_page(p));
764 struct mem_cgroup *memcg;
765 struct lruvec *lruvec;
768 memcg = mem_cgroup_from_obj(p);
771 * Untracked pages have no memcg, no lruvec. Update only the
772 * node. If we reparent the slab objects to the root memcg,
773 * when we free the slab object, we need to update the per-memcg
774 * vmstats to keep it correct for the root memcg.
777 __mod_node_page_state(pgdat, idx, val);
779 lruvec = mem_cgroup_lruvec(memcg, pgdat);
780 __mod_lruvec_state(lruvec, idx, val);
786 * __count_memcg_events - account VM events in a cgroup
787 * @memcg: the memory cgroup
788 * @idx: the event item
789 * @count: the number of events that occurred
791 void __count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx,
794 if (mem_cgroup_disabled())
797 __this_cpu_add(memcg->vmstats_percpu->events[idx], count);
798 memcg_rstat_updated(memcg, count);
801 static unsigned long memcg_events(struct mem_cgroup *memcg, int event)
803 return READ_ONCE(memcg->vmstats.events[event]);
806 static unsigned long memcg_events_local(struct mem_cgroup *memcg, int event)
811 for_each_possible_cpu(cpu)
812 x += per_cpu(memcg->vmstats_percpu->events[event], cpu);
816 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
819 /* pagein of a big page is an event. So, ignore page size */
821 __count_memcg_events(memcg, PGPGIN, 1);
823 __count_memcg_events(memcg, PGPGOUT, 1);
824 nr_pages = -nr_pages; /* for event */
827 __this_cpu_add(memcg->vmstats_percpu->nr_page_events, nr_pages);
830 static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
831 enum mem_cgroup_events_target target)
833 unsigned long val, next;
835 val = __this_cpu_read(memcg->vmstats_percpu->nr_page_events);
836 next = __this_cpu_read(memcg->vmstats_percpu->targets[target]);
837 /* from time_after() in jiffies.h */
838 if ((long)(next - val) < 0) {
840 case MEM_CGROUP_TARGET_THRESH:
841 next = val + THRESHOLDS_EVENTS_TARGET;
843 case MEM_CGROUP_TARGET_SOFTLIMIT:
844 next = val + SOFTLIMIT_EVENTS_TARGET;
849 __this_cpu_write(memcg->vmstats_percpu->targets[target], next);
856 * Check events in order.
859 static void memcg_check_events(struct mem_cgroup *memcg, int nid)
861 if (IS_ENABLED(CONFIG_PREEMPT_RT))
864 /* threshold event is triggered in finer grain than soft limit */
865 if (unlikely(mem_cgroup_event_ratelimit(memcg,
866 MEM_CGROUP_TARGET_THRESH))) {
869 do_softlimit = mem_cgroup_event_ratelimit(memcg,
870 MEM_CGROUP_TARGET_SOFTLIMIT);
871 mem_cgroup_threshold(memcg);
872 if (unlikely(do_softlimit))
873 mem_cgroup_update_tree(memcg, nid);
877 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
880 * mm_update_next_owner() may clear mm->owner to NULL
881 * if it races with swapoff, page migration, etc.
882 * So this can be called with p == NULL.
887 return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
889 EXPORT_SYMBOL(mem_cgroup_from_task);
891 static __always_inline struct mem_cgroup *active_memcg(void)
894 return this_cpu_read(int_active_memcg);
896 return current->active_memcg;
900 * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
901 * @mm: mm from which memcg should be extracted. It can be NULL.
903 * Obtain a reference on mm->memcg and returns it if successful. If mm
904 * is NULL, then the memcg is chosen as follows:
905 * 1) The active memcg, if set.
906 * 2) current->mm->memcg, if available
908 * If mem_cgroup is disabled, NULL is returned.
910 struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
912 struct mem_cgroup *memcg;
914 if (mem_cgroup_disabled())
918 * Page cache insertions can happen without an
919 * actual mm context, e.g. during disk probing
920 * on boot, loopback IO, acct() writes etc.
922 * No need to css_get on root memcg as the reference
923 * counting is disabled on the root level in the
924 * cgroup core. See CSS_NO_REF.
927 memcg = active_memcg();
928 if (unlikely(memcg)) {
929 /* remote memcg must hold a ref */
930 css_get(&memcg->css);
935 return root_mem_cgroup;
940 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
941 if (unlikely(!memcg))
942 memcg = root_mem_cgroup;
943 } while (!css_tryget(&memcg->css));
947 EXPORT_SYMBOL(get_mem_cgroup_from_mm);
949 static __always_inline bool memcg_kmem_bypass(void)
951 /* Allow remote memcg charging from any context. */
952 if (unlikely(active_memcg()))
955 /* Memcg to charge can't be determined. */
956 if (!in_task() || !current->mm || (current->flags & PF_KTHREAD))
963 * mem_cgroup_iter - iterate over memory cgroup hierarchy
964 * @root: hierarchy root
965 * @prev: previously returned memcg, NULL on first invocation
966 * @reclaim: cookie for shared reclaim walks, NULL for full walks
968 * Returns references to children of the hierarchy below @root, or
969 * @root itself, or %NULL after a full round-trip.
971 * Caller must pass the return value in @prev on subsequent
972 * invocations for reference counting, or use mem_cgroup_iter_break()
973 * to cancel a hierarchy walk before the round-trip is complete.
975 * Reclaimers can specify a node in @reclaim to divide up the memcgs
976 * in the hierarchy among all concurrent reclaimers operating on the
979 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
980 struct mem_cgroup *prev,
981 struct mem_cgroup_reclaim_cookie *reclaim)
983 struct mem_cgroup_reclaim_iter *iter;
984 struct cgroup_subsys_state *css = NULL;
985 struct mem_cgroup *memcg = NULL;
986 struct mem_cgroup *pos = NULL;
988 if (mem_cgroup_disabled())
992 root = root_mem_cgroup;
994 if (prev && !reclaim)
1000 struct mem_cgroup_per_node *mz;
1002 mz = root->nodeinfo[reclaim->pgdat->node_id];
1005 if (prev && reclaim->generation != iter->generation)
1009 pos = READ_ONCE(iter->position);
1010 if (!pos || css_tryget(&pos->css))
1013 * css reference reached zero, so iter->position will
1014 * be cleared by ->css_released. However, we should not
1015 * rely on this happening soon, because ->css_released
1016 * is called from a work queue, and by busy-waiting we
1017 * might block it. So we clear iter->position right
1020 (void)cmpxchg(&iter->position, pos, NULL);
1028 css = css_next_descendant_pre(css, &root->css);
1031 * Reclaimers share the hierarchy walk, and a
1032 * new one might jump in right at the end of
1033 * the hierarchy - make sure they see at least
1034 * one group and restart from the beginning.
1042 * Verify the css and acquire a reference. The root
1043 * is provided by the caller, so we know it's alive
1044 * and kicking, and don't take an extra reference.
1046 memcg = mem_cgroup_from_css(css);
1048 if (css == &root->css)
1051 if (css_tryget(css))
1059 * The position could have already been updated by a competing
1060 * thread, so check that the value hasn't changed since we read
1061 * it to avoid reclaiming from the same cgroup twice.
1063 (void)cmpxchg(&iter->position, pos, memcg);
1071 reclaim->generation = iter->generation;
1076 if (prev && prev != root)
1077 css_put(&prev->css);
1083 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1084 * @root: hierarchy root
1085 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1087 void mem_cgroup_iter_break(struct mem_cgroup *root,
1088 struct mem_cgroup *prev)
1091 root = root_mem_cgroup;
1092 if (prev && prev != root)
1093 css_put(&prev->css);
1096 static void __invalidate_reclaim_iterators(struct mem_cgroup *from,
1097 struct mem_cgroup *dead_memcg)
1099 struct mem_cgroup_reclaim_iter *iter;
1100 struct mem_cgroup_per_node *mz;
1103 for_each_node(nid) {
1104 mz = from->nodeinfo[nid];
1106 cmpxchg(&iter->position, dead_memcg, NULL);
1110 static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
1112 struct mem_cgroup *memcg = dead_memcg;
1113 struct mem_cgroup *last;
1116 __invalidate_reclaim_iterators(memcg, dead_memcg);
1118 } while ((memcg = parent_mem_cgroup(memcg)));
1121 * When cgruop1 non-hierarchy mode is used,
1122 * parent_mem_cgroup() does not walk all the way up to the
1123 * cgroup root (root_mem_cgroup). So we have to handle
1124 * dead_memcg from cgroup root separately.
1126 if (last != root_mem_cgroup)
1127 __invalidate_reclaim_iterators(root_mem_cgroup,
1132 * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
1133 * @memcg: hierarchy root
1134 * @fn: function to call for each task
1135 * @arg: argument passed to @fn
1137 * This function iterates over tasks attached to @memcg or to any of its
1138 * descendants and calls @fn for each task. If @fn returns a non-zero
1139 * value, the function breaks the iteration loop and returns the value.
1140 * Otherwise, it will iterate over all tasks and return 0.
1142 * This function must not be called for the root memory cgroup.
1144 int mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
1145 int (*fn)(struct task_struct *, void *), void *arg)
1147 struct mem_cgroup *iter;
1150 BUG_ON(memcg == root_mem_cgroup);
1152 for_each_mem_cgroup_tree(iter, memcg) {
1153 struct css_task_iter it;
1154 struct task_struct *task;
1156 css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it);
1157 while (!ret && (task = css_task_iter_next(&it)))
1158 ret = fn(task, arg);
1159 css_task_iter_end(&it);
1161 mem_cgroup_iter_break(memcg, iter);
1168 #ifdef CONFIG_DEBUG_VM
1169 void lruvec_memcg_debug(struct lruvec *lruvec, struct folio *folio)
1171 struct mem_cgroup *memcg;
1173 if (mem_cgroup_disabled())
1176 memcg = folio_memcg(folio);
1179 VM_BUG_ON_FOLIO(lruvec_memcg(lruvec) != root_mem_cgroup, folio);
1181 VM_BUG_ON_FOLIO(lruvec_memcg(lruvec) != memcg, folio);
1186 * folio_lruvec_lock - Lock the lruvec for a folio.
1187 * @folio: Pointer to the folio.
1189 * These functions are safe to use under any of the following conditions:
1191 * - folio_test_lru false
1192 * - folio_memcg_lock()
1193 * - folio frozen (refcount of 0)
1195 * Return: The lruvec this folio is on with its lock held.
1197 struct lruvec *folio_lruvec_lock(struct folio *folio)
1199 struct lruvec *lruvec = folio_lruvec(folio);
1201 spin_lock(&lruvec->lru_lock);
1202 lruvec_memcg_debug(lruvec, folio);
1208 * folio_lruvec_lock_irq - Lock the lruvec for a folio.
1209 * @folio: Pointer to the folio.
1211 * These functions are safe to use under any of the following conditions:
1213 * - folio_test_lru false
1214 * - folio_memcg_lock()
1215 * - folio frozen (refcount of 0)
1217 * Return: The lruvec this folio is on with its lock held and interrupts
1220 struct lruvec *folio_lruvec_lock_irq(struct folio *folio)
1222 struct lruvec *lruvec = folio_lruvec(folio);
1224 spin_lock_irq(&lruvec->lru_lock);
1225 lruvec_memcg_debug(lruvec, folio);
1231 * folio_lruvec_lock_irqsave - Lock the lruvec for a folio.
1232 * @folio: Pointer to the folio.
1233 * @flags: Pointer to irqsave flags.
1235 * These functions are safe to use under any of the following conditions:
1237 * - folio_test_lru false
1238 * - folio_memcg_lock()
1239 * - folio frozen (refcount of 0)
1241 * Return: The lruvec this folio is on with its lock held and interrupts
1244 struct lruvec *folio_lruvec_lock_irqsave(struct folio *folio,
1245 unsigned long *flags)
1247 struct lruvec *lruvec = folio_lruvec(folio);
1249 spin_lock_irqsave(&lruvec->lru_lock, *flags);
1250 lruvec_memcg_debug(lruvec, folio);
1256 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1257 * @lruvec: mem_cgroup per zone lru vector
1258 * @lru: index of lru list the page is sitting on
1259 * @zid: zone id of the accounted pages
1260 * @nr_pages: positive when adding or negative when removing
1262 * This function must be called under lru_lock, just before a page is added
1263 * to or just after a page is removed from an lru list (that ordering being
1264 * so as to allow it to check that lru_size 0 is consistent with list_empty).
1266 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1267 int zid, int nr_pages)
1269 struct mem_cgroup_per_node *mz;
1270 unsigned long *lru_size;
1273 if (mem_cgroup_disabled())
1276 mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
1277 lru_size = &mz->lru_zone_size[zid][lru];
1280 *lru_size += nr_pages;
1283 if (WARN_ONCE(size < 0,
1284 "%s(%p, %d, %d): lru_size %ld\n",
1285 __func__, lruvec, lru, nr_pages, size)) {
1291 *lru_size += nr_pages;
1295 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1296 * @memcg: the memory cgroup
1298 * Returns the maximum amount of memory @mem can be charged with, in
1301 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1303 unsigned long margin = 0;
1304 unsigned long count;
1305 unsigned long limit;
1307 count = page_counter_read(&memcg->memory);
1308 limit = READ_ONCE(memcg->memory.max);
1310 margin = limit - count;
1312 if (do_memsw_account()) {
1313 count = page_counter_read(&memcg->memsw);
1314 limit = READ_ONCE(memcg->memsw.max);
1316 margin = min(margin, limit - count);
1325 * A routine for checking "mem" is under move_account() or not.
1327 * Checking a cgroup is mc.from or mc.to or under hierarchy of
1328 * moving cgroups. This is for waiting at high-memory pressure
1331 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1333 struct mem_cgroup *from;
1334 struct mem_cgroup *to;
1337 * Unlike task_move routines, we access mc.to, mc.from not under
1338 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1340 spin_lock(&mc.lock);
1346 ret = mem_cgroup_is_descendant(from, memcg) ||
1347 mem_cgroup_is_descendant(to, memcg);
1349 spin_unlock(&mc.lock);
1353 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1355 if (mc.moving_task && current != mc.moving_task) {
1356 if (mem_cgroup_under_move(memcg)) {
1358 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1359 /* moving charge context might have finished. */
1362 finish_wait(&mc.waitq, &wait);
1369 struct memory_stat {
1374 static const struct memory_stat memory_stats[] = {
1375 { "anon", NR_ANON_MAPPED },
1376 { "file", NR_FILE_PAGES },
1377 { "kernel", MEMCG_KMEM },
1378 { "kernel_stack", NR_KERNEL_STACK_KB },
1379 { "pagetables", NR_PAGETABLE },
1380 { "percpu", MEMCG_PERCPU_B },
1381 { "sock", MEMCG_SOCK },
1382 { "vmalloc", MEMCG_VMALLOC },
1383 { "shmem", NR_SHMEM },
1384 { "file_mapped", NR_FILE_MAPPED },
1385 { "file_dirty", NR_FILE_DIRTY },
1386 { "file_writeback", NR_WRITEBACK },
1388 { "swapcached", NR_SWAPCACHE },
1390 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1391 { "anon_thp", NR_ANON_THPS },
1392 { "file_thp", NR_FILE_THPS },
1393 { "shmem_thp", NR_SHMEM_THPS },
1395 { "inactive_anon", NR_INACTIVE_ANON },
1396 { "active_anon", NR_ACTIVE_ANON },
1397 { "inactive_file", NR_INACTIVE_FILE },
1398 { "active_file", NR_ACTIVE_FILE },
1399 { "unevictable", NR_UNEVICTABLE },
1400 { "slab_reclaimable", NR_SLAB_RECLAIMABLE_B },
1401 { "slab_unreclaimable", NR_SLAB_UNRECLAIMABLE_B },
1403 /* The memory events */
1404 { "workingset_refault_anon", WORKINGSET_REFAULT_ANON },
1405 { "workingset_refault_file", WORKINGSET_REFAULT_FILE },
1406 { "workingset_activate_anon", WORKINGSET_ACTIVATE_ANON },
1407 { "workingset_activate_file", WORKINGSET_ACTIVATE_FILE },
1408 { "workingset_restore_anon", WORKINGSET_RESTORE_ANON },
1409 { "workingset_restore_file", WORKINGSET_RESTORE_FILE },
1410 { "workingset_nodereclaim", WORKINGSET_NODERECLAIM },
1413 /* Translate stat items to the correct unit for memory.stat output */
1414 static int memcg_page_state_unit(int item)
1417 case MEMCG_PERCPU_B:
1418 case NR_SLAB_RECLAIMABLE_B:
1419 case NR_SLAB_UNRECLAIMABLE_B:
1420 case WORKINGSET_REFAULT_ANON:
1421 case WORKINGSET_REFAULT_FILE:
1422 case WORKINGSET_ACTIVATE_ANON:
1423 case WORKINGSET_ACTIVATE_FILE:
1424 case WORKINGSET_RESTORE_ANON:
1425 case WORKINGSET_RESTORE_FILE:
1426 case WORKINGSET_NODERECLAIM:
1428 case NR_KERNEL_STACK_KB:
1435 static inline unsigned long memcg_page_state_output(struct mem_cgroup *memcg,
1438 return memcg_page_state(memcg, item) * memcg_page_state_unit(item);
1441 static char *memory_stat_format(struct mem_cgroup *memcg)
1446 seq_buf_init(&s, kmalloc(PAGE_SIZE, GFP_KERNEL), PAGE_SIZE);
1451 * Provide statistics on the state of the memory subsystem as
1452 * well as cumulative event counters that show past behavior.
1454 * This list is ordered following a combination of these gradients:
1455 * 1) generic big picture -> specifics and details
1456 * 2) reflecting userspace activity -> reflecting kernel heuristics
1458 * Current memory state:
1460 mem_cgroup_flush_stats();
1462 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
1465 size = memcg_page_state_output(memcg, memory_stats[i].idx);
1466 seq_buf_printf(&s, "%s %llu\n", memory_stats[i].name, size);
1468 if (unlikely(memory_stats[i].idx == NR_SLAB_UNRECLAIMABLE_B)) {
1469 size += memcg_page_state_output(memcg,
1470 NR_SLAB_RECLAIMABLE_B);
1471 seq_buf_printf(&s, "slab %llu\n", size);
1475 /* Accumulated memory events */
1477 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGFAULT),
1478 memcg_events(memcg, PGFAULT));
1479 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGMAJFAULT),
1480 memcg_events(memcg, PGMAJFAULT));
1481 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGREFILL),
1482 memcg_events(memcg, PGREFILL));
1483 seq_buf_printf(&s, "pgscan %lu\n",
1484 memcg_events(memcg, PGSCAN_KSWAPD) +
1485 memcg_events(memcg, PGSCAN_DIRECT));
1486 seq_buf_printf(&s, "pgsteal %lu\n",
1487 memcg_events(memcg, PGSTEAL_KSWAPD) +
1488 memcg_events(memcg, PGSTEAL_DIRECT));
1489 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGACTIVATE),
1490 memcg_events(memcg, PGACTIVATE));
1491 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGDEACTIVATE),
1492 memcg_events(memcg, PGDEACTIVATE));
1493 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGLAZYFREE),
1494 memcg_events(memcg, PGLAZYFREE));
1495 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGLAZYFREED),
1496 memcg_events(memcg, PGLAZYFREED));
1498 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1499 seq_buf_printf(&s, "%s %lu\n", vm_event_name(THP_FAULT_ALLOC),
1500 memcg_events(memcg, THP_FAULT_ALLOC));
1501 seq_buf_printf(&s, "%s %lu\n", vm_event_name(THP_COLLAPSE_ALLOC),
1502 memcg_events(memcg, THP_COLLAPSE_ALLOC));
1503 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
1505 /* The above should easily fit into one page */
1506 WARN_ON_ONCE(seq_buf_has_overflowed(&s));
1511 #define K(x) ((x) << (PAGE_SHIFT-10))
1513 * mem_cgroup_print_oom_context: Print OOM information relevant to
1514 * memory controller.
1515 * @memcg: The memory cgroup that went over limit
1516 * @p: Task that is going to be killed
1518 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1521 void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p)
1526 pr_cont(",oom_memcg=");
1527 pr_cont_cgroup_path(memcg->css.cgroup);
1529 pr_cont(",global_oom");
1531 pr_cont(",task_memcg=");
1532 pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
1538 * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
1539 * memory controller.
1540 * @memcg: The memory cgroup that went over limit
1542 void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
1546 pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1547 K((u64)page_counter_read(&memcg->memory)),
1548 K((u64)READ_ONCE(memcg->memory.max)), memcg->memory.failcnt);
1549 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1550 pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n",
1551 K((u64)page_counter_read(&memcg->swap)),
1552 K((u64)READ_ONCE(memcg->swap.max)), memcg->swap.failcnt);
1554 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1555 K((u64)page_counter_read(&memcg->memsw)),
1556 K((u64)memcg->memsw.max), memcg->memsw.failcnt);
1557 pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1558 K((u64)page_counter_read(&memcg->kmem)),
1559 K((u64)memcg->kmem.max), memcg->kmem.failcnt);
1562 pr_info("Memory cgroup stats for ");
1563 pr_cont_cgroup_path(memcg->css.cgroup);
1565 buf = memory_stat_format(memcg);
1573 * Return the memory (and swap, if configured) limit for a memcg.
1575 unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg)
1577 unsigned long max = READ_ONCE(memcg->memory.max);
1579 if (cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
1580 if (mem_cgroup_swappiness(memcg))
1581 max += min(READ_ONCE(memcg->swap.max),
1582 (unsigned long)total_swap_pages);
1584 if (mem_cgroup_swappiness(memcg)) {
1585 /* Calculate swap excess capacity from memsw limit */
1586 unsigned long swap = READ_ONCE(memcg->memsw.max) - max;
1588 max += min(swap, (unsigned long)total_swap_pages);
1594 unsigned long mem_cgroup_size(struct mem_cgroup *memcg)
1596 return page_counter_read(&memcg->memory);
1599 static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1602 struct oom_control oc = {
1606 .gfp_mask = gfp_mask,
1611 if (mutex_lock_killable(&oom_lock))
1614 if (mem_cgroup_margin(memcg) >= (1 << order))
1618 * A few threads which were not waiting at mutex_lock_killable() can
1619 * fail to bail out. Therefore, check again after holding oom_lock.
1621 ret = task_is_dying() || out_of_memory(&oc);
1624 mutex_unlock(&oom_lock);
1628 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
1631 unsigned long *total_scanned)
1633 struct mem_cgroup *victim = NULL;
1636 unsigned long excess;
1637 unsigned long nr_scanned;
1638 struct mem_cgroup_reclaim_cookie reclaim = {
1642 excess = soft_limit_excess(root_memcg);
1645 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1650 * If we have not been able to reclaim
1651 * anything, it might because there are
1652 * no reclaimable pages under this hierarchy
1657 * We want to do more targeted reclaim.
1658 * excess >> 2 is not to excessive so as to
1659 * reclaim too much, nor too less that we keep
1660 * coming back to reclaim from this cgroup
1662 if (total >= (excess >> 2) ||
1663 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1668 total += mem_cgroup_shrink_node(victim, gfp_mask, false,
1669 pgdat, &nr_scanned);
1670 *total_scanned += nr_scanned;
1671 if (!soft_limit_excess(root_memcg))
1674 mem_cgroup_iter_break(root_memcg, victim);
1678 #ifdef CONFIG_LOCKDEP
1679 static struct lockdep_map memcg_oom_lock_dep_map = {
1680 .name = "memcg_oom_lock",
1684 static DEFINE_SPINLOCK(memcg_oom_lock);
1687 * Check OOM-Killer is already running under our hierarchy.
1688 * If someone is running, return false.
1690 static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
1692 struct mem_cgroup *iter, *failed = NULL;
1694 spin_lock(&memcg_oom_lock);
1696 for_each_mem_cgroup_tree(iter, memcg) {
1697 if (iter->oom_lock) {
1699 * this subtree of our hierarchy is already locked
1700 * so we cannot give a lock.
1703 mem_cgroup_iter_break(memcg, iter);
1706 iter->oom_lock = true;
1711 * OK, we failed to lock the whole subtree so we have
1712 * to clean up what we set up to the failing subtree
1714 for_each_mem_cgroup_tree(iter, memcg) {
1715 if (iter == failed) {
1716 mem_cgroup_iter_break(memcg, iter);
1719 iter->oom_lock = false;
1722 mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
1724 spin_unlock(&memcg_oom_lock);
1729 static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1731 struct mem_cgroup *iter;
1733 spin_lock(&memcg_oom_lock);
1734 mutex_release(&memcg_oom_lock_dep_map, _RET_IP_);
1735 for_each_mem_cgroup_tree(iter, memcg)
1736 iter->oom_lock = false;
1737 spin_unlock(&memcg_oom_lock);
1740 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1742 struct mem_cgroup *iter;
1744 spin_lock(&memcg_oom_lock);
1745 for_each_mem_cgroup_tree(iter, memcg)
1747 spin_unlock(&memcg_oom_lock);
1750 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1752 struct mem_cgroup *iter;
1755 * Be careful about under_oom underflows because a child memcg
1756 * could have been added after mem_cgroup_mark_under_oom.
1758 spin_lock(&memcg_oom_lock);
1759 for_each_mem_cgroup_tree(iter, memcg)
1760 if (iter->under_oom > 0)
1762 spin_unlock(&memcg_oom_lock);
1765 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1767 struct oom_wait_info {
1768 struct mem_cgroup *memcg;
1769 wait_queue_entry_t wait;
1772 static int memcg_oom_wake_function(wait_queue_entry_t *wait,
1773 unsigned mode, int sync, void *arg)
1775 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
1776 struct mem_cgroup *oom_wait_memcg;
1777 struct oom_wait_info *oom_wait_info;
1779 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1780 oom_wait_memcg = oom_wait_info->memcg;
1782 if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
1783 !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
1785 return autoremove_wake_function(wait, mode, sync, arg);
1788 static void memcg_oom_recover(struct mem_cgroup *memcg)
1791 * For the following lockless ->under_oom test, the only required
1792 * guarantee is that it must see the state asserted by an OOM when
1793 * this function is called as a result of userland actions
1794 * triggered by the notification of the OOM. This is trivially
1795 * achieved by invoking mem_cgroup_mark_under_oom() before
1796 * triggering notification.
1798 if (memcg && memcg->under_oom)
1799 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
1803 * Returns true if successfully killed one or more processes. Though in some
1804 * corner cases it can return true even without killing any process.
1806 static bool mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
1810 if (order > PAGE_ALLOC_COSTLY_ORDER)
1813 memcg_memory_event(memcg, MEMCG_OOM);
1816 * We are in the middle of the charge context here, so we
1817 * don't want to block when potentially sitting on a callstack
1818 * that holds all kinds of filesystem and mm locks.
1820 * cgroup1 allows disabling the OOM killer and waiting for outside
1821 * handling until the charge can succeed; remember the context and put
1822 * the task to sleep at the end of the page fault when all locks are
1825 * On the other hand, in-kernel OOM killer allows for an async victim
1826 * memory reclaim (oom_reaper) and that means that we are not solely
1827 * relying on the oom victim to make a forward progress and we can
1828 * invoke the oom killer here.
1830 * Please note that mem_cgroup_out_of_memory might fail to find a
1831 * victim and then we have to bail out from the charge path.
1833 if (memcg->oom_kill_disable) {
1834 if (current->in_user_fault) {
1835 css_get(&memcg->css);
1836 current->memcg_in_oom = memcg;
1837 current->memcg_oom_gfp_mask = mask;
1838 current->memcg_oom_order = order;
1843 mem_cgroup_mark_under_oom(memcg);
1845 locked = mem_cgroup_oom_trylock(memcg);
1848 mem_cgroup_oom_notify(memcg);
1850 mem_cgroup_unmark_under_oom(memcg);
1851 ret = mem_cgroup_out_of_memory(memcg, mask, order);
1854 mem_cgroup_oom_unlock(memcg);
1860 * mem_cgroup_oom_synchronize - complete memcg OOM handling
1861 * @handle: actually kill/wait or just clean up the OOM state
1863 * This has to be called at the end of a page fault if the memcg OOM
1864 * handler was enabled.
1866 * Memcg supports userspace OOM handling where failed allocations must
1867 * sleep on a waitqueue until the userspace task resolves the
1868 * situation. Sleeping directly in the charge context with all kinds
1869 * of locks held is not a good idea, instead we remember an OOM state
1870 * in the task and mem_cgroup_oom_synchronize() has to be called at
1871 * the end of the page fault to complete the OOM handling.
1873 * Returns %true if an ongoing memcg OOM situation was detected and
1874 * completed, %false otherwise.
1876 bool mem_cgroup_oom_synchronize(bool handle)
1878 struct mem_cgroup *memcg = current->memcg_in_oom;
1879 struct oom_wait_info owait;
1882 /* OOM is global, do not handle */
1889 owait.memcg = memcg;
1890 owait.wait.flags = 0;
1891 owait.wait.func = memcg_oom_wake_function;
1892 owait.wait.private = current;
1893 INIT_LIST_HEAD(&owait.wait.entry);
1895 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
1896 mem_cgroup_mark_under_oom(memcg);
1898 locked = mem_cgroup_oom_trylock(memcg);
1901 mem_cgroup_oom_notify(memcg);
1903 if (locked && !memcg->oom_kill_disable) {
1904 mem_cgroup_unmark_under_oom(memcg);
1905 finish_wait(&memcg_oom_waitq, &owait.wait);
1906 mem_cgroup_out_of_memory(memcg, current->memcg_oom_gfp_mask,
1907 current->memcg_oom_order);
1910 mem_cgroup_unmark_under_oom(memcg);
1911 finish_wait(&memcg_oom_waitq, &owait.wait);
1915 mem_cgroup_oom_unlock(memcg);
1917 * There is no guarantee that an OOM-lock contender
1918 * sees the wakeups triggered by the OOM kill
1919 * uncharges. Wake any sleepers explicitly.
1921 memcg_oom_recover(memcg);
1924 current->memcg_in_oom = NULL;
1925 css_put(&memcg->css);
1930 * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
1931 * @victim: task to be killed by the OOM killer
1932 * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
1934 * Returns a pointer to a memory cgroup, which has to be cleaned up
1935 * by killing all belonging OOM-killable tasks.
1937 * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
1939 struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim,
1940 struct mem_cgroup *oom_domain)
1942 struct mem_cgroup *oom_group = NULL;
1943 struct mem_cgroup *memcg;
1945 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
1949 oom_domain = root_mem_cgroup;
1953 memcg = mem_cgroup_from_task(victim);
1954 if (memcg == root_mem_cgroup)
1958 * If the victim task has been asynchronously moved to a different
1959 * memory cgroup, we might end up killing tasks outside oom_domain.
1960 * In this case it's better to ignore memory.group.oom.
1962 if (unlikely(!mem_cgroup_is_descendant(memcg, oom_domain)))
1966 * Traverse the memory cgroup hierarchy from the victim task's
1967 * cgroup up to the OOMing cgroup (or root) to find the
1968 * highest-level memory cgroup with oom.group set.
1970 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
1971 if (memcg->oom_group)
1974 if (memcg == oom_domain)
1979 css_get(&oom_group->css);
1986 void mem_cgroup_print_oom_group(struct mem_cgroup *memcg)
1988 pr_info("Tasks in ");
1989 pr_cont_cgroup_path(memcg->css.cgroup);
1990 pr_cont(" are going to be killed due to memory.oom.group set\n");
1994 * folio_memcg_lock - Bind a folio to its memcg.
1995 * @folio: The folio.
1997 * This function prevents unlocked LRU folios from being moved to
2000 * It ensures lifetime of the bound memcg. The caller is responsible
2001 * for the lifetime of the folio.
2003 void folio_memcg_lock(struct folio *folio)
2005 struct mem_cgroup *memcg;
2006 unsigned long flags;
2009 * The RCU lock is held throughout the transaction. The fast
2010 * path can get away without acquiring the memcg->move_lock
2011 * because page moving starts with an RCU grace period.
2015 if (mem_cgroup_disabled())
2018 memcg = folio_memcg(folio);
2019 if (unlikely(!memcg))
2022 #ifdef CONFIG_PROVE_LOCKING
2023 local_irq_save(flags);
2024 might_lock(&memcg->move_lock);
2025 local_irq_restore(flags);
2028 if (atomic_read(&memcg->moving_account) <= 0)
2031 spin_lock_irqsave(&memcg->move_lock, flags);
2032 if (memcg != folio_memcg(folio)) {
2033 spin_unlock_irqrestore(&memcg->move_lock, flags);
2038 * When charge migration first begins, we can have multiple
2039 * critical sections holding the fast-path RCU lock and one
2040 * holding the slowpath move_lock. Track the task who has the
2041 * move_lock for unlock_page_memcg().
2043 memcg->move_lock_task = current;
2044 memcg->move_lock_flags = flags;
2047 void lock_page_memcg(struct page *page)
2049 folio_memcg_lock(page_folio(page));
2052 static void __folio_memcg_unlock(struct mem_cgroup *memcg)
2054 if (memcg && memcg->move_lock_task == current) {
2055 unsigned long flags = memcg->move_lock_flags;
2057 memcg->move_lock_task = NULL;
2058 memcg->move_lock_flags = 0;
2060 spin_unlock_irqrestore(&memcg->move_lock, flags);
2067 * folio_memcg_unlock - Release the binding between a folio and its memcg.
2068 * @folio: The folio.
2070 * This releases the binding created by folio_memcg_lock(). This does
2071 * not change the accounting of this folio to its memcg, but it does
2072 * permit others to change it.
2074 void folio_memcg_unlock(struct folio *folio)
2076 __folio_memcg_unlock(folio_memcg(folio));
2079 void unlock_page_memcg(struct page *page)
2081 folio_memcg_unlock(page_folio(page));
2084 struct memcg_stock_pcp {
2085 struct mem_cgroup *cached; /* this never be root cgroup */
2086 unsigned int nr_pages;
2088 #ifdef CONFIG_MEMCG_KMEM
2089 struct obj_cgroup *cached_objcg;
2090 struct pglist_data *cached_pgdat;
2091 unsigned int nr_bytes;
2092 int nr_slab_reclaimable_b;
2093 int nr_slab_unreclaimable_b;
2096 struct work_struct work;
2097 unsigned long flags;
2098 #define FLUSHING_CACHED_CHARGE 0
2100 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
2101 static DEFINE_MUTEX(percpu_charge_mutex);
2103 #ifdef CONFIG_MEMCG_KMEM
2104 static void drain_obj_stock(struct memcg_stock_pcp *stock);
2105 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2106 struct mem_cgroup *root_memcg);
2107 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages);
2110 static inline void drain_obj_stock(struct memcg_stock_pcp *stock)
2113 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2114 struct mem_cgroup *root_memcg)
2118 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages)
2124 * consume_stock: Try to consume stocked charge on this cpu.
2125 * @memcg: memcg to consume from.
2126 * @nr_pages: how many pages to charge.
2128 * The charges will only happen if @memcg matches the current cpu's memcg
2129 * stock, and at least @nr_pages are available in that stock. Failure to
2130 * service an allocation will refill the stock.
2132 * returns true if successful, false otherwise.
2134 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2136 struct memcg_stock_pcp *stock;
2137 unsigned long flags;
2140 if (nr_pages > MEMCG_CHARGE_BATCH)
2143 local_irq_save(flags);
2145 stock = this_cpu_ptr(&memcg_stock);
2146 if (memcg == stock->cached && stock->nr_pages >= nr_pages) {
2147 stock->nr_pages -= nr_pages;
2151 local_irq_restore(flags);
2157 * Returns stocks cached in percpu and reset cached information.
2159 static void drain_stock(struct memcg_stock_pcp *stock)
2161 struct mem_cgroup *old = stock->cached;
2166 if (stock->nr_pages) {
2167 page_counter_uncharge(&old->memory, stock->nr_pages);
2168 if (do_memsw_account())
2169 page_counter_uncharge(&old->memsw, stock->nr_pages);
2170 stock->nr_pages = 0;
2174 stock->cached = NULL;
2177 static void drain_local_stock(struct work_struct *dummy)
2179 struct memcg_stock_pcp *stock;
2180 unsigned long flags;
2183 * The only protection from cpu hotplug (memcg_hotplug_cpu_dead) vs.
2184 * drain_stock races is that we always operate on local CPU stock
2185 * here with IRQ disabled
2187 local_irq_save(flags);
2189 stock = this_cpu_ptr(&memcg_stock);
2190 drain_obj_stock(stock);
2192 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2194 local_irq_restore(flags);
2198 * Cache charges(val) to local per_cpu area.
2199 * This will be consumed by consume_stock() function, later.
2201 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2203 struct memcg_stock_pcp *stock;
2204 unsigned long flags;
2206 local_irq_save(flags);
2208 stock = this_cpu_ptr(&memcg_stock);
2209 if (stock->cached != memcg) { /* reset if necessary */
2211 css_get(&memcg->css);
2212 stock->cached = memcg;
2214 stock->nr_pages += nr_pages;
2216 if (stock->nr_pages > MEMCG_CHARGE_BATCH)
2219 local_irq_restore(flags);
2223 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2224 * of the hierarchy under it.
2226 static void drain_all_stock(struct mem_cgroup *root_memcg)
2230 /* If someone's already draining, avoid adding running more workers. */
2231 if (!mutex_trylock(&percpu_charge_mutex))
2234 * Notify other cpus that system-wide "drain" is running
2235 * We do not care about races with the cpu hotplug because cpu down
2236 * as well as workers from this path always operate on the local
2237 * per-cpu data. CPU up doesn't touch memcg_stock at all.
2240 for_each_online_cpu(cpu) {
2241 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2242 struct mem_cgroup *memcg;
2246 memcg = stock->cached;
2247 if (memcg && stock->nr_pages &&
2248 mem_cgroup_is_descendant(memcg, root_memcg))
2250 else if (obj_stock_flush_required(stock, root_memcg))
2255 !test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2257 drain_local_stock(&stock->work);
2259 schedule_work_on(cpu, &stock->work);
2263 mutex_unlock(&percpu_charge_mutex);
2266 static int memcg_hotplug_cpu_dead(unsigned int cpu)
2268 struct memcg_stock_pcp *stock;
2270 stock = &per_cpu(memcg_stock, cpu);
2276 static unsigned long reclaim_high(struct mem_cgroup *memcg,
2277 unsigned int nr_pages,
2280 unsigned long nr_reclaimed = 0;
2283 unsigned long pflags;
2285 if (page_counter_read(&memcg->memory) <=
2286 READ_ONCE(memcg->memory.high))
2289 memcg_memory_event(memcg, MEMCG_HIGH);
2291 psi_memstall_enter(&pflags);
2292 nr_reclaimed += try_to_free_mem_cgroup_pages(memcg, nr_pages,
2294 psi_memstall_leave(&pflags);
2295 } while ((memcg = parent_mem_cgroup(memcg)) &&
2296 !mem_cgroup_is_root(memcg));
2298 return nr_reclaimed;
2301 static void high_work_func(struct work_struct *work)
2303 struct mem_cgroup *memcg;
2305 memcg = container_of(work, struct mem_cgroup, high_work);
2306 reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
2310 * Clamp the maximum sleep time per allocation batch to 2 seconds. This is
2311 * enough to still cause a significant slowdown in most cases, while still
2312 * allowing diagnostics and tracing to proceed without becoming stuck.
2314 #define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ)
2317 * When calculating the delay, we use these either side of the exponentiation to
2318 * maintain precision and scale to a reasonable number of jiffies (see the table
2321 * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the
2322 * overage ratio to a delay.
2323 * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down the
2324 * proposed penalty in order to reduce to a reasonable number of jiffies, and
2325 * to produce a reasonable delay curve.
2327 * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a
2328 * reasonable delay curve compared to precision-adjusted overage, not
2329 * penalising heavily at first, but still making sure that growth beyond the
2330 * limit penalises misbehaviour cgroups by slowing them down exponentially. For
2331 * example, with a high of 100 megabytes:
2333 * +-------+------------------------+
2334 * | usage | time to allocate in ms |
2335 * +-------+------------------------+
2357 * +-------+------------------------+
2359 #define MEMCG_DELAY_PRECISION_SHIFT 20
2360 #define MEMCG_DELAY_SCALING_SHIFT 14
2362 static u64 calculate_overage(unsigned long usage, unsigned long high)
2370 * Prevent division by 0 in overage calculation by acting as if
2371 * it was a threshold of 1 page
2373 high = max(high, 1UL);
2375 overage = usage - high;
2376 overage <<= MEMCG_DELAY_PRECISION_SHIFT;
2377 return div64_u64(overage, high);
2380 static u64 mem_find_max_overage(struct mem_cgroup *memcg)
2382 u64 overage, max_overage = 0;
2385 overage = calculate_overage(page_counter_read(&memcg->memory),
2386 READ_ONCE(memcg->memory.high));
2387 max_overage = max(overage, max_overage);
2388 } while ((memcg = parent_mem_cgroup(memcg)) &&
2389 !mem_cgroup_is_root(memcg));
2394 static u64 swap_find_max_overage(struct mem_cgroup *memcg)
2396 u64 overage, max_overage = 0;
2399 overage = calculate_overage(page_counter_read(&memcg->swap),
2400 READ_ONCE(memcg->swap.high));
2402 memcg_memory_event(memcg, MEMCG_SWAP_HIGH);
2403 max_overage = max(overage, max_overage);
2404 } while ((memcg = parent_mem_cgroup(memcg)) &&
2405 !mem_cgroup_is_root(memcg));
2411 * Get the number of jiffies that we should penalise a mischievous cgroup which
2412 * is exceeding its memory.high by checking both it and its ancestors.
2414 static unsigned long calculate_high_delay(struct mem_cgroup *memcg,
2415 unsigned int nr_pages,
2418 unsigned long penalty_jiffies;
2424 * We use overage compared to memory.high to calculate the number of
2425 * jiffies to sleep (penalty_jiffies). Ideally this value should be
2426 * fairly lenient on small overages, and increasingly harsh when the
2427 * memcg in question makes it clear that it has no intention of stopping
2428 * its crazy behaviour, so we exponentially increase the delay based on
2431 penalty_jiffies = max_overage * max_overage * HZ;
2432 penalty_jiffies >>= MEMCG_DELAY_PRECISION_SHIFT;
2433 penalty_jiffies >>= MEMCG_DELAY_SCALING_SHIFT;
2436 * Factor in the task's own contribution to the overage, such that four
2437 * N-sized allocations are throttled approximately the same as one
2438 * 4N-sized allocation.
2440 * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or
2441 * larger the current charge patch is than that.
2443 return penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH;
2447 * Scheduled by try_charge() to be executed from the userland return path
2448 * and reclaims memory over the high limit.
2450 void mem_cgroup_handle_over_high(void)
2452 unsigned long penalty_jiffies;
2453 unsigned long pflags;
2454 unsigned long nr_reclaimed;
2455 unsigned int nr_pages = current->memcg_nr_pages_over_high;
2456 int nr_retries = MAX_RECLAIM_RETRIES;
2457 struct mem_cgroup *memcg;
2458 bool in_retry = false;
2460 if (likely(!nr_pages))
2463 memcg = get_mem_cgroup_from_mm(current->mm);
2464 current->memcg_nr_pages_over_high = 0;
2468 * The allocating task should reclaim at least the batch size, but for
2469 * subsequent retries we only want to do what's necessary to prevent oom
2470 * or breaching resource isolation.
2472 * This is distinct from memory.max or page allocator behaviour because
2473 * memory.high is currently batched, whereas memory.max and the page
2474 * allocator run every time an allocation is made.
2476 nr_reclaimed = reclaim_high(memcg,
2477 in_retry ? SWAP_CLUSTER_MAX : nr_pages,
2481 * memory.high is breached and reclaim is unable to keep up. Throttle
2482 * allocators proactively to slow down excessive growth.
2484 penalty_jiffies = calculate_high_delay(memcg, nr_pages,
2485 mem_find_max_overage(memcg));
2487 penalty_jiffies += calculate_high_delay(memcg, nr_pages,
2488 swap_find_max_overage(memcg));
2491 * Clamp the max delay per usermode return so as to still keep the
2492 * application moving forwards and also permit diagnostics, albeit
2495 penalty_jiffies = min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES);
2498 * Don't sleep if the amount of jiffies this memcg owes us is so low
2499 * that it's not even worth doing, in an attempt to be nice to those who
2500 * go only a small amount over their memory.high value and maybe haven't
2501 * been aggressively reclaimed enough yet.
2503 if (penalty_jiffies <= HZ / 100)
2507 * If reclaim is making forward progress but we're still over
2508 * memory.high, we want to encourage that rather than doing allocator
2511 if (nr_reclaimed || nr_retries--) {
2517 * If we exit early, we're guaranteed to die (since
2518 * schedule_timeout_killable sets TASK_KILLABLE). This means we don't
2519 * need to account for any ill-begotten jiffies to pay them off later.
2521 psi_memstall_enter(&pflags);
2522 schedule_timeout_killable(penalty_jiffies);
2523 psi_memstall_leave(&pflags);
2526 css_put(&memcg->css);
2529 static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask,
2530 unsigned int nr_pages)
2532 unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
2533 int nr_retries = MAX_RECLAIM_RETRIES;
2534 struct mem_cgroup *mem_over_limit;
2535 struct page_counter *counter;
2536 unsigned long nr_reclaimed;
2537 bool passed_oom = false;
2538 bool may_swap = true;
2539 bool drained = false;
2540 unsigned long pflags;
2543 if (consume_stock(memcg, nr_pages))
2546 if (!do_memsw_account() ||
2547 page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2548 if (page_counter_try_charge(&memcg->memory, batch, &counter))
2550 if (do_memsw_account())
2551 page_counter_uncharge(&memcg->memsw, batch);
2552 mem_over_limit = mem_cgroup_from_counter(counter, memory);
2554 mem_over_limit = mem_cgroup_from_counter(counter, memsw);
2558 if (batch > nr_pages) {
2564 * Prevent unbounded recursion when reclaim operations need to
2565 * allocate memory. This might exceed the limits temporarily,
2566 * but we prefer facilitating memory reclaim and getting back
2567 * under the limit over triggering OOM kills in these cases.
2569 if (unlikely(current->flags & PF_MEMALLOC))
2572 if (unlikely(task_in_memcg_oom(current)))
2575 if (!gfpflags_allow_blocking(gfp_mask))
2578 memcg_memory_event(mem_over_limit, MEMCG_MAX);
2580 psi_memstall_enter(&pflags);
2581 nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
2582 gfp_mask, may_swap);
2583 psi_memstall_leave(&pflags);
2585 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2589 drain_all_stock(mem_over_limit);
2594 if (gfp_mask & __GFP_NORETRY)
2597 * Even though the limit is exceeded at this point, reclaim
2598 * may have been able to free some pages. Retry the charge
2599 * before killing the task.
2601 * Only for regular pages, though: huge pages are rather
2602 * unlikely to succeed so close to the limit, and we fall back
2603 * to regular pages anyway in case of failure.
2605 if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
2608 * At task move, charge accounts can be doubly counted. So, it's
2609 * better to wait until the end of task_move if something is going on.
2611 if (mem_cgroup_wait_acct_move(mem_over_limit))
2617 if (gfp_mask & __GFP_RETRY_MAYFAIL)
2620 /* Avoid endless loop for tasks bypassed by the oom killer */
2621 if (passed_oom && task_is_dying())
2625 * keep retrying as long as the memcg oom killer is able to make
2626 * a forward progress or bypass the charge if the oom killer
2627 * couldn't make any progress.
2629 if (mem_cgroup_oom(mem_over_limit, gfp_mask,
2630 get_order(nr_pages * PAGE_SIZE))) {
2632 nr_retries = MAX_RECLAIM_RETRIES;
2637 * Memcg doesn't have a dedicated reserve for atomic
2638 * allocations. But like the global atomic pool, we need to
2639 * put the burden of reclaim on regular allocation requests
2640 * and let these go through as privileged allocations.
2642 if (!(gfp_mask & (__GFP_NOFAIL | __GFP_HIGH)))
2646 * The allocation either can't fail or will lead to more memory
2647 * being freed very soon. Allow memory usage go over the limit
2648 * temporarily by force charging it.
2650 page_counter_charge(&memcg->memory, nr_pages);
2651 if (do_memsw_account())
2652 page_counter_charge(&memcg->memsw, nr_pages);
2657 if (batch > nr_pages)
2658 refill_stock(memcg, batch - nr_pages);
2661 * If the hierarchy is above the normal consumption range, schedule
2662 * reclaim on returning to userland. We can perform reclaim here
2663 * if __GFP_RECLAIM but let's always punt for simplicity and so that
2664 * GFP_KERNEL can consistently be used during reclaim. @memcg is
2665 * not recorded as it most likely matches current's and won't
2666 * change in the meantime. As high limit is checked again before
2667 * reclaim, the cost of mismatch is negligible.
2670 bool mem_high, swap_high;
2672 mem_high = page_counter_read(&memcg->memory) >
2673 READ_ONCE(memcg->memory.high);
2674 swap_high = page_counter_read(&memcg->swap) >
2675 READ_ONCE(memcg->swap.high);
2677 /* Don't bother a random interrupted task */
2680 schedule_work(&memcg->high_work);
2686 if (mem_high || swap_high) {
2688 * The allocating tasks in this cgroup will need to do
2689 * reclaim or be throttled to prevent further growth
2690 * of the memory or swap footprints.
2692 * Target some best-effort fairness between the tasks,
2693 * and distribute reclaim work and delay penalties
2694 * based on how much each task is actually allocating.
2696 current->memcg_nr_pages_over_high += batch;
2697 set_notify_resume(current);
2700 } while ((memcg = parent_mem_cgroup(memcg)));
2702 if (current->memcg_nr_pages_over_high > MEMCG_CHARGE_BATCH &&
2703 !(current->flags & PF_MEMALLOC) &&
2704 gfpflags_allow_blocking(gfp_mask)) {
2705 mem_cgroup_handle_over_high();
2710 static inline int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2711 unsigned int nr_pages)
2713 if (mem_cgroup_is_root(memcg))
2716 return try_charge_memcg(memcg, gfp_mask, nr_pages);
2719 static inline void cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
2721 if (mem_cgroup_is_root(memcg))
2724 page_counter_uncharge(&memcg->memory, nr_pages);
2725 if (do_memsw_account())
2726 page_counter_uncharge(&memcg->memsw, nr_pages);
2729 static void commit_charge(struct folio *folio, struct mem_cgroup *memcg)
2731 VM_BUG_ON_FOLIO(folio_memcg(folio), folio);
2733 * Any of the following ensures page's memcg stability:
2737 * - lock_page_memcg()
2738 * - exclusive reference
2740 folio->memcg_data = (unsigned long)memcg;
2743 static struct mem_cgroup *get_mem_cgroup_from_objcg(struct obj_cgroup *objcg)
2745 struct mem_cgroup *memcg;
2749 memcg = obj_cgroup_memcg(objcg);
2750 if (unlikely(!css_tryget(&memcg->css)))
2757 #ifdef CONFIG_MEMCG_KMEM
2759 * The allocated objcg pointers array is not accounted directly.
2760 * Moreover, it should not come from DMA buffer and is not readily
2761 * reclaimable. So those GFP bits should be masked off.
2763 #define OBJCGS_CLEAR_MASK (__GFP_DMA | __GFP_RECLAIMABLE | __GFP_ACCOUNT)
2766 * mod_objcg_mlstate() may be called with irq enabled, so
2767 * mod_memcg_lruvec_state() should be used.
2769 static inline void mod_objcg_mlstate(struct obj_cgroup *objcg,
2770 struct pglist_data *pgdat,
2771 enum node_stat_item idx, int nr)
2773 struct mem_cgroup *memcg;
2774 struct lruvec *lruvec;
2777 memcg = obj_cgroup_memcg(objcg);
2778 lruvec = mem_cgroup_lruvec(memcg, pgdat);
2779 mod_memcg_lruvec_state(lruvec, idx, nr);
2783 int memcg_alloc_slab_cgroups(struct slab *slab, struct kmem_cache *s,
2784 gfp_t gfp, bool new_slab)
2786 unsigned int objects = objs_per_slab(s, slab);
2787 unsigned long memcg_data;
2790 gfp &= ~OBJCGS_CLEAR_MASK;
2791 vec = kcalloc_node(objects, sizeof(struct obj_cgroup *), gfp,
2796 memcg_data = (unsigned long) vec | MEMCG_DATA_OBJCGS;
2799 * If the slab is brand new and nobody can yet access its
2800 * memcg_data, no synchronization is required and memcg_data can
2801 * be simply assigned.
2803 slab->memcg_data = memcg_data;
2804 } else if (cmpxchg(&slab->memcg_data, 0, memcg_data)) {
2806 * If the slab is already in use, somebody can allocate and
2807 * assign obj_cgroups in parallel. In this case the existing
2808 * objcg vector should be reused.
2814 kmemleak_not_leak(vec);
2819 * Returns a pointer to the memory cgroup to which the kernel object is charged.
2821 * A passed kernel object can be a slab object or a generic kernel page, so
2822 * different mechanisms for getting the memory cgroup pointer should be used.
2823 * In certain cases (e.g. kernel stacks or large kmallocs with SLUB) the caller
2824 * can not know for sure how the kernel object is implemented.
2825 * mem_cgroup_from_obj() can be safely used in such cases.
2827 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
2828 * cgroup_mutex, etc.
2830 struct mem_cgroup *mem_cgroup_from_obj(void *p)
2832 struct folio *folio;
2834 if (mem_cgroup_disabled())
2837 folio = virt_to_folio(p);
2840 * Slab objects are accounted individually, not per-page.
2841 * Memcg membership data for each individual object is saved in
2844 if (folio_test_slab(folio)) {
2845 struct obj_cgroup **objcgs;
2849 slab = folio_slab(folio);
2850 objcgs = slab_objcgs(slab);
2854 off = obj_to_index(slab->slab_cache, slab, p);
2856 return obj_cgroup_memcg(objcgs[off]);
2862 * page_memcg_check() is used here, because in theory we can encounter
2863 * a folio where the slab flag has been cleared already, but
2864 * slab->memcg_data has not been freed yet
2865 * page_memcg_check(page) will guarantee that a proper memory
2866 * cgroup pointer or NULL will be returned.
2868 return page_memcg_check(folio_page(folio, 0));
2871 __always_inline struct obj_cgroup *get_obj_cgroup_from_current(void)
2873 struct obj_cgroup *objcg = NULL;
2874 struct mem_cgroup *memcg;
2876 if (memcg_kmem_bypass())
2880 if (unlikely(active_memcg()))
2881 memcg = active_memcg();
2883 memcg = mem_cgroup_from_task(current);
2885 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg)) {
2886 objcg = rcu_dereference(memcg->objcg);
2887 if (objcg && obj_cgroup_tryget(objcg))
2896 static int memcg_alloc_cache_id(void)
2901 id = ida_simple_get(&memcg_cache_ida,
2902 0, MEMCG_CACHES_MAX_SIZE, GFP_KERNEL);
2906 if (id < memcg_nr_cache_ids)
2910 * There's no space for the new id in memcg_caches arrays,
2911 * so we have to grow them.
2913 down_write(&memcg_cache_ids_sem);
2915 size = 2 * (id + 1);
2916 if (size < MEMCG_CACHES_MIN_SIZE)
2917 size = MEMCG_CACHES_MIN_SIZE;
2918 else if (size > MEMCG_CACHES_MAX_SIZE)
2919 size = MEMCG_CACHES_MAX_SIZE;
2921 err = memcg_update_all_list_lrus(size);
2923 memcg_nr_cache_ids = size;
2925 up_write(&memcg_cache_ids_sem);
2928 ida_simple_remove(&memcg_cache_ida, id);
2934 static void memcg_free_cache_id(int id)
2936 ida_simple_remove(&memcg_cache_ida, id);
2939 static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages)
2941 mod_memcg_state(memcg, MEMCG_KMEM, nr_pages);
2942 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
2944 page_counter_charge(&memcg->kmem, nr_pages);
2946 page_counter_uncharge(&memcg->kmem, -nr_pages);
2952 * obj_cgroup_uncharge_pages: uncharge a number of kernel pages from a objcg
2953 * @objcg: object cgroup to uncharge
2954 * @nr_pages: number of pages to uncharge
2956 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
2957 unsigned int nr_pages)
2959 struct mem_cgroup *memcg;
2961 memcg = get_mem_cgroup_from_objcg(objcg);
2963 memcg_account_kmem(memcg, -nr_pages);
2964 refill_stock(memcg, nr_pages);
2966 css_put(&memcg->css);
2970 * obj_cgroup_charge_pages: charge a number of kernel pages to a objcg
2971 * @objcg: object cgroup to charge
2972 * @gfp: reclaim mode
2973 * @nr_pages: number of pages to charge
2975 * Returns 0 on success, an error code on failure.
2977 static int obj_cgroup_charge_pages(struct obj_cgroup *objcg, gfp_t gfp,
2978 unsigned int nr_pages)
2980 struct mem_cgroup *memcg;
2983 memcg = get_mem_cgroup_from_objcg(objcg);
2985 ret = try_charge_memcg(memcg, gfp, nr_pages);
2989 memcg_account_kmem(memcg, nr_pages);
2991 css_put(&memcg->css);
2997 * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup
2998 * @page: page to charge
2999 * @gfp: reclaim mode
3000 * @order: allocation order
3002 * Returns 0 on success, an error code on failure.
3004 int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
3006 struct obj_cgroup *objcg;
3009 objcg = get_obj_cgroup_from_current();
3011 ret = obj_cgroup_charge_pages(objcg, gfp, 1 << order);
3013 page->memcg_data = (unsigned long)objcg |
3017 obj_cgroup_put(objcg);
3023 * __memcg_kmem_uncharge_page: uncharge a kmem page
3024 * @page: page to uncharge
3025 * @order: allocation order
3027 void __memcg_kmem_uncharge_page(struct page *page, int order)
3029 struct folio *folio = page_folio(page);
3030 struct obj_cgroup *objcg;
3031 unsigned int nr_pages = 1 << order;
3033 if (!folio_memcg_kmem(folio))
3036 objcg = __folio_objcg(folio);
3037 obj_cgroup_uncharge_pages(objcg, nr_pages);
3038 folio->memcg_data = 0;
3039 obj_cgroup_put(objcg);
3042 void mod_objcg_state(struct obj_cgroup *objcg, struct pglist_data *pgdat,
3043 enum node_stat_item idx, int nr)
3045 struct memcg_stock_pcp *stock;
3046 unsigned long flags;
3049 local_irq_save(flags);
3050 stock = this_cpu_ptr(&memcg_stock);
3053 * Save vmstat data in stock and skip vmstat array update unless
3054 * accumulating over a page of vmstat data or when pgdat or idx
3057 if (stock->cached_objcg != objcg) {
3058 drain_obj_stock(stock);
3059 obj_cgroup_get(objcg);
3060 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3061 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3062 stock->cached_objcg = objcg;
3063 stock->cached_pgdat = pgdat;
3064 } else if (stock->cached_pgdat != pgdat) {
3065 /* Flush the existing cached vmstat data */
3066 struct pglist_data *oldpg = stock->cached_pgdat;
3068 if (stock->nr_slab_reclaimable_b) {
3069 mod_objcg_mlstate(objcg, oldpg, NR_SLAB_RECLAIMABLE_B,
3070 stock->nr_slab_reclaimable_b);
3071 stock->nr_slab_reclaimable_b = 0;
3073 if (stock->nr_slab_unreclaimable_b) {
3074 mod_objcg_mlstate(objcg, oldpg, NR_SLAB_UNRECLAIMABLE_B,
3075 stock->nr_slab_unreclaimable_b);
3076 stock->nr_slab_unreclaimable_b = 0;
3078 stock->cached_pgdat = pgdat;
3081 bytes = (idx == NR_SLAB_RECLAIMABLE_B) ? &stock->nr_slab_reclaimable_b
3082 : &stock->nr_slab_unreclaimable_b;
3084 * Even for large object >= PAGE_SIZE, the vmstat data will still be
3085 * cached locally at least once before pushing it out.
3092 if (abs(*bytes) > PAGE_SIZE) {
3100 mod_objcg_mlstate(objcg, pgdat, idx, nr);
3102 local_irq_restore(flags);
3105 static bool consume_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes)
3107 struct memcg_stock_pcp *stock;
3108 unsigned long flags;
3111 local_irq_save(flags);
3113 stock = this_cpu_ptr(&memcg_stock);
3114 if (objcg == stock->cached_objcg && stock->nr_bytes >= nr_bytes) {
3115 stock->nr_bytes -= nr_bytes;
3119 local_irq_restore(flags);
3124 static void drain_obj_stock(struct memcg_stock_pcp *stock)
3126 struct obj_cgroup *old = stock->cached_objcg;
3131 if (stock->nr_bytes) {
3132 unsigned int nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3133 unsigned int nr_bytes = stock->nr_bytes & (PAGE_SIZE - 1);
3136 obj_cgroup_uncharge_pages(old, nr_pages);
3139 * The leftover is flushed to the centralized per-memcg value.
3140 * On the next attempt to refill obj stock it will be moved
3141 * to a per-cpu stock (probably, on an other CPU), see
3142 * refill_obj_stock().
3144 * How often it's flushed is a trade-off between the memory
3145 * limit enforcement accuracy and potential CPU contention,
3146 * so it might be changed in the future.
3148 atomic_add(nr_bytes, &old->nr_charged_bytes);
3149 stock->nr_bytes = 0;
3153 * Flush the vmstat data in current stock
3155 if (stock->nr_slab_reclaimable_b || stock->nr_slab_unreclaimable_b) {
3156 if (stock->nr_slab_reclaimable_b) {
3157 mod_objcg_mlstate(old, stock->cached_pgdat,
3158 NR_SLAB_RECLAIMABLE_B,
3159 stock->nr_slab_reclaimable_b);
3160 stock->nr_slab_reclaimable_b = 0;
3162 if (stock->nr_slab_unreclaimable_b) {
3163 mod_objcg_mlstate(old, stock->cached_pgdat,
3164 NR_SLAB_UNRECLAIMABLE_B,
3165 stock->nr_slab_unreclaimable_b);
3166 stock->nr_slab_unreclaimable_b = 0;
3168 stock->cached_pgdat = NULL;
3171 obj_cgroup_put(old);
3172 stock->cached_objcg = NULL;
3175 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
3176 struct mem_cgroup *root_memcg)
3178 struct mem_cgroup *memcg;
3180 if (stock->cached_objcg) {
3181 memcg = obj_cgroup_memcg(stock->cached_objcg);
3182 if (memcg && mem_cgroup_is_descendant(memcg, root_memcg))
3189 static void refill_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes,
3190 bool allow_uncharge)
3192 struct memcg_stock_pcp *stock;
3193 unsigned long flags;
3194 unsigned int nr_pages = 0;
3196 local_irq_save(flags);
3198 stock = this_cpu_ptr(&memcg_stock);
3199 if (stock->cached_objcg != objcg) { /* reset if necessary */
3200 drain_obj_stock(stock);
3201 obj_cgroup_get(objcg);
3202 stock->cached_objcg = objcg;
3203 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3204 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3205 allow_uncharge = true; /* Allow uncharge when objcg changes */
3207 stock->nr_bytes += nr_bytes;
3209 if (allow_uncharge && (stock->nr_bytes > PAGE_SIZE)) {
3210 nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3211 stock->nr_bytes &= (PAGE_SIZE - 1);
3214 local_irq_restore(flags);
3217 obj_cgroup_uncharge_pages(objcg, nr_pages);
3220 int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size)
3222 unsigned int nr_pages, nr_bytes;
3225 if (consume_obj_stock(objcg, size))
3229 * In theory, objcg->nr_charged_bytes can have enough
3230 * pre-charged bytes to satisfy the allocation. However,
3231 * flushing objcg->nr_charged_bytes requires two atomic
3232 * operations, and objcg->nr_charged_bytes can't be big.
3233 * The shared objcg->nr_charged_bytes can also become a
3234 * performance bottleneck if all tasks of the same memcg are
3235 * trying to update it. So it's better to ignore it and try
3236 * grab some new pages. The stock's nr_bytes will be flushed to
3237 * objcg->nr_charged_bytes later on when objcg changes.
3239 * The stock's nr_bytes may contain enough pre-charged bytes
3240 * to allow one less page from being charged, but we can't rely
3241 * on the pre-charged bytes not being changed outside of
3242 * consume_obj_stock() or refill_obj_stock(). So ignore those
3243 * pre-charged bytes as well when charging pages. To avoid a
3244 * page uncharge right after a page charge, we set the
3245 * allow_uncharge flag to false when calling refill_obj_stock()
3246 * to temporarily allow the pre-charged bytes to exceed the page
3247 * size limit. The maximum reachable value of the pre-charged
3248 * bytes is (sizeof(object) + PAGE_SIZE - 2) if there is no data
3251 nr_pages = size >> PAGE_SHIFT;
3252 nr_bytes = size & (PAGE_SIZE - 1);
3257 ret = obj_cgroup_charge_pages(objcg, gfp, nr_pages);
3258 if (!ret && nr_bytes)
3259 refill_obj_stock(objcg, PAGE_SIZE - nr_bytes, false);
3264 void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size)
3266 refill_obj_stock(objcg, size, true);
3269 #endif /* CONFIG_MEMCG_KMEM */
3272 * Because page_memcg(head) is not set on tails, set it now.
3274 void split_page_memcg(struct page *head, unsigned int nr)
3276 struct folio *folio = page_folio(head);
3277 struct mem_cgroup *memcg = folio_memcg(folio);
3280 if (mem_cgroup_disabled() || !memcg)
3283 for (i = 1; i < nr; i++)
3284 folio_page(folio, i)->memcg_data = folio->memcg_data;
3286 if (folio_memcg_kmem(folio))
3287 obj_cgroup_get_many(__folio_objcg(folio), nr - 1);
3289 css_get_many(&memcg->css, nr - 1);
3292 #ifdef CONFIG_MEMCG_SWAP
3294 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3295 * @entry: swap entry to be moved
3296 * @from: mem_cgroup which the entry is moved from
3297 * @to: mem_cgroup which the entry is moved to
3299 * It succeeds only when the swap_cgroup's record for this entry is the same
3300 * as the mem_cgroup's id of @from.
3302 * Returns 0 on success, -EINVAL on failure.
3304 * The caller must have charged to @to, IOW, called page_counter_charge() about
3305 * both res and memsw, and called css_get().
3307 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3308 struct mem_cgroup *from, struct mem_cgroup *to)
3310 unsigned short old_id, new_id;
3312 old_id = mem_cgroup_id(from);
3313 new_id = mem_cgroup_id(to);
3315 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3316 mod_memcg_state(from, MEMCG_SWAP, -1);
3317 mod_memcg_state(to, MEMCG_SWAP, 1);
3323 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3324 struct mem_cgroup *from, struct mem_cgroup *to)
3330 static DEFINE_MUTEX(memcg_max_mutex);
3332 static int mem_cgroup_resize_max(struct mem_cgroup *memcg,
3333 unsigned long max, bool memsw)
3335 bool enlarge = false;
3336 bool drained = false;
3338 bool limits_invariant;
3339 struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory;
3342 if (signal_pending(current)) {
3347 mutex_lock(&memcg_max_mutex);
3349 * Make sure that the new limit (memsw or memory limit) doesn't
3350 * break our basic invariant rule memory.max <= memsw.max.
3352 limits_invariant = memsw ? max >= READ_ONCE(memcg->memory.max) :
3353 max <= memcg->memsw.max;
3354 if (!limits_invariant) {
3355 mutex_unlock(&memcg_max_mutex);
3359 if (max > counter->max)
3361 ret = page_counter_set_max(counter, max);
3362 mutex_unlock(&memcg_max_mutex);
3368 drain_all_stock(memcg);
3373 if (!try_to_free_mem_cgroup_pages(memcg, 1,
3374 GFP_KERNEL, !memsw)) {
3380 if (!ret && enlarge)
3381 memcg_oom_recover(memcg);
3386 unsigned long mem_cgroup_soft_limit_reclaim(pg_data_t *pgdat, int order,
3388 unsigned long *total_scanned)
3390 unsigned long nr_reclaimed = 0;
3391 struct mem_cgroup_per_node *mz, *next_mz = NULL;
3392 unsigned long reclaimed;
3394 struct mem_cgroup_tree_per_node *mctz;
3395 unsigned long excess;
3396 unsigned long nr_scanned;
3401 mctz = soft_limit_tree.rb_tree_per_node[pgdat->node_id];
3404 * Do not even bother to check the largest node if the root
3405 * is empty. Do it lockless to prevent lock bouncing. Races
3406 * are acceptable as soft limit is best effort anyway.
3408 if (!mctz || RB_EMPTY_ROOT(&mctz->rb_root))
3412 * This loop can run a while, specially if mem_cgroup's continuously
3413 * keep exceeding their soft limit and putting the system under
3420 mz = mem_cgroup_largest_soft_limit_node(mctz);
3425 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, pgdat,
3426 gfp_mask, &nr_scanned);
3427 nr_reclaimed += reclaimed;
3428 *total_scanned += nr_scanned;
3429 spin_lock_irq(&mctz->lock);
3430 __mem_cgroup_remove_exceeded(mz, mctz);
3433 * If we failed to reclaim anything from this memory cgroup
3434 * it is time to move on to the next cgroup
3438 next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
3440 excess = soft_limit_excess(mz->memcg);
3442 * One school of thought says that we should not add
3443 * back the node to the tree if reclaim returns 0.
3444 * But our reclaim could return 0, simply because due
3445 * to priority we are exposing a smaller subset of
3446 * memory to reclaim from. Consider this as a longer
3449 /* If excess == 0, no tree ops */
3450 __mem_cgroup_insert_exceeded(mz, mctz, excess);
3451 spin_unlock_irq(&mctz->lock);
3452 css_put(&mz->memcg->css);
3455 * Could not reclaim anything and there are no more
3456 * mem cgroups to try or we seem to be looping without
3457 * reclaiming anything.
3459 if (!nr_reclaimed &&
3461 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3463 } while (!nr_reclaimed);
3465 css_put(&next_mz->memcg->css);
3466 return nr_reclaimed;
3470 * Reclaims as many pages from the given memcg as possible.
3472 * Caller is responsible for holding css reference for memcg.
3474 static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
3476 int nr_retries = MAX_RECLAIM_RETRIES;
3478 /* we call try-to-free pages for make this cgroup empty */
3479 lru_add_drain_all();
3481 drain_all_stock(memcg);
3483 /* try to free all pages in this cgroup */
3484 while (nr_retries && page_counter_read(&memcg->memory)) {
3485 if (signal_pending(current))
3488 if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL, true))
3495 static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
3496 char *buf, size_t nbytes,
3499 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3501 if (mem_cgroup_is_root(memcg))
3503 return mem_cgroup_force_empty(memcg) ?: nbytes;
3506 static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
3512 static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
3513 struct cftype *cft, u64 val)
3518 pr_warn_once("Non-hierarchical mode is deprecated. "
3519 "Please report your usecase to linux-mm@kvack.org if you "
3520 "depend on this functionality.\n");
3525 static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3529 if (mem_cgroup_is_root(memcg)) {
3530 mem_cgroup_flush_stats();
3531 val = memcg_page_state(memcg, NR_FILE_PAGES) +
3532 memcg_page_state(memcg, NR_ANON_MAPPED);
3534 val += memcg_page_state(memcg, MEMCG_SWAP);
3537 val = page_counter_read(&memcg->memory);
3539 val = page_counter_read(&memcg->memsw);
3552 static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
3555 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3556 struct page_counter *counter;
3558 switch (MEMFILE_TYPE(cft->private)) {
3560 counter = &memcg->memory;
3563 counter = &memcg->memsw;
3566 counter = &memcg->kmem;
3569 counter = &memcg->tcpmem;
3575 switch (MEMFILE_ATTR(cft->private)) {
3577 if (counter == &memcg->memory)
3578 return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
3579 if (counter == &memcg->memsw)
3580 return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
3581 return (u64)page_counter_read(counter) * PAGE_SIZE;
3583 return (u64)counter->max * PAGE_SIZE;
3585 return (u64)counter->watermark * PAGE_SIZE;
3587 return counter->failcnt;
3588 case RES_SOFT_LIMIT:
3589 return (u64)memcg->soft_limit * PAGE_SIZE;
3595 #ifdef CONFIG_MEMCG_KMEM
3596 static int memcg_online_kmem(struct mem_cgroup *memcg)
3598 struct obj_cgroup *objcg;
3601 if (cgroup_memory_nokmem)
3604 BUG_ON(memcg->kmemcg_id >= 0);
3606 memcg_id = memcg_alloc_cache_id();
3610 objcg = obj_cgroup_alloc();
3612 memcg_free_cache_id(memcg_id);
3615 objcg->memcg = memcg;
3616 rcu_assign_pointer(memcg->objcg, objcg);
3618 static_branch_enable(&memcg_kmem_enabled_key);
3620 memcg->kmemcg_id = memcg_id;
3625 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3627 struct mem_cgroup *parent;
3630 if (memcg->kmemcg_id == -1)
3633 parent = parent_mem_cgroup(memcg);
3635 parent = root_mem_cgroup;
3637 memcg_reparent_objcgs(memcg, parent);
3639 kmemcg_id = memcg->kmemcg_id;
3640 BUG_ON(kmemcg_id < 0);
3643 * After we have finished memcg_reparent_objcgs(), all list_lrus
3644 * corresponding to this cgroup are guaranteed to remain empty.
3645 * The ordering is imposed by list_lru_node->lock taken by
3646 * memcg_drain_all_list_lrus().
3648 memcg_drain_all_list_lrus(kmemcg_id, parent);
3650 memcg_free_cache_id(kmemcg_id);
3651 memcg->kmemcg_id = -1;
3654 static int memcg_online_kmem(struct mem_cgroup *memcg)
3658 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3661 #endif /* CONFIG_MEMCG_KMEM */
3663 static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max)
3667 mutex_lock(&memcg_max_mutex);
3669 ret = page_counter_set_max(&memcg->tcpmem, max);
3673 if (!memcg->tcpmem_active) {
3675 * The active flag needs to be written after the static_key
3676 * update. This is what guarantees that the socket activation
3677 * function is the last one to run. See mem_cgroup_sk_alloc()
3678 * for details, and note that we don't mark any socket as
3679 * belonging to this memcg until that flag is up.
3681 * We need to do this, because static_keys will span multiple
3682 * sites, but we can't control their order. If we mark a socket
3683 * as accounted, but the accounting functions are not patched in
3684 * yet, we'll lose accounting.
3686 * We never race with the readers in mem_cgroup_sk_alloc(),
3687 * because when this value change, the code to process it is not
3690 static_branch_inc(&memcg_sockets_enabled_key);
3691 memcg->tcpmem_active = true;
3694 mutex_unlock(&memcg_max_mutex);
3699 * The user of this function is...
3702 static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
3703 char *buf, size_t nbytes, loff_t off)
3705 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3706 unsigned long nr_pages;
3709 buf = strstrip(buf);
3710 ret = page_counter_memparse(buf, "-1", &nr_pages);
3714 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3716 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3720 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3722 ret = mem_cgroup_resize_max(memcg, nr_pages, false);
3725 ret = mem_cgroup_resize_max(memcg, nr_pages, true);
3728 /* kmem.limit_in_bytes is deprecated. */
3732 ret = memcg_update_tcp_max(memcg, nr_pages);
3736 case RES_SOFT_LIMIT:
3737 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
3740 memcg->soft_limit = nr_pages;
3745 return ret ?: nbytes;
3748 static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
3749 size_t nbytes, loff_t off)
3751 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3752 struct page_counter *counter;
3754 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3756 counter = &memcg->memory;
3759 counter = &memcg->memsw;
3762 counter = &memcg->kmem;
3765 counter = &memcg->tcpmem;
3771 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3773 page_counter_reset_watermark(counter);
3776 counter->failcnt = 0;
3785 static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
3788 return mem_cgroup_from_css(css)->move_charge_at_immigrate;
3792 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3793 struct cftype *cft, u64 val)
3795 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3797 if (val & ~MOVE_MASK)
3801 * No kind of locking is needed in here, because ->can_attach() will
3802 * check this value once in the beginning of the process, and then carry
3803 * on with stale data. This means that changes to this value will only
3804 * affect task migrations starting after the change.
3806 memcg->move_charge_at_immigrate = val;
3810 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3811 struct cftype *cft, u64 val)
3819 #define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE))
3820 #define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON))
3821 #define LRU_ALL ((1 << NR_LRU_LISTS) - 1)
3823 static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
3824 int nid, unsigned int lru_mask, bool tree)
3826 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
3827 unsigned long nr = 0;
3830 VM_BUG_ON((unsigned)nid >= nr_node_ids);
3833 if (!(BIT(lru) & lru_mask))
3836 nr += lruvec_page_state(lruvec, NR_LRU_BASE + lru);
3838 nr += lruvec_page_state_local(lruvec, NR_LRU_BASE + lru);
3843 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
3844 unsigned int lru_mask,
3847 unsigned long nr = 0;
3851 if (!(BIT(lru) & lru_mask))
3854 nr += memcg_page_state(memcg, NR_LRU_BASE + lru);
3856 nr += memcg_page_state_local(memcg, NR_LRU_BASE + lru);
3861 static int memcg_numa_stat_show(struct seq_file *m, void *v)
3865 unsigned int lru_mask;
3868 static const struct numa_stat stats[] = {
3869 { "total", LRU_ALL },
3870 { "file", LRU_ALL_FILE },
3871 { "anon", LRU_ALL_ANON },
3872 { "unevictable", BIT(LRU_UNEVICTABLE) },
3874 const struct numa_stat *stat;
3876 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
3878 mem_cgroup_flush_stats();
3880 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
3881 seq_printf(m, "%s=%lu", stat->name,
3882 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
3884 for_each_node_state(nid, N_MEMORY)
3885 seq_printf(m, " N%d=%lu", nid,
3886 mem_cgroup_node_nr_lru_pages(memcg, nid,
3887 stat->lru_mask, false));
3891 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
3893 seq_printf(m, "hierarchical_%s=%lu", stat->name,
3894 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
3896 for_each_node_state(nid, N_MEMORY)
3897 seq_printf(m, " N%d=%lu", nid,
3898 mem_cgroup_node_nr_lru_pages(memcg, nid,
3899 stat->lru_mask, true));
3905 #endif /* CONFIG_NUMA */
3907 static const unsigned int memcg1_stats[] = {
3910 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3920 static const char *const memcg1_stat_names[] = {
3923 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3933 /* Universal VM events cgroup1 shows, original sort order */
3934 static const unsigned int memcg1_events[] = {
3941 static int memcg_stat_show(struct seq_file *m, void *v)
3943 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
3944 unsigned long memory, memsw;
3945 struct mem_cgroup *mi;
3948 BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats));
3950 mem_cgroup_flush_stats();
3952 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
3955 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
3957 nr = memcg_page_state_local(memcg, memcg1_stats[i]);
3958 seq_printf(m, "%s %lu\n", memcg1_stat_names[i], nr * PAGE_SIZE);
3961 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
3962 seq_printf(m, "%s %lu\n", vm_event_name(memcg1_events[i]),
3963 memcg_events_local(memcg, memcg1_events[i]));
3965 for (i = 0; i < NR_LRU_LISTS; i++)
3966 seq_printf(m, "%s %lu\n", lru_list_name(i),
3967 memcg_page_state_local(memcg, NR_LRU_BASE + i) *
3970 /* Hierarchical information */
3971 memory = memsw = PAGE_COUNTER_MAX;
3972 for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
3973 memory = min(memory, READ_ONCE(mi->memory.max));
3974 memsw = min(memsw, READ_ONCE(mi->memsw.max));
3976 seq_printf(m, "hierarchical_memory_limit %llu\n",
3977 (u64)memory * PAGE_SIZE);
3978 if (do_memsw_account())
3979 seq_printf(m, "hierarchical_memsw_limit %llu\n",
3980 (u64)memsw * PAGE_SIZE);
3982 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
3985 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
3987 nr = memcg_page_state(memcg, memcg1_stats[i]);
3988 seq_printf(m, "total_%s %llu\n", memcg1_stat_names[i],
3989 (u64)nr * PAGE_SIZE);
3992 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
3993 seq_printf(m, "total_%s %llu\n",
3994 vm_event_name(memcg1_events[i]),
3995 (u64)memcg_events(memcg, memcg1_events[i]));
3997 for (i = 0; i < NR_LRU_LISTS; i++)
3998 seq_printf(m, "total_%s %llu\n", lru_list_name(i),
3999 (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
4002 #ifdef CONFIG_DEBUG_VM
4005 struct mem_cgroup_per_node *mz;
4006 unsigned long anon_cost = 0;
4007 unsigned long file_cost = 0;
4009 for_each_online_pgdat(pgdat) {
4010 mz = memcg->nodeinfo[pgdat->node_id];
4012 anon_cost += mz->lruvec.anon_cost;
4013 file_cost += mz->lruvec.file_cost;
4015 seq_printf(m, "anon_cost %lu\n", anon_cost);
4016 seq_printf(m, "file_cost %lu\n", file_cost);
4023 static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
4026 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4028 return mem_cgroup_swappiness(memcg);
4031 static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
4032 struct cftype *cft, u64 val)
4034 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4039 if (!mem_cgroup_is_root(memcg))
4040 memcg->swappiness = val;
4042 vm_swappiness = val;
4047 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4049 struct mem_cgroup_threshold_ary *t;
4050 unsigned long usage;
4055 t = rcu_dereference(memcg->thresholds.primary);
4057 t = rcu_dereference(memcg->memsw_thresholds.primary);
4062 usage = mem_cgroup_usage(memcg, swap);
4065 * current_threshold points to threshold just below or equal to usage.
4066 * If it's not true, a threshold was crossed after last
4067 * call of __mem_cgroup_threshold().
4069 i = t->current_threshold;
4072 * Iterate backward over array of thresholds starting from
4073 * current_threshold and check if a threshold is crossed.
4074 * If none of thresholds below usage is crossed, we read
4075 * only one element of the array here.
4077 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4078 eventfd_signal(t->entries[i].eventfd, 1);
4080 /* i = current_threshold + 1 */
4084 * Iterate forward over array of thresholds starting from
4085 * current_threshold+1 and check if a threshold is crossed.
4086 * If none of thresholds above usage is crossed, we read
4087 * only one element of the array here.
4089 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4090 eventfd_signal(t->entries[i].eventfd, 1);
4092 /* Update current_threshold */
4093 t->current_threshold = i - 1;
4098 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4101 __mem_cgroup_threshold(memcg, false);
4102 if (do_memsw_account())
4103 __mem_cgroup_threshold(memcg, true);
4105 memcg = parent_mem_cgroup(memcg);
4109 static int compare_thresholds(const void *a, const void *b)
4111 const struct mem_cgroup_threshold *_a = a;
4112 const struct mem_cgroup_threshold *_b = b;
4114 if (_a->threshold > _b->threshold)
4117 if (_a->threshold < _b->threshold)
4123 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
4125 struct mem_cgroup_eventfd_list *ev;
4127 spin_lock(&memcg_oom_lock);
4129 list_for_each_entry(ev, &memcg->oom_notify, list)
4130 eventfd_signal(ev->eventfd, 1);
4132 spin_unlock(&memcg_oom_lock);
4136 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
4138 struct mem_cgroup *iter;
4140 for_each_mem_cgroup_tree(iter, memcg)
4141 mem_cgroup_oom_notify_cb(iter);
4144 static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4145 struct eventfd_ctx *eventfd, const char *args, enum res_type type)
4147 struct mem_cgroup_thresholds *thresholds;
4148 struct mem_cgroup_threshold_ary *new;
4149 unsigned long threshold;
4150 unsigned long usage;
4153 ret = page_counter_memparse(args, "-1", &threshold);
4157 mutex_lock(&memcg->thresholds_lock);
4160 thresholds = &memcg->thresholds;
4161 usage = mem_cgroup_usage(memcg, false);
4162 } else if (type == _MEMSWAP) {
4163 thresholds = &memcg->memsw_thresholds;
4164 usage = mem_cgroup_usage(memcg, true);
4168 /* Check if a threshold crossed before adding a new one */
4169 if (thresholds->primary)
4170 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4172 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4174 /* Allocate memory for new array of thresholds */
4175 new = kmalloc(struct_size(new, entries, size), GFP_KERNEL);
4182 /* Copy thresholds (if any) to new array */
4183 if (thresholds->primary)
4184 memcpy(new->entries, thresholds->primary->entries,
4185 flex_array_size(new, entries, size - 1));
4187 /* Add new threshold */
4188 new->entries[size - 1].eventfd = eventfd;
4189 new->entries[size - 1].threshold = threshold;
4191 /* Sort thresholds. Registering of new threshold isn't time-critical */
4192 sort(new->entries, size, sizeof(*new->entries),
4193 compare_thresholds, NULL);
4195 /* Find current threshold */
4196 new->current_threshold = -1;
4197 for (i = 0; i < size; i++) {
4198 if (new->entries[i].threshold <= usage) {
4200 * new->current_threshold will not be used until
4201 * rcu_assign_pointer(), so it's safe to increment
4204 ++new->current_threshold;
4209 /* Free old spare buffer and save old primary buffer as spare */
4210 kfree(thresholds->spare);
4211 thresholds->spare = thresholds->primary;
4213 rcu_assign_pointer(thresholds->primary, new);
4215 /* To be sure that nobody uses thresholds */
4219 mutex_unlock(&memcg->thresholds_lock);
4224 static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4225 struct eventfd_ctx *eventfd, const char *args)
4227 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
4230 static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
4231 struct eventfd_ctx *eventfd, const char *args)
4233 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
4236 static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4237 struct eventfd_ctx *eventfd, enum res_type type)
4239 struct mem_cgroup_thresholds *thresholds;
4240 struct mem_cgroup_threshold_ary *new;
4241 unsigned long usage;
4242 int i, j, size, entries;
4244 mutex_lock(&memcg->thresholds_lock);
4247 thresholds = &memcg->thresholds;
4248 usage = mem_cgroup_usage(memcg, false);
4249 } else if (type == _MEMSWAP) {
4250 thresholds = &memcg->memsw_thresholds;
4251 usage = mem_cgroup_usage(memcg, true);
4255 if (!thresholds->primary)
4258 /* Check if a threshold crossed before removing */
4259 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4261 /* Calculate new number of threshold */
4263 for (i = 0; i < thresholds->primary->size; i++) {
4264 if (thresholds->primary->entries[i].eventfd != eventfd)
4270 new = thresholds->spare;
4272 /* If no items related to eventfd have been cleared, nothing to do */
4276 /* Set thresholds array to NULL if we don't have thresholds */
4285 /* Copy thresholds and find current threshold */
4286 new->current_threshold = -1;
4287 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4288 if (thresholds->primary->entries[i].eventfd == eventfd)
4291 new->entries[j] = thresholds->primary->entries[i];
4292 if (new->entries[j].threshold <= usage) {
4294 * new->current_threshold will not be used
4295 * until rcu_assign_pointer(), so it's safe to increment
4298 ++new->current_threshold;
4304 /* Swap primary and spare array */
4305 thresholds->spare = thresholds->primary;
4307 rcu_assign_pointer(thresholds->primary, new);
4309 /* To be sure that nobody uses thresholds */
4312 /* If all events are unregistered, free the spare array */
4314 kfree(thresholds->spare);
4315 thresholds->spare = NULL;
4318 mutex_unlock(&memcg->thresholds_lock);
4321 static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4322 struct eventfd_ctx *eventfd)
4324 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
4327 static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4328 struct eventfd_ctx *eventfd)
4330 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
4333 static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
4334 struct eventfd_ctx *eventfd, const char *args)
4336 struct mem_cgroup_eventfd_list *event;
4338 event = kmalloc(sizeof(*event), GFP_KERNEL);
4342 spin_lock(&memcg_oom_lock);
4344 event->eventfd = eventfd;
4345 list_add(&event->list, &memcg->oom_notify);
4347 /* already in OOM ? */
4348 if (memcg->under_oom)
4349 eventfd_signal(eventfd, 1);
4350 spin_unlock(&memcg_oom_lock);
4355 static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
4356 struct eventfd_ctx *eventfd)
4358 struct mem_cgroup_eventfd_list *ev, *tmp;
4360 spin_lock(&memcg_oom_lock);
4362 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
4363 if (ev->eventfd == eventfd) {
4364 list_del(&ev->list);
4369 spin_unlock(&memcg_oom_lock);
4372 static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
4374 struct mem_cgroup *memcg = mem_cgroup_from_seq(sf);
4376 seq_printf(sf, "oom_kill_disable %d\n", memcg->oom_kill_disable);
4377 seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
4378 seq_printf(sf, "oom_kill %lu\n",
4379 atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
4383 static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
4384 struct cftype *cft, u64 val)
4386 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4388 /* cannot set to root cgroup and only 0 and 1 are allowed */
4389 if (mem_cgroup_is_root(memcg) || !((val == 0) || (val == 1)))
4392 memcg->oom_kill_disable = val;
4394 memcg_oom_recover(memcg);
4399 #ifdef CONFIG_CGROUP_WRITEBACK
4401 #include <trace/events/writeback.h>
4403 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4405 return wb_domain_init(&memcg->cgwb_domain, gfp);
4408 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4410 wb_domain_exit(&memcg->cgwb_domain);
4413 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4415 wb_domain_size_changed(&memcg->cgwb_domain);
4418 struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
4420 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4422 if (!memcg->css.parent)
4425 return &memcg->cgwb_domain;
4429 * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
4430 * @wb: bdi_writeback in question
4431 * @pfilepages: out parameter for number of file pages
4432 * @pheadroom: out parameter for number of allocatable pages according to memcg
4433 * @pdirty: out parameter for number of dirty pages
4434 * @pwriteback: out parameter for number of pages under writeback
4436 * Determine the numbers of file, headroom, dirty, and writeback pages in
4437 * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom
4438 * is a bit more involved.
4440 * A memcg's headroom is "min(max, high) - used". In the hierarchy, the
4441 * headroom is calculated as the lowest headroom of itself and the
4442 * ancestors. Note that this doesn't consider the actual amount of
4443 * available memory in the system. The caller should further cap
4444 * *@pheadroom accordingly.
4446 void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
4447 unsigned long *pheadroom, unsigned long *pdirty,
4448 unsigned long *pwriteback)
4450 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4451 struct mem_cgroup *parent;
4453 mem_cgroup_flush_stats();
4455 *pdirty = memcg_page_state(memcg, NR_FILE_DIRTY);
4456 *pwriteback = memcg_page_state(memcg, NR_WRITEBACK);
4457 *pfilepages = memcg_page_state(memcg, NR_INACTIVE_FILE) +
4458 memcg_page_state(memcg, NR_ACTIVE_FILE);
4460 *pheadroom = PAGE_COUNTER_MAX;
4461 while ((parent = parent_mem_cgroup(memcg))) {
4462 unsigned long ceiling = min(READ_ONCE(memcg->memory.max),
4463 READ_ONCE(memcg->memory.high));
4464 unsigned long used = page_counter_read(&memcg->memory);
4466 *pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
4472 * Foreign dirty flushing
4474 * There's an inherent mismatch between memcg and writeback. The former
4475 * tracks ownership per-page while the latter per-inode. This was a
4476 * deliberate design decision because honoring per-page ownership in the
4477 * writeback path is complicated, may lead to higher CPU and IO overheads
4478 * and deemed unnecessary given that write-sharing an inode across
4479 * different cgroups isn't a common use-case.
4481 * Combined with inode majority-writer ownership switching, this works well
4482 * enough in most cases but there are some pathological cases. For
4483 * example, let's say there are two cgroups A and B which keep writing to
4484 * different but confined parts of the same inode. B owns the inode and
4485 * A's memory is limited far below B's. A's dirty ratio can rise enough to
4486 * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
4487 * triggering background writeback. A will be slowed down without a way to
4488 * make writeback of the dirty pages happen.
4490 * Conditions like the above can lead to a cgroup getting repeatedly and
4491 * severely throttled after making some progress after each
4492 * dirty_expire_interval while the underlying IO device is almost
4495 * Solving this problem completely requires matching the ownership tracking
4496 * granularities between memcg and writeback in either direction. However,
4497 * the more egregious behaviors can be avoided by simply remembering the
4498 * most recent foreign dirtying events and initiating remote flushes on
4499 * them when local writeback isn't enough to keep the memory clean enough.
4501 * The following two functions implement such mechanism. When a foreign
4502 * page - a page whose memcg and writeback ownerships don't match - is
4503 * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
4504 * bdi_writeback on the page owning memcg. When balance_dirty_pages()
4505 * decides that the memcg needs to sleep due to high dirty ratio, it calls
4506 * mem_cgroup_flush_foreign() which queues writeback on the recorded
4507 * foreign bdi_writebacks which haven't expired. Both the numbers of
4508 * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
4509 * limited to MEMCG_CGWB_FRN_CNT.
4511 * The mechanism only remembers IDs and doesn't hold any object references.
4512 * As being wrong occasionally doesn't matter, updates and accesses to the
4513 * records are lockless and racy.
4515 void mem_cgroup_track_foreign_dirty_slowpath(struct folio *folio,
4516 struct bdi_writeback *wb)
4518 struct mem_cgroup *memcg = folio_memcg(folio);
4519 struct memcg_cgwb_frn *frn;
4520 u64 now = get_jiffies_64();
4521 u64 oldest_at = now;
4525 trace_track_foreign_dirty(folio, wb);
4528 * Pick the slot to use. If there is already a slot for @wb, keep
4529 * using it. If not replace the oldest one which isn't being
4532 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4533 frn = &memcg->cgwb_frn[i];
4534 if (frn->bdi_id == wb->bdi->id &&
4535 frn->memcg_id == wb->memcg_css->id)
4537 if (time_before64(frn->at, oldest_at) &&
4538 atomic_read(&frn->done.cnt) == 1) {
4540 oldest_at = frn->at;
4544 if (i < MEMCG_CGWB_FRN_CNT) {
4546 * Re-using an existing one. Update timestamp lazily to
4547 * avoid making the cacheline hot. We want them to be
4548 * reasonably up-to-date and significantly shorter than
4549 * dirty_expire_interval as that's what expires the record.
4550 * Use the shorter of 1s and dirty_expire_interval / 8.
4552 unsigned long update_intv =
4553 min_t(unsigned long, HZ,
4554 msecs_to_jiffies(dirty_expire_interval * 10) / 8);
4556 if (time_before64(frn->at, now - update_intv))
4558 } else if (oldest >= 0) {
4559 /* replace the oldest free one */
4560 frn = &memcg->cgwb_frn[oldest];
4561 frn->bdi_id = wb->bdi->id;
4562 frn->memcg_id = wb->memcg_css->id;
4567 /* issue foreign writeback flushes for recorded foreign dirtying events */
4568 void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
4570 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4571 unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
4572 u64 now = jiffies_64;
4575 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4576 struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
4579 * If the record is older than dirty_expire_interval,
4580 * writeback on it has already started. No need to kick it
4581 * off again. Also, don't start a new one if there's
4582 * already one in flight.
4584 if (time_after64(frn->at, now - intv) &&
4585 atomic_read(&frn->done.cnt) == 1) {
4587 trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
4588 cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id,
4589 WB_REASON_FOREIGN_FLUSH,
4595 #else /* CONFIG_CGROUP_WRITEBACK */
4597 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4602 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4606 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4610 #endif /* CONFIG_CGROUP_WRITEBACK */
4613 * DO NOT USE IN NEW FILES.
4615 * "cgroup.event_control" implementation.
4617 * This is way over-engineered. It tries to support fully configurable
4618 * events for each user. Such level of flexibility is completely
4619 * unnecessary especially in the light of the planned unified hierarchy.
4621 * Please deprecate this and replace with something simpler if at all
4626 * Unregister event and free resources.
4628 * Gets called from workqueue.
4630 static void memcg_event_remove(struct work_struct *work)
4632 struct mem_cgroup_event *event =
4633 container_of(work, struct mem_cgroup_event, remove);
4634 struct mem_cgroup *memcg = event->memcg;
4636 remove_wait_queue(event->wqh, &event->wait);
4638 event->unregister_event(memcg, event->eventfd);
4640 /* Notify userspace the event is going away. */
4641 eventfd_signal(event->eventfd, 1);
4643 eventfd_ctx_put(event->eventfd);
4645 css_put(&memcg->css);
4649 * Gets called on EPOLLHUP on eventfd when user closes it.
4651 * Called with wqh->lock held and interrupts disabled.
4653 static int memcg_event_wake(wait_queue_entry_t *wait, unsigned mode,
4654 int sync, void *key)
4656 struct mem_cgroup_event *event =
4657 container_of(wait, struct mem_cgroup_event, wait);
4658 struct mem_cgroup *memcg = event->memcg;
4659 __poll_t flags = key_to_poll(key);
4661 if (flags & EPOLLHUP) {
4663 * If the event has been detached at cgroup removal, we
4664 * can simply return knowing the other side will cleanup
4667 * We can't race against event freeing since the other
4668 * side will require wqh->lock via remove_wait_queue(),
4671 spin_lock(&memcg->event_list_lock);
4672 if (!list_empty(&event->list)) {
4673 list_del_init(&event->list);
4675 * We are in atomic context, but cgroup_event_remove()
4676 * may sleep, so we have to call it in workqueue.
4678 schedule_work(&event->remove);
4680 spin_unlock(&memcg->event_list_lock);
4686 static void memcg_event_ptable_queue_proc(struct file *file,
4687 wait_queue_head_t *wqh, poll_table *pt)
4689 struct mem_cgroup_event *event =
4690 container_of(pt, struct mem_cgroup_event, pt);
4693 add_wait_queue(wqh, &event->wait);
4697 * DO NOT USE IN NEW FILES.
4699 * Parse input and register new cgroup event handler.
4701 * Input must be in format '<event_fd> <control_fd> <args>'.
4702 * Interpretation of args is defined by control file implementation.
4704 static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
4705 char *buf, size_t nbytes, loff_t off)
4707 struct cgroup_subsys_state *css = of_css(of);
4708 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4709 struct mem_cgroup_event *event;
4710 struct cgroup_subsys_state *cfile_css;
4711 unsigned int efd, cfd;
4718 if (IS_ENABLED(CONFIG_PREEMPT_RT))
4721 buf = strstrip(buf);
4723 efd = simple_strtoul(buf, &endp, 10);
4728 cfd = simple_strtoul(buf, &endp, 10);
4729 if ((*endp != ' ') && (*endp != '\0'))
4733 event = kzalloc(sizeof(*event), GFP_KERNEL);
4737 event->memcg = memcg;
4738 INIT_LIST_HEAD(&event->list);
4739 init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
4740 init_waitqueue_func_entry(&event->wait, memcg_event_wake);
4741 INIT_WORK(&event->remove, memcg_event_remove);
4749 event->eventfd = eventfd_ctx_fileget(efile.file);
4750 if (IS_ERR(event->eventfd)) {
4751 ret = PTR_ERR(event->eventfd);
4758 goto out_put_eventfd;
4761 /* the process need read permission on control file */
4762 /* AV: shouldn't we check that it's been opened for read instead? */
4763 ret = file_permission(cfile.file, MAY_READ);
4768 * Determine the event callbacks and set them in @event. This used
4769 * to be done via struct cftype but cgroup core no longer knows
4770 * about these events. The following is crude but the whole thing
4771 * is for compatibility anyway.
4773 * DO NOT ADD NEW FILES.
4775 name = cfile.file->f_path.dentry->d_name.name;
4777 if (!strcmp(name, "memory.usage_in_bytes")) {
4778 event->register_event = mem_cgroup_usage_register_event;
4779 event->unregister_event = mem_cgroup_usage_unregister_event;
4780 } else if (!strcmp(name, "memory.oom_control")) {
4781 event->register_event = mem_cgroup_oom_register_event;
4782 event->unregister_event = mem_cgroup_oom_unregister_event;
4783 } else if (!strcmp(name, "memory.pressure_level")) {
4784 event->register_event = vmpressure_register_event;
4785 event->unregister_event = vmpressure_unregister_event;
4786 } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
4787 event->register_event = memsw_cgroup_usage_register_event;
4788 event->unregister_event = memsw_cgroup_usage_unregister_event;
4795 * Verify @cfile should belong to @css. Also, remaining events are
4796 * automatically removed on cgroup destruction but the removal is
4797 * asynchronous, so take an extra ref on @css.
4799 cfile_css = css_tryget_online_from_dir(cfile.file->f_path.dentry->d_parent,
4800 &memory_cgrp_subsys);
4802 if (IS_ERR(cfile_css))
4804 if (cfile_css != css) {
4809 ret = event->register_event(memcg, event->eventfd, buf);
4813 vfs_poll(efile.file, &event->pt);
4815 spin_lock_irq(&memcg->event_list_lock);
4816 list_add(&event->list, &memcg->event_list);
4817 spin_unlock_irq(&memcg->event_list_lock);
4829 eventfd_ctx_put(event->eventfd);
4838 #if defined(CONFIG_MEMCG_KMEM) && (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG))
4839 static int mem_cgroup_slab_show(struct seq_file *m, void *p)
4843 * Please, take a look at tools/cgroup/slabinfo.py .
4849 static struct cftype mem_cgroup_legacy_files[] = {
4851 .name = "usage_in_bytes",
4852 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
4853 .read_u64 = mem_cgroup_read_u64,
4856 .name = "max_usage_in_bytes",
4857 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
4858 .write = mem_cgroup_reset,
4859 .read_u64 = mem_cgroup_read_u64,
4862 .name = "limit_in_bytes",
4863 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
4864 .write = mem_cgroup_write,
4865 .read_u64 = mem_cgroup_read_u64,
4868 .name = "soft_limit_in_bytes",
4869 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
4870 .write = mem_cgroup_write,
4871 .read_u64 = mem_cgroup_read_u64,
4875 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
4876 .write = mem_cgroup_reset,
4877 .read_u64 = mem_cgroup_read_u64,
4881 .seq_show = memcg_stat_show,
4884 .name = "force_empty",
4885 .write = mem_cgroup_force_empty_write,
4888 .name = "use_hierarchy",
4889 .write_u64 = mem_cgroup_hierarchy_write,
4890 .read_u64 = mem_cgroup_hierarchy_read,
4893 .name = "cgroup.event_control", /* XXX: for compat */
4894 .write = memcg_write_event_control,
4895 .flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE,
4898 .name = "swappiness",
4899 .read_u64 = mem_cgroup_swappiness_read,
4900 .write_u64 = mem_cgroup_swappiness_write,
4903 .name = "move_charge_at_immigrate",
4904 .read_u64 = mem_cgroup_move_charge_read,
4905 .write_u64 = mem_cgroup_move_charge_write,
4908 .name = "oom_control",
4909 .seq_show = mem_cgroup_oom_control_read,
4910 .write_u64 = mem_cgroup_oom_control_write,
4911 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
4914 .name = "pressure_level",
4918 .name = "numa_stat",
4919 .seq_show = memcg_numa_stat_show,
4923 .name = "kmem.limit_in_bytes",
4924 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
4925 .write = mem_cgroup_write,
4926 .read_u64 = mem_cgroup_read_u64,
4929 .name = "kmem.usage_in_bytes",
4930 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
4931 .read_u64 = mem_cgroup_read_u64,
4934 .name = "kmem.failcnt",
4935 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
4936 .write = mem_cgroup_reset,
4937 .read_u64 = mem_cgroup_read_u64,
4940 .name = "kmem.max_usage_in_bytes",
4941 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
4942 .write = mem_cgroup_reset,
4943 .read_u64 = mem_cgroup_read_u64,
4945 #if defined(CONFIG_MEMCG_KMEM) && \
4946 (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG))
4948 .name = "kmem.slabinfo",
4949 .seq_show = mem_cgroup_slab_show,
4953 .name = "kmem.tcp.limit_in_bytes",
4954 .private = MEMFILE_PRIVATE(_TCP, RES_LIMIT),
4955 .write = mem_cgroup_write,
4956 .read_u64 = mem_cgroup_read_u64,
4959 .name = "kmem.tcp.usage_in_bytes",
4960 .private = MEMFILE_PRIVATE(_TCP, RES_USAGE),
4961 .read_u64 = mem_cgroup_read_u64,
4964 .name = "kmem.tcp.failcnt",
4965 .private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT),
4966 .write = mem_cgroup_reset,
4967 .read_u64 = mem_cgroup_read_u64,
4970 .name = "kmem.tcp.max_usage_in_bytes",
4971 .private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE),
4972 .write = mem_cgroup_reset,
4973 .read_u64 = mem_cgroup_read_u64,
4975 { }, /* terminate */
4979 * Private memory cgroup IDR
4981 * Swap-out records and page cache shadow entries need to store memcg
4982 * references in constrained space, so we maintain an ID space that is
4983 * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
4984 * memory-controlled cgroups to 64k.
4986 * However, there usually are many references to the offline CSS after
4987 * the cgroup has been destroyed, such as page cache or reclaimable
4988 * slab objects, that don't need to hang on to the ID. We want to keep
4989 * those dead CSS from occupying IDs, or we might quickly exhaust the
4990 * relatively small ID space and prevent the creation of new cgroups
4991 * even when there are much fewer than 64k cgroups - possibly none.
4993 * Maintain a private 16-bit ID space for memcg, and allow the ID to
4994 * be freed and recycled when it's no longer needed, which is usually
4995 * when the CSS is offlined.
4997 * The only exception to that are records of swapped out tmpfs/shmem
4998 * pages that need to be attributed to live ancestors on swapin. But
4999 * those references are manageable from userspace.
5002 static DEFINE_IDR(mem_cgroup_idr);
5004 static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
5006 if (memcg->id.id > 0) {
5007 idr_remove(&mem_cgroup_idr, memcg->id.id);
5012 static void __maybe_unused mem_cgroup_id_get_many(struct mem_cgroup *memcg,
5015 refcount_add(n, &memcg->id.ref);
5018 static void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
5020 if (refcount_sub_and_test(n, &memcg->id.ref)) {
5021 mem_cgroup_id_remove(memcg);
5023 /* Memcg ID pins CSS */
5024 css_put(&memcg->css);
5028 static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
5030 mem_cgroup_id_put_many(memcg, 1);
5034 * mem_cgroup_from_id - look up a memcg from a memcg id
5035 * @id: the memcg id to look up
5037 * Caller must hold rcu_read_lock().
5039 struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
5041 WARN_ON_ONCE(!rcu_read_lock_held());
5042 return idr_find(&mem_cgroup_idr, id);
5045 static int alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5047 struct mem_cgroup_per_node *pn;
5050 * This routine is called against possible nodes.
5051 * But it's BUG to call kmalloc() against offline node.
5053 * TODO: this routine can waste much memory for nodes which will
5054 * never be onlined. It's better to use memory hotplug callback
5057 if (!node_state(node, N_NORMAL_MEMORY))
5059 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
5063 pn->lruvec_stats_percpu = alloc_percpu_gfp(struct lruvec_stats_percpu,
5064 GFP_KERNEL_ACCOUNT);
5065 if (!pn->lruvec_stats_percpu) {
5070 lruvec_init(&pn->lruvec);
5073 memcg->nodeinfo[node] = pn;
5077 static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5079 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
5084 free_percpu(pn->lruvec_stats_percpu);
5088 static void __mem_cgroup_free(struct mem_cgroup *memcg)
5093 free_mem_cgroup_per_node_info(memcg, node);
5094 free_percpu(memcg->vmstats_percpu);
5098 static void mem_cgroup_free(struct mem_cgroup *memcg)
5100 memcg_wb_domain_exit(memcg);
5101 __mem_cgroup_free(memcg);
5104 static struct mem_cgroup *mem_cgroup_alloc(void)
5106 struct mem_cgroup *memcg;
5108 int __maybe_unused i;
5109 long error = -ENOMEM;
5111 memcg = kzalloc(struct_size(memcg, nodeinfo, nr_node_ids), GFP_KERNEL);
5113 return ERR_PTR(error);
5115 memcg->id.id = idr_alloc(&mem_cgroup_idr, NULL,
5116 1, MEM_CGROUP_ID_MAX,
5118 if (memcg->id.id < 0) {
5119 error = memcg->id.id;
5123 memcg->vmstats_percpu = alloc_percpu_gfp(struct memcg_vmstats_percpu,
5124 GFP_KERNEL_ACCOUNT);
5125 if (!memcg->vmstats_percpu)
5129 if (alloc_mem_cgroup_per_node_info(memcg, node))
5132 if (memcg_wb_domain_init(memcg, GFP_KERNEL))
5135 INIT_WORK(&memcg->high_work, high_work_func);
5136 INIT_LIST_HEAD(&memcg->oom_notify);
5137 mutex_init(&memcg->thresholds_lock);
5138 spin_lock_init(&memcg->move_lock);
5139 vmpressure_init(&memcg->vmpressure);
5140 INIT_LIST_HEAD(&memcg->event_list);
5141 spin_lock_init(&memcg->event_list_lock);
5142 memcg->socket_pressure = jiffies;
5143 #ifdef CONFIG_MEMCG_KMEM
5144 memcg->kmemcg_id = -1;
5145 INIT_LIST_HEAD(&memcg->objcg_list);
5147 #ifdef CONFIG_CGROUP_WRITEBACK
5148 INIT_LIST_HEAD(&memcg->cgwb_list);
5149 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5150 memcg->cgwb_frn[i].done =
5151 __WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
5153 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5154 spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
5155 INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
5156 memcg->deferred_split_queue.split_queue_len = 0;
5158 idr_replace(&mem_cgroup_idr, memcg, memcg->id.id);
5161 mem_cgroup_id_remove(memcg);
5162 __mem_cgroup_free(memcg);
5163 return ERR_PTR(error);
5166 static struct cgroup_subsys_state * __ref
5167 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
5169 struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
5170 struct mem_cgroup *memcg, *old_memcg;
5171 long error = -ENOMEM;
5173 old_memcg = set_active_memcg(parent);
5174 memcg = mem_cgroup_alloc();
5175 set_active_memcg(old_memcg);
5177 return ERR_CAST(memcg);
5179 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5180 memcg->soft_limit = PAGE_COUNTER_MAX;
5181 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5183 memcg->swappiness = mem_cgroup_swappiness(parent);
5184 memcg->oom_kill_disable = parent->oom_kill_disable;
5186 page_counter_init(&memcg->memory, &parent->memory);
5187 page_counter_init(&memcg->swap, &parent->swap);
5188 page_counter_init(&memcg->kmem, &parent->kmem);
5189 page_counter_init(&memcg->tcpmem, &parent->tcpmem);
5191 page_counter_init(&memcg->memory, NULL);
5192 page_counter_init(&memcg->swap, NULL);
5193 page_counter_init(&memcg->kmem, NULL);
5194 page_counter_init(&memcg->tcpmem, NULL);
5196 root_mem_cgroup = memcg;
5200 /* The following stuff does not apply to the root */
5201 error = memcg_online_kmem(memcg);
5205 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5206 static_branch_inc(&memcg_sockets_enabled_key);
5210 mem_cgroup_id_remove(memcg);
5211 mem_cgroup_free(memcg);
5212 return ERR_PTR(error);
5215 static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
5217 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5220 * A memcg must be visible for expand_shrinker_info()
5221 * by the time the maps are allocated. So, we allocate maps
5222 * here, when for_each_mem_cgroup() can't skip it.
5224 if (alloc_shrinker_info(memcg)) {
5225 mem_cgroup_id_remove(memcg);
5229 /* Online state pins memcg ID, memcg ID pins CSS */
5230 refcount_set(&memcg->id.ref, 1);
5233 if (unlikely(mem_cgroup_is_root(memcg)))
5234 queue_delayed_work(system_unbound_wq, &stats_flush_dwork,
5239 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
5241 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5242 struct mem_cgroup_event *event, *tmp;
5245 * Unregister events and notify userspace.
5246 * Notify userspace about cgroup removing only after rmdir of cgroup
5247 * directory to avoid race between userspace and kernelspace.
5249 spin_lock_irq(&memcg->event_list_lock);
5250 list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
5251 list_del_init(&event->list);
5252 schedule_work(&event->remove);
5254 spin_unlock_irq(&memcg->event_list_lock);
5256 page_counter_set_min(&memcg->memory, 0);
5257 page_counter_set_low(&memcg->memory, 0);
5259 memcg_offline_kmem(memcg);
5260 reparent_shrinker_deferred(memcg);
5261 wb_memcg_offline(memcg);
5263 drain_all_stock(memcg);
5265 mem_cgroup_id_put(memcg);
5268 static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
5270 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5272 invalidate_reclaim_iterators(memcg);
5275 static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
5277 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5278 int __maybe_unused i;
5280 #ifdef CONFIG_CGROUP_WRITEBACK
5281 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5282 wb_wait_for_completion(&memcg->cgwb_frn[i].done);
5284 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5285 static_branch_dec(&memcg_sockets_enabled_key);
5287 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg->tcpmem_active)
5288 static_branch_dec(&memcg_sockets_enabled_key);
5290 vmpressure_cleanup(&memcg->vmpressure);
5291 cancel_work_sync(&memcg->high_work);
5292 mem_cgroup_remove_from_trees(memcg);
5293 free_shrinker_info(memcg);
5295 /* Need to offline kmem if online_css() fails */
5296 memcg_offline_kmem(memcg);
5297 mem_cgroup_free(memcg);
5301 * mem_cgroup_css_reset - reset the states of a mem_cgroup
5302 * @css: the target css
5304 * Reset the states of the mem_cgroup associated with @css. This is
5305 * invoked when the userland requests disabling on the default hierarchy
5306 * but the memcg is pinned through dependency. The memcg should stop
5307 * applying policies and should revert to the vanilla state as it may be
5308 * made visible again.
5310 * The current implementation only resets the essential configurations.
5311 * This needs to be expanded to cover all the visible parts.
5313 static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
5315 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5317 page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
5318 page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
5319 page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
5320 page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
5321 page_counter_set_min(&memcg->memory, 0);
5322 page_counter_set_low(&memcg->memory, 0);
5323 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5324 memcg->soft_limit = PAGE_COUNTER_MAX;
5325 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5326 memcg_wb_domain_size_changed(memcg);
5329 static void mem_cgroup_css_rstat_flush(struct cgroup_subsys_state *css, int cpu)
5331 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5332 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
5333 struct memcg_vmstats_percpu *statc;
5337 statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
5339 for (i = 0; i < MEMCG_NR_STAT; i++) {
5341 * Collect the aggregated propagation counts of groups
5342 * below us. We're in a per-cpu loop here and this is
5343 * a global counter, so the first cycle will get them.
5345 delta = memcg->vmstats.state_pending[i];
5347 memcg->vmstats.state_pending[i] = 0;
5349 /* Add CPU changes on this level since the last flush */
5350 v = READ_ONCE(statc->state[i]);
5351 if (v != statc->state_prev[i]) {
5352 delta += v - statc->state_prev[i];
5353 statc->state_prev[i] = v;
5359 /* Aggregate counts on this level and propagate upwards */
5360 memcg->vmstats.state[i] += delta;
5362 parent->vmstats.state_pending[i] += delta;
5365 for (i = 0; i < NR_VM_EVENT_ITEMS; i++) {
5366 delta = memcg->vmstats.events_pending[i];
5368 memcg->vmstats.events_pending[i] = 0;
5370 v = READ_ONCE(statc->events[i]);
5371 if (v != statc->events_prev[i]) {
5372 delta += v - statc->events_prev[i];
5373 statc->events_prev[i] = v;
5379 memcg->vmstats.events[i] += delta;
5381 parent->vmstats.events_pending[i] += delta;
5384 for_each_node_state(nid, N_MEMORY) {
5385 struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
5386 struct mem_cgroup_per_node *ppn = NULL;
5387 struct lruvec_stats_percpu *lstatc;
5390 ppn = parent->nodeinfo[nid];
5392 lstatc = per_cpu_ptr(pn->lruvec_stats_percpu, cpu);
5394 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++) {
5395 delta = pn->lruvec_stats.state_pending[i];
5397 pn->lruvec_stats.state_pending[i] = 0;
5399 v = READ_ONCE(lstatc->state[i]);
5400 if (v != lstatc->state_prev[i]) {
5401 delta += v - lstatc->state_prev[i];
5402 lstatc->state_prev[i] = v;
5408 pn->lruvec_stats.state[i] += delta;
5410 ppn->lruvec_stats.state_pending[i] += delta;
5416 /* Handlers for move charge at task migration. */
5417 static int mem_cgroup_do_precharge(unsigned long count)
5421 /* Try a single bulk charge without reclaim first, kswapd may wake */
5422 ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count);
5424 mc.precharge += count;
5428 /* Try charges one by one with reclaim, but do not retry */
5430 ret = try_charge(mc.to, GFP_KERNEL | __GFP_NORETRY, 1);
5444 enum mc_target_type {
5451 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5452 unsigned long addr, pte_t ptent)
5454 struct page *page = vm_normal_page(vma, addr, ptent);
5456 if (!page || !page_mapped(page))
5458 if (PageAnon(page)) {
5459 if (!(mc.flags & MOVE_ANON))
5462 if (!(mc.flags & MOVE_FILE))
5465 if (!get_page_unless_zero(page))
5471 #if defined(CONFIG_SWAP) || defined(CONFIG_DEVICE_PRIVATE)
5472 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5473 pte_t ptent, swp_entry_t *entry)
5475 struct page *page = NULL;
5476 swp_entry_t ent = pte_to_swp_entry(ptent);
5478 if (!(mc.flags & MOVE_ANON))
5482 * Handle MEMORY_DEVICE_PRIVATE which are ZONE_DEVICE page belonging to
5483 * a device and because they are not accessible by CPU they are store
5484 * as special swap entry in the CPU page table.
5486 if (is_device_private_entry(ent)) {
5487 page = pfn_swap_entry_to_page(ent);
5489 * MEMORY_DEVICE_PRIVATE means ZONE_DEVICE page and which have
5490 * a refcount of 1 when free (unlike normal page)
5492 if (!page_ref_add_unless(page, 1, 1))
5497 if (non_swap_entry(ent))
5501 * Because lookup_swap_cache() updates some statistics counter,
5502 * we call find_get_page() with swapper_space directly.
5504 page = find_get_page(swap_address_space(ent), swp_offset(ent));
5505 entry->val = ent.val;
5510 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5511 pte_t ptent, swp_entry_t *entry)
5517 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5518 unsigned long addr, pte_t ptent)
5520 if (!vma->vm_file) /* anonymous vma */
5522 if (!(mc.flags & MOVE_FILE))
5525 /* page is moved even if it's not RSS of this task(page-faulted). */
5526 /* shmem/tmpfs may report page out on swap: account for that too. */
5527 return find_get_incore_page(vma->vm_file->f_mapping,
5528 linear_page_index(vma, addr));
5532 * mem_cgroup_move_account - move account of the page
5534 * @compound: charge the page as compound or small page
5535 * @from: mem_cgroup which the page is moved from.
5536 * @to: mem_cgroup which the page is moved to. @from != @to.
5538 * The caller must make sure the page is not on LRU (isolate_page() is useful.)
5540 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
5543 static int mem_cgroup_move_account(struct page *page,
5545 struct mem_cgroup *from,
5546 struct mem_cgroup *to)
5548 struct folio *folio = page_folio(page);
5549 struct lruvec *from_vec, *to_vec;
5550 struct pglist_data *pgdat;
5551 unsigned int nr_pages = compound ? folio_nr_pages(folio) : 1;
5554 VM_BUG_ON(from == to);
5555 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
5556 VM_BUG_ON(compound && !folio_test_large(folio));
5559 * Prevent mem_cgroup_migrate() from looking at
5560 * page's memory cgroup of its source page while we change it.
5563 if (!folio_trylock(folio))
5567 if (folio_memcg(folio) != from)
5570 pgdat = folio_pgdat(folio);
5571 from_vec = mem_cgroup_lruvec(from, pgdat);
5572 to_vec = mem_cgroup_lruvec(to, pgdat);
5574 folio_memcg_lock(folio);
5576 if (folio_test_anon(folio)) {
5577 if (folio_mapped(folio)) {
5578 __mod_lruvec_state(from_vec, NR_ANON_MAPPED, -nr_pages);
5579 __mod_lruvec_state(to_vec, NR_ANON_MAPPED, nr_pages);
5580 if (folio_test_transhuge(folio)) {
5581 __mod_lruvec_state(from_vec, NR_ANON_THPS,
5583 __mod_lruvec_state(to_vec, NR_ANON_THPS,
5588 __mod_lruvec_state(from_vec, NR_FILE_PAGES, -nr_pages);
5589 __mod_lruvec_state(to_vec, NR_FILE_PAGES, nr_pages);
5591 if (folio_test_swapbacked(folio)) {
5592 __mod_lruvec_state(from_vec, NR_SHMEM, -nr_pages);
5593 __mod_lruvec_state(to_vec, NR_SHMEM, nr_pages);
5596 if (folio_mapped(folio)) {
5597 __mod_lruvec_state(from_vec, NR_FILE_MAPPED, -nr_pages);
5598 __mod_lruvec_state(to_vec, NR_FILE_MAPPED, nr_pages);
5601 if (folio_test_dirty(folio)) {
5602 struct address_space *mapping = folio_mapping(folio);
5604 if (mapping_can_writeback(mapping)) {
5605 __mod_lruvec_state(from_vec, NR_FILE_DIRTY,
5607 __mod_lruvec_state(to_vec, NR_FILE_DIRTY,
5613 if (folio_test_writeback(folio)) {
5614 __mod_lruvec_state(from_vec, NR_WRITEBACK, -nr_pages);
5615 __mod_lruvec_state(to_vec, NR_WRITEBACK, nr_pages);
5619 * All state has been migrated, let's switch to the new memcg.
5621 * It is safe to change page's memcg here because the page
5622 * is referenced, charged, isolated, and locked: we can't race
5623 * with (un)charging, migration, LRU putback, or anything else
5624 * that would rely on a stable page's memory cgroup.
5626 * Note that lock_page_memcg is a memcg lock, not a page lock,
5627 * to save space. As soon as we switch page's memory cgroup to a
5628 * new memcg that isn't locked, the above state can change
5629 * concurrently again. Make sure we're truly done with it.
5634 css_put(&from->css);
5636 folio->memcg_data = (unsigned long)to;
5638 __folio_memcg_unlock(from);
5641 nid = folio_nid(folio);
5643 local_irq_disable();
5644 mem_cgroup_charge_statistics(to, nr_pages);
5645 memcg_check_events(to, nid);
5646 mem_cgroup_charge_statistics(from, -nr_pages);
5647 memcg_check_events(from, nid);
5650 folio_unlock(folio);
5656 * get_mctgt_type - get target type of moving charge
5657 * @vma: the vma the pte to be checked belongs
5658 * @addr: the address corresponding to the pte to be checked
5659 * @ptent: the pte to be checked
5660 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5663 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5664 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5665 * move charge. if @target is not NULL, the page is stored in target->page
5666 * with extra refcnt got(Callers should handle it).
5667 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5668 * target for charge migration. if @target is not NULL, the entry is stored
5670 * 3(MC_TARGET_DEVICE): like MC_TARGET_PAGE but page is MEMORY_DEVICE_PRIVATE
5671 * (so ZONE_DEVICE page and thus not on the lru).
5672 * For now we such page is charge like a regular page would be as for all
5673 * intent and purposes it is just special memory taking the place of a
5676 * See Documentations/vm/hmm.txt and include/linux/hmm.h
5678 * Called with pte lock held.
5681 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
5682 unsigned long addr, pte_t ptent, union mc_target *target)
5684 struct page *page = NULL;
5685 enum mc_target_type ret = MC_TARGET_NONE;
5686 swp_entry_t ent = { .val = 0 };
5688 if (pte_present(ptent))
5689 page = mc_handle_present_pte(vma, addr, ptent);
5690 else if (is_swap_pte(ptent))
5691 page = mc_handle_swap_pte(vma, ptent, &ent);
5692 else if (pte_none(ptent))
5693 page = mc_handle_file_pte(vma, addr, ptent);
5695 if (!page && !ent.val)
5699 * Do only loose check w/o serialization.
5700 * mem_cgroup_move_account() checks the page is valid or
5701 * not under LRU exclusion.
5703 if (page_memcg(page) == mc.from) {
5704 ret = MC_TARGET_PAGE;
5705 if (is_device_private_page(page))
5706 ret = MC_TARGET_DEVICE;
5708 target->page = page;
5710 if (!ret || !target)
5714 * There is a swap entry and a page doesn't exist or isn't charged.
5715 * But we cannot move a tail-page in a THP.
5717 if (ent.val && !ret && (!page || !PageTransCompound(page)) &&
5718 mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
5719 ret = MC_TARGET_SWAP;
5726 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5728 * We don't consider PMD mapped swapping or file mapped pages because THP does
5729 * not support them for now.
5730 * Caller should make sure that pmd_trans_huge(pmd) is true.
5732 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5733 unsigned long addr, pmd_t pmd, union mc_target *target)
5735 struct page *page = NULL;
5736 enum mc_target_type ret = MC_TARGET_NONE;
5738 if (unlikely(is_swap_pmd(pmd))) {
5739 VM_BUG_ON(thp_migration_supported() &&
5740 !is_pmd_migration_entry(pmd));
5743 page = pmd_page(pmd);
5744 VM_BUG_ON_PAGE(!page || !PageHead(page), page);
5745 if (!(mc.flags & MOVE_ANON))
5747 if (page_memcg(page) == mc.from) {
5748 ret = MC_TARGET_PAGE;
5751 target->page = page;
5757 static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5758 unsigned long addr, pmd_t pmd, union mc_target *target)
5760 return MC_TARGET_NONE;
5764 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5765 unsigned long addr, unsigned long end,
5766 struct mm_walk *walk)
5768 struct vm_area_struct *vma = walk->vma;
5772 ptl = pmd_trans_huge_lock(pmd, vma);
5775 * Note their can not be MC_TARGET_DEVICE for now as we do not
5776 * support transparent huge page with MEMORY_DEVICE_PRIVATE but
5777 * this might change.
5779 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
5780 mc.precharge += HPAGE_PMD_NR;
5785 if (pmd_trans_unstable(pmd))
5787 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5788 for (; addr != end; pte++, addr += PAGE_SIZE)
5789 if (get_mctgt_type(vma, addr, *pte, NULL))
5790 mc.precharge++; /* increment precharge temporarily */
5791 pte_unmap_unlock(pte - 1, ptl);
5797 static const struct mm_walk_ops precharge_walk_ops = {
5798 .pmd_entry = mem_cgroup_count_precharge_pte_range,
5801 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5803 unsigned long precharge;
5806 walk_page_range(mm, 0, mm->highest_vm_end, &precharge_walk_ops, NULL);
5807 mmap_read_unlock(mm);
5809 precharge = mc.precharge;
5815 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5817 unsigned long precharge = mem_cgroup_count_precharge(mm);
5819 VM_BUG_ON(mc.moving_task);
5820 mc.moving_task = current;
5821 return mem_cgroup_do_precharge(precharge);
5824 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5825 static void __mem_cgroup_clear_mc(void)
5827 struct mem_cgroup *from = mc.from;
5828 struct mem_cgroup *to = mc.to;
5830 /* we must uncharge all the leftover precharges from mc.to */
5832 cancel_charge(mc.to, mc.precharge);
5836 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5837 * we must uncharge here.
5839 if (mc.moved_charge) {
5840 cancel_charge(mc.from, mc.moved_charge);
5841 mc.moved_charge = 0;
5843 /* we must fixup refcnts and charges */
5844 if (mc.moved_swap) {
5845 /* uncharge swap account from the old cgroup */
5846 if (!mem_cgroup_is_root(mc.from))
5847 page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
5849 mem_cgroup_id_put_many(mc.from, mc.moved_swap);
5852 * we charged both to->memory and to->memsw, so we
5853 * should uncharge to->memory.
5855 if (!mem_cgroup_is_root(mc.to))
5856 page_counter_uncharge(&mc.to->memory, mc.moved_swap);
5860 memcg_oom_recover(from);
5861 memcg_oom_recover(to);
5862 wake_up_all(&mc.waitq);
5865 static void mem_cgroup_clear_mc(void)
5867 struct mm_struct *mm = mc.mm;
5870 * we must clear moving_task before waking up waiters at the end of
5873 mc.moving_task = NULL;
5874 __mem_cgroup_clear_mc();
5875 spin_lock(&mc.lock);
5879 spin_unlock(&mc.lock);
5884 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
5886 struct cgroup_subsys_state *css;
5887 struct mem_cgroup *memcg = NULL; /* unneeded init to make gcc happy */
5888 struct mem_cgroup *from;
5889 struct task_struct *leader, *p;
5890 struct mm_struct *mm;
5891 unsigned long move_flags;
5894 /* charge immigration isn't supported on the default hierarchy */
5895 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
5899 * Multi-process migrations only happen on the default hierarchy
5900 * where charge immigration is not used. Perform charge
5901 * immigration if @tset contains a leader and whine if there are
5905 cgroup_taskset_for_each_leader(leader, css, tset) {
5908 memcg = mem_cgroup_from_css(css);
5914 * We are now committed to this value whatever it is. Changes in this
5915 * tunable will only affect upcoming migrations, not the current one.
5916 * So we need to save it, and keep it going.
5918 move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
5922 from = mem_cgroup_from_task(p);
5924 VM_BUG_ON(from == memcg);
5926 mm = get_task_mm(p);
5929 /* We move charges only when we move a owner of the mm */
5930 if (mm->owner == p) {
5933 VM_BUG_ON(mc.precharge);
5934 VM_BUG_ON(mc.moved_charge);
5935 VM_BUG_ON(mc.moved_swap);
5937 spin_lock(&mc.lock);
5941 mc.flags = move_flags;
5942 spin_unlock(&mc.lock);
5943 /* We set mc.moving_task later */
5945 ret = mem_cgroup_precharge_mc(mm);
5947 mem_cgroup_clear_mc();
5954 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
5957 mem_cgroup_clear_mc();
5960 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
5961 unsigned long addr, unsigned long end,
5962 struct mm_walk *walk)
5965 struct vm_area_struct *vma = walk->vma;
5968 enum mc_target_type target_type;
5969 union mc_target target;
5972 ptl = pmd_trans_huge_lock(pmd, vma);
5974 if (mc.precharge < HPAGE_PMD_NR) {
5978 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
5979 if (target_type == MC_TARGET_PAGE) {
5981 if (!isolate_lru_page(page)) {
5982 if (!mem_cgroup_move_account(page, true,
5984 mc.precharge -= HPAGE_PMD_NR;
5985 mc.moved_charge += HPAGE_PMD_NR;
5987 putback_lru_page(page);
5990 } else if (target_type == MC_TARGET_DEVICE) {
5992 if (!mem_cgroup_move_account(page, true,
5994 mc.precharge -= HPAGE_PMD_NR;
5995 mc.moved_charge += HPAGE_PMD_NR;
6003 if (pmd_trans_unstable(pmd))
6006 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6007 for (; addr != end; addr += PAGE_SIZE) {
6008 pte_t ptent = *(pte++);
6009 bool device = false;
6015 switch (get_mctgt_type(vma, addr, ptent, &target)) {
6016 case MC_TARGET_DEVICE:
6019 case MC_TARGET_PAGE:
6022 * We can have a part of the split pmd here. Moving it
6023 * can be done but it would be too convoluted so simply
6024 * ignore such a partial THP and keep it in original
6025 * memcg. There should be somebody mapping the head.
6027 if (PageTransCompound(page))
6029 if (!device && isolate_lru_page(page))
6031 if (!mem_cgroup_move_account(page, false,
6034 /* we uncharge from mc.from later. */
6038 putback_lru_page(page);
6039 put: /* get_mctgt_type() gets the page */
6042 case MC_TARGET_SWAP:
6044 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
6046 mem_cgroup_id_get_many(mc.to, 1);
6047 /* we fixup other refcnts and charges later. */
6055 pte_unmap_unlock(pte - 1, ptl);
6060 * We have consumed all precharges we got in can_attach().
6061 * We try charge one by one, but don't do any additional
6062 * charges to mc.to if we have failed in charge once in attach()
6065 ret = mem_cgroup_do_precharge(1);
6073 static const struct mm_walk_ops charge_walk_ops = {
6074 .pmd_entry = mem_cgroup_move_charge_pte_range,
6077 static void mem_cgroup_move_charge(void)
6079 lru_add_drain_all();
6081 * Signal lock_page_memcg() to take the memcg's move_lock
6082 * while we're moving its pages to another memcg. Then wait
6083 * for already started RCU-only updates to finish.
6085 atomic_inc(&mc.from->moving_account);
6088 if (unlikely(!mmap_read_trylock(mc.mm))) {
6090 * Someone who are holding the mmap_lock might be waiting in
6091 * waitq. So we cancel all extra charges, wake up all waiters,
6092 * and retry. Because we cancel precharges, we might not be able
6093 * to move enough charges, but moving charge is a best-effort
6094 * feature anyway, so it wouldn't be a big problem.
6096 __mem_cgroup_clear_mc();
6101 * When we have consumed all precharges and failed in doing
6102 * additional charge, the page walk just aborts.
6104 walk_page_range(mc.mm, 0, mc.mm->highest_vm_end, &charge_walk_ops,
6107 mmap_read_unlock(mc.mm);
6108 atomic_dec(&mc.from->moving_account);
6111 static void mem_cgroup_move_task(void)
6114 mem_cgroup_move_charge();
6115 mem_cgroup_clear_mc();
6118 #else /* !CONFIG_MMU */
6119 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
6123 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6126 static void mem_cgroup_move_task(void)
6131 static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
6133 if (value == PAGE_COUNTER_MAX)
6134 seq_puts(m, "max\n");
6136 seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
6141 static u64 memory_current_read(struct cgroup_subsys_state *css,
6144 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6146 return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
6149 static int memory_min_show(struct seq_file *m, void *v)
6151 return seq_puts_memcg_tunable(m,
6152 READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
6155 static ssize_t memory_min_write(struct kernfs_open_file *of,
6156 char *buf, size_t nbytes, loff_t off)
6158 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6162 buf = strstrip(buf);
6163 err = page_counter_memparse(buf, "max", &min);
6167 page_counter_set_min(&memcg->memory, min);
6172 static int memory_low_show(struct seq_file *m, void *v)
6174 return seq_puts_memcg_tunable(m,
6175 READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
6178 static ssize_t memory_low_write(struct kernfs_open_file *of,
6179 char *buf, size_t nbytes, loff_t off)
6181 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6185 buf = strstrip(buf);
6186 err = page_counter_memparse(buf, "max", &low);
6190 page_counter_set_low(&memcg->memory, low);
6195 static int memory_high_show(struct seq_file *m, void *v)
6197 return seq_puts_memcg_tunable(m,
6198 READ_ONCE(mem_cgroup_from_seq(m)->memory.high));
6201 static ssize_t memory_high_write(struct kernfs_open_file *of,
6202 char *buf, size_t nbytes, loff_t off)
6204 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6205 unsigned int nr_retries = MAX_RECLAIM_RETRIES;
6206 bool drained = false;
6210 buf = strstrip(buf);
6211 err = page_counter_memparse(buf, "max", &high);
6215 page_counter_set_high(&memcg->memory, high);
6218 unsigned long nr_pages = page_counter_read(&memcg->memory);
6219 unsigned long reclaimed;
6221 if (nr_pages <= high)
6224 if (signal_pending(current))
6228 drain_all_stock(memcg);
6233 reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
6236 if (!reclaimed && !nr_retries--)
6240 memcg_wb_domain_size_changed(memcg);
6244 static int memory_max_show(struct seq_file *m, void *v)
6246 return seq_puts_memcg_tunable(m,
6247 READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
6250 static ssize_t memory_max_write(struct kernfs_open_file *of,
6251 char *buf, size_t nbytes, loff_t off)
6253 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6254 unsigned int nr_reclaims = MAX_RECLAIM_RETRIES;
6255 bool drained = false;
6259 buf = strstrip(buf);
6260 err = page_counter_memparse(buf, "max", &max);
6264 xchg(&memcg->memory.max, max);
6267 unsigned long nr_pages = page_counter_read(&memcg->memory);
6269 if (nr_pages <= max)
6272 if (signal_pending(current))
6276 drain_all_stock(memcg);
6282 if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
6288 memcg_memory_event(memcg, MEMCG_OOM);
6289 if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
6293 memcg_wb_domain_size_changed(memcg);
6297 static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
6299 seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
6300 seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
6301 seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
6302 seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
6303 seq_printf(m, "oom_kill %lu\n",
6304 atomic_long_read(&events[MEMCG_OOM_KILL]));
6305 seq_printf(m, "oom_group_kill %lu\n",
6306 atomic_long_read(&events[MEMCG_OOM_GROUP_KILL]));
6309 static int memory_events_show(struct seq_file *m, void *v)
6311 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6313 __memory_events_show(m, memcg->memory_events);
6317 static int memory_events_local_show(struct seq_file *m, void *v)
6319 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6321 __memory_events_show(m, memcg->memory_events_local);
6325 static int memory_stat_show(struct seq_file *m, void *v)
6327 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6330 buf = memory_stat_format(memcg);
6339 static inline unsigned long lruvec_page_state_output(struct lruvec *lruvec,
6342 return lruvec_page_state(lruvec, item) * memcg_page_state_unit(item);
6345 static int memory_numa_stat_show(struct seq_file *m, void *v)
6348 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6350 mem_cgroup_flush_stats();
6352 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
6355 if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS)
6358 seq_printf(m, "%s", memory_stats[i].name);
6359 for_each_node_state(nid, N_MEMORY) {
6361 struct lruvec *lruvec;
6363 lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
6364 size = lruvec_page_state_output(lruvec,
6365 memory_stats[i].idx);
6366 seq_printf(m, " N%d=%llu", nid, size);
6375 static int memory_oom_group_show(struct seq_file *m, void *v)
6377 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6379 seq_printf(m, "%d\n", memcg->oom_group);
6384 static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
6385 char *buf, size_t nbytes, loff_t off)
6387 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6390 buf = strstrip(buf);
6394 ret = kstrtoint(buf, 0, &oom_group);
6398 if (oom_group != 0 && oom_group != 1)
6401 memcg->oom_group = oom_group;
6406 static struct cftype memory_files[] = {
6409 .flags = CFTYPE_NOT_ON_ROOT,
6410 .read_u64 = memory_current_read,
6414 .flags = CFTYPE_NOT_ON_ROOT,
6415 .seq_show = memory_min_show,
6416 .write = memory_min_write,
6420 .flags = CFTYPE_NOT_ON_ROOT,
6421 .seq_show = memory_low_show,
6422 .write = memory_low_write,
6426 .flags = CFTYPE_NOT_ON_ROOT,
6427 .seq_show = memory_high_show,
6428 .write = memory_high_write,
6432 .flags = CFTYPE_NOT_ON_ROOT,
6433 .seq_show = memory_max_show,
6434 .write = memory_max_write,
6438 .flags = CFTYPE_NOT_ON_ROOT,
6439 .file_offset = offsetof(struct mem_cgroup, events_file),
6440 .seq_show = memory_events_show,
6443 .name = "events.local",
6444 .flags = CFTYPE_NOT_ON_ROOT,
6445 .file_offset = offsetof(struct mem_cgroup, events_local_file),
6446 .seq_show = memory_events_local_show,
6450 .seq_show = memory_stat_show,
6454 .name = "numa_stat",
6455 .seq_show = memory_numa_stat_show,
6459 .name = "oom.group",
6460 .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
6461 .seq_show = memory_oom_group_show,
6462 .write = memory_oom_group_write,
6467 struct cgroup_subsys memory_cgrp_subsys = {
6468 .css_alloc = mem_cgroup_css_alloc,
6469 .css_online = mem_cgroup_css_online,
6470 .css_offline = mem_cgroup_css_offline,
6471 .css_released = mem_cgroup_css_released,
6472 .css_free = mem_cgroup_css_free,
6473 .css_reset = mem_cgroup_css_reset,
6474 .css_rstat_flush = mem_cgroup_css_rstat_flush,
6475 .can_attach = mem_cgroup_can_attach,
6476 .cancel_attach = mem_cgroup_cancel_attach,
6477 .post_attach = mem_cgroup_move_task,
6478 .dfl_cftypes = memory_files,
6479 .legacy_cftypes = mem_cgroup_legacy_files,
6484 * This function calculates an individual cgroup's effective
6485 * protection which is derived from its own memory.min/low, its
6486 * parent's and siblings' settings, as well as the actual memory
6487 * distribution in the tree.
6489 * The following rules apply to the effective protection values:
6491 * 1. At the first level of reclaim, effective protection is equal to
6492 * the declared protection in memory.min and memory.low.
6494 * 2. To enable safe delegation of the protection configuration, at
6495 * subsequent levels the effective protection is capped to the
6496 * parent's effective protection.
6498 * 3. To make complex and dynamic subtrees easier to configure, the
6499 * user is allowed to overcommit the declared protection at a given
6500 * level. If that is the case, the parent's effective protection is
6501 * distributed to the children in proportion to how much protection
6502 * they have declared and how much of it they are utilizing.
6504 * This makes distribution proportional, but also work-conserving:
6505 * if one cgroup claims much more protection than it uses memory,
6506 * the unused remainder is available to its siblings.
6508 * 4. Conversely, when the declared protection is undercommitted at a
6509 * given level, the distribution of the larger parental protection
6510 * budget is NOT proportional. A cgroup's protection from a sibling
6511 * is capped to its own memory.min/low setting.
6513 * 5. However, to allow protecting recursive subtrees from each other
6514 * without having to declare each individual cgroup's fixed share
6515 * of the ancestor's claim to protection, any unutilized -
6516 * "floating" - protection from up the tree is distributed in
6517 * proportion to each cgroup's *usage*. This makes the protection
6518 * neutral wrt sibling cgroups and lets them compete freely over
6519 * the shared parental protection budget, but it protects the
6520 * subtree as a whole from neighboring subtrees.
6522 * Note that 4. and 5. are not in conflict: 4. is about protecting
6523 * against immediate siblings whereas 5. is about protecting against
6524 * neighboring subtrees.
6526 static unsigned long effective_protection(unsigned long usage,
6527 unsigned long parent_usage,
6528 unsigned long setting,
6529 unsigned long parent_effective,
6530 unsigned long siblings_protected)
6532 unsigned long protected;
6535 protected = min(usage, setting);
6537 * If all cgroups at this level combined claim and use more
6538 * protection then what the parent affords them, distribute
6539 * shares in proportion to utilization.
6541 * We are using actual utilization rather than the statically
6542 * claimed protection in order to be work-conserving: claimed
6543 * but unused protection is available to siblings that would
6544 * otherwise get a smaller chunk than what they claimed.
6546 if (siblings_protected > parent_effective)
6547 return protected * parent_effective / siblings_protected;
6550 * Ok, utilized protection of all children is within what the
6551 * parent affords them, so we know whatever this child claims
6552 * and utilizes is effectively protected.
6554 * If there is unprotected usage beyond this value, reclaim
6555 * will apply pressure in proportion to that amount.
6557 * If there is unutilized protection, the cgroup will be fully
6558 * shielded from reclaim, but we do return a smaller value for
6559 * protection than what the group could enjoy in theory. This
6560 * is okay. With the overcommit distribution above, effective
6561 * protection is always dependent on how memory is actually
6562 * consumed among the siblings anyway.
6567 * If the children aren't claiming (all of) the protection
6568 * afforded to them by the parent, distribute the remainder in
6569 * proportion to the (unprotected) memory of each cgroup. That
6570 * way, cgroups that aren't explicitly prioritized wrt each
6571 * other compete freely over the allowance, but they are
6572 * collectively protected from neighboring trees.
6574 * We're using unprotected memory for the weight so that if
6575 * some cgroups DO claim explicit protection, we don't protect
6576 * the same bytes twice.
6578 * Check both usage and parent_usage against the respective
6579 * protected values. One should imply the other, but they
6580 * aren't read atomically - make sure the division is sane.
6582 if (!(cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT))
6584 if (parent_effective > siblings_protected &&
6585 parent_usage > siblings_protected &&
6586 usage > protected) {
6587 unsigned long unclaimed;
6589 unclaimed = parent_effective - siblings_protected;
6590 unclaimed *= usage - protected;
6591 unclaimed /= parent_usage - siblings_protected;
6600 * mem_cgroup_calculate_protection - check if memory consumption is in the normal range
6601 * @root: the top ancestor of the sub-tree being checked
6602 * @memcg: the memory cgroup to check
6604 * WARNING: This function is not stateless! It can only be used as part
6605 * of a top-down tree iteration, not for isolated queries.
6607 void mem_cgroup_calculate_protection(struct mem_cgroup *root,
6608 struct mem_cgroup *memcg)
6610 unsigned long usage, parent_usage;
6611 struct mem_cgroup *parent;
6613 if (mem_cgroup_disabled())
6617 root = root_mem_cgroup;
6620 * Effective values of the reclaim targets are ignored so they
6621 * can be stale. Have a look at mem_cgroup_protection for more
6623 * TODO: calculation should be more robust so that we do not need
6624 * that special casing.
6629 usage = page_counter_read(&memcg->memory);
6633 parent = parent_mem_cgroup(memcg);
6634 /* No parent means a non-hierarchical mode on v1 memcg */
6638 if (parent == root) {
6639 memcg->memory.emin = READ_ONCE(memcg->memory.min);
6640 memcg->memory.elow = READ_ONCE(memcg->memory.low);
6644 parent_usage = page_counter_read(&parent->memory);
6646 WRITE_ONCE(memcg->memory.emin, effective_protection(usage, parent_usage,
6647 READ_ONCE(memcg->memory.min),
6648 READ_ONCE(parent->memory.emin),
6649 atomic_long_read(&parent->memory.children_min_usage)));
6651 WRITE_ONCE(memcg->memory.elow, effective_protection(usage, parent_usage,
6652 READ_ONCE(memcg->memory.low),
6653 READ_ONCE(parent->memory.elow),
6654 atomic_long_read(&parent->memory.children_low_usage)));
6657 static int charge_memcg(struct folio *folio, struct mem_cgroup *memcg,
6660 long nr_pages = folio_nr_pages(folio);
6663 ret = try_charge(memcg, gfp, nr_pages);
6667 css_get(&memcg->css);
6668 commit_charge(folio, memcg);
6670 local_irq_disable();
6671 mem_cgroup_charge_statistics(memcg, nr_pages);
6672 memcg_check_events(memcg, folio_nid(folio));
6678 int __mem_cgroup_charge(struct folio *folio, struct mm_struct *mm, gfp_t gfp)
6680 struct mem_cgroup *memcg;
6683 memcg = get_mem_cgroup_from_mm(mm);
6684 ret = charge_memcg(folio, memcg, gfp);
6685 css_put(&memcg->css);
6691 * mem_cgroup_swapin_charge_page - charge a newly allocated page for swapin
6692 * @page: page to charge
6693 * @mm: mm context of the victim
6694 * @gfp: reclaim mode
6695 * @entry: swap entry for which the page is allocated
6697 * This function charges a page allocated for swapin. Please call this before
6698 * adding the page to the swapcache.
6700 * Returns 0 on success. Otherwise, an error code is returned.
6702 int mem_cgroup_swapin_charge_page(struct page *page, struct mm_struct *mm,
6703 gfp_t gfp, swp_entry_t entry)
6705 struct folio *folio = page_folio(page);
6706 struct mem_cgroup *memcg;
6710 if (mem_cgroup_disabled())
6713 id = lookup_swap_cgroup_id(entry);
6715 memcg = mem_cgroup_from_id(id);
6716 if (!memcg || !css_tryget_online(&memcg->css))
6717 memcg = get_mem_cgroup_from_mm(mm);
6720 ret = charge_memcg(folio, memcg, gfp);
6722 css_put(&memcg->css);
6727 * mem_cgroup_swapin_uncharge_swap - uncharge swap slot
6728 * @entry: swap entry for which the page is charged
6730 * Call this function after successfully adding the charged page to swapcache.
6732 * Note: This function assumes the page for which swap slot is being uncharged
6735 void mem_cgroup_swapin_uncharge_swap(swp_entry_t entry)
6738 * Cgroup1's unified memory+swap counter has been charged with the
6739 * new swapcache page, finish the transfer by uncharging the swap
6740 * slot. The swap slot would also get uncharged when it dies, but
6741 * it can stick around indefinitely and we'd count the page twice
6744 * Cgroup2 has separate resource counters for memory and swap,
6745 * so this is a non-issue here. Memory and swap charge lifetimes
6746 * correspond 1:1 to page and swap slot lifetimes: we charge the
6747 * page to memory here, and uncharge swap when the slot is freed.
6749 if (!mem_cgroup_disabled() && do_memsw_account()) {
6751 * The swap entry might not get freed for a long time,
6752 * let's not wait for it. The page already received a
6753 * memory+swap charge, drop the swap entry duplicate.
6755 mem_cgroup_uncharge_swap(entry, 1);
6759 struct uncharge_gather {
6760 struct mem_cgroup *memcg;
6761 unsigned long nr_memory;
6762 unsigned long pgpgout;
6763 unsigned long nr_kmem;
6767 static inline void uncharge_gather_clear(struct uncharge_gather *ug)
6769 memset(ug, 0, sizeof(*ug));
6772 static void uncharge_batch(const struct uncharge_gather *ug)
6774 unsigned long flags;
6776 if (ug->nr_memory) {
6777 page_counter_uncharge(&ug->memcg->memory, ug->nr_memory);
6778 if (do_memsw_account())
6779 page_counter_uncharge(&ug->memcg->memsw, ug->nr_memory);
6781 memcg_account_kmem(ug->memcg, -ug->nr_kmem);
6782 memcg_oom_recover(ug->memcg);
6785 local_irq_save(flags);
6786 __count_memcg_events(ug->memcg, PGPGOUT, ug->pgpgout);
6787 __this_cpu_add(ug->memcg->vmstats_percpu->nr_page_events, ug->nr_memory);
6788 memcg_check_events(ug->memcg, ug->nid);
6789 local_irq_restore(flags);
6791 /* drop reference from uncharge_folio */
6792 css_put(&ug->memcg->css);
6795 static void uncharge_folio(struct folio *folio, struct uncharge_gather *ug)
6798 struct mem_cgroup *memcg;
6799 struct obj_cgroup *objcg;
6801 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
6804 * Nobody should be changing or seriously looking at
6805 * folio memcg or objcg at this point, we have fully
6806 * exclusive access to the folio.
6808 if (folio_memcg_kmem(folio)) {
6809 objcg = __folio_objcg(folio);
6811 * This get matches the put at the end of the function and
6812 * kmem pages do not hold memcg references anymore.
6814 memcg = get_mem_cgroup_from_objcg(objcg);
6816 memcg = __folio_memcg(folio);
6822 if (ug->memcg != memcg) {
6825 uncharge_gather_clear(ug);
6828 ug->nid = folio_nid(folio);
6830 /* pairs with css_put in uncharge_batch */
6831 css_get(&memcg->css);
6834 nr_pages = folio_nr_pages(folio);
6836 if (folio_memcg_kmem(folio)) {
6837 ug->nr_memory += nr_pages;
6838 ug->nr_kmem += nr_pages;
6840 folio->memcg_data = 0;
6841 obj_cgroup_put(objcg);
6843 /* LRU pages aren't accounted at the root level */
6844 if (!mem_cgroup_is_root(memcg))
6845 ug->nr_memory += nr_pages;
6848 folio->memcg_data = 0;
6851 css_put(&memcg->css);
6854 void __mem_cgroup_uncharge(struct folio *folio)
6856 struct uncharge_gather ug;
6858 /* Don't touch folio->lru of any random page, pre-check: */
6859 if (!folio_memcg(folio))
6862 uncharge_gather_clear(&ug);
6863 uncharge_folio(folio, &ug);
6864 uncharge_batch(&ug);
6868 * __mem_cgroup_uncharge_list - uncharge a list of page
6869 * @page_list: list of pages to uncharge
6871 * Uncharge a list of pages previously charged with
6872 * __mem_cgroup_charge().
6874 void __mem_cgroup_uncharge_list(struct list_head *page_list)
6876 struct uncharge_gather ug;
6877 struct folio *folio;
6879 uncharge_gather_clear(&ug);
6880 list_for_each_entry(folio, page_list, lru)
6881 uncharge_folio(folio, &ug);
6883 uncharge_batch(&ug);
6887 * mem_cgroup_migrate - Charge a folio's replacement.
6888 * @old: Currently circulating folio.
6889 * @new: Replacement folio.
6891 * Charge @new as a replacement folio for @old. @old will
6892 * be uncharged upon free.
6894 * Both folios must be locked, @new->mapping must be set up.
6896 void mem_cgroup_migrate(struct folio *old, struct folio *new)
6898 struct mem_cgroup *memcg;
6899 long nr_pages = folio_nr_pages(new);
6900 unsigned long flags;
6902 VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
6903 VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
6904 VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
6905 VM_BUG_ON_FOLIO(folio_nr_pages(old) != nr_pages, new);
6907 if (mem_cgroup_disabled())
6910 /* Page cache replacement: new folio already charged? */
6911 if (folio_memcg(new))
6914 memcg = folio_memcg(old);
6915 VM_WARN_ON_ONCE_FOLIO(!memcg, old);
6919 /* Force-charge the new page. The old one will be freed soon */
6920 if (!mem_cgroup_is_root(memcg)) {
6921 page_counter_charge(&memcg->memory, nr_pages);
6922 if (do_memsw_account())
6923 page_counter_charge(&memcg->memsw, nr_pages);
6926 css_get(&memcg->css);
6927 commit_charge(new, memcg);
6929 local_irq_save(flags);
6930 mem_cgroup_charge_statistics(memcg, nr_pages);
6931 memcg_check_events(memcg, folio_nid(new));
6932 local_irq_restore(flags);
6935 DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
6936 EXPORT_SYMBOL(memcg_sockets_enabled_key);
6938 void mem_cgroup_sk_alloc(struct sock *sk)
6940 struct mem_cgroup *memcg;
6942 if (!mem_cgroup_sockets_enabled)
6945 /* Do not associate the sock with unrelated interrupted task's memcg. */
6950 memcg = mem_cgroup_from_task(current);
6951 if (memcg == root_mem_cgroup)
6953 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg->tcpmem_active)
6955 if (css_tryget(&memcg->css))
6956 sk->sk_memcg = memcg;
6961 void mem_cgroup_sk_free(struct sock *sk)
6964 css_put(&sk->sk_memcg->css);
6968 * mem_cgroup_charge_skmem - charge socket memory
6969 * @memcg: memcg to charge
6970 * @nr_pages: number of pages to charge
6971 * @gfp_mask: reclaim mode
6973 * Charges @nr_pages to @memcg. Returns %true if the charge fit within
6974 * @memcg's configured limit, %false if it doesn't.
6976 bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages,
6979 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
6980 struct page_counter *fail;
6982 if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) {
6983 memcg->tcpmem_pressure = 0;
6986 memcg->tcpmem_pressure = 1;
6987 if (gfp_mask & __GFP_NOFAIL) {
6988 page_counter_charge(&memcg->tcpmem, nr_pages);
6994 if (try_charge(memcg, gfp_mask, nr_pages) == 0) {
6995 mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
7003 * mem_cgroup_uncharge_skmem - uncharge socket memory
7004 * @memcg: memcg to uncharge
7005 * @nr_pages: number of pages to uncharge
7007 void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
7009 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
7010 page_counter_uncharge(&memcg->tcpmem, nr_pages);
7014 mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
7016 refill_stock(memcg, nr_pages);
7019 static int __init cgroup_memory(char *s)
7023 while ((token = strsep(&s, ",")) != NULL) {
7026 if (!strcmp(token, "nosocket"))
7027 cgroup_memory_nosocket = true;
7028 if (!strcmp(token, "nokmem"))
7029 cgroup_memory_nokmem = true;
7033 __setup("cgroup.memory=", cgroup_memory);
7036 * subsys_initcall() for memory controller.
7038 * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
7039 * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
7040 * basically everything that doesn't depend on a specific mem_cgroup structure
7041 * should be initialized from here.
7043 static int __init mem_cgroup_init(void)
7048 * Currently s32 type (can refer to struct batched_lruvec_stat) is
7049 * used for per-memcg-per-cpu caching of per-node statistics. In order
7050 * to work fine, we should make sure that the overfill threshold can't
7051 * exceed S32_MAX / PAGE_SIZE.
7053 BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE);
7055 cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
7056 memcg_hotplug_cpu_dead);
7058 for_each_possible_cpu(cpu)
7059 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
7062 for_each_node(node) {
7063 struct mem_cgroup_tree_per_node *rtpn;
7065 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL,
7066 node_online(node) ? node : NUMA_NO_NODE);
7068 rtpn->rb_root = RB_ROOT;
7069 rtpn->rb_rightmost = NULL;
7070 spin_lock_init(&rtpn->lock);
7071 soft_limit_tree.rb_tree_per_node[node] = rtpn;
7076 subsys_initcall(mem_cgroup_init);
7078 #ifdef CONFIG_MEMCG_SWAP
7079 static struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
7081 while (!refcount_inc_not_zero(&memcg->id.ref)) {
7083 * The root cgroup cannot be destroyed, so it's refcount must
7086 if (WARN_ON_ONCE(memcg == root_mem_cgroup)) {
7090 memcg = parent_mem_cgroup(memcg);
7092 memcg = root_mem_cgroup;
7098 * mem_cgroup_swapout - transfer a memsw charge to swap
7099 * @page: page whose memsw charge to transfer
7100 * @entry: swap entry to move the charge to
7102 * Transfer the memsw charge of @page to @entry.
7104 void mem_cgroup_swapout(struct page *page, swp_entry_t entry)
7106 struct mem_cgroup *memcg, *swap_memcg;
7107 unsigned int nr_entries;
7108 unsigned short oldid;
7110 VM_BUG_ON_PAGE(PageLRU(page), page);
7111 VM_BUG_ON_PAGE(page_count(page), page);
7113 if (mem_cgroup_disabled())
7116 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
7119 memcg = page_memcg(page);
7121 VM_WARN_ON_ONCE_PAGE(!memcg, page);
7126 * In case the memcg owning these pages has been offlined and doesn't
7127 * have an ID allocated to it anymore, charge the closest online
7128 * ancestor for the swap instead and transfer the memory+swap charge.
7130 swap_memcg = mem_cgroup_id_get_online(memcg);
7131 nr_entries = thp_nr_pages(page);
7132 /* Get references for the tail pages, too */
7134 mem_cgroup_id_get_many(swap_memcg, nr_entries - 1);
7135 oldid = swap_cgroup_record(entry, mem_cgroup_id(swap_memcg),
7137 VM_BUG_ON_PAGE(oldid, page);
7138 mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries);
7140 page->memcg_data = 0;
7142 if (!mem_cgroup_is_root(memcg))
7143 page_counter_uncharge(&memcg->memory, nr_entries);
7145 if (!cgroup_memory_noswap && memcg != swap_memcg) {
7146 if (!mem_cgroup_is_root(swap_memcg))
7147 page_counter_charge(&swap_memcg->memsw, nr_entries);
7148 page_counter_uncharge(&memcg->memsw, nr_entries);
7152 * Interrupts should be disabled here because the caller holds the
7153 * i_pages lock which is taken with interrupts-off. It is
7154 * important here to have the interrupts disabled because it is the
7155 * only synchronisation we have for updating the per-CPU variables.
7157 VM_BUG_ON(!irqs_disabled());
7158 mem_cgroup_charge_statistics(memcg, -nr_entries);
7159 memcg_check_events(memcg, page_to_nid(page));
7161 css_put(&memcg->css);
7165 * __mem_cgroup_try_charge_swap - try charging swap space for a page
7166 * @page: page being added to swap
7167 * @entry: swap entry to charge
7169 * Try to charge @page's memcg for the swap space at @entry.
7171 * Returns 0 on success, -ENOMEM on failure.
7173 int __mem_cgroup_try_charge_swap(struct page *page, swp_entry_t entry)
7175 unsigned int nr_pages = thp_nr_pages(page);
7176 struct page_counter *counter;
7177 struct mem_cgroup *memcg;
7178 unsigned short oldid;
7180 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
7183 memcg = page_memcg(page);
7185 VM_WARN_ON_ONCE_PAGE(!memcg, page);
7190 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7194 memcg = mem_cgroup_id_get_online(memcg);
7196 if (!cgroup_memory_noswap && !mem_cgroup_is_root(memcg) &&
7197 !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
7198 memcg_memory_event(memcg, MEMCG_SWAP_MAX);
7199 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7200 mem_cgroup_id_put(memcg);
7204 /* Get references for the tail pages, too */
7206 mem_cgroup_id_get_many(memcg, nr_pages - 1);
7207 oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg), nr_pages);
7208 VM_BUG_ON_PAGE(oldid, page);
7209 mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
7215 * __mem_cgroup_uncharge_swap - uncharge swap space
7216 * @entry: swap entry to uncharge
7217 * @nr_pages: the amount of swap space to uncharge
7219 void __mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
7221 struct mem_cgroup *memcg;
7224 id = swap_cgroup_record(entry, 0, nr_pages);
7226 memcg = mem_cgroup_from_id(id);
7228 if (!cgroup_memory_noswap && !mem_cgroup_is_root(memcg)) {
7229 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
7230 page_counter_uncharge(&memcg->swap, nr_pages);
7232 page_counter_uncharge(&memcg->memsw, nr_pages);
7234 mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
7235 mem_cgroup_id_put_many(memcg, nr_pages);
7240 long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
7242 long nr_swap_pages = get_nr_swap_pages();
7244 if (cgroup_memory_noswap || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
7245 return nr_swap_pages;
7246 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg))
7247 nr_swap_pages = min_t(long, nr_swap_pages,
7248 READ_ONCE(memcg->swap.max) -
7249 page_counter_read(&memcg->swap));
7250 return nr_swap_pages;
7253 bool mem_cgroup_swap_full(struct page *page)
7255 struct mem_cgroup *memcg;
7257 VM_BUG_ON_PAGE(!PageLocked(page), page);
7261 if (cgroup_memory_noswap || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
7264 memcg = page_memcg(page);
7268 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg)) {
7269 unsigned long usage = page_counter_read(&memcg->swap);
7271 if (usage * 2 >= READ_ONCE(memcg->swap.high) ||
7272 usage * 2 >= READ_ONCE(memcg->swap.max))
7279 static int __init setup_swap_account(char *s)
7281 if (!strcmp(s, "1"))
7282 cgroup_memory_noswap = false;
7283 else if (!strcmp(s, "0"))
7284 cgroup_memory_noswap = true;
7287 __setup("swapaccount=", setup_swap_account);
7289 static u64 swap_current_read(struct cgroup_subsys_state *css,
7292 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7294 return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
7297 static int swap_high_show(struct seq_file *m, void *v)
7299 return seq_puts_memcg_tunable(m,
7300 READ_ONCE(mem_cgroup_from_seq(m)->swap.high));
7303 static ssize_t swap_high_write(struct kernfs_open_file *of,
7304 char *buf, size_t nbytes, loff_t off)
7306 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7310 buf = strstrip(buf);
7311 err = page_counter_memparse(buf, "max", &high);
7315 page_counter_set_high(&memcg->swap, high);
7320 static int swap_max_show(struct seq_file *m, void *v)
7322 return seq_puts_memcg_tunable(m,
7323 READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
7326 static ssize_t swap_max_write(struct kernfs_open_file *of,
7327 char *buf, size_t nbytes, loff_t off)
7329 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7333 buf = strstrip(buf);
7334 err = page_counter_memparse(buf, "max", &max);
7338 xchg(&memcg->swap.max, max);
7343 static int swap_events_show(struct seq_file *m, void *v)
7345 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
7347 seq_printf(m, "high %lu\n",
7348 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH]));
7349 seq_printf(m, "max %lu\n",
7350 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
7351 seq_printf(m, "fail %lu\n",
7352 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
7357 static struct cftype swap_files[] = {
7359 .name = "swap.current",
7360 .flags = CFTYPE_NOT_ON_ROOT,
7361 .read_u64 = swap_current_read,
7364 .name = "swap.high",
7365 .flags = CFTYPE_NOT_ON_ROOT,
7366 .seq_show = swap_high_show,
7367 .write = swap_high_write,
7371 .flags = CFTYPE_NOT_ON_ROOT,
7372 .seq_show = swap_max_show,
7373 .write = swap_max_write,
7376 .name = "swap.events",
7377 .flags = CFTYPE_NOT_ON_ROOT,
7378 .file_offset = offsetof(struct mem_cgroup, swap_events_file),
7379 .seq_show = swap_events_show,
7384 static struct cftype memsw_files[] = {
7386 .name = "memsw.usage_in_bytes",
7387 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
7388 .read_u64 = mem_cgroup_read_u64,
7391 .name = "memsw.max_usage_in_bytes",
7392 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
7393 .write = mem_cgroup_reset,
7394 .read_u64 = mem_cgroup_read_u64,
7397 .name = "memsw.limit_in_bytes",
7398 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
7399 .write = mem_cgroup_write,
7400 .read_u64 = mem_cgroup_read_u64,
7403 .name = "memsw.failcnt",
7404 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
7405 .write = mem_cgroup_reset,
7406 .read_u64 = mem_cgroup_read_u64,
7408 { }, /* terminate */
7412 * If mem_cgroup_swap_init() is implemented as a subsys_initcall()
7413 * instead of a core_initcall(), this could mean cgroup_memory_noswap still
7414 * remains set to false even when memcg is disabled via "cgroup_disable=memory"
7415 * boot parameter. This may result in premature OOPS inside
7416 * mem_cgroup_get_nr_swap_pages() function in corner cases.
7418 static int __init mem_cgroup_swap_init(void)
7420 /* No memory control -> no swap control */
7421 if (mem_cgroup_disabled())
7422 cgroup_memory_noswap = true;
7424 if (cgroup_memory_noswap)
7427 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files));
7428 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files));
7432 core_initcall(mem_cgroup_swap_init);
7434 #endif /* CONFIG_MEMCG_SWAP */