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 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 /* memcg and lruvec stats flushing */
107 static void flush_memcg_stats_dwork(struct work_struct *w);
108 static DECLARE_DEFERRABLE_WORK(stats_flush_dwork, flush_memcg_stats_dwork);
109 static DEFINE_SPINLOCK(stats_flush_lock);
111 #define THRESHOLDS_EVENTS_TARGET 128
112 #define SOFTLIMIT_EVENTS_TARGET 1024
115 * Cgroups above their limits are maintained in a RB-Tree, independent of
116 * their hierarchy representation
119 struct mem_cgroup_tree_per_node {
120 struct rb_root rb_root;
121 struct rb_node *rb_rightmost;
125 struct mem_cgroup_tree {
126 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
129 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
132 struct mem_cgroup_eventfd_list {
133 struct list_head list;
134 struct eventfd_ctx *eventfd;
138 * cgroup_event represents events which userspace want to receive.
140 struct mem_cgroup_event {
142 * memcg which the event belongs to.
144 struct mem_cgroup *memcg;
146 * eventfd to signal userspace about the event.
148 struct eventfd_ctx *eventfd;
150 * Each of these stored in a list by the cgroup.
152 struct list_head list;
154 * register_event() callback will be used to add new userspace
155 * waiter for changes related to this event. Use eventfd_signal()
156 * on eventfd to send notification to userspace.
158 int (*register_event)(struct mem_cgroup *memcg,
159 struct eventfd_ctx *eventfd, const char *args);
161 * unregister_event() callback will be called when userspace closes
162 * the eventfd or on cgroup removing. This callback must be set,
163 * if you want provide notification functionality.
165 void (*unregister_event)(struct mem_cgroup *memcg,
166 struct eventfd_ctx *eventfd);
168 * All fields below needed to unregister event when
169 * userspace closes eventfd.
172 wait_queue_head_t *wqh;
173 wait_queue_entry_t wait;
174 struct work_struct remove;
177 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
178 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
180 /* Stuffs for move charges at task migration. */
182 * Types of charges to be moved.
184 #define MOVE_ANON 0x1U
185 #define MOVE_FILE 0x2U
186 #define MOVE_MASK (MOVE_ANON | MOVE_FILE)
188 /* "mc" and its members are protected by cgroup_mutex */
189 static struct move_charge_struct {
190 spinlock_t lock; /* for from, to */
191 struct mm_struct *mm;
192 struct mem_cgroup *from;
193 struct mem_cgroup *to;
195 unsigned long precharge;
196 unsigned long moved_charge;
197 unsigned long moved_swap;
198 struct task_struct *moving_task; /* a task moving charges */
199 wait_queue_head_t waitq; /* a waitq for other context */
201 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
202 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
206 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
207 * limit reclaim to prevent infinite loops, if they ever occur.
209 #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
210 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
212 /* for encoding cft->private value on file */
221 #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
222 #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
223 #define MEMFILE_ATTR(val) ((val) & 0xffff)
224 /* Used for OOM notifier */
225 #define OOM_CONTROL (0)
228 * Iteration constructs for visiting all cgroups (under a tree). If
229 * loops are exited prematurely (break), mem_cgroup_iter_break() must
230 * be used for reference counting.
232 #define for_each_mem_cgroup_tree(iter, root) \
233 for (iter = mem_cgroup_iter(root, NULL, NULL); \
235 iter = mem_cgroup_iter(root, iter, NULL))
237 #define for_each_mem_cgroup(iter) \
238 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
240 iter = mem_cgroup_iter(NULL, iter, NULL))
242 static inline bool should_force_charge(void)
244 return tsk_is_oom_victim(current) || fatal_signal_pending(current) ||
245 (current->flags & PF_EXITING);
248 /* Some nice accessors for the vmpressure. */
249 struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
252 memcg = root_mem_cgroup;
253 return &memcg->vmpressure;
256 struct mem_cgroup *vmpressure_to_memcg(struct vmpressure *vmpr)
258 return container_of(vmpr, struct mem_cgroup, vmpressure);
261 #ifdef CONFIG_MEMCG_KMEM
262 extern spinlock_t css_set_lock;
264 bool mem_cgroup_kmem_disabled(void)
266 return cgroup_memory_nokmem;
269 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
270 unsigned int nr_pages);
272 static void obj_cgroup_release(struct percpu_ref *ref)
274 struct obj_cgroup *objcg = container_of(ref, struct obj_cgroup, refcnt);
275 unsigned int nr_bytes;
276 unsigned int nr_pages;
280 * At this point all allocated objects are freed, and
281 * objcg->nr_charged_bytes can't have an arbitrary byte value.
282 * However, it can be PAGE_SIZE or (x * PAGE_SIZE).
284 * The following sequence can lead to it:
285 * 1) CPU0: objcg == stock->cached_objcg
286 * 2) CPU1: we do a small allocation (e.g. 92 bytes),
287 * PAGE_SIZE bytes are charged
288 * 3) CPU1: a process from another memcg is allocating something,
289 * the stock if flushed,
290 * objcg->nr_charged_bytes = PAGE_SIZE - 92
291 * 5) CPU0: we do release this object,
292 * 92 bytes are added to stock->nr_bytes
293 * 6) CPU0: stock is flushed,
294 * 92 bytes are added to objcg->nr_charged_bytes
296 * In the result, nr_charged_bytes == PAGE_SIZE.
297 * This page will be uncharged in obj_cgroup_release().
299 nr_bytes = atomic_read(&objcg->nr_charged_bytes);
300 WARN_ON_ONCE(nr_bytes & (PAGE_SIZE - 1));
301 nr_pages = nr_bytes >> PAGE_SHIFT;
304 obj_cgroup_uncharge_pages(objcg, nr_pages);
306 spin_lock_irqsave(&css_set_lock, flags);
307 list_del(&objcg->list);
308 spin_unlock_irqrestore(&css_set_lock, flags);
310 percpu_ref_exit(ref);
311 kfree_rcu(objcg, rcu);
314 static struct obj_cgroup *obj_cgroup_alloc(void)
316 struct obj_cgroup *objcg;
319 objcg = kzalloc(sizeof(struct obj_cgroup), GFP_KERNEL);
323 ret = percpu_ref_init(&objcg->refcnt, obj_cgroup_release, 0,
329 INIT_LIST_HEAD(&objcg->list);
333 static void memcg_reparent_objcgs(struct mem_cgroup *memcg,
334 struct mem_cgroup *parent)
336 struct obj_cgroup *objcg, *iter;
338 objcg = rcu_replace_pointer(memcg->objcg, NULL, true);
340 spin_lock_irq(&css_set_lock);
342 /* 1) Ready to reparent active objcg. */
343 list_add(&objcg->list, &memcg->objcg_list);
344 /* 2) Reparent active objcg and already reparented objcgs to parent. */
345 list_for_each_entry(iter, &memcg->objcg_list, list)
346 WRITE_ONCE(iter->memcg, parent);
347 /* 3) Move already reparented objcgs to the parent's list */
348 list_splice(&memcg->objcg_list, &parent->objcg_list);
350 spin_unlock_irq(&css_set_lock);
352 percpu_ref_kill(&objcg->refcnt);
356 * This will be used as a shrinker list's index.
357 * The main reason for not using cgroup id for this:
358 * this works better in sparse environments, where we have a lot of memcgs,
359 * but only a few kmem-limited. Or also, if we have, for instance, 200
360 * memcgs, and none but the 200th is kmem-limited, we'd have to have a
361 * 200 entry array for that.
363 * The current size of the caches array is stored in memcg_nr_cache_ids. It
364 * will double each time we have to increase it.
366 static DEFINE_IDA(memcg_cache_ida);
367 int memcg_nr_cache_ids;
369 /* Protects memcg_nr_cache_ids */
370 static DECLARE_RWSEM(memcg_cache_ids_sem);
372 void memcg_get_cache_ids(void)
374 down_read(&memcg_cache_ids_sem);
377 void memcg_put_cache_ids(void)
379 up_read(&memcg_cache_ids_sem);
383 * MIN_SIZE is different than 1, because we would like to avoid going through
384 * the alloc/free process all the time. In a small machine, 4 kmem-limited
385 * cgroups is a reasonable guess. In the future, it could be a parameter or
386 * tunable, but that is strictly not necessary.
388 * MAX_SIZE should be as large as the number of cgrp_ids. Ideally, we could get
389 * this constant directly from cgroup, but it is understandable that this is
390 * better kept as an internal representation in cgroup.c. In any case, the
391 * cgrp_id space is not getting any smaller, and we don't have to necessarily
392 * increase ours as well if it increases.
394 #define MEMCG_CACHES_MIN_SIZE 4
395 #define MEMCG_CACHES_MAX_SIZE MEM_CGROUP_ID_MAX
398 * A lot of the calls to the cache allocation functions are expected to be
399 * inlined by the compiler. Since the calls to memcg_slab_pre_alloc_hook() are
400 * conditional to this static branch, we'll have to allow modules that does
401 * kmem_cache_alloc and the such to see this symbol as well
403 DEFINE_STATIC_KEY_FALSE(memcg_kmem_enabled_key);
404 EXPORT_SYMBOL(memcg_kmem_enabled_key);
408 * mem_cgroup_css_from_page - css of the memcg associated with a page
409 * @page: page of interest
411 * If memcg is bound to the default hierarchy, css of the memcg associated
412 * with @page is returned. The returned css remains associated with @page
413 * until it is released.
415 * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
418 struct cgroup_subsys_state *mem_cgroup_css_from_page(struct page *page)
420 struct mem_cgroup *memcg;
422 memcg = page_memcg(page);
424 if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
425 memcg = root_mem_cgroup;
431 * page_cgroup_ino - return inode number of the memcg a page is charged to
434 * Look up the closest online ancestor of the memory cgroup @page is charged to
435 * and return its inode number or 0 if @page is not charged to any cgroup. It
436 * is safe to call this function without holding a reference to @page.
438 * Note, this function is inherently racy, because there is nothing to prevent
439 * the cgroup inode from getting torn down and potentially reallocated a moment
440 * after page_cgroup_ino() returns, so it only should be used by callers that
441 * do not care (such as procfs interfaces).
443 ino_t page_cgroup_ino(struct page *page)
445 struct mem_cgroup *memcg;
446 unsigned long ino = 0;
449 memcg = page_memcg_check(page);
451 while (memcg && !(memcg->css.flags & CSS_ONLINE))
452 memcg = parent_mem_cgroup(memcg);
454 ino = cgroup_ino(memcg->css.cgroup);
459 static struct mem_cgroup_per_node *
460 mem_cgroup_page_nodeinfo(struct mem_cgroup *memcg, struct page *page)
462 int nid = page_to_nid(page);
464 return memcg->nodeinfo[nid];
467 static struct mem_cgroup_tree_per_node *
468 soft_limit_tree_node(int nid)
470 return soft_limit_tree.rb_tree_per_node[nid];
473 static struct mem_cgroup_tree_per_node *
474 soft_limit_tree_from_page(struct page *page)
476 int nid = page_to_nid(page);
478 return soft_limit_tree.rb_tree_per_node[nid];
481 static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_node *mz,
482 struct mem_cgroup_tree_per_node *mctz,
483 unsigned long new_usage_in_excess)
485 struct rb_node **p = &mctz->rb_root.rb_node;
486 struct rb_node *parent = NULL;
487 struct mem_cgroup_per_node *mz_node;
488 bool rightmost = true;
493 mz->usage_in_excess = new_usage_in_excess;
494 if (!mz->usage_in_excess)
498 mz_node = rb_entry(parent, struct mem_cgroup_per_node,
500 if (mz->usage_in_excess < mz_node->usage_in_excess) {
509 mctz->rb_rightmost = &mz->tree_node;
511 rb_link_node(&mz->tree_node, parent, p);
512 rb_insert_color(&mz->tree_node, &mctz->rb_root);
516 static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
517 struct mem_cgroup_tree_per_node *mctz)
522 if (&mz->tree_node == mctz->rb_rightmost)
523 mctz->rb_rightmost = rb_prev(&mz->tree_node);
525 rb_erase(&mz->tree_node, &mctz->rb_root);
529 static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
530 struct mem_cgroup_tree_per_node *mctz)
534 spin_lock_irqsave(&mctz->lock, flags);
535 __mem_cgroup_remove_exceeded(mz, mctz);
536 spin_unlock_irqrestore(&mctz->lock, flags);
539 static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
541 unsigned long nr_pages = page_counter_read(&memcg->memory);
542 unsigned long soft_limit = READ_ONCE(memcg->soft_limit);
543 unsigned long excess = 0;
545 if (nr_pages > soft_limit)
546 excess = nr_pages - soft_limit;
551 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
553 unsigned long excess;
554 struct mem_cgroup_per_node *mz;
555 struct mem_cgroup_tree_per_node *mctz;
557 mctz = soft_limit_tree_from_page(page);
561 * Necessary to update all ancestors when hierarchy is used.
562 * because their event counter is not touched.
564 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
565 mz = mem_cgroup_page_nodeinfo(memcg, page);
566 excess = soft_limit_excess(memcg);
568 * We have to update the tree if mz is on RB-tree or
569 * mem is over its softlimit.
571 if (excess || mz->on_tree) {
574 spin_lock_irqsave(&mctz->lock, flags);
575 /* if on-tree, remove it */
577 __mem_cgroup_remove_exceeded(mz, mctz);
579 * Insert again. mz->usage_in_excess will be updated.
580 * If excess is 0, no tree ops.
582 __mem_cgroup_insert_exceeded(mz, mctz, excess);
583 spin_unlock_irqrestore(&mctz->lock, flags);
588 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
590 struct mem_cgroup_tree_per_node *mctz;
591 struct mem_cgroup_per_node *mz;
595 mz = memcg->nodeinfo[nid];
596 mctz = soft_limit_tree_node(nid);
598 mem_cgroup_remove_exceeded(mz, mctz);
602 static struct mem_cgroup_per_node *
603 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
605 struct mem_cgroup_per_node *mz;
609 if (!mctz->rb_rightmost)
610 goto done; /* Nothing to reclaim from */
612 mz = rb_entry(mctz->rb_rightmost,
613 struct mem_cgroup_per_node, tree_node);
615 * Remove the node now but someone else can add it back,
616 * we will to add it back at the end of reclaim to its correct
617 * position in the tree.
619 __mem_cgroup_remove_exceeded(mz, mctz);
620 if (!soft_limit_excess(mz->memcg) ||
621 !css_tryget(&mz->memcg->css))
627 static struct mem_cgroup_per_node *
628 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
630 struct mem_cgroup_per_node *mz;
632 spin_lock_irq(&mctz->lock);
633 mz = __mem_cgroup_largest_soft_limit_node(mctz);
634 spin_unlock_irq(&mctz->lock);
639 * __mod_memcg_state - update cgroup memory statistics
640 * @memcg: the memory cgroup
641 * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item
642 * @val: delta to add to the counter, can be negative
644 void __mod_memcg_state(struct mem_cgroup *memcg, int idx, int val)
646 if (mem_cgroup_disabled())
649 __this_cpu_add(memcg->vmstats_percpu->state[idx], val);
650 cgroup_rstat_updated(memcg->css.cgroup, smp_processor_id());
653 /* idx can be of type enum memcg_stat_item or node_stat_item. */
654 static unsigned long memcg_page_state_local(struct mem_cgroup *memcg, int idx)
659 for_each_possible_cpu(cpu)
660 x += per_cpu(memcg->vmstats_percpu->state[idx], cpu);
668 void __mod_memcg_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
671 struct mem_cgroup_per_node *pn;
672 struct mem_cgroup *memcg;
674 pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
678 __mod_memcg_state(memcg, idx, val);
681 __this_cpu_add(pn->lruvec_stats_percpu->state[idx], val);
685 * __mod_lruvec_state - update lruvec memory statistics
686 * @lruvec: the lruvec
687 * @idx: the stat item
688 * @val: delta to add to the counter, can be negative
690 * The lruvec is the intersection of the NUMA node and a cgroup. This
691 * function updates the all three counters that are affected by a
692 * change of state at this level: per-node, per-cgroup, per-lruvec.
694 void __mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
698 __mod_node_page_state(lruvec_pgdat(lruvec), idx, val);
700 /* Update memcg and lruvec */
701 if (!mem_cgroup_disabled())
702 __mod_memcg_lruvec_state(lruvec, idx, val);
705 void __mod_lruvec_page_state(struct page *page, enum node_stat_item idx,
708 struct page *head = compound_head(page); /* rmap on tail pages */
709 struct mem_cgroup *memcg;
710 pg_data_t *pgdat = page_pgdat(page);
711 struct lruvec *lruvec;
714 memcg = page_memcg(head);
715 /* Untracked pages have no memcg, no lruvec. Update only the node */
718 __mod_node_page_state(pgdat, idx, val);
722 lruvec = mem_cgroup_lruvec(memcg, pgdat);
723 __mod_lruvec_state(lruvec, idx, val);
726 EXPORT_SYMBOL(__mod_lruvec_page_state);
728 void __mod_lruvec_kmem_state(void *p, enum node_stat_item idx, int val)
730 pg_data_t *pgdat = page_pgdat(virt_to_page(p));
731 struct mem_cgroup *memcg;
732 struct lruvec *lruvec;
735 memcg = mem_cgroup_from_obj(p);
738 * Untracked pages have no memcg, no lruvec. Update only the
739 * node. If we reparent the slab objects to the root memcg,
740 * when we free the slab object, we need to update the per-memcg
741 * vmstats to keep it correct for the root memcg.
744 __mod_node_page_state(pgdat, idx, val);
746 lruvec = mem_cgroup_lruvec(memcg, pgdat);
747 __mod_lruvec_state(lruvec, idx, val);
753 * mod_objcg_mlstate() may be called with irq enabled, so
754 * mod_memcg_lruvec_state() should be used.
756 static inline void mod_objcg_mlstate(struct obj_cgroup *objcg,
757 struct pglist_data *pgdat,
758 enum node_stat_item idx, int nr)
760 struct mem_cgroup *memcg;
761 struct lruvec *lruvec;
764 memcg = obj_cgroup_memcg(objcg);
765 lruvec = mem_cgroup_lruvec(memcg, pgdat);
766 mod_memcg_lruvec_state(lruvec, idx, nr);
771 * __count_memcg_events - account VM events in a cgroup
772 * @memcg: the memory cgroup
773 * @idx: the event item
774 * @count: the number of events that occurred
776 void __count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx,
779 if (mem_cgroup_disabled())
782 __this_cpu_add(memcg->vmstats_percpu->events[idx], count);
783 cgroup_rstat_updated(memcg->css.cgroup, smp_processor_id());
786 static unsigned long memcg_events(struct mem_cgroup *memcg, int event)
788 return READ_ONCE(memcg->vmstats.events[event]);
791 static unsigned long memcg_events_local(struct mem_cgroup *memcg, int event)
796 for_each_possible_cpu(cpu)
797 x += per_cpu(memcg->vmstats_percpu->events[event], cpu);
801 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
805 /* pagein of a big page is an event. So, ignore page size */
807 __count_memcg_events(memcg, PGPGIN, 1);
809 __count_memcg_events(memcg, PGPGOUT, 1);
810 nr_pages = -nr_pages; /* for event */
813 __this_cpu_add(memcg->vmstats_percpu->nr_page_events, nr_pages);
816 static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
817 enum mem_cgroup_events_target target)
819 unsigned long val, next;
821 val = __this_cpu_read(memcg->vmstats_percpu->nr_page_events);
822 next = __this_cpu_read(memcg->vmstats_percpu->targets[target]);
823 /* from time_after() in jiffies.h */
824 if ((long)(next - val) < 0) {
826 case MEM_CGROUP_TARGET_THRESH:
827 next = val + THRESHOLDS_EVENTS_TARGET;
829 case MEM_CGROUP_TARGET_SOFTLIMIT:
830 next = val + SOFTLIMIT_EVENTS_TARGET;
835 __this_cpu_write(memcg->vmstats_percpu->targets[target], next);
842 * Check events in order.
845 static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
847 /* threshold event is triggered in finer grain than soft limit */
848 if (unlikely(mem_cgroup_event_ratelimit(memcg,
849 MEM_CGROUP_TARGET_THRESH))) {
852 do_softlimit = mem_cgroup_event_ratelimit(memcg,
853 MEM_CGROUP_TARGET_SOFTLIMIT);
854 mem_cgroup_threshold(memcg);
855 if (unlikely(do_softlimit))
856 mem_cgroup_update_tree(memcg, page);
860 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
863 * mm_update_next_owner() may clear mm->owner to NULL
864 * if it races with swapoff, page migration, etc.
865 * So this can be called with p == NULL.
870 return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
872 EXPORT_SYMBOL(mem_cgroup_from_task);
874 static __always_inline struct mem_cgroup *active_memcg(void)
877 return this_cpu_read(int_active_memcg);
879 return current->active_memcg;
883 * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
884 * @mm: mm from which memcg should be extracted. It can be NULL.
886 * Obtain a reference on mm->memcg and returns it if successful. If mm
887 * is NULL, then the memcg is chosen as follows:
888 * 1) The active memcg, if set.
889 * 2) current->mm->memcg, if available
891 * If mem_cgroup is disabled, NULL is returned.
893 struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
895 struct mem_cgroup *memcg;
897 if (mem_cgroup_disabled())
901 * Page cache insertions can happen without an
902 * actual mm context, e.g. during disk probing
903 * on boot, loopback IO, acct() writes etc.
905 * No need to css_get on root memcg as the reference
906 * counting is disabled on the root level in the
907 * cgroup core. See CSS_NO_REF.
910 memcg = active_memcg();
911 if (unlikely(memcg)) {
912 /* remote memcg must hold a ref */
913 css_get(&memcg->css);
918 return root_mem_cgroup;
923 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
924 if (unlikely(!memcg))
925 memcg = root_mem_cgroup;
926 } while (!css_tryget(&memcg->css));
930 EXPORT_SYMBOL(get_mem_cgroup_from_mm);
932 static __always_inline bool memcg_kmem_bypass(void)
934 /* Allow remote memcg charging from any context. */
935 if (unlikely(active_memcg()))
938 /* Memcg to charge can't be determined. */
939 if (!in_task() || !current->mm || (current->flags & PF_KTHREAD))
946 * mem_cgroup_iter - iterate over memory cgroup hierarchy
947 * @root: hierarchy root
948 * @prev: previously returned memcg, NULL on first invocation
949 * @reclaim: cookie for shared reclaim walks, NULL for full walks
951 * Returns references to children of the hierarchy below @root, or
952 * @root itself, or %NULL after a full round-trip.
954 * Caller must pass the return value in @prev on subsequent
955 * invocations for reference counting, or use mem_cgroup_iter_break()
956 * to cancel a hierarchy walk before the round-trip is complete.
958 * Reclaimers can specify a node in @reclaim to divide up the memcgs
959 * in the hierarchy among all concurrent reclaimers operating on the
962 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
963 struct mem_cgroup *prev,
964 struct mem_cgroup_reclaim_cookie *reclaim)
966 struct mem_cgroup_reclaim_iter *iter;
967 struct cgroup_subsys_state *css = NULL;
968 struct mem_cgroup *memcg = NULL;
969 struct mem_cgroup *pos = NULL;
971 if (mem_cgroup_disabled())
975 root = root_mem_cgroup;
977 if (prev && !reclaim)
983 struct mem_cgroup_per_node *mz;
985 mz = root->nodeinfo[reclaim->pgdat->node_id];
988 if (prev && reclaim->generation != iter->generation)
992 pos = READ_ONCE(iter->position);
993 if (!pos || css_tryget(&pos->css))
996 * css reference reached zero, so iter->position will
997 * be cleared by ->css_released. However, we should not
998 * rely on this happening soon, because ->css_released
999 * is called from a work queue, and by busy-waiting we
1000 * might block it. So we clear iter->position right
1003 (void)cmpxchg(&iter->position, pos, NULL);
1011 css = css_next_descendant_pre(css, &root->css);
1014 * Reclaimers share the hierarchy walk, and a
1015 * new one might jump in right at the end of
1016 * the hierarchy - make sure they see at least
1017 * one group and restart from the beginning.
1025 * Verify the css and acquire a reference. The root
1026 * is provided by the caller, so we know it's alive
1027 * and kicking, and don't take an extra reference.
1029 memcg = mem_cgroup_from_css(css);
1031 if (css == &root->css)
1034 if (css_tryget(css))
1042 * The position could have already been updated by a competing
1043 * thread, so check that the value hasn't changed since we read
1044 * it to avoid reclaiming from the same cgroup twice.
1046 (void)cmpxchg(&iter->position, pos, memcg);
1054 reclaim->generation = iter->generation;
1059 if (prev && prev != root)
1060 css_put(&prev->css);
1066 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1067 * @root: hierarchy root
1068 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1070 void mem_cgroup_iter_break(struct mem_cgroup *root,
1071 struct mem_cgroup *prev)
1074 root = root_mem_cgroup;
1075 if (prev && prev != root)
1076 css_put(&prev->css);
1079 static void __invalidate_reclaim_iterators(struct mem_cgroup *from,
1080 struct mem_cgroup *dead_memcg)
1082 struct mem_cgroup_reclaim_iter *iter;
1083 struct mem_cgroup_per_node *mz;
1086 for_each_node(nid) {
1087 mz = from->nodeinfo[nid];
1089 cmpxchg(&iter->position, dead_memcg, NULL);
1093 static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
1095 struct mem_cgroup *memcg = dead_memcg;
1096 struct mem_cgroup *last;
1099 __invalidate_reclaim_iterators(memcg, dead_memcg);
1101 } while ((memcg = parent_mem_cgroup(memcg)));
1104 * When cgruop1 non-hierarchy mode is used,
1105 * parent_mem_cgroup() does not walk all the way up to the
1106 * cgroup root (root_mem_cgroup). So we have to handle
1107 * dead_memcg from cgroup root separately.
1109 if (last != root_mem_cgroup)
1110 __invalidate_reclaim_iterators(root_mem_cgroup,
1115 * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
1116 * @memcg: hierarchy root
1117 * @fn: function to call for each task
1118 * @arg: argument passed to @fn
1120 * This function iterates over tasks attached to @memcg or to any of its
1121 * descendants and calls @fn for each task. If @fn returns a non-zero
1122 * value, the function breaks the iteration loop and returns the value.
1123 * Otherwise, it will iterate over all tasks and return 0.
1125 * This function must not be called for the root memory cgroup.
1127 int mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
1128 int (*fn)(struct task_struct *, void *), void *arg)
1130 struct mem_cgroup *iter;
1133 BUG_ON(memcg == root_mem_cgroup);
1135 for_each_mem_cgroup_tree(iter, memcg) {
1136 struct css_task_iter it;
1137 struct task_struct *task;
1139 css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it);
1140 while (!ret && (task = css_task_iter_next(&it)))
1141 ret = fn(task, arg);
1142 css_task_iter_end(&it);
1144 mem_cgroup_iter_break(memcg, iter);
1151 #ifdef CONFIG_DEBUG_VM
1152 void lruvec_memcg_debug(struct lruvec *lruvec, struct page *page)
1154 struct mem_cgroup *memcg;
1156 if (mem_cgroup_disabled())
1159 memcg = page_memcg(page);
1162 VM_BUG_ON_PAGE(lruvec_memcg(lruvec) != root_mem_cgroup, page);
1164 VM_BUG_ON_PAGE(lruvec_memcg(lruvec) != memcg, page);
1169 * lock_page_lruvec - lock and return lruvec for a given page.
1172 * These functions are safe to use under any of the following conditions:
1175 * - lock_page_memcg()
1176 * - page->_refcount is zero
1178 struct lruvec *lock_page_lruvec(struct page *page)
1180 struct lruvec *lruvec;
1182 lruvec = mem_cgroup_page_lruvec(page);
1183 spin_lock(&lruvec->lru_lock);
1185 lruvec_memcg_debug(lruvec, page);
1190 struct lruvec *lock_page_lruvec_irq(struct page *page)
1192 struct lruvec *lruvec;
1194 lruvec = mem_cgroup_page_lruvec(page);
1195 spin_lock_irq(&lruvec->lru_lock);
1197 lruvec_memcg_debug(lruvec, page);
1202 struct lruvec *lock_page_lruvec_irqsave(struct page *page, unsigned long *flags)
1204 struct lruvec *lruvec;
1206 lruvec = mem_cgroup_page_lruvec(page);
1207 spin_lock_irqsave(&lruvec->lru_lock, *flags);
1209 lruvec_memcg_debug(lruvec, page);
1215 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1216 * @lruvec: mem_cgroup per zone lru vector
1217 * @lru: index of lru list the page is sitting on
1218 * @zid: zone id of the accounted pages
1219 * @nr_pages: positive when adding or negative when removing
1221 * This function must be called under lru_lock, just before a page is added
1222 * to or just after a page is removed from an lru list (that ordering being
1223 * so as to allow it to check that lru_size 0 is consistent with list_empty).
1225 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1226 int zid, int nr_pages)
1228 struct mem_cgroup_per_node *mz;
1229 unsigned long *lru_size;
1232 if (mem_cgroup_disabled())
1235 mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
1236 lru_size = &mz->lru_zone_size[zid][lru];
1239 *lru_size += nr_pages;
1242 if (WARN_ONCE(size < 0,
1243 "%s(%p, %d, %d): lru_size %ld\n",
1244 __func__, lruvec, lru, nr_pages, size)) {
1250 *lru_size += nr_pages;
1254 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1255 * @memcg: the memory cgroup
1257 * Returns the maximum amount of memory @mem can be charged with, in
1260 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1262 unsigned long margin = 0;
1263 unsigned long count;
1264 unsigned long limit;
1266 count = page_counter_read(&memcg->memory);
1267 limit = READ_ONCE(memcg->memory.max);
1269 margin = limit - count;
1271 if (do_memsw_account()) {
1272 count = page_counter_read(&memcg->memsw);
1273 limit = READ_ONCE(memcg->memsw.max);
1275 margin = min(margin, limit - count);
1284 * A routine for checking "mem" is under move_account() or not.
1286 * Checking a cgroup is mc.from or mc.to or under hierarchy of
1287 * moving cgroups. This is for waiting at high-memory pressure
1290 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1292 struct mem_cgroup *from;
1293 struct mem_cgroup *to;
1296 * Unlike task_move routines, we access mc.to, mc.from not under
1297 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1299 spin_lock(&mc.lock);
1305 ret = mem_cgroup_is_descendant(from, memcg) ||
1306 mem_cgroup_is_descendant(to, memcg);
1308 spin_unlock(&mc.lock);
1312 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1314 if (mc.moving_task && current != mc.moving_task) {
1315 if (mem_cgroup_under_move(memcg)) {
1317 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1318 /* moving charge context might have finished. */
1321 finish_wait(&mc.waitq, &wait);
1328 struct memory_stat {
1333 static const struct memory_stat memory_stats[] = {
1334 { "anon", NR_ANON_MAPPED },
1335 { "file", NR_FILE_PAGES },
1336 { "kernel_stack", NR_KERNEL_STACK_KB },
1337 { "pagetables", NR_PAGETABLE },
1338 { "percpu", MEMCG_PERCPU_B },
1339 { "sock", MEMCG_SOCK },
1340 { "shmem", NR_SHMEM },
1341 { "file_mapped", NR_FILE_MAPPED },
1342 { "file_dirty", NR_FILE_DIRTY },
1343 { "file_writeback", NR_WRITEBACK },
1345 { "swapcached", NR_SWAPCACHE },
1347 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1348 { "anon_thp", NR_ANON_THPS },
1349 { "file_thp", NR_FILE_THPS },
1350 { "shmem_thp", NR_SHMEM_THPS },
1352 { "inactive_anon", NR_INACTIVE_ANON },
1353 { "active_anon", NR_ACTIVE_ANON },
1354 { "inactive_file", NR_INACTIVE_FILE },
1355 { "active_file", NR_ACTIVE_FILE },
1356 { "unevictable", NR_UNEVICTABLE },
1357 { "slab_reclaimable", NR_SLAB_RECLAIMABLE_B },
1358 { "slab_unreclaimable", NR_SLAB_UNRECLAIMABLE_B },
1360 /* The memory events */
1361 { "workingset_refault_anon", WORKINGSET_REFAULT_ANON },
1362 { "workingset_refault_file", WORKINGSET_REFAULT_FILE },
1363 { "workingset_activate_anon", WORKINGSET_ACTIVATE_ANON },
1364 { "workingset_activate_file", WORKINGSET_ACTIVATE_FILE },
1365 { "workingset_restore_anon", WORKINGSET_RESTORE_ANON },
1366 { "workingset_restore_file", WORKINGSET_RESTORE_FILE },
1367 { "workingset_nodereclaim", WORKINGSET_NODERECLAIM },
1370 /* Translate stat items to the correct unit for memory.stat output */
1371 static int memcg_page_state_unit(int item)
1374 case MEMCG_PERCPU_B:
1375 case NR_SLAB_RECLAIMABLE_B:
1376 case NR_SLAB_UNRECLAIMABLE_B:
1377 case WORKINGSET_REFAULT_ANON:
1378 case WORKINGSET_REFAULT_FILE:
1379 case WORKINGSET_ACTIVATE_ANON:
1380 case WORKINGSET_ACTIVATE_FILE:
1381 case WORKINGSET_RESTORE_ANON:
1382 case WORKINGSET_RESTORE_FILE:
1383 case WORKINGSET_NODERECLAIM:
1385 case NR_KERNEL_STACK_KB:
1392 static inline unsigned long memcg_page_state_output(struct mem_cgroup *memcg,
1395 return memcg_page_state(memcg, item) * memcg_page_state_unit(item);
1398 static char *memory_stat_format(struct mem_cgroup *memcg)
1403 seq_buf_init(&s, kmalloc(PAGE_SIZE, GFP_KERNEL), PAGE_SIZE);
1408 * Provide statistics on the state of the memory subsystem as
1409 * well as cumulative event counters that show past behavior.
1411 * This list is ordered following a combination of these gradients:
1412 * 1) generic big picture -> specifics and details
1413 * 2) reflecting userspace activity -> reflecting kernel heuristics
1415 * Current memory state:
1417 cgroup_rstat_flush(memcg->css.cgroup);
1419 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
1422 size = memcg_page_state_output(memcg, memory_stats[i].idx);
1423 seq_buf_printf(&s, "%s %llu\n", memory_stats[i].name, size);
1425 if (unlikely(memory_stats[i].idx == NR_SLAB_UNRECLAIMABLE_B)) {
1426 size += memcg_page_state_output(memcg,
1427 NR_SLAB_RECLAIMABLE_B);
1428 seq_buf_printf(&s, "slab %llu\n", size);
1432 /* Accumulated memory events */
1434 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGFAULT),
1435 memcg_events(memcg, PGFAULT));
1436 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGMAJFAULT),
1437 memcg_events(memcg, PGMAJFAULT));
1438 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGREFILL),
1439 memcg_events(memcg, PGREFILL));
1440 seq_buf_printf(&s, "pgscan %lu\n",
1441 memcg_events(memcg, PGSCAN_KSWAPD) +
1442 memcg_events(memcg, PGSCAN_DIRECT));
1443 seq_buf_printf(&s, "pgsteal %lu\n",
1444 memcg_events(memcg, PGSTEAL_KSWAPD) +
1445 memcg_events(memcg, PGSTEAL_DIRECT));
1446 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGACTIVATE),
1447 memcg_events(memcg, PGACTIVATE));
1448 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGDEACTIVATE),
1449 memcg_events(memcg, PGDEACTIVATE));
1450 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGLAZYFREE),
1451 memcg_events(memcg, PGLAZYFREE));
1452 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGLAZYFREED),
1453 memcg_events(memcg, PGLAZYFREED));
1455 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1456 seq_buf_printf(&s, "%s %lu\n", vm_event_name(THP_FAULT_ALLOC),
1457 memcg_events(memcg, THP_FAULT_ALLOC));
1458 seq_buf_printf(&s, "%s %lu\n", vm_event_name(THP_COLLAPSE_ALLOC),
1459 memcg_events(memcg, THP_COLLAPSE_ALLOC));
1460 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
1462 /* The above should easily fit into one page */
1463 WARN_ON_ONCE(seq_buf_has_overflowed(&s));
1468 #define K(x) ((x) << (PAGE_SHIFT-10))
1470 * mem_cgroup_print_oom_context: Print OOM information relevant to
1471 * memory controller.
1472 * @memcg: The memory cgroup that went over limit
1473 * @p: Task that is going to be killed
1475 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1478 void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p)
1483 pr_cont(",oom_memcg=");
1484 pr_cont_cgroup_path(memcg->css.cgroup);
1486 pr_cont(",global_oom");
1488 pr_cont(",task_memcg=");
1489 pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
1495 * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
1496 * memory controller.
1497 * @memcg: The memory cgroup that went over limit
1499 void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
1503 pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1504 K((u64)page_counter_read(&memcg->memory)),
1505 K((u64)READ_ONCE(memcg->memory.max)), memcg->memory.failcnt);
1506 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1507 pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n",
1508 K((u64)page_counter_read(&memcg->swap)),
1509 K((u64)READ_ONCE(memcg->swap.max)), memcg->swap.failcnt);
1511 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1512 K((u64)page_counter_read(&memcg->memsw)),
1513 K((u64)memcg->memsw.max), memcg->memsw.failcnt);
1514 pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1515 K((u64)page_counter_read(&memcg->kmem)),
1516 K((u64)memcg->kmem.max), memcg->kmem.failcnt);
1519 pr_info("Memory cgroup stats for ");
1520 pr_cont_cgroup_path(memcg->css.cgroup);
1522 buf = memory_stat_format(memcg);
1530 * Return the memory (and swap, if configured) limit for a memcg.
1532 unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg)
1534 unsigned long max = READ_ONCE(memcg->memory.max);
1536 if (cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
1537 if (mem_cgroup_swappiness(memcg))
1538 max += min(READ_ONCE(memcg->swap.max),
1539 (unsigned long)total_swap_pages);
1541 if (mem_cgroup_swappiness(memcg)) {
1542 /* Calculate swap excess capacity from memsw limit */
1543 unsigned long swap = READ_ONCE(memcg->memsw.max) - max;
1545 max += min(swap, (unsigned long)total_swap_pages);
1551 unsigned long mem_cgroup_size(struct mem_cgroup *memcg)
1553 return page_counter_read(&memcg->memory);
1556 static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1559 struct oom_control oc = {
1563 .gfp_mask = gfp_mask,
1568 if (mutex_lock_killable(&oom_lock))
1571 if (mem_cgroup_margin(memcg) >= (1 << order))
1575 * A few threads which were not waiting at mutex_lock_killable() can
1576 * fail to bail out. Therefore, check again after holding oom_lock.
1578 ret = should_force_charge() || out_of_memory(&oc);
1581 mutex_unlock(&oom_lock);
1585 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
1588 unsigned long *total_scanned)
1590 struct mem_cgroup *victim = NULL;
1593 unsigned long excess;
1594 unsigned long nr_scanned;
1595 struct mem_cgroup_reclaim_cookie reclaim = {
1599 excess = soft_limit_excess(root_memcg);
1602 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1607 * If we have not been able to reclaim
1608 * anything, it might because there are
1609 * no reclaimable pages under this hierarchy
1614 * We want to do more targeted reclaim.
1615 * excess >> 2 is not to excessive so as to
1616 * reclaim too much, nor too less that we keep
1617 * coming back to reclaim from this cgroup
1619 if (total >= (excess >> 2) ||
1620 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1625 total += mem_cgroup_shrink_node(victim, gfp_mask, false,
1626 pgdat, &nr_scanned);
1627 *total_scanned += nr_scanned;
1628 if (!soft_limit_excess(root_memcg))
1631 mem_cgroup_iter_break(root_memcg, victim);
1635 #ifdef CONFIG_LOCKDEP
1636 static struct lockdep_map memcg_oom_lock_dep_map = {
1637 .name = "memcg_oom_lock",
1641 static DEFINE_SPINLOCK(memcg_oom_lock);
1644 * Check OOM-Killer is already running under our hierarchy.
1645 * If someone is running, return false.
1647 static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
1649 struct mem_cgroup *iter, *failed = NULL;
1651 spin_lock(&memcg_oom_lock);
1653 for_each_mem_cgroup_tree(iter, memcg) {
1654 if (iter->oom_lock) {
1656 * this subtree of our hierarchy is already locked
1657 * so we cannot give a lock.
1660 mem_cgroup_iter_break(memcg, iter);
1663 iter->oom_lock = true;
1668 * OK, we failed to lock the whole subtree so we have
1669 * to clean up what we set up to the failing subtree
1671 for_each_mem_cgroup_tree(iter, memcg) {
1672 if (iter == failed) {
1673 mem_cgroup_iter_break(memcg, iter);
1676 iter->oom_lock = false;
1679 mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
1681 spin_unlock(&memcg_oom_lock);
1686 static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1688 struct mem_cgroup *iter;
1690 spin_lock(&memcg_oom_lock);
1691 mutex_release(&memcg_oom_lock_dep_map, _RET_IP_);
1692 for_each_mem_cgroup_tree(iter, memcg)
1693 iter->oom_lock = false;
1694 spin_unlock(&memcg_oom_lock);
1697 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1699 struct mem_cgroup *iter;
1701 spin_lock(&memcg_oom_lock);
1702 for_each_mem_cgroup_tree(iter, memcg)
1704 spin_unlock(&memcg_oom_lock);
1707 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1709 struct mem_cgroup *iter;
1712 * Be careful about under_oom underflows because a child memcg
1713 * could have been added after mem_cgroup_mark_under_oom.
1715 spin_lock(&memcg_oom_lock);
1716 for_each_mem_cgroup_tree(iter, memcg)
1717 if (iter->under_oom > 0)
1719 spin_unlock(&memcg_oom_lock);
1722 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1724 struct oom_wait_info {
1725 struct mem_cgroup *memcg;
1726 wait_queue_entry_t wait;
1729 static int memcg_oom_wake_function(wait_queue_entry_t *wait,
1730 unsigned mode, int sync, void *arg)
1732 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
1733 struct mem_cgroup *oom_wait_memcg;
1734 struct oom_wait_info *oom_wait_info;
1736 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1737 oom_wait_memcg = oom_wait_info->memcg;
1739 if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
1740 !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
1742 return autoremove_wake_function(wait, mode, sync, arg);
1745 static void memcg_oom_recover(struct mem_cgroup *memcg)
1748 * For the following lockless ->under_oom test, the only required
1749 * guarantee is that it must see the state asserted by an OOM when
1750 * this function is called as a result of userland actions
1751 * triggered by the notification of the OOM. This is trivially
1752 * achieved by invoking mem_cgroup_mark_under_oom() before
1753 * triggering notification.
1755 if (memcg && memcg->under_oom)
1756 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
1766 static enum oom_status mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
1768 enum oom_status ret;
1771 if (order > PAGE_ALLOC_COSTLY_ORDER)
1774 memcg_memory_event(memcg, MEMCG_OOM);
1777 * We are in the middle of the charge context here, so we
1778 * don't want to block when potentially sitting on a callstack
1779 * that holds all kinds of filesystem and mm locks.
1781 * cgroup1 allows disabling the OOM killer and waiting for outside
1782 * handling until the charge can succeed; remember the context and put
1783 * the task to sleep at the end of the page fault when all locks are
1786 * On the other hand, in-kernel OOM killer allows for an async victim
1787 * memory reclaim (oom_reaper) and that means that we are not solely
1788 * relying on the oom victim to make a forward progress and we can
1789 * invoke the oom killer here.
1791 * Please note that mem_cgroup_out_of_memory might fail to find a
1792 * victim and then we have to bail out from the charge path.
1794 if (memcg->oom_kill_disable) {
1795 if (!current->in_user_fault)
1797 css_get(&memcg->css);
1798 current->memcg_in_oom = memcg;
1799 current->memcg_oom_gfp_mask = mask;
1800 current->memcg_oom_order = order;
1805 mem_cgroup_mark_under_oom(memcg);
1807 locked = mem_cgroup_oom_trylock(memcg);
1810 mem_cgroup_oom_notify(memcg);
1812 mem_cgroup_unmark_under_oom(memcg);
1813 if (mem_cgroup_out_of_memory(memcg, mask, order))
1819 mem_cgroup_oom_unlock(memcg);
1825 * mem_cgroup_oom_synchronize - complete memcg OOM handling
1826 * @handle: actually kill/wait or just clean up the OOM state
1828 * This has to be called at the end of a page fault if the memcg OOM
1829 * handler was enabled.
1831 * Memcg supports userspace OOM handling where failed allocations must
1832 * sleep on a waitqueue until the userspace task resolves the
1833 * situation. Sleeping directly in the charge context with all kinds
1834 * of locks held is not a good idea, instead we remember an OOM state
1835 * in the task and mem_cgroup_oom_synchronize() has to be called at
1836 * the end of the page fault to complete the OOM handling.
1838 * Returns %true if an ongoing memcg OOM situation was detected and
1839 * completed, %false otherwise.
1841 bool mem_cgroup_oom_synchronize(bool handle)
1843 struct mem_cgroup *memcg = current->memcg_in_oom;
1844 struct oom_wait_info owait;
1847 /* OOM is global, do not handle */
1854 owait.memcg = memcg;
1855 owait.wait.flags = 0;
1856 owait.wait.func = memcg_oom_wake_function;
1857 owait.wait.private = current;
1858 INIT_LIST_HEAD(&owait.wait.entry);
1860 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
1861 mem_cgroup_mark_under_oom(memcg);
1863 locked = mem_cgroup_oom_trylock(memcg);
1866 mem_cgroup_oom_notify(memcg);
1868 if (locked && !memcg->oom_kill_disable) {
1869 mem_cgroup_unmark_under_oom(memcg);
1870 finish_wait(&memcg_oom_waitq, &owait.wait);
1871 mem_cgroup_out_of_memory(memcg, current->memcg_oom_gfp_mask,
1872 current->memcg_oom_order);
1875 mem_cgroup_unmark_under_oom(memcg);
1876 finish_wait(&memcg_oom_waitq, &owait.wait);
1880 mem_cgroup_oom_unlock(memcg);
1882 * There is no guarantee that an OOM-lock contender
1883 * sees the wakeups triggered by the OOM kill
1884 * uncharges. Wake any sleepers explicitly.
1886 memcg_oom_recover(memcg);
1889 current->memcg_in_oom = NULL;
1890 css_put(&memcg->css);
1895 * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
1896 * @victim: task to be killed by the OOM killer
1897 * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
1899 * Returns a pointer to a memory cgroup, which has to be cleaned up
1900 * by killing all belonging OOM-killable tasks.
1902 * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
1904 struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim,
1905 struct mem_cgroup *oom_domain)
1907 struct mem_cgroup *oom_group = NULL;
1908 struct mem_cgroup *memcg;
1910 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
1914 oom_domain = root_mem_cgroup;
1918 memcg = mem_cgroup_from_task(victim);
1919 if (memcg == root_mem_cgroup)
1923 * If the victim task has been asynchronously moved to a different
1924 * memory cgroup, we might end up killing tasks outside oom_domain.
1925 * In this case it's better to ignore memory.group.oom.
1927 if (unlikely(!mem_cgroup_is_descendant(memcg, oom_domain)))
1931 * Traverse the memory cgroup hierarchy from the victim task's
1932 * cgroup up to the OOMing cgroup (or root) to find the
1933 * highest-level memory cgroup with oom.group set.
1935 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
1936 if (memcg->oom_group)
1939 if (memcg == oom_domain)
1944 css_get(&oom_group->css);
1951 void mem_cgroup_print_oom_group(struct mem_cgroup *memcg)
1953 pr_info("Tasks in ");
1954 pr_cont_cgroup_path(memcg->css.cgroup);
1955 pr_cont(" are going to be killed due to memory.oom.group set\n");
1959 * lock_page_memcg - lock a page and memcg binding
1962 * This function protects unlocked LRU pages from being moved to
1965 * It ensures lifetime of the locked memcg. Caller is responsible
1966 * for the lifetime of the page.
1968 void lock_page_memcg(struct page *page)
1970 struct page *head = compound_head(page); /* rmap on tail pages */
1971 struct mem_cgroup *memcg;
1972 unsigned long flags;
1975 * The RCU lock is held throughout the transaction. The fast
1976 * path can get away without acquiring the memcg->move_lock
1977 * because page moving starts with an RCU grace period.
1981 if (mem_cgroup_disabled())
1984 memcg = page_memcg(head);
1985 if (unlikely(!memcg))
1988 #ifdef CONFIG_PROVE_LOCKING
1989 local_irq_save(flags);
1990 might_lock(&memcg->move_lock);
1991 local_irq_restore(flags);
1994 if (atomic_read(&memcg->moving_account) <= 0)
1997 spin_lock_irqsave(&memcg->move_lock, flags);
1998 if (memcg != page_memcg(head)) {
1999 spin_unlock_irqrestore(&memcg->move_lock, flags);
2004 * When charge migration first begins, we can have multiple
2005 * critical sections holding the fast-path RCU lock and one
2006 * holding the slowpath move_lock. Track the task who has the
2007 * move_lock for unlock_page_memcg().
2009 memcg->move_lock_task = current;
2010 memcg->move_lock_flags = flags;
2012 EXPORT_SYMBOL(lock_page_memcg);
2014 static void __unlock_page_memcg(struct mem_cgroup *memcg)
2016 if (memcg && memcg->move_lock_task == current) {
2017 unsigned long flags = memcg->move_lock_flags;
2019 memcg->move_lock_task = NULL;
2020 memcg->move_lock_flags = 0;
2022 spin_unlock_irqrestore(&memcg->move_lock, flags);
2029 * unlock_page_memcg - unlock a page and memcg binding
2032 void unlock_page_memcg(struct page *page)
2034 struct page *head = compound_head(page);
2036 __unlock_page_memcg(page_memcg(head));
2038 EXPORT_SYMBOL(unlock_page_memcg);
2041 #ifdef CONFIG_MEMCG_KMEM
2042 struct obj_cgroup *cached_objcg;
2043 struct pglist_data *cached_pgdat;
2044 unsigned int nr_bytes;
2045 int nr_slab_reclaimable_b;
2046 int nr_slab_unreclaimable_b;
2052 struct memcg_stock_pcp {
2053 struct mem_cgroup *cached; /* this never be root cgroup */
2054 unsigned int nr_pages;
2055 struct obj_stock task_obj;
2056 struct obj_stock irq_obj;
2058 struct work_struct work;
2059 unsigned long flags;
2060 #define FLUSHING_CACHED_CHARGE 0
2062 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
2063 static DEFINE_MUTEX(percpu_charge_mutex);
2065 #ifdef CONFIG_MEMCG_KMEM
2066 static void drain_obj_stock(struct obj_stock *stock);
2067 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2068 struct mem_cgroup *root_memcg);
2071 static inline void drain_obj_stock(struct obj_stock *stock)
2074 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2075 struct mem_cgroup *root_memcg)
2082 * Most kmem_cache_alloc() calls are from user context. The irq disable/enable
2083 * sequence used in this case to access content from object stock is slow.
2084 * To optimize for user context access, there are now two object stocks for
2085 * task context and interrupt context access respectively.
2087 * The task context object stock can be accessed by disabling preemption only
2088 * which is cheap in non-preempt kernel. The interrupt context object stock
2089 * can only be accessed after disabling interrupt. User context code can
2090 * access interrupt object stock, but not vice versa.
2092 static inline struct obj_stock *get_obj_stock(unsigned long *pflags)
2094 struct memcg_stock_pcp *stock;
2096 if (likely(in_task())) {
2099 stock = this_cpu_ptr(&memcg_stock);
2100 return &stock->task_obj;
2103 local_irq_save(*pflags);
2104 stock = this_cpu_ptr(&memcg_stock);
2105 return &stock->irq_obj;
2108 static inline void put_obj_stock(unsigned long flags)
2110 if (likely(in_task()))
2113 local_irq_restore(flags);
2117 * consume_stock: Try to consume stocked charge on this cpu.
2118 * @memcg: memcg to consume from.
2119 * @nr_pages: how many pages to charge.
2121 * The charges will only happen if @memcg matches the current cpu's memcg
2122 * stock, and at least @nr_pages are available in that stock. Failure to
2123 * service an allocation will refill the stock.
2125 * returns true if successful, false otherwise.
2127 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2129 struct memcg_stock_pcp *stock;
2130 unsigned long flags;
2133 if (nr_pages > MEMCG_CHARGE_BATCH)
2136 local_irq_save(flags);
2138 stock = this_cpu_ptr(&memcg_stock);
2139 if (memcg == stock->cached && stock->nr_pages >= nr_pages) {
2140 stock->nr_pages -= nr_pages;
2144 local_irq_restore(flags);
2150 * Returns stocks cached in percpu and reset cached information.
2152 static void drain_stock(struct memcg_stock_pcp *stock)
2154 struct mem_cgroup *old = stock->cached;
2159 if (stock->nr_pages) {
2160 page_counter_uncharge(&old->memory, stock->nr_pages);
2161 if (do_memsw_account())
2162 page_counter_uncharge(&old->memsw, stock->nr_pages);
2163 stock->nr_pages = 0;
2167 stock->cached = NULL;
2170 static void drain_local_stock(struct work_struct *dummy)
2172 struct memcg_stock_pcp *stock;
2173 unsigned long flags;
2176 * The only protection from cpu hotplug (memcg_hotplug_cpu_dead) vs.
2177 * drain_stock races is that we always operate on local CPU stock
2178 * here with IRQ disabled
2180 local_irq_save(flags);
2182 stock = this_cpu_ptr(&memcg_stock);
2183 drain_obj_stock(&stock->irq_obj);
2185 drain_obj_stock(&stock->task_obj);
2187 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2189 local_irq_restore(flags);
2193 * Cache charges(val) to local per_cpu area.
2194 * This will be consumed by consume_stock() function, later.
2196 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2198 struct memcg_stock_pcp *stock;
2199 unsigned long flags;
2201 local_irq_save(flags);
2203 stock = this_cpu_ptr(&memcg_stock);
2204 if (stock->cached != memcg) { /* reset if necessary */
2206 css_get(&memcg->css);
2207 stock->cached = memcg;
2209 stock->nr_pages += nr_pages;
2211 if (stock->nr_pages > MEMCG_CHARGE_BATCH)
2214 local_irq_restore(flags);
2218 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2219 * of the hierarchy under it.
2221 static void drain_all_stock(struct mem_cgroup *root_memcg)
2225 /* If someone's already draining, avoid adding running more workers. */
2226 if (!mutex_trylock(&percpu_charge_mutex))
2229 * Notify other cpus that system-wide "drain" is running
2230 * We do not care about races with the cpu hotplug because cpu down
2231 * as well as workers from this path always operate on the local
2232 * per-cpu data. CPU up doesn't touch memcg_stock at all.
2235 for_each_online_cpu(cpu) {
2236 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2237 struct mem_cgroup *memcg;
2241 memcg = stock->cached;
2242 if (memcg && stock->nr_pages &&
2243 mem_cgroup_is_descendant(memcg, root_memcg))
2245 else if (obj_stock_flush_required(stock, root_memcg))
2250 !test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2252 drain_local_stock(&stock->work);
2254 schedule_work_on(cpu, &stock->work);
2258 mutex_unlock(&percpu_charge_mutex);
2261 static int memcg_hotplug_cpu_dead(unsigned int cpu)
2263 struct memcg_stock_pcp *stock;
2265 stock = &per_cpu(memcg_stock, cpu);
2271 static unsigned long reclaim_high(struct mem_cgroup *memcg,
2272 unsigned int nr_pages,
2275 unsigned long nr_reclaimed = 0;
2278 unsigned long pflags;
2280 if (page_counter_read(&memcg->memory) <=
2281 READ_ONCE(memcg->memory.high))
2284 memcg_memory_event(memcg, MEMCG_HIGH);
2286 psi_memstall_enter(&pflags);
2287 nr_reclaimed += try_to_free_mem_cgroup_pages(memcg, nr_pages,
2289 psi_memstall_leave(&pflags);
2290 } while ((memcg = parent_mem_cgroup(memcg)) &&
2291 !mem_cgroup_is_root(memcg));
2293 return nr_reclaimed;
2296 static void high_work_func(struct work_struct *work)
2298 struct mem_cgroup *memcg;
2300 memcg = container_of(work, struct mem_cgroup, high_work);
2301 reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
2305 * Clamp the maximum sleep time per allocation batch to 2 seconds. This is
2306 * enough to still cause a significant slowdown in most cases, while still
2307 * allowing diagnostics and tracing to proceed without becoming stuck.
2309 #define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ)
2312 * When calculating the delay, we use these either side of the exponentiation to
2313 * maintain precision and scale to a reasonable number of jiffies (see the table
2316 * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the
2317 * overage ratio to a delay.
2318 * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down the
2319 * proposed penalty in order to reduce to a reasonable number of jiffies, and
2320 * to produce a reasonable delay curve.
2322 * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a
2323 * reasonable delay curve compared to precision-adjusted overage, not
2324 * penalising heavily at first, but still making sure that growth beyond the
2325 * limit penalises misbehaviour cgroups by slowing them down exponentially. For
2326 * example, with a high of 100 megabytes:
2328 * +-------+------------------------+
2329 * | usage | time to allocate in ms |
2330 * +-------+------------------------+
2352 * +-------+------------------------+
2354 #define MEMCG_DELAY_PRECISION_SHIFT 20
2355 #define MEMCG_DELAY_SCALING_SHIFT 14
2357 static u64 calculate_overage(unsigned long usage, unsigned long high)
2365 * Prevent division by 0 in overage calculation by acting as if
2366 * it was a threshold of 1 page
2368 high = max(high, 1UL);
2370 overage = usage - high;
2371 overage <<= MEMCG_DELAY_PRECISION_SHIFT;
2372 return div64_u64(overage, high);
2375 static u64 mem_find_max_overage(struct mem_cgroup *memcg)
2377 u64 overage, max_overage = 0;
2380 overage = calculate_overage(page_counter_read(&memcg->memory),
2381 READ_ONCE(memcg->memory.high));
2382 max_overage = max(overage, max_overage);
2383 } while ((memcg = parent_mem_cgroup(memcg)) &&
2384 !mem_cgroup_is_root(memcg));
2389 static u64 swap_find_max_overage(struct mem_cgroup *memcg)
2391 u64 overage, max_overage = 0;
2394 overage = calculate_overage(page_counter_read(&memcg->swap),
2395 READ_ONCE(memcg->swap.high));
2397 memcg_memory_event(memcg, MEMCG_SWAP_HIGH);
2398 max_overage = max(overage, max_overage);
2399 } while ((memcg = parent_mem_cgroup(memcg)) &&
2400 !mem_cgroup_is_root(memcg));
2406 * Get the number of jiffies that we should penalise a mischievous cgroup which
2407 * is exceeding its memory.high by checking both it and its ancestors.
2409 static unsigned long calculate_high_delay(struct mem_cgroup *memcg,
2410 unsigned int nr_pages,
2413 unsigned long penalty_jiffies;
2419 * We use overage compared to memory.high to calculate the number of
2420 * jiffies to sleep (penalty_jiffies). Ideally this value should be
2421 * fairly lenient on small overages, and increasingly harsh when the
2422 * memcg in question makes it clear that it has no intention of stopping
2423 * its crazy behaviour, so we exponentially increase the delay based on
2426 penalty_jiffies = max_overage * max_overage * HZ;
2427 penalty_jiffies >>= MEMCG_DELAY_PRECISION_SHIFT;
2428 penalty_jiffies >>= MEMCG_DELAY_SCALING_SHIFT;
2431 * Factor in the task's own contribution to the overage, such that four
2432 * N-sized allocations are throttled approximately the same as one
2433 * 4N-sized allocation.
2435 * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or
2436 * larger the current charge patch is than that.
2438 return penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH;
2442 * Scheduled by try_charge() to be executed from the userland return path
2443 * and reclaims memory over the high limit.
2445 void mem_cgroup_handle_over_high(void)
2447 unsigned long penalty_jiffies;
2448 unsigned long pflags;
2449 unsigned long nr_reclaimed;
2450 unsigned int nr_pages = current->memcg_nr_pages_over_high;
2451 int nr_retries = MAX_RECLAIM_RETRIES;
2452 struct mem_cgroup *memcg;
2453 bool in_retry = false;
2455 if (likely(!nr_pages))
2458 memcg = get_mem_cgroup_from_mm(current->mm);
2459 current->memcg_nr_pages_over_high = 0;
2463 * The allocating task should reclaim at least the batch size, but for
2464 * subsequent retries we only want to do what's necessary to prevent oom
2465 * or breaching resource isolation.
2467 * This is distinct from memory.max or page allocator behaviour because
2468 * memory.high is currently batched, whereas memory.max and the page
2469 * allocator run every time an allocation is made.
2471 nr_reclaimed = reclaim_high(memcg,
2472 in_retry ? SWAP_CLUSTER_MAX : nr_pages,
2476 * memory.high is breached and reclaim is unable to keep up. Throttle
2477 * allocators proactively to slow down excessive growth.
2479 penalty_jiffies = calculate_high_delay(memcg, nr_pages,
2480 mem_find_max_overage(memcg));
2482 penalty_jiffies += calculate_high_delay(memcg, nr_pages,
2483 swap_find_max_overage(memcg));
2486 * Clamp the max delay per usermode return so as to still keep the
2487 * application moving forwards and also permit diagnostics, albeit
2490 penalty_jiffies = min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES);
2493 * Don't sleep if the amount of jiffies this memcg owes us is so low
2494 * that it's not even worth doing, in an attempt to be nice to those who
2495 * go only a small amount over their memory.high value and maybe haven't
2496 * been aggressively reclaimed enough yet.
2498 if (penalty_jiffies <= HZ / 100)
2502 * If reclaim is making forward progress but we're still over
2503 * memory.high, we want to encourage that rather than doing allocator
2506 if (nr_reclaimed || nr_retries--) {
2512 * If we exit early, we're guaranteed to die (since
2513 * schedule_timeout_killable sets TASK_KILLABLE). This means we don't
2514 * need to account for any ill-begotten jiffies to pay them off later.
2516 psi_memstall_enter(&pflags);
2517 schedule_timeout_killable(penalty_jiffies);
2518 psi_memstall_leave(&pflags);
2521 css_put(&memcg->css);
2524 static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask,
2525 unsigned int nr_pages)
2527 unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
2528 int nr_retries = MAX_RECLAIM_RETRIES;
2529 struct mem_cgroup *mem_over_limit;
2530 struct page_counter *counter;
2531 enum oom_status oom_status;
2532 unsigned long nr_reclaimed;
2533 bool may_swap = true;
2534 bool drained = false;
2535 unsigned long pflags;
2538 if (consume_stock(memcg, nr_pages))
2541 if (!do_memsw_account() ||
2542 page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2543 if (page_counter_try_charge(&memcg->memory, batch, &counter))
2545 if (do_memsw_account())
2546 page_counter_uncharge(&memcg->memsw, batch);
2547 mem_over_limit = mem_cgroup_from_counter(counter, memory);
2549 mem_over_limit = mem_cgroup_from_counter(counter, memsw);
2553 if (batch > nr_pages) {
2559 * Memcg doesn't have a dedicated reserve for atomic
2560 * allocations. But like the global atomic pool, we need to
2561 * put the burden of reclaim on regular allocation requests
2562 * and let these go through as privileged allocations.
2564 if (gfp_mask & __GFP_ATOMIC)
2568 * Unlike in global OOM situations, memcg is not in a physical
2569 * memory shortage. Allow dying and OOM-killed tasks to
2570 * bypass the last charges so that they can exit quickly and
2571 * free their memory.
2573 if (unlikely(should_force_charge()))
2577 * Prevent unbounded recursion when reclaim operations need to
2578 * allocate memory. This might exceed the limits temporarily,
2579 * but we prefer facilitating memory reclaim and getting back
2580 * under the limit over triggering OOM kills in these cases.
2582 if (unlikely(current->flags & PF_MEMALLOC))
2585 if (unlikely(task_in_memcg_oom(current)))
2588 if (!gfpflags_allow_blocking(gfp_mask))
2591 memcg_memory_event(mem_over_limit, MEMCG_MAX);
2593 psi_memstall_enter(&pflags);
2594 nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
2595 gfp_mask, may_swap);
2596 psi_memstall_leave(&pflags);
2598 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2602 drain_all_stock(mem_over_limit);
2607 if (gfp_mask & __GFP_NORETRY)
2610 * Even though the limit is exceeded at this point, reclaim
2611 * may have been able to free some pages. Retry the charge
2612 * before killing the task.
2614 * Only for regular pages, though: huge pages are rather
2615 * unlikely to succeed so close to the limit, and we fall back
2616 * to regular pages anyway in case of failure.
2618 if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
2621 * At task move, charge accounts can be doubly counted. So, it's
2622 * better to wait until the end of task_move if something is going on.
2624 if (mem_cgroup_wait_acct_move(mem_over_limit))
2630 if (gfp_mask & __GFP_RETRY_MAYFAIL)
2633 if (fatal_signal_pending(current))
2637 * keep retrying as long as the memcg oom killer is able to make
2638 * a forward progress or bypass the charge if the oom killer
2639 * couldn't make any progress.
2641 oom_status = mem_cgroup_oom(mem_over_limit, gfp_mask,
2642 get_order(nr_pages * PAGE_SIZE));
2643 switch (oom_status) {
2645 nr_retries = MAX_RECLAIM_RETRIES;
2653 if (!(gfp_mask & __GFP_NOFAIL))
2657 * The allocation either can't fail or will lead to more memory
2658 * being freed very soon. Allow memory usage go over the limit
2659 * temporarily by force charging it.
2661 page_counter_charge(&memcg->memory, nr_pages);
2662 if (do_memsw_account())
2663 page_counter_charge(&memcg->memsw, nr_pages);
2668 if (batch > nr_pages)
2669 refill_stock(memcg, batch - nr_pages);
2672 * If the hierarchy is above the normal consumption range, schedule
2673 * reclaim on returning to userland. We can perform reclaim here
2674 * if __GFP_RECLAIM but let's always punt for simplicity and so that
2675 * GFP_KERNEL can consistently be used during reclaim. @memcg is
2676 * not recorded as it most likely matches current's and won't
2677 * change in the meantime. As high limit is checked again before
2678 * reclaim, the cost of mismatch is negligible.
2681 bool mem_high, swap_high;
2683 mem_high = page_counter_read(&memcg->memory) >
2684 READ_ONCE(memcg->memory.high);
2685 swap_high = page_counter_read(&memcg->swap) >
2686 READ_ONCE(memcg->swap.high);
2688 /* Don't bother a random interrupted task */
2689 if (in_interrupt()) {
2691 schedule_work(&memcg->high_work);
2697 if (mem_high || swap_high) {
2699 * The allocating tasks in this cgroup will need to do
2700 * reclaim or be throttled to prevent further growth
2701 * of the memory or swap footprints.
2703 * Target some best-effort fairness between the tasks,
2704 * and distribute reclaim work and delay penalties
2705 * based on how much each task is actually allocating.
2707 current->memcg_nr_pages_over_high += batch;
2708 set_notify_resume(current);
2711 } while ((memcg = parent_mem_cgroup(memcg)));
2716 static inline int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2717 unsigned int nr_pages)
2719 if (mem_cgroup_is_root(memcg))
2722 return try_charge_memcg(memcg, gfp_mask, nr_pages);
2725 #if defined(CONFIG_MEMCG_KMEM) || defined(CONFIG_MMU)
2726 static void cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
2728 if (mem_cgroup_is_root(memcg))
2731 page_counter_uncharge(&memcg->memory, nr_pages);
2732 if (do_memsw_account())
2733 page_counter_uncharge(&memcg->memsw, nr_pages);
2737 static void commit_charge(struct page *page, struct mem_cgroup *memcg)
2739 VM_BUG_ON_PAGE(page_memcg(page), page);
2741 * Any of the following ensures page's memcg stability:
2745 * - lock_page_memcg()
2746 * - exclusive reference
2748 page->memcg_data = (unsigned long)memcg;
2751 static struct mem_cgroup *get_mem_cgroup_from_objcg(struct obj_cgroup *objcg)
2753 struct mem_cgroup *memcg;
2757 memcg = obj_cgroup_memcg(objcg);
2758 if (unlikely(!css_tryget(&memcg->css)))
2765 #ifdef CONFIG_MEMCG_KMEM
2767 * The allocated objcg pointers array is not accounted directly.
2768 * Moreover, it should not come from DMA buffer and is not readily
2769 * reclaimable. So those GFP bits should be masked off.
2771 #define OBJCGS_CLEAR_MASK (__GFP_DMA | __GFP_RECLAIMABLE | __GFP_ACCOUNT)
2773 int memcg_alloc_page_obj_cgroups(struct page *page, struct kmem_cache *s,
2774 gfp_t gfp, bool new_page)
2776 unsigned int objects = objs_per_slab_page(s, page);
2777 unsigned long memcg_data;
2780 gfp &= ~OBJCGS_CLEAR_MASK;
2781 vec = kcalloc_node(objects, sizeof(struct obj_cgroup *), gfp,
2786 memcg_data = (unsigned long) vec | MEMCG_DATA_OBJCGS;
2789 * If the slab page is brand new and nobody can yet access
2790 * it's memcg_data, no synchronization is required and
2791 * memcg_data can be simply assigned.
2793 page->memcg_data = memcg_data;
2794 } else if (cmpxchg(&page->memcg_data, 0, memcg_data)) {
2796 * If the slab page is already in use, somebody can allocate
2797 * and assign obj_cgroups in parallel. In this case the existing
2798 * objcg vector should be reused.
2804 kmemleak_not_leak(vec);
2809 * Returns a pointer to the memory cgroup to which the kernel object is charged.
2811 * A passed kernel object can be a slab object or a generic kernel page, so
2812 * different mechanisms for getting the memory cgroup pointer should be used.
2813 * In certain cases (e.g. kernel stacks or large kmallocs with SLUB) the caller
2814 * can not know for sure how the kernel object is implemented.
2815 * mem_cgroup_from_obj() can be safely used in such cases.
2817 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
2818 * cgroup_mutex, etc.
2820 struct mem_cgroup *mem_cgroup_from_obj(void *p)
2824 if (mem_cgroup_disabled())
2827 page = virt_to_head_page(p);
2830 * Slab objects are accounted individually, not per-page.
2831 * Memcg membership data for each individual object is saved in
2832 * the page->obj_cgroups.
2834 if (page_objcgs_check(page)) {
2835 struct obj_cgroup *objcg;
2838 off = obj_to_index(page->slab_cache, page, p);
2839 objcg = page_objcgs(page)[off];
2841 return obj_cgroup_memcg(objcg);
2847 * page_memcg_check() is used here, because page_has_obj_cgroups()
2848 * check above could fail because the object cgroups vector wasn't set
2849 * at that moment, but it can be set concurrently.
2850 * page_memcg_check(page) will guarantee that a proper memory
2851 * cgroup pointer or NULL will be returned.
2853 return page_memcg_check(page);
2856 __always_inline struct obj_cgroup *get_obj_cgroup_from_current(void)
2858 struct obj_cgroup *objcg = NULL;
2859 struct mem_cgroup *memcg;
2861 if (memcg_kmem_bypass())
2865 if (unlikely(active_memcg()))
2866 memcg = active_memcg();
2868 memcg = mem_cgroup_from_task(current);
2870 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg)) {
2871 objcg = rcu_dereference(memcg->objcg);
2872 if (objcg && obj_cgroup_tryget(objcg))
2881 static int memcg_alloc_cache_id(void)
2886 id = ida_simple_get(&memcg_cache_ida,
2887 0, MEMCG_CACHES_MAX_SIZE, GFP_KERNEL);
2891 if (id < memcg_nr_cache_ids)
2895 * There's no space for the new id in memcg_caches arrays,
2896 * so we have to grow them.
2898 down_write(&memcg_cache_ids_sem);
2900 size = 2 * (id + 1);
2901 if (size < MEMCG_CACHES_MIN_SIZE)
2902 size = MEMCG_CACHES_MIN_SIZE;
2903 else if (size > MEMCG_CACHES_MAX_SIZE)
2904 size = MEMCG_CACHES_MAX_SIZE;
2906 err = memcg_update_all_list_lrus(size);
2908 memcg_nr_cache_ids = size;
2910 up_write(&memcg_cache_ids_sem);
2913 ida_simple_remove(&memcg_cache_ida, id);
2919 static void memcg_free_cache_id(int id)
2921 ida_simple_remove(&memcg_cache_ida, id);
2925 * obj_cgroup_uncharge_pages: uncharge a number of kernel pages from a objcg
2926 * @objcg: object cgroup to uncharge
2927 * @nr_pages: number of pages to uncharge
2929 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
2930 unsigned int nr_pages)
2932 struct mem_cgroup *memcg;
2934 memcg = get_mem_cgroup_from_objcg(objcg);
2936 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
2937 page_counter_uncharge(&memcg->kmem, nr_pages);
2938 refill_stock(memcg, nr_pages);
2940 css_put(&memcg->css);
2944 * obj_cgroup_charge_pages: charge a number of kernel pages to a objcg
2945 * @objcg: object cgroup to charge
2946 * @gfp: reclaim mode
2947 * @nr_pages: number of pages to charge
2949 * Returns 0 on success, an error code on failure.
2951 static int obj_cgroup_charge_pages(struct obj_cgroup *objcg, gfp_t gfp,
2952 unsigned int nr_pages)
2954 struct page_counter *counter;
2955 struct mem_cgroup *memcg;
2958 memcg = get_mem_cgroup_from_objcg(objcg);
2960 ret = try_charge_memcg(memcg, gfp, nr_pages);
2964 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) &&
2965 !page_counter_try_charge(&memcg->kmem, nr_pages, &counter)) {
2968 * Enforce __GFP_NOFAIL allocation because callers are not
2969 * prepared to see failures and likely do not have any failure
2972 if (gfp & __GFP_NOFAIL) {
2973 page_counter_charge(&memcg->kmem, nr_pages);
2976 cancel_charge(memcg, nr_pages);
2980 css_put(&memcg->css);
2986 * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup
2987 * @page: page to charge
2988 * @gfp: reclaim mode
2989 * @order: allocation order
2991 * Returns 0 on success, an error code on failure.
2993 int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
2995 struct obj_cgroup *objcg;
2998 objcg = get_obj_cgroup_from_current();
3000 ret = obj_cgroup_charge_pages(objcg, gfp, 1 << order);
3002 page->memcg_data = (unsigned long)objcg |
3006 obj_cgroup_put(objcg);
3012 * __memcg_kmem_uncharge_page: uncharge a kmem page
3013 * @page: page to uncharge
3014 * @order: allocation order
3016 void __memcg_kmem_uncharge_page(struct page *page, int order)
3018 struct obj_cgroup *objcg;
3019 unsigned int nr_pages = 1 << order;
3021 if (!PageMemcgKmem(page))
3024 objcg = __page_objcg(page);
3025 obj_cgroup_uncharge_pages(objcg, nr_pages);
3026 page->memcg_data = 0;
3027 obj_cgroup_put(objcg);
3030 void mod_objcg_state(struct obj_cgroup *objcg, struct pglist_data *pgdat,
3031 enum node_stat_item idx, int nr)
3033 unsigned long flags;
3034 struct obj_stock *stock = get_obj_stock(&flags);
3038 * Save vmstat data in stock and skip vmstat array update unless
3039 * accumulating over a page of vmstat data or when pgdat or idx
3042 if (stock->cached_objcg != objcg) {
3043 drain_obj_stock(stock);
3044 obj_cgroup_get(objcg);
3045 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3046 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3047 stock->cached_objcg = objcg;
3048 stock->cached_pgdat = pgdat;
3049 } else if (stock->cached_pgdat != pgdat) {
3050 /* Flush the existing cached vmstat data */
3051 struct pglist_data *oldpg = stock->cached_pgdat;
3053 if (stock->nr_slab_reclaimable_b) {
3054 mod_objcg_mlstate(objcg, oldpg, NR_SLAB_RECLAIMABLE_B,
3055 stock->nr_slab_reclaimable_b);
3056 stock->nr_slab_reclaimable_b = 0;
3058 if (stock->nr_slab_unreclaimable_b) {
3059 mod_objcg_mlstate(objcg, oldpg, NR_SLAB_UNRECLAIMABLE_B,
3060 stock->nr_slab_unreclaimable_b);
3061 stock->nr_slab_unreclaimable_b = 0;
3063 stock->cached_pgdat = pgdat;
3066 bytes = (idx == NR_SLAB_RECLAIMABLE_B) ? &stock->nr_slab_reclaimable_b
3067 : &stock->nr_slab_unreclaimable_b;
3069 * Even for large object >= PAGE_SIZE, the vmstat data will still be
3070 * cached locally at least once before pushing it out.
3077 if (abs(*bytes) > PAGE_SIZE) {
3085 mod_objcg_mlstate(objcg, pgdat, idx, nr);
3087 put_obj_stock(flags);
3090 static bool consume_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes)
3092 unsigned long flags;
3093 struct obj_stock *stock = get_obj_stock(&flags);
3096 if (objcg == stock->cached_objcg && stock->nr_bytes >= nr_bytes) {
3097 stock->nr_bytes -= nr_bytes;
3101 put_obj_stock(flags);
3106 static void drain_obj_stock(struct obj_stock *stock)
3108 struct obj_cgroup *old = stock->cached_objcg;
3113 if (stock->nr_bytes) {
3114 unsigned int nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3115 unsigned int nr_bytes = stock->nr_bytes & (PAGE_SIZE - 1);
3118 obj_cgroup_uncharge_pages(old, nr_pages);
3121 * The leftover is flushed to the centralized per-memcg value.
3122 * On the next attempt to refill obj stock it will be moved
3123 * to a per-cpu stock (probably, on an other CPU), see
3124 * refill_obj_stock().
3126 * How often it's flushed is a trade-off between the memory
3127 * limit enforcement accuracy and potential CPU contention,
3128 * so it might be changed in the future.
3130 atomic_add(nr_bytes, &old->nr_charged_bytes);
3131 stock->nr_bytes = 0;
3135 * Flush the vmstat data in current stock
3137 if (stock->nr_slab_reclaimable_b || stock->nr_slab_unreclaimable_b) {
3138 if (stock->nr_slab_reclaimable_b) {
3139 mod_objcg_mlstate(old, stock->cached_pgdat,
3140 NR_SLAB_RECLAIMABLE_B,
3141 stock->nr_slab_reclaimable_b);
3142 stock->nr_slab_reclaimable_b = 0;
3144 if (stock->nr_slab_unreclaimable_b) {
3145 mod_objcg_mlstate(old, stock->cached_pgdat,
3146 NR_SLAB_UNRECLAIMABLE_B,
3147 stock->nr_slab_unreclaimable_b);
3148 stock->nr_slab_unreclaimable_b = 0;
3150 stock->cached_pgdat = NULL;
3153 obj_cgroup_put(old);
3154 stock->cached_objcg = NULL;
3157 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
3158 struct mem_cgroup *root_memcg)
3160 struct mem_cgroup *memcg;
3162 if (in_task() && stock->task_obj.cached_objcg) {
3163 memcg = obj_cgroup_memcg(stock->task_obj.cached_objcg);
3164 if (memcg && mem_cgroup_is_descendant(memcg, root_memcg))
3167 if (stock->irq_obj.cached_objcg) {
3168 memcg = obj_cgroup_memcg(stock->irq_obj.cached_objcg);
3169 if (memcg && mem_cgroup_is_descendant(memcg, root_memcg))
3176 static void refill_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes,
3177 bool allow_uncharge)
3179 unsigned long flags;
3180 struct obj_stock *stock = get_obj_stock(&flags);
3181 unsigned int nr_pages = 0;
3183 if (stock->cached_objcg != objcg) { /* reset if necessary */
3184 drain_obj_stock(stock);
3185 obj_cgroup_get(objcg);
3186 stock->cached_objcg = objcg;
3187 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3188 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3189 allow_uncharge = true; /* Allow uncharge when objcg changes */
3191 stock->nr_bytes += nr_bytes;
3193 if (allow_uncharge && (stock->nr_bytes > PAGE_SIZE)) {
3194 nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3195 stock->nr_bytes &= (PAGE_SIZE - 1);
3198 put_obj_stock(flags);
3201 obj_cgroup_uncharge_pages(objcg, nr_pages);
3204 int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size)
3206 unsigned int nr_pages, nr_bytes;
3209 if (consume_obj_stock(objcg, size))
3213 * In theory, objcg->nr_charged_bytes can have enough
3214 * pre-charged bytes to satisfy the allocation. However,
3215 * flushing objcg->nr_charged_bytes requires two atomic
3216 * operations, and objcg->nr_charged_bytes can't be big.
3217 * The shared objcg->nr_charged_bytes can also become a
3218 * performance bottleneck if all tasks of the same memcg are
3219 * trying to update it. So it's better to ignore it and try
3220 * grab some new pages. The stock's nr_bytes will be flushed to
3221 * objcg->nr_charged_bytes later on when objcg changes.
3223 * The stock's nr_bytes may contain enough pre-charged bytes
3224 * to allow one less page from being charged, but we can't rely
3225 * on the pre-charged bytes not being changed outside of
3226 * consume_obj_stock() or refill_obj_stock(). So ignore those
3227 * pre-charged bytes as well when charging pages. To avoid a
3228 * page uncharge right after a page charge, we set the
3229 * allow_uncharge flag to false when calling refill_obj_stock()
3230 * to temporarily allow the pre-charged bytes to exceed the page
3231 * size limit. The maximum reachable value of the pre-charged
3232 * bytes is (sizeof(object) + PAGE_SIZE - 2) if there is no data
3235 nr_pages = size >> PAGE_SHIFT;
3236 nr_bytes = size & (PAGE_SIZE - 1);
3241 ret = obj_cgroup_charge_pages(objcg, gfp, nr_pages);
3242 if (!ret && nr_bytes)
3243 refill_obj_stock(objcg, PAGE_SIZE - nr_bytes, false);
3248 void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size)
3250 refill_obj_stock(objcg, size, true);
3253 #endif /* CONFIG_MEMCG_KMEM */
3256 * Because page_memcg(head) is not set on tails, set it now.
3258 void split_page_memcg(struct page *head, unsigned int nr)
3260 struct mem_cgroup *memcg = page_memcg(head);
3263 if (mem_cgroup_disabled() || !memcg)
3266 for (i = 1; i < nr; i++)
3267 head[i].memcg_data = head->memcg_data;
3269 if (PageMemcgKmem(head))
3270 obj_cgroup_get_many(__page_objcg(head), nr - 1);
3272 css_get_many(&memcg->css, nr - 1);
3275 #ifdef CONFIG_MEMCG_SWAP
3277 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3278 * @entry: swap entry to be moved
3279 * @from: mem_cgroup which the entry is moved from
3280 * @to: mem_cgroup which the entry is moved to
3282 * It succeeds only when the swap_cgroup's record for this entry is the same
3283 * as the mem_cgroup's id of @from.
3285 * Returns 0 on success, -EINVAL on failure.
3287 * The caller must have charged to @to, IOW, called page_counter_charge() about
3288 * both res and memsw, and called css_get().
3290 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3291 struct mem_cgroup *from, struct mem_cgroup *to)
3293 unsigned short old_id, new_id;
3295 old_id = mem_cgroup_id(from);
3296 new_id = mem_cgroup_id(to);
3298 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3299 mod_memcg_state(from, MEMCG_SWAP, -1);
3300 mod_memcg_state(to, MEMCG_SWAP, 1);
3306 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3307 struct mem_cgroup *from, struct mem_cgroup *to)
3313 static DEFINE_MUTEX(memcg_max_mutex);
3315 static int mem_cgroup_resize_max(struct mem_cgroup *memcg,
3316 unsigned long max, bool memsw)
3318 bool enlarge = false;
3319 bool drained = false;
3321 bool limits_invariant;
3322 struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory;
3325 if (signal_pending(current)) {
3330 mutex_lock(&memcg_max_mutex);
3332 * Make sure that the new limit (memsw or memory limit) doesn't
3333 * break our basic invariant rule memory.max <= memsw.max.
3335 limits_invariant = memsw ? max >= READ_ONCE(memcg->memory.max) :
3336 max <= memcg->memsw.max;
3337 if (!limits_invariant) {
3338 mutex_unlock(&memcg_max_mutex);
3342 if (max > counter->max)
3344 ret = page_counter_set_max(counter, max);
3345 mutex_unlock(&memcg_max_mutex);
3351 drain_all_stock(memcg);
3356 if (!try_to_free_mem_cgroup_pages(memcg, 1,
3357 GFP_KERNEL, !memsw)) {
3363 if (!ret && enlarge)
3364 memcg_oom_recover(memcg);
3369 unsigned long mem_cgroup_soft_limit_reclaim(pg_data_t *pgdat, int order,
3371 unsigned long *total_scanned)
3373 unsigned long nr_reclaimed = 0;
3374 struct mem_cgroup_per_node *mz, *next_mz = NULL;
3375 unsigned long reclaimed;
3377 struct mem_cgroup_tree_per_node *mctz;
3378 unsigned long excess;
3379 unsigned long nr_scanned;
3384 mctz = soft_limit_tree_node(pgdat->node_id);
3387 * Do not even bother to check the largest node if the root
3388 * is empty. Do it lockless to prevent lock bouncing. Races
3389 * are acceptable as soft limit is best effort anyway.
3391 if (!mctz || RB_EMPTY_ROOT(&mctz->rb_root))
3395 * This loop can run a while, specially if mem_cgroup's continuously
3396 * keep exceeding their soft limit and putting the system under
3403 mz = mem_cgroup_largest_soft_limit_node(mctz);
3408 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, pgdat,
3409 gfp_mask, &nr_scanned);
3410 nr_reclaimed += reclaimed;
3411 *total_scanned += nr_scanned;
3412 spin_lock_irq(&mctz->lock);
3413 __mem_cgroup_remove_exceeded(mz, mctz);
3416 * If we failed to reclaim anything from this memory cgroup
3417 * it is time to move on to the next cgroup
3421 next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
3423 excess = soft_limit_excess(mz->memcg);
3425 * One school of thought says that we should not add
3426 * back the node to the tree if reclaim returns 0.
3427 * But our reclaim could return 0, simply because due
3428 * to priority we are exposing a smaller subset of
3429 * memory to reclaim from. Consider this as a longer
3432 /* If excess == 0, no tree ops */
3433 __mem_cgroup_insert_exceeded(mz, mctz, excess);
3434 spin_unlock_irq(&mctz->lock);
3435 css_put(&mz->memcg->css);
3438 * Could not reclaim anything and there are no more
3439 * mem cgroups to try or we seem to be looping without
3440 * reclaiming anything.
3442 if (!nr_reclaimed &&
3444 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3446 } while (!nr_reclaimed);
3448 css_put(&next_mz->memcg->css);
3449 return nr_reclaimed;
3453 * Reclaims as many pages from the given memcg as possible.
3455 * Caller is responsible for holding css reference for memcg.
3457 static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
3459 int nr_retries = MAX_RECLAIM_RETRIES;
3461 /* we call try-to-free pages for make this cgroup empty */
3462 lru_add_drain_all();
3464 drain_all_stock(memcg);
3466 /* try to free all pages in this cgroup */
3467 while (nr_retries && page_counter_read(&memcg->memory)) {
3470 if (signal_pending(current))
3473 progress = try_to_free_mem_cgroup_pages(memcg, 1,
3477 /* maybe some writeback is necessary */
3478 congestion_wait(BLK_RW_ASYNC, HZ/10);
3486 static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
3487 char *buf, size_t nbytes,
3490 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3492 if (mem_cgroup_is_root(memcg))
3494 return mem_cgroup_force_empty(memcg) ?: nbytes;
3497 static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
3503 static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
3504 struct cftype *cft, u64 val)
3509 pr_warn_once("Non-hierarchical mode is deprecated. "
3510 "Please report your usecase to linux-mm@kvack.org if you "
3511 "depend on this functionality.\n");
3516 static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3520 if (mem_cgroup_is_root(memcg)) {
3521 /* mem_cgroup_threshold() calls here from irqsafe context */
3522 cgroup_rstat_flush_irqsafe(memcg->css.cgroup);
3523 val = memcg_page_state(memcg, NR_FILE_PAGES) +
3524 memcg_page_state(memcg, NR_ANON_MAPPED);
3526 val += memcg_page_state(memcg, MEMCG_SWAP);
3529 val = page_counter_read(&memcg->memory);
3531 val = page_counter_read(&memcg->memsw);
3544 static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
3547 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3548 struct page_counter *counter;
3550 switch (MEMFILE_TYPE(cft->private)) {
3552 counter = &memcg->memory;
3555 counter = &memcg->memsw;
3558 counter = &memcg->kmem;
3561 counter = &memcg->tcpmem;
3567 switch (MEMFILE_ATTR(cft->private)) {
3569 if (counter == &memcg->memory)
3570 return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
3571 if (counter == &memcg->memsw)
3572 return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
3573 return (u64)page_counter_read(counter) * PAGE_SIZE;
3575 return (u64)counter->max * PAGE_SIZE;
3577 return (u64)counter->watermark * PAGE_SIZE;
3579 return counter->failcnt;
3580 case RES_SOFT_LIMIT:
3581 return (u64)memcg->soft_limit * PAGE_SIZE;
3587 #ifdef CONFIG_MEMCG_KMEM
3588 static int memcg_online_kmem(struct mem_cgroup *memcg)
3590 struct obj_cgroup *objcg;
3593 if (cgroup_memory_nokmem)
3596 BUG_ON(memcg->kmemcg_id >= 0);
3597 BUG_ON(memcg->kmem_state);
3599 memcg_id = memcg_alloc_cache_id();
3603 objcg = obj_cgroup_alloc();
3605 memcg_free_cache_id(memcg_id);
3608 objcg->memcg = memcg;
3609 rcu_assign_pointer(memcg->objcg, objcg);
3611 static_branch_enable(&memcg_kmem_enabled_key);
3613 memcg->kmemcg_id = memcg_id;
3614 memcg->kmem_state = KMEM_ONLINE;
3619 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3621 struct cgroup_subsys_state *css;
3622 struct mem_cgroup *parent, *child;
3625 if (memcg->kmem_state != KMEM_ONLINE)
3628 memcg->kmem_state = KMEM_ALLOCATED;
3630 parent = parent_mem_cgroup(memcg);
3632 parent = root_mem_cgroup;
3634 memcg_reparent_objcgs(memcg, parent);
3636 kmemcg_id = memcg->kmemcg_id;
3637 BUG_ON(kmemcg_id < 0);
3640 * Change kmemcg_id of this cgroup and all its descendants to the
3641 * parent's id, and then move all entries from this cgroup's list_lrus
3642 * to ones of the parent. After we have finished, all list_lrus
3643 * corresponding to this cgroup are guaranteed to remain empty. The
3644 * ordering is imposed by list_lru_node->lock taken by
3645 * memcg_drain_all_list_lrus().
3647 rcu_read_lock(); /* can be called from css_free w/o cgroup_mutex */
3648 css_for_each_descendant_pre(css, &memcg->css) {
3649 child = mem_cgroup_from_css(css);
3650 BUG_ON(child->kmemcg_id != kmemcg_id);
3651 child->kmemcg_id = parent->kmemcg_id;
3655 memcg_drain_all_list_lrus(kmemcg_id, parent);
3657 memcg_free_cache_id(kmemcg_id);
3660 static void memcg_free_kmem(struct mem_cgroup *memcg)
3662 /* css_alloc() failed, offlining didn't happen */
3663 if (unlikely(memcg->kmem_state == KMEM_ONLINE))
3664 memcg_offline_kmem(memcg);
3667 static int memcg_online_kmem(struct mem_cgroup *memcg)
3671 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3674 static void memcg_free_kmem(struct mem_cgroup *memcg)
3677 #endif /* CONFIG_MEMCG_KMEM */
3679 static int memcg_update_kmem_max(struct mem_cgroup *memcg,
3684 mutex_lock(&memcg_max_mutex);
3685 ret = page_counter_set_max(&memcg->kmem, max);
3686 mutex_unlock(&memcg_max_mutex);
3690 static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max)
3694 mutex_lock(&memcg_max_mutex);
3696 ret = page_counter_set_max(&memcg->tcpmem, max);
3700 if (!memcg->tcpmem_active) {
3702 * The active flag needs to be written after the static_key
3703 * update. This is what guarantees that the socket activation
3704 * function is the last one to run. See mem_cgroup_sk_alloc()
3705 * for details, and note that we don't mark any socket as
3706 * belonging to this memcg until that flag is up.
3708 * We need to do this, because static_keys will span multiple
3709 * sites, but we can't control their order. If we mark a socket
3710 * as accounted, but the accounting functions are not patched in
3711 * yet, we'll lose accounting.
3713 * We never race with the readers in mem_cgroup_sk_alloc(),
3714 * because when this value change, the code to process it is not
3717 static_branch_inc(&memcg_sockets_enabled_key);
3718 memcg->tcpmem_active = true;
3721 mutex_unlock(&memcg_max_mutex);
3726 * The user of this function is...
3729 static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
3730 char *buf, size_t nbytes, loff_t off)
3732 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3733 unsigned long nr_pages;
3736 buf = strstrip(buf);
3737 ret = page_counter_memparse(buf, "-1", &nr_pages);
3741 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3743 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3747 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3749 ret = mem_cgroup_resize_max(memcg, nr_pages, false);
3752 ret = mem_cgroup_resize_max(memcg, nr_pages, true);
3755 pr_warn_once("kmem.limit_in_bytes is deprecated and will be removed. "
3756 "Please report your usecase to linux-mm@kvack.org if you "
3757 "depend on this functionality.\n");
3758 ret = memcg_update_kmem_max(memcg, nr_pages);
3761 ret = memcg_update_tcp_max(memcg, nr_pages);
3765 case RES_SOFT_LIMIT:
3766 memcg->soft_limit = nr_pages;
3770 return ret ?: nbytes;
3773 static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
3774 size_t nbytes, loff_t off)
3776 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3777 struct page_counter *counter;
3779 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3781 counter = &memcg->memory;
3784 counter = &memcg->memsw;
3787 counter = &memcg->kmem;
3790 counter = &memcg->tcpmem;
3796 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3798 page_counter_reset_watermark(counter);
3801 counter->failcnt = 0;
3810 static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
3813 return mem_cgroup_from_css(css)->move_charge_at_immigrate;
3817 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3818 struct cftype *cft, u64 val)
3820 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3822 if (val & ~MOVE_MASK)
3826 * No kind of locking is needed in here, because ->can_attach() will
3827 * check this value once in the beginning of the process, and then carry
3828 * on with stale data. This means that changes to this value will only
3829 * affect task migrations starting after the change.
3831 memcg->move_charge_at_immigrate = val;
3835 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3836 struct cftype *cft, u64 val)
3844 #define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE))
3845 #define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON))
3846 #define LRU_ALL ((1 << NR_LRU_LISTS) - 1)
3848 static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
3849 int nid, unsigned int lru_mask, bool tree)
3851 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
3852 unsigned long nr = 0;
3855 VM_BUG_ON((unsigned)nid >= nr_node_ids);
3858 if (!(BIT(lru) & lru_mask))
3861 nr += lruvec_page_state(lruvec, NR_LRU_BASE + lru);
3863 nr += lruvec_page_state_local(lruvec, NR_LRU_BASE + lru);
3868 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
3869 unsigned int lru_mask,
3872 unsigned long nr = 0;
3876 if (!(BIT(lru) & lru_mask))
3879 nr += memcg_page_state(memcg, NR_LRU_BASE + lru);
3881 nr += memcg_page_state_local(memcg, NR_LRU_BASE + lru);
3886 static int memcg_numa_stat_show(struct seq_file *m, void *v)
3890 unsigned int lru_mask;
3893 static const struct numa_stat stats[] = {
3894 { "total", LRU_ALL },
3895 { "file", LRU_ALL_FILE },
3896 { "anon", LRU_ALL_ANON },
3897 { "unevictable", BIT(LRU_UNEVICTABLE) },
3899 const struct numa_stat *stat;
3901 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
3903 cgroup_rstat_flush(memcg->css.cgroup);
3905 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
3906 seq_printf(m, "%s=%lu", stat->name,
3907 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
3909 for_each_node_state(nid, N_MEMORY)
3910 seq_printf(m, " N%d=%lu", nid,
3911 mem_cgroup_node_nr_lru_pages(memcg, nid,
3912 stat->lru_mask, false));
3916 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
3918 seq_printf(m, "hierarchical_%s=%lu", stat->name,
3919 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
3921 for_each_node_state(nid, N_MEMORY)
3922 seq_printf(m, " N%d=%lu", nid,
3923 mem_cgroup_node_nr_lru_pages(memcg, nid,
3924 stat->lru_mask, true));
3930 #endif /* CONFIG_NUMA */
3932 static const unsigned int memcg1_stats[] = {
3935 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3945 static const char *const memcg1_stat_names[] = {
3948 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3958 /* Universal VM events cgroup1 shows, original sort order */
3959 static const unsigned int memcg1_events[] = {
3966 static int memcg_stat_show(struct seq_file *m, void *v)
3968 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
3969 unsigned long memory, memsw;
3970 struct mem_cgroup *mi;
3973 BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats));
3975 cgroup_rstat_flush(memcg->css.cgroup);
3977 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
3980 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
3982 nr = memcg_page_state_local(memcg, memcg1_stats[i]);
3983 seq_printf(m, "%s %lu\n", memcg1_stat_names[i], nr * PAGE_SIZE);
3986 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
3987 seq_printf(m, "%s %lu\n", vm_event_name(memcg1_events[i]),
3988 memcg_events_local(memcg, memcg1_events[i]));
3990 for (i = 0; i < NR_LRU_LISTS; i++)
3991 seq_printf(m, "%s %lu\n", lru_list_name(i),
3992 memcg_page_state_local(memcg, NR_LRU_BASE + i) *
3995 /* Hierarchical information */
3996 memory = memsw = PAGE_COUNTER_MAX;
3997 for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
3998 memory = min(memory, READ_ONCE(mi->memory.max));
3999 memsw = min(memsw, READ_ONCE(mi->memsw.max));
4001 seq_printf(m, "hierarchical_memory_limit %llu\n",
4002 (u64)memory * PAGE_SIZE);
4003 if (do_memsw_account())
4004 seq_printf(m, "hierarchical_memsw_limit %llu\n",
4005 (u64)memsw * PAGE_SIZE);
4007 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
4010 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
4012 nr = memcg_page_state(memcg, memcg1_stats[i]);
4013 seq_printf(m, "total_%s %llu\n", memcg1_stat_names[i],
4014 (u64)nr * PAGE_SIZE);
4017 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
4018 seq_printf(m, "total_%s %llu\n",
4019 vm_event_name(memcg1_events[i]),
4020 (u64)memcg_events(memcg, memcg1_events[i]));
4022 for (i = 0; i < NR_LRU_LISTS; i++)
4023 seq_printf(m, "total_%s %llu\n", lru_list_name(i),
4024 (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
4027 #ifdef CONFIG_DEBUG_VM
4030 struct mem_cgroup_per_node *mz;
4031 unsigned long anon_cost = 0;
4032 unsigned long file_cost = 0;
4034 for_each_online_pgdat(pgdat) {
4035 mz = memcg->nodeinfo[pgdat->node_id];
4037 anon_cost += mz->lruvec.anon_cost;
4038 file_cost += mz->lruvec.file_cost;
4040 seq_printf(m, "anon_cost %lu\n", anon_cost);
4041 seq_printf(m, "file_cost %lu\n", file_cost);
4048 static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
4051 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4053 return mem_cgroup_swappiness(memcg);
4056 static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
4057 struct cftype *cft, u64 val)
4059 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4064 if (!mem_cgroup_is_root(memcg))
4065 memcg->swappiness = val;
4067 vm_swappiness = val;
4072 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4074 struct mem_cgroup_threshold_ary *t;
4075 unsigned long usage;
4080 t = rcu_dereference(memcg->thresholds.primary);
4082 t = rcu_dereference(memcg->memsw_thresholds.primary);
4087 usage = mem_cgroup_usage(memcg, swap);
4090 * current_threshold points to threshold just below or equal to usage.
4091 * If it's not true, a threshold was crossed after last
4092 * call of __mem_cgroup_threshold().
4094 i = t->current_threshold;
4097 * Iterate backward over array of thresholds starting from
4098 * current_threshold and check if a threshold is crossed.
4099 * If none of thresholds below usage is crossed, we read
4100 * only one element of the array here.
4102 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4103 eventfd_signal(t->entries[i].eventfd, 1);
4105 /* i = current_threshold + 1 */
4109 * Iterate forward over array of thresholds starting from
4110 * current_threshold+1 and check if a threshold is crossed.
4111 * If none of thresholds above usage is crossed, we read
4112 * only one element of the array here.
4114 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4115 eventfd_signal(t->entries[i].eventfd, 1);
4117 /* Update current_threshold */
4118 t->current_threshold = i - 1;
4123 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4126 __mem_cgroup_threshold(memcg, false);
4127 if (do_memsw_account())
4128 __mem_cgroup_threshold(memcg, true);
4130 memcg = parent_mem_cgroup(memcg);
4134 static int compare_thresholds(const void *a, const void *b)
4136 const struct mem_cgroup_threshold *_a = a;
4137 const struct mem_cgroup_threshold *_b = b;
4139 if (_a->threshold > _b->threshold)
4142 if (_a->threshold < _b->threshold)
4148 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
4150 struct mem_cgroup_eventfd_list *ev;
4152 spin_lock(&memcg_oom_lock);
4154 list_for_each_entry(ev, &memcg->oom_notify, list)
4155 eventfd_signal(ev->eventfd, 1);
4157 spin_unlock(&memcg_oom_lock);
4161 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
4163 struct mem_cgroup *iter;
4165 for_each_mem_cgroup_tree(iter, memcg)
4166 mem_cgroup_oom_notify_cb(iter);
4169 static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4170 struct eventfd_ctx *eventfd, const char *args, enum res_type type)
4172 struct mem_cgroup_thresholds *thresholds;
4173 struct mem_cgroup_threshold_ary *new;
4174 unsigned long threshold;
4175 unsigned long usage;
4178 ret = page_counter_memparse(args, "-1", &threshold);
4182 mutex_lock(&memcg->thresholds_lock);
4185 thresholds = &memcg->thresholds;
4186 usage = mem_cgroup_usage(memcg, false);
4187 } else if (type == _MEMSWAP) {
4188 thresholds = &memcg->memsw_thresholds;
4189 usage = mem_cgroup_usage(memcg, true);
4193 /* Check if a threshold crossed before adding a new one */
4194 if (thresholds->primary)
4195 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4197 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4199 /* Allocate memory for new array of thresholds */
4200 new = kmalloc(struct_size(new, entries, size), GFP_KERNEL);
4207 /* Copy thresholds (if any) to new array */
4208 if (thresholds->primary)
4209 memcpy(new->entries, thresholds->primary->entries,
4210 flex_array_size(new, entries, size - 1));
4212 /* Add new threshold */
4213 new->entries[size - 1].eventfd = eventfd;
4214 new->entries[size - 1].threshold = threshold;
4216 /* Sort thresholds. Registering of new threshold isn't time-critical */
4217 sort(new->entries, size, sizeof(*new->entries),
4218 compare_thresholds, NULL);
4220 /* Find current threshold */
4221 new->current_threshold = -1;
4222 for (i = 0; i < size; i++) {
4223 if (new->entries[i].threshold <= usage) {
4225 * new->current_threshold will not be used until
4226 * rcu_assign_pointer(), so it's safe to increment
4229 ++new->current_threshold;
4234 /* Free old spare buffer and save old primary buffer as spare */
4235 kfree(thresholds->spare);
4236 thresholds->spare = thresholds->primary;
4238 rcu_assign_pointer(thresholds->primary, new);
4240 /* To be sure that nobody uses thresholds */
4244 mutex_unlock(&memcg->thresholds_lock);
4249 static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4250 struct eventfd_ctx *eventfd, const char *args)
4252 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
4255 static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
4256 struct eventfd_ctx *eventfd, const char *args)
4258 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
4261 static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4262 struct eventfd_ctx *eventfd, enum res_type type)
4264 struct mem_cgroup_thresholds *thresholds;
4265 struct mem_cgroup_threshold_ary *new;
4266 unsigned long usage;
4267 int i, j, size, entries;
4269 mutex_lock(&memcg->thresholds_lock);
4272 thresholds = &memcg->thresholds;
4273 usage = mem_cgroup_usage(memcg, false);
4274 } else if (type == _MEMSWAP) {
4275 thresholds = &memcg->memsw_thresholds;
4276 usage = mem_cgroup_usage(memcg, true);
4280 if (!thresholds->primary)
4283 /* Check if a threshold crossed before removing */
4284 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4286 /* Calculate new number of threshold */
4288 for (i = 0; i < thresholds->primary->size; i++) {
4289 if (thresholds->primary->entries[i].eventfd != eventfd)
4295 new = thresholds->spare;
4297 /* If no items related to eventfd have been cleared, nothing to do */
4301 /* Set thresholds array to NULL if we don't have thresholds */
4310 /* Copy thresholds and find current threshold */
4311 new->current_threshold = -1;
4312 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4313 if (thresholds->primary->entries[i].eventfd == eventfd)
4316 new->entries[j] = thresholds->primary->entries[i];
4317 if (new->entries[j].threshold <= usage) {
4319 * new->current_threshold will not be used
4320 * until rcu_assign_pointer(), so it's safe to increment
4323 ++new->current_threshold;
4329 /* Swap primary and spare array */
4330 thresholds->spare = thresholds->primary;
4332 rcu_assign_pointer(thresholds->primary, new);
4334 /* To be sure that nobody uses thresholds */
4337 /* If all events are unregistered, free the spare array */
4339 kfree(thresholds->spare);
4340 thresholds->spare = NULL;
4343 mutex_unlock(&memcg->thresholds_lock);
4346 static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4347 struct eventfd_ctx *eventfd)
4349 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
4352 static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4353 struct eventfd_ctx *eventfd)
4355 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
4358 static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
4359 struct eventfd_ctx *eventfd, const char *args)
4361 struct mem_cgroup_eventfd_list *event;
4363 event = kmalloc(sizeof(*event), GFP_KERNEL);
4367 spin_lock(&memcg_oom_lock);
4369 event->eventfd = eventfd;
4370 list_add(&event->list, &memcg->oom_notify);
4372 /* already in OOM ? */
4373 if (memcg->under_oom)
4374 eventfd_signal(eventfd, 1);
4375 spin_unlock(&memcg_oom_lock);
4380 static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
4381 struct eventfd_ctx *eventfd)
4383 struct mem_cgroup_eventfd_list *ev, *tmp;
4385 spin_lock(&memcg_oom_lock);
4387 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
4388 if (ev->eventfd == eventfd) {
4389 list_del(&ev->list);
4394 spin_unlock(&memcg_oom_lock);
4397 static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
4399 struct mem_cgroup *memcg = mem_cgroup_from_seq(sf);
4401 seq_printf(sf, "oom_kill_disable %d\n", memcg->oom_kill_disable);
4402 seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
4403 seq_printf(sf, "oom_kill %lu\n",
4404 atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
4408 static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
4409 struct cftype *cft, u64 val)
4411 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4413 /* cannot set to root cgroup and only 0 and 1 are allowed */
4414 if (mem_cgroup_is_root(memcg) || !((val == 0) || (val == 1)))
4417 memcg->oom_kill_disable = val;
4419 memcg_oom_recover(memcg);
4424 #ifdef CONFIG_CGROUP_WRITEBACK
4426 #include <trace/events/writeback.h>
4428 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4430 return wb_domain_init(&memcg->cgwb_domain, gfp);
4433 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4435 wb_domain_exit(&memcg->cgwb_domain);
4438 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4440 wb_domain_size_changed(&memcg->cgwb_domain);
4443 struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
4445 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4447 if (!memcg->css.parent)
4450 return &memcg->cgwb_domain;
4454 * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
4455 * @wb: bdi_writeback in question
4456 * @pfilepages: out parameter for number of file pages
4457 * @pheadroom: out parameter for number of allocatable pages according to memcg
4458 * @pdirty: out parameter for number of dirty pages
4459 * @pwriteback: out parameter for number of pages under writeback
4461 * Determine the numbers of file, headroom, dirty, and writeback pages in
4462 * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom
4463 * is a bit more involved.
4465 * A memcg's headroom is "min(max, high) - used". In the hierarchy, the
4466 * headroom is calculated as the lowest headroom of itself and the
4467 * ancestors. Note that this doesn't consider the actual amount of
4468 * available memory in the system. The caller should further cap
4469 * *@pheadroom accordingly.
4471 void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
4472 unsigned long *pheadroom, unsigned long *pdirty,
4473 unsigned long *pwriteback)
4475 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4476 struct mem_cgroup *parent;
4478 cgroup_rstat_flush_irqsafe(memcg->css.cgroup);
4480 *pdirty = memcg_page_state(memcg, NR_FILE_DIRTY);
4481 *pwriteback = memcg_page_state(memcg, NR_WRITEBACK);
4482 *pfilepages = memcg_page_state(memcg, NR_INACTIVE_FILE) +
4483 memcg_page_state(memcg, NR_ACTIVE_FILE);
4485 *pheadroom = PAGE_COUNTER_MAX;
4486 while ((parent = parent_mem_cgroup(memcg))) {
4487 unsigned long ceiling = min(READ_ONCE(memcg->memory.max),
4488 READ_ONCE(memcg->memory.high));
4489 unsigned long used = page_counter_read(&memcg->memory);
4491 *pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
4497 * Foreign dirty flushing
4499 * There's an inherent mismatch between memcg and writeback. The former
4500 * tracks ownership per-page while the latter per-inode. This was a
4501 * deliberate design decision because honoring per-page ownership in the
4502 * writeback path is complicated, may lead to higher CPU and IO overheads
4503 * and deemed unnecessary given that write-sharing an inode across
4504 * different cgroups isn't a common use-case.
4506 * Combined with inode majority-writer ownership switching, this works well
4507 * enough in most cases but there are some pathological cases. For
4508 * example, let's say there are two cgroups A and B which keep writing to
4509 * different but confined parts of the same inode. B owns the inode and
4510 * A's memory is limited far below B's. A's dirty ratio can rise enough to
4511 * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
4512 * triggering background writeback. A will be slowed down without a way to
4513 * make writeback of the dirty pages happen.
4515 * Conditions like the above can lead to a cgroup getting repeatedly and
4516 * severely throttled after making some progress after each
4517 * dirty_expire_interval while the underlying IO device is almost
4520 * Solving this problem completely requires matching the ownership tracking
4521 * granularities between memcg and writeback in either direction. However,
4522 * the more egregious behaviors can be avoided by simply remembering the
4523 * most recent foreign dirtying events and initiating remote flushes on
4524 * them when local writeback isn't enough to keep the memory clean enough.
4526 * The following two functions implement such mechanism. When a foreign
4527 * page - a page whose memcg and writeback ownerships don't match - is
4528 * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
4529 * bdi_writeback on the page owning memcg. When balance_dirty_pages()
4530 * decides that the memcg needs to sleep due to high dirty ratio, it calls
4531 * mem_cgroup_flush_foreign() which queues writeback on the recorded
4532 * foreign bdi_writebacks which haven't expired. Both the numbers of
4533 * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
4534 * limited to MEMCG_CGWB_FRN_CNT.
4536 * The mechanism only remembers IDs and doesn't hold any object references.
4537 * As being wrong occasionally doesn't matter, updates and accesses to the
4538 * records are lockless and racy.
4540 void mem_cgroup_track_foreign_dirty_slowpath(struct page *page,
4541 struct bdi_writeback *wb)
4543 struct mem_cgroup *memcg = page_memcg(page);
4544 struct memcg_cgwb_frn *frn;
4545 u64 now = get_jiffies_64();
4546 u64 oldest_at = now;
4550 trace_track_foreign_dirty(page, wb);
4553 * Pick the slot to use. If there is already a slot for @wb, keep
4554 * using it. If not replace the oldest one which isn't being
4557 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4558 frn = &memcg->cgwb_frn[i];
4559 if (frn->bdi_id == wb->bdi->id &&
4560 frn->memcg_id == wb->memcg_css->id)
4562 if (time_before64(frn->at, oldest_at) &&
4563 atomic_read(&frn->done.cnt) == 1) {
4565 oldest_at = frn->at;
4569 if (i < MEMCG_CGWB_FRN_CNT) {
4571 * Re-using an existing one. Update timestamp lazily to
4572 * avoid making the cacheline hot. We want them to be
4573 * reasonably up-to-date and significantly shorter than
4574 * dirty_expire_interval as that's what expires the record.
4575 * Use the shorter of 1s and dirty_expire_interval / 8.
4577 unsigned long update_intv =
4578 min_t(unsigned long, HZ,
4579 msecs_to_jiffies(dirty_expire_interval * 10) / 8);
4581 if (time_before64(frn->at, now - update_intv))
4583 } else if (oldest >= 0) {
4584 /* replace the oldest free one */
4585 frn = &memcg->cgwb_frn[oldest];
4586 frn->bdi_id = wb->bdi->id;
4587 frn->memcg_id = wb->memcg_css->id;
4592 /* issue foreign writeback flushes for recorded foreign dirtying events */
4593 void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
4595 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4596 unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
4597 u64 now = jiffies_64;
4600 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4601 struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
4604 * If the record is older than dirty_expire_interval,
4605 * writeback on it has already started. No need to kick it
4606 * off again. Also, don't start a new one if there's
4607 * already one in flight.
4609 if (time_after64(frn->at, now - intv) &&
4610 atomic_read(&frn->done.cnt) == 1) {
4612 trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
4613 cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id,
4614 WB_REASON_FOREIGN_FLUSH,
4620 #else /* CONFIG_CGROUP_WRITEBACK */
4622 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4627 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4631 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4635 #endif /* CONFIG_CGROUP_WRITEBACK */
4638 * DO NOT USE IN NEW FILES.
4640 * "cgroup.event_control" implementation.
4642 * This is way over-engineered. It tries to support fully configurable
4643 * events for each user. Such level of flexibility is completely
4644 * unnecessary especially in the light of the planned unified hierarchy.
4646 * Please deprecate this and replace with something simpler if at all
4651 * Unregister event and free resources.
4653 * Gets called from workqueue.
4655 static void memcg_event_remove(struct work_struct *work)
4657 struct mem_cgroup_event *event =
4658 container_of(work, struct mem_cgroup_event, remove);
4659 struct mem_cgroup *memcg = event->memcg;
4661 remove_wait_queue(event->wqh, &event->wait);
4663 event->unregister_event(memcg, event->eventfd);
4665 /* Notify userspace the event is going away. */
4666 eventfd_signal(event->eventfd, 1);
4668 eventfd_ctx_put(event->eventfd);
4670 css_put(&memcg->css);
4674 * Gets called on EPOLLHUP on eventfd when user closes it.
4676 * Called with wqh->lock held and interrupts disabled.
4678 static int memcg_event_wake(wait_queue_entry_t *wait, unsigned mode,
4679 int sync, void *key)
4681 struct mem_cgroup_event *event =
4682 container_of(wait, struct mem_cgroup_event, wait);
4683 struct mem_cgroup *memcg = event->memcg;
4684 __poll_t flags = key_to_poll(key);
4686 if (flags & EPOLLHUP) {
4688 * If the event has been detached at cgroup removal, we
4689 * can simply return knowing the other side will cleanup
4692 * We can't race against event freeing since the other
4693 * side will require wqh->lock via remove_wait_queue(),
4696 spin_lock(&memcg->event_list_lock);
4697 if (!list_empty(&event->list)) {
4698 list_del_init(&event->list);
4700 * We are in atomic context, but cgroup_event_remove()
4701 * may sleep, so we have to call it in workqueue.
4703 schedule_work(&event->remove);
4705 spin_unlock(&memcg->event_list_lock);
4711 static void memcg_event_ptable_queue_proc(struct file *file,
4712 wait_queue_head_t *wqh, poll_table *pt)
4714 struct mem_cgroup_event *event =
4715 container_of(pt, struct mem_cgroup_event, pt);
4718 add_wait_queue(wqh, &event->wait);
4722 * DO NOT USE IN NEW FILES.
4724 * Parse input and register new cgroup event handler.
4726 * Input must be in format '<event_fd> <control_fd> <args>'.
4727 * Interpretation of args is defined by control file implementation.
4729 static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
4730 char *buf, size_t nbytes, loff_t off)
4732 struct cgroup_subsys_state *css = of_css(of);
4733 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4734 struct mem_cgroup_event *event;
4735 struct cgroup_subsys_state *cfile_css;
4736 unsigned int efd, cfd;
4743 buf = strstrip(buf);
4745 efd = simple_strtoul(buf, &endp, 10);
4750 cfd = simple_strtoul(buf, &endp, 10);
4751 if ((*endp != ' ') && (*endp != '\0'))
4755 event = kzalloc(sizeof(*event), GFP_KERNEL);
4759 event->memcg = memcg;
4760 INIT_LIST_HEAD(&event->list);
4761 init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
4762 init_waitqueue_func_entry(&event->wait, memcg_event_wake);
4763 INIT_WORK(&event->remove, memcg_event_remove);
4771 event->eventfd = eventfd_ctx_fileget(efile.file);
4772 if (IS_ERR(event->eventfd)) {
4773 ret = PTR_ERR(event->eventfd);
4780 goto out_put_eventfd;
4783 /* the process need read permission on control file */
4784 /* AV: shouldn't we check that it's been opened for read instead? */
4785 ret = file_permission(cfile.file, MAY_READ);
4790 * Determine the event callbacks and set them in @event. This used
4791 * to be done via struct cftype but cgroup core no longer knows
4792 * about these events. The following is crude but the whole thing
4793 * is for compatibility anyway.
4795 * DO NOT ADD NEW FILES.
4797 name = cfile.file->f_path.dentry->d_name.name;
4799 if (!strcmp(name, "memory.usage_in_bytes")) {
4800 event->register_event = mem_cgroup_usage_register_event;
4801 event->unregister_event = mem_cgroup_usage_unregister_event;
4802 } else if (!strcmp(name, "memory.oom_control")) {
4803 event->register_event = mem_cgroup_oom_register_event;
4804 event->unregister_event = mem_cgroup_oom_unregister_event;
4805 } else if (!strcmp(name, "memory.pressure_level")) {
4806 event->register_event = vmpressure_register_event;
4807 event->unregister_event = vmpressure_unregister_event;
4808 } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
4809 event->register_event = memsw_cgroup_usage_register_event;
4810 event->unregister_event = memsw_cgroup_usage_unregister_event;
4817 * Verify @cfile should belong to @css. Also, remaining events are
4818 * automatically removed on cgroup destruction but the removal is
4819 * asynchronous, so take an extra ref on @css.
4821 cfile_css = css_tryget_online_from_dir(cfile.file->f_path.dentry->d_parent,
4822 &memory_cgrp_subsys);
4824 if (IS_ERR(cfile_css))
4826 if (cfile_css != css) {
4831 ret = event->register_event(memcg, event->eventfd, buf);
4835 vfs_poll(efile.file, &event->pt);
4837 spin_lock_irq(&memcg->event_list_lock);
4838 list_add(&event->list, &memcg->event_list);
4839 spin_unlock_irq(&memcg->event_list_lock);
4851 eventfd_ctx_put(event->eventfd);
4860 static struct cftype mem_cgroup_legacy_files[] = {
4862 .name = "usage_in_bytes",
4863 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
4864 .read_u64 = mem_cgroup_read_u64,
4867 .name = "max_usage_in_bytes",
4868 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
4869 .write = mem_cgroup_reset,
4870 .read_u64 = mem_cgroup_read_u64,
4873 .name = "limit_in_bytes",
4874 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
4875 .write = mem_cgroup_write,
4876 .read_u64 = mem_cgroup_read_u64,
4879 .name = "soft_limit_in_bytes",
4880 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
4881 .write = mem_cgroup_write,
4882 .read_u64 = mem_cgroup_read_u64,
4886 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
4887 .write = mem_cgroup_reset,
4888 .read_u64 = mem_cgroup_read_u64,
4892 .seq_show = memcg_stat_show,
4895 .name = "force_empty",
4896 .write = mem_cgroup_force_empty_write,
4899 .name = "use_hierarchy",
4900 .write_u64 = mem_cgroup_hierarchy_write,
4901 .read_u64 = mem_cgroup_hierarchy_read,
4904 .name = "cgroup.event_control", /* XXX: for compat */
4905 .write = memcg_write_event_control,
4906 .flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE,
4909 .name = "swappiness",
4910 .read_u64 = mem_cgroup_swappiness_read,
4911 .write_u64 = mem_cgroup_swappiness_write,
4914 .name = "move_charge_at_immigrate",
4915 .read_u64 = mem_cgroup_move_charge_read,
4916 .write_u64 = mem_cgroup_move_charge_write,
4919 .name = "oom_control",
4920 .seq_show = mem_cgroup_oom_control_read,
4921 .write_u64 = mem_cgroup_oom_control_write,
4922 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
4925 .name = "pressure_level",
4929 .name = "numa_stat",
4930 .seq_show = memcg_numa_stat_show,
4934 .name = "kmem.limit_in_bytes",
4935 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
4936 .write = mem_cgroup_write,
4937 .read_u64 = mem_cgroup_read_u64,
4940 .name = "kmem.usage_in_bytes",
4941 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
4942 .read_u64 = mem_cgroup_read_u64,
4945 .name = "kmem.failcnt",
4946 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
4947 .write = mem_cgroup_reset,
4948 .read_u64 = mem_cgroup_read_u64,
4951 .name = "kmem.max_usage_in_bytes",
4952 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
4953 .write = mem_cgroup_reset,
4954 .read_u64 = mem_cgroup_read_u64,
4956 #if defined(CONFIG_MEMCG_KMEM) && \
4957 (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG))
4959 .name = "kmem.slabinfo",
4960 .seq_show = memcg_slab_show,
4964 .name = "kmem.tcp.limit_in_bytes",
4965 .private = MEMFILE_PRIVATE(_TCP, RES_LIMIT),
4966 .write = mem_cgroup_write,
4967 .read_u64 = mem_cgroup_read_u64,
4970 .name = "kmem.tcp.usage_in_bytes",
4971 .private = MEMFILE_PRIVATE(_TCP, RES_USAGE),
4972 .read_u64 = mem_cgroup_read_u64,
4975 .name = "kmem.tcp.failcnt",
4976 .private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT),
4977 .write = mem_cgroup_reset,
4978 .read_u64 = mem_cgroup_read_u64,
4981 .name = "kmem.tcp.max_usage_in_bytes",
4982 .private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE),
4983 .write = mem_cgroup_reset,
4984 .read_u64 = mem_cgroup_read_u64,
4986 { }, /* terminate */
4990 * Private memory cgroup IDR
4992 * Swap-out records and page cache shadow entries need to store memcg
4993 * references in constrained space, so we maintain an ID space that is
4994 * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
4995 * memory-controlled cgroups to 64k.
4997 * However, there usually are many references to the offline CSS after
4998 * the cgroup has been destroyed, such as page cache or reclaimable
4999 * slab objects, that don't need to hang on to the ID. We want to keep
5000 * those dead CSS from occupying IDs, or we might quickly exhaust the
5001 * relatively small ID space and prevent the creation of new cgroups
5002 * even when there are much fewer than 64k cgroups - possibly none.
5004 * Maintain a private 16-bit ID space for memcg, and allow the ID to
5005 * be freed and recycled when it's no longer needed, which is usually
5006 * when the CSS is offlined.
5008 * The only exception to that are records of swapped out tmpfs/shmem
5009 * pages that need to be attributed to live ancestors on swapin. But
5010 * those references are manageable from userspace.
5013 static DEFINE_IDR(mem_cgroup_idr);
5015 static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
5017 if (memcg->id.id > 0) {
5018 idr_remove(&mem_cgroup_idr, memcg->id.id);
5023 static void __maybe_unused mem_cgroup_id_get_many(struct mem_cgroup *memcg,
5026 refcount_add(n, &memcg->id.ref);
5029 static void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
5031 if (refcount_sub_and_test(n, &memcg->id.ref)) {
5032 mem_cgroup_id_remove(memcg);
5034 /* Memcg ID pins CSS */
5035 css_put(&memcg->css);
5039 static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
5041 mem_cgroup_id_put_many(memcg, 1);
5045 * mem_cgroup_from_id - look up a memcg from a memcg id
5046 * @id: the memcg id to look up
5048 * Caller must hold rcu_read_lock().
5050 struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
5052 WARN_ON_ONCE(!rcu_read_lock_held());
5053 return idr_find(&mem_cgroup_idr, id);
5056 static int alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5058 struct mem_cgroup_per_node *pn;
5061 * This routine is called against possible nodes.
5062 * But it's BUG to call kmalloc() against offline node.
5064 * TODO: this routine can waste much memory for nodes which will
5065 * never be onlined. It's better to use memory hotplug callback
5068 if (!node_state(node, N_NORMAL_MEMORY))
5070 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
5074 pn->lruvec_stats_percpu = alloc_percpu_gfp(struct lruvec_stats_percpu,
5075 GFP_KERNEL_ACCOUNT);
5076 if (!pn->lruvec_stats_percpu) {
5081 lruvec_init(&pn->lruvec);
5082 pn->usage_in_excess = 0;
5083 pn->on_tree = false;
5086 memcg->nodeinfo[node] = pn;
5090 static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5092 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
5097 free_percpu(pn->lruvec_stats_percpu);
5101 static void __mem_cgroup_free(struct mem_cgroup *memcg)
5106 free_mem_cgroup_per_node_info(memcg, node);
5107 free_percpu(memcg->vmstats_percpu);
5111 static void mem_cgroup_free(struct mem_cgroup *memcg)
5113 memcg_wb_domain_exit(memcg);
5114 __mem_cgroup_free(memcg);
5117 static struct mem_cgroup *mem_cgroup_alloc(void)
5119 struct mem_cgroup *memcg;
5122 int __maybe_unused i;
5123 long error = -ENOMEM;
5125 size = sizeof(struct mem_cgroup);
5126 size += nr_node_ids * sizeof(struct mem_cgroup_per_node *);
5128 memcg = kzalloc(size, GFP_KERNEL);
5130 return ERR_PTR(error);
5132 memcg->id.id = idr_alloc(&mem_cgroup_idr, NULL,
5133 1, MEM_CGROUP_ID_MAX,
5135 if (memcg->id.id < 0) {
5136 error = memcg->id.id;
5140 memcg->vmstats_percpu = alloc_percpu_gfp(struct memcg_vmstats_percpu,
5141 GFP_KERNEL_ACCOUNT);
5142 if (!memcg->vmstats_percpu)
5146 if (alloc_mem_cgroup_per_node_info(memcg, node))
5149 if (memcg_wb_domain_init(memcg, GFP_KERNEL))
5152 INIT_WORK(&memcg->high_work, high_work_func);
5153 INIT_LIST_HEAD(&memcg->oom_notify);
5154 mutex_init(&memcg->thresholds_lock);
5155 spin_lock_init(&memcg->move_lock);
5156 vmpressure_init(&memcg->vmpressure);
5157 INIT_LIST_HEAD(&memcg->event_list);
5158 spin_lock_init(&memcg->event_list_lock);
5159 memcg->socket_pressure = jiffies;
5160 #ifdef CONFIG_MEMCG_KMEM
5161 memcg->kmemcg_id = -1;
5162 INIT_LIST_HEAD(&memcg->objcg_list);
5164 #ifdef CONFIG_CGROUP_WRITEBACK
5165 INIT_LIST_HEAD(&memcg->cgwb_list);
5166 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5167 memcg->cgwb_frn[i].done =
5168 __WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
5170 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5171 spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
5172 INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
5173 memcg->deferred_split_queue.split_queue_len = 0;
5175 idr_replace(&mem_cgroup_idr, memcg, memcg->id.id);
5178 mem_cgroup_id_remove(memcg);
5179 __mem_cgroup_free(memcg);
5180 return ERR_PTR(error);
5183 static struct cgroup_subsys_state * __ref
5184 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
5186 struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
5187 struct mem_cgroup *memcg, *old_memcg;
5188 long error = -ENOMEM;
5190 old_memcg = set_active_memcg(parent);
5191 memcg = mem_cgroup_alloc();
5192 set_active_memcg(old_memcg);
5194 return ERR_CAST(memcg);
5196 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5197 memcg->soft_limit = PAGE_COUNTER_MAX;
5198 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5200 memcg->swappiness = mem_cgroup_swappiness(parent);
5201 memcg->oom_kill_disable = parent->oom_kill_disable;
5203 page_counter_init(&memcg->memory, &parent->memory);
5204 page_counter_init(&memcg->swap, &parent->swap);
5205 page_counter_init(&memcg->kmem, &parent->kmem);
5206 page_counter_init(&memcg->tcpmem, &parent->tcpmem);
5208 page_counter_init(&memcg->memory, NULL);
5209 page_counter_init(&memcg->swap, NULL);
5210 page_counter_init(&memcg->kmem, NULL);
5211 page_counter_init(&memcg->tcpmem, NULL);
5213 root_mem_cgroup = memcg;
5217 /* The following stuff does not apply to the root */
5218 error = memcg_online_kmem(memcg);
5222 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5223 static_branch_inc(&memcg_sockets_enabled_key);
5227 mem_cgroup_id_remove(memcg);
5228 mem_cgroup_free(memcg);
5229 return ERR_PTR(error);
5232 static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
5234 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5237 * A memcg must be visible for expand_shrinker_info()
5238 * by the time the maps are allocated. So, we allocate maps
5239 * here, when for_each_mem_cgroup() can't skip it.
5241 if (alloc_shrinker_info(memcg)) {
5242 mem_cgroup_id_remove(memcg);
5246 /* Online state pins memcg ID, memcg ID pins CSS */
5247 refcount_set(&memcg->id.ref, 1);
5250 if (unlikely(mem_cgroup_is_root(memcg)))
5251 queue_delayed_work(system_unbound_wq, &stats_flush_dwork,
5256 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
5258 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5259 struct mem_cgroup_event *event, *tmp;
5262 * Unregister events and notify userspace.
5263 * Notify userspace about cgroup removing only after rmdir of cgroup
5264 * directory to avoid race between userspace and kernelspace.
5266 spin_lock_irq(&memcg->event_list_lock);
5267 list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
5268 list_del_init(&event->list);
5269 schedule_work(&event->remove);
5271 spin_unlock_irq(&memcg->event_list_lock);
5273 page_counter_set_min(&memcg->memory, 0);
5274 page_counter_set_low(&memcg->memory, 0);
5276 memcg_offline_kmem(memcg);
5277 reparent_shrinker_deferred(memcg);
5278 wb_memcg_offline(memcg);
5280 drain_all_stock(memcg);
5282 mem_cgroup_id_put(memcg);
5285 static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
5287 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5289 invalidate_reclaim_iterators(memcg);
5292 static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
5294 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5295 int __maybe_unused i;
5297 #ifdef CONFIG_CGROUP_WRITEBACK
5298 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5299 wb_wait_for_completion(&memcg->cgwb_frn[i].done);
5301 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5302 static_branch_dec(&memcg_sockets_enabled_key);
5304 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg->tcpmem_active)
5305 static_branch_dec(&memcg_sockets_enabled_key);
5307 vmpressure_cleanup(&memcg->vmpressure);
5308 cancel_work_sync(&memcg->high_work);
5309 mem_cgroup_remove_from_trees(memcg);
5310 free_shrinker_info(memcg);
5311 memcg_free_kmem(memcg);
5312 mem_cgroup_free(memcg);
5316 * mem_cgroup_css_reset - reset the states of a mem_cgroup
5317 * @css: the target css
5319 * Reset the states of the mem_cgroup associated with @css. This is
5320 * invoked when the userland requests disabling on the default hierarchy
5321 * but the memcg is pinned through dependency. The memcg should stop
5322 * applying policies and should revert to the vanilla state as it may be
5323 * made visible again.
5325 * The current implementation only resets the essential configurations.
5326 * This needs to be expanded to cover all the visible parts.
5328 static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
5330 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5332 page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
5333 page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
5334 page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
5335 page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
5336 page_counter_set_min(&memcg->memory, 0);
5337 page_counter_set_low(&memcg->memory, 0);
5338 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5339 memcg->soft_limit = PAGE_COUNTER_MAX;
5340 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5341 memcg_wb_domain_size_changed(memcg);
5344 void mem_cgroup_flush_stats(void)
5346 if (!spin_trylock(&stats_flush_lock))
5349 cgroup_rstat_flush_irqsafe(root_mem_cgroup->css.cgroup);
5350 spin_unlock(&stats_flush_lock);
5353 static void flush_memcg_stats_dwork(struct work_struct *w)
5355 mem_cgroup_flush_stats();
5356 queue_delayed_work(system_unbound_wq, &stats_flush_dwork, 2UL*HZ);
5359 static void mem_cgroup_css_rstat_flush(struct cgroup_subsys_state *css, int cpu)
5361 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5362 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
5363 struct memcg_vmstats_percpu *statc;
5367 statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
5369 for (i = 0; i < MEMCG_NR_STAT; i++) {
5371 * Collect the aggregated propagation counts of groups
5372 * below us. We're in a per-cpu loop here and this is
5373 * a global counter, so the first cycle will get them.
5375 delta = memcg->vmstats.state_pending[i];
5377 memcg->vmstats.state_pending[i] = 0;
5379 /* Add CPU changes on this level since the last flush */
5380 v = READ_ONCE(statc->state[i]);
5381 if (v != statc->state_prev[i]) {
5382 delta += v - statc->state_prev[i];
5383 statc->state_prev[i] = v;
5389 /* Aggregate counts on this level and propagate upwards */
5390 memcg->vmstats.state[i] += delta;
5392 parent->vmstats.state_pending[i] += delta;
5395 for (i = 0; i < NR_VM_EVENT_ITEMS; i++) {
5396 delta = memcg->vmstats.events_pending[i];
5398 memcg->vmstats.events_pending[i] = 0;
5400 v = READ_ONCE(statc->events[i]);
5401 if (v != statc->events_prev[i]) {
5402 delta += v - statc->events_prev[i];
5403 statc->events_prev[i] = v;
5409 memcg->vmstats.events[i] += delta;
5411 parent->vmstats.events_pending[i] += delta;
5414 for_each_node_state(nid, N_MEMORY) {
5415 struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
5416 struct mem_cgroup_per_node *ppn = NULL;
5417 struct lruvec_stats_percpu *lstatc;
5420 ppn = parent->nodeinfo[nid];
5422 lstatc = per_cpu_ptr(pn->lruvec_stats_percpu, cpu);
5424 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++) {
5425 delta = pn->lruvec_stats.state_pending[i];
5427 pn->lruvec_stats.state_pending[i] = 0;
5429 v = READ_ONCE(lstatc->state[i]);
5430 if (v != lstatc->state_prev[i]) {
5431 delta += v - lstatc->state_prev[i];
5432 lstatc->state_prev[i] = v;
5438 pn->lruvec_stats.state[i] += delta;
5440 ppn->lruvec_stats.state_pending[i] += delta;
5446 /* Handlers for move charge at task migration. */
5447 static int mem_cgroup_do_precharge(unsigned long count)
5451 /* Try a single bulk charge without reclaim first, kswapd may wake */
5452 ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count);
5454 mc.precharge += count;
5458 /* Try charges one by one with reclaim, but do not retry */
5460 ret = try_charge(mc.to, GFP_KERNEL | __GFP_NORETRY, 1);
5474 enum mc_target_type {
5481 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5482 unsigned long addr, pte_t ptent)
5484 struct page *page = vm_normal_page(vma, addr, ptent);
5486 if (!page || !page_mapped(page))
5488 if (PageAnon(page)) {
5489 if (!(mc.flags & MOVE_ANON))
5492 if (!(mc.flags & MOVE_FILE))
5495 if (!get_page_unless_zero(page))
5501 #if defined(CONFIG_SWAP) || defined(CONFIG_DEVICE_PRIVATE)
5502 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5503 pte_t ptent, swp_entry_t *entry)
5505 struct page *page = NULL;
5506 swp_entry_t ent = pte_to_swp_entry(ptent);
5508 if (!(mc.flags & MOVE_ANON))
5512 * Handle MEMORY_DEVICE_PRIVATE which are ZONE_DEVICE page belonging to
5513 * a device and because they are not accessible by CPU they are store
5514 * as special swap entry in the CPU page table.
5516 if (is_device_private_entry(ent)) {
5517 page = pfn_swap_entry_to_page(ent);
5519 * MEMORY_DEVICE_PRIVATE means ZONE_DEVICE page and which have
5520 * a refcount of 1 when free (unlike normal page)
5522 if (!page_ref_add_unless(page, 1, 1))
5527 if (non_swap_entry(ent))
5531 * Because lookup_swap_cache() updates some statistics counter,
5532 * we call find_get_page() with swapper_space directly.
5534 page = find_get_page(swap_address_space(ent), swp_offset(ent));
5535 entry->val = ent.val;
5540 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5541 pte_t ptent, swp_entry_t *entry)
5547 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5548 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5550 if (!vma->vm_file) /* anonymous vma */
5552 if (!(mc.flags & MOVE_FILE))
5555 /* page is moved even if it's not RSS of this task(page-faulted). */
5556 /* shmem/tmpfs may report page out on swap: account for that too. */
5557 return find_get_incore_page(vma->vm_file->f_mapping,
5558 linear_page_index(vma, addr));
5562 * mem_cgroup_move_account - move account of the page
5564 * @compound: charge the page as compound or small page
5565 * @from: mem_cgroup which the page is moved from.
5566 * @to: mem_cgroup which the page is moved to. @from != @to.
5568 * The caller must make sure the page is not on LRU (isolate_page() is useful.)
5570 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
5573 static int mem_cgroup_move_account(struct page *page,
5575 struct mem_cgroup *from,
5576 struct mem_cgroup *to)
5578 struct lruvec *from_vec, *to_vec;
5579 struct pglist_data *pgdat;
5580 unsigned int nr_pages = compound ? thp_nr_pages(page) : 1;
5583 VM_BUG_ON(from == to);
5584 VM_BUG_ON_PAGE(PageLRU(page), page);
5585 VM_BUG_ON(compound && !PageTransHuge(page));
5588 * Prevent mem_cgroup_migrate() from looking at
5589 * page's memory cgroup of its source page while we change it.
5592 if (!trylock_page(page))
5596 if (page_memcg(page) != from)
5599 pgdat = page_pgdat(page);
5600 from_vec = mem_cgroup_lruvec(from, pgdat);
5601 to_vec = mem_cgroup_lruvec(to, pgdat);
5603 lock_page_memcg(page);
5605 if (PageAnon(page)) {
5606 if (page_mapped(page)) {
5607 __mod_lruvec_state(from_vec, NR_ANON_MAPPED, -nr_pages);
5608 __mod_lruvec_state(to_vec, NR_ANON_MAPPED, nr_pages);
5609 if (PageTransHuge(page)) {
5610 __mod_lruvec_state(from_vec, NR_ANON_THPS,
5612 __mod_lruvec_state(to_vec, NR_ANON_THPS,
5617 __mod_lruvec_state(from_vec, NR_FILE_PAGES, -nr_pages);
5618 __mod_lruvec_state(to_vec, NR_FILE_PAGES, nr_pages);
5620 if (PageSwapBacked(page)) {
5621 __mod_lruvec_state(from_vec, NR_SHMEM, -nr_pages);
5622 __mod_lruvec_state(to_vec, NR_SHMEM, nr_pages);
5625 if (page_mapped(page)) {
5626 __mod_lruvec_state(from_vec, NR_FILE_MAPPED, -nr_pages);
5627 __mod_lruvec_state(to_vec, NR_FILE_MAPPED, nr_pages);
5630 if (PageDirty(page)) {
5631 struct address_space *mapping = page_mapping(page);
5633 if (mapping_can_writeback(mapping)) {
5634 __mod_lruvec_state(from_vec, NR_FILE_DIRTY,
5636 __mod_lruvec_state(to_vec, NR_FILE_DIRTY,
5642 if (PageWriteback(page)) {
5643 __mod_lruvec_state(from_vec, NR_WRITEBACK, -nr_pages);
5644 __mod_lruvec_state(to_vec, NR_WRITEBACK, nr_pages);
5648 * All state has been migrated, let's switch to the new memcg.
5650 * It is safe to change page's memcg here because the page
5651 * is referenced, charged, isolated, and locked: we can't race
5652 * with (un)charging, migration, LRU putback, or anything else
5653 * that would rely on a stable page's memory cgroup.
5655 * Note that lock_page_memcg is a memcg lock, not a page lock,
5656 * to save space. As soon as we switch page's memory cgroup to a
5657 * new memcg that isn't locked, the above state can change
5658 * concurrently again. Make sure we're truly done with it.
5663 css_put(&from->css);
5665 page->memcg_data = (unsigned long)to;
5667 __unlock_page_memcg(from);
5671 local_irq_disable();
5672 mem_cgroup_charge_statistics(to, page, nr_pages);
5673 memcg_check_events(to, page);
5674 mem_cgroup_charge_statistics(from, page, -nr_pages);
5675 memcg_check_events(from, page);
5684 * get_mctgt_type - get target type of moving charge
5685 * @vma: the vma the pte to be checked belongs
5686 * @addr: the address corresponding to the pte to be checked
5687 * @ptent: the pte to be checked
5688 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5691 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5692 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5693 * move charge. if @target is not NULL, the page is stored in target->page
5694 * with extra refcnt got(Callers should handle it).
5695 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5696 * target for charge migration. if @target is not NULL, the entry is stored
5698 * 3(MC_TARGET_DEVICE): like MC_TARGET_PAGE but page is MEMORY_DEVICE_PRIVATE
5699 * (so ZONE_DEVICE page and thus not on the lru).
5700 * For now we such page is charge like a regular page would be as for all
5701 * intent and purposes it is just special memory taking the place of a
5704 * See Documentations/vm/hmm.txt and include/linux/hmm.h
5706 * Called with pte lock held.
5709 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
5710 unsigned long addr, pte_t ptent, union mc_target *target)
5712 struct page *page = NULL;
5713 enum mc_target_type ret = MC_TARGET_NONE;
5714 swp_entry_t ent = { .val = 0 };
5716 if (pte_present(ptent))
5717 page = mc_handle_present_pte(vma, addr, ptent);
5718 else if (is_swap_pte(ptent))
5719 page = mc_handle_swap_pte(vma, ptent, &ent);
5720 else if (pte_none(ptent))
5721 page = mc_handle_file_pte(vma, addr, ptent, &ent);
5723 if (!page && !ent.val)
5727 * Do only loose check w/o serialization.
5728 * mem_cgroup_move_account() checks the page is valid or
5729 * not under LRU exclusion.
5731 if (page_memcg(page) == mc.from) {
5732 ret = MC_TARGET_PAGE;
5733 if (is_device_private_page(page))
5734 ret = MC_TARGET_DEVICE;
5736 target->page = page;
5738 if (!ret || !target)
5742 * There is a swap entry and a page doesn't exist or isn't charged.
5743 * But we cannot move a tail-page in a THP.
5745 if (ent.val && !ret && (!page || !PageTransCompound(page)) &&
5746 mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
5747 ret = MC_TARGET_SWAP;
5754 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5756 * We don't consider PMD mapped swapping or file mapped pages because THP does
5757 * not support them for now.
5758 * Caller should make sure that pmd_trans_huge(pmd) is true.
5760 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5761 unsigned long addr, pmd_t pmd, union mc_target *target)
5763 struct page *page = NULL;
5764 enum mc_target_type ret = MC_TARGET_NONE;
5766 if (unlikely(is_swap_pmd(pmd))) {
5767 VM_BUG_ON(thp_migration_supported() &&
5768 !is_pmd_migration_entry(pmd));
5771 page = pmd_page(pmd);
5772 VM_BUG_ON_PAGE(!page || !PageHead(page), page);
5773 if (!(mc.flags & MOVE_ANON))
5775 if (page_memcg(page) == mc.from) {
5776 ret = MC_TARGET_PAGE;
5779 target->page = page;
5785 static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5786 unsigned long addr, pmd_t pmd, union mc_target *target)
5788 return MC_TARGET_NONE;
5792 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5793 unsigned long addr, unsigned long end,
5794 struct mm_walk *walk)
5796 struct vm_area_struct *vma = walk->vma;
5800 ptl = pmd_trans_huge_lock(pmd, vma);
5803 * Note their can not be MC_TARGET_DEVICE for now as we do not
5804 * support transparent huge page with MEMORY_DEVICE_PRIVATE but
5805 * this might change.
5807 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
5808 mc.precharge += HPAGE_PMD_NR;
5813 if (pmd_trans_unstable(pmd))
5815 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5816 for (; addr != end; pte++, addr += PAGE_SIZE)
5817 if (get_mctgt_type(vma, addr, *pte, NULL))
5818 mc.precharge++; /* increment precharge temporarily */
5819 pte_unmap_unlock(pte - 1, ptl);
5825 static const struct mm_walk_ops precharge_walk_ops = {
5826 .pmd_entry = mem_cgroup_count_precharge_pte_range,
5829 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5831 unsigned long precharge;
5834 walk_page_range(mm, 0, mm->highest_vm_end, &precharge_walk_ops, NULL);
5835 mmap_read_unlock(mm);
5837 precharge = mc.precharge;
5843 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5845 unsigned long precharge = mem_cgroup_count_precharge(mm);
5847 VM_BUG_ON(mc.moving_task);
5848 mc.moving_task = current;
5849 return mem_cgroup_do_precharge(precharge);
5852 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5853 static void __mem_cgroup_clear_mc(void)
5855 struct mem_cgroup *from = mc.from;
5856 struct mem_cgroup *to = mc.to;
5858 /* we must uncharge all the leftover precharges from mc.to */
5860 cancel_charge(mc.to, mc.precharge);
5864 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5865 * we must uncharge here.
5867 if (mc.moved_charge) {
5868 cancel_charge(mc.from, mc.moved_charge);
5869 mc.moved_charge = 0;
5871 /* we must fixup refcnts and charges */
5872 if (mc.moved_swap) {
5873 /* uncharge swap account from the old cgroup */
5874 if (!mem_cgroup_is_root(mc.from))
5875 page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
5877 mem_cgroup_id_put_many(mc.from, mc.moved_swap);
5880 * we charged both to->memory and to->memsw, so we
5881 * should uncharge to->memory.
5883 if (!mem_cgroup_is_root(mc.to))
5884 page_counter_uncharge(&mc.to->memory, mc.moved_swap);
5888 memcg_oom_recover(from);
5889 memcg_oom_recover(to);
5890 wake_up_all(&mc.waitq);
5893 static void mem_cgroup_clear_mc(void)
5895 struct mm_struct *mm = mc.mm;
5898 * we must clear moving_task before waking up waiters at the end of
5901 mc.moving_task = NULL;
5902 __mem_cgroup_clear_mc();
5903 spin_lock(&mc.lock);
5907 spin_unlock(&mc.lock);
5912 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
5914 struct cgroup_subsys_state *css;
5915 struct mem_cgroup *memcg = NULL; /* unneeded init to make gcc happy */
5916 struct mem_cgroup *from;
5917 struct task_struct *leader, *p;
5918 struct mm_struct *mm;
5919 unsigned long move_flags;
5922 /* charge immigration isn't supported on the default hierarchy */
5923 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
5927 * Multi-process migrations only happen on the default hierarchy
5928 * where charge immigration is not used. Perform charge
5929 * immigration if @tset contains a leader and whine if there are
5933 cgroup_taskset_for_each_leader(leader, css, tset) {
5936 memcg = mem_cgroup_from_css(css);
5942 * We are now committed to this value whatever it is. Changes in this
5943 * tunable will only affect upcoming migrations, not the current one.
5944 * So we need to save it, and keep it going.
5946 move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
5950 from = mem_cgroup_from_task(p);
5952 VM_BUG_ON(from == memcg);
5954 mm = get_task_mm(p);
5957 /* We move charges only when we move a owner of the mm */
5958 if (mm->owner == p) {
5961 VM_BUG_ON(mc.precharge);
5962 VM_BUG_ON(mc.moved_charge);
5963 VM_BUG_ON(mc.moved_swap);
5965 spin_lock(&mc.lock);
5969 mc.flags = move_flags;
5970 spin_unlock(&mc.lock);
5971 /* We set mc.moving_task later */
5973 ret = mem_cgroup_precharge_mc(mm);
5975 mem_cgroup_clear_mc();
5982 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
5985 mem_cgroup_clear_mc();
5988 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
5989 unsigned long addr, unsigned long end,
5990 struct mm_walk *walk)
5993 struct vm_area_struct *vma = walk->vma;
5996 enum mc_target_type target_type;
5997 union mc_target target;
6000 ptl = pmd_trans_huge_lock(pmd, vma);
6002 if (mc.precharge < HPAGE_PMD_NR) {
6006 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
6007 if (target_type == MC_TARGET_PAGE) {
6009 if (!isolate_lru_page(page)) {
6010 if (!mem_cgroup_move_account(page, true,
6012 mc.precharge -= HPAGE_PMD_NR;
6013 mc.moved_charge += HPAGE_PMD_NR;
6015 putback_lru_page(page);
6018 } else if (target_type == MC_TARGET_DEVICE) {
6020 if (!mem_cgroup_move_account(page, true,
6022 mc.precharge -= HPAGE_PMD_NR;
6023 mc.moved_charge += HPAGE_PMD_NR;
6031 if (pmd_trans_unstable(pmd))
6034 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6035 for (; addr != end; addr += PAGE_SIZE) {
6036 pte_t ptent = *(pte++);
6037 bool device = false;
6043 switch (get_mctgt_type(vma, addr, ptent, &target)) {
6044 case MC_TARGET_DEVICE:
6047 case MC_TARGET_PAGE:
6050 * We can have a part of the split pmd here. Moving it
6051 * can be done but it would be too convoluted so simply
6052 * ignore such a partial THP and keep it in original
6053 * memcg. There should be somebody mapping the head.
6055 if (PageTransCompound(page))
6057 if (!device && isolate_lru_page(page))
6059 if (!mem_cgroup_move_account(page, false,
6062 /* we uncharge from mc.from later. */
6066 putback_lru_page(page);
6067 put: /* get_mctgt_type() gets the page */
6070 case MC_TARGET_SWAP:
6072 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
6074 mem_cgroup_id_get_many(mc.to, 1);
6075 /* we fixup other refcnts and charges later. */
6083 pte_unmap_unlock(pte - 1, ptl);
6088 * We have consumed all precharges we got in can_attach().
6089 * We try charge one by one, but don't do any additional
6090 * charges to mc.to if we have failed in charge once in attach()
6093 ret = mem_cgroup_do_precharge(1);
6101 static const struct mm_walk_ops charge_walk_ops = {
6102 .pmd_entry = mem_cgroup_move_charge_pte_range,
6105 static void mem_cgroup_move_charge(void)
6107 lru_add_drain_all();
6109 * Signal lock_page_memcg() to take the memcg's move_lock
6110 * while we're moving its pages to another memcg. Then wait
6111 * for already started RCU-only updates to finish.
6113 atomic_inc(&mc.from->moving_account);
6116 if (unlikely(!mmap_read_trylock(mc.mm))) {
6118 * Someone who are holding the mmap_lock might be waiting in
6119 * waitq. So we cancel all extra charges, wake up all waiters,
6120 * and retry. Because we cancel precharges, we might not be able
6121 * to move enough charges, but moving charge is a best-effort
6122 * feature anyway, so it wouldn't be a big problem.
6124 __mem_cgroup_clear_mc();
6129 * When we have consumed all precharges and failed in doing
6130 * additional charge, the page walk just aborts.
6132 walk_page_range(mc.mm, 0, mc.mm->highest_vm_end, &charge_walk_ops,
6135 mmap_read_unlock(mc.mm);
6136 atomic_dec(&mc.from->moving_account);
6139 static void mem_cgroup_move_task(void)
6142 mem_cgroup_move_charge();
6143 mem_cgroup_clear_mc();
6146 #else /* !CONFIG_MMU */
6147 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
6151 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6154 static void mem_cgroup_move_task(void)
6159 static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
6161 if (value == PAGE_COUNTER_MAX)
6162 seq_puts(m, "max\n");
6164 seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
6169 static u64 memory_current_read(struct cgroup_subsys_state *css,
6172 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6174 return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
6177 static int memory_min_show(struct seq_file *m, void *v)
6179 return seq_puts_memcg_tunable(m,
6180 READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
6183 static ssize_t memory_min_write(struct kernfs_open_file *of,
6184 char *buf, size_t nbytes, loff_t off)
6186 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6190 buf = strstrip(buf);
6191 err = page_counter_memparse(buf, "max", &min);
6195 page_counter_set_min(&memcg->memory, min);
6200 static int memory_low_show(struct seq_file *m, void *v)
6202 return seq_puts_memcg_tunable(m,
6203 READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
6206 static ssize_t memory_low_write(struct kernfs_open_file *of,
6207 char *buf, size_t nbytes, loff_t off)
6209 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6213 buf = strstrip(buf);
6214 err = page_counter_memparse(buf, "max", &low);
6218 page_counter_set_low(&memcg->memory, low);
6223 static int memory_high_show(struct seq_file *m, void *v)
6225 return seq_puts_memcg_tunable(m,
6226 READ_ONCE(mem_cgroup_from_seq(m)->memory.high));
6229 static ssize_t memory_high_write(struct kernfs_open_file *of,
6230 char *buf, size_t nbytes, loff_t off)
6232 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6233 unsigned int nr_retries = MAX_RECLAIM_RETRIES;
6234 bool drained = false;
6238 buf = strstrip(buf);
6239 err = page_counter_memparse(buf, "max", &high);
6243 page_counter_set_high(&memcg->memory, high);
6246 unsigned long nr_pages = page_counter_read(&memcg->memory);
6247 unsigned long reclaimed;
6249 if (nr_pages <= high)
6252 if (signal_pending(current))
6256 drain_all_stock(memcg);
6261 reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
6264 if (!reclaimed && !nr_retries--)
6268 memcg_wb_domain_size_changed(memcg);
6272 static int memory_max_show(struct seq_file *m, void *v)
6274 return seq_puts_memcg_tunable(m,
6275 READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
6278 static ssize_t memory_max_write(struct kernfs_open_file *of,
6279 char *buf, size_t nbytes, loff_t off)
6281 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6282 unsigned int nr_reclaims = MAX_RECLAIM_RETRIES;
6283 bool drained = false;
6287 buf = strstrip(buf);
6288 err = page_counter_memparse(buf, "max", &max);
6292 xchg(&memcg->memory.max, max);
6295 unsigned long nr_pages = page_counter_read(&memcg->memory);
6297 if (nr_pages <= max)
6300 if (signal_pending(current))
6304 drain_all_stock(memcg);
6310 if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
6316 memcg_memory_event(memcg, MEMCG_OOM);
6317 if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
6321 memcg_wb_domain_size_changed(memcg);
6325 static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
6327 seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
6328 seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
6329 seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
6330 seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
6331 seq_printf(m, "oom_kill %lu\n",
6332 atomic_long_read(&events[MEMCG_OOM_KILL]));
6335 static int memory_events_show(struct seq_file *m, void *v)
6337 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6339 __memory_events_show(m, memcg->memory_events);
6343 static int memory_events_local_show(struct seq_file *m, void *v)
6345 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6347 __memory_events_show(m, memcg->memory_events_local);
6351 static int memory_stat_show(struct seq_file *m, void *v)
6353 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6356 buf = memory_stat_format(memcg);
6365 static inline unsigned long lruvec_page_state_output(struct lruvec *lruvec,
6368 return lruvec_page_state(lruvec, item) * memcg_page_state_unit(item);
6371 static int memory_numa_stat_show(struct seq_file *m, void *v)
6374 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6376 cgroup_rstat_flush(memcg->css.cgroup);
6378 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
6381 if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS)
6384 seq_printf(m, "%s", memory_stats[i].name);
6385 for_each_node_state(nid, N_MEMORY) {
6387 struct lruvec *lruvec;
6389 lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
6390 size = lruvec_page_state_output(lruvec,
6391 memory_stats[i].idx);
6392 seq_printf(m, " N%d=%llu", nid, size);
6401 static int memory_oom_group_show(struct seq_file *m, void *v)
6403 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6405 seq_printf(m, "%d\n", memcg->oom_group);
6410 static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
6411 char *buf, size_t nbytes, loff_t off)
6413 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6416 buf = strstrip(buf);
6420 ret = kstrtoint(buf, 0, &oom_group);
6424 if (oom_group != 0 && oom_group != 1)
6427 memcg->oom_group = oom_group;
6432 static struct cftype memory_files[] = {
6435 .flags = CFTYPE_NOT_ON_ROOT,
6436 .read_u64 = memory_current_read,
6440 .flags = CFTYPE_NOT_ON_ROOT,
6441 .seq_show = memory_min_show,
6442 .write = memory_min_write,
6446 .flags = CFTYPE_NOT_ON_ROOT,
6447 .seq_show = memory_low_show,
6448 .write = memory_low_write,
6452 .flags = CFTYPE_NOT_ON_ROOT,
6453 .seq_show = memory_high_show,
6454 .write = memory_high_write,
6458 .flags = CFTYPE_NOT_ON_ROOT,
6459 .seq_show = memory_max_show,
6460 .write = memory_max_write,
6464 .flags = CFTYPE_NOT_ON_ROOT,
6465 .file_offset = offsetof(struct mem_cgroup, events_file),
6466 .seq_show = memory_events_show,
6469 .name = "events.local",
6470 .flags = CFTYPE_NOT_ON_ROOT,
6471 .file_offset = offsetof(struct mem_cgroup, events_local_file),
6472 .seq_show = memory_events_local_show,
6476 .seq_show = memory_stat_show,
6480 .name = "numa_stat",
6481 .seq_show = memory_numa_stat_show,
6485 .name = "oom.group",
6486 .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
6487 .seq_show = memory_oom_group_show,
6488 .write = memory_oom_group_write,
6493 struct cgroup_subsys memory_cgrp_subsys = {
6494 .css_alloc = mem_cgroup_css_alloc,
6495 .css_online = mem_cgroup_css_online,
6496 .css_offline = mem_cgroup_css_offline,
6497 .css_released = mem_cgroup_css_released,
6498 .css_free = mem_cgroup_css_free,
6499 .css_reset = mem_cgroup_css_reset,
6500 .css_rstat_flush = mem_cgroup_css_rstat_flush,
6501 .can_attach = mem_cgroup_can_attach,
6502 .cancel_attach = mem_cgroup_cancel_attach,
6503 .post_attach = mem_cgroup_move_task,
6504 .dfl_cftypes = memory_files,
6505 .legacy_cftypes = mem_cgroup_legacy_files,
6510 * This function calculates an individual cgroup's effective
6511 * protection which is derived from its own memory.min/low, its
6512 * parent's and siblings' settings, as well as the actual memory
6513 * distribution in the tree.
6515 * The following rules apply to the effective protection values:
6517 * 1. At the first level of reclaim, effective protection is equal to
6518 * the declared protection in memory.min and memory.low.
6520 * 2. To enable safe delegation of the protection configuration, at
6521 * subsequent levels the effective protection is capped to the
6522 * parent's effective protection.
6524 * 3. To make complex and dynamic subtrees easier to configure, the
6525 * user is allowed to overcommit the declared protection at a given
6526 * level. If that is the case, the parent's effective protection is
6527 * distributed to the children in proportion to how much protection
6528 * they have declared and how much of it they are utilizing.
6530 * This makes distribution proportional, but also work-conserving:
6531 * if one cgroup claims much more protection than it uses memory,
6532 * the unused remainder is available to its siblings.
6534 * 4. Conversely, when the declared protection is undercommitted at a
6535 * given level, the distribution of the larger parental protection
6536 * budget is NOT proportional. A cgroup's protection from a sibling
6537 * is capped to its own memory.min/low setting.
6539 * 5. However, to allow protecting recursive subtrees from each other
6540 * without having to declare each individual cgroup's fixed share
6541 * of the ancestor's claim to protection, any unutilized -
6542 * "floating" - protection from up the tree is distributed in
6543 * proportion to each cgroup's *usage*. This makes the protection
6544 * neutral wrt sibling cgroups and lets them compete freely over
6545 * the shared parental protection budget, but it protects the
6546 * subtree as a whole from neighboring subtrees.
6548 * Note that 4. and 5. are not in conflict: 4. is about protecting
6549 * against immediate siblings whereas 5. is about protecting against
6550 * neighboring subtrees.
6552 static unsigned long effective_protection(unsigned long usage,
6553 unsigned long parent_usage,
6554 unsigned long setting,
6555 unsigned long parent_effective,
6556 unsigned long siblings_protected)
6558 unsigned long protected;
6561 protected = min(usage, setting);
6563 * If all cgroups at this level combined claim and use more
6564 * protection then what the parent affords them, distribute
6565 * shares in proportion to utilization.
6567 * We are using actual utilization rather than the statically
6568 * claimed protection in order to be work-conserving: claimed
6569 * but unused protection is available to siblings that would
6570 * otherwise get a smaller chunk than what they claimed.
6572 if (siblings_protected > parent_effective)
6573 return protected * parent_effective / siblings_protected;
6576 * Ok, utilized protection of all children is within what the
6577 * parent affords them, so we know whatever this child claims
6578 * and utilizes is effectively protected.
6580 * If there is unprotected usage beyond this value, reclaim
6581 * will apply pressure in proportion to that amount.
6583 * If there is unutilized protection, the cgroup will be fully
6584 * shielded from reclaim, but we do return a smaller value for
6585 * protection than what the group could enjoy in theory. This
6586 * is okay. With the overcommit distribution above, effective
6587 * protection is always dependent on how memory is actually
6588 * consumed among the siblings anyway.
6593 * If the children aren't claiming (all of) the protection
6594 * afforded to them by the parent, distribute the remainder in
6595 * proportion to the (unprotected) memory of each cgroup. That
6596 * way, cgroups that aren't explicitly prioritized wrt each
6597 * other compete freely over the allowance, but they are
6598 * collectively protected from neighboring trees.
6600 * We're using unprotected memory for the weight so that if
6601 * some cgroups DO claim explicit protection, we don't protect
6602 * the same bytes twice.
6604 * Check both usage and parent_usage against the respective
6605 * protected values. One should imply the other, but they
6606 * aren't read atomically - make sure the division is sane.
6608 if (!(cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT))
6610 if (parent_effective > siblings_protected &&
6611 parent_usage > siblings_protected &&
6612 usage > protected) {
6613 unsigned long unclaimed;
6615 unclaimed = parent_effective - siblings_protected;
6616 unclaimed *= usage - protected;
6617 unclaimed /= parent_usage - siblings_protected;
6626 * mem_cgroup_calculate_protection - check if memory consumption is in the normal range
6627 * @root: the top ancestor of the sub-tree being checked
6628 * @memcg: the memory cgroup to check
6630 * WARNING: This function is not stateless! It can only be used as part
6631 * of a top-down tree iteration, not for isolated queries.
6633 void mem_cgroup_calculate_protection(struct mem_cgroup *root,
6634 struct mem_cgroup *memcg)
6636 unsigned long usage, parent_usage;
6637 struct mem_cgroup *parent;
6639 if (mem_cgroup_disabled())
6643 root = root_mem_cgroup;
6646 * Effective values of the reclaim targets are ignored so they
6647 * can be stale. Have a look at mem_cgroup_protection for more
6649 * TODO: calculation should be more robust so that we do not need
6650 * that special casing.
6655 usage = page_counter_read(&memcg->memory);
6659 parent = parent_mem_cgroup(memcg);
6660 /* No parent means a non-hierarchical mode on v1 memcg */
6664 if (parent == root) {
6665 memcg->memory.emin = READ_ONCE(memcg->memory.min);
6666 memcg->memory.elow = READ_ONCE(memcg->memory.low);
6670 parent_usage = page_counter_read(&parent->memory);
6672 WRITE_ONCE(memcg->memory.emin, effective_protection(usage, parent_usage,
6673 READ_ONCE(memcg->memory.min),
6674 READ_ONCE(parent->memory.emin),
6675 atomic_long_read(&parent->memory.children_min_usage)));
6677 WRITE_ONCE(memcg->memory.elow, effective_protection(usage, parent_usage,
6678 READ_ONCE(memcg->memory.low),
6679 READ_ONCE(parent->memory.elow),
6680 atomic_long_read(&parent->memory.children_low_usage)));
6683 static int charge_memcg(struct page *page, struct mem_cgroup *memcg, gfp_t gfp)
6685 unsigned int nr_pages = thp_nr_pages(page);
6688 ret = try_charge(memcg, gfp, nr_pages);
6692 css_get(&memcg->css);
6693 commit_charge(page, memcg);
6695 local_irq_disable();
6696 mem_cgroup_charge_statistics(memcg, page, nr_pages);
6697 memcg_check_events(memcg, page);
6704 * __mem_cgroup_charge - charge a newly allocated page to a cgroup
6705 * @page: page to charge
6706 * @mm: mm context of the victim
6707 * @gfp_mask: reclaim mode
6709 * Try to charge @page to the memcg that @mm belongs to, reclaiming
6710 * pages according to @gfp_mask if necessary. if @mm is NULL, try to
6711 * charge to the active memcg.
6713 * Do not use this for pages allocated for swapin.
6715 * Returns 0 on success. Otherwise, an error code is returned.
6717 int __mem_cgroup_charge(struct page *page, struct mm_struct *mm,
6720 struct mem_cgroup *memcg;
6723 memcg = get_mem_cgroup_from_mm(mm);
6724 ret = charge_memcg(page, memcg, gfp_mask);
6725 css_put(&memcg->css);
6731 * mem_cgroup_swapin_charge_page - charge a newly allocated page for swapin
6732 * @page: page to charge
6733 * @mm: mm context of the victim
6734 * @gfp: reclaim mode
6735 * @entry: swap entry for which the page is allocated
6737 * This function charges a page allocated for swapin. Please call this before
6738 * adding the page to the swapcache.
6740 * Returns 0 on success. Otherwise, an error code is returned.
6742 int mem_cgroup_swapin_charge_page(struct page *page, struct mm_struct *mm,
6743 gfp_t gfp, swp_entry_t entry)
6745 struct mem_cgroup *memcg;
6749 if (mem_cgroup_disabled())
6752 id = lookup_swap_cgroup_id(entry);
6754 memcg = mem_cgroup_from_id(id);
6755 if (!memcg || !css_tryget_online(&memcg->css))
6756 memcg = get_mem_cgroup_from_mm(mm);
6759 ret = charge_memcg(page, memcg, gfp);
6761 css_put(&memcg->css);
6766 * mem_cgroup_swapin_uncharge_swap - uncharge swap slot
6767 * @entry: swap entry for which the page is charged
6769 * Call this function after successfully adding the charged page to swapcache.
6771 * Note: This function assumes the page for which swap slot is being uncharged
6774 void mem_cgroup_swapin_uncharge_swap(swp_entry_t entry)
6777 * Cgroup1's unified memory+swap counter has been charged with the
6778 * new swapcache page, finish the transfer by uncharging the swap
6779 * slot. The swap slot would also get uncharged when it dies, but
6780 * it can stick around indefinitely and we'd count the page twice
6783 * Cgroup2 has separate resource counters for memory and swap,
6784 * so this is a non-issue here. Memory and swap charge lifetimes
6785 * correspond 1:1 to page and swap slot lifetimes: we charge the
6786 * page to memory here, and uncharge swap when the slot is freed.
6788 if (!mem_cgroup_disabled() && do_memsw_account()) {
6790 * The swap entry might not get freed for a long time,
6791 * let's not wait for it. The page already received a
6792 * memory+swap charge, drop the swap entry duplicate.
6794 mem_cgroup_uncharge_swap(entry, 1);
6798 struct uncharge_gather {
6799 struct mem_cgroup *memcg;
6800 unsigned long nr_memory;
6801 unsigned long pgpgout;
6802 unsigned long nr_kmem;
6803 struct page *dummy_page;
6806 static inline void uncharge_gather_clear(struct uncharge_gather *ug)
6808 memset(ug, 0, sizeof(*ug));
6811 static void uncharge_batch(const struct uncharge_gather *ug)
6813 unsigned long flags;
6815 if (ug->nr_memory) {
6816 page_counter_uncharge(&ug->memcg->memory, ug->nr_memory);
6817 if (do_memsw_account())
6818 page_counter_uncharge(&ug->memcg->memsw, ug->nr_memory);
6819 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && ug->nr_kmem)
6820 page_counter_uncharge(&ug->memcg->kmem, ug->nr_kmem);
6821 memcg_oom_recover(ug->memcg);
6824 local_irq_save(flags);
6825 __count_memcg_events(ug->memcg, PGPGOUT, ug->pgpgout);
6826 __this_cpu_add(ug->memcg->vmstats_percpu->nr_page_events, ug->nr_memory);
6827 memcg_check_events(ug->memcg, ug->dummy_page);
6828 local_irq_restore(flags);
6830 /* drop reference from uncharge_page */
6831 css_put(&ug->memcg->css);
6834 static void uncharge_page(struct page *page, struct uncharge_gather *ug)
6836 unsigned long nr_pages;
6837 struct mem_cgroup *memcg;
6838 struct obj_cgroup *objcg;
6839 bool use_objcg = PageMemcgKmem(page);
6841 VM_BUG_ON_PAGE(PageLRU(page), page);
6844 * Nobody should be changing or seriously looking at
6845 * page memcg or objcg at this point, we have fully
6846 * exclusive access to the page.
6849 objcg = __page_objcg(page);
6851 * This get matches the put at the end of the function and
6852 * kmem pages do not hold memcg references anymore.
6854 memcg = get_mem_cgroup_from_objcg(objcg);
6856 memcg = __page_memcg(page);
6862 if (ug->memcg != memcg) {
6865 uncharge_gather_clear(ug);
6868 ug->dummy_page = page;
6870 /* pairs with css_put in uncharge_batch */
6871 css_get(&memcg->css);
6874 nr_pages = compound_nr(page);
6877 ug->nr_memory += nr_pages;
6878 ug->nr_kmem += nr_pages;
6880 page->memcg_data = 0;
6881 obj_cgroup_put(objcg);
6883 /* LRU pages aren't accounted at the root level */
6884 if (!mem_cgroup_is_root(memcg))
6885 ug->nr_memory += nr_pages;
6888 page->memcg_data = 0;
6891 css_put(&memcg->css);
6895 * __mem_cgroup_uncharge - uncharge a page
6896 * @page: page to uncharge
6898 * Uncharge a page previously charged with __mem_cgroup_charge().
6900 void __mem_cgroup_uncharge(struct page *page)
6902 struct uncharge_gather ug;
6904 /* Don't touch page->lru of any random page, pre-check: */
6905 if (!page_memcg(page))
6908 uncharge_gather_clear(&ug);
6909 uncharge_page(page, &ug);
6910 uncharge_batch(&ug);
6914 * __mem_cgroup_uncharge_list - uncharge a list of page
6915 * @page_list: list of pages to uncharge
6917 * Uncharge a list of pages previously charged with
6918 * __mem_cgroup_charge().
6920 void __mem_cgroup_uncharge_list(struct list_head *page_list)
6922 struct uncharge_gather ug;
6925 uncharge_gather_clear(&ug);
6926 list_for_each_entry(page, page_list, lru)
6927 uncharge_page(page, &ug);
6929 uncharge_batch(&ug);
6933 * mem_cgroup_migrate - charge a page's replacement
6934 * @oldpage: currently circulating page
6935 * @newpage: replacement page
6937 * Charge @newpage as a replacement page for @oldpage. @oldpage will
6938 * be uncharged upon free.
6940 * Both pages must be locked, @newpage->mapping must be set up.
6942 void mem_cgroup_migrate(struct page *oldpage, struct page *newpage)
6944 struct mem_cgroup *memcg;
6945 unsigned int nr_pages;
6946 unsigned long flags;
6948 VM_BUG_ON_PAGE(!PageLocked(oldpage), oldpage);
6949 VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
6950 VM_BUG_ON_PAGE(PageAnon(oldpage) != PageAnon(newpage), newpage);
6951 VM_BUG_ON_PAGE(PageTransHuge(oldpage) != PageTransHuge(newpage),
6954 if (mem_cgroup_disabled())
6957 /* Page cache replacement: new page already charged? */
6958 if (page_memcg(newpage))
6961 memcg = page_memcg(oldpage);
6962 VM_WARN_ON_ONCE_PAGE(!memcg, oldpage);
6966 /* Force-charge the new page. The old one will be freed soon */
6967 nr_pages = thp_nr_pages(newpage);
6969 if (!mem_cgroup_is_root(memcg)) {
6970 page_counter_charge(&memcg->memory, nr_pages);
6971 if (do_memsw_account())
6972 page_counter_charge(&memcg->memsw, nr_pages);
6975 css_get(&memcg->css);
6976 commit_charge(newpage, memcg);
6978 local_irq_save(flags);
6979 mem_cgroup_charge_statistics(memcg, newpage, nr_pages);
6980 memcg_check_events(memcg, newpage);
6981 local_irq_restore(flags);
6984 DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
6985 EXPORT_SYMBOL(memcg_sockets_enabled_key);
6987 void mem_cgroup_sk_alloc(struct sock *sk)
6989 struct mem_cgroup *memcg;
6991 if (!mem_cgroup_sockets_enabled)
6994 /* Do not associate the sock with unrelated interrupted task's memcg. */
6999 memcg = mem_cgroup_from_task(current);
7000 if (memcg == root_mem_cgroup)
7002 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg->tcpmem_active)
7004 if (css_tryget(&memcg->css))
7005 sk->sk_memcg = memcg;
7010 void mem_cgroup_sk_free(struct sock *sk)
7013 css_put(&sk->sk_memcg->css);
7017 * mem_cgroup_charge_skmem - charge socket memory
7018 * @memcg: memcg to charge
7019 * @nr_pages: number of pages to charge
7020 * @gfp_mask: reclaim mode
7022 * Charges @nr_pages to @memcg. Returns %true if the charge fit within
7023 * @memcg's configured limit, %false if it doesn't.
7025 bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages,
7028 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
7029 struct page_counter *fail;
7031 if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) {
7032 memcg->tcpmem_pressure = 0;
7035 memcg->tcpmem_pressure = 1;
7036 if (gfp_mask & __GFP_NOFAIL) {
7037 page_counter_charge(&memcg->tcpmem, nr_pages);
7043 if (try_charge(memcg, gfp_mask, nr_pages) == 0) {
7044 mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
7052 * mem_cgroup_uncharge_skmem - uncharge socket memory
7053 * @memcg: memcg to uncharge
7054 * @nr_pages: number of pages to uncharge
7056 void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
7058 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
7059 page_counter_uncharge(&memcg->tcpmem, nr_pages);
7063 mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
7065 refill_stock(memcg, nr_pages);
7068 static int __init cgroup_memory(char *s)
7072 while ((token = strsep(&s, ",")) != NULL) {
7075 if (!strcmp(token, "nosocket"))
7076 cgroup_memory_nosocket = true;
7077 if (!strcmp(token, "nokmem"))
7078 cgroup_memory_nokmem = true;
7082 __setup("cgroup.memory=", cgroup_memory);
7085 * subsys_initcall() for memory controller.
7087 * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
7088 * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
7089 * basically everything that doesn't depend on a specific mem_cgroup structure
7090 * should be initialized from here.
7092 static int __init mem_cgroup_init(void)
7097 * Currently s32 type (can refer to struct batched_lruvec_stat) is
7098 * used for per-memcg-per-cpu caching of per-node statistics. In order
7099 * to work fine, we should make sure that the overfill threshold can't
7100 * exceed S32_MAX / PAGE_SIZE.
7102 BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE);
7104 cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
7105 memcg_hotplug_cpu_dead);
7107 for_each_possible_cpu(cpu)
7108 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
7111 for_each_node(node) {
7112 struct mem_cgroup_tree_per_node *rtpn;
7114 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL,
7115 node_online(node) ? node : NUMA_NO_NODE);
7117 rtpn->rb_root = RB_ROOT;
7118 rtpn->rb_rightmost = NULL;
7119 spin_lock_init(&rtpn->lock);
7120 soft_limit_tree.rb_tree_per_node[node] = rtpn;
7125 subsys_initcall(mem_cgroup_init);
7127 #ifdef CONFIG_MEMCG_SWAP
7128 static struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
7130 while (!refcount_inc_not_zero(&memcg->id.ref)) {
7132 * The root cgroup cannot be destroyed, so it's refcount must
7135 if (WARN_ON_ONCE(memcg == root_mem_cgroup)) {
7139 memcg = parent_mem_cgroup(memcg);
7141 memcg = root_mem_cgroup;
7147 * mem_cgroup_swapout - transfer a memsw charge to swap
7148 * @page: page whose memsw charge to transfer
7149 * @entry: swap entry to move the charge to
7151 * Transfer the memsw charge of @page to @entry.
7153 void mem_cgroup_swapout(struct page *page, swp_entry_t entry)
7155 struct mem_cgroup *memcg, *swap_memcg;
7156 unsigned int nr_entries;
7157 unsigned short oldid;
7159 VM_BUG_ON_PAGE(PageLRU(page), page);
7160 VM_BUG_ON_PAGE(page_count(page), page);
7162 if (mem_cgroup_disabled())
7165 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
7168 memcg = page_memcg(page);
7170 VM_WARN_ON_ONCE_PAGE(!memcg, page);
7175 * In case the memcg owning these pages has been offlined and doesn't
7176 * have an ID allocated to it anymore, charge the closest online
7177 * ancestor for the swap instead and transfer the memory+swap charge.
7179 swap_memcg = mem_cgroup_id_get_online(memcg);
7180 nr_entries = thp_nr_pages(page);
7181 /* Get references for the tail pages, too */
7183 mem_cgroup_id_get_many(swap_memcg, nr_entries - 1);
7184 oldid = swap_cgroup_record(entry, mem_cgroup_id(swap_memcg),
7186 VM_BUG_ON_PAGE(oldid, page);
7187 mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries);
7189 page->memcg_data = 0;
7191 if (!mem_cgroup_is_root(memcg))
7192 page_counter_uncharge(&memcg->memory, nr_entries);
7194 if (!cgroup_memory_noswap && memcg != swap_memcg) {
7195 if (!mem_cgroup_is_root(swap_memcg))
7196 page_counter_charge(&swap_memcg->memsw, nr_entries);
7197 page_counter_uncharge(&memcg->memsw, nr_entries);
7201 * Interrupts should be disabled here because the caller holds the
7202 * i_pages lock which is taken with interrupts-off. It is
7203 * important here to have the interrupts disabled because it is the
7204 * only synchronisation we have for updating the per-CPU variables.
7206 VM_BUG_ON(!irqs_disabled());
7207 mem_cgroup_charge_statistics(memcg, page, -nr_entries);
7208 memcg_check_events(memcg, page);
7210 css_put(&memcg->css);
7214 * __mem_cgroup_try_charge_swap - try charging swap space for a page
7215 * @page: page being added to swap
7216 * @entry: swap entry to charge
7218 * Try to charge @page's memcg for the swap space at @entry.
7220 * Returns 0 on success, -ENOMEM on failure.
7222 int __mem_cgroup_try_charge_swap(struct page *page, swp_entry_t entry)
7224 unsigned int nr_pages = thp_nr_pages(page);
7225 struct page_counter *counter;
7226 struct mem_cgroup *memcg;
7227 unsigned short oldid;
7229 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
7232 memcg = page_memcg(page);
7234 VM_WARN_ON_ONCE_PAGE(!memcg, page);
7239 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7243 memcg = mem_cgroup_id_get_online(memcg);
7245 if (!cgroup_memory_noswap && !mem_cgroup_is_root(memcg) &&
7246 !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
7247 memcg_memory_event(memcg, MEMCG_SWAP_MAX);
7248 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7249 mem_cgroup_id_put(memcg);
7253 /* Get references for the tail pages, too */
7255 mem_cgroup_id_get_many(memcg, nr_pages - 1);
7256 oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg), nr_pages);
7257 VM_BUG_ON_PAGE(oldid, page);
7258 mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
7264 * __mem_cgroup_uncharge_swap - uncharge swap space
7265 * @entry: swap entry to uncharge
7266 * @nr_pages: the amount of swap space to uncharge
7268 void __mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
7270 struct mem_cgroup *memcg;
7273 id = swap_cgroup_record(entry, 0, nr_pages);
7275 memcg = mem_cgroup_from_id(id);
7277 if (!cgroup_memory_noswap && !mem_cgroup_is_root(memcg)) {
7278 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
7279 page_counter_uncharge(&memcg->swap, nr_pages);
7281 page_counter_uncharge(&memcg->memsw, nr_pages);
7283 mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
7284 mem_cgroup_id_put_many(memcg, nr_pages);
7289 long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
7291 long nr_swap_pages = get_nr_swap_pages();
7293 if (cgroup_memory_noswap || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
7294 return nr_swap_pages;
7295 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg))
7296 nr_swap_pages = min_t(long, nr_swap_pages,
7297 READ_ONCE(memcg->swap.max) -
7298 page_counter_read(&memcg->swap));
7299 return nr_swap_pages;
7302 bool mem_cgroup_swap_full(struct page *page)
7304 struct mem_cgroup *memcg;
7306 VM_BUG_ON_PAGE(!PageLocked(page), page);
7310 if (cgroup_memory_noswap || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
7313 memcg = page_memcg(page);
7317 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg)) {
7318 unsigned long usage = page_counter_read(&memcg->swap);
7320 if (usage * 2 >= READ_ONCE(memcg->swap.high) ||
7321 usage * 2 >= READ_ONCE(memcg->swap.max))
7328 static int __init setup_swap_account(char *s)
7330 if (!strcmp(s, "1"))
7331 cgroup_memory_noswap = false;
7332 else if (!strcmp(s, "0"))
7333 cgroup_memory_noswap = true;
7336 __setup("swapaccount=", setup_swap_account);
7338 static u64 swap_current_read(struct cgroup_subsys_state *css,
7341 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7343 return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
7346 static int swap_high_show(struct seq_file *m, void *v)
7348 return seq_puts_memcg_tunable(m,
7349 READ_ONCE(mem_cgroup_from_seq(m)->swap.high));
7352 static ssize_t swap_high_write(struct kernfs_open_file *of,
7353 char *buf, size_t nbytes, loff_t off)
7355 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7359 buf = strstrip(buf);
7360 err = page_counter_memparse(buf, "max", &high);
7364 page_counter_set_high(&memcg->swap, high);
7369 static int swap_max_show(struct seq_file *m, void *v)
7371 return seq_puts_memcg_tunable(m,
7372 READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
7375 static ssize_t swap_max_write(struct kernfs_open_file *of,
7376 char *buf, size_t nbytes, loff_t off)
7378 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7382 buf = strstrip(buf);
7383 err = page_counter_memparse(buf, "max", &max);
7387 xchg(&memcg->swap.max, max);
7392 static int swap_events_show(struct seq_file *m, void *v)
7394 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
7396 seq_printf(m, "high %lu\n",
7397 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH]));
7398 seq_printf(m, "max %lu\n",
7399 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
7400 seq_printf(m, "fail %lu\n",
7401 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
7406 static struct cftype swap_files[] = {
7408 .name = "swap.current",
7409 .flags = CFTYPE_NOT_ON_ROOT,
7410 .read_u64 = swap_current_read,
7413 .name = "swap.high",
7414 .flags = CFTYPE_NOT_ON_ROOT,
7415 .seq_show = swap_high_show,
7416 .write = swap_high_write,
7420 .flags = CFTYPE_NOT_ON_ROOT,
7421 .seq_show = swap_max_show,
7422 .write = swap_max_write,
7425 .name = "swap.events",
7426 .flags = CFTYPE_NOT_ON_ROOT,
7427 .file_offset = offsetof(struct mem_cgroup, swap_events_file),
7428 .seq_show = swap_events_show,
7433 static struct cftype memsw_files[] = {
7435 .name = "memsw.usage_in_bytes",
7436 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
7437 .read_u64 = mem_cgroup_read_u64,
7440 .name = "memsw.max_usage_in_bytes",
7441 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
7442 .write = mem_cgroup_reset,
7443 .read_u64 = mem_cgroup_read_u64,
7446 .name = "memsw.limit_in_bytes",
7447 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
7448 .write = mem_cgroup_write,
7449 .read_u64 = mem_cgroup_read_u64,
7452 .name = "memsw.failcnt",
7453 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
7454 .write = mem_cgroup_reset,
7455 .read_u64 = mem_cgroup_read_u64,
7457 { }, /* terminate */
7461 * If mem_cgroup_swap_init() is implemented as a subsys_initcall()
7462 * instead of a core_initcall(), this could mean cgroup_memory_noswap still
7463 * remains set to false even when memcg is disabled via "cgroup_disable=memory"
7464 * boot parameter. This may result in premature OOPS inside
7465 * mem_cgroup_get_nr_swap_pages() function in corner cases.
7467 static int __init mem_cgroup_swap_init(void)
7469 /* No memory control -> no swap control */
7470 if (mem_cgroup_disabled())
7471 cgroup_memory_noswap = true;
7473 if (cgroup_memory_noswap)
7476 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files));
7477 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files));
7481 core_initcall(mem_cgroup_swap_init);
7483 #endif /* CONFIG_MEMCG_SWAP */