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 task_is_dying(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 = task_is_dying() || 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 passed_oom = false;
2534 bool may_swap = true;
2535 bool drained = false;
2536 unsigned long pflags;
2539 if (consume_stock(memcg, nr_pages))
2542 if (!do_memsw_account() ||
2543 page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2544 if (page_counter_try_charge(&memcg->memory, batch, &counter))
2546 if (do_memsw_account())
2547 page_counter_uncharge(&memcg->memsw, batch);
2548 mem_over_limit = mem_cgroup_from_counter(counter, memory);
2550 mem_over_limit = mem_cgroup_from_counter(counter, memsw);
2554 if (batch > nr_pages) {
2560 * Memcg doesn't have a dedicated reserve for atomic
2561 * allocations. But like the global atomic pool, we need to
2562 * put the burden of reclaim on regular allocation requests
2563 * and let these go through as privileged allocations.
2565 if (gfp_mask & __GFP_ATOMIC)
2569 * Prevent unbounded recursion when reclaim operations need to
2570 * allocate memory. This might exceed the limits temporarily,
2571 * but we prefer facilitating memory reclaim and getting back
2572 * under the limit over triggering OOM kills in these cases.
2574 if (unlikely(current->flags & PF_MEMALLOC))
2577 if (unlikely(task_in_memcg_oom(current)))
2580 if (!gfpflags_allow_blocking(gfp_mask))
2583 memcg_memory_event(mem_over_limit, MEMCG_MAX);
2585 psi_memstall_enter(&pflags);
2586 nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
2587 gfp_mask, may_swap);
2588 psi_memstall_leave(&pflags);
2590 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2594 drain_all_stock(mem_over_limit);
2599 if (gfp_mask & __GFP_NORETRY)
2602 * Even though the limit is exceeded at this point, reclaim
2603 * may have been able to free some pages. Retry the charge
2604 * before killing the task.
2606 * Only for regular pages, though: huge pages are rather
2607 * unlikely to succeed so close to the limit, and we fall back
2608 * to regular pages anyway in case of failure.
2610 if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
2613 * At task move, charge accounts can be doubly counted. So, it's
2614 * better to wait until the end of task_move if something is going on.
2616 if (mem_cgroup_wait_acct_move(mem_over_limit))
2622 if (gfp_mask & __GFP_RETRY_MAYFAIL)
2625 /* Avoid endless loop for tasks bypassed by the oom killer */
2626 if (passed_oom && task_is_dying())
2630 * keep retrying as long as the memcg oom killer is able to make
2631 * a forward progress or bypass the charge if the oom killer
2632 * couldn't make any progress.
2634 oom_status = mem_cgroup_oom(mem_over_limit, gfp_mask,
2635 get_order(nr_pages * PAGE_SIZE));
2636 if (oom_status == OOM_SUCCESS) {
2638 nr_retries = MAX_RECLAIM_RETRIES;
2642 if (!(gfp_mask & __GFP_NOFAIL))
2646 * The allocation either can't fail or will lead to more memory
2647 * being freed very soon. Allow memory usage go over the limit
2648 * temporarily by force charging it.
2650 page_counter_charge(&memcg->memory, nr_pages);
2651 if (do_memsw_account())
2652 page_counter_charge(&memcg->memsw, nr_pages);
2657 if (batch > nr_pages)
2658 refill_stock(memcg, batch - nr_pages);
2661 * If the hierarchy is above the normal consumption range, schedule
2662 * reclaim on returning to userland. We can perform reclaim here
2663 * if __GFP_RECLAIM but let's always punt for simplicity and so that
2664 * GFP_KERNEL can consistently be used during reclaim. @memcg is
2665 * not recorded as it most likely matches current's and won't
2666 * change in the meantime. As high limit is checked again before
2667 * reclaim, the cost of mismatch is negligible.
2670 bool mem_high, swap_high;
2672 mem_high = page_counter_read(&memcg->memory) >
2673 READ_ONCE(memcg->memory.high);
2674 swap_high = page_counter_read(&memcg->swap) >
2675 READ_ONCE(memcg->swap.high);
2677 /* Don't bother a random interrupted task */
2678 if (in_interrupt()) {
2680 schedule_work(&memcg->high_work);
2686 if (mem_high || swap_high) {
2688 * The allocating tasks in this cgroup will need to do
2689 * reclaim or be throttled to prevent further growth
2690 * of the memory or swap footprints.
2692 * Target some best-effort fairness between the tasks,
2693 * and distribute reclaim work and delay penalties
2694 * based on how much each task is actually allocating.
2696 current->memcg_nr_pages_over_high += batch;
2697 set_notify_resume(current);
2700 } while ((memcg = parent_mem_cgroup(memcg)));
2705 static inline int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2706 unsigned int nr_pages)
2708 if (mem_cgroup_is_root(memcg))
2711 return try_charge_memcg(memcg, gfp_mask, nr_pages);
2714 #if defined(CONFIG_MEMCG_KMEM) || defined(CONFIG_MMU)
2715 static void cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
2717 if (mem_cgroup_is_root(memcg))
2720 page_counter_uncharge(&memcg->memory, nr_pages);
2721 if (do_memsw_account())
2722 page_counter_uncharge(&memcg->memsw, nr_pages);
2726 static void commit_charge(struct page *page, struct mem_cgroup *memcg)
2728 VM_BUG_ON_PAGE(page_memcg(page), page);
2730 * Any of the following ensures page's memcg stability:
2734 * - lock_page_memcg()
2735 * - exclusive reference
2737 page->memcg_data = (unsigned long)memcg;
2740 static struct mem_cgroup *get_mem_cgroup_from_objcg(struct obj_cgroup *objcg)
2742 struct mem_cgroup *memcg;
2746 memcg = obj_cgroup_memcg(objcg);
2747 if (unlikely(!css_tryget(&memcg->css)))
2754 #ifdef CONFIG_MEMCG_KMEM
2756 * The allocated objcg pointers array is not accounted directly.
2757 * Moreover, it should not come from DMA buffer and is not readily
2758 * reclaimable. So those GFP bits should be masked off.
2760 #define OBJCGS_CLEAR_MASK (__GFP_DMA | __GFP_RECLAIMABLE | __GFP_ACCOUNT)
2762 int memcg_alloc_page_obj_cgroups(struct page *page, struct kmem_cache *s,
2763 gfp_t gfp, bool new_page)
2765 unsigned int objects = objs_per_slab_page(s, page);
2766 unsigned long memcg_data;
2769 gfp &= ~OBJCGS_CLEAR_MASK;
2770 vec = kcalloc_node(objects, sizeof(struct obj_cgroup *), gfp,
2775 memcg_data = (unsigned long) vec | MEMCG_DATA_OBJCGS;
2778 * If the slab page is brand new and nobody can yet access
2779 * it's memcg_data, no synchronization is required and
2780 * memcg_data can be simply assigned.
2782 page->memcg_data = memcg_data;
2783 } else if (cmpxchg(&page->memcg_data, 0, memcg_data)) {
2785 * If the slab page is already in use, somebody can allocate
2786 * and assign obj_cgroups in parallel. In this case the existing
2787 * objcg vector should be reused.
2793 kmemleak_not_leak(vec);
2798 * Returns a pointer to the memory cgroup to which the kernel object is charged.
2800 * A passed kernel object can be a slab object or a generic kernel page, so
2801 * different mechanisms for getting the memory cgroup pointer should be used.
2802 * In certain cases (e.g. kernel stacks or large kmallocs with SLUB) the caller
2803 * can not know for sure how the kernel object is implemented.
2804 * mem_cgroup_from_obj() can be safely used in such cases.
2806 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
2807 * cgroup_mutex, etc.
2809 struct mem_cgroup *mem_cgroup_from_obj(void *p)
2813 if (mem_cgroup_disabled())
2816 page = virt_to_head_page(p);
2819 * Slab objects are accounted individually, not per-page.
2820 * Memcg membership data for each individual object is saved in
2821 * the page->obj_cgroups.
2823 if (page_objcgs_check(page)) {
2824 struct obj_cgroup *objcg;
2827 off = obj_to_index(page->slab_cache, page, p);
2828 objcg = page_objcgs(page)[off];
2830 return obj_cgroup_memcg(objcg);
2836 * page_memcg_check() is used here, because page_has_obj_cgroups()
2837 * check above could fail because the object cgroups vector wasn't set
2838 * at that moment, but it can be set concurrently.
2839 * page_memcg_check(page) will guarantee that a proper memory
2840 * cgroup pointer or NULL will be returned.
2842 return page_memcg_check(page);
2845 __always_inline struct obj_cgroup *get_obj_cgroup_from_current(void)
2847 struct obj_cgroup *objcg = NULL;
2848 struct mem_cgroup *memcg;
2850 if (memcg_kmem_bypass())
2854 if (unlikely(active_memcg()))
2855 memcg = active_memcg();
2857 memcg = mem_cgroup_from_task(current);
2859 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg)) {
2860 objcg = rcu_dereference(memcg->objcg);
2861 if (objcg && obj_cgroup_tryget(objcg))
2870 static int memcg_alloc_cache_id(void)
2875 id = ida_simple_get(&memcg_cache_ida,
2876 0, MEMCG_CACHES_MAX_SIZE, GFP_KERNEL);
2880 if (id < memcg_nr_cache_ids)
2884 * There's no space for the new id in memcg_caches arrays,
2885 * so we have to grow them.
2887 down_write(&memcg_cache_ids_sem);
2889 size = 2 * (id + 1);
2890 if (size < MEMCG_CACHES_MIN_SIZE)
2891 size = MEMCG_CACHES_MIN_SIZE;
2892 else if (size > MEMCG_CACHES_MAX_SIZE)
2893 size = MEMCG_CACHES_MAX_SIZE;
2895 err = memcg_update_all_list_lrus(size);
2897 memcg_nr_cache_ids = size;
2899 up_write(&memcg_cache_ids_sem);
2902 ida_simple_remove(&memcg_cache_ida, id);
2908 static void memcg_free_cache_id(int id)
2910 ida_simple_remove(&memcg_cache_ida, id);
2914 * obj_cgroup_uncharge_pages: uncharge a number of kernel pages from a objcg
2915 * @objcg: object cgroup to uncharge
2916 * @nr_pages: number of pages to uncharge
2918 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
2919 unsigned int nr_pages)
2921 struct mem_cgroup *memcg;
2923 memcg = get_mem_cgroup_from_objcg(objcg);
2925 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
2926 page_counter_uncharge(&memcg->kmem, nr_pages);
2927 refill_stock(memcg, nr_pages);
2929 css_put(&memcg->css);
2933 * obj_cgroup_charge_pages: charge a number of kernel pages to a objcg
2934 * @objcg: object cgroup to charge
2935 * @gfp: reclaim mode
2936 * @nr_pages: number of pages to charge
2938 * Returns 0 on success, an error code on failure.
2940 static int obj_cgroup_charge_pages(struct obj_cgroup *objcg, gfp_t gfp,
2941 unsigned int nr_pages)
2943 struct page_counter *counter;
2944 struct mem_cgroup *memcg;
2947 memcg = get_mem_cgroup_from_objcg(objcg);
2949 ret = try_charge_memcg(memcg, gfp, nr_pages);
2953 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) &&
2954 !page_counter_try_charge(&memcg->kmem, nr_pages, &counter)) {
2957 * Enforce __GFP_NOFAIL allocation because callers are not
2958 * prepared to see failures and likely do not have any failure
2961 if (gfp & __GFP_NOFAIL) {
2962 page_counter_charge(&memcg->kmem, nr_pages);
2965 cancel_charge(memcg, nr_pages);
2969 css_put(&memcg->css);
2975 * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup
2976 * @page: page to charge
2977 * @gfp: reclaim mode
2978 * @order: allocation order
2980 * Returns 0 on success, an error code on failure.
2982 int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
2984 struct obj_cgroup *objcg;
2987 objcg = get_obj_cgroup_from_current();
2989 ret = obj_cgroup_charge_pages(objcg, gfp, 1 << order);
2991 page->memcg_data = (unsigned long)objcg |
2995 obj_cgroup_put(objcg);
3001 * __memcg_kmem_uncharge_page: uncharge a kmem page
3002 * @page: page to uncharge
3003 * @order: allocation order
3005 void __memcg_kmem_uncharge_page(struct page *page, int order)
3007 struct obj_cgroup *objcg;
3008 unsigned int nr_pages = 1 << order;
3010 if (!PageMemcgKmem(page))
3013 objcg = __page_objcg(page);
3014 obj_cgroup_uncharge_pages(objcg, nr_pages);
3015 page->memcg_data = 0;
3016 obj_cgroup_put(objcg);
3019 void mod_objcg_state(struct obj_cgroup *objcg, struct pglist_data *pgdat,
3020 enum node_stat_item idx, int nr)
3022 unsigned long flags;
3023 struct obj_stock *stock = get_obj_stock(&flags);
3027 * Save vmstat data in stock and skip vmstat array update unless
3028 * accumulating over a page of vmstat data or when pgdat or idx
3031 if (stock->cached_objcg != objcg) {
3032 drain_obj_stock(stock);
3033 obj_cgroup_get(objcg);
3034 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3035 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3036 stock->cached_objcg = objcg;
3037 stock->cached_pgdat = pgdat;
3038 } else if (stock->cached_pgdat != pgdat) {
3039 /* Flush the existing cached vmstat data */
3040 struct pglist_data *oldpg = stock->cached_pgdat;
3042 if (stock->nr_slab_reclaimable_b) {
3043 mod_objcg_mlstate(objcg, oldpg, NR_SLAB_RECLAIMABLE_B,
3044 stock->nr_slab_reclaimable_b);
3045 stock->nr_slab_reclaimable_b = 0;
3047 if (stock->nr_slab_unreclaimable_b) {
3048 mod_objcg_mlstate(objcg, oldpg, NR_SLAB_UNRECLAIMABLE_B,
3049 stock->nr_slab_unreclaimable_b);
3050 stock->nr_slab_unreclaimable_b = 0;
3052 stock->cached_pgdat = pgdat;
3055 bytes = (idx == NR_SLAB_RECLAIMABLE_B) ? &stock->nr_slab_reclaimable_b
3056 : &stock->nr_slab_unreclaimable_b;
3058 * Even for large object >= PAGE_SIZE, the vmstat data will still be
3059 * cached locally at least once before pushing it out.
3066 if (abs(*bytes) > PAGE_SIZE) {
3074 mod_objcg_mlstate(objcg, pgdat, idx, nr);
3076 put_obj_stock(flags);
3079 static bool consume_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes)
3081 unsigned long flags;
3082 struct obj_stock *stock = get_obj_stock(&flags);
3085 if (objcg == stock->cached_objcg && stock->nr_bytes >= nr_bytes) {
3086 stock->nr_bytes -= nr_bytes;
3090 put_obj_stock(flags);
3095 static void drain_obj_stock(struct obj_stock *stock)
3097 struct obj_cgroup *old = stock->cached_objcg;
3102 if (stock->nr_bytes) {
3103 unsigned int nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3104 unsigned int nr_bytes = stock->nr_bytes & (PAGE_SIZE - 1);
3107 obj_cgroup_uncharge_pages(old, nr_pages);
3110 * The leftover is flushed to the centralized per-memcg value.
3111 * On the next attempt to refill obj stock it will be moved
3112 * to a per-cpu stock (probably, on an other CPU), see
3113 * refill_obj_stock().
3115 * How often it's flushed is a trade-off between the memory
3116 * limit enforcement accuracy and potential CPU contention,
3117 * so it might be changed in the future.
3119 atomic_add(nr_bytes, &old->nr_charged_bytes);
3120 stock->nr_bytes = 0;
3124 * Flush the vmstat data in current stock
3126 if (stock->nr_slab_reclaimable_b || stock->nr_slab_unreclaimable_b) {
3127 if (stock->nr_slab_reclaimable_b) {
3128 mod_objcg_mlstate(old, stock->cached_pgdat,
3129 NR_SLAB_RECLAIMABLE_B,
3130 stock->nr_slab_reclaimable_b);
3131 stock->nr_slab_reclaimable_b = 0;
3133 if (stock->nr_slab_unreclaimable_b) {
3134 mod_objcg_mlstate(old, stock->cached_pgdat,
3135 NR_SLAB_UNRECLAIMABLE_B,
3136 stock->nr_slab_unreclaimable_b);
3137 stock->nr_slab_unreclaimable_b = 0;
3139 stock->cached_pgdat = NULL;
3142 obj_cgroup_put(old);
3143 stock->cached_objcg = NULL;
3146 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
3147 struct mem_cgroup *root_memcg)
3149 struct mem_cgroup *memcg;
3151 if (in_task() && stock->task_obj.cached_objcg) {
3152 memcg = obj_cgroup_memcg(stock->task_obj.cached_objcg);
3153 if (memcg && mem_cgroup_is_descendant(memcg, root_memcg))
3156 if (stock->irq_obj.cached_objcg) {
3157 memcg = obj_cgroup_memcg(stock->irq_obj.cached_objcg);
3158 if (memcg && mem_cgroup_is_descendant(memcg, root_memcg))
3165 static void refill_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes,
3166 bool allow_uncharge)
3168 unsigned long flags;
3169 struct obj_stock *stock = get_obj_stock(&flags);
3170 unsigned int nr_pages = 0;
3172 if (stock->cached_objcg != objcg) { /* reset if necessary */
3173 drain_obj_stock(stock);
3174 obj_cgroup_get(objcg);
3175 stock->cached_objcg = objcg;
3176 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3177 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3178 allow_uncharge = true; /* Allow uncharge when objcg changes */
3180 stock->nr_bytes += nr_bytes;
3182 if (allow_uncharge && (stock->nr_bytes > PAGE_SIZE)) {
3183 nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3184 stock->nr_bytes &= (PAGE_SIZE - 1);
3187 put_obj_stock(flags);
3190 obj_cgroup_uncharge_pages(objcg, nr_pages);
3193 int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size)
3195 unsigned int nr_pages, nr_bytes;
3198 if (consume_obj_stock(objcg, size))
3202 * In theory, objcg->nr_charged_bytes can have enough
3203 * pre-charged bytes to satisfy the allocation. However,
3204 * flushing objcg->nr_charged_bytes requires two atomic
3205 * operations, and objcg->nr_charged_bytes can't be big.
3206 * The shared objcg->nr_charged_bytes can also become a
3207 * performance bottleneck if all tasks of the same memcg are
3208 * trying to update it. So it's better to ignore it and try
3209 * grab some new pages. The stock's nr_bytes will be flushed to
3210 * objcg->nr_charged_bytes later on when objcg changes.
3212 * The stock's nr_bytes may contain enough pre-charged bytes
3213 * to allow one less page from being charged, but we can't rely
3214 * on the pre-charged bytes not being changed outside of
3215 * consume_obj_stock() or refill_obj_stock(). So ignore those
3216 * pre-charged bytes as well when charging pages. To avoid a
3217 * page uncharge right after a page charge, we set the
3218 * allow_uncharge flag to false when calling refill_obj_stock()
3219 * to temporarily allow the pre-charged bytes to exceed the page
3220 * size limit. The maximum reachable value of the pre-charged
3221 * bytes is (sizeof(object) + PAGE_SIZE - 2) if there is no data
3224 nr_pages = size >> PAGE_SHIFT;
3225 nr_bytes = size & (PAGE_SIZE - 1);
3230 ret = obj_cgroup_charge_pages(objcg, gfp, nr_pages);
3231 if (!ret && nr_bytes)
3232 refill_obj_stock(objcg, PAGE_SIZE - nr_bytes, false);
3237 void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size)
3239 refill_obj_stock(objcg, size, true);
3242 #endif /* CONFIG_MEMCG_KMEM */
3245 * Because page_memcg(head) is not set on tails, set it now.
3247 void split_page_memcg(struct page *head, unsigned int nr)
3249 struct mem_cgroup *memcg = page_memcg(head);
3252 if (mem_cgroup_disabled() || !memcg)
3255 for (i = 1; i < nr; i++)
3256 head[i].memcg_data = head->memcg_data;
3258 if (PageMemcgKmem(head))
3259 obj_cgroup_get_many(__page_objcg(head), nr - 1);
3261 css_get_many(&memcg->css, nr - 1);
3264 #ifdef CONFIG_MEMCG_SWAP
3266 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3267 * @entry: swap entry to be moved
3268 * @from: mem_cgroup which the entry is moved from
3269 * @to: mem_cgroup which the entry is moved to
3271 * It succeeds only when the swap_cgroup's record for this entry is the same
3272 * as the mem_cgroup's id of @from.
3274 * Returns 0 on success, -EINVAL on failure.
3276 * The caller must have charged to @to, IOW, called page_counter_charge() about
3277 * both res and memsw, and called css_get().
3279 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3280 struct mem_cgroup *from, struct mem_cgroup *to)
3282 unsigned short old_id, new_id;
3284 old_id = mem_cgroup_id(from);
3285 new_id = mem_cgroup_id(to);
3287 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3288 mod_memcg_state(from, MEMCG_SWAP, -1);
3289 mod_memcg_state(to, MEMCG_SWAP, 1);
3295 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3296 struct mem_cgroup *from, struct mem_cgroup *to)
3302 static DEFINE_MUTEX(memcg_max_mutex);
3304 static int mem_cgroup_resize_max(struct mem_cgroup *memcg,
3305 unsigned long max, bool memsw)
3307 bool enlarge = false;
3308 bool drained = false;
3310 bool limits_invariant;
3311 struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory;
3314 if (signal_pending(current)) {
3319 mutex_lock(&memcg_max_mutex);
3321 * Make sure that the new limit (memsw or memory limit) doesn't
3322 * break our basic invariant rule memory.max <= memsw.max.
3324 limits_invariant = memsw ? max >= READ_ONCE(memcg->memory.max) :
3325 max <= memcg->memsw.max;
3326 if (!limits_invariant) {
3327 mutex_unlock(&memcg_max_mutex);
3331 if (max > counter->max)
3333 ret = page_counter_set_max(counter, max);
3334 mutex_unlock(&memcg_max_mutex);
3340 drain_all_stock(memcg);
3345 if (!try_to_free_mem_cgroup_pages(memcg, 1,
3346 GFP_KERNEL, !memsw)) {
3352 if (!ret && enlarge)
3353 memcg_oom_recover(memcg);
3358 unsigned long mem_cgroup_soft_limit_reclaim(pg_data_t *pgdat, int order,
3360 unsigned long *total_scanned)
3362 unsigned long nr_reclaimed = 0;
3363 struct mem_cgroup_per_node *mz, *next_mz = NULL;
3364 unsigned long reclaimed;
3366 struct mem_cgroup_tree_per_node *mctz;
3367 unsigned long excess;
3368 unsigned long nr_scanned;
3373 mctz = soft_limit_tree_node(pgdat->node_id);
3376 * Do not even bother to check the largest node if the root
3377 * is empty. Do it lockless to prevent lock bouncing. Races
3378 * are acceptable as soft limit is best effort anyway.
3380 if (!mctz || RB_EMPTY_ROOT(&mctz->rb_root))
3384 * This loop can run a while, specially if mem_cgroup's continuously
3385 * keep exceeding their soft limit and putting the system under
3392 mz = mem_cgroup_largest_soft_limit_node(mctz);
3397 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, pgdat,
3398 gfp_mask, &nr_scanned);
3399 nr_reclaimed += reclaimed;
3400 *total_scanned += nr_scanned;
3401 spin_lock_irq(&mctz->lock);
3402 __mem_cgroup_remove_exceeded(mz, mctz);
3405 * If we failed to reclaim anything from this memory cgroup
3406 * it is time to move on to the next cgroup
3410 next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
3412 excess = soft_limit_excess(mz->memcg);
3414 * One school of thought says that we should not add
3415 * back the node to the tree if reclaim returns 0.
3416 * But our reclaim could return 0, simply because due
3417 * to priority we are exposing a smaller subset of
3418 * memory to reclaim from. Consider this as a longer
3421 /* If excess == 0, no tree ops */
3422 __mem_cgroup_insert_exceeded(mz, mctz, excess);
3423 spin_unlock_irq(&mctz->lock);
3424 css_put(&mz->memcg->css);
3427 * Could not reclaim anything and there are no more
3428 * mem cgroups to try or we seem to be looping without
3429 * reclaiming anything.
3431 if (!nr_reclaimed &&
3433 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3435 } while (!nr_reclaimed);
3437 css_put(&next_mz->memcg->css);
3438 return nr_reclaimed;
3442 * Reclaims as many pages from the given memcg as possible.
3444 * Caller is responsible for holding css reference for memcg.
3446 static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
3448 int nr_retries = MAX_RECLAIM_RETRIES;
3450 /* we call try-to-free pages for make this cgroup empty */
3451 lru_add_drain_all();
3453 drain_all_stock(memcg);
3455 /* try to free all pages in this cgroup */
3456 while (nr_retries && page_counter_read(&memcg->memory)) {
3459 if (signal_pending(current))
3462 progress = try_to_free_mem_cgroup_pages(memcg, 1,
3466 /* maybe some writeback is necessary */
3467 congestion_wait(BLK_RW_ASYNC, HZ/10);
3475 static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
3476 char *buf, size_t nbytes,
3479 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3481 if (mem_cgroup_is_root(memcg))
3483 return mem_cgroup_force_empty(memcg) ?: nbytes;
3486 static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
3492 static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
3493 struct cftype *cft, u64 val)
3498 pr_warn_once("Non-hierarchical mode is deprecated. "
3499 "Please report your usecase to linux-mm@kvack.org if you "
3500 "depend on this functionality.\n");
3505 static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3509 if (mem_cgroup_is_root(memcg)) {
3510 /* mem_cgroup_threshold() calls here from irqsafe context */
3511 cgroup_rstat_flush_irqsafe(memcg->css.cgroup);
3512 val = memcg_page_state(memcg, NR_FILE_PAGES) +
3513 memcg_page_state(memcg, NR_ANON_MAPPED);
3515 val += memcg_page_state(memcg, MEMCG_SWAP);
3518 val = page_counter_read(&memcg->memory);
3520 val = page_counter_read(&memcg->memsw);
3533 static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
3536 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3537 struct page_counter *counter;
3539 switch (MEMFILE_TYPE(cft->private)) {
3541 counter = &memcg->memory;
3544 counter = &memcg->memsw;
3547 counter = &memcg->kmem;
3550 counter = &memcg->tcpmem;
3556 switch (MEMFILE_ATTR(cft->private)) {
3558 if (counter == &memcg->memory)
3559 return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
3560 if (counter == &memcg->memsw)
3561 return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
3562 return (u64)page_counter_read(counter) * PAGE_SIZE;
3564 return (u64)counter->max * PAGE_SIZE;
3566 return (u64)counter->watermark * PAGE_SIZE;
3568 return counter->failcnt;
3569 case RES_SOFT_LIMIT:
3570 return (u64)memcg->soft_limit * PAGE_SIZE;
3576 #ifdef CONFIG_MEMCG_KMEM
3577 static int memcg_online_kmem(struct mem_cgroup *memcg)
3579 struct obj_cgroup *objcg;
3582 if (cgroup_memory_nokmem)
3585 BUG_ON(memcg->kmemcg_id >= 0);
3586 BUG_ON(memcg->kmem_state);
3588 memcg_id = memcg_alloc_cache_id();
3592 objcg = obj_cgroup_alloc();
3594 memcg_free_cache_id(memcg_id);
3597 objcg->memcg = memcg;
3598 rcu_assign_pointer(memcg->objcg, objcg);
3600 static_branch_enable(&memcg_kmem_enabled_key);
3602 memcg->kmemcg_id = memcg_id;
3603 memcg->kmem_state = KMEM_ONLINE;
3608 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3610 struct cgroup_subsys_state *css;
3611 struct mem_cgroup *parent, *child;
3614 if (memcg->kmem_state != KMEM_ONLINE)
3617 memcg->kmem_state = KMEM_ALLOCATED;
3619 parent = parent_mem_cgroup(memcg);
3621 parent = root_mem_cgroup;
3623 memcg_reparent_objcgs(memcg, parent);
3625 kmemcg_id = memcg->kmemcg_id;
3626 BUG_ON(kmemcg_id < 0);
3629 * Change kmemcg_id of this cgroup and all its descendants to the
3630 * parent's id, and then move all entries from this cgroup's list_lrus
3631 * to ones of the parent. After we have finished, all list_lrus
3632 * corresponding to this cgroup are guaranteed to remain empty. The
3633 * ordering is imposed by list_lru_node->lock taken by
3634 * memcg_drain_all_list_lrus().
3636 rcu_read_lock(); /* can be called from css_free w/o cgroup_mutex */
3637 css_for_each_descendant_pre(css, &memcg->css) {
3638 child = mem_cgroup_from_css(css);
3639 BUG_ON(child->kmemcg_id != kmemcg_id);
3640 child->kmemcg_id = parent->kmemcg_id;
3644 memcg_drain_all_list_lrus(kmemcg_id, parent);
3646 memcg_free_cache_id(kmemcg_id);
3649 static void memcg_free_kmem(struct mem_cgroup *memcg)
3651 /* css_alloc() failed, offlining didn't happen */
3652 if (unlikely(memcg->kmem_state == KMEM_ONLINE))
3653 memcg_offline_kmem(memcg);
3656 static int memcg_online_kmem(struct mem_cgroup *memcg)
3660 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3663 static void memcg_free_kmem(struct mem_cgroup *memcg)
3666 #endif /* CONFIG_MEMCG_KMEM */
3668 static int memcg_update_kmem_max(struct mem_cgroup *memcg,
3673 mutex_lock(&memcg_max_mutex);
3674 ret = page_counter_set_max(&memcg->kmem, max);
3675 mutex_unlock(&memcg_max_mutex);
3679 static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max)
3683 mutex_lock(&memcg_max_mutex);
3685 ret = page_counter_set_max(&memcg->tcpmem, max);
3689 if (!memcg->tcpmem_active) {
3691 * The active flag needs to be written after the static_key
3692 * update. This is what guarantees that the socket activation
3693 * function is the last one to run. See mem_cgroup_sk_alloc()
3694 * for details, and note that we don't mark any socket as
3695 * belonging to this memcg until that flag is up.
3697 * We need to do this, because static_keys will span multiple
3698 * sites, but we can't control their order. If we mark a socket
3699 * as accounted, but the accounting functions are not patched in
3700 * yet, we'll lose accounting.
3702 * We never race with the readers in mem_cgroup_sk_alloc(),
3703 * because when this value change, the code to process it is not
3706 static_branch_inc(&memcg_sockets_enabled_key);
3707 memcg->tcpmem_active = true;
3710 mutex_unlock(&memcg_max_mutex);
3715 * The user of this function is...
3718 static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
3719 char *buf, size_t nbytes, loff_t off)
3721 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3722 unsigned long nr_pages;
3725 buf = strstrip(buf);
3726 ret = page_counter_memparse(buf, "-1", &nr_pages);
3730 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3732 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3736 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3738 ret = mem_cgroup_resize_max(memcg, nr_pages, false);
3741 ret = mem_cgroup_resize_max(memcg, nr_pages, true);
3744 pr_warn_once("kmem.limit_in_bytes is deprecated and will be removed. "
3745 "Please report your usecase to linux-mm@kvack.org if you "
3746 "depend on this functionality.\n");
3747 ret = memcg_update_kmem_max(memcg, nr_pages);
3750 ret = memcg_update_tcp_max(memcg, nr_pages);
3754 case RES_SOFT_LIMIT:
3755 memcg->soft_limit = nr_pages;
3759 return ret ?: nbytes;
3762 static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
3763 size_t nbytes, loff_t off)
3765 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3766 struct page_counter *counter;
3768 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3770 counter = &memcg->memory;
3773 counter = &memcg->memsw;
3776 counter = &memcg->kmem;
3779 counter = &memcg->tcpmem;
3785 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3787 page_counter_reset_watermark(counter);
3790 counter->failcnt = 0;
3799 static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
3802 return mem_cgroup_from_css(css)->move_charge_at_immigrate;
3806 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3807 struct cftype *cft, u64 val)
3809 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3811 if (val & ~MOVE_MASK)
3815 * No kind of locking is needed in here, because ->can_attach() will
3816 * check this value once in the beginning of the process, and then carry
3817 * on with stale data. This means that changes to this value will only
3818 * affect task migrations starting after the change.
3820 memcg->move_charge_at_immigrate = val;
3824 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3825 struct cftype *cft, u64 val)
3833 #define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE))
3834 #define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON))
3835 #define LRU_ALL ((1 << NR_LRU_LISTS) - 1)
3837 static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
3838 int nid, unsigned int lru_mask, bool tree)
3840 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
3841 unsigned long nr = 0;
3844 VM_BUG_ON((unsigned)nid >= nr_node_ids);
3847 if (!(BIT(lru) & lru_mask))
3850 nr += lruvec_page_state(lruvec, NR_LRU_BASE + lru);
3852 nr += lruvec_page_state_local(lruvec, NR_LRU_BASE + lru);
3857 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
3858 unsigned int lru_mask,
3861 unsigned long nr = 0;
3865 if (!(BIT(lru) & lru_mask))
3868 nr += memcg_page_state(memcg, NR_LRU_BASE + lru);
3870 nr += memcg_page_state_local(memcg, NR_LRU_BASE + lru);
3875 static int memcg_numa_stat_show(struct seq_file *m, void *v)
3879 unsigned int lru_mask;
3882 static const struct numa_stat stats[] = {
3883 { "total", LRU_ALL },
3884 { "file", LRU_ALL_FILE },
3885 { "anon", LRU_ALL_ANON },
3886 { "unevictable", BIT(LRU_UNEVICTABLE) },
3888 const struct numa_stat *stat;
3890 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
3892 cgroup_rstat_flush(memcg->css.cgroup);
3894 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
3895 seq_printf(m, "%s=%lu", stat->name,
3896 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
3898 for_each_node_state(nid, N_MEMORY)
3899 seq_printf(m, " N%d=%lu", nid,
3900 mem_cgroup_node_nr_lru_pages(memcg, nid,
3901 stat->lru_mask, false));
3905 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
3907 seq_printf(m, "hierarchical_%s=%lu", stat->name,
3908 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
3910 for_each_node_state(nid, N_MEMORY)
3911 seq_printf(m, " N%d=%lu", nid,
3912 mem_cgroup_node_nr_lru_pages(memcg, nid,
3913 stat->lru_mask, true));
3919 #endif /* CONFIG_NUMA */
3921 static const unsigned int memcg1_stats[] = {
3924 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3934 static const char *const memcg1_stat_names[] = {
3937 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3947 /* Universal VM events cgroup1 shows, original sort order */
3948 static const unsigned int memcg1_events[] = {
3955 static int memcg_stat_show(struct seq_file *m, void *v)
3957 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
3958 unsigned long memory, memsw;
3959 struct mem_cgroup *mi;
3962 BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats));
3964 cgroup_rstat_flush(memcg->css.cgroup);
3966 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
3969 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
3971 nr = memcg_page_state_local(memcg, memcg1_stats[i]);
3972 seq_printf(m, "%s %lu\n", memcg1_stat_names[i], nr * PAGE_SIZE);
3975 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
3976 seq_printf(m, "%s %lu\n", vm_event_name(memcg1_events[i]),
3977 memcg_events_local(memcg, memcg1_events[i]));
3979 for (i = 0; i < NR_LRU_LISTS; i++)
3980 seq_printf(m, "%s %lu\n", lru_list_name(i),
3981 memcg_page_state_local(memcg, NR_LRU_BASE + i) *
3984 /* Hierarchical information */
3985 memory = memsw = PAGE_COUNTER_MAX;
3986 for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
3987 memory = min(memory, READ_ONCE(mi->memory.max));
3988 memsw = min(memsw, READ_ONCE(mi->memsw.max));
3990 seq_printf(m, "hierarchical_memory_limit %llu\n",
3991 (u64)memory * PAGE_SIZE);
3992 if (do_memsw_account())
3993 seq_printf(m, "hierarchical_memsw_limit %llu\n",
3994 (u64)memsw * PAGE_SIZE);
3996 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
3999 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
4001 nr = memcg_page_state(memcg, memcg1_stats[i]);
4002 seq_printf(m, "total_%s %llu\n", memcg1_stat_names[i],
4003 (u64)nr * PAGE_SIZE);
4006 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
4007 seq_printf(m, "total_%s %llu\n",
4008 vm_event_name(memcg1_events[i]),
4009 (u64)memcg_events(memcg, memcg1_events[i]));
4011 for (i = 0; i < NR_LRU_LISTS; i++)
4012 seq_printf(m, "total_%s %llu\n", lru_list_name(i),
4013 (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
4016 #ifdef CONFIG_DEBUG_VM
4019 struct mem_cgroup_per_node *mz;
4020 unsigned long anon_cost = 0;
4021 unsigned long file_cost = 0;
4023 for_each_online_pgdat(pgdat) {
4024 mz = memcg->nodeinfo[pgdat->node_id];
4026 anon_cost += mz->lruvec.anon_cost;
4027 file_cost += mz->lruvec.file_cost;
4029 seq_printf(m, "anon_cost %lu\n", anon_cost);
4030 seq_printf(m, "file_cost %lu\n", file_cost);
4037 static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
4040 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4042 return mem_cgroup_swappiness(memcg);
4045 static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
4046 struct cftype *cft, u64 val)
4048 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4053 if (!mem_cgroup_is_root(memcg))
4054 memcg->swappiness = val;
4056 vm_swappiness = val;
4061 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4063 struct mem_cgroup_threshold_ary *t;
4064 unsigned long usage;
4069 t = rcu_dereference(memcg->thresholds.primary);
4071 t = rcu_dereference(memcg->memsw_thresholds.primary);
4076 usage = mem_cgroup_usage(memcg, swap);
4079 * current_threshold points to threshold just below or equal to usage.
4080 * If it's not true, a threshold was crossed after last
4081 * call of __mem_cgroup_threshold().
4083 i = t->current_threshold;
4086 * Iterate backward over array of thresholds starting from
4087 * current_threshold and check if a threshold is crossed.
4088 * If none of thresholds below usage is crossed, we read
4089 * only one element of the array here.
4091 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4092 eventfd_signal(t->entries[i].eventfd, 1);
4094 /* i = current_threshold + 1 */
4098 * Iterate forward over array of thresholds starting from
4099 * current_threshold+1 and check if a threshold is crossed.
4100 * If none of thresholds above usage is crossed, we read
4101 * only one element of the array here.
4103 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4104 eventfd_signal(t->entries[i].eventfd, 1);
4106 /* Update current_threshold */
4107 t->current_threshold = i - 1;
4112 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4115 __mem_cgroup_threshold(memcg, false);
4116 if (do_memsw_account())
4117 __mem_cgroup_threshold(memcg, true);
4119 memcg = parent_mem_cgroup(memcg);
4123 static int compare_thresholds(const void *a, const void *b)
4125 const struct mem_cgroup_threshold *_a = a;
4126 const struct mem_cgroup_threshold *_b = b;
4128 if (_a->threshold > _b->threshold)
4131 if (_a->threshold < _b->threshold)
4137 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
4139 struct mem_cgroup_eventfd_list *ev;
4141 spin_lock(&memcg_oom_lock);
4143 list_for_each_entry(ev, &memcg->oom_notify, list)
4144 eventfd_signal(ev->eventfd, 1);
4146 spin_unlock(&memcg_oom_lock);
4150 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
4152 struct mem_cgroup *iter;
4154 for_each_mem_cgroup_tree(iter, memcg)
4155 mem_cgroup_oom_notify_cb(iter);
4158 static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4159 struct eventfd_ctx *eventfd, const char *args, enum res_type type)
4161 struct mem_cgroup_thresholds *thresholds;
4162 struct mem_cgroup_threshold_ary *new;
4163 unsigned long threshold;
4164 unsigned long usage;
4167 ret = page_counter_memparse(args, "-1", &threshold);
4171 mutex_lock(&memcg->thresholds_lock);
4174 thresholds = &memcg->thresholds;
4175 usage = mem_cgroup_usage(memcg, false);
4176 } else if (type == _MEMSWAP) {
4177 thresholds = &memcg->memsw_thresholds;
4178 usage = mem_cgroup_usage(memcg, true);
4182 /* Check if a threshold crossed before adding a new one */
4183 if (thresholds->primary)
4184 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4186 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4188 /* Allocate memory for new array of thresholds */
4189 new = kmalloc(struct_size(new, entries, size), GFP_KERNEL);
4196 /* Copy thresholds (if any) to new array */
4197 if (thresholds->primary)
4198 memcpy(new->entries, thresholds->primary->entries,
4199 flex_array_size(new, entries, size - 1));
4201 /* Add new threshold */
4202 new->entries[size - 1].eventfd = eventfd;
4203 new->entries[size - 1].threshold = threshold;
4205 /* Sort thresholds. Registering of new threshold isn't time-critical */
4206 sort(new->entries, size, sizeof(*new->entries),
4207 compare_thresholds, NULL);
4209 /* Find current threshold */
4210 new->current_threshold = -1;
4211 for (i = 0; i < size; i++) {
4212 if (new->entries[i].threshold <= usage) {
4214 * new->current_threshold will not be used until
4215 * rcu_assign_pointer(), so it's safe to increment
4218 ++new->current_threshold;
4223 /* Free old spare buffer and save old primary buffer as spare */
4224 kfree(thresholds->spare);
4225 thresholds->spare = thresholds->primary;
4227 rcu_assign_pointer(thresholds->primary, new);
4229 /* To be sure that nobody uses thresholds */
4233 mutex_unlock(&memcg->thresholds_lock);
4238 static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4239 struct eventfd_ctx *eventfd, const char *args)
4241 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
4244 static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
4245 struct eventfd_ctx *eventfd, const char *args)
4247 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
4250 static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4251 struct eventfd_ctx *eventfd, enum res_type type)
4253 struct mem_cgroup_thresholds *thresholds;
4254 struct mem_cgroup_threshold_ary *new;
4255 unsigned long usage;
4256 int i, j, size, entries;
4258 mutex_lock(&memcg->thresholds_lock);
4261 thresholds = &memcg->thresholds;
4262 usage = mem_cgroup_usage(memcg, false);
4263 } else if (type == _MEMSWAP) {
4264 thresholds = &memcg->memsw_thresholds;
4265 usage = mem_cgroup_usage(memcg, true);
4269 if (!thresholds->primary)
4272 /* Check if a threshold crossed before removing */
4273 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4275 /* Calculate new number of threshold */
4277 for (i = 0; i < thresholds->primary->size; i++) {
4278 if (thresholds->primary->entries[i].eventfd != eventfd)
4284 new = thresholds->spare;
4286 /* If no items related to eventfd have been cleared, nothing to do */
4290 /* Set thresholds array to NULL if we don't have thresholds */
4299 /* Copy thresholds and find current threshold */
4300 new->current_threshold = -1;
4301 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4302 if (thresholds->primary->entries[i].eventfd == eventfd)
4305 new->entries[j] = thresholds->primary->entries[i];
4306 if (new->entries[j].threshold <= usage) {
4308 * new->current_threshold will not be used
4309 * until rcu_assign_pointer(), so it's safe to increment
4312 ++new->current_threshold;
4318 /* Swap primary and spare array */
4319 thresholds->spare = thresholds->primary;
4321 rcu_assign_pointer(thresholds->primary, new);
4323 /* To be sure that nobody uses thresholds */
4326 /* If all events are unregistered, free the spare array */
4328 kfree(thresholds->spare);
4329 thresholds->spare = NULL;
4332 mutex_unlock(&memcg->thresholds_lock);
4335 static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4336 struct eventfd_ctx *eventfd)
4338 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
4341 static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4342 struct eventfd_ctx *eventfd)
4344 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
4347 static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
4348 struct eventfd_ctx *eventfd, const char *args)
4350 struct mem_cgroup_eventfd_list *event;
4352 event = kmalloc(sizeof(*event), GFP_KERNEL);
4356 spin_lock(&memcg_oom_lock);
4358 event->eventfd = eventfd;
4359 list_add(&event->list, &memcg->oom_notify);
4361 /* already in OOM ? */
4362 if (memcg->under_oom)
4363 eventfd_signal(eventfd, 1);
4364 spin_unlock(&memcg_oom_lock);
4369 static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
4370 struct eventfd_ctx *eventfd)
4372 struct mem_cgroup_eventfd_list *ev, *tmp;
4374 spin_lock(&memcg_oom_lock);
4376 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
4377 if (ev->eventfd == eventfd) {
4378 list_del(&ev->list);
4383 spin_unlock(&memcg_oom_lock);
4386 static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
4388 struct mem_cgroup *memcg = mem_cgroup_from_seq(sf);
4390 seq_printf(sf, "oom_kill_disable %d\n", memcg->oom_kill_disable);
4391 seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
4392 seq_printf(sf, "oom_kill %lu\n",
4393 atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
4397 static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
4398 struct cftype *cft, u64 val)
4400 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4402 /* cannot set to root cgroup and only 0 and 1 are allowed */
4403 if (mem_cgroup_is_root(memcg) || !((val == 0) || (val == 1)))
4406 memcg->oom_kill_disable = val;
4408 memcg_oom_recover(memcg);
4413 #ifdef CONFIG_CGROUP_WRITEBACK
4415 #include <trace/events/writeback.h>
4417 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4419 return wb_domain_init(&memcg->cgwb_domain, gfp);
4422 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4424 wb_domain_exit(&memcg->cgwb_domain);
4427 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4429 wb_domain_size_changed(&memcg->cgwb_domain);
4432 struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
4434 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4436 if (!memcg->css.parent)
4439 return &memcg->cgwb_domain;
4443 * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
4444 * @wb: bdi_writeback in question
4445 * @pfilepages: out parameter for number of file pages
4446 * @pheadroom: out parameter for number of allocatable pages according to memcg
4447 * @pdirty: out parameter for number of dirty pages
4448 * @pwriteback: out parameter for number of pages under writeback
4450 * Determine the numbers of file, headroom, dirty, and writeback pages in
4451 * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom
4452 * is a bit more involved.
4454 * A memcg's headroom is "min(max, high) - used". In the hierarchy, the
4455 * headroom is calculated as the lowest headroom of itself and the
4456 * ancestors. Note that this doesn't consider the actual amount of
4457 * available memory in the system. The caller should further cap
4458 * *@pheadroom accordingly.
4460 void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
4461 unsigned long *pheadroom, unsigned long *pdirty,
4462 unsigned long *pwriteback)
4464 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4465 struct mem_cgroup *parent;
4467 cgroup_rstat_flush_irqsafe(memcg->css.cgroup);
4469 *pdirty = memcg_page_state(memcg, NR_FILE_DIRTY);
4470 *pwriteback = memcg_page_state(memcg, NR_WRITEBACK);
4471 *pfilepages = memcg_page_state(memcg, NR_INACTIVE_FILE) +
4472 memcg_page_state(memcg, NR_ACTIVE_FILE);
4474 *pheadroom = PAGE_COUNTER_MAX;
4475 while ((parent = parent_mem_cgroup(memcg))) {
4476 unsigned long ceiling = min(READ_ONCE(memcg->memory.max),
4477 READ_ONCE(memcg->memory.high));
4478 unsigned long used = page_counter_read(&memcg->memory);
4480 *pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
4486 * Foreign dirty flushing
4488 * There's an inherent mismatch between memcg and writeback. The former
4489 * tracks ownership per-page while the latter per-inode. This was a
4490 * deliberate design decision because honoring per-page ownership in the
4491 * writeback path is complicated, may lead to higher CPU and IO overheads
4492 * and deemed unnecessary given that write-sharing an inode across
4493 * different cgroups isn't a common use-case.
4495 * Combined with inode majority-writer ownership switching, this works well
4496 * enough in most cases but there are some pathological cases. For
4497 * example, let's say there are two cgroups A and B which keep writing to
4498 * different but confined parts of the same inode. B owns the inode and
4499 * A's memory is limited far below B's. A's dirty ratio can rise enough to
4500 * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
4501 * triggering background writeback. A will be slowed down without a way to
4502 * make writeback of the dirty pages happen.
4504 * Conditions like the above can lead to a cgroup getting repeatedly and
4505 * severely throttled after making some progress after each
4506 * dirty_expire_interval while the underlying IO device is almost
4509 * Solving this problem completely requires matching the ownership tracking
4510 * granularities between memcg and writeback in either direction. However,
4511 * the more egregious behaviors can be avoided by simply remembering the
4512 * most recent foreign dirtying events and initiating remote flushes on
4513 * them when local writeback isn't enough to keep the memory clean enough.
4515 * The following two functions implement such mechanism. When a foreign
4516 * page - a page whose memcg and writeback ownerships don't match - is
4517 * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
4518 * bdi_writeback on the page owning memcg. When balance_dirty_pages()
4519 * decides that the memcg needs to sleep due to high dirty ratio, it calls
4520 * mem_cgroup_flush_foreign() which queues writeback on the recorded
4521 * foreign bdi_writebacks which haven't expired. Both the numbers of
4522 * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
4523 * limited to MEMCG_CGWB_FRN_CNT.
4525 * The mechanism only remembers IDs and doesn't hold any object references.
4526 * As being wrong occasionally doesn't matter, updates and accesses to the
4527 * records are lockless and racy.
4529 void mem_cgroup_track_foreign_dirty_slowpath(struct page *page,
4530 struct bdi_writeback *wb)
4532 struct mem_cgroup *memcg = page_memcg(page);
4533 struct memcg_cgwb_frn *frn;
4534 u64 now = get_jiffies_64();
4535 u64 oldest_at = now;
4539 trace_track_foreign_dirty(page, wb);
4542 * Pick the slot to use. If there is already a slot for @wb, keep
4543 * using it. If not replace the oldest one which isn't being
4546 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4547 frn = &memcg->cgwb_frn[i];
4548 if (frn->bdi_id == wb->bdi->id &&
4549 frn->memcg_id == wb->memcg_css->id)
4551 if (time_before64(frn->at, oldest_at) &&
4552 atomic_read(&frn->done.cnt) == 1) {
4554 oldest_at = frn->at;
4558 if (i < MEMCG_CGWB_FRN_CNT) {
4560 * Re-using an existing one. Update timestamp lazily to
4561 * avoid making the cacheline hot. We want them to be
4562 * reasonably up-to-date and significantly shorter than
4563 * dirty_expire_interval as that's what expires the record.
4564 * Use the shorter of 1s and dirty_expire_interval / 8.
4566 unsigned long update_intv =
4567 min_t(unsigned long, HZ,
4568 msecs_to_jiffies(dirty_expire_interval * 10) / 8);
4570 if (time_before64(frn->at, now - update_intv))
4572 } else if (oldest >= 0) {
4573 /* replace the oldest free one */
4574 frn = &memcg->cgwb_frn[oldest];
4575 frn->bdi_id = wb->bdi->id;
4576 frn->memcg_id = wb->memcg_css->id;
4581 /* issue foreign writeback flushes for recorded foreign dirtying events */
4582 void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
4584 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4585 unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
4586 u64 now = jiffies_64;
4589 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4590 struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
4593 * If the record is older than dirty_expire_interval,
4594 * writeback on it has already started. No need to kick it
4595 * off again. Also, don't start a new one if there's
4596 * already one in flight.
4598 if (time_after64(frn->at, now - intv) &&
4599 atomic_read(&frn->done.cnt) == 1) {
4601 trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
4602 cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id,
4603 WB_REASON_FOREIGN_FLUSH,
4609 #else /* CONFIG_CGROUP_WRITEBACK */
4611 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4616 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4620 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4624 #endif /* CONFIG_CGROUP_WRITEBACK */
4627 * DO NOT USE IN NEW FILES.
4629 * "cgroup.event_control" implementation.
4631 * This is way over-engineered. It tries to support fully configurable
4632 * events for each user. Such level of flexibility is completely
4633 * unnecessary especially in the light of the planned unified hierarchy.
4635 * Please deprecate this and replace with something simpler if at all
4640 * Unregister event and free resources.
4642 * Gets called from workqueue.
4644 static void memcg_event_remove(struct work_struct *work)
4646 struct mem_cgroup_event *event =
4647 container_of(work, struct mem_cgroup_event, remove);
4648 struct mem_cgroup *memcg = event->memcg;
4650 remove_wait_queue(event->wqh, &event->wait);
4652 event->unregister_event(memcg, event->eventfd);
4654 /* Notify userspace the event is going away. */
4655 eventfd_signal(event->eventfd, 1);
4657 eventfd_ctx_put(event->eventfd);
4659 css_put(&memcg->css);
4663 * Gets called on EPOLLHUP on eventfd when user closes it.
4665 * Called with wqh->lock held and interrupts disabled.
4667 static int memcg_event_wake(wait_queue_entry_t *wait, unsigned mode,
4668 int sync, void *key)
4670 struct mem_cgroup_event *event =
4671 container_of(wait, struct mem_cgroup_event, wait);
4672 struct mem_cgroup *memcg = event->memcg;
4673 __poll_t flags = key_to_poll(key);
4675 if (flags & EPOLLHUP) {
4677 * If the event has been detached at cgroup removal, we
4678 * can simply return knowing the other side will cleanup
4681 * We can't race against event freeing since the other
4682 * side will require wqh->lock via remove_wait_queue(),
4685 spin_lock(&memcg->event_list_lock);
4686 if (!list_empty(&event->list)) {
4687 list_del_init(&event->list);
4689 * We are in atomic context, but cgroup_event_remove()
4690 * may sleep, so we have to call it in workqueue.
4692 schedule_work(&event->remove);
4694 spin_unlock(&memcg->event_list_lock);
4700 static void memcg_event_ptable_queue_proc(struct file *file,
4701 wait_queue_head_t *wqh, poll_table *pt)
4703 struct mem_cgroup_event *event =
4704 container_of(pt, struct mem_cgroup_event, pt);
4707 add_wait_queue(wqh, &event->wait);
4711 * DO NOT USE IN NEW FILES.
4713 * Parse input and register new cgroup event handler.
4715 * Input must be in format '<event_fd> <control_fd> <args>'.
4716 * Interpretation of args is defined by control file implementation.
4718 static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
4719 char *buf, size_t nbytes, loff_t off)
4721 struct cgroup_subsys_state *css = of_css(of);
4722 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4723 struct mem_cgroup_event *event;
4724 struct cgroup_subsys_state *cfile_css;
4725 unsigned int efd, cfd;
4732 buf = strstrip(buf);
4734 efd = simple_strtoul(buf, &endp, 10);
4739 cfd = simple_strtoul(buf, &endp, 10);
4740 if ((*endp != ' ') && (*endp != '\0'))
4744 event = kzalloc(sizeof(*event), GFP_KERNEL);
4748 event->memcg = memcg;
4749 INIT_LIST_HEAD(&event->list);
4750 init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
4751 init_waitqueue_func_entry(&event->wait, memcg_event_wake);
4752 INIT_WORK(&event->remove, memcg_event_remove);
4760 event->eventfd = eventfd_ctx_fileget(efile.file);
4761 if (IS_ERR(event->eventfd)) {
4762 ret = PTR_ERR(event->eventfd);
4769 goto out_put_eventfd;
4772 /* the process need read permission on control file */
4773 /* AV: shouldn't we check that it's been opened for read instead? */
4774 ret = file_permission(cfile.file, MAY_READ);
4779 * Determine the event callbacks and set them in @event. This used
4780 * to be done via struct cftype but cgroup core no longer knows
4781 * about these events. The following is crude but the whole thing
4782 * is for compatibility anyway.
4784 * DO NOT ADD NEW FILES.
4786 name = cfile.file->f_path.dentry->d_name.name;
4788 if (!strcmp(name, "memory.usage_in_bytes")) {
4789 event->register_event = mem_cgroup_usage_register_event;
4790 event->unregister_event = mem_cgroup_usage_unregister_event;
4791 } else if (!strcmp(name, "memory.oom_control")) {
4792 event->register_event = mem_cgroup_oom_register_event;
4793 event->unregister_event = mem_cgroup_oom_unregister_event;
4794 } else if (!strcmp(name, "memory.pressure_level")) {
4795 event->register_event = vmpressure_register_event;
4796 event->unregister_event = vmpressure_unregister_event;
4797 } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
4798 event->register_event = memsw_cgroup_usage_register_event;
4799 event->unregister_event = memsw_cgroup_usage_unregister_event;
4806 * Verify @cfile should belong to @css. Also, remaining events are
4807 * automatically removed on cgroup destruction but the removal is
4808 * asynchronous, so take an extra ref on @css.
4810 cfile_css = css_tryget_online_from_dir(cfile.file->f_path.dentry->d_parent,
4811 &memory_cgrp_subsys);
4813 if (IS_ERR(cfile_css))
4815 if (cfile_css != css) {
4820 ret = event->register_event(memcg, event->eventfd, buf);
4824 vfs_poll(efile.file, &event->pt);
4826 spin_lock_irq(&memcg->event_list_lock);
4827 list_add(&event->list, &memcg->event_list);
4828 spin_unlock_irq(&memcg->event_list_lock);
4840 eventfd_ctx_put(event->eventfd);
4849 static struct cftype mem_cgroup_legacy_files[] = {
4851 .name = "usage_in_bytes",
4852 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
4853 .read_u64 = mem_cgroup_read_u64,
4856 .name = "max_usage_in_bytes",
4857 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
4858 .write = mem_cgroup_reset,
4859 .read_u64 = mem_cgroup_read_u64,
4862 .name = "limit_in_bytes",
4863 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
4864 .write = mem_cgroup_write,
4865 .read_u64 = mem_cgroup_read_u64,
4868 .name = "soft_limit_in_bytes",
4869 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
4870 .write = mem_cgroup_write,
4871 .read_u64 = mem_cgroup_read_u64,
4875 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
4876 .write = mem_cgroup_reset,
4877 .read_u64 = mem_cgroup_read_u64,
4881 .seq_show = memcg_stat_show,
4884 .name = "force_empty",
4885 .write = mem_cgroup_force_empty_write,
4888 .name = "use_hierarchy",
4889 .write_u64 = mem_cgroup_hierarchy_write,
4890 .read_u64 = mem_cgroup_hierarchy_read,
4893 .name = "cgroup.event_control", /* XXX: for compat */
4894 .write = memcg_write_event_control,
4895 .flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE,
4898 .name = "swappiness",
4899 .read_u64 = mem_cgroup_swappiness_read,
4900 .write_u64 = mem_cgroup_swappiness_write,
4903 .name = "move_charge_at_immigrate",
4904 .read_u64 = mem_cgroup_move_charge_read,
4905 .write_u64 = mem_cgroup_move_charge_write,
4908 .name = "oom_control",
4909 .seq_show = mem_cgroup_oom_control_read,
4910 .write_u64 = mem_cgroup_oom_control_write,
4911 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
4914 .name = "pressure_level",
4918 .name = "numa_stat",
4919 .seq_show = memcg_numa_stat_show,
4923 .name = "kmem.limit_in_bytes",
4924 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
4925 .write = mem_cgroup_write,
4926 .read_u64 = mem_cgroup_read_u64,
4929 .name = "kmem.usage_in_bytes",
4930 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
4931 .read_u64 = mem_cgroup_read_u64,
4934 .name = "kmem.failcnt",
4935 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
4936 .write = mem_cgroup_reset,
4937 .read_u64 = mem_cgroup_read_u64,
4940 .name = "kmem.max_usage_in_bytes",
4941 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
4942 .write = mem_cgroup_reset,
4943 .read_u64 = mem_cgroup_read_u64,
4945 #if defined(CONFIG_MEMCG_KMEM) && \
4946 (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG))
4948 .name = "kmem.slabinfo",
4949 .seq_show = memcg_slab_show,
4953 .name = "kmem.tcp.limit_in_bytes",
4954 .private = MEMFILE_PRIVATE(_TCP, RES_LIMIT),
4955 .write = mem_cgroup_write,
4956 .read_u64 = mem_cgroup_read_u64,
4959 .name = "kmem.tcp.usage_in_bytes",
4960 .private = MEMFILE_PRIVATE(_TCP, RES_USAGE),
4961 .read_u64 = mem_cgroup_read_u64,
4964 .name = "kmem.tcp.failcnt",
4965 .private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT),
4966 .write = mem_cgroup_reset,
4967 .read_u64 = mem_cgroup_read_u64,
4970 .name = "kmem.tcp.max_usage_in_bytes",
4971 .private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE),
4972 .write = mem_cgroup_reset,
4973 .read_u64 = mem_cgroup_read_u64,
4975 { }, /* terminate */
4979 * Private memory cgroup IDR
4981 * Swap-out records and page cache shadow entries need to store memcg
4982 * references in constrained space, so we maintain an ID space that is
4983 * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
4984 * memory-controlled cgroups to 64k.
4986 * However, there usually are many references to the offline CSS after
4987 * the cgroup has been destroyed, such as page cache or reclaimable
4988 * slab objects, that don't need to hang on to the ID. We want to keep
4989 * those dead CSS from occupying IDs, or we might quickly exhaust the
4990 * relatively small ID space and prevent the creation of new cgroups
4991 * even when there are much fewer than 64k cgroups - possibly none.
4993 * Maintain a private 16-bit ID space for memcg, and allow the ID to
4994 * be freed and recycled when it's no longer needed, which is usually
4995 * when the CSS is offlined.
4997 * The only exception to that are records of swapped out tmpfs/shmem
4998 * pages that need to be attributed to live ancestors on swapin. But
4999 * those references are manageable from userspace.
5002 static DEFINE_IDR(mem_cgroup_idr);
5004 static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
5006 if (memcg->id.id > 0) {
5007 idr_remove(&mem_cgroup_idr, memcg->id.id);
5012 static void __maybe_unused mem_cgroup_id_get_many(struct mem_cgroup *memcg,
5015 refcount_add(n, &memcg->id.ref);
5018 static void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
5020 if (refcount_sub_and_test(n, &memcg->id.ref)) {
5021 mem_cgroup_id_remove(memcg);
5023 /* Memcg ID pins CSS */
5024 css_put(&memcg->css);
5028 static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
5030 mem_cgroup_id_put_many(memcg, 1);
5034 * mem_cgroup_from_id - look up a memcg from a memcg id
5035 * @id: the memcg id to look up
5037 * Caller must hold rcu_read_lock().
5039 struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
5041 WARN_ON_ONCE(!rcu_read_lock_held());
5042 return idr_find(&mem_cgroup_idr, id);
5045 static int alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5047 struct mem_cgroup_per_node *pn;
5050 * This routine is called against possible nodes.
5051 * But it's BUG to call kmalloc() against offline node.
5053 * TODO: this routine can waste much memory for nodes which will
5054 * never be onlined. It's better to use memory hotplug callback
5057 if (!node_state(node, N_NORMAL_MEMORY))
5059 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
5063 pn->lruvec_stats_percpu = alloc_percpu_gfp(struct lruvec_stats_percpu,
5064 GFP_KERNEL_ACCOUNT);
5065 if (!pn->lruvec_stats_percpu) {
5070 lruvec_init(&pn->lruvec);
5071 pn->usage_in_excess = 0;
5072 pn->on_tree = false;
5075 memcg->nodeinfo[node] = pn;
5079 static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5081 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
5086 free_percpu(pn->lruvec_stats_percpu);
5090 static void __mem_cgroup_free(struct mem_cgroup *memcg)
5095 free_mem_cgroup_per_node_info(memcg, node);
5096 free_percpu(memcg->vmstats_percpu);
5100 static void mem_cgroup_free(struct mem_cgroup *memcg)
5102 memcg_wb_domain_exit(memcg);
5103 __mem_cgroup_free(memcg);
5106 static struct mem_cgroup *mem_cgroup_alloc(void)
5108 struct mem_cgroup *memcg;
5111 int __maybe_unused i;
5112 long error = -ENOMEM;
5114 size = sizeof(struct mem_cgroup);
5115 size += nr_node_ids * sizeof(struct mem_cgroup_per_node *);
5117 memcg = kzalloc(size, GFP_KERNEL);
5119 return ERR_PTR(error);
5121 memcg->id.id = idr_alloc(&mem_cgroup_idr, NULL,
5122 1, MEM_CGROUP_ID_MAX,
5124 if (memcg->id.id < 0) {
5125 error = memcg->id.id;
5129 memcg->vmstats_percpu = alloc_percpu_gfp(struct memcg_vmstats_percpu,
5130 GFP_KERNEL_ACCOUNT);
5131 if (!memcg->vmstats_percpu)
5135 if (alloc_mem_cgroup_per_node_info(memcg, node))
5138 if (memcg_wb_domain_init(memcg, GFP_KERNEL))
5141 INIT_WORK(&memcg->high_work, high_work_func);
5142 INIT_LIST_HEAD(&memcg->oom_notify);
5143 mutex_init(&memcg->thresholds_lock);
5144 spin_lock_init(&memcg->move_lock);
5145 vmpressure_init(&memcg->vmpressure);
5146 INIT_LIST_HEAD(&memcg->event_list);
5147 spin_lock_init(&memcg->event_list_lock);
5148 memcg->socket_pressure = jiffies;
5149 #ifdef CONFIG_MEMCG_KMEM
5150 memcg->kmemcg_id = -1;
5151 INIT_LIST_HEAD(&memcg->objcg_list);
5153 #ifdef CONFIG_CGROUP_WRITEBACK
5154 INIT_LIST_HEAD(&memcg->cgwb_list);
5155 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5156 memcg->cgwb_frn[i].done =
5157 __WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
5159 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5160 spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
5161 INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
5162 memcg->deferred_split_queue.split_queue_len = 0;
5164 idr_replace(&mem_cgroup_idr, memcg, memcg->id.id);
5167 mem_cgroup_id_remove(memcg);
5168 __mem_cgroup_free(memcg);
5169 return ERR_PTR(error);
5172 static struct cgroup_subsys_state * __ref
5173 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
5175 struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
5176 struct mem_cgroup *memcg, *old_memcg;
5177 long error = -ENOMEM;
5179 old_memcg = set_active_memcg(parent);
5180 memcg = mem_cgroup_alloc();
5181 set_active_memcg(old_memcg);
5183 return ERR_CAST(memcg);
5185 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5186 memcg->soft_limit = PAGE_COUNTER_MAX;
5187 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5189 memcg->swappiness = mem_cgroup_swappiness(parent);
5190 memcg->oom_kill_disable = parent->oom_kill_disable;
5192 page_counter_init(&memcg->memory, &parent->memory);
5193 page_counter_init(&memcg->swap, &parent->swap);
5194 page_counter_init(&memcg->kmem, &parent->kmem);
5195 page_counter_init(&memcg->tcpmem, &parent->tcpmem);
5197 page_counter_init(&memcg->memory, NULL);
5198 page_counter_init(&memcg->swap, NULL);
5199 page_counter_init(&memcg->kmem, NULL);
5200 page_counter_init(&memcg->tcpmem, NULL);
5202 root_mem_cgroup = memcg;
5206 /* The following stuff does not apply to the root */
5207 error = memcg_online_kmem(memcg);
5211 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5212 static_branch_inc(&memcg_sockets_enabled_key);
5216 mem_cgroup_id_remove(memcg);
5217 mem_cgroup_free(memcg);
5218 return ERR_PTR(error);
5221 static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
5223 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5226 * A memcg must be visible for expand_shrinker_info()
5227 * by the time the maps are allocated. So, we allocate maps
5228 * here, when for_each_mem_cgroup() can't skip it.
5230 if (alloc_shrinker_info(memcg)) {
5231 mem_cgroup_id_remove(memcg);
5235 /* Online state pins memcg ID, memcg ID pins CSS */
5236 refcount_set(&memcg->id.ref, 1);
5239 if (unlikely(mem_cgroup_is_root(memcg)))
5240 queue_delayed_work(system_unbound_wq, &stats_flush_dwork,
5245 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
5247 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5248 struct mem_cgroup_event *event, *tmp;
5251 * Unregister events and notify userspace.
5252 * Notify userspace about cgroup removing only after rmdir of cgroup
5253 * directory to avoid race between userspace and kernelspace.
5255 spin_lock_irq(&memcg->event_list_lock);
5256 list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
5257 list_del_init(&event->list);
5258 schedule_work(&event->remove);
5260 spin_unlock_irq(&memcg->event_list_lock);
5262 page_counter_set_min(&memcg->memory, 0);
5263 page_counter_set_low(&memcg->memory, 0);
5265 memcg_offline_kmem(memcg);
5266 reparent_shrinker_deferred(memcg);
5267 wb_memcg_offline(memcg);
5269 drain_all_stock(memcg);
5271 mem_cgroup_id_put(memcg);
5274 static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
5276 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5278 invalidate_reclaim_iterators(memcg);
5281 static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
5283 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5284 int __maybe_unused i;
5286 #ifdef CONFIG_CGROUP_WRITEBACK
5287 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5288 wb_wait_for_completion(&memcg->cgwb_frn[i].done);
5290 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5291 static_branch_dec(&memcg_sockets_enabled_key);
5293 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg->tcpmem_active)
5294 static_branch_dec(&memcg_sockets_enabled_key);
5296 vmpressure_cleanup(&memcg->vmpressure);
5297 cancel_work_sync(&memcg->high_work);
5298 mem_cgroup_remove_from_trees(memcg);
5299 free_shrinker_info(memcg);
5300 memcg_free_kmem(memcg);
5301 mem_cgroup_free(memcg);
5305 * mem_cgroup_css_reset - reset the states of a mem_cgroup
5306 * @css: the target css
5308 * Reset the states of the mem_cgroup associated with @css. This is
5309 * invoked when the userland requests disabling on the default hierarchy
5310 * but the memcg is pinned through dependency. The memcg should stop
5311 * applying policies and should revert to the vanilla state as it may be
5312 * made visible again.
5314 * The current implementation only resets the essential configurations.
5315 * This needs to be expanded to cover all the visible parts.
5317 static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
5319 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5321 page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
5322 page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
5323 page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
5324 page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
5325 page_counter_set_min(&memcg->memory, 0);
5326 page_counter_set_low(&memcg->memory, 0);
5327 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5328 memcg->soft_limit = PAGE_COUNTER_MAX;
5329 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5330 memcg_wb_domain_size_changed(memcg);
5333 void mem_cgroup_flush_stats(void)
5335 if (!spin_trylock(&stats_flush_lock))
5338 cgroup_rstat_flush_irqsafe(root_mem_cgroup->css.cgroup);
5339 spin_unlock(&stats_flush_lock);
5342 static void flush_memcg_stats_dwork(struct work_struct *w)
5344 mem_cgroup_flush_stats();
5345 queue_delayed_work(system_unbound_wq, &stats_flush_dwork, 2UL*HZ);
5348 static void mem_cgroup_css_rstat_flush(struct cgroup_subsys_state *css, int cpu)
5350 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5351 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
5352 struct memcg_vmstats_percpu *statc;
5356 statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
5358 for (i = 0; i < MEMCG_NR_STAT; i++) {
5360 * Collect the aggregated propagation counts of groups
5361 * below us. We're in a per-cpu loop here and this is
5362 * a global counter, so the first cycle will get them.
5364 delta = memcg->vmstats.state_pending[i];
5366 memcg->vmstats.state_pending[i] = 0;
5368 /* Add CPU changes on this level since the last flush */
5369 v = READ_ONCE(statc->state[i]);
5370 if (v != statc->state_prev[i]) {
5371 delta += v - statc->state_prev[i];
5372 statc->state_prev[i] = v;
5378 /* Aggregate counts on this level and propagate upwards */
5379 memcg->vmstats.state[i] += delta;
5381 parent->vmstats.state_pending[i] += delta;
5384 for (i = 0; i < NR_VM_EVENT_ITEMS; i++) {
5385 delta = memcg->vmstats.events_pending[i];
5387 memcg->vmstats.events_pending[i] = 0;
5389 v = READ_ONCE(statc->events[i]);
5390 if (v != statc->events_prev[i]) {
5391 delta += v - statc->events_prev[i];
5392 statc->events_prev[i] = v;
5398 memcg->vmstats.events[i] += delta;
5400 parent->vmstats.events_pending[i] += delta;
5403 for_each_node_state(nid, N_MEMORY) {
5404 struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
5405 struct mem_cgroup_per_node *ppn = NULL;
5406 struct lruvec_stats_percpu *lstatc;
5409 ppn = parent->nodeinfo[nid];
5411 lstatc = per_cpu_ptr(pn->lruvec_stats_percpu, cpu);
5413 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++) {
5414 delta = pn->lruvec_stats.state_pending[i];
5416 pn->lruvec_stats.state_pending[i] = 0;
5418 v = READ_ONCE(lstatc->state[i]);
5419 if (v != lstatc->state_prev[i]) {
5420 delta += v - lstatc->state_prev[i];
5421 lstatc->state_prev[i] = v;
5427 pn->lruvec_stats.state[i] += delta;
5429 ppn->lruvec_stats.state_pending[i] += delta;
5435 /* Handlers for move charge at task migration. */
5436 static int mem_cgroup_do_precharge(unsigned long count)
5440 /* Try a single bulk charge without reclaim first, kswapd may wake */
5441 ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count);
5443 mc.precharge += count;
5447 /* Try charges one by one with reclaim, but do not retry */
5449 ret = try_charge(mc.to, GFP_KERNEL | __GFP_NORETRY, 1);
5463 enum mc_target_type {
5470 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5471 unsigned long addr, pte_t ptent)
5473 struct page *page = vm_normal_page(vma, addr, ptent);
5475 if (!page || !page_mapped(page))
5477 if (PageAnon(page)) {
5478 if (!(mc.flags & MOVE_ANON))
5481 if (!(mc.flags & MOVE_FILE))
5484 if (!get_page_unless_zero(page))
5490 #if defined(CONFIG_SWAP) || defined(CONFIG_DEVICE_PRIVATE)
5491 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5492 pte_t ptent, swp_entry_t *entry)
5494 struct page *page = NULL;
5495 swp_entry_t ent = pte_to_swp_entry(ptent);
5497 if (!(mc.flags & MOVE_ANON))
5501 * Handle MEMORY_DEVICE_PRIVATE which are ZONE_DEVICE page belonging to
5502 * a device and because they are not accessible by CPU they are store
5503 * as special swap entry in the CPU page table.
5505 if (is_device_private_entry(ent)) {
5506 page = pfn_swap_entry_to_page(ent);
5508 * MEMORY_DEVICE_PRIVATE means ZONE_DEVICE page and which have
5509 * a refcount of 1 when free (unlike normal page)
5511 if (!page_ref_add_unless(page, 1, 1))
5516 if (non_swap_entry(ent))
5520 * Because lookup_swap_cache() updates some statistics counter,
5521 * we call find_get_page() with swapper_space directly.
5523 page = find_get_page(swap_address_space(ent), swp_offset(ent));
5524 entry->val = ent.val;
5529 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5530 pte_t ptent, swp_entry_t *entry)
5536 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5537 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5539 if (!vma->vm_file) /* anonymous vma */
5541 if (!(mc.flags & MOVE_FILE))
5544 /* page is moved even if it's not RSS of this task(page-faulted). */
5545 /* shmem/tmpfs may report page out on swap: account for that too. */
5546 return find_get_incore_page(vma->vm_file->f_mapping,
5547 linear_page_index(vma, addr));
5551 * mem_cgroup_move_account - move account of the page
5553 * @compound: charge the page as compound or small page
5554 * @from: mem_cgroup which the page is moved from.
5555 * @to: mem_cgroup which the page is moved to. @from != @to.
5557 * The caller must make sure the page is not on LRU (isolate_page() is useful.)
5559 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
5562 static int mem_cgroup_move_account(struct page *page,
5564 struct mem_cgroup *from,
5565 struct mem_cgroup *to)
5567 struct lruvec *from_vec, *to_vec;
5568 struct pglist_data *pgdat;
5569 unsigned int nr_pages = compound ? thp_nr_pages(page) : 1;
5572 VM_BUG_ON(from == to);
5573 VM_BUG_ON_PAGE(PageLRU(page), page);
5574 VM_BUG_ON(compound && !PageTransHuge(page));
5577 * Prevent mem_cgroup_migrate() from looking at
5578 * page's memory cgroup of its source page while we change it.
5581 if (!trylock_page(page))
5585 if (page_memcg(page) != from)
5588 pgdat = page_pgdat(page);
5589 from_vec = mem_cgroup_lruvec(from, pgdat);
5590 to_vec = mem_cgroup_lruvec(to, pgdat);
5592 lock_page_memcg(page);
5594 if (PageAnon(page)) {
5595 if (page_mapped(page)) {
5596 __mod_lruvec_state(from_vec, NR_ANON_MAPPED, -nr_pages);
5597 __mod_lruvec_state(to_vec, NR_ANON_MAPPED, nr_pages);
5598 if (PageTransHuge(page)) {
5599 __mod_lruvec_state(from_vec, NR_ANON_THPS,
5601 __mod_lruvec_state(to_vec, NR_ANON_THPS,
5606 __mod_lruvec_state(from_vec, NR_FILE_PAGES, -nr_pages);
5607 __mod_lruvec_state(to_vec, NR_FILE_PAGES, nr_pages);
5609 if (PageSwapBacked(page)) {
5610 __mod_lruvec_state(from_vec, NR_SHMEM, -nr_pages);
5611 __mod_lruvec_state(to_vec, NR_SHMEM, nr_pages);
5614 if (page_mapped(page)) {
5615 __mod_lruvec_state(from_vec, NR_FILE_MAPPED, -nr_pages);
5616 __mod_lruvec_state(to_vec, NR_FILE_MAPPED, nr_pages);
5619 if (PageDirty(page)) {
5620 struct address_space *mapping = page_mapping(page);
5622 if (mapping_can_writeback(mapping)) {
5623 __mod_lruvec_state(from_vec, NR_FILE_DIRTY,
5625 __mod_lruvec_state(to_vec, NR_FILE_DIRTY,
5631 if (PageWriteback(page)) {
5632 __mod_lruvec_state(from_vec, NR_WRITEBACK, -nr_pages);
5633 __mod_lruvec_state(to_vec, NR_WRITEBACK, nr_pages);
5637 * All state has been migrated, let's switch to the new memcg.
5639 * It is safe to change page's memcg here because the page
5640 * is referenced, charged, isolated, and locked: we can't race
5641 * with (un)charging, migration, LRU putback, or anything else
5642 * that would rely on a stable page's memory cgroup.
5644 * Note that lock_page_memcg is a memcg lock, not a page lock,
5645 * to save space. As soon as we switch page's memory cgroup to a
5646 * new memcg that isn't locked, the above state can change
5647 * concurrently again. Make sure we're truly done with it.
5652 css_put(&from->css);
5654 page->memcg_data = (unsigned long)to;
5656 __unlock_page_memcg(from);
5660 local_irq_disable();
5661 mem_cgroup_charge_statistics(to, page, nr_pages);
5662 memcg_check_events(to, page);
5663 mem_cgroup_charge_statistics(from, page, -nr_pages);
5664 memcg_check_events(from, page);
5673 * get_mctgt_type - get target type of moving charge
5674 * @vma: the vma the pte to be checked belongs
5675 * @addr: the address corresponding to the pte to be checked
5676 * @ptent: the pte to be checked
5677 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5680 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5681 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5682 * move charge. if @target is not NULL, the page is stored in target->page
5683 * with extra refcnt got(Callers should handle it).
5684 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5685 * target for charge migration. if @target is not NULL, the entry is stored
5687 * 3(MC_TARGET_DEVICE): like MC_TARGET_PAGE but page is MEMORY_DEVICE_PRIVATE
5688 * (so ZONE_DEVICE page and thus not on the lru).
5689 * For now we such page is charge like a regular page would be as for all
5690 * intent and purposes it is just special memory taking the place of a
5693 * See Documentations/vm/hmm.txt and include/linux/hmm.h
5695 * Called with pte lock held.
5698 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
5699 unsigned long addr, pte_t ptent, union mc_target *target)
5701 struct page *page = NULL;
5702 enum mc_target_type ret = MC_TARGET_NONE;
5703 swp_entry_t ent = { .val = 0 };
5705 if (pte_present(ptent))
5706 page = mc_handle_present_pte(vma, addr, ptent);
5707 else if (is_swap_pte(ptent))
5708 page = mc_handle_swap_pte(vma, ptent, &ent);
5709 else if (pte_none(ptent))
5710 page = mc_handle_file_pte(vma, addr, ptent, &ent);
5712 if (!page && !ent.val)
5716 * Do only loose check w/o serialization.
5717 * mem_cgroup_move_account() checks the page is valid or
5718 * not under LRU exclusion.
5720 if (page_memcg(page) == mc.from) {
5721 ret = MC_TARGET_PAGE;
5722 if (is_device_private_page(page))
5723 ret = MC_TARGET_DEVICE;
5725 target->page = page;
5727 if (!ret || !target)
5731 * There is a swap entry and a page doesn't exist or isn't charged.
5732 * But we cannot move a tail-page in a THP.
5734 if (ent.val && !ret && (!page || !PageTransCompound(page)) &&
5735 mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
5736 ret = MC_TARGET_SWAP;
5743 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5745 * We don't consider PMD mapped swapping or file mapped pages because THP does
5746 * not support them for now.
5747 * Caller should make sure that pmd_trans_huge(pmd) is true.
5749 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5750 unsigned long addr, pmd_t pmd, union mc_target *target)
5752 struct page *page = NULL;
5753 enum mc_target_type ret = MC_TARGET_NONE;
5755 if (unlikely(is_swap_pmd(pmd))) {
5756 VM_BUG_ON(thp_migration_supported() &&
5757 !is_pmd_migration_entry(pmd));
5760 page = pmd_page(pmd);
5761 VM_BUG_ON_PAGE(!page || !PageHead(page), page);
5762 if (!(mc.flags & MOVE_ANON))
5764 if (page_memcg(page) == mc.from) {
5765 ret = MC_TARGET_PAGE;
5768 target->page = page;
5774 static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5775 unsigned long addr, pmd_t pmd, union mc_target *target)
5777 return MC_TARGET_NONE;
5781 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5782 unsigned long addr, unsigned long end,
5783 struct mm_walk *walk)
5785 struct vm_area_struct *vma = walk->vma;
5789 ptl = pmd_trans_huge_lock(pmd, vma);
5792 * Note their can not be MC_TARGET_DEVICE for now as we do not
5793 * support transparent huge page with MEMORY_DEVICE_PRIVATE but
5794 * this might change.
5796 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
5797 mc.precharge += HPAGE_PMD_NR;
5802 if (pmd_trans_unstable(pmd))
5804 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5805 for (; addr != end; pte++, addr += PAGE_SIZE)
5806 if (get_mctgt_type(vma, addr, *pte, NULL))
5807 mc.precharge++; /* increment precharge temporarily */
5808 pte_unmap_unlock(pte - 1, ptl);
5814 static const struct mm_walk_ops precharge_walk_ops = {
5815 .pmd_entry = mem_cgroup_count_precharge_pte_range,
5818 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5820 unsigned long precharge;
5823 walk_page_range(mm, 0, mm->highest_vm_end, &precharge_walk_ops, NULL);
5824 mmap_read_unlock(mm);
5826 precharge = mc.precharge;
5832 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5834 unsigned long precharge = mem_cgroup_count_precharge(mm);
5836 VM_BUG_ON(mc.moving_task);
5837 mc.moving_task = current;
5838 return mem_cgroup_do_precharge(precharge);
5841 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5842 static void __mem_cgroup_clear_mc(void)
5844 struct mem_cgroup *from = mc.from;
5845 struct mem_cgroup *to = mc.to;
5847 /* we must uncharge all the leftover precharges from mc.to */
5849 cancel_charge(mc.to, mc.precharge);
5853 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5854 * we must uncharge here.
5856 if (mc.moved_charge) {
5857 cancel_charge(mc.from, mc.moved_charge);
5858 mc.moved_charge = 0;
5860 /* we must fixup refcnts and charges */
5861 if (mc.moved_swap) {
5862 /* uncharge swap account from the old cgroup */
5863 if (!mem_cgroup_is_root(mc.from))
5864 page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
5866 mem_cgroup_id_put_many(mc.from, mc.moved_swap);
5869 * we charged both to->memory and to->memsw, so we
5870 * should uncharge to->memory.
5872 if (!mem_cgroup_is_root(mc.to))
5873 page_counter_uncharge(&mc.to->memory, mc.moved_swap);
5877 memcg_oom_recover(from);
5878 memcg_oom_recover(to);
5879 wake_up_all(&mc.waitq);
5882 static void mem_cgroup_clear_mc(void)
5884 struct mm_struct *mm = mc.mm;
5887 * we must clear moving_task before waking up waiters at the end of
5890 mc.moving_task = NULL;
5891 __mem_cgroup_clear_mc();
5892 spin_lock(&mc.lock);
5896 spin_unlock(&mc.lock);
5901 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
5903 struct cgroup_subsys_state *css;
5904 struct mem_cgroup *memcg = NULL; /* unneeded init to make gcc happy */
5905 struct mem_cgroup *from;
5906 struct task_struct *leader, *p;
5907 struct mm_struct *mm;
5908 unsigned long move_flags;
5911 /* charge immigration isn't supported on the default hierarchy */
5912 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
5916 * Multi-process migrations only happen on the default hierarchy
5917 * where charge immigration is not used. Perform charge
5918 * immigration if @tset contains a leader and whine if there are
5922 cgroup_taskset_for_each_leader(leader, css, tset) {
5925 memcg = mem_cgroup_from_css(css);
5931 * We are now committed to this value whatever it is. Changes in this
5932 * tunable will only affect upcoming migrations, not the current one.
5933 * So we need to save it, and keep it going.
5935 move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
5939 from = mem_cgroup_from_task(p);
5941 VM_BUG_ON(from == memcg);
5943 mm = get_task_mm(p);
5946 /* We move charges only when we move a owner of the mm */
5947 if (mm->owner == p) {
5950 VM_BUG_ON(mc.precharge);
5951 VM_BUG_ON(mc.moved_charge);
5952 VM_BUG_ON(mc.moved_swap);
5954 spin_lock(&mc.lock);
5958 mc.flags = move_flags;
5959 spin_unlock(&mc.lock);
5960 /* We set mc.moving_task later */
5962 ret = mem_cgroup_precharge_mc(mm);
5964 mem_cgroup_clear_mc();
5971 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
5974 mem_cgroup_clear_mc();
5977 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
5978 unsigned long addr, unsigned long end,
5979 struct mm_walk *walk)
5982 struct vm_area_struct *vma = walk->vma;
5985 enum mc_target_type target_type;
5986 union mc_target target;
5989 ptl = pmd_trans_huge_lock(pmd, vma);
5991 if (mc.precharge < HPAGE_PMD_NR) {
5995 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
5996 if (target_type == MC_TARGET_PAGE) {
5998 if (!isolate_lru_page(page)) {
5999 if (!mem_cgroup_move_account(page, true,
6001 mc.precharge -= HPAGE_PMD_NR;
6002 mc.moved_charge += HPAGE_PMD_NR;
6004 putback_lru_page(page);
6007 } else if (target_type == MC_TARGET_DEVICE) {
6009 if (!mem_cgroup_move_account(page, true,
6011 mc.precharge -= HPAGE_PMD_NR;
6012 mc.moved_charge += HPAGE_PMD_NR;
6020 if (pmd_trans_unstable(pmd))
6023 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6024 for (; addr != end; addr += PAGE_SIZE) {
6025 pte_t ptent = *(pte++);
6026 bool device = false;
6032 switch (get_mctgt_type(vma, addr, ptent, &target)) {
6033 case MC_TARGET_DEVICE:
6036 case MC_TARGET_PAGE:
6039 * We can have a part of the split pmd here. Moving it
6040 * can be done but it would be too convoluted so simply
6041 * ignore such a partial THP and keep it in original
6042 * memcg. There should be somebody mapping the head.
6044 if (PageTransCompound(page))
6046 if (!device && isolate_lru_page(page))
6048 if (!mem_cgroup_move_account(page, false,
6051 /* we uncharge from mc.from later. */
6055 putback_lru_page(page);
6056 put: /* get_mctgt_type() gets the page */
6059 case MC_TARGET_SWAP:
6061 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
6063 mem_cgroup_id_get_many(mc.to, 1);
6064 /* we fixup other refcnts and charges later. */
6072 pte_unmap_unlock(pte - 1, ptl);
6077 * We have consumed all precharges we got in can_attach().
6078 * We try charge one by one, but don't do any additional
6079 * charges to mc.to if we have failed in charge once in attach()
6082 ret = mem_cgroup_do_precharge(1);
6090 static const struct mm_walk_ops charge_walk_ops = {
6091 .pmd_entry = mem_cgroup_move_charge_pte_range,
6094 static void mem_cgroup_move_charge(void)
6096 lru_add_drain_all();
6098 * Signal lock_page_memcg() to take the memcg's move_lock
6099 * while we're moving its pages to another memcg. Then wait
6100 * for already started RCU-only updates to finish.
6102 atomic_inc(&mc.from->moving_account);
6105 if (unlikely(!mmap_read_trylock(mc.mm))) {
6107 * Someone who are holding the mmap_lock might be waiting in
6108 * waitq. So we cancel all extra charges, wake up all waiters,
6109 * and retry. Because we cancel precharges, we might not be able
6110 * to move enough charges, but moving charge is a best-effort
6111 * feature anyway, so it wouldn't be a big problem.
6113 __mem_cgroup_clear_mc();
6118 * When we have consumed all precharges and failed in doing
6119 * additional charge, the page walk just aborts.
6121 walk_page_range(mc.mm, 0, mc.mm->highest_vm_end, &charge_walk_ops,
6124 mmap_read_unlock(mc.mm);
6125 atomic_dec(&mc.from->moving_account);
6128 static void mem_cgroup_move_task(void)
6131 mem_cgroup_move_charge();
6132 mem_cgroup_clear_mc();
6135 #else /* !CONFIG_MMU */
6136 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
6140 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6143 static void mem_cgroup_move_task(void)
6148 static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
6150 if (value == PAGE_COUNTER_MAX)
6151 seq_puts(m, "max\n");
6153 seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
6158 static u64 memory_current_read(struct cgroup_subsys_state *css,
6161 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6163 return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
6166 static int memory_min_show(struct seq_file *m, void *v)
6168 return seq_puts_memcg_tunable(m,
6169 READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
6172 static ssize_t memory_min_write(struct kernfs_open_file *of,
6173 char *buf, size_t nbytes, loff_t off)
6175 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6179 buf = strstrip(buf);
6180 err = page_counter_memparse(buf, "max", &min);
6184 page_counter_set_min(&memcg->memory, min);
6189 static int memory_low_show(struct seq_file *m, void *v)
6191 return seq_puts_memcg_tunable(m,
6192 READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
6195 static ssize_t memory_low_write(struct kernfs_open_file *of,
6196 char *buf, size_t nbytes, loff_t off)
6198 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6202 buf = strstrip(buf);
6203 err = page_counter_memparse(buf, "max", &low);
6207 page_counter_set_low(&memcg->memory, low);
6212 static int memory_high_show(struct seq_file *m, void *v)
6214 return seq_puts_memcg_tunable(m,
6215 READ_ONCE(mem_cgroup_from_seq(m)->memory.high));
6218 static ssize_t memory_high_write(struct kernfs_open_file *of,
6219 char *buf, size_t nbytes, loff_t off)
6221 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6222 unsigned int nr_retries = MAX_RECLAIM_RETRIES;
6223 bool drained = false;
6227 buf = strstrip(buf);
6228 err = page_counter_memparse(buf, "max", &high);
6232 page_counter_set_high(&memcg->memory, high);
6235 unsigned long nr_pages = page_counter_read(&memcg->memory);
6236 unsigned long reclaimed;
6238 if (nr_pages <= high)
6241 if (signal_pending(current))
6245 drain_all_stock(memcg);
6250 reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
6253 if (!reclaimed && !nr_retries--)
6257 memcg_wb_domain_size_changed(memcg);
6261 static int memory_max_show(struct seq_file *m, void *v)
6263 return seq_puts_memcg_tunable(m,
6264 READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
6267 static ssize_t memory_max_write(struct kernfs_open_file *of,
6268 char *buf, size_t nbytes, loff_t off)
6270 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6271 unsigned int nr_reclaims = MAX_RECLAIM_RETRIES;
6272 bool drained = false;
6276 buf = strstrip(buf);
6277 err = page_counter_memparse(buf, "max", &max);
6281 xchg(&memcg->memory.max, max);
6284 unsigned long nr_pages = page_counter_read(&memcg->memory);
6286 if (nr_pages <= max)
6289 if (signal_pending(current))
6293 drain_all_stock(memcg);
6299 if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
6305 memcg_memory_event(memcg, MEMCG_OOM);
6306 if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
6310 memcg_wb_domain_size_changed(memcg);
6314 static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
6316 seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
6317 seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
6318 seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
6319 seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
6320 seq_printf(m, "oom_kill %lu\n",
6321 atomic_long_read(&events[MEMCG_OOM_KILL]));
6324 static int memory_events_show(struct seq_file *m, void *v)
6326 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6328 __memory_events_show(m, memcg->memory_events);
6332 static int memory_events_local_show(struct seq_file *m, void *v)
6334 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6336 __memory_events_show(m, memcg->memory_events_local);
6340 static int memory_stat_show(struct seq_file *m, void *v)
6342 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6345 buf = memory_stat_format(memcg);
6354 static inline unsigned long lruvec_page_state_output(struct lruvec *lruvec,
6357 return lruvec_page_state(lruvec, item) * memcg_page_state_unit(item);
6360 static int memory_numa_stat_show(struct seq_file *m, void *v)
6363 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6365 cgroup_rstat_flush(memcg->css.cgroup);
6367 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
6370 if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS)
6373 seq_printf(m, "%s", memory_stats[i].name);
6374 for_each_node_state(nid, N_MEMORY) {
6376 struct lruvec *lruvec;
6378 lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
6379 size = lruvec_page_state_output(lruvec,
6380 memory_stats[i].idx);
6381 seq_printf(m, " N%d=%llu", nid, size);
6390 static int memory_oom_group_show(struct seq_file *m, void *v)
6392 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6394 seq_printf(m, "%d\n", memcg->oom_group);
6399 static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
6400 char *buf, size_t nbytes, loff_t off)
6402 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6405 buf = strstrip(buf);
6409 ret = kstrtoint(buf, 0, &oom_group);
6413 if (oom_group != 0 && oom_group != 1)
6416 memcg->oom_group = oom_group;
6421 static struct cftype memory_files[] = {
6424 .flags = CFTYPE_NOT_ON_ROOT,
6425 .read_u64 = memory_current_read,
6429 .flags = CFTYPE_NOT_ON_ROOT,
6430 .seq_show = memory_min_show,
6431 .write = memory_min_write,
6435 .flags = CFTYPE_NOT_ON_ROOT,
6436 .seq_show = memory_low_show,
6437 .write = memory_low_write,
6441 .flags = CFTYPE_NOT_ON_ROOT,
6442 .seq_show = memory_high_show,
6443 .write = memory_high_write,
6447 .flags = CFTYPE_NOT_ON_ROOT,
6448 .seq_show = memory_max_show,
6449 .write = memory_max_write,
6453 .flags = CFTYPE_NOT_ON_ROOT,
6454 .file_offset = offsetof(struct mem_cgroup, events_file),
6455 .seq_show = memory_events_show,
6458 .name = "events.local",
6459 .flags = CFTYPE_NOT_ON_ROOT,
6460 .file_offset = offsetof(struct mem_cgroup, events_local_file),
6461 .seq_show = memory_events_local_show,
6465 .seq_show = memory_stat_show,
6469 .name = "numa_stat",
6470 .seq_show = memory_numa_stat_show,
6474 .name = "oom.group",
6475 .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
6476 .seq_show = memory_oom_group_show,
6477 .write = memory_oom_group_write,
6482 struct cgroup_subsys memory_cgrp_subsys = {
6483 .css_alloc = mem_cgroup_css_alloc,
6484 .css_online = mem_cgroup_css_online,
6485 .css_offline = mem_cgroup_css_offline,
6486 .css_released = mem_cgroup_css_released,
6487 .css_free = mem_cgroup_css_free,
6488 .css_reset = mem_cgroup_css_reset,
6489 .css_rstat_flush = mem_cgroup_css_rstat_flush,
6490 .can_attach = mem_cgroup_can_attach,
6491 .cancel_attach = mem_cgroup_cancel_attach,
6492 .post_attach = mem_cgroup_move_task,
6493 .dfl_cftypes = memory_files,
6494 .legacy_cftypes = mem_cgroup_legacy_files,
6499 * This function calculates an individual cgroup's effective
6500 * protection which is derived from its own memory.min/low, its
6501 * parent's and siblings' settings, as well as the actual memory
6502 * distribution in the tree.
6504 * The following rules apply to the effective protection values:
6506 * 1. At the first level of reclaim, effective protection is equal to
6507 * the declared protection in memory.min and memory.low.
6509 * 2. To enable safe delegation of the protection configuration, at
6510 * subsequent levels the effective protection is capped to the
6511 * parent's effective protection.
6513 * 3. To make complex and dynamic subtrees easier to configure, the
6514 * user is allowed to overcommit the declared protection at a given
6515 * level. If that is the case, the parent's effective protection is
6516 * distributed to the children in proportion to how much protection
6517 * they have declared and how much of it they are utilizing.
6519 * This makes distribution proportional, but also work-conserving:
6520 * if one cgroup claims much more protection than it uses memory,
6521 * the unused remainder is available to its siblings.
6523 * 4. Conversely, when the declared protection is undercommitted at a
6524 * given level, the distribution of the larger parental protection
6525 * budget is NOT proportional. A cgroup's protection from a sibling
6526 * is capped to its own memory.min/low setting.
6528 * 5. However, to allow protecting recursive subtrees from each other
6529 * without having to declare each individual cgroup's fixed share
6530 * of the ancestor's claim to protection, any unutilized -
6531 * "floating" - protection from up the tree is distributed in
6532 * proportion to each cgroup's *usage*. This makes the protection
6533 * neutral wrt sibling cgroups and lets them compete freely over
6534 * the shared parental protection budget, but it protects the
6535 * subtree as a whole from neighboring subtrees.
6537 * Note that 4. and 5. are not in conflict: 4. is about protecting
6538 * against immediate siblings whereas 5. is about protecting against
6539 * neighboring subtrees.
6541 static unsigned long effective_protection(unsigned long usage,
6542 unsigned long parent_usage,
6543 unsigned long setting,
6544 unsigned long parent_effective,
6545 unsigned long siblings_protected)
6547 unsigned long protected;
6550 protected = min(usage, setting);
6552 * If all cgroups at this level combined claim and use more
6553 * protection then what the parent affords them, distribute
6554 * shares in proportion to utilization.
6556 * We are using actual utilization rather than the statically
6557 * claimed protection in order to be work-conserving: claimed
6558 * but unused protection is available to siblings that would
6559 * otherwise get a smaller chunk than what they claimed.
6561 if (siblings_protected > parent_effective)
6562 return protected * parent_effective / siblings_protected;
6565 * Ok, utilized protection of all children is within what the
6566 * parent affords them, so we know whatever this child claims
6567 * and utilizes is effectively protected.
6569 * If there is unprotected usage beyond this value, reclaim
6570 * will apply pressure in proportion to that amount.
6572 * If there is unutilized protection, the cgroup will be fully
6573 * shielded from reclaim, but we do return a smaller value for
6574 * protection than what the group could enjoy in theory. This
6575 * is okay. With the overcommit distribution above, effective
6576 * protection is always dependent on how memory is actually
6577 * consumed among the siblings anyway.
6582 * If the children aren't claiming (all of) the protection
6583 * afforded to them by the parent, distribute the remainder in
6584 * proportion to the (unprotected) memory of each cgroup. That
6585 * way, cgroups that aren't explicitly prioritized wrt each
6586 * other compete freely over the allowance, but they are
6587 * collectively protected from neighboring trees.
6589 * We're using unprotected memory for the weight so that if
6590 * some cgroups DO claim explicit protection, we don't protect
6591 * the same bytes twice.
6593 * Check both usage and parent_usage against the respective
6594 * protected values. One should imply the other, but they
6595 * aren't read atomically - make sure the division is sane.
6597 if (!(cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT))
6599 if (parent_effective > siblings_protected &&
6600 parent_usage > siblings_protected &&
6601 usage > protected) {
6602 unsigned long unclaimed;
6604 unclaimed = parent_effective - siblings_protected;
6605 unclaimed *= usage - protected;
6606 unclaimed /= parent_usage - siblings_protected;
6615 * mem_cgroup_calculate_protection - check if memory consumption is in the normal range
6616 * @root: the top ancestor of the sub-tree being checked
6617 * @memcg: the memory cgroup to check
6619 * WARNING: This function is not stateless! It can only be used as part
6620 * of a top-down tree iteration, not for isolated queries.
6622 void mem_cgroup_calculate_protection(struct mem_cgroup *root,
6623 struct mem_cgroup *memcg)
6625 unsigned long usage, parent_usage;
6626 struct mem_cgroup *parent;
6628 if (mem_cgroup_disabled())
6632 root = root_mem_cgroup;
6635 * Effective values of the reclaim targets are ignored so they
6636 * can be stale. Have a look at mem_cgroup_protection for more
6638 * TODO: calculation should be more robust so that we do not need
6639 * that special casing.
6644 usage = page_counter_read(&memcg->memory);
6648 parent = parent_mem_cgroup(memcg);
6649 /* No parent means a non-hierarchical mode on v1 memcg */
6653 if (parent == root) {
6654 memcg->memory.emin = READ_ONCE(memcg->memory.min);
6655 memcg->memory.elow = READ_ONCE(memcg->memory.low);
6659 parent_usage = page_counter_read(&parent->memory);
6661 WRITE_ONCE(memcg->memory.emin, effective_protection(usage, parent_usage,
6662 READ_ONCE(memcg->memory.min),
6663 READ_ONCE(parent->memory.emin),
6664 atomic_long_read(&parent->memory.children_min_usage)));
6666 WRITE_ONCE(memcg->memory.elow, effective_protection(usage, parent_usage,
6667 READ_ONCE(memcg->memory.low),
6668 READ_ONCE(parent->memory.elow),
6669 atomic_long_read(&parent->memory.children_low_usage)));
6672 static int charge_memcg(struct page *page, struct mem_cgroup *memcg, gfp_t gfp)
6674 unsigned int nr_pages = thp_nr_pages(page);
6677 ret = try_charge(memcg, gfp, nr_pages);
6681 css_get(&memcg->css);
6682 commit_charge(page, memcg);
6684 local_irq_disable();
6685 mem_cgroup_charge_statistics(memcg, page, nr_pages);
6686 memcg_check_events(memcg, page);
6693 * __mem_cgroup_charge - charge a newly allocated page to a cgroup
6694 * @page: page to charge
6695 * @mm: mm context of the victim
6696 * @gfp_mask: reclaim mode
6698 * Try to charge @page to the memcg that @mm belongs to, reclaiming
6699 * pages according to @gfp_mask if necessary. if @mm is NULL, try to
6700 * charge to the active memcg.
6702 * Do not use this for pages allocated for swapin.
6704 * Returns 0 on success. Otherwise, an error code is returned.
6706 int __mem_cgroup_charge(struct page *page, struct mm_struct *mm,
6709 struct mem_cgroup *memcg;
6712 memcg = get_mem_cgroup_from_mm(mm);
6713 ret = charge_memcg(page, memcg, gfp_mask);
6714 css_put(&memcg->css);
6720 * mem_cgroup_swapin_charge_page - charge a newly allocated page for swapin
6721 * @page: page to charge
6722 * @mm: mm context of the victim
6723 * @gfp: reclaim mode
6724 * @entry: swap entry for which the page is allocated
6726 * This function charges a page allocated for swapin. Please call this before
6727 * adding the page to the swapcache.
6729 * Returns 0 on success. Otherwise, an error code is returned.
6731 int mem_cgroup_swapin_charge_page(struct page *page, struct mm_struct *mm,
6732 gfp_t gfp, swp_entry_t entry)
6734 struct mem_cgroup *memcg;
6738 if (mem_cgroup_disabled())
6741 id = lookup_swap_cgroup_id(entry);
6743 memcg = mem_cgroup_from_id(id);
6744 if (!memcg || !css_tryget_online(&memcg->css))
6745 memcg = get_mem_cgroup_from_mm(mm);
6748 ret = charge_memcg(page, memcg, gfp);
6750 css_put(&memcg->css);
6755 * mem_cgroup_swapin_uncharge_swap - uncharge swap slot
6756 * @entry: swap entry for which the page is charged
6758 * Call this function after successfully adding the charged page to swapcache.
6760 * Note: This function assumes the page for which swap slot is being uncharged
6763 void mem_cgroup_swapin_uncharge_swap(swp_entry_t entry)
6766 * Cgroup1's unified memory+swap counter has been charged with the
6767 * new swapcache page, finish the transfer by uncharging the swap
6768 * slot. The swap slot would also get uncharged when it dies, but
6769 * it can stick around indefinitely and we'd count the page twice
6772 * Cgroup2 has separate resource counters for memory and swap,
6773 * so this is a non-issue here. Memory and swap charge lifetimes
6774 * correspond 1:1 to page and swap slot lifetimes: we charge the
6775 * page to memory here, and uncharge swap when the slot is freed.
6777 if (!mem_cgroup_disabled() && do_memsw_account()) {
6779 * The swap entry might not get freed for a long time,
6780 * let's not wait for it. The page already received a
6781 * memory+swap charge, drop the swap entry duplicate.
6783 mem_cgroup_uncharge_swap(entry, 1);
6787 struct uncharge_gather {
6788 struct mem_cgroup *memcg;
6789 unsigned long nr_memory;
6790 unsigned long pgpgout;
6791 unsigned long nr_kmem;
6792 struct page *dummy_page;
6795 static inline void uncharge_gather_clear(struct uncharge_gather *ug)
6797 memset(ug, 0, sizeof(*ug));
6800 static void uncharge_batch(const struct uncharge_gather *ug)
6802 unsigned long flags;
6804 if (ug->nr_memory) {
6805 page_counter_uncharge(&ug->memcg->memory, ug->nr_memory);
6806 if (do_memsw_account())
6807 page_counter_uncharge(&ug->memcg->memsw, ug->nr_memory);
6808 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && ug->nr_kmem)
6809 page_counter_uncharge(&ug->memcg->kmem, ug->nr_kmem);
6810 memcg_oom_recover(ug->memcg);
6813 local_irq_save(flags);
6814 __count_memcg_events(ug->memcg, PGPGOUT, ug->pgpgout);
6815 __this_cpu_add(ug->memcg->vmstats_percpu->nr_page_events, ug->nr_memory);
6816 memcg_check_events(ug->memcg, ug->dummy_page);
6817 local_irq_restore(flags);
6819 /* drop reference from uncharge_page */
6820 css_put(&ug->memcg->css);
6823 static void uncharge_page(struct page *page, struct uncharge_gather *ug)
6825 unsigned long nr_pages;
6826 struct mem_cgroup *memcg;
6827 struct obj_cgroup *objcg;
6828 bool use_objcg = PageMemcgKmem(page);
6830 VM_BUG_ON_PAGE(PageLRU(page), page);
6833 * Nobody should be changing or seriously looking at
6834 * page memcg or objcg at this point, we have fully
6835 * exclusive access to the page.
6838 objcg = __page_objcg(page);
6840 * This get matches the put at the end of the function and
6841 * kmem pages do not hold memcg references anymore.
6843 memcg = get_mem_cgroup_from_objcg(objcg);
6845 memcg = __page_memcg(page);
6851 if (ug->memcg != memcg) {
6854 uncharge_gather_clear(ug);
6857 ug->dummy_page = page;
6859 /* pairs with css_put in uncharge_batch */
6860 css_get(&memcg->css);
6863 nr_pages = compound_nr(page);
6866 ug->nr_memory += nr_pages;
6867 ug->nr_kmem += nr_pages;
6869 page->memcg_data = 0;
6870 obj_cgroup_put(objcg);
6872 /* LRU pages aren't accounted at the root level */
6873 if (!mem_cgroup_is_root(memcg))
6874 ug->nr_memory += nr_pages;
6877 page->memcg_data = 0;
6880 css_put(&memcg->css);
6884 * __mem_cgroup_uncharge - uncharge a page
6885 * @page: page to uncharge
6887 * Uncharge a page previously charged with __mem_cgroup_charge().
6889 void __mem_cgroup_uncharge(struct page *page)
6891 struct uncharge_gather ug;
6893 /* Don't touch page->lru of any random page, pre-check: */
6894 if (!page_memcg(page))
6897 uncharge_gather_clear(&ug);
6898 uncharge_page(page, &ug);
6899 uncharge_batch(&ug);
6903 * __mem_cgroup_uncharge_list - uncharge a list of page
6904 * @page_list: list of pages to uncharge
6906 * Uncharge a list of pages previously charged with
6907 * __mem_cgroup_charge().
6909 void __mem_cgroup_uncharge_list(struct list_head *page_list)
6911 struct uncharge_gather ug;
6914 uncharge_gather_clear(&ug);
6915 list_for_each_entry(page, page_list, lru)
6916 uncharge_page(page, &ug);
6918 uncharge_batch(&ug);
6922 * mem_cgroup_migrate - charge a page's replacement
6923 * @oldpage: currently circulating page
6924 * @newpage: replacement page
6926 * Charge @newpage as a replacement page for @oldpage. @oldpage will
6927 * be uncharged upon free.
6929 * Both pages must be locked, @newpage->mapping must be set up.
6931 void mem_cgroup_migrate(struct page *oldpage, struct page *newpage)
6933 struct mem_cgroup *memcg;
6934 unsigned int nr_pages;
6935 unsigned long flags;
6937 VM_BUG_ON_PAGE(!PageLocked(oldpage), oldpage);
6938 VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
6939 VM_BUG_ON_PAGE(PageAnon(oldpage) != PageAnon(newpage), newpage);
6940 VM_BUG_ON_PAGE(PageTransHuge(oldpage) != PageTransHuge(newpage),
6943 if (mem_cgroup_disabled())
6946 /* Page cache replacement: new page already charged? */
6947 if (page_memcg(newpage))
6950 memcg = page_memcg(oldpage);
6951 VM_WARN_ON_ONCE_PAGE(!memcg, oldpage);
6955 /* Force-charge the new page. The old one will be freed soon */
6956 nr_pages = thp_nr_pages(newpage);
6958 if (!mem_cgroup_is_root(memcg)) {
6959 page_counter_charge(&memcg->memory, nr_pages);
6960 if (do_memsw_account())
6961 page_counter_charge(&memcg->memsw, nr_pages);
6964 css_get(&memcg->css);
6965 commit_charge(newpage, memcg);
6967 local_irq_save(flags);
6968 mem_cgroup_charge_statistics(memcg, newpage, nr_pages);
6969 memcg_check_events(memcg, newpage);
6970 local_irq_restore(flags);
6973 DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
6974 EXPORT_SYMBOL(memcg_sockets_enabled_key);
6976 void mem_cgroup_sk_alloc(struct sock *sk)
6978 struct mem_cgroup *memcg;
6980 if (!mem_cgroup_sockets_enabled)
6983 /* Do not associate the sock with unrelated interrupted task's memcg. */
6988 memcg = mem_cgroup_from_task(current);
6989 if (memcg == root_mem_cgroup)
6991 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg->tcpmem_active)
6993 if (css_tryget(&memcg->css))
6994 sk->sk_memcg = memcg;
6999 void mem_cgroup_sk_free(struct sock *sk)
7002 css_put(&sk->sk_memcg->css);
7006 * mem_cgroup_charge_skmem - charge socket memory
7007 * @memcg: memcg to charge
7008 * @nr_pages: number of pages to charge
7009 * @gfp_mask: reclaim mode
7011 * Charges @nr_pages to @memcg. Returns %true if the charge fit within
7012 * @memcg's configured limit, %false if it doesn't.
7014 bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages,
7017 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
7018 struct page_counter *fail;
7020 if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) {
7021 memcg->tcpmem_pressure = 0;
7024 memcg->tcpmem_pressure = 1;
7025 if (gfp_mask & __GFP_NOFAIL) {
7026 page_counter_charge(&memcg->tcpmem, nr_pages);
7032 if (try_charge(memcg, gfp_mask, nr_pages) == 0) {
7033 mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
7041 * mem_cgroup_uncharge_skmem - uncharge socket memory
7042 * @memcg: memcg to uncharge
7043 * @nr_pages: number of pages to uncharge
7045 void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
7047 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
7048 page_counter_uncharge(&memcg->tcpmem, nr_pages);
7052 mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
7054 refill_stock(memcg, nr_pages);
7057 static int __init cgroup_memory(char *s)
7061 while ((token = strsep(&s, ",")) != NULL) {
7064 if (!strcmp(token, "nosocket"))
7065 cgroup_memory_nosocket = true;
7066 if (!strcmp(token, "nokmem"))
7067 cgroup_memory_nokmem = true;
7071 __setup("cgroup.memory=", cgroup_memory);
7074 * subsys_initcall() for memory controller.
7076 * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
7077 * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
7078 * basically everything that doesn't depend on a specific mem_cgroup structure
7079 * should be initialized from here.
7081 static int __init mem_cgroup_init(void)
7086 * Currently s32 type (can refer to struct batched_lruvec_stat) is
7087 * used for per-memcg-per-cpu caching of per-node statistics. In order
7088 * to work fine, we should make sure that the overfill threshold can't
7089 * exceed S32_MAX / PAGE_SIZE.
7091 BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE);
7093 cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
7094 memcg_hotplug_cpu_dead);
7096 for_each_possible_cpu(cpu)
7097 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
7100 for_each_node(node) {
7101 struct mem_cgroup_tree_per_node *rtpn;
7103 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL,
7104 node_online(node) ? node : NUMA_NO_NODE);
7106 rtpn->rb_root = RB_ROOT;
7107 rtpn->rb_rightmost = NULL;
7108 spin_lock_init(&rtpn->lock);
7109 soft_limit_tree.rb_tree_per_node[node] = rtpn;
7114 subsys_initcall(mem_cgroup_init);
7116 #ifdef CONFIG_MEMCG_SWAP
7117 static struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
7119 while (!refcount_inc_not_zero(&memcg->id.ref)) {
7121 * The root cgroup cannot be destroyed, so it's refcount must
7124 if (WARN_ON_ONCE(memcg == root_mem_cgroup)) {
7128 memcg = parent_mem_cgroup(memcg);
7130 memcg = root_mem_cgroup;
7136 * mem_cgroup_swapout - transfer a memsw charge to swap
7137 * @page: page whose memsw charge to transfer
7138 * @entry: swap entry to move the charge to
7140 * Transfer the memsw charge of @page to @entry.
7142 void mem_cgroup_swapout(struct page *page, swp_entry_t entry)
7144 struct mem_cgroup *memcg, *swap_memcg;
7145 unsigned int nr_entries;
7146 unsigned short oldid;
7148 VM_BUG_ON_PAGE(PageLRU(page), page);
7149 VM_BUG_ON_PAGE(page_count(page), page);
7151 if (mem_cgroup_disabled())
7154 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
7157 memcg = page_memcg(page);
7159 VM_WARN_ON_ONCE_PAGE(!memcg, page);
7164 * In case the memcg owning these pages has been offlined and doesn't
7165 * have an ID allocated to it anymore, charge the closest online
7166 * ancestor for the swap instead and transfer the memory+swap charge.
7168 swap_memcg = mem_cgroup_id_get_online(memcg);
7169 nr_entries = thp_nr_pages(page);
7170 /* Get references for the tail pages, too */
7172 mem_cgroup_id_get_many(swap_memcg, nr_entries - 1);
7173 oldid = swap_cgroup_record(entry, mem_cgroup_id(swap_memcg),
7175 VM_BUG_ON_PAGE(oldid, page);
7176 mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries);
7178 page->memcg_data = 0;
7180 if (!mem_cgroup_is_root(memcg))
7181 page_counter_uncharge(&memcg->memory, nr_entries);
7183 if (!cgroup_memory_noswap && memcg != swap_memcg) {
7184 if (!mem_cgroup_is_root(swap_memcg))
7185 page_counter_charge(&swap_memcg->memsw, nr_entries);
7186 page_counter_uncharge(&memcg->memsw, nr_entries);
7190 * Interrupts should be disabled here because the caller holds the
7191 * i_pages lock which is taken with interrupts-off. It is
7192 * important here to have the interrupts disabled because it is the
7193 * only synchronisation we have for updating the per-CPU variables.
7195 VM_BUG_ON(!irqs_disabled());
7196 mem_cgroup_charge_statistics(memcg, page, -nr_entries);
7197 memcg_check_events(memcg, page);
7199 css_put(&memcg->css);
7203 * __mem_cgroup_try_charge_swap - try charging swap space for a page
7204 * @page: page being added to swap
7205 * @entry: swap entry to charge
7207 * Try to charge @page's memcg for the swap space at @entry.
7209 * Returns 0 on success, -ENOMEM on failure.
7211 int __mem_cgroup_try_charge_swap(struct page *page, swp_entry_t entry)
7213 unsigned int nr_pages = thp_nr_pages(page);
7214 struct page_counter *counter;
7215 struct mem_cgroup *memcg;
7216 unsigned short oldid;
7218 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
7221 memcg = page_memcg(page);
7223 VM_WARN_ON_ONCE_PAGE(!memcg, page);
7228 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7232 memcg = mem_cgroup_id_get_online(memcg);
7234 if (!cgroup_memory_noswap && !mem_cgroup_is_root(memcg) &&
7235 !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
7236 memcg_memory_event(memcg, MEMCG_SWAP_MAX);
7237 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7238 mem_cgroup_id_put(memcg);
7242 /* Get references for the tail pages, too */
7244 mem_cgroup_id_get_many(memcg, nr_pages - 1);
7245 oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg), nr_pages);
7246 VM_BUG_ON_PAGE(oldid, page);
7247 mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
7253 * __mem_cgroup_uncharge_swap - uncharge swap space
7254 * @entry: swap entry to uncharge
7255 * @nr_pages: the amount of swap space to uncharge
7257 void __mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
7259 struct mem_cgroup *memcg;
7262 id = swap_cgroup_record(entry, 0, nr_pages);
7264 memcg = mem_cgroup_from_id(id);
7266 if (!cgroup_memory_noswap && !mem_cgroup_is_root(memcg)) {
7267 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
7268 page_counter_uncharge(&memcg->swap, nr_pages);
7270 page_counter_uncharge(&memcg->memsw, nr_pages);
7272 mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
7273 mem_cgroup_id_put_many(memcg, nr_pages);
7278 long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
7280 long nr_swap_pages = get_nr_swap_pages();
7282 if (cgroup_memory_noswap || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
7283 return nr_swap_pages;
7284 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg))
7285 nr_swap_pages = min_t(long, nr_swap_pages,
7286 READ_ONCE(memcg->swap.max) -
7287 page_counter_read(&memcg->swap));
7288 return nr_swap_pages;
7291 bool mem_cgroup_swap_full(struct page *page)
7293 struct mem_cgroup *memcg;
7295 VM_BUG_ON_PAGE(!PageLocked(page), page);
7299 if (cgroup_memory_noswap || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
7302 memcg = page_memcg(page);
7306 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg)) {
7307 unsigned long usage = page_counter_read(&memcg->swap);
7309 if (usage * 2 >= READ_ONCE(memcg->swap.high) ||
7310 usage * 2 >= READ_ONCE(memcg->swap.max))
7317 static int __init setup_swap_account(char *s)
7319 if (!strcmp(s, "1"))
7320 cgroup_memory_noswap = false;
7321 else if (!strcmp(s, "0"))
7322 cgroup_memory_noswap = true;
7325 __setup("swapaccount=", setup_swap_account);
7327 static u64 swap_current_read(struct cgroup_subsys_state *css,
7330 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7332 return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
7335 static int swap_high_show(struct seq_file *m, void *v)
7337 return seq_puts_memcg_tunable(m,
7338 READ_ONCE(mem_cgroup_from_seq(m)->swap.high));
7341 static ssize_t swap_high_write(struct kernfs_open_file *of,
7342 char *buf, size_t nbytes, loff_t off)
7344 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7348 buf = strstrip(buf);
7349 err = page_counter_memparse(buf, "max", &high);
7353 page_counter_set_high(&memcg->swap, high);
7358 static int swap_max_show(struct seq_file *m, void *v)
7360 return seq_puts_memcg_tunable(m,
7361 READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
7364 static ssize_t swap_max_write(struct kernfs_open_file *of,
7365 char *buf, size_t nbytes, loff_t off)
7367 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7371 buf = strstrip(buf);
7372 err = page_counter_memparse(buf, "max", &max);
7376 xchg(&memcg->swap.max, max);
7381 static int swap_events_show(struct seq_file *m, void *v)
7383 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
7385 seq_printf(m, "high %lu\n",
7386 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH]));
7387 seq_printf(m, "max %lu\n",
7388 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
7389 seq_printf(m, "fail %lu\n",
7390 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
7395 static struct cftype swap_files[] = {
7397 .name = "swap.current",
7398 .flags = CFTYPE_NOT_ON_ROOT,
7399 .read_u64 = swap_current_read,
7402 .name = "swap.high",
7403 .flags = CFTYPE_NOT_ON_ROOT,
7404 .seq_show = swap_high_show,
7405 .write = swap_high_write,
7409 .flags = CFTYPE_NOT_ON_ROOT,
7410 .seq_show = swap_max_show,
7411 .write = swap_max_write,
7414 .name = "swap.events",
7415 .flags = CFTYPE_NOT_ON_ROOT,
7416 .file_offset = offsetof(struct mem_cgroup, swap_events_file),
7417 .seq_show = swap_events_show,
7422 static struct cftype memsw_files[] = {
7424 .name = "memsw.usage_in_bytes",
7425 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
7426 .read_u64 = mem_cgroup_read_u64,
7429 .name = "memsw.max_usage_in_bytes",
7430 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
7431 .write = mem_cgroup_reset,
7432 .read_u64 = mem_cgroup_read_u64,
7435 .name = "memsw.limit_in_bytes",
7436 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
7437 .write = mem_cgroup_write,
7438 .read_u64 = mem_cgroup_read_u64,
7441 .name = "memsw.failcnt",
7442 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
7443 .write = mem_cgroup_reset,
7444 .read_u64 = mem_cgroup_read_u64,
7446 { }, /* terminate */
7450 * If mem_cgroup_swap_init() is implemented as a subsys_initcall()
7451 * instead of a core_initcall(), this could mean cgroup_memory_noswap still
7452 * remains set to false even when memcg is disabled via "cgroup_disable=memory"
7453 * boot parameter. This may result in premature OOPS inside
7454 * mem_cgroup_get_nr_swap_pages() function in corner cases.
7456 static int __init mem_cgroup_swap_init(void)
7458 /* No memory control -> no swap control */
7459 if (mem_cgroup_disabled())
7460 cgroup_memory_noswap = true;
7462 if (cgroup_memory_noswap)
7465 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files));
7466 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files));
7470 core_initcall(mem_cgroup_swap_init);
7472 #endif /* CONFIG_MEMCG_SWAP */