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 #define THRESHOLDS_EVENTS_TARGET 128
107 #define SOFTLIMIT_EVENTS_TARGET 1024
110 * Cgroups above their limits are maintained in a RB-Tree, independent of
111 * their hierarchy representation
114 struct mem_cgroup_tree_per_node {
115 struct rb_root rb_root;
116 struct rb_node *rb_rightmost;
120 struct mem_cgroup_tree {
121 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
124 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
127 struct mem_cgroup_eventfd_list {
128 struct list_head list;
129 struct eventfd_ctx *eventfd;
133 * cgroup_event represents events which userspace want to receive.
135 struct mem_cgroup_event {
137 * memcg which the event belongs to.
139 struct mem_cgroup *memcg;
141 * eventfd to signal userspace about the event.
143 struct eventfd_ctx *eventfd;
145 * Each of these stored in a list by the cgroup.
147 struct list_head list;
149 * register_event() callback will be used to add new userspace
150 * waiter for changes related to this event. Use eventfd_signal()
151 * on eventfd to send notification to userspace.
153 int (*register_event)(struct mem_cgroup *memcg,
154 struct eventfd_ctx *eventfd, const char *args);
156 * unregister_event() callback will be called when userspace closes
157 * the eventfd or on cgroup removing. This callback must be set,
158 * if you want provide notification functionality.
160 void (*unregister_event)(struct mem_cgroup *memcg,
161 struct eventfd_ctx *eventfd);
163 * All fields below needed to unregister event when
164 * userspace closes eventfd.
167 wait_queue_head_t *wqh;
168 wait_queue_entry_t wait;
169 struct work_struct remove;
172 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
173 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
175 /* Stuffs for move charges at task migration. */
177 * Types of charges to be moved.
179 #define MOVE_ANON 0x1U
180 #define MOVE_FILE 0x2U
181 #define MOVE_MASK (MOVE_ANON | MOVE_FILE)
183 /* "mc" and its members are protected by cgroup_mutex */
184 static struct move_charge_struct {
185 spinlock_t lock; /* for from, to */
186 struct mm_struct *mm;
187 struct mem_cgroup *from;
188 struct mem_cgroup *to;
190 unsigned long precharge;
191 unsigned long moved_charge;
192 unsigned long moved_swap;
193 struct task_struct *moving_task; /* a task moving charges */
194 wait_queue_head_t waitq; /* a waitq for other context */
196 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
197 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
201 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
202 * limit reclaim to prevent infinite loops, if they ever occur.
204 #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
205 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
207 /* for encoding cft->private value on file */
216 #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
217 #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
218 #define MEMFILE_ATTR(val) ((val) & 0xffff)
219 /* Used for OOM notifier */
220 #define OOM_CONTROL (0)
223 * Iteration constructs for visiting all cgroups (under a tree). If
224 * loops are exited prematurely (break), mem_cgroup_iter_break() must
225 * be used for reference counting.
227 #define for_each_mem_cgroup_tree(iter, root) \
228 for (iter = mem_cgroup_iter(root, NULL, NULL); \
230 iter = mem_cgroup_iter(root, iter, NULL))
232 #define for_each_mem_cgroup(iter) \
233 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
235 iter = mem_cgroup_iter(NULL, iter, NULL))
237 static inline bool should_force_charge(void)
239 return tsk_is_oom_victim(current) || fatal_signal_pending(current) ||
240 (current->flags & PF_EXITING);
243 /* Some nice accessors for the vmpressure. */
244 struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
247 memcg = root_mem_cgroup;
248 return &memcg->vmpressure;
251 struct cgroup_subsys_state *vmpressure_to_css(struct vmpressure *vmpr)
253 return &container_of(vmpr, struct mem_cgroup, vmpressure)->css;
256 #ifdef CONFIG_MEMCG_KMEM
257 extern spinlock_t css_set_lock;
259 bool mem_cgroup_kmem_disabled(void)
261 return cgroup_memory_nokmem;
264 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
265 unsigned int nr_pages);
267 static void obj_cgroup_release(struct percpu_ref *ref)
269 struct obj_cgroup *objcg = container_of(ref, struct obj_cgroup, refcnt);
270 unsigned int nr_bytes;
271 unsigned int nr_pages;
275 * At this point all allocated objects are freed, and
276 * objcg->nr_charged_bytes can't have an arbitrary byte value.
277 * However, it can be PAGE_SIZE or (x * PAGE_SIZE).
279 * The following sequence can lead to it:
280 * 1) CPU0: objcg == stock->cached_objcg
281 * 2) CPU1: we do a small allocation (e.g. 92 bytes),
282 * PAGE_SIZE bytes are charged
283 * 3) CPU1: a process from another memcg is allocating something,
284 * the stock if flushed,
285 * objcg->nr_charged_bytes = PAGE_SIZE - 92
286 * 5) CPU0: we do release this object,
287 * 92 bytes are added to stock->nr_bytes
288 * 6) CPU0: stock is flushed,
289 * 92 bytes are added to objcg->nr_charged_bytes
291 * In the result, nr_charged_bytes == PAGE_SIZE.
292 * This page will be uncharged in obj_cgroup_release().
294 nr_bytes = atomic_read(&objcg->nr_charged_bytes);
295 WARN_ON_ONCE(nr_bytes & (PAGE_SIZE - 1));
296 nr_pages = nr_bytes >> PAGE_SHIFT;
299 obj_cgroup_uncharge_pages(objcg, nr_pages);
301 spin_lock_irqsave(&css_set_lock, flags);
302 list_del(&objcg->list);
303 spin_unlock_irqrestore(&css_set_lock, flags);
305 percpu_ref_exit(ref);
306 kfree_rcu(objcg, rcu);
309 static struct obj_cgroup *obj_cgroup_alloc(void)
311 struct obj_cgroup *objcg;
314 objcg = kzalloc(sizeof(struct obj_cgroup), GFP_KERNEL);
318 ret = percpu_ref_init(&objcg->refcnt, obj_cgroup_release, 0,
324 INIT_LIST_HEAD(&objcg->list);
328 static void memcg_reparent_objcgs(struct mem_cgroup *memcg,
329 struct mem_cgroup *parent)
331 struct obj_cgroup *objcg, *iter;
333 objcg = rcu_replace_pointer(memcg->objcg, NULL, true);
335 spin_lock_irq(&css_set_lock);
337 /* 1) Ready to reparent active objcg. */
338 list_add(&objcg->list, &memcg->objcg_list);
339 /* 2) Reparent active objcg and already reparented objcgs to parent. */
340 list_for_each_entry(iter, &memcg->objcg_list, list)
341 WRITE_ONCE(iter->memcg, parent);
342 /* 3) Move already reparented objcgs to the parent's list */
343 list_splice(&memcg->objcg_list, &parent->objcg_list);
345 spin_unlock_irq(&css_set_lock);
347 percpu_ref_kill(&objcg->refcnt);
351 * This will be used as a shrinker list's index.
352 * The main reason for not using cgroup id for this:
353 * this works better in sparse environments, where we have a lot of memcgs,
354 * but only a few kmem-limited. Or also, if we have, for instance, 200
355 * memcgs, and none but the 200th is kmem-limited, we'd have to have a
356 * 200 entry array for that.
358 * The current size of the caches array is stored in memcg_nr_cache_ids. It
359 * will double each time we have to increase it.
361 static DEFINE_IDA(memcg_cache_ida);
362 int memcg_nr_cache_ids;
364 /* Protects memcg_nr_cache_ids */
365 static DECLARE_RWSEM(memcg_cache_ids_sem);
367 void memcg_get_cache_ids(void)
369 down_read(&memcg_cache_ids_sem);
372 void memcg_put_cache_ids(void)
374 up_read(&memcg_cache_ids_sem);
378 * MIN_SIZE is different than 1, because we would like to avoid going through
379 * the alloc/free process all the time. In a small machine, 4 kmem-limited
380 * cgroups is a reasonable guess. In the future, it could be a parameter or
381 * tunable, but that is strictly not necessary.
383 * MAX_SIZE should be as large as the number of cgrp_ids. Ideally, we could get
384 * this constant directly from cgroup, but it is understandable that this is
385 * better kept as an internal representation in cgroup.c. In any case, the
386 * cgrp_id space is not getting any smaller, and we don't have to necessarily
387 * increase ours as well if it increases.
389 #define MEMCG_CACHES_MIN_SIZE 4
390 #define MEMCG_CACHES_MAX_SIZE MEM_CGROUP_ID_MAX
393 * A lot of the calls to the cache allocation functions are expected to be
394 * inlined by the compiler. Since the calls to memcg_slab_pre_alloc_hook() are
395 * conditional to this static branch, we'll have to allow modules that does
396 * kmem_cache_alloc and the such to see this symbol as well
398 DEFINE_STATIC_KEY_FALSE(memcg_kmem_enabled_key);
399 EXPORT_SYMBOL(memcg_kmem_enabled_key);
403 * mem_cgroup_css_from_page - css of the memcg associated with a page
404 * @page: page of interest
406 * If memcg is bound to the default hierarchy, css of the memcg associated
407 * with @page is returned. The returned css remains associated with @page
408 * until it is released.
410 * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
413 struct cgroup_subsys_state *mem_cgroup_css_from_page(struct page *page)
415 struct mem_cgroup *memcg;
417 memcg = page_memcg(page);
419 if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
420 memcg = root_mem_cgroup;
426 * page_cgroup_ino - return inode number of the memcg a page is charged to
429 * Look up the closest online ancestor of the memory cgroup @page is charged to
430 * and return its inode number or 0 if @page is not charged to any cgroup. It
431 * is safe to call this function without holding a reference to @page.
433 * Note, this function is inherently racy, because there is nothing to prevent
434 * the cgroup inode from getting torn down and potentially reallocated a moment
435 * after page_cgroup_ino() returns, so it only should be used by callers that
436 * do not care (such as procfs interfaces).
438 ino_t page_cgroup_ino(struct page *page)
440 struct mem_cgroup *memcg;
441 unsigned long ino = 0;
444 memcg = page_memcg_check(page);
446 while (memcg && !(memcg->css.flags & CSS_ONLINE))
447 memcg = parent_mem_cgroup(memcg);
449 ino = cgroup_ino(memcg->css.cgroup);
454 static struct mem_cgroup_per_node *
455 mem_cgroup_page_nodeinfo(struct mem_cgroup *memcg, struct page *page)
457 int nid = page_to_nid(page);
459 return memcg->nodeinfo[nid];
462 static struct mem_cgroup_tree_per_node *
463 soft_limit_tree_node(int nid)
465 return soft_limit_tree.rb_tree_per_node[nid];
468 static struct mem_cgroup_tree_per_node *
469 soft_limit_tree_from_page(struct page *page)
471 int nid = page_to_nid(page);
473 return soft_limit_tree.rb_tree_per_node[nid];
476 static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_node *mz,
477 struct mem_cgroup_tree_per_node *mctz,
478 unsigned long new_usage_in_excess)
480 struct rb_node **p = &mctz->rb_root.rb_node;
481 struct rb_node *parent = NULL;
482 struct mem_cgroup_per_node *mz_node;
483 bool rightmost = true;
488 mz->usage_in_excess = new_usage_in_excess;
489 if (!mz->usage_in_excess)
493 mz_node = rb_entry(parent, struct mem_cgroup_per_node,
495 if (mz->usage_in_excess < mz_node->usage_in_excess) {
504 mctz->rb_rightmost = &mz->tree_node;
506 rb_link_node(&mz->tree_node, parent, p);
507 rb_insert_color(&mz->tree_node, &mctz->rb_root);
511 static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
512 struct mem_cgroup_tree_per_node *mctz)
517 if (&mz->tree_node == mctz->rb_rightmost)
518 mctz->rb_rightmost = rb_prev(&mz->tree_node);
520 rb_erase(&mz->tree_node, &mctz->rb_root);
524 static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
525 struct mem_cgroup_tree_per_node *mctz)
529 spin_lock_irqsave(&mctz->lock, flags);
530 __mem_cgroup_remove_exceeded(mz, mctz);
531 spin_unlock_irqrestore(&mctz->lock, flags);
534 static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
536 unsigned long nr_pages = page_counter_read(&memcg->memory);
537 unsigned long soft_limit = READ_ONCE(memcg->soft_limit);
538 unsigned long excess = 0;
540 if (nr_pages > soft_limit)
541 excess = nr_pages - soft_limit;
546 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
548 unsigned long excess;
549 struct mem_cgroup_per_node *mz;
550 struct mem_cgroup_tree_per_node *mctz;
552 mctz = soft_limit_tree_from_page(page);
556 * Necessary to update all ancestors when hierarchy is used.
557 * because their event counter is not touched.
559 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
560 mz = mem_cgroup_page_nodeinfo(memcg, page);
561 excess = soft_limit_excess(memcg);
563 * We have to update the tree if mz is on RB-tree or
564 * mem is over its softlimit.
566 if (excess || mz->on_tree) {
569 spin_lock_irqsave(&mctz->lock, flags);
570 /* if on-tree, remove it */
572 __mem_cgroup_remove_exceeded(mz, mctz);
574 * Insert again. mz->usage_in_excess will be updated.
575 * If excess is 0, no tree ops.
577 __mem_cgroup_insert_exceeded(mz, mctz, excess);
578 spin_unlock_irqrestore(&mctz->lock, flags);
583 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
585 struct mem_cgroup_tree_per_node *mctz;
586 struct mem_cgroup_per_node *mz;
590 mz = memcg->nodeinfo[nid];
591 mctz = soft_limit_tree_node(nid);
593 mem_cgroup_remove_exceeded(mz, mctz);
597 static struct mem_cgroup_per_node *
598 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
600 struct mem_cgroup_per_node *mz;
604 if (!mctz->rb_rightmost)
605 goto done; /* Nothing to reclaim from */
607 mz = rb_entry(mctz->rb_rightmost,
608 struct mem_cgroup_per_node, tree_node);
610 * Remove the node now but someone else can add it back,
611 * we will to add it back at the end of reclaim to its correct
612 * position in the tree.
614 __mem_cgroup_remove_exceeded(mz, mctz);
615 if (!soft_limit_excess(mz->memcg) ||
616 !css_tryget(&mz->memcg->css))
622 static struct mem_cgroup_per_node *
623 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
625 struct mem_cgroup_per_node *mz;
627 spin_lock_irq(&mctz->lock);
628 mz = __mem_cgroup_largest_soft_limit_node(mctz);
629 spin_unlock_irq(&mctz->lock);
634 * __mod_memcg_state - update cgroup memory statistics
635 * @memcg: the memory cgroup
636 * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item
637 * @val: delta to add to the counter, can be negative
639 void __mod_memcg_state(struct mem_cgroup *memcg, int idx, int val)
641 if (mem_cgroup_disabled())
644 __this_cpu_add(memcg->vmstats_percpu->state[idx], val);
645 cgroup_rstat_updated(memcg->css.cgroup, smp_processor_id());
648 /* idx can be of type enum memcg_stat_item or node_stat_item. */
649 static unsigned long memcg_page_state_local(struct mem_cgroup *memcg, int idx)
654 for_each_possible_cpu(cpu)
655 x += per_cpu(memcg->vmstats_percpu->state[idx], cpu);
663 static struct mem_cgroup_per_node *
664 parent_nodeinfo(struct mem_cgroup_per_node *pn, int nid)
666 struct mem_cgroup *parent;
668 parent = parent_mem_cgroup(pn->memcg);
671 return parent->nodeinfo[nid];
674 void __mod_memcg_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
677 struct mem_cgroup_per_node *pn;
678 struct mem_cgroup *memcg;
679 long x, threshold = MEMCG_CHARGE_BATCH;
681 pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
685 __mod_memcg_state(memcg, idx, val);
688 __this_cpu_add(pn->lruvec_stat_local->count[idx], val);
690 if (vmstat_item_in_bytes(idx))
691 threshold <<= PAGE_SHIFT;
693 x = val + __this_cpu_read(pn->lruvec_stat_cpu->count[idx]);
694 if (unlikely(abs(x) > threshold)) {
695 pg_data_t *pgdat = lruvec_pgdat(lruvec);
696 struct mem_cgroup_per_node *pi;
698 for (pi = pn; pi; pi = parent_nodeinfo(pi, pgdat->node_id))
699 atomic_long_add(x, &pi->lruvec_stat[idx]);
702 __this_cpu_write(pn->lruvec_stat_cpu->count[idx], x);
706 * __mod_lruvec_state - update lruvec memory statistics
707 * @lruvec: the lruvec
708 * @idx: the stat item
709 * @val: delta to add to the counter, can be negative
711 * The lruvec is the intersection of the NUMA node and a cgroup. This
712 * function updates the all three counters that are affected by a
713 * change of state at this level: per-node, per-cgroup, per-lruvec.
715 void __mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
719 __mod_node_page_state(lruvec_pgdat(lruvec), idx, val);
721 /* Update memcg and lruvec */
722 if (!mem_cgroup_disabled())
723 __mod_memcg_lruvec_state(lruvec, idx, val);
726 void __mod_lruvec_page_state(struct page *page, enum node_stat_item idx,
729 struct page *head = compound_head(page); /* rmap on tail pages */
730 struct mem_cgroup *memcg;
731 pg_data_t *pgdat = page_pgdat(page);
732 struct lruvec *lruvec;
735 memcg = page_memcg(head);
736 /* Untracked pages have no memcg, no lruvec. Update only the node */
739 __mod_node_page_state(pgdat, idx, val);
743 lruvec = mem_cgroup_lruvec(memcg, pgdat);
744 __mod_lruvec_state(lruvec, idx, val);
747 EXPORT_SYMBOL(__mod_lruvec_page_state);
749 void __mod_lruvec_kmem_state(void *p, enum node_stat_item idx, int val)
751 pg_data_t *pgdat = page_pgdat(virt_to_page(p));
752 struct mem_cgroup *memcg;
753 struct lruvec *lruvec;
756 memcg = mem_cgroup_from_obj(p);
759 * Untracked pages have no memcg, no lruvec. Update only the
760 * node. If we reparent the slab objects to the root memcg,
761 * when we free the slab object, we need to update the per-memcg
762 * vmstats to keep it correct for the root memcg.
765 __mod_node_page_state(pgdat, idx, val);
767 lruvec = mem_cgroup_lruvec(memcg, pgdat);
768 __mod_lruvec_state(lruvec, idx, val);
774 * mod_objcg_mlstate() may be called with irq enabled, so
775 * mod_memcg_lruvec_state() should be used.
777 static inline void mod_objcg_mlstate(struct obj_cgroup *objcg,
778 struct pglist_data *pgdat,
779 enum node_stat_item idx, int nr)
781 struct mem_cgroup *memcg;
782 struct lruvec *lruvec;
785 memcg = obj_cgroup_memcg(objcg);
786 lruvec = mem_cgroup_lruvec(memcg, pgdat);
787 mod_memcg_lruvec_state(lruvec, idx, nr);
792 * __count_memcg_events - account VM events in a cgroup
793 * @memcg: the memory cgroup
794 * @idx: the event item
795 * @count: the number of events that occurred
797 void __count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx,
800 if (mem_cgroup_disabled())
803 __this_cpu_add(memcg->vmstats_percpu->events[idx], count);
804 cgroup_rstat_updated(memcg->css.cgroup, smp_processor_id());
807 static unsigned long memcg_events(struct mem_cgroup *memcg, int event)
809 return READ_ONCE(memcg->vmstats.events[event]);
812 static unsigned long memcg_events_local(struct mem_cgroup *memcg, int event)
817 for_each_possible_cpu(cpu)
818 x += per_cpu(memcg->vmstats_percpu->events[event], cpu);
822 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
826 /* pagein of a big page is an event. So, ignore page size */
828 __count_memcg_events(memcg, PGPGIN, 1);
830 __count_memcg_events(memcg, PGPGOUT, 1);
831 nr_pages = -nr_pages; /* for event */
834 __this_cpu_add(memcg->vmstats_percpu->nr_page_events, nr_pages);
837 static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
838 enum mem_cgroup_events_target target)
840 unsigned long val, next;
842 val = __this_cpu_read(memcg->vmstats_percpu->nr_page_events);
843 next = __this_cpu_read(memcg->vmstats_percpu->targets[target]);
844 /* from time_after() in jiffies.h */
845 if ((long)(next - val) < 0) {
847 case MEM_CGROUP_TARGET_THRESH:
848 next = val + THRESHOLDS_EVENTS_TARGET;
850 case MEM_CGROUP_TARGET_SOFTLIMIT:
851 next = val + SOFTLIMIT_EVENTS_TARGET;
856 __this_cpu_write(memcg->vmstats_percpu->targets[target], next);
863 * Check events in order.
866 static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
868 /* threshold event is triggered in finer grain than soft limit */
869 if (unlikely(mem_cgroup_event_ratelimit(memcg,
870 MEM_CGROUP_TARGET_THRESH))) {
873 do_softlimit = mem_cgroup_event_ratelimit(memcg,
874 MEM_CGROUP_TARGET_SOFTLIMIT);
875 mem_cgroup_threshold(memcg);
876 if (unlikely(do_softlimit))
877 mem_cgroup_update_tree(memcg, page);
881 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
884 * mm_update_next_owner() may clear mm->owner to NULL
885 * if it races with swapoff, page migration, etc.
886 * So this can be called with p == NULL.
891 return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
893 EXPORT_SYMBOL(mem_cgroup_from_task);
895 static __always_inline struct mem_cgroup *active_memcg(void)
898 return this_cpu_read(int_active_memcg);
900 return current->active_memcg;
904 * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
905 * @mm: mm from which memcg should be extracted. It can be NULL.
907 * Obtain a reference on mm->memcg and returns it if successful. If mm
908 * is NULL, then the memcg is chosen as follows:
909 * 1) The active memcg, if set.
910 * 2) current->mm->memcg, if available
912 * If mem_cgroup is disabled, NULL is returned.
914 struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
916 struct mem_cgroup *memcg;
918 if (mem_cgroup_disabled())
922 * Page cache insertions can happen without an
923 * actual mm context, e.g. during disk probing
924 * on boot, loopback IO, acct() writes etc.
926 * No need to css_get on root memcg as the reference
927 * counting is disabled on the root level in the
928 * cgroup core. See CSS_NO_REF.
931 memcg = active_memcg();
932 if (unlikely(memcg)) {
933 /* remote memcg must hold a ref */
934 css_get(&memcg->css);
939 return root_mem_cgroup;
944 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
945 if (unlikely(!memcg))
946 memcg = root_mem_cgroup;
947 } while (!css_tryget(&memcg->css));
951 EXPORT_SYMBOL(get_mem_cgroup_from_mm);
953 static __always_inline bool memcg_kmem_bypass(void)
955 /* Allow remote memcg charging from any context. */
956 if (unlikely(active_memcg()))
959 /* Memcg to charge can't be determined. */
960 if (in_interrupt() || !current->mm || (current->flags & PF_KTHREAD))
967 * mem_cgroup_iter - iterate over memory cgroup hierarchy
968 * @root: hierarchy root
969 * @prev: previously returned memcg, NULL on first invocation
970 * @reclaim: cookie for shared reclaim walks, NULL for full walks
972 * Returns references to children of the hierarchy below @root, or
973 * @root itself, or %NULL after a full round-trip.
975 * Caller must pass the return value in @prev on subsequent
976 * invocations for reference counting, or use mem_cgroup_iter_break()
977 * to cancel a hierarchy walk before the round-trip is complete.
979 * Reclaimers can specify a node in @reclaim to divide up the memcgs
980 * in the hierarchy among all concurrent reclaimers operating on the
983 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
984 struct mem_cgroup *prev,
985 struct mem_cgroup_reclaim_cookie *reclaim)
987 struct mem_cgroup_reclaim_iter *iter;
988 struct cgroup_subsys_state *css = NULL;
989 struct mem_cgroup *memcg = NULL;
990 struct mem_cgroup *pos = NULL;
992 if (mem_cgroup_disabled())
996 root = root_mem_cgroup;
998 if (prev && !reclaim)
1004 struct mem_cgroup_per_node *mz;
1006 mz = root->nodeinfo[reclaim->pgdat->node_id];
1009 if (prev && reclaim->generation != iter->generation)
1013 pos = READ_ONCE(iter->position);
1014 if (!pos || css_tryget(&pos->css))
1017 * css reference reached zero, so iter->position will
1018 * be cleared by ->css_released. However, we should not
1019 * rely on this happening soon, because ->css_released
1020 * is called from a work queue, and by busy-waiting we
1021 * might block it. So we clear iter->position right
1024 (void)cmpxchg(&iter->position, pos, NULL);
1032 css = css_next_descendant_pre(css, &root->css);
1035 * Reclaimers share the hierarchy walk, and a
1036 * new one might jump in right at the end of
1037 * the hierarchy - make sure they see at least
1038 * one group and restart from the beginning.
1046 * Verify the css and acquire a reference. The root
1047 * is provided by the caller, so we know it's alive
1048 * and kicking, and don't take an extra reference.
1050 memcg = mem_cgroup_from_css(css);
1052 if (css == &root->css)
1055 if (css_tryget(css))
1063 * The position could have already been updated by a competing
1064 * thread, so check that the value hasn't changed since we read
1065 * it to avoid reclaiming from the same cgroup twice.
1067 (void)cmpxchg(&iter->position, pos, memcg);
1075 reclaim->generation = iter->generation;
1080 if (prev && prev != root)
1081 css_put(&prev->css);
1087 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1088 * @root: hierarchy root
1089 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1091 void mem_cgroup_iter_break(struct mem_cgroup *root,
1092 struct mem_cgroup *prev)
1095 root = root_mem_cgroup;
1096 if (prev && prev != root)
1097 css_put(&prev->css);
1100 static void __invalidate_reclaim_iterators(struct mem_cgroup *from,
1101 struct mem_cgroup *dead_memcg)
1103 struct mem_cgroup_reclaim_iter *iter;
1104 struct mem_cgroup_per_node *mz;
1107 for_each_node(nid) {
1108 mz = from->nodeinfo[nid];
1110 cmpxchg(&iter->position, dead_memcg, NULL);
1114 static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
1116 struct mem_cgroup *memcg = dead_memcg;
1117 struct mem_cgroup *last;
1120 __invalidate_reclaim_iterators(memcg, dead_memcg);
1122 } while ((memcg = parent_mem_cgroup(memcg)));
1125 * When cgruop1 non-hierarchy mode is used,
1126 * parent_mem_cgroup() does not walk all the way up to the
1127 * cgroup root (root_mem_cgroup). So we have to handle
1128 * dead_memcg from cgroup root separately.
1130 if (last != root_mem_cgroup)
1131 __invalidate_reclaim_iterators(root_mem_cgroup,
1136 * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
1137 * @memcg: hierarchy root
1138 * @fn: function to call for each task
1139 * @arg: argument passed to @fn
1141 * This function iterates over tasks attached to @memcg or to any of its
1142 * descendants and calls @fn for each task. If @fn returns a non-zero
1143 * value, the function breaks the iteration loop and returns the value.
1144 * Otherwise, it will iterate over all tasks and return 0.
1146 * This function must not be called for the root memory cgroup.
1148 int mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
1149 int (*fn)(struct task_struct *, void *), void *arg)
1151 struct mem_cgroup *iter;
1154 BUG_ON(memcg == root_mem_cgroup);
1156 for_each_mem_cgroup_tree(iter, memcg) {
1157 struct css_task_iter it;
1158 struct task_struct *task;
1160 css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it);
1161 while (!ret && (task = css_task_iter_next(&it)))
1162 ret = fn(task, arg);
1163 css_task_iter_end(&it);
1165 mem_cgroup_iter_break(memcg, iter);
1172 #ifdef CONFIG_DEBUG_VM
1173 void lruvec_memcg_debug(struct lruvec *lruvec, struct page *page)
1175 struct mem_cgroup *memcg;
1177 if (mem_cgroup_disabled())
1180 memcg = page_memcg(page);
1183 VM_BUG_ON_PAGE(lruvec_memcg(lruvec) != root_mem_cgroup, page);
1185 VM_BUG_ON_PAGE(lruvec_memcg(lruvec) != memcg, page);
1190 * lock_page_lruvec - lock and return lruvec for a given page.
1193 * These functions are safe to use under any of the following conditions:
1196 * - lock_page_memcg()
1197 * - page->_refcount is zero
1199 struct lruvec *lock_page_lruvec(struct page *page)
1201 struct lruvec *lruvec;
1203 lruvec = mem_cgroup_page_lruvec(page);
1204 spin_lock(&lruvec->lru_lock);
1206 lruvec_memcg_debug(lruvec, page);
1211 struct lruvec *lock_page_lruvec_irq(struct page *page)
1213 struct lruvec *lruvec;
1215 lruvec = mem_cgroup_page_lruvec(page);
1216 spin_lock_irq(&lruvec->lru_lock);
1218 lruvec_memcg_debug(lruvec, page);
1223 struct lruvec *lock_page_lruvec_irqsave(struct page *page, unsigned long *flags)
1225 struct lruvec *lruvec;
1227 lruvec = mem_cgroup_page_lruvec(page);
1228 spin_lock_irqsave(&lruvec->lru_lock, *flags);
1230 lruvec_memcg_debug(lruvec, page);
1236 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1237 * @lruvec: mem_cgroup per zone lru vector
1238 * @lru: index of lru list the page is sitting on
1239 * @zid: zone id of the accounted pages
1240 * @nr_pages: positive when adding or negative when removing
1242 * This function must be called under lru_lock, just before a page is added
1243 * to or just after a page is removed from an lru list (that ordering being
1244 * so as to allow it to check that lru_size 0 is consistent with list_empty).
1246 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1247 int zid, int nr_pages)
1249 struct mem_cgroup_per_node *mz;
1250 unsigned long *lru_size;
1253 if (mem_cgroup_disabled())
1256 mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
1257 lru_size = &mz->lru_zone_size[zid][lru];
1260 *lru_size += nr_pages;
1263 if (WARN_ONCE(size < 0,
1264 "%s(%p, %d, %d): lru_size %ld\n",
1265 __func__, lruvec, lru, nr_pages, size)) {
1271 *lru_size += nr_pages;
1275 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1276 * @memcg: the memory cgroup
1278 * Returns the maximum amount of memory @mem can be charged with, in
1281 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1283 unsigned long margin = 0;
1284 unsigned long count;
1285 unsigned long limit;
1287 count = page_counter_read(&memcg->memory);
1288 limit = READ_ONCE(memcg->memory.max);
1290 margin = limit - count;
1292 if (do_memsw_account()) {
1293 count = page_counter_read(&memcg->memsw);
1294 limit = READ_ONCE(memcg->memsw.max);
1296 margin = min(margin, limit - count);
1305 * A routine for checking "mem" is under move_account() or not.
1307 * Checking a cgroup is mc.from or mc.to or under hierarchy of
1308 * moving cgroups. This is for waiting at high-memory pressure
1311 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1313 struct mem_cgroup *from;
1314 struct mem_cgroup *to;
1317 * Unlike task_move routines, we access mc.to, mc.from not under
1318 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1320 spin_lock(&mc.lock);
1326 ret = mem_cgroup_is_descendant(from, memcg) ||
1327 mem_cgroup_is_descendant(to, memcg);
1329 spin_unlock(&mc.lock);
1333 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1335 if (mc.moving_task && current != mc.moving_task) {
1336 if (mem_cgroup_under_move(memcg)) {
1338 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1339 /* moving charge context might have finished. */
1342 finish_wait(&mc.waitq, &wait);
1349 struct memory_stat {
1354 static const struct memory_stat memory_stats[] = {
1355 { "anon", NR_ANON_MAPPED },
1356 { "file", NR_FILE_PAGES },
1357 { "kernel_stack", NR_KERNEL_STACK_KB },
1358 { "pagetables", NR_PAGETABLE },
1359 { "percpu", MEMCG_PERCPU_B },
1360 { "sock", MEMCG_SOCK },
1361 { "shmem", NR_SHMEM },
1362 { "file_mapped", NR_FILE_MAPPED },
1363 { "file_dirty", NR_FILE_DIRTY },
1364 { "file_writeback", NR_WRITEBACK },
1366 { "swapcached", NR_SWAPCACHE },
1368 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1369 { "anon_thp", NR_ANON_THPS },
1370 { "file_thp", NR_FILE_THPS },
1371 { "shmem_thp", NR_SHMEM_THPS },
1373 { "inactive_anon", NR_INACTIVE_ANON },
1374 { "active_anon", NR_ACTIVE_ANON },
1375 { "inactive_file", NR_INACTIVE_FILE },
1376 { "active_file", NR_ACTIVE_FILE },
1377 { "unevictable", NR_UNEVICTABLE },
1378 { "slab_reclaimable", NR_SLAB_RECLAIMABLE_B },
1379 { "slab_unreclaimable", NR_SLAB_UNRECLAIMABLE_B },
1381 /* The memory events */
1382 { "workingset_refault_anon", WORKINGSET_REFAULT_ANON },
1383 { "workingset_refault_file", WORKINGSET_REFAULT_FILE },
1384 { "workingset_activate_anon", WORKINGSET_ACTIVATE_ANON },
1385 { "workingset_activate_file", WORKINGSET_ACTIVATE_FILE },
1386 { "workingset_restore_anon", WORKINGSET_RESTORE_ANON },
1387 { "workingset_restore_file", WORKINGSET_RESTORE_FILE },
1388 { "workingset_nodereclaim", WORKINGSET_NODERECLAIM },
1391 /* Translate stat items to the correct unit for memory.stat output */
1392 static int memcg_page_state_unit(int item)
1395 case MEMCG_PERCPU_B:
1396 case NR_SLAB_RECLAIMABLE_B:
1397 case NR_SLAB_UNRECLAIMABLE_B:
1398 case WORKINGSET_REFAULT_ANON:
1399 case WORKINGSET_REFAULT_FILE:
1400 case WORKINGSET_ACTIVATE_ANON:
1401 case WORKINGSET_ACTIVATE_FILE:
1402 case WORKINGSET_RESTORE_ANON:
1403 case WORKINGSET_RESTORE_FILE:
1404 case WORKINGSET_NODERECLAIM:
1406 case NR_KERNEL_STACK_KB:
1413 static inline unsigned long memcg_page_state_output(struct mem_cgroup *memcg,
1416 return memcg_page_state(memcg, item) * memcg_page_state_unit(item);
1419 static char *memory_stat_format(struct mem_cgroup *memcg)
1424 seq_buf_init(&s, kmalloc(PAGE_SIZE, GFP_KERNEL), PAGE_SIZE);
1429 * Provide statistics on the state of the memory subsystem as
1430 * well as cumulative event counters that show past behavior.
1432 * This list is ordered following a combination of these gradients:
1433 * 1) generic big picture -> specifics and details
1434 * 2) reflecting userspace activity -> reflecting kernel heuristics
1436 * Current memory state:
1438 cgroup_rstat_flush(memcg->css.cgroup);
1440 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
1443 size = memcg_page_state_output(memcg, memory_stats[i].idx);
1444 seq_buf_printf(&s, "%s %llu\n", memory_stats[i].name, size);
1446 if (unlikely(memory_stats[i].idx == NR_SLAB_UNRECLAIMABLE_B)) {
1447 size += memcg_page_state_output(memcg,
1448 NR_SLAB_RECLAIMABLE_B);
1449 seq_buf_printf(&s, "slab %llu\n", size);
1453 /* Accumulated memory events */
1455 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGFAULT),
1456 memcg_events(memcg, PGFAULT));
1457 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGMAJFAULT),
1458 memcg_events(memcg, PGMAJFAULT));
1459 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGREFILL),
1460 memcg_events(memcg, PGREFILL));
1461 seq_buf_printf(&s, "pgscan %lu\n",
1462 memcg_events(memcg, PGSCAN_KSWAPD) +
1463 memcg_events(memcg, PGSCAN_DIRECT));
1464 seq_buf_printf(&s, "pgsteal %lu\n",
1465 memcg_events(memcg, PGSTEAL_KSWAPD) +
1466 memcg_events(memcg, PGSTEAL_DIRECT));
1467 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGACTIVATE),
1468 memcg_events(memcg, PGACTIVATE));
1469 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGDEACTIVATE),
1470 memcg_events(memcg, PGDEACTIVATE));
1471 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGLAZYFREE),
1472 memcg_events(memcg, PGLAZYFREE));
1473 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGLAZYFREED),
1474 memcg_events(memcg, PGLAZYFREED));
1476 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1477 seq_buf_printf(&s, "%s %lu\n", vm_event_name(THP_FAULT_ALLOC),
1478 memcg_events(memcg, THP_FAULT_ALLOC));
1479 seq_buf_printf(&s, "%s %lu\n", vm_event_name(THP_COLLAPSE_ALLOC),
1480 memcg_events(memcg, THP_COLLAPSE_ALLOC));
1481 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
1483 /* The above should easily fit into one page */
1484 WARN_ON_ONCE(seq_buf_has_overflowed(&s));
1489 #define K(x) ((x) << (PAGE_SHIFT-10))
1491 * mem_cgroup_print_oom_context: Print OOM information relevant to
1492 * memory controller.
1493 * @memcg: The memory cgroup that went over limit
1494 * @p: Task that is going to be killed
1496 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1499 void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p)
1504 pr_cont(",oom_memcg=");
1505 pr_cont_cgroup_path(memcg->css.cgroup);
1507 pr_cont(",global_oom");
1509 pr_cont(",task_memcg=");
1510 pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
1516 * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
1517 * memory controller.
1518 * @memcg: The memory cgroup that went over limit
1520 void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
1524 pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1525 K((u64)page_counter_read(&memcg->memory)),
1526 K((u64)READ_ONCE(memcg->memory.max)), memcg->memory.failcnt);
1527 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1528 pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n",
1529 K((u64)page_counter_read(&memcg->swap)),
1530 K((u64)READ_ONCE(memcg->swap.max)), memcg->swap.failcnt);
1532 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1533 K((u64)page_counter_read(&memcg->memsw)),
1534 K((u64)memcg->memsw.max), memcg->memsw.failcnt);
1535 pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1536 K((u64)page_counter_read(&memcg->kmem)),
1537 K((u64)memcg->kmem.max), memcg->kmem.failcnt);
1540 pr_info("Memory cgroup stats for ");
1541 pr_cont_cgroup_path(memcg->css.cgroup);
1543 buf = memory_stat_format(memcg);
1551 * Return the memory (and swap, if configured) limit for a memcg.
1553 unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg)
1555 unsigned long max = READ_ONCE(memcg->memory.max);
1557 if (cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
1558 if (mem_cgroup_swappiness(memcg))
1559 max += min(READ_ONCE(memcg->swap.max),
1560 (unsigned long)total_swap_pages);
1562 if (mem_cgroup_swappiness(memcg)) {
1563 /* Calculate swap excess capacity from memsw limit */
1564 unsigned long swap = READ_ONCE(memcg->memsw.max) - max;
1566 max += min(swap, (unsigned long)total_swap_pages);
1572 unsigned long mem_cgroup_size(struct mem_cgroup *memcg)
1574 return page_counter_read(&memcg->memory);
1577 static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1580 struct oom_control oc = {
1584 .gfp_mask = gfp_mask,
1589 if (mutex_lock_killable(&oom_lock))
1592 if (mem_cgroup_margin(memcg) >= (1 << order))
1596 * A few threads which were not waiting at mutex_lock_killable() can
1597 * fail to bail out. Therefore, check again after holding oom_lock.
1599 ret = should_force_charge() || out_of_memory(&oc);
1602 mutex_unlock(&oom_lock);
1606 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
1609 unsigned long *total_scanned)
1611 struct mem_cgroup *victim = NULL;
1614 unsigned long excess;
1615 unsigned long nr_scanned;
1616 struct mem_cgroup_reclaim_cookie reclaim = {
1620 excess = soft_limit_excess(root_memcg);
1623 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1628 * If we have not been able to reclaim
1629 * anything, it might because there are
1630 * no reclaimable pages under this hierarchy
1635 * We want to do more targeted reclaim.
1636 * excess >> 2 is not to excessive so as to
1637 * reclaim too much, nor too less that we keep
1638 * coming back to reclaim from this cgroup
1640 if (total >= (excess >> 2) ||
1641 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1646 total += mem_cgroup_shrink_node(victim, gfp_mask, false,
1647 pgdat, &nr_scanned);
1648 *total_scanned += nr_scanned;
1649 if (!soft_limit_excess(root_memcg))
1652 mem_cgroup_iter_break(root_memcg, victim);
1656 #ifdef CONFIG_LOCKDEP
1657 static struct lockdep_map memcg_oom_lock_dep_map = {
1658 .name = "memcg_oom_lock",
1662 static DEFINE_SPINLOCK(memcg_oom_lock);
1665 * Check OOM-Killer is already running under our hierarchy.
1666 * If someone is running, return false.
1668 static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
1670 struct mem_cgroup *iter, *failed = NULL;
1672 spin_lock(&memcg_oom_lock);
1674 for_each_mem_cgroup_tree(iter, memcg) {
1675 if (iter->oom_lock) {
1677 * this subtree of our hierarchy is already locked
1678 * so we cannot give a lock.
1681 mem_cgroup_iter_break(memcg, iter);
1684 iter->oom_lock = true;
1689 * OK, we failed to lock the whole subtree so we have
1690 * to clean up what we set up to the failing subtree
1692 for_each_mem_cgroup_tree(iter, memcg) {
1693 if (iter == failed) {
1694 mem_cgroup_iter_break(memcg, iter);
1697 iter->oom_lock = false;
1700 mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
1702 spin_unlock(&memcg_oom_lock);
1707 static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1709 struct mem_cgroup *iter;
1711 spin_lock(&memcg_oom_lock);
1712 mutex_release(&memcg_oom_lock_dep_map, _RET_IP_);
1713 for_each_mem_cgroup_tree(iter, memcg)
1714 iter->oom_lock = false;
1715 spin_unlock(&memcg_oom_lock);
1718 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1720 struct mem_cgroup *iter;
1722 spin_lock(&memcg_oom_lock);
1723 for_each_mem_cgroup_tree(iter, memcg)
1725 spin_unlock(&memcg_oom_lock);
1728 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1730 struct mem_cgroup *iter;
1733 * Be careful about under_oom underflows because a child memcg
1734 * could have been added after mem_cgroup_mark_under_oom.
1736 spin_lock(&memcg_oom_lock);
1737 for_each_mem_cgroup_tree(iter, memcg)
1738 if (iter->under_oom > 0)
1740 spin_unlock(&memcg_oom_lock);
1743 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1745 struct oom_wait_info {
1746 struct mem_cgroup *memcg;
1747 wait_queue_entry_t wait;
1750 static int memcg_oom_wake_function(wait_queue_entry_t *wait,
1751 unsigned mode, int sync, void *arg)
1753 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
1754 struct mem_cgroup *oom_wait_memcg;
1755 struct oom_wait_info *oom_wait_info;
1757 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1758 oom_wait_memcg = oom_wait_info->memcg;
1760 if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
1761 !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
1763 return autoremove_wake_function(wait, mode, sync, arg);
1766 static void memcg_oom_recover(struct mem_cgroup *memcg)
1769 * For the following lockless ->under_oom test, the only required
1770 * guarantee is that it must see the state asserted by an OOM when
1771 * this function is called as a result of userland actions
1772 * triggered by the notification of the OOM. This is trivially
1773 * achieved by invoking mem_cgroup_mark_under_oom() before
1774 * triggering notification.
1776 if (memcg && memcg->under_oom)
1777 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
1787 static enum oom_status mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
1789 enum oom_status ret;
1792 if (order > PAGE_ALLOC_COSTLY_ORDER)
1795 memcg_memory_event(memcg, MEMCG_OOM);
1798 * We are in the middle of the charge context here, so we
1799 * don't want to block when potentially sitting on a callstack
1800 * that holds all kinds of filesystem and mm locks.
1802 * cgroup1 allows disabling the OOM killer and waiting for outside
1803 * handling until the charge can succeed; remember the context and put
1804 * the task to sleep at the end of the page fault when all locks are
1807 * On the other hand, in-kernel OOM killer allows for an async victim
1808 * memory reclaim (oom_reaper) and that means that we are not solely
1809 * relying on the oom victim to make a forward progress and we can
1810 * invoke the oom killer here.
1812 * Please note that mem_cgroup_out_of_memory might fail to find a
1813 * victim and then we have to bail out from the charge path.
1815 if (memcg->oom_kill_disable) {
1816 if (!current->in_user_fault)
1818 css_get(&memcg->css);
1819 current->memcg_in_oom = memcg;
1820 current->memcg_oom_gfp_mask = mask;
1821 current->memcg_oom_order = order;
1826 mem_cgroup_mark_under_oom(memcg);
1828 locked = mem_cgroup_oom_trylock(memcg);
1831 mem_cgroup_oom_notify(memcg);
1833 mem_cgroup_unmark_under_oom(memcg);
1834 if (mem_cgroup_out_of_memory(memcg, mask, order))
1840 mem_cgroup_oom_unlock(memcg);
1846 * mem_cgroup_oom_synchronize - complete memcg OOM handling
1847 * @handle: actually kill/wait or just clean up the OOM state
1849 * This has to be called at the end of a page fault if the memcg OOM
1850 * handler was enabled.
1852 * Memcg supports userspace OOM handling where failed allocations must
1853 * sleep on a waitqueue until the userspace task resolves the
1854 * situation. Sleeping directly in the charge context with all kinds
1855 * of locks held is not a good idea, instead we remember an OOM state
1856 * in the task and mem_cgroup_oom_synchronize() has to be called at
1857 * the end of the page fault to complete the OOM handling.
1859 * Returns %true if an ongoing memcg OOM situation was detected and
1860 * completed, %false otherwise.
1862 bool mem_cgroup_oom_synchronize(bool handle)
1864 struct mem_cgroup *memcg = current->memcg_in_oom;
1865 struct oom_wait_info owait;
1868 /* OOM is global, do not handle */
1875 owait.memcg = memcg;
1876 owait.wait.flags = 0;
1877 owait.wait.func = memcg_oom_wake_function;
1878 owait.wait.private = current;
1879 INIT_LIST_HEAD(&owait.wait.entry);
1881 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
1882 mem_cgroup_mark_under_oom(memcg);
1884 locked = mem_cgroup_oom_trylock(memcg);
1887 mem_cgroup_oom_notify(memcg);
1889 if (locked && !memcg->oom_kill_disable) {
1890 mem_cgroup_unmark_under_oom(memcg);
1891 finish_wait(&memcg_oom_waitq, &owait.wait);
1892 mem_cgroup_out_of_memory(memcg, current->memcg_oom_gfp_mask,
1893 current->memcg_oom_order);
1896 mem_cgroup_unmark_under_oom(memcg);
1897 finish_wait(&memcg_oom_waitq, &owait.wait);
1901 mem_cgroup_oom_unlock(memcg);
1903 * There is no guarantee that an OOM-lock contender
1904 * sees the wakeups triggered by the OOM kill
1905 * uncharges. Wake any sleepers explicitly.
1907 memcg_oom_recover(memcg);
1910 current->memcg_in_oom = NULL;
1911 css_put(&memcg->css);
1916 * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
1917 * @victim: task to be killed by the OOM killer
1918 * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
1920 * Returns a pointer to a memory cgroup, which has to be cleaned up
1921 * by killing all belonging OOM-killable tasks.
1923 * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
1925 struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim,
1926 struct mem_cgroup *oom_domain)
1928 struct mem_cgroup *oom_group = NULL;
1929 struct mem_cgroup *memcg;
1931 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
1935 oom_domain = root_mem_cgroup;
1939 memcg = mem_cgroup_from_task(victim);
1940 if (memcg == root_mem_cgroup)
1944 * If the victim task has been asynchronously moved to a different
1945 * memory cgroup, we might end up killing tasks outside oom_domain.
1946 * In this case it's better to ignore memory.group.oom.
1948 if (unlikely(!mem_cgroup_is_descendant(memcg, oom_domain)))
1952 * Traverse the memory cgroup hierarchy from the victim task's
1953 * cgroup up to the OOMing cgroup (or root) to find the
1954 * highest-level memory cgroup with oom.group set.
1956 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
1957 if (memcg->oom_group)
1960 if (memcg == oom_domain)
1965 css_get(&oom_group->css);
1972 void mem_cgroup_print_oom_group(struct mem_cgroup *memcg)
1974 pr_info("Tasks in ");
1975 pr_cont_cgroup_path(memcg->css.cgroup);
1976 pr_cont(" are going to be killed due to memory.oom.group set\n");
1980 * lock_page_memcg - lock a page and memcg binding
1983 * This function protects unlocked LRU pages from being moved to
1986 * It ensures lifetime of the locked memcg. Caller is responsible
1987 * for the lifetime of the page.
1989 void lock_page_memcg(struct page *page)
1991 struct page *head = compound_head(page); /* rmap on tail pages */
1992 struct mem_cgroup *memcg;
1993 unsigned long flags;
1996 * The RCU lock is held throughout the transaction. The fast
1997 * path can get away without acquiring the memcg->move_lock
1998 * because page moving starts with an RCU grace period.
2002 if (mem_cgroup_disabled())
2005 memcg = page_memcg(head);
2006 if (unlikely(!memcg))
2009 #ifdef CONFIG_PROVE_LOCKING
2010 local_irq_save(flags);
2011 might_lock(&memcg->move_lock);
2012 local_irq_restore(flags);
2015 if (atomic_read(&memcg->moving_account) <= 0)
2018 spin_lock_irqsave(&memcg->move_lock, flags);
2019 if (memcg != page_memcg(head)) {
2020 spin_unlock_irqrestore(&memcg->move_lock, flags);
2025 * When charge migration first begins, we can have multiple
2026 * critical sections holding the fast-path RCU lock and one
2027 * holding the slowpath move_lock. Track the task who has the
2028 * move_lock for unlock_page_memcg().
2030 memcg->move_lock_task = current;
2031 memcg->move_lock_flags = flags;
2033 EXPORT_SYMBOL(lock_page_memcg);
2035 static void __unlock_page_memcg(struct mem_cgroup *memcg)
2037 if (memcg && memcg->move_lock_task == current) {
2038 unsigned long flags = memcg->move_lock_flags;
2040 memcg->move_lock_task = NULL;
2041 memcg->move_lock_flags = 0;
2043 spin_unlock_irqrestore(&memcg->move_lock, flags);
2050 * unlock_page_memcg - unlock a page and memcg binding
2053 void unlock_page_memcg(struct page *page)
2055 struct page *head = compound_head(page);
2057 __unlock_page_memcg(page_memcg(head));
2059 EXPORT_SYMBOL(unlock_page_memcg);
2062 #ifdef CONFIG_MEMCG_KMEM
2063 struct obj_cgroup *cached_objcg;
2064 struct pglist_data *cached_pgdat;
2065 unsigned int nr_bytes;
2066 int nr_slab_reclaimable_b;
2067 int nr_slab_unreclaimable_b;
2073 struct memcg_stock_pcp {
2074 struct mem_cgroup *cached; /* this never be root cgroup */
2075 unsigned int nr_pages;
2076 struct obj_stock task_obj;
2077 struct obj_stock irq_obj;
2079 struct work_struct work;
2080 unsigned long flags;
2081 #define FLUSHING_CACHED_CHARGE 0
2083 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
2084 static DEFINE_MUTEX(percpu_charge_mutex);
2086 #ifdef CONFIG_MEMCG_KMEM
2087 static void drain_obj_stock(struct obj_stock *stock);
2088 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2089 struct mem_cgroup *root_memcg);
2092 static inline void drain_obj_stock(struct obj_stock *stock)
2095 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2096 struct mem_cgroup *root_memcg)
2103 * Most kmem_cache_alloc() calls are from user context. The irq disable/enable
2104 * sequence used in this case to access content from object stock is slow.
2105 * To optimize for user context access, there are now two object stocks for
2106 * task context and interrupt context access respectively.
2108 * The task context object stock can be accessed by disabling preemption only
2109 * which is cheap in non-preempt kernel. The interrupt context object stock
2110 * can only be accessed after disabling interrupt. User context code can
2111 * access interrupt object stock, but not vice versa.
2113 static inline struct obj_stock *get_obj_stock(unsigned long *pflags)
2115 struct memcg_stock_pcp *stock;
2117 if (likely(in_task())) {
2120 stock = this_cpu_ptr(&memcg_stock);
2121 return &stock->task_obj;
2124 local_irq_save(*pflags);
2125 stock = this_cpu_ptr(&memcg_stock);
2126 return &stock->irq_obj;
2129 static inline void put_obj_stock(unsigned long flags)
2131 if (likely(in_task()))
2134 local_irq_restore(flags);
2138 * consume_stock: Try to consume stocked charge on this cpu.
2139 * @memcg: memcg to consume from.
2140 * @nr_pages: how many pages to charge.
2142 * The charges will only happen if @memcg matches the current cpu's memcg
2143 * stock, and at least @nr_pages are available in that stock. Failure to
2144 * service an allocation will refill the stock.
2146 * returns true if successful, false otherwise.
2148 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2150 struct memcg_stock_pcp *stock;
2151 unsigned long flags;
2154 if (nr_pages > MEMCG_CHARGE_BATCH)
2157 local_irq_save(flags);
2159 stock = this_cpu_ptr(&memcg_stock);
2160 if (memcg == stock->cached && stock->nr_pages >= nr_pages) {
2161 stock->nr_pages -= nr_pages;
2165 local_irq_restore(flags);
2171 * Returns stocks cached in percpu and reset cached information.
2173 static void drain_stock(struct memcg_stock_pcp *stock)
2175 struct mem_cgroup *old = stock->cached;
2180 if (stock->nr_pages) {
2181 page_counter_uncharge(&old->memory, stock->nr_pages);
2182 if (do_memsw_account())
2183 page_counter_uncharge(&old->memsw, stock->nr_pages);
2184 stock->nr_pages = 0;
2188 stock->cached = NULL;
2191 static void drain_local_stock(struct work_struct *dummy)
2193 struct memcg_stock_pcp *stock;
2194 unsigned long flags;
2197 * The only protection from memory hotplug vs. drain_stock races is
2198 * that we always operate on local CPU stock here with IRQ disabled
2200 local_irq_save(flags);
2202 stock = this_cpu_ptr(&memcg_stock);
2203 drain_obj_stock(&stock->irq_obj);
2205 drain_obj_stock(&stock->task_obj);
2207 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2209 local_irq_restore(flags);
2213 * Cache charges(val) to local per_cpu area.
2214 * This will be consumed by consume_stock() function, later.
2216 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2218 struct memcg_stock_pcp *stock;
2219 unsigned long flags;
2221 local_irq_save(flags);
2223 stock = this_cpu_ptr(&memcg_stock);
2224 if (stock->cached != memcg) { /* reset if necessary */
2226 css_get(&memcg->css);
2227 stock->cached = memcg;
2229 stock->nr_pages += nr_pages;
2231 if (stock->nr_pages > MEMCG_CHARGE_BATCH)
2234 local_irq_restore(flags);
2238 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2239 * of the hierarchy under it.
2241 static void drain_all_stock(struct mem_cgroup *root_memcg)
2245 /* If someone's already draining, avoid adding running more workers. */
2246 if (!mutex_trylock(&percpu_charge_mutex))
2249 * Notify other cpus that system-wide "drain" is running
2250 * We do not care about races with the cpu hotplug because cpu down
2251 * as well as workers from this path always operate on the local
2252 * per-cpu data. CPU up doesn't touch memcg_stock at all.
2255 for_each_online_cpu(cpu) {
2256 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2257 struct mem_cgroup *memcg;
2261 memcg = stock->cached;
2262 if (memcg && stock->nr_pages &&
2263 mem_cgroup_is_descendant(memcg, root_memcg))
2265 if (obj_stock_flush_required(stock, root_memcg))
2270 !test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2272 drain_local_stock(&stock->work);
2274 schedule_work_on(cpu, &stock->work);
2278 mutex_unlock(&percpu_charge_mutex);
2281 static void memcg_flush_lruvec_page_state(struct mem_cgroup *memcg, int cpu)
2285 for_each_node(nid) {
2286 struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
2287 unsigned long stat[NR_VM_NODE_STAT_ITEMS];
2288 struct batched_lruvec_stat *lstatc;
2291 lstatc = per_cpu_ptr(pn->lruvec_stat_cpu, cpu);
2292 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++) {
2293 stat[i] = lstatc->count[i];
2294 lstatc->count[i] = 0;
2298 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++)
2299 atomic_long_add(stat[i], &pn->lruvec_stat[i]);
2300 } while ((pn = parent_nodeinfo(pn, nid)));
2304 static int memcg_hotplug_cpu_dead(unsigned int cpu)
2306 struct memcg_stock_pcp *stock;
2307 struct mem_cgroup *memcg;
2309 stock = &per_cpu(memcg_stock, cpu);
2312 for_each_mem_cgroup(memcg)
2313 memcg_flush_lruvec_page_state(memcg, cpu);
2318 static unsigned long reclaim_high(struct mem_cgroup *memcg,
2319 unsigned int nr_pages,
2322 unsigned long nr_reclaimed = 0;
2325 unsigned long pflags;
2327 if (page_counter_read(&memcg->memory) <=
2328 READ_ONCE(memcg->memory.high))
2331 memcg_memory_event(memcg, MEMCG_HIGH);
2333 psi_memstall_enter(&pflags);
2334 nr_reclaimed += try_to_free_mem_cgroup_pages(memcg, nr_pages,
2336 psi_memstall_leave(&pflags);
2337 } while ((memcg = parent_mem_cgroup(memcg)) &&
2338 !mem_cgroup_is_root(memcg));
2340 return nr_reclaimed;
2343 static void high_work_func(struct work_struct *work)
2345 struct mem_cgroup *memcg;
2347 memcg = container_of(work, struct mem_cgroup, high_work);
2348 reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
2352 * Clamp the maximum sleep time per allocation batch to 2 seconds. This is
2353 * enough to still cause a significant slowdown in most cases, while still
2354 * allowing diagnostics and tracing to proceed without becoming stuck.
2356 #define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ)
2359 * When calculating the delay, we use these either side of the exponentiation to
2360 * maintain precision and scale to a reasonable number of jiffies (see the table
2363 * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the
2364 * overage ratio to a delay.
2365 * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down the
2366 * proposed penalty in order to reduce to a reasonable number of jiffies, and
2367 * to produce a reasonable delay curve.
2369 * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a
2370 * reasonable delay curve compared to precision-adjusted overage, not
2371 * penalising heavily at first, but still making sure that growth beyond the
2372 * limit penalises misbehaviour cgroups by slowing them down exponentially. For
2373 * example, with a high of 100 megabytes:
2375 * +-------+------------------------+
2376 * | usage | time to allocate in ms |
2377 * +-------+------------------------+
2399 * +-------+------------------------+
2401 #define MEMCG_DELAY_PRECISION_SHIFT 20
2402 #define MEMCG_DELAY_SCALING_SHIFT 14
2404 static u64 calculate_overage(unsigned long usage, unsigned long high)
2412 * Prevent division by 0 in overage calculation by acting as if
2413 * it was a threshold of 1 page
2415 high = max(high, 1UL);
2417 overage = usage - high;
2418 overage <<= MEMCG_DELAY_PRECISION_SHIFT;
2419 return div64_u64(overage, high);
2422 static u64 mem_find_max_overage(struct mem_cgroup *memcg)
2424 u64 overage, max_overage = 0;
2427 overage = calculate_overage(page_counter_read(&memcg->memory),
2428 READ_ONCE(memcg->memory.high));
2429 max_overage = max(overage, max_overage);
2430 } while ((memcg = parent_mem_cgroup(memcg)) &&
2431 !mem_cgroup_is_root(memcg));
2436 static u64 swap_find_max_overage(struct mem_cgroup *memcg)
2438 u64 overage, max_overage = 0;
2441 overage = calculate_overage(page_counter_read(&memcg->swap),
2442 READ_ONCE(memcg->swap.high));
2444 memcg_memory_event(memcg, MEMCG_SWAP_HIGH);
2445 max_overage = max(overage, max_overage);
2446 } while ((memcg = parent_mem_cgroup(memcg)) &&
2447 !mem_cgroup_is_root(memcg));
2453 * Get the number of jiffies that we should penalise a mischievous cgroup which
2454 * is exceeding its memory.high by checking both it and its ancestors.
2456 static unsigned long calculate_high_delay(struct mem_cgroup *memcg,
2457 unsigned int nr_pages,
2460 unsigned long penalty_jiffies;
2466 * We use overage compared to memory.high to calculate the number of
2467 * jiffies to sleep (penalty_jiffies). Ideally this value should be
2468 * fairly lenient on small overages, and increasingly harsh when the
2469 * memcg in question makes it clear that it has no intention of stopping
2470 * its crazy behaviour, so we exponentially increase the delay based on
2473 penalty_jiffies = max_overage * max_overage * HZ;
2474 penalty_jiffies >>= MEMCG_DELAY_PRECISION_SHIFT;
2475 penalty_jiffies >>= MEMCG_DELAY_SCALING_SHIFT;
2478 * Factor in the task's own contribution to the overage, such that four
2479 * N-sized allocations are throttled approximately the same as one
2480 * 4N-sized allocation.
2482 * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or
2483 * larger the current charge patch is than that.
2485 return penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH;
2489 * Scheduled by try_charge() to be executed from the userland return path
2490 * and reclaims memory over the high limit.
2492 void mem_cgroup_handle_over_high(void)
2494 unsigned long penalty_jiffies;
2495 unsigned long pflags;
2496 unsigned long nr_reclaimed;
2497 unsigned int nr_pages = current->memcg_nr_pages_over_high;
2498 int nr_retries = MAX_RECLAIM_RETRIES;
2499 struct mem_cgroup *memcg;
2500 bool in_retry = false;
2502 if (likely(!nr_pages))
2505 memcg = get_mem_cgroup_from_mm(current->mm);
2506 current->memcg_nr_pages_over_high = 0;
2510 * The allocating task should reclaim at least the batch size, but for
2511 * subsequent retries we only want to do what's necessary to prevent oom
2512 * or breaching resource isolation.
2514 * This is distinct from memory.max or page allocator behaviour because
2515 * memory.high is currently batched, whereas memory.max and the page
2516 * allocator run every time an allocation is made.
2518 nr_reclaimed = reclaim_high(memcg,
2519 in_retry ? SWAP_CLUSTER_MAX : nr_pages,
2523 * memory.high is breached and reclaim is unable to keep up. Throttle
2524 * allocators proactively to slow down excessive growth.
2526 penalty_jiffies = calculate_high_delay(memcg, nr_pages,
2527 mem_find_max_overage(memcg));
2529 penalty_jiffies += calculate_high_delay(memcg, nr_pages,
2530 swap_find_max_overage(memcg));
2533 * Clamp the max delay per usermode return so as to still keep the
2534 * application moving forwards and also permit diagnostics, albeit
2537 penalty_jiffies = min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES);
2540 * Don't sleep if the amount of jiffies this memcg owes us is so low
2541 * that it's not even worth doing, in an attempt to be nice to those who
2542 * go only a small amount over their memory.high value and maybe haven't
2543 * been aggressively reclaimed enough yet.
2545 if (penalty_jiffies <= HZ / 100)
2549 * If reclaim is making forward progress but we're still over
2550 * memory.high, we want to encourage that rather than doing allocator
2553 if (nr_reclaimed || nr_retries--) {
2559 * If we exit early, we're guaranteed to die (since
2560 * schedule_timeout_killable sets TASK_KILLABLE). This means we don't
2561 * need to account for any ill-begotten jiffies to pay them off later.
2563 psi_memstall_enter(&pflags);
2564 schedule_timeout_killable(penalty_jiffies);
2565 psi_memstall_leave(&pflags);
2568 css_put(&memcg->css);
2571 static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask,
2572 unsigned int nr_pages)
2574 unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
2575 int nr_retries = MAX_RECLAIM_RETRIES;
2576 struct mem_cgroup *mem_over_limit;
2577 struct page_counter *counter;
2578 enum oom_status oom_status;
2579 unsigned long nr_reclaimed;
2580 bool may_swap = true;
2581 bool drained = false;
2582 unsigned long pflags;
2585 if (consume_stock(memcg, nr_pages))
2588 if (!do_memsw_account() ||
2589 page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2590 if (page_counter_try_charge(&memcg->memory, batch, &counter))
2592 if (do_memsw_account())
2593 page_counter_uncharge(&memcg->memsw, batch);
2594 mem_over_limit = mem_cgroup_from_counter(counter, memory);
2596 mem_over_limit = mem_cgroup_from_counter(counter, memsw);
2600 if (batch > nr_pages) {
2606 * Memcg doesn't have a dedicated reserve for atomic
2607 * allocations. But like the global atomic pool, we need to
2608 * put the burden of reclaim on regular allocation requests
2609 * and let these go through as privileged allocations.
2611 if (gfp_mask & __GFP_ATOMIC)
2615 * Unlike in global OOM situations, memcg is not in a physical
2616 * memory shortage. Allow dying and OOM-killed tasks to
2617 * bypass the last charges so that they can exit quickly and
2618 * free their memory.
2620 if (unlikely(should_force_charge()))
2624 * Prevent unbounded recursion when reclaim operations need to
2625 * allocate memory. This might exceed the limits temporarily,
2626 * but we prefer facilitating memory reclaim and getting back
2627 * under the limit over triggering OOM kills in these cases.
2629 if (unlikely(current->flags & PF_MEMALLOC))
2632 if (unlikely(task_in_memcg_oom(current)))
2635 if (!gfpflags_allow_blocking(gfp_mask))
2638 memcg_memory_event(mem_over_limit, MEMCG_MAX);
2640 psi_memstall_enter(&pflags);
2641 nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
2642 gfp_mask, may_swap);
2643 psi_memstall_leave(&pflags);
2645 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2649 drain_all_stock(mem_over_limit);
2654 if (gfp_mask & __GFP_NORETRY)
2657 * Even though the limit is exceeded at this point, reclaim
2658 * may have been able to free some pages. Retry the charge
2659 * before killing the task.
2661 * Only for regular pages, though: huge pages are rather
2662 * unlikely to succeed so close to the limit, and we fall back
2663 * to regular pages anyway in case of failure.
2665 if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
2668 * At task move, charge accounts can be doubly counted. So, it's
2669 * better to wait until the end of task_move if something is going on.
2671 if (mem_cgroup_wait_acct_move(mem_over_limit))
2677 if (gfp_mask & __GFP_RETRY_MAYFAIL)
2680 if (fatal_signal_pending(current))
2684 * keep retrying as long as the memcg oom killer is able to make
2685 * a forward progress or bypass the charge if the oom killer
2686 * couldn't make any progress.
2688 oom_status = mem_cgroup_oom(mem_over_limit, gfp_mask,
2689 get_order(nr_pages * PAGE_SIZE));
2690 switch (oom_status) {
2692 nr_retries = MAX_RECLAIM_RETRIES;
2700 if (!(gfp_mask & __GFP_NOFAIL))
2704 * The allocation either can't fail or will lead to more memory
2705 * being freed very soon. Allow memory usage go over the limit
2706 * temporarily by force charging it.
2708 page_counter_charge(&memcg->memory, nr_pages);
2709 if (do_memsw_account())
2710 page_counter_charge(&memcg->memsw, nr_pages);
2715 if (batch > nr_pages)
2716 refill_stock(memcg, batch - nr_pages);
2719 * If the hierarchy is above the normal consumption range, schedule
2720 * reclaim on returning to userland. We can perform reclaim here
2721 * if __GFP_RECLAIM but let's always punt for simplicity and so that
2722 * GFP_KERNEL can consistently be used during reclaim. @memcg is
2723 * not recorded as it most likely matches current's and won't
2724 * change in the meantime. As high limit is checked again before
2725 * reclaim, the cost of mismatch is negligible.
2728 bool mem_high, swap_high;
2730 mem_high = page_counter_read(&memcg->memory) >
2731 READ_ONCE(memcg->memory.high);
2732 swap_high = page_counter_read(&memcg->swap) >
2733 READ_ONCE(memcg->swap.high);
2735 /* Don't bother a random interrupted task */
2736 if (in_interrupt()) {
2738 schedule_work(&memcg->high_work);
2744 if (mem_high || swap_high) {
2746 * The allocating tasks in this cgroup will need to do
2747 * reclaim or be throttled to prevent further growth
2748 * of the memory or swap footprints.
2750 * Target some best-effort fairness between the tasks,
2751 * and distribute reclaim work and delay penalties
2752 * based on how much each task is actually allocating.
2754 current->memcg_nr_pages_over_high += batch;
2755 set_notify_resume(current);
2758 } while ((memcg = parent_mem_cgroup(memcg)));
2763 static inline int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2764 unsigned int nr_pages)
2766 if (mem_cgroup_is_root(memcg))
2769 return try_charge_memcg(memcg, gfp_mask, nr_pages);
2772 #if defined(CONFIG_MEMCG_KMEM) || defined(CONFIG_MMU)
2773 static void cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
2775 if (mem_cgroup_is_root(memcg))
2778 page_counter_uncharge(&memcg->memory, nr_pages);
2779 if (do_memsw_account())
2780 page_counter_uncharge(&memcg->memsw, nr_pages);
2784 static void commit_charge(struct page *page, struct mem_cgroup *memcg)
2786 VM_BUG_ON_PAGE(page_memcg(page), page);
2788 * Any of the following ensures page's memcg stability:
2792 * - lock_page_memcg()
2793 * - exclusive reference
2795 page->memcg_data = (unsigned long)memcg;
2798 static struct mem_cgroup *get_mem_cgroup_from_objcg(struct obj_cgroup *objcg)
2800 struct mem_cgroup *memcg;
2804 memcg = obj_cgroup_memcg(objcg);
2805 if (unlikely(!css_tryget(&memcg->css)))
2812 #ifdef CONFIG_MEMCG_KMEM
2814 * The allocated objcg pointers array is not accounted directly.
2815 * Moreover, it should not come from DMA buffer and is not readily
2816 * reclaimable. So those GFP bits should be masked off.
2818 #define OBJCGS_CLEAR_MASK (__GFP_DMA | __GFP_RECLAIMABLE | __GFP_ACCOUNT)
2820 int memcg_alloc_page_obj_cgroups(struct page *page, struct kmem_cache *s,
2821 gfp_t gfp, bool new_page)
2823 unsigned int objects = objs_per_slab_page(s, page);
2824 unsigned long memcg_data;
2827 gfp &= ~OBJCGS_CLEAR_MASK;
2828 vec = kcalloc_node(objects, sizeof(struct obj_cgroup *), gfp,
2833 memcg_data = (unsigned long) vec | MEMCG_DATA_OBJCGS;
2836 * If the slab page is brand new and nobody can yet access
2837 * it's memcg_data, no synchronization is required and
2838 * memcg_data can be simply assigned.
2840 page->memcg_data = memcg_data;
2841 } else if (cmpxchg(&page->memcg_data, 0, memcg_data)) {
2843 * If the slab page is already in use, somebody can allocate
2844 * and assign obj_cgroups in parallel. In this case the existing
2845 * objcg vector should be reused.
2851 kmemleak_not_leak(vec);
2856 * Returns a pointer to the memory cgroup to which the kernel object is charged.
2858 * A passed kernel object can be a slab object or a generic kernel page, so
2859 * different mechanisms for getting the memory cgroup pointer should be used.
2860 * In certain cases (e.g. kernel stacks or large kmallocs with SLUB) the caller
2861 * can not know for sure how the kernel object is implemented.
2862 * mem_cgroup_from_obj() can be safely used in such cases.
2864 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
2865 * cgroup_mutex, etc.
2867 struct mem_cgroup *mem_cgroup_from_obj(void *p)
2871 if (mem_cgroup_disabled())
2874 page = virt_to_head_page(p);
2877 * Slab objects are accounted individually, not per-page.
2878 * Memcg membership data for each individual object is saved in
2879 * the page->obj_cgroups.
2881 if (page_objcgs_check(page)) {
2882 struct obj_cgroup *objcg;
2885 off = obj_to_index(page->slab_cache, page, p);
2886 objcg = page_objcgs(page)[off];
2888 return obj_cgroup_memcg(objcg);
2894 * page_memcg_check() is used here, because page_has_obj_cgroups()
2895 * check above could fail because the object cgroups vector wasn't set
2896 * at that moment, but it can be set concurrently.
2897 * page_memcg_check(page) will guarantee that a proper memory
2898 * cgroup pointer or NULL will be returned.
2900 return page_memcg_check(page);
2903 __always_inline struct obj_cgroup *get_obj_cgroup_from_current(void)
2905 struct obj_cgroup *objcg = NULL;
2906 struct mem_cgroup *memcg;
2908 if (memcg_kmem_bypass())
2912 if (unlikely(active_memcg()))
2913 memcg = active_memcg();
2915 memcg = mem_cgroup_from_task(current);
2917 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg)) {
2918 objcg = rcu_dereference(memcg->objcg);
2919 if (objcg && obj_cgroup_tryget(objcg))
2928 static int memcg_alloc_cache_id(void)
2933 id = ida_simple_get(&memcg_cache_ida,
2934 0, MEMCG_CACHES_MAX_SIZE, GFP_KERNEL);
2938 if (id < memcg_nr_cache_ids)
2942 * There's no space for the new id in memcg_caches arrays,
2943 * so we have to grow them.
2945 down_write(&memcg_cache_ids_sem);
2947 size = 2 * (id + 1);
2948 if (size < MEMCG_CACHES_MIN_SIZE)
2949 size = MEMCG_CACHES_MIN_SIZE;
2950 else if (size > MEMCG_CACHES_MAX_SIZE)
2951 size = MEMCG_CACHES_MAX_SIZE;
2953 err = memcg_update_all_list_lrus(size);
2955 memcg_nr_cache_ids = size;
2957 up_write(&memcg_cache_ids_sem);
2960 ida_simple_remove(&memcg_cache_ida, id);
2966 static void memcg_free_cache_id(int id)
2968 ida_simple_remove(&memcg_cache_ida, id);
2972 * obj_cgroup_uncharge_pages: uncharge a number of kernel pages from a objcg
2973 * @objcg: object cgroup to uncharge
2974 * @nr_pages: number of pages to uncharge
2976 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
2977 unsigned int nr_pages)
2979 struct mem_cgroup *memcg;
2981 memcg = get_mem_cgroup_from_objcg(objcg);
2983 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
2984 page_counter_uncharge(&memcg->kmem, nr_pages);
2985 refill_stock(memcg, nr_pages);
2987 css_put(&memcg->css);
2991 * obj_cgroup_charge_pages: charge a number of kernel pages to a objcg
2992 * @objcg: object cgroup to charge
2993 * @gfp: reclaim mode
2994 * @nr_pages: number of pages to charge
2996 * Returns 0 on success, an error code on failure.
2998 static int obj_cgroup_charge_pages(struct obj_cgroup *objcg, gfp_t gfp,
2999 unsigned int nr_pages)
3001 struct page_counter *counter;
3002 struct mem_cgroup *memcg;
3005 memcg = get_mem_cgroup_from_objcg(objcg);
3007 ret = try_charge_memcg(memcg, gfp, nr_pages);
3011 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) &&
3012 !page_counter_try_charge(&memcg->kmem, nr_pages, &counter)) {
3015 * Enforce __GFP_NOFAIL allocation because callers are not
3016 * prepared to see failures and likely do not have any failure
3019 if (gfp & __GFP_NOFAIL) {
3020 page_counter_charge(&memcg->kmem, nr_pages);
3023 cancel_charge(memcg, nr_pages);
3027 css_put(&memcg->css);
3033 * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup
3034 * @page: page to charge
3035 * @gfp: reclaim mode
3036 * @order: allocation order
3038 * Returns 0 on success, an error code on failure.
3040 int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
3042 struct obj_cgroup *objcg;
3045 objcg = get_obj_cgroup_from_current();
3047 ret = obj_cgroup_charge_pages(objcg, gfp, 1 << order);
3049 page->memcg_data = (unsigned long)objcg |
3053 obj_cgroup_put(objcg);
3059 * __memcg_kmem_uncharge_page: uncharge a kmem page
3060 * @page: page to uncharge
3061 * @order: allocation order
3063 void __memcg_kmem_uncharge_page(struct page *page, int order)
3065 struct obj_cgroup *objcg;
3066 unsigned int nr_pages = 1 << order;
3068 if (!PageMemcgKmem(page))
3071 objcg = __page_objcg(page);
3072 obj_cgroup_uncharge_pages(objcg, nr_pages);
3073 page->memcg_data = 0;
3074 obj_cgroup_put(objcg);
3077 void mod_objcg_state(struct obj_cgroup *objcg, struct pglist_data *pgdat,
3078 enum node_stat_item idx, int nr)
3080 unsigned long flags;
3081 struct obj_stock *stock = get_obj_stock(&flags);
3085 * Save vmstat data in stock and skip vmstat array update unless
3086 * accumulating over a page of vmstat data or when pgdat or idx
3089 if (stock->cached_objcg != objcg) {
3090 drain_obj_stock(stock);
3091 obj_cgroup_get(objcg);
3092 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3093 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3094 stock->cached_objcg = objcg;
3095 stock->cached_pgdat = pgdat;
3096 } else if (stock->cached_pgdat != pgdat) {
3097 /* Flush the existing cached vmstat data */
3098 struct pglist_data *oldpg = stock->cached_pgdat;
3100 if (stock->nr_slab_reclaimable_b) {
3101 mod_objcg_mlstate(objcg, oldpg, NR_SLAB_RECLAIMABLE_B,
3102 stock->nr_slab_reclaimable_b);
3103 stock->nr_slab_reclaimable_b = 0;
3105 if (stock->nr_slab_unreclaimable_b) {
3106 mod_objcg_mlstate(objcg, oldpg, NR_SLAB_UNRECLAIMABLE_B,
3107 stock->nr_slab_unreclaimable_b);
3108 stock->nr_slab_unreclaimable_b = 0;
3110 stock->cached_pgdat = pgdat;
3113 bytes = (idx == NR_SLAB_RECLAIMABLE_B) ? &stock->nr_slab_reclaimable_b
3114 : &stock->nr_slab_unreclaimable_b;
3116 * Even for large object >= PAGE_SIZE, the vmstat data will still be
3117 * cached locally at least once before pushing it out.
3124 if (abs(*bytes) > PAGE_SIZE) {
3132 mod_objcg_mlstate(objcg, pgdat, idx, nr);
3134 put_obj_stock(flags);
3137 static bool consume_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes)
3139 unsigned long flags;
3140 struct obj_stock *stock = get_obj_stock(&flags);
3143 if (objcg == stock->cached_objcg && stock->nr_bytes >= nr_bytes) {
3144 stock->nr_bytes -= nr_bytes;
3148 put_obj_stock(flags);
3153 static void drain_obj_stock(struct obj_stock *stock)
3155 struct obj_cgroup *old = stock->cached_objcg;
3160 if (stock->nr_bytes) {
3161 unsigned int nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3162 unsigned int nr_bytes = stock->nr_bytes & (PAGE_SIZE - 1);
3165 obj_cgroup_uncharge_pages(old, nr_pages);
3168 * The leftover is flushed to the centralized per-memcg value.
3169 * On the next attempt to refill obj stock it will be moved
3170 * to a per-cpu stock (probably, on an other CPU), see
3171 * refill_obj_stock().
3173 * How often it's flushed is a trade-off between the memory
3174 * limit enforcement accuracy and potential CPU contention,
3175 * so it might be changed in the future.
3177 atomic_add(nr_bytes, &old->nr_charged_bytes);
3178 stock->nr_bytes = 0;
3182 * Flush the vmstat data in current stock
3184 if (stock->nr_slab_reclaimable_b || stock->nr_slab_unreclaimable_b) {
3185 if (stock->nr_slab_reclaimable_b) {
3186 mod_objcg_mlstate(old, stock->cached_pgdat,
3187 NR_SLAB_RECLAIMABLE_B,
3188 stock->nr_slab_reclaimable_b);
3189 stock->nr_slab_reclaimable_b = 0;
3191 if (stock->nr_slab_unreclaimable_b) {
3192 mod_objcg_mlstate(old, stock->cached_pgdat,
3193 NR_SLAB_UNRECLAIMABLE_B,
3194 stock->nr_slab_unreclaimable_b);
3195 stock->nr_slab_unreclaimable_b = 0;
3197 stock->cached_pgdat = NULL;
3200 obj_cgroup_put(old);
3201 stock->cached_objcg = NULL;
3204 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
3205 struct mem_cgroup *root_memcg)
3207 struct mem_cgroup *memcg;
3209 if (in_task() && stock->task_obj.cached_objcg) {
3210 memcg = obj_cgroup_memcg(stock->task_obj.cached_objcg);
3211 if (memcg && mem_cgroup_is_descendant(memcg, root_memcg))
3214 if (stock->irq_obj.cached_objcg) {
3215 memcg = obj_cgroup_memcg(stock->irq_obj.cached_objcg);
3216 if (memcg && mem_cgroup_is_descendant(memcg, root_memcg))
3223 static void refill_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes,
3224 bool allow_uncharge)
3226 unsigned long flags;
3227 struct obj_stock *stock = get_obj_stock(&flags);
3228 unsigned int nr_pages = 0;
3230 if (stock->cached_objcg != objcg) { /* reset if necessary */
3231 drain_obj_stock(stock);
3232 obj_cgroup_get(objcg);
3233 stock->cached_objcg = objcg;
3234 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3235 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3236 allow_uncharge = true; /* Allow uncharge when objcg changes */
3238 stock->nr_bytes += nr_bytes;
3240 if (allow_uncharge && (stock->nr_bytes > PAGE_SIZE)) {
3241 nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3242 stock->nr_bytes &= (PAGE_SIZE - 1);
3245 put_obj_stock(flags);
3248 obj_cgroup_uncharge_pages(objcg, nr_pages);
3251 int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size)
3253 unsigned int nr_pages, nr_bytes;
3256 if (consume_obj_stock(objcg, size))
3260 * In theory, objcg->nr_charged_bytes can have enough
3261 * pre-charged bytes to satisfy the allocation. However,
3262 * flushing objcg->nr_charged_bytes requires two atomic
3263 * operations, and objcg->nr_charged_bytes can't be big.
3264 * The shared objcg->nr_charged_bytes can also become a
3265 * performance bottleneck if all tasks of the same memcg are
3266 * trying to update it. So it's better to ignore it and try
3267 * grab some new pages. The stock's nr_bytes will be flushed to
3268 * objcg->nr_charged_bytes later on when objcg changes.
3270 * The stock's nr_bytes may contain enough pre-charged bytes
3271 * to allow one less page from being charged, but we can't rely
3272 * on the pre-charged bytes not being changed outside of
3273 * consume_obj_stock() or refill_obj_stock(). So ignore those
3274 * pre-charged bytes as well when charging pages. To avoid a
3275 * page uncharge right after a page charge, we set the
3276 * allow_uncharge flag to false when calling refill_obj_stock()
3277 * to temporarily allow the pre-charged bytes to exceed the page
3278 * size limit. The maximum reachable value of the pre-charged
3279 * bytes is (sizeof(object) + PAGE_SIZE - 2) if there is no data
3282 nr_pages = size >> PAGE_SHIFT;
3283 nr_bytes = size & (PAGE_SIZE - 1);
3288 ret = obj_cgroup_charge_pages(objcg, gfp, nr_pages);
3289 if (!ret && nr_bytes)
3290 refill_obj_stock(objcg, PAGE_SIZE - nr_bytes, false);
3295 void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size)
3297 refill_obj_stock(objcg, size, true);
3300 #endif /* CONFIG_MEMCG_KMEM */
3303 * Because page_memcg(head) is not set on tails, set it now.
3305 void split_page_memcg(struct page *head, unsigned int nr)
3307 struct mem_cgroup *memcg = page_memcg(head);
3310 if (mem_cgroup_disabled() || !memcg)
3313 for (i = 1; i < nr; i++)
3314 head[i].memcg_data = head->memcg_data;
3316 if (PageMemcgKmem(head))
3317 obj_cgroup_get_many(__page_objcg(head), nr - 1);
3319 css_get_many(&memcg->css, nr - 1);
3322 #ifdef CONFIG_MEMCG_SWAP
3324 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3325 * @entry: swap entry to be moved
3326 * @from: mem_cgroup which the entry is moved from
3327 * @to: mem_cgroup which the entry is moved to
3329 * It succeeds only when the swap_cgroup's record for this entry is the same
3330 * as the mem_cgroup's id of @from.
3332 * Returns 0 on success, -EINVAL on failure.
3334 * The caller must have charged to @to, IOW, called page_counter_charge() about
3335 * both res and memsw, and called css_get().
3337 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3338 struct mem_cgroup *from, struct mem_cgroup *to)
3340 unsigned short old_id, new_id;
3342 old_id = mem_cgroup_id(from);
3343 new_id = mem_cgroup_id(to);
3345 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3346 mod_memcg_state(from, MEMCG_SWAP, -1);
3347 mod_memcg_state(to, MEMCG_SWAP, 1);
3353 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3354 struct mem_cgroup *from, struct mem_cgroup *to)
3360 static DEFINE_MUTEX(memcg_max_mutex);
3362 static int mem_cgroup_resize_max(struct mem_cgroup *memcg,
3363 unsigned long max, bool memsw)
3365 bool enlarge = false;
3366 bool drained = false;
3368 bool limits_invariant;
3369 struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory;
3372 if (signal_pending(current)) {
3377 mutex_lock(&memcg_max_mutex);
3379 * Make sure that the new limit (memsw or memory limit) doesn't
3380 * break our basic invariant rule memory.max <= memsw.max.
3382 limits_invariant = memsw ? max >= READ_ONCE(memcg->memory.max) :
3383 max <= memcg->memsw.max;
3384 if (!limits_invariant) {
3385 mutex_unlock(&memcg_max_mutex);
3389 if (max > counter->max)
3391 ret = page_counter_set_max(counter, max);
3392 mutex_unlock(&memcg_max_mutex);
3398 drain_all_stock(memcg);
3403 if (!try_to_free_mem_cgroup_pages(memcg, 1,
3404 GFP_KERNEL, !memsw)) {
3410 if (!ret && enlarge)
3411 memcg_oom_recover(memcg);
3416 unsigned long mem_cgroup_soft_limit_reclaim(pg_data_t *pgdat, int order,
3418 unsigned long *total_scanned)
3420 unsigned long nr_reclaimed = 0;
3421 struct mem_cgroup_per_node *mz, *next_mz = NULL;
3422 unsigned long reclaimed;
3424 struct mem_cgroup_tree_per_node *mctz;
3425 unsigned long excess;
3426 unsigned long nr_scanned;
3431 mctz = soft_limit_tree_node(pgdat->node_id);
3434 * Do not even bother to check the largest node if the root
3435 * is empty. Do it lockless to prevent lock bouncing. Races
3436 * are acceptable as soft limit is best effort anyway.
3438 if (!mctz || RB_EMPTY_ROOT(&mctz->rb_root))
3442 * This loop can run a while, specially if mem_cgroup's continuously
3443 * keep exceeding their soft limit and putting the system under
3450 mz = mem_cgroup_largest_soft_limit_node(mctz);
3455 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, pgdat,
3456 gfp_mask, &nr_scanned);
3457 nr_reclaimed += reclaimed;
3458 *total_scanned += nr_scanned;
3459 spin_lock_irq(&mctz->lock);
3460 __mem_cgroup_remove_exceeded(mz, mctz);
3463 * If we failed to reclaim anything from this memory cgroup
3464 * it is time to move on to the next cgroup
3468 next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
3470 excess = soft_limit_excess(mz->memcg);
3472 * One school of thought says that we should not add
3473 * back the node to the tree if reclaim returns 0.
3474 * But our reclaim could return 0, simply because due
3475 * to priority we are exposing a smaller subset of
3476 * memory to reclaim from. Consider this as a longer
3479 /* If excess == 0, no tree ops */
3480 __mem_cgroup_insert_exceeded(mz, mctz, excess);
3481 spin_unlock_irq(&mctz->lock);
3482 css_put(&mz->memcg->css);
3485 * Could not reclaim anything and there are no more
3486 * mem cgroups to try or we seem to be looping without
3487 * reclaiming anything.
3489 if (!nr_reclaimed &&
3491 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3493 } while (!nr_reclaimed);
3495 css_put(&next_mz->memcg->css);
3496 return nr_reclaimed;
3500 * Reclaims as many pages from the given memcg as possible.
3502 * Caller is responsible for holding css reference for memcg.
3504 static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
3506 int nr_retries = MAX_RECLAIM_RETRIES;
3508 /* we call try-to-free pages for make this cgroup empty */
3509 lru_add_drain_all();
3511 drain_all_stock(memcg);
3513 /* try to free all pages in this cgroup */
3514 while (nr_retries && page_counter_read(&memcg->memory)) {
3517 if (signal_pending(current))
3520 progress = try_to_free_mem_cgroup_pages(memcg, 1,
3524 /* maybe some writeback is necessary */
3525 congestion_wait(BLK_RW_ASYNC, HZ/10);
3533 static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
3534 char *buf, size_t nbytes,
3537 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3539 if (mem_cgroup_is_root(memcg))
3541 return mem_cgroup_force_empty(memcg) ?: nbytes;
3544 static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
3550 static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
3551 struct cftype *cft, u64 val)
3556 pr_warn_once("Non-hierarchical mode is deprecated. "
3557 "Please report your usecase to linux-mm@kvack.org if you "
3558 "depend on this functionality.\n");
3563 static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3567 if (mem_cgroup_is_root(memcg)) {
3568 /* mem_cgroup_threshold() calls here from irqsafe context */
3569 cgroup_rstat_flush_irqsafe(memcg->css.cgroup);
3570 val = memcg_page_state(memcg, NR_FILE_PAGES) +
3571 memcg_page_state(memcg, NR_ANON_MAPPED);
3573 val += memcg_page_state(memcg, MEMCG_SWAP);
3576 val = page_counter_read(&memcg->memory);
3578 val = page_counter_read(&memcg->memsw);
3591 static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
3594 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3595 struct page_counter *counter;
3597 switch (MEMFILE_TYPE(cft->private)) {
3599 counter = &memcg->memory;
3602 counter = &memcg->memsw;
3605 counter = &memcg->kmem;
3608 counter = &memcg->tcpmem;
3614 switch (MEMFILE_ATTR(cft->private)) {
3616 if (counter == &memcg->memory)
3617 return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
3618 if (counter == &memcg->memsw)
3619 return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
3620 return (u64)page_counter_read(counter) * PAGE_SIZE;
3622 return (u64)counter->max * PAGE_SIZE;
3624 return (u64)counter->watermark * PAGE_SIZE;
3626 return counter->failcnt;
3627 case RES_SOFT_LIMIT:
3628 return (u64)memcg->soft_limit * PAGE_SIZE;
3634 #ifdef CONFIG_MEMCG_KMEM
3635 static int memcg_online_kmem(struct mem_cgroup *memcg)
3637 struct obj_cgroup *objcg;
3640 if (cgroup_memory_nokmem)
3643 BUG_ON(memcg->kmemcg_id >= 0);
3644 BUG_ON(memcg->kmem_state);
3646 memcg_id = memcg_alloc_cache_id();
3650 objcg = obj_cgroup_alloc();
3652 memcg_free_cache_id(memcg_id);
3655 objcg->memcg = memcg;
3656 rcu_assign_pointer(memcg->objcg, objcg);
3658 static_branch_enable(&memcg_kmem_enabled_key);
3660 memcg->kmemcg_id = memcg_id;
3661 memcg->kmem_state = KMEM_ONLINE;
3666 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3668 struct cgroup_subsys_state *css;
3669 struct mem_cgroup *parent, *child;
3672 if (memcg->kmem_state != KMEM_ONLINE)
3675 memcg->kmem_state = KMEM_ALLOCATED;
3677 parent = parent_mem_cgroup(memcg);
3679 parent = root_mem_cgroup;
3681 memcg_reparent_objcgs(memcg, parent);
3683 kmemcg_id = memcg->kmemcg_id;
3684 BUG_ON(kmemcg_id < 0);
3687 * Change kmemcg_id of this cgroup and all its descendants to the
3688 * parent's id, and then move all entries from this cgroup's list_lrus
3689 * to ones of the parent. After we have finished, all list_lrus
3690 * corresponding to this cgroup are guaranteed to remain empty. The
3691 * ordering is imposed by list_lru_node->lock taken by
3692 * memcg_drain_all_list_lrus().
3694 rcu_read_lock(); /* can be called from css_free w/o cgroup_mutex */
3695 css_for_each_descendant_pre(css, &memcg->css) {
3696 child = mem_cgroup_from_css(css);
3697 BUG_ON(child->kmemcg_id != kmemcg_id);
3698 child->kmemcg_id = parent->kmemcg_id;
3702 memcg_drain_all_list_lrus(kmemcg_id, parent);
3704 memcg_free_cache_id(kmemcg_id);
3707 static void memcg_free_kmem(struct mem_cgroup *memcg)
3709 /* css_alloc() failed, offlining didn't happen */
3710 if (unlikely(memcg->kmem_state == KMEM_ONLINE))
3711 memcg_offline_kmem(memcg);
3714 static int memcg_online_kmem(struct mem_cgroup *memcg)
3718 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3721 static void memcg_free_kmem(struct mem_cgroup *memcg)
3724 #endif /* CONFIG_MEMCG_KMEM */
3726 static int memcg_update_kmem_max(struct mem_cgroup *memcg,
3731 mutex_lock(&memcg_max_mutex);
3732 ret = page_counter_set_max(&memcg->kmem, max);
3733 mutex_unlock(&memcg_max_mutex);
3737 static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max)
3741 mutex_lock(&memcg_max_mutex);
3743 ret = page_counter_set_max(&memcg->tcpmem, max);
3747 if (!memcg->tcpmem_active) {
3749 * The active flag needs to be written after the static_key
3750 * update. This is what guarantees that the socket activation
3751 * function is the last one to run. See mem_cgroup_sk_alloc()
3752 * for details, and note that we don't mark any socket as
3753 * belonging to this memcg until that flag is up.
3755 * We need to do this, because static_keys will span multiple
3756 * sites, but we can't control their order. If we mark a socket
3757 * as accounted, but the accounting functions are not patched in
3758 * yet, we'll lose accounting.
3760 * We never race with the readers in mem_cgroup_sk_alloc(),
3761 * because when this value change, the code to process it is not
3764 static_branch_inc(&memcg_sockets_enabled_key);
3765 memcg->tcpmem_active = true;
3768 mutex_unlock(&memcg_max_mutex);
3773 * The user of this function is...
3776 static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
3777 char *buf, size_t nbytes, loff_t off)
3779 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3780 unsigned long nr_pages;
3783 buf = strstrip(buf);
3784 ret = page_counter_memparse(buf, "-1", &nr_pages);
3788 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3790 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3794 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3796 ret = mem_cgroup_resize_max(memcg, nr_pages, false);
3799 ret = mem_cgroup_resize_max(memcg, nr_pages, true);
3802 pr_warn_once("kmem.limit_in_bytes is deprecated and will be removed. "
3803 "Please report your usecase to linux-mm@kvack.org if you "
3804 "depend on this functionality.\n");
3805 ret = memcg_update_kmem_max(memcg, nr_pages);
3808 ret = memcg_update_tcp_max(memcg, nr_pages);
3812 case RES_SOFT_LIMIT:
3813 memcg->soft_limit = nr_pages;
3817 return ret ?: nbytes;
3820 static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
3821 size_t nbytes, loff_t off)
3823 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3824 struct page_counter *counter;
3826 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3828 counter = &memcg->memory;
3831 counter = &memcg->memsw;
3834 counter = &memcg->kmem;
3837 counter = &memcg->tcpmem;
3843 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3845 page_counter_reset_watermark(counter);
3848 counter->failcnt = 0;
3857 static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
3860 return mem_cgroup_from_css(css)->move_charge_at_immigrate;
3864 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3865 struct cftype *cft, u64 val)
3867 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3869 if (val & ~MOVE_MASK)
3873 * No kind of locking is needed in here, because ->can_attach() will
3874 * check this value once in the beginning of the process, and then carry
3875 * on with stale data. This means that changes to this value will only
3876 * affect task migrations starting after the change.
3878 memcg->move_charge_at_immigrate = val;
3882 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3883 struct cftype *cft, u64 val)
3891 #define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE))
3892 #define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON))
3893 #define LRU_ALL ((1 << NR_LRU_LISTS) - 1)
3895 static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
3896 int nid, unsigned int lru_mask, bool tree)
3898 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
3899 unsigned long nr = 0;
3902 VM_BUG_ON((unsigned)nid >= nr_node_ids);
3905 if (!(BIT(lru) & lru_mask))
3908 nr += lruvec_page_state(lruvec, NR_LRU_BASE + lru);
3910 nr += lruvec_page_state_local(lruvec, NR_LRU_BASE + lru);
3915 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
3916 unsigned int lru_mask,
3919 unsigned long nr = 0;
3923 if (!(BIT(lru) & lru_mask))
3926 nr += memcg_page_state(memcg, NR_LRU_BASE + lru);
3928 nr += memcg_page_state_local(memcg, NR_LRU_BASE + lru);
3933 static int memcg_numa_stat_show(struct seq_file *m, void *v)
3937 unsigned int lru_mask;
3940 static const struct numa_stat stats[] = {
3941 { "total", LRU_ALL },
3942 { "file", LRU_ALL_FILE },
3943 { "anon", LRU_ALL_ANON },
3944 { "unevictable", BIT(LRU_UNEVICTABLE) },
3946 const struct numa_stat *stat;
3948 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
3950 cgroup_rstat_flush(memcg->css.cgroup);
3952 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
3953 seq_printf(m, "%s=%lu", stat->name,
3954 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
3956 for_each_node_state(nid, N_MEMORY)
3957 seq_printf(m, " N%d=%lu", nid,
3958 mem_cgroup_node_nr_lru_pages(memcg, nid,
3959 stat->lru_mask, false));
3963 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
3965 seq_printf(m, "hierarchical_%s=%lu", stat->name,
3966 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
3968 for_each_node_state(nid, N_MEMORY)
3969 seq_printf(m, " N%d=%lu", nid,
3970 mem_cgroup_node_nr_lru_pages(memcg, nid,
3971 stat->lru_mask, true));
3977 #endif /* CONFIG_NUMA */
3979 static const unsigned int memcg1_stats[] = {
3982 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3992 static const char *const memcg1_stat_names[] = {
3995 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4005 /* Universal VM events cgroup1 shows, original sort order */
4006 static const unsigned int memcg1_events[] = {
4013 static int memcg_stat_show(struct seq_file *m, void *v)
4015 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
4016 unsigned long memory, memsw;
4017 struct mem_cgroup *mi;
4020 BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats));
4022 cgroup_rstat_flush(memcg->css.cgroup);
4024 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
4027 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
4029 nr = memcg_page_state_local(memcg, memcg1_stats[i]);
4030 seq_printf(m, "%s %lu\n", memcg1_stat_names[i], nr * PAGE_SIZE);
4033 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
4034 seq_printf(m, "%s %lu\n", vm_event_name(memcg1_events[i]),
4035 memcg_events_local(memcg, memcg1_events[i]));
4037 for (i = 0; i < NR_LRU_LISTS; i++)
4038 seq_printf(m, "%s %lu\n", lru_list_name(i),
4039 memcg_page_state_local(memcg, NR_LRU_BASE + i) *
4042 /* Hierarchical information */
4043 memory = memsw = PAGE_COUNTER_MAX;
4044 for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
4045 memory = min(memory, READ_ONCE(mi->memory.max));
4046 memsw = min(memsw, READ_ONCE(mi->memsw.max));
4048 seq_printf(m, "hierarchical_memory_limit %llu\n",
4049 (u64)memory * PAGE_SIZE);
4050 if (do_memsw_account())
4051 seq_printf(m, "hierarchical_memsw_limit %llu\n",
4052 (u64)memsw * PAGE_SIZE);
4054 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
4057 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
4059 nr = memcg_page_state(memcg, memcg1_stats[i]);
4060 seq_printf(m, "total_%s %llu\n", memcg1_stat_names[i],
4061 (u64)nr * PAGE_SIZE);
4064 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
4065 seq_printf(m, "total_%s %llu\n",
4066 vm_event_name(memcg1_events[i]),
4067 (u64)memcg_events(memcg, memcg1_events[i]));
4069 for (i = 0; i < NR_LRU_LISTS; i++)
4070 seq_printf(m, "total_%s %llu\n", lru_list_name(i),
4071 (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
4074 #ifdef CONFIG_DEBUG_VM
4077 struct mem_cgroup_per_node *mz;
4078 unsigned long anon_cost = 0;
4079 unsigned long file_cost = 0;
4081 for_each_online_pgdat(pgdat) {
4082 mz = memcg->nodeinfo[pgdat->node_id];
4084 anon_cost += mz->lruvec.anon_cost;
4085 file_cost += mz->lruvec.file_cost;
4087 seq_printf(m, "anon_cost %lu\n", anon_cost);
4088 seq_printf(m, "file_cost %lu\n", file_cost);
4095 static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
4098 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4100 return mem_cgroup_swappiness(memcg);
4103 static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
4104 struct cftype *cft, u64 val)
4106 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4111 if (!mem_cgroup_is_root(memcg))
4112 memcg->swappiness = val;
4114 vm_swappiness = val;
4119 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4121 struct mem_cgroup_threshold_ary *t;
4122 unsigned long usage;
4127 t = rcu_dereference(memcg->thresholds.primary);
4129 t = rcu_dereference(memcg->memsw_thresholds.primary);
4134 usage = mem_cgroup_usage(memcg, swap);
4137 * current_threshold points to threshold just below or equal to usage.
4138 * If it's not true, a threshold was crossed after last
4139 * call of __mem_cgroup_threshold().
4141 i = t->current_threshold;
4144 * Iterate backward over array of thresholds starting from
4145 * current_threshold and check if a threshold is crossed.
4146 * If none of thresholds below usage is crossed, we read
4147 * only one element of the array here.
4149 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4150 eventfd_signal(t->entries[i].eventfd, 1);
4152 /* i = current_threshold + 1 */
4156 * Iterate forward over array of thresholds starting from
4157 * current_threshold+1 and check if a threshold is crossed.
4158 * If none of thresholds above usage is crossed, we read
4159 * only one element of the array here.
4161 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4162 eventfd_signal(t->entries[i].eventfd, 1);
4164 /* Update current_threshold */
4165 t->current_threshold = i - 1;
4170 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4173 __mem_cgroup_threshold(memcg, false);
4174 if (do_memsw_account())
4175 __mem_cgroup_threshold(memcg, true);
4177 memcg = parent_mem_cgroup(memcg);
4181 static int compare_thresholds(const void *a, const void *b)
4183 const struct mem_cgroup_threshold *_a = a;
4184 const struct mem_cgroup_threshold *_b = b;
4186 if (_a->threshold > _b->threshold)
4189 if (_a->threshold < _b->threshold)
4195 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
4197 struct mem_cgroup_eventfd_list *ev;
4199 spin_lock(&memcg_oom_lock);
4201 list_for_each_entry(ev, &memcg->oom_notify, list)
4202 eventfd_signal(ev->eventfd, 1);
4204 spin_unlock(&memcg_oom_lock);
4208 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
4210 struct mem_cgroup *iter;
4212 for_each_mem_cgroup_tree(iter, memcg)
4213 mem_cgroup_oom_notify_cb(iter);
4216 static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4217 struct eventfd_ctx *eventfd, const char *args, enum res_type type)
4219 struct mem_cgroup_thresholds *thresholds;
4220 struct mem_cgroup_threshold_ary *new;
4221 unsigned long threshold;
4222 unsigned long usage;
4225 ret = page_counter_memparse(args, "-1", &threshold);
4229 mutex_lock(&memcg->thresholds_lock);
4232 thresholds = &memcg->thresholds;
4233 usage = mem_cgroup_usage(memcg, false);
4234 } else if (type == _MEMSWAP) {
4235 thresholds = &memcg->memsw_thresholds;
4236 usage = mem_cgroup_usage(memcg, true);
4240 /* Check if a threshold crossed before adding a new one */
4241 if (thresholds->primary)
4242 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4244 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4246 /* Allocate memory for new array of thresholds */
4247 new = kmalloc(struct_size(new, entries, size), GFP_KERNEL);
4254 /* Copy thresholds (if any) to new array */
4255 if (thresholds->primary)
4256 memcpy(new->entries, thresholds->primary->entries,
4257 flex_array_size(new, entries, size - 1));
4259 /* Add new threshold */
4260 new->entries[size - 1].eventfd = eventfd;
4261 new->entries[size - 1].threshold = threshold;
4263 /* Sort thresholds. Registering of new threshold isn't time-critical */
4264 sort(new->entries, size, sizeof(*new->entries),
4265 compare_thresholds, NULL);
4267 /* Find current threshold */
4268 new->current_threshold = -1;
4269 for (i = 0; i < size; i++) {
4270 if (new->entries[i].threshold <= usage) {
4272 * new->current_threshold will not be used until
4273 * rcu_assign_pointer(), so it's safe to increment
4276 ++new->current_threshold;
4281 /* Free old spare buffer and save old primary buffer as spare */
4282 kfree(thresholds->spare);
4283 thresholds->spare = thresholds->primary;
4285 rcu_assign_pointer(thresholds->primary, new);
4287 /* To be sure that nobody uses thresholds */
4291 mutex_unlock(&memcg->thresholds_lock);
4296 static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4297 struct eventfd_ctx *eventfd, const char *args)
4299 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
4302 static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
4303 struct eventfd_ctx *eventfd, const char *args)
4305 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
4308 static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4309 struct eventfd_ctx *eventfd, enum res_type type)
4311 struct mem_cgroup_thresholds *thresholds;
4312 struct mem_cgroup_threshold_ary *new;
4313 unsigned long usage;
4314 int i, j, size, entries;
4316 mutex_lock(&memcg->thresholds_lock);
4319 thresholds = &memcg->thresholds;
4320 usage = mem_cgroup_usage(memcg, false);
4321 } else if (type == _MEMSWAP) {
4322 thresholds = &memcg->memsw_thresholds;
4323 usage = mem_cgroup_usage(memcg, true);
4327 if (!thresholds->primary)
4330 /* Check if a threshold crossed before removing */
4331 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4333 /* Calculate new number of threshold */
4335 for (i = 0; i < thresholds->primary->size; i++) {
4336 if (thresholds->primary->entries[i].eventfd != eventfd)
4342 new = thresholds->spare;
4344 /* If no items related to eventfd have been cleared, nothing to do */
4348 /* Set thresholds array to NULL if we don't have thresholds */
4357 /* Copy thresholds and find current threshold */
4358 new->current_threshold = -1;
4359 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4360 if (thresholds->primary->entries[i].eventfd == eventfd)
4363 new->entries[j] = thresholds->primary->entries[i];
4364 if (new->entries[j].threshold <= usage) {
4366 * new->current_threshold will not be used
4367 * until rcu_assign_pointer(), so it's safe to increment
4370 ++new->current_threshold;
4376 /* Swap primary and spare array */
4377 thresholds->spare = thresholds->primary;
4379 rcu_assign_pointer(thresholds->primary, new);
4381 /* To be sure that nobody uses thresholds */
4384 /* If all events are unregistered, free the spare array */
4386 kfree(thresholds->spare);
4387 thresholds->spare = NULL;
4390 mutex_unlock(&memcg->thresholds_lock);
4393 static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4394 struct eventfd_ctx *eventfd)
4396 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
4399 static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4400 struct eventfd_ctx *eventfd)
4402 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
4405 static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
4406 struct eventfd_ctx *eventfd, const char *args)
4408 struct mem_cgroup_eventfd_list *event;
4410 event = kmalloc(sizeof(*event), GFP_KERNEL);
4414 spin_lock(&memcg_oom_lock);
4416 event->eventfd = eventfd;
4417 list_add(&event->list, &memcg->oom_notify);
4419 /* already in OOM ? */
4420 if (memcg->under_oom)
4421 eventfd_signal(eventfd, 1);
4422 spin_unlock(&memcg_oom_lock);
4427 static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
4428 struct eventfd_ctx *eventfd)
4430 struct mem_cgroup_eventfd_list *ev, *tmp;
4432 spin_lock(&memcg_oom_lock);
4434 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
4435 if (ev->eventfd == eventfd) {
4436 list_del(&ev->list);
4441 spin_unlock(&memcg_oom_lock);
4444 static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
4446 struct mem_cgroup *memcg = mem_cgroup_from_seq(sf);
4448 seq_printf(sf, "oom_kill_disable %d\n", memcg->oom_kill_disable);
4449 seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
4450 seq_printf(sf, "oom_kill %lu\n",
4451 atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
4455 static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
4456 struct cftype *cft, u64 val)
4458 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4460 /* cannot set to root cgroup and only 0 and 1 are allowed */
4461 if (mem_cgroup_is_root(memcg) || !((val == 0) || (val == 1)))
4464 memcg->oom_kill_disable = val;
4466 memcg_oom_recover(memcg);
4471 #ifdef CONFIG_CGROUP_WRITEBACK
4473 #include <trace/events/writeback.h>
4475 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4477 return wb_domain_init(&memcg->cgwb_domain, gfp);
4480 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4482 wb_domain_exit(&memcg->cgwb_domain);
4485 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4487 wb_domain_size_changed(&memcg->cgwb_domain);
4490 struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
4492 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4494 if (!memcg->css.parent)
4497 return &memcg->cgwb_domain;
4501 * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
4502 * @wb: bdi_writeback in question
4503 * @pfilepages: out parameter for number of file pages
4504 * @pheadroom: out parameter for number of allocatable pages according to memcg
4505 * @pdirty: out parameter for number of dirty pages
4506 * @pwriteback: out parameter for number of pages under writeback
4508 * Determine the numbers of file, headroom, dirty, and writeback pages in
4509 * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom
4510 * is a bit more involved.
4512 * A memcg's headroom is "min(max, high) - used". In the hierarchy, the
4513 * headroom is calculated as the lowest headroom of itself and the
4514 * ancestors. Note that this doesn't consider the actual amount of
4515 * available memory in the system. The caller should further cap
4516 * *@pheadroom accordingly.
4518 void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
4519 unsigned long *pheadroom, unsigned long *pdirty,
4520 unsigned long *pwriteback)
4522 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4523 struct mem_cgroup *parent;
4525 cgroup_rstat_flush_irqsafe(memcg->css.cgroup);
4527 *pdirty = memcg_page_state(memcg, NR_FILE_DIRTY);
4528 *pwriteback = memcg_page_state(memcg, NR_WRITEBACK);
4529 *pfilepages = memcg_page_state(memcg, NR_INACTIVE_FILE) +
4530 memcg_page_state(memcg, NR_ACTIVE_FILE);
4532 *pheadroom = PAGE_COUNTER_MAX;
4533 while ((parent = parent_mem_cgroup(memcg))) {
4534 unsigned long ceiling = min(READ_ONCE(memcg->memory.max),
4535 READ_ONCE(memcg->memory.high));
4536 unsigned long used = page_counter_read(&memcg->memory);
4538 *pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
4544 * Foreign dirty flushing
4546 * There's an inherent mismatch between memcg and writeback. The former
4547 * tracks ownership per-page while the latter per-inode. This was a
4548 * deliberate design decision because honoring per-page ownership in the
4549 * writeback path is complicated, may lead to higher CPU and IO overheads
4550 * and deemed unnecessary given that write-sharing an inode across
4551 * different cgroups isn't a common use-case.
4553 * Combined with inode majority-writer ownership switching, this works well
4554 * enough in most cases but there are some pathological cases. For
4555 * example, let's say there are two cgroups A and B which keep writing to
4556 * different but confined parts of the same inode. B owns the inode and
4557 * A's memory is limited far below B's. A's dirty ratio can rise enough to
4558 * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
4559 * triggering background writeback. A will be slowed down without a way to
4560 * make writeback of the dirty pages happen.
4562 * Conditions like the above can lead to a cgroup getting repeatedly and
4563 * severely throttled after making some progress after each
4564 * dirty_expire_interval while the underlying IO device is almost
4567 * Solving this problem completely requires matching the ownership tracking
4568 * granularities between memcg and writeback in either direction. However,
4569 * the more egregious behaviors can be avoided by simply remembering the
4570 * most recent foreign dirtying events and initiating remote flushes on
4571 * them when local writeback isn't enough to keep the memory clean enough.
4573 * The following two functions implement such mechanism. When a foreign
4574 * page - a page whose memcg and writeback ownerships don't match - is
4575 * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
4576 * bdi_writeback on the page owning memcg. When balance_dirty_pages()
4577 * decides that the memcg needs to sleep due to high dirty ratio, it calls
4578 * mem_cgroup_flush_foreign() which queues writeback on the recorded
4579 * foreign bdi_writebacks which haven't expired. Both the numbers of
4580 * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
4581 * limited to MEMCG_CGWB_FRN_CNT.
4583 * The mechanism only remembers IDs and doesn't hold any object references.
4584 * As being wrong occasionally doesn't matter, updates and accesses to the
4585 * records are lockless and racy.
4587 void mem_cgroup_track_foreign_dirty_slowpath(struct page *page,
4588 struct bdi_writeback *wb)
4590 struct mem_cgroup *memcg = page_memcg(page);
4591 struct memcg_cgwb_frn *frn;
4592 u64 now = get_jiffies_64();
4593 u64 oldest_at = now;
4597 trace_track_foreign_dirty(page, wb);
4600 * Pick the slot to use. If there is already a slot for @wb, keep
4601 * using it. If not replace the oldest one which isn't being
4604 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4605 frn = &memcg->cgwb_frn[i];
4606 if (frn->bdi_id == wb->bdi->id &&
4607 frn->memcg_id == wb->memcg_css->id)
4609 if (time_before64(frn->at, oldest_at) &&
4610 atomic_read(&frn->done.cnt) == 1) {
4612 oldest_at = frn->at;
4616 if (i < MEMCG_CGWB_FRN_CNT) {
4618 * Re-using an existing one. Update timestamp lazily to
4619 * avoid making the cacheline hot. We want them to be
4620 * reasonably up-to-date and significantly shorter than
4621 * dirty_expire_interval as that's what expires the record.
4622 * Use the shorter of 1s and dirty_expire_interval / 8.
4624 unsigned long update_intv =
4625 min_t(unsigned long, HZ,
4626 msecs_to_jiffies(dirty_expire_interval * 10) / 8);
4628 if (time_before64(frn->at, now - update_intv))
4630 } else if (oldest >= 0) {
4631 /* replace the oldest free one */
4632 frn = &memcg->cgwb_frn[oldest];
4633 frn->bdi_id = wb->bdi->id;
4634 frn->memcg_id = wb->memcg_css->id;
4639 /* issue foreign writeback flushes for recorded foreign dirtying events */
4640 void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
4642 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4643 unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
4644 u64 now = jiffies_64;
4647 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4648 struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
4651 * If the record is older than dirty_expire_interval,
4652 * writeback on it has already started. No need to kick it
4653 * off again. Also, don't start a new one if there's
4654 * already one in flight.
4656 if (time_after64(frn->at, now - intv) &&
4657 atomic_read(&frn->done.cnt) == 1) {
4659 trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
4660 cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id,
4661 WB_REASON_FOREIGN_FLUSH,
4667 #else /* CONFIG_CGROUP_WRITEBACK */
4669 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4674 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4678 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4682 #endif /* CONFIG_CGROUP_WRITEBACK */
4685 * DO NOT USE IN NEW FILES.
4687 * "cgroup.event_control" implementation.
4689 * This is way over-engineered. It tries to support fully configurable
4690 * events for each user. Such level of flexibility is completely
4691 * unnecessary especially in the light of the planned unified hierarchy.
4693 * Please deprecate this and replace with something simpler if at all
4698 * Unregister event and free resources.
4700 * Gets called from workqueue.
4702 static void memcg_event_remove(struct work_struct *work)
4704 struct mem_cgroup_event *event =
4705 container_of(work, struct mem_cgroup_event, remove);
4706 struct mem_cgroup *memcg = event->memcg;
4708 remove_wait_queue(event->wqh, &event->wait);
4710 event->unregister_event(memcg, event->eventfd);
4712 /* Notify userspace the event is going away. */
4713 eventfd_signal(event->eventfd, 1);
4715 eventfd_ctx_put(event->eventfd);
4717 css_put(&memcg->css);
4721 * Gets called on EPOLLHUP on eventfd when user closes it.
4723 * Called with wqh->lock held and interrupts disabled.
4725 static int memcg_event_wake(wait_queue_entry_t *wait, unsigned mode,
4726 int sync, void *key)
4728 struct mem_cgroup_event *event =
4729 container_of(wait, struct mem_cgroup_event, wait);
4730 struct mem_cgroup *memcg = event->memcg;
4731 __poll_t flags = key_to_poll(key);
4733 if (flags & EPOLLHUP) {
4735 * If the event has been detached at cgroup removal, we
4736 * can simply return knowing the other side will cleanup
4739 * We can't race against event freeing since the other
4740 * side will require wqh->lock via remove_wait_queue(),
4743 spin_lock(&memcg->event_list_lock);
4744 if (!list_empty(&event->list)) {
4745 list_del_init(&event->list);
4747 * We are in atomic context, but cgroup_event_remove()
4748 * may sleep, so we have to call it in workqueue.
4750 schedule_work(&event->remove);
4752 spin_unlock(&memcg->event_list_lock);
4758 static void memcg_event_ptable_queue_proc(struct file *file,
4759 wait_queue_head_t *wqh, poll_table *pt)
4761 struct mem_cgroup_event *event =
4762 container_of(pt, struct mem_cgroup_event, pt);
4765 add_wait_queue(wqh, &event->wait);
4769 * DO NOT USE IN NEW FILES.
4771 * Parse input and register new cgroup event handler.
4773 * Input must be in format '<event_fd> <control_fd> <args>'.
4774 * Interpretation of args is defined by control file implementation.
4776 static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
4777 char *buf, size_t nbytes, loff_t off)
4779 struct cgroup_subsys_state *css = of_css(of);
4780 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4781 struct mem_cgroup_event *event;
4782 struct cgroup_subsys_state *cfile_css;
4783 unsigned int efd, cfd;
4790 buf = strstrip(buf);
4792 efd = simple_strtoul(buf, &endp, 10);
4797 cfd = simple_strtoul(buf, &endp, 10);
4798 if ((*endp != ' ') && (*endp != '\0'))
4802 event = kzalloc(sizeof(*event), GFP_KERNEL);
4806 event->memcg = memcg;
4807 INIT_LIST_HEAD(&event->list);
4808 init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
4809 init_waitqueue_func_entry(&event->wait, memcg_event_wake);
4810 INIT_WORK(&event->remove, memcg_event_remove);
4818 event->eventfd = eventfd_ctx_fileget(efile.file);
4819 if (IS_ERR(event->eventfd)) {
4820 ret = PTR_ERR(event->eventfd);
4827 goto out_put_eventfd;
4830 /* the process need read permission on control file */
4831 /* AV: shouldn't we check that it's been opened for read instead? */
4832 ret = file_permission(cfile.file, MAY_READ);
4837 * Determine the event callbacks and set them in @event. This used
4838 * to be done via struct cftype but cgroup core no longer knows
4839 * about these events. The following is crude but the whole thing
4840 * is for compatibility anyway.
4842 * DO NOT ADD NEW FILES.
4844 name = cfile.file->f_path.dentry->d_name.name;
4846 if (!strcmp(name, "memory.usage_in_bytes")) {
4847 event->register_event = mem_cgroup_usage_register_event;
4848 event->unregister_event = mem_cgroup_usage_unregister_event;
4849 } else if (!strcmp(name, "memory.oom_control")) {
4850 event->register_event = mem_cgroup_oom_register_event;
4851 event->unregister_event = mem_cgroup_oom_unregister_event;
4852 } else if (!strcmp(name, "memory.pressure_level")) {
4853 event->register_event = vmpressure_register_event;
4854 event->unregister_event = vmpressure_unregister_event;
4855 } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
4856 event->register_event = memsw_cgroup_usage_register_event;
4857 event->unregister_event = memsw_cgroup_usage_unregister_event;
4864 * Verify @cfile should belong to @css. Also, remaining events are
4865 * automatically removed on cgroup destruction but the removal is
4866 * asynchronous, so take an extra ref on @css.
4868 cfile_css = css_tryget_online_from_dir(cfile.file->f_path.dentry->d_parent,
4869 &memory_cgrp_subsys);
4871 if (IS_ERR(cfile_css))
4873 if (cfile_css != css) {
4878 ret = event->register_event(memcg, event->eventfd, buf);
4882 vfs_poll(efile.file, &event->pt);
4884 spin_lock(&memcg->event_list_lock);
4885 list_add(&event->list, &memcg->event_list);
4886 spin_unlock(&memcg->event_list_lock);
4898 eventfd_ctx_put(event->eventfd);
4907 static struct cftype mem_cgroup_legacy_files[] = {
4909 .name = "usage_in_bytes",
4910 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
4911 .read_u64 = mem_cgroup_read_u64,
4914 .name = "max_usage_in_bytes",
4915 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
4916 .write = mem_cgroup_reset,
4917 .read_u64 = mem_cgroup_read_u64,
4920 .name = "limit_in_bytes",
4921 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
4922 .write = mem_cgroup_write,
4923 .read_u64 = mem_cgroup_read_u64,
4926 .name = "soft_limit_in_bytes",
4927 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
4928 .write = mem_cgroup_write,
4929 .read_u64 = mem_cgroup_read_u64,
4933 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
4934 .write = mem_cgroup_reset,
4935 .read_u64 = mem_cgroup_read_u64,
4939 .seq_show = memcg_stat_show,
4942 .name = "force_empty",
4943 .write = mem_cgroup_force_empty_write,
4946 .name = "use_hierarchy",
4947 .write_u64 = mem_cgroup_hierarchy_write,
4948 .read_u64 = mem_cgroup_hierarchy_read,
4951 .name = "cgroup.event_control", /* XXX: for compat */
4952 .write = memcg_write_event_control,
4953 .flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE,
4956 .name = "swappiness",
4957 .read_u64 = mem_cgroup_swappiness_read,
4958 .write_u64 = mem_cgroup_swappiness_write,
4961 .name = "move_charge_at_immigrate",
4962 .read_u64 = mem_cgroup_move_charge_read,
4963 .write_u64 = mem_cgroup_move_charge_write,
4966 .name = "oom_control",
4967 .seq_show = mem_cgroup_oom_control_read,
4968 .write_u64 = mem_cgroup_oom_control_write,
4969 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
4972 .name = "pressure_level",
4976 .name = "numa_stat",
4977 .seq_show = memcg_numa_stat_show,
4981 .name = "kmem.limit_in_bytes",
4982 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
4983 .write = mem_cgroup_write,
4984 .read_u64 = mem_cgroup_read_u64,
4987 .name = "kmem.usage_in_bytes",
4988 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
4989 .read_u64 = mem_cgroup_read_u64,
4992 .name = "kmem.failcnt",
4993 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
4994 .write = mem_cgroup_reset,
4995 .read_u64 = mem_cgroup_read_u64,
4998 .name = "kmem.max_usage_in_bytes",
4999 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
5000 .write = mem_cgroup_reset,
5001 .read_u64 = mem_cgroup_read_u64,
5003 #if defined(CONFIG_MEMCG_KMEM) && \
5004 (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG))
5006 .name = "kmem.slabinfo",
5007 .seq_show = memcg_slab_show,
5011 .name = "kmem.tcp.limit_in_bytes",
5012 .private = MEMFILE_PRIVATE(_TCP, RES_LIMIT),
5013 .write = mem_cgroup_write,
5014 .read_u64 = mem_cgroup_read_u64,
5017 .name = "kmem.tcp.usage_in_bytes",
5018 .private = MEMFILE_PRIVATE(_TCP, RES_USAGE),
5019 .read_u64 = mem_cgroup_read_u64,
5022 .name = "kmem.tcp.failcnt",
5023 .private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT),
5024 .write = mem_cgroup_reset,
5025 .read_u64 = mem_cgroup_read_u64,
5028 .name = "kmem.tcp.max_usage_in_bytes",
5029 .private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE),
5030 .write = mem_cgroup_reset,
5031 .read_u64 = mem_cgroup_read_u64,
5033 { }, /* terminate */
5037 * Private memory cgroup IDR
5039 * Swap-out records and page cache shadow entries need to store memcg
5040 * references in constrained space, so we maintain an ID space that is
5041 * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
5042 * memory-controlled cgroups to 64k.
5044 * However, there usually are many references to the offline CSS after
5045 * the cgroup has been destroyed, such as page cache or reclaimable
5046 * slab objects, that don't need to hang on to the ID. We want to keep
5047 * those dead CSS from occupying IDs, or we might quickly exhaust the
5048 * relatively small ID space and prevent the creation of new cgroups
5049 * even when there are much fewer than 64k cgroups - possibly none.
5051 * Maintain a private 16-bit ID space for memcg, and allow the ID to
5052 * be freed and recycled when it's no longer needed, which is usually
5053 * when the CSS is offlined.
5055 * The only exception to that are records of swapped out tmpfs/shmem
5056 * pages that need to be attributed to live ancestors on swapin. But
5057 * those references are manageable from userspace.
5060 static DEFINE_IDR(mem_cgroup_idr);
5062 static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
5064 if (memcg->id.id > 0) {
5065 idr_remove(&mem_cgroup_idr, memcg->id.id);
5070 static void __maybe_unused mem_cgroup_id_get_many(struct mem_cgroup *memcg,
5073 refcount_add(n, &memcg->id.ref);
5076 static void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
5078 if (refcount_sub_and_test(n, &memcg->id.ref)) {
5079 mem_cgroup_id_remove(memcg);
5081 /* Memcg ID pins CSS */
5082 css_put(&memcg->css);
5086 static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
5088 mem_cgroup_id_put_many(memcg, 1);
5092 * mem_cgroup_from_id - look up a memcg from a memcg id
5093 * @id: the memcg id to look up
5095 * Caller must hold rcu_read_lock().
5097 struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
5099 WARN_ON_ONCE(!rcu_read_lock_held());
5100 return idr_find(&mem_cgroup_idr, id);
5103 static int alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5105 struct mem_cgroup_per_node *pn;
5108 * This routine is called against possible nodes.
5109 * But it's BUG to call kmalloc() against offline node.
5111 * TODO: this routine can waste much memory for nodes which will
5112 * never be onlined. It's better to use memory hotplug callback
5115 if (!node_state(node, N_NORMAL_MEMORY))
5117 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
5121 pn->lruvec_stat_local = alloc_percpu_gfp(struct lruvec_stat,
5122 GFP_KERNEL_ACCOUNT);
5123 if (!pn->lruvec_stat_local) {
5128 pn->lruvec_stat_cpu = alloc_percpu_gfp(struct batched_lruvec_stat,
5129 GFP_KERNEL_ACCOUNT);
5130 if (!pn->lruvec_stat_cpu) {
5131 free_percpu(pn->lruvec_stat_local);
5136 lruvec_init(&pn->lruvec);
5137 pn->usage_in_excess = 0;
5138 pn->on_tree = false;
5141 memcg->nodeinfo[node] = pn;
5145 static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5147 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
5152 free_percpu(pn->lruvec_stat_cpu);
5153 free_percpu(pn->lruvec_stat_local);
5157 static void __mem_cgroup_free(struct mem_cgroup *memcg)
5162 free_mem_cgroup_per_node_info(memcg, node);
5163 free_percpu(memcg->vmstats_percpu);
5167 static void mem_cgroup_free(struct mem_cgroup *memcg)
5171 memcg_wb_domain_exit(memcg);
5173 * Flush percpu lruvec stats to guarantee the value
5174 * correctness on parent's and all ancestor levels.
5176 for_each_online_cpu(cpu)
5177 memcg_flush_lruvec_page_state(memcg, cpu);
5178 __mem_cgroup_free(memcg);
5181 static struct mem_cgroup *mem_cgroup_alloc(void)
5183 struct mem_cgroup *memcg;
5186 int __maybe_unused i;
5187 long error = -ENOMEM;
5189 size = sizeof(struct mem_cgroup);
5190 size += nr_node_ids * sizeof(struct mem_cgroup_per_node *);
5192 memcg = kzalloc(size, GFP_KERNEL);
5194 return ERR_PTR(error);
5196 memcg->id.id = idr_alloc(&mem_cgroup_idr, NULL,
5197 1, MEM_CGROUP_ID_MAX,
5199 if (memcg->id.id < 0) {
5200 error = memcg->id.id;
5204 memcg->vmstats_percpu = alloc_percpu_gfp(struct memcg_vmstats_percpu,
5205 GFP_KERNEL_ACCOUNT);
5206 if (!memcg->vmstats_percpu)
5210 if (alloc_mem_cgroup_per_node_info(memcg, node))
5213 if (memcg_wb_domain_init(memcg, GFP_KERNEL))
5216 INIT_WORK(&memcg->high_work, high_work_func);
5217 INIT_LIST_HEAD(&memcg->oom_notify);
5218 mutex_init(&memcg->thresholds_lock);
5219 spin_lock_init(&memcg->move_lock);
5220 vmpressure_init(&memcg->vmpressure);
5221 INIT_LIST_HEAD(&memcg->event_list);
5222 spin_lock_init(&memcg->event_list_lock);
5223 memcg->socket_pressure = jiffies;
5224 #ifdef CONFIG_MEMCG_KMEM
5225 memcg->kmemcg_id = -1;
5226 INIT_LIST_HEAD(&memcg->objcg_list);
5228 #ifdef CONFIG_CGROUP_WRITEBACK
5229 INIT_LIST_HEAD(&memcg->cgwb_list);
5230 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5231 memcg->cgwb_frn[i].done =
5232 __WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
5234 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5235 spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
5236 INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
5237 memcg->deferred_split_queue.split_queue_len = 0;
5239 idr_replace(&mem_cgroup_idr, memcg, memcg->id.id);
5242 mem_cgroup_id_remove(memcg);
5243 __mem_cgroup_free(memcg);
5244 return ERR_PTR(error);
5247 static struct cgroup_subsys_state * __ref
5248 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
5250 struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
5251 struct mem_cgroup *memcg, *old_memcg;
5252 long error = -ENOMEM;
5254 old_memcg = set_active_memcg(parent);
5255 memcg = mem_cgroup_alloc();
5256 set_active_memcg(old_memcg);
5258 return ERR_CAST(memcg);
5260 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5261 memcg->soft_limit = PAGE_COUNTER_MAX;
5262 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5264 memcg->swappiness = mem_cgroup_swappiness(parent);
5265 memcg->oom_kill_disable = parent->oom_kill_disable;
5267 page_counter_init(&memcg->memory, &parent->memory);
5268 page_counter_init(&memcg->swap, &parent->swap);
5269 page_counter_init(&memcg->kmem, &parent->kmem);
5270 page_counter_init(&memcg->tcpmem, &parent->tcpmem);
5272 page_counter_init(&memcg->memory, NULL);
5273 page_counter_init(&memcg->swap, NULL);
5274 page_counter_init(&memcg->kmem, NULL);
5275 page_counter_init(&memcg->tcpmem, NULL);
5277 root_mem_cgroup = memcg;
5281 /* The following stuff does not apply to the root */
5282 error = memcg_online_kmem(memcg);
5286 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5287 static_branch_inc(&memcg_sockets_enabled_key);
5291 mem_cgroup_id_remove(memcg);
5292 mem_cgroup_free(memcg);
5293 return ERR_PTR(error);
5296 static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
5298 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5301 * A memcg must be visible for expand_shrinker_info()
5302 * by the time the maps are allocated. So, we allocate maps
5303 * here, when for_each_mem_cgroup() can't skip it.
5305 if (alloc_shrinker_info(memcg)) {
5306 mem_cgroup_id_remove(memcg);
5310 /* Online state pins memcg ID, memcg ID pins CSS */
5311 refcount_set(&memcg->id.ref, 1);
5316 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
5318 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5319 struct mem_cgroup_event *event, *tmp;
5322 * Unregister events and notify userspace.
5323 * Notify userspace about cgroup removing only after rmdir of cgroup
5324 * directory to avoid race between userspace and kernelspace.
5326 spin_lock(&memcg->event_list_lock);
5327 list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
5328 list_del_init(&event->list);
5329 schedule_work(&event->remove);
5331 spin_unlock(&memcg->event_list_lock);
5333 page_counter_set_min(&memcg->memory, 0);
5334 page_counter_set_low(&memcg->memory, 0);
5336 memcg_offline_kmem(memcg);
5337 reparent_shrinker_deferred(memcg);
5338 wb_memcg_offline(memcg);
5340 drain_all_stock(memcg);
5342 mem_cgroup_id_put(memcg);
5345 static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
5347 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5349 invalidate_reclaim_iterators(memcg);
5352 static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
5354 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5355 int __maybe_unused i;
5357 #ifdef CONFIG_CGROUP_WRITEBACK
5358 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5359 wb_wait_for_completion(&memcg->cgwb_frn[i].done);
5361 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5362 static_branch_dec(&memcg_sockets_enabled_key);
5364 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg->tcpmem_active)
5365 static_branch_dec(&memcg_sockets_enabled_key);
5367 vmpressure_cleanup(&memcg->vmpressure);
5368 cancel_work_sync(&memcg->high_work);
5369 mem_cgroup_remove_from_trees(memcg);
5370 free_shrinker_info(memcg);
5371 memcg_free_kmem(memcg);
5372 mem_cgroup_free(memcg);
5376 * mem_cgroup_css_reset - reset the states of a mem_cgroup
5377 * @css: the target css
5379 * Reset the states of the mem_cgroup associated with @css. This is
5380 * invoked when the userland requests disabling on the default hierarchy
5381 * but the memcg is pinned through dependency. The memcg should stop
5382 * applying policies and should revert to the vanilla state as it may be
5383 * made visible again.
5385 * The current implementation only resets the essential configurations.
5386 * This needs to be expanded to cover all the visible parts.
5388 static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
5390 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5392 page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
5393 page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
5394 page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
5395 page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
5396 page_counter_set_min(&memcg->memory, 0);
5397 page_counter_set_low(&memcg->memory, 0);
5398 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5399 memcg->soft_limit = PAGE_COUNTER_MAX;
5400 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5401 memcg_wb_domain_size_changed(memcg);
5404 static void mem_cgroup_css_rstat_flush(struct cgroup_subsys_state *css, int cpu)
5406 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5407 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
5408 struct memcg_vmstats_percpu *statc;
5412 statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
5414 for (i = 0; i < MEMCG_NR_STAT; i++) {
5416 * Collect the aggregated propagation counts of groups
5417 * below us. We're in a per-cpu loop here and this is
5418 * a global counter, so the first cycle will get them.
5420 delta = memcg->vmstats.state_pending[i];
5422 memcg->vmstats.state_pending[i] = 0;
5424 /* Add CPU changes on this level since the last flush */
5425 v = READ_ONCE(statc->state[i]);
5426 if (v != statc->state_prev[i]) {
5427 delta += v - statc->state_prev[i];
5428 statc->state_prev[i] = v;
5434 /* Aggregate counts on this level and propagate upwards */
5435 memcg->vmstats.state[i] += delta;
5437 parent->vmstats.state_pending[i] += delta;
5440 for (i = 0; i < NR_VM_EVENT_ITEMS; i++) {
5441 delta = memcg->vmstats.events_pending[i];
5443 memcg->vmstats.events_pending[i] = 0;
5445 v = READ_ONCE(statc->events[i]);
5446 if (v != statc->events_prev[i]) {
5447 delta += v - statc->events_prev[i];
5448 statc->events_prev[i] = v;
5454 memcg->vmstats.events[i] += delta;
5456 parent->vmstats.events_pending[i] += delta;
5461 /* Handlers for move charge at task migration. */
5462 static int mem_cgroup_do_precharge(unsigned long count)
5466 /* Try a single bulk charge without reclaim first, kswapd may wake */
5467 ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count);
5469 mc.precharge += count;
5473 /* Try charges one by one with reclaim, but do not retry */
5475 ret = try_charge(mc.to, GFP_KERNEL | __GFP_NORETRY, 1);
5489 enum mc_target_type {
5496 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5497 unsigned long addr, pte_t ptent)
5499 struct page *page = vm_normal_page(vma, addr, ptent);
5501 if (!page || !page_mapped(page))
5503 if (PageAnon(page)) {
5504 if (!(mc.flags & MOVE_ANON))
5507 if (!(mc.flags & MOVE_FILE))
5510 if (!get_page_unless_zero(page))
5516 #if defined(CONFIG_SWAP) || defined(CONFIG_DEVICE_PRIVATE)
5517 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5518 pte_t ptent, swp_entry_t *entry)
5520 struct page *page = NULL;
5521 swp_entry_t ent = pte_to_swp_entry(ptent);
5523 if (!(mc.flags & MOVE_ANON))
5527 * Handle MEMORY_DEVICE_PRIVATE which are ZONE_DEVICE page belonging to
5528 * a device and because they are not accessible by CPU they are store
5529 * as special swap entry in the CPU page table.
5531 if (is_device_private_entry(ent)) {
5532 page = pfn_swap_entry_to_page(ent);
5534 * MEMORY_DEVICE_PRIVATE means ZONE_DEVICE page and which have
5535 * a refcount of 1 when free (unlike normal page)
5537 if (!page_ref_add_unless(page, 1, 1))
5542 if (non_swap_entry(ent))
5546 * Because lookup_swap_cache() updates some statistics counter,
5547 * we call find_get_page() with swapper_space directly.
5549 page = find_get_page(swap_address_space(ent), swp_offset(ent));
5550 entry->val = ent.val;
5555 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5556 pte_t ptent, swp_entry_t *entry)
5562 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5563 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5565 if (!vma->vm_file) /* anonymous vma */
5567 if (!(mc.flags & MOVE_FILE))
5570 /* page is moved even if it's not RSS of this task(page-faulted). */
5571 /* shmem/tmpfs may report page out on swap: account for that too. */
5572 return find_get_incore_page(vma->vm_file->f_mapping,
5573 linear_page_index(vma, addr));
5577 * mem_cgroup_move_account - move account of the page
5579 * @compound: charge the page as compound or small page
5580 * @from: mem_cgroup which the page is moved from.
5581 * @to: mem_cgroup which the page is moved to. @from != @to.
5583 * The caller must make sure the page is not on LRU (isolate_page() is useful.)
5585 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
5588 static int mem_cgroup_move_account(struct page *page,
5590 struct mem_cgroup *from,
5591 struct mem_cgroup *to)
5593 struct lruvec *from_vec, *to_vec;
5594 struct pglist_data *pgdat;
5595 unsigned int nr_pages = compound ? thp_nr_pages(page) : 1;
5598 VM_BUG_ON(from == to);
5599 VM_BUG_ON_PAGE(PageLRU(page), page);
5600 VM_BUG_ON(compound && !PageTransHuge(page));
5603 * Prevent mem_cgroup_migrate() from looking at
5604 * page's memory cgroup of its source page while we change it.
5607 if (!trylock_page(page))
5611 if (page_memcg(page) != from)
5614 pgdat = page_pgdat(page);
5615 from_vec = mem_cgroup_lruvec(from, pgdat);
5616 to_vec = mem_cgroup_lruvec(to, pgdat);
5618 lock_page_memcg(page);
5620 if (PageAnon(page)) {
5621 if (page_mapped(page)) {
5622 __mod_lruvec_state(from_vec, NR_ANON_MAPPED, -nr_pages);
5623 __mod_lruvec_state(to_vec, NR_ANON_MAPPED, nr_pages);
5624 if (PageTransHuge(page)) {
5625 __mod_lruvec_state(from_vec, NR_ANON_THPS,
5627 __mod_lruvec_state(to_vec, NR_ANON_THPS,
5632 __mod_lruvec_state(from_vec, NR_FILE_PAGES, -nr_pages);
5633 __mod_lruvec_state(to_vec, NR_FILE_PAGES, nr_pages);
5635 if (PageSwapBacked(page)) {
5636 __mod_lruvec_state(from_vec, NR_SHMEM, -nr_pages);
5637 __mod_lruvec_state(to_vec, NR_SHMEM, nr_pages);
5640 if (page_mapped(page)) {
5641 __mod_lruvec_state(from_vec, NR_FILE_MAPPED, -nr_pages);
5642 __mod_lruvec_state(to_vec, NR_FILE_MAPPED, nr_pages);
5645 if (PageDirty(page)) {
5646 struct address_space *mapping = page_mapping(page);
5648 if (mapping_can_writeback(mapping)) {
5649 __mod_lruvec_state(from_vec, NR_FILE_DIRTY,
5651 __mod_lruvec_state(to_vec, NR_FILE_DIRTY,
5657 if (PageWriteback(page)) {
5658 __mod_lruvec_state(from_vec, NR_WRITEBACK, -nr_pages);
5659 __mod_lruvec_state(to_vec, NR_WRITEBACK, nr_pages);
5663 * All state has been migrated, let's switch to the new memcg.
5665 * It is safe to change page's memcg here because the page
5666 * is referenced, charged, isolated, and locked: we can't race
5667 * with (un)charging, migration, LRU putback, or anything else
5668 * that would rely on a stable page's memory cgroup.
5670 * Note that lock_page_memcg is a memcg lock, not a page lock,
5671 * to save space. As soon as we switch page's memory cgroup to a
5672 * new memcg that isn't locked, the above state can change
5673 * concurrently again. Make sure we're truly done with it.
5678 css_put(&from->css);
5680 page->memcg_data = (unsigned long)to;
5682 __unlock_page_memcg(from);
5686 local_irq_disable();
5687 mem_cgroup_charge_statistics(to, page, nr_pages);
5688 memcg_check_events(to, page);
5689 mem_cgroup_charge_statistics(from, page, -nr_pages);
5690 memcg_check_events(from, page);
5699 * get_mctgt_type - get target type of moving charge
5700 * @vma: the vma the pte to be checked belongs
5701 * @addr: the address corresponding to the pte to be checked
5702 * @ptent: the pte to be checked
5703 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5706 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5707 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5708 * move charge. if @target is not NULL, the page is stored in target->page
5709 * with extra refcnt got(Callers should handle it).
5710 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5711 * target for charge migration. if @target is not NULL, the entry is stored
5713 * 3(MC_TARGET_DEVICE): like MC_TARGET_PAGE but page is MEMORY_DEVICE_PRIVATE
5714 * (so ZONE_DEVICE page and thus not on the lru).
5715 * For now we such page is charge like a regular page would be as for all
5716 * intent and purposes it is just special memory taking the place of a
5719 * See Documentations/vm/hmm.txt and include/linux/hmm.h
5721 * Called with pte lock held.
5724 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
5725 unsigned long addr, pte_t ptent, union mc_target *target)
5727 struct page *page = NULL;
5728 enum mc_target_type ret = MC_TARGET_NONE;
5729 swp_entry_t ent = { .val = 0 };
5731 if (pte_present(ptent))
5732 page = mc_handle_present_pte(vma, addr, ptent);
5733 else if (is_swap_pte(ptent))
5734 page = mc_handle_swap_pte(vma, ptent, &ent);
5735 else if (pte_none(ptent))
5736 page = mc_handle_file_pte(vma, addr, ptent, &ent);
5738 if (!page && !ent.val)
5742 * Do only loose check w/o serialization.
5743 * mem_cgroup_move_account() checks the page is valid or
5744 * not under LRU exclusion.
5746 if (page_memcg(page) == mc.from) {
5747 ret = MC_TARGET_PAGE;
5748 if (is_device_private_page(page))
5749 ret = MC_TARGET_DEVICE;
5751 target->page = page;
5753 if (!ret || !target)
5757 * There is a swap entry and a page doesn't exist or isn't charged.
5758 * But we cannot move a tail-page in a THP.
5760 if (ent.val && !ret && (!page || !PageTransCompound(page)) &&
5761 mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
5762 ret = MC_TARGET_SWAP;
5769 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5771 * We don't consider PMD mapped swapping or file mapped pages because THP does
5772 * not support them for now.
5773 * Caller should make sure that pmd_trans_huge(pmd) is true.
5775 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5776 unsigned long addr, pmd_t pmd, union mc_target *target)
5778 struct page *page = NULL;
5779 enum mc_target_type ret = MC_TARGET_NONE;
5781 if (unlikely(is_swap_pmd(pmd))) {
5782 VM_BUG_ON(thp_migration_supported() &&
5783 !is_pmd_migration_entry(pmd));
5786 page = pmd_page(pmd);
5787 VM_BUG_ON_PAGE(!page || !PageHead(page), page);
5788 if (!(mc.flags & MOVE_ANON))
5790 if (page_memcg(page) == mc.from) {
5791 ret = MC_TARGET_PAGE;
5794 target->page = page;
5800 static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5801 unsigned long addr, pmd_t pmd, union mc_target *target)
5803 return MC_TARGET_NONE;
5807 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5808 unsigned long addr, unsigned long end,
5809 struct mm_walk *walk)
5811 struct vm_area_struct *vma = walk->vma;
5815 ptl = pmd_trans_huge_lock(pmd, vma);
5818 * Note their can not be MC_TARGET_DEVICE for now as we do not
5819 * support transparent huge page with MEMORY_DEVICE_PRIVATE but
5820 * this might change.
5822 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
5823 mc.precharge += HPAGE_PMD_NR;
5828 if (pmd_trans_unstable(pmd))
5830 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5831 for (; addr != end; pte++, addr += PAGE_SIZE)
5832 if (get_mctgt_type(vma, addr, *pte, NULL))
5833 mc.precharge++; /* increment precharge temporarily */
5834 pte_unmap_unlock(pte - 1, ptl);
5840 static const struct mm_walk_ops precharge_walk_ops = {
5841 .pmd_entry = mem_cgroup_count_precharge_pte_range,
5844 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5846 unsigned long precharge;
5849 walk_page_range(mm, 0, mm->highest_vm_end, &precharge_walk_ops, NULL);
5850 mmap_read_unlock(mm);
5852 precharge = mc.precharge;
5858 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5860 unsigned long precharge = mem_cgroup_count_precharge(mm);
5862 VM_BUG_ON(mc.moving_task);
5863 mc.moving_task = current;
5864 return mem_cgroup_do_precharge(precharge);
5867 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5868 static void __mem_cgroup_clear_mc(void)
5870 struct mem_cgroup *from = mc.from;
5871 struct mem_cgroup *to = mc.to;
5873 /* we must uncharge all the leftover precharges from mc.to */
5875 cancel_charge(mc.to, mc.precharge);
5879 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5880 * we must uncharge here.
5882 if (mc.moved_charge) {
5883 cancel_charge(mc.from, mc.moved_charge);
5884 mc.moved_charge = 0;
5886 /* we must fixup refcnts and charges */
5887 if (mc.moved_swap) {
5888 /* uncharge swap account from the old cgroup */
5889 if (!mem_cgroup_is_root(mc.from))
5890 page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
5892 mem_cgroup_id_put_many(mc.from, mc.moved_swap);
5895 * we charged both to->memory and to->memsw, so we
5896 * should uncharge to->memory.
5898 if (!mem_cgroup_is_root(mc.to))
5899 page_counter_uncharge(&mc.to->memory, mc.moved_swap);
5903 memcg_oom_recover(from);
5904 memcg_oom_recover(to);
5905 wake_up_all(&mc.waitq);
5908 static void mem_cgroup_clear_mc(void)
5910 struct mm_struct *mm = mc.mm;
5913 * we must clear moving_task before waking up waiters at the end of
5916 mc.moving_task = NULL;
5917 __mem_cgroup_clear_mc();
5918 spin_lock(&mc.lock);
5922 spin_unlock(&mc.lock);
5927 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
5929 struct cgroup_subsys_state *css;
5930 struct mem_cgroup *memcg = NULL; /* unneeded init to make gcc happy */
5931 struct mem_cgroup *from;
5932 struct task_struct *leader, *p;
5933 struct mm_struct *mm;
5934 unsigned long move_flags;
5937 /* charge immigration isn't supported on the default hierarchy */
5938 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
5942 * Multi-process migrations only happen on the default hierarchy
5943 * where charge immigration is not used. Perform charge
5944 * immigration if @tset contains a leader and whine if there are
5948 cgroup_taskset_for_each_leader(leader, css, tset) {
5951 memcg = mem_cgroup_from_css(css);
5957 * We are now committed to this value whatever it is. Changes in this
5958 * tunable will only affect upcoming migrations, not the current one.
5959 * So we need to save it, and keep it going.
5961 move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
5965 from = mem_cgroup_from_task(p);
5967 VM_BUG_ON(from == memcg);
5969 mm = get_task_mm(p);
5972 /* We move charges only when we move a owner of the mm */
5973 if (mm->owner == p) {
5976 VM_BUG_ON(mc.precharge);
5977 VM_BUG_ON(mc.moved_charge);
5978 VM_BUG_ON(mc.moved_swap);
5980 spin_lock(&mc.lock);
5984 mc.flags = move_flags;
5985 spin_unlock(&mc.lock);
5986 /* We set mc.moving_task later */
5988 ret = mem_cgroup_precharge_mc(mm);
5990 mem_cgroup_clear_mc();
5997 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6000 mem_cgroup_clear_mc();
6003 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
6004 unsigned long addr, unsigned long end,
6005 struct mm_walk *walk)
6008 struct vm_area_struct *vma = walk->vma;
6011 enum mc_target_type target_type;
6012 union mc_target target;
6015 ptl = pmd_trans_huge_lock(pmd, vma);
6017 if (mc.precharge < HPAGE_PMD_NR) {
6021 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
6022 if (target_type == MC_TARGET_PAGE) {
6024 if (!isolate_lru_page(page)) {
6025 if (!mem_cgroup_move_account(page, true,
6027 mc.precharge -= HPAGE_PMD_NR;
6028 mc.moved_charge += HPAGE_PMD_NR;
6030 putback_lru_page(page);
6033 } else if (target_type == MC_TARGET_DEVICE) {
6035 if (!mem_cgroup_move_account(page, true,
6037 mc.precharge -= HPAGE_PMD_NR;
6038 mc.moved_charge += HPAGE_PMD_NR;
6046 if (pmd_trans_unstable(pmd))
6049 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6050 for (; addr != end; addr += PAGE_SIZE) {
6051 pte_t ptent = *(pte++);
6052 bool device = false;
6058 switch (get_mctgt_type(vma, addr, ptent, &target)) {
6059 case MC_TARGET_DEVICE:
6062 case MC_TARGET_PAGE:
6065 * We can have a part of the split pmd here. Moving it
6066 * can be done but it would be too convoluted so simply
6067 * ignore such a partial THP and keep it in original
6068 * memcg. There should be somebody mapping the head.
6070 if (PageTransCompound(page))
6072 if (!device && isolate_lru_page(page))
6074 if (!mem_cgroup_move_account(page, false,
6077 /* we uncharge from mc.from later. */
6081 putback_lru_page(page);
6082 put: /* get_mctgt_type() gets the page */
6085 case MC_TARGET_SWAP:
6087 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
6089 mem_cgroup_id_get_many(mc.to, 1);
6090 /* we fixup other refcnts and charges later. */
6098 pte_unmap_unlock(pte - 1, ptl);
6103 * We have consumed all precharges we got in can_attach().
6104 * We try charge one by one, but don't do any additional
6105 * charges to mc.to if we have failed in charge once in attach()
6108 ret = mem_cgroup_do_precharge(1);
6116 static const struct mm_walk_ops charge_walk_ops = {
6117 .pmd_entry = mem_cgroup_move_charge_pte_range,
6120 static void mem_cgroup_move_charge(void)
6122 lru_add_drain_all();
6124 * Signal lock_page_memcg() to take the memcg's move_lock
6125 * while we're moving its pages to another memcg. Then wait
6126 * for already started RCU-only updates to finish.
6128 atomic_inc(&mc.from->moving_account);
6131 if (unlikely(!mmap_read_trylock(mc.mm))) {
6133 * Someone who are holding the mmap_lock might be waiting in
6134 * waitq. So we cancel all extra charges, wake up all waiters,
6135 * and retry. Because we cancel precharges, we might not be able
6136 * to move enough charges, but moving charge is a best-effort
6137 * feature anyway, so it wouldn't be a big problem.
6139 __mem_cgroup_clear_mc();
6144 * When we have consumed all precharges and failed in doing
6145 * additional charge, the page walk just aborts.
6147 walk_page_range(mc.mm, 0, mc.mm->highest_vm_end, &charge_walk_ops,
6150 mmap_read_unlock(mc.mm);
6151 atomic_dec(&mc.from->moving_account);
6154 static void mem_cgroup_move_task(void)
6157 mem_cgroup_move_charge();
6158 mem_cgroup_clear_mc();
6161 #else /* !CONFIG_MMU */
6162 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
6166 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6169 static void mem_cgroup_move_task(void)
6174 static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
6176 if (value == PAGE_COUNTER_MAX)
6177 seq_puts(m, "max\n");
6179 seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
6184 static u64 memory_current_read(struct cgroup_subsys_state *css,
6187 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6189 return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
6192 static int memory_min_show(struct seq_file *m, void *v)
6194 return seq_puts_memcg_tunable(m,
6195 READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
6198 static ssize_t memory_min_write(struct kernfs_open_file *of,
6199 char *buf, size_t nbytes, loff_t off)
6201 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6205 buf = strstrip(buf);
6206 err = page_counter_memparse(buf, "max", &min);
6210 page_counter_set_min(&memcg->memory, min);
6215 static int memory_low_show(struct seq_file *m, void *v)
6217 return seq_puts_memcg_tunable(m,
6218 READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
6221 static ssize_t memory_low_write(struct kernfs_open_file *of,
6222 char *buf, size_t nbytes, loff_t off)
6224 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6228 buf = strstrip(buf);
6229 err = page_counter_memparse(buf, "max", &low);
6233 page_counter_set_low(&memcg->memory, low);
6238 static int memory_high_show(struct seq_file *m, void *v)
6240 return seq_puts_memcg_tunable(m,
6241 READ_ONCE(mem_cgroup_from_seq(m)->memory.high));
6244 static ssize_t memory_high_write(struct kernfs_open_file *of,
6245 char *buf, size_t nbytes, loff_t off)
6247 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6248 unsigned int nr_retries = MAX_RECLAIM_RETRIES;
6249 bool drained = false;
6253 buf = strstrip(buf);
6254 err = page_counter_memparse(buf, "max", &high);
6258 page_counter_set_high(&memcg->memory, high);
6261 unsigned long nr_pages = page_counter_read(&memcg->memory);
6262 unsigned long reclaimed;
6264 if (nr_pages <= high)
6267 if (signal_pending(current))
6271 drain_all_stock(memcg);
6276 reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
6279 if (!reclaimed && !nr_retries--)
6283 memcg_wb_domain_size_changed(memcg);
6287 static int memory_max_show(struct seq_file *m, void *v)
6289 return seq_puts_memcg_tunable(m,
6290 READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
6293 static ssize_t memory_max_write(struct kernfs_open_file *of,
6294 char *buf, size_t nbytes, loff_t off)
6296 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6297 unsigned int nr_reclaims = MAX_RECLAIM_RETRIES;
6298 bool drained = false;
6302 buf = strstrip(buf);
6303 err = page_counter_memparse(buf, "max", &max);
6307 xchg(&memcg->memory.max, max);
6310 unsigned long nr_pages = page_counter_read(&memcg->memory);
6312 if (nr_pages <= max)
6315 if (signal_pending(current))
6319 drain_all_stock(memcg);
6325 if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
6331 memcg_memory_event(memcg, MEMCG_OOM);
6332 if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
6336 memcg_wb_domain_size_changed(memcg);
6340 static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
6342 seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
6343 seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
6344 seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
6345 seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
6346 seq_printf(m, "oom_kill %lu\n",
6347 atomic_long_read(&events[MEMCG_OOM_KILL]));
6350 static int memory_events_show(struct seq_file *m, void *v)
6352 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6354 __memory_events_show(m, memcg->memory_events);
6358 static int memory_events_local_show(struct seq_file *m, void *v)
6360 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6362 __memory_events_show(m, memcg->memory_events_local);
6366 static int memory_stat_show(struct seq_file *m, void *v)
6368 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6371 buf = memory_stat_format(memcg);
6380 static inline unsigned long lruvec_page_state_output(struct lruvec *lruvec,
6383 return lruvec_page_state(lruvec, item) * memcg_page_state_unit(item);
6386 static int memory_numa_stat_show(struct seq_file *m, void *v)
6389 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6391 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
6394 if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS)
6397 seq_printf(m, "%s", memory_stats[i].name);
6398 for_each_node_state(nid, N_MEMORY) {
6400 struct lruvec *lruvec;
6402 lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
6403 size = lruvec_page_state_output(lruvec,
6404 memory_stats[i].idx);
6405 seq_printf(m, " N%d=%llu", nid, size);
6414 static int memory_oom_group_show(struct seq_file *m, void *v)
6416 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6418 seq_printf(m, "%d\n", memcg->oom_group);
6423 static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
6424 char *buf, size_t nbytes, loff_t off)
6426 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6429 buf = strstrip(buf);
6433 ret = kstrtoint(buf, 0, &oom_group);
6437 if (oom_group != 0 && oom_group != 1)
6440 memcg->oom_group = oom_group;
6445 static struct cftype memory_files[] = {
6448 .flags = CFTYPE_NOT_ON_ROOT,
6449 .read_u64 = memory_current_read,
6453 .flags = CFTYPE_NOT_ON_ROOT,
6454 .seq_show = memory_min_show,
6455 .write = memory_min_write,
6459 .flags = CFTYPE_NOT_ON_ROOT,
6460 .seq_show = memory_low_show,
6461 .write = memory_low_write,
6465 .flags = CFTYPE_NOT_ON_ROOT,
6466 .seq_show = memory_high_show,
6467 .write = memory_high_write,
6471 .flags = CFTYPE_NOT_ON_ROOT,
6472 .seq_show = memory_max_show,
6473 .write = memory_max_write,
6477 .flags = CFTYPE_NOT_ON_ROOT,
6478 .file_offset = offsetof(struct mem_cgroup, events_file),
6479 .seq_show = memory_events_show,
6482 .name = "events.local",
6483 .flags = CFTYPE_NOT_ON_ROOT,
6484 .file_offset = offsetof(struct mem_cgroup, events_local_file),
6485 .seq_show = memory_events_local_show,
6489 .seq_show = memory_stat_show,
6493 .name = "numa_stat",
6494 .seq_show = memory_numa_stat_show,
6498 .name = "oom.group",
6499 .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
6500 .seq_show = memory_oom_group_show,
6501 .write = memory_oom_group_write,
6506 struct cgroup_subsys memory_cgrp_subsys = {
6507 .css_alloc = mem_cgroup_css_alloc,
6508 .css_online = mem_cgroup_css_online,
6509 .css_offline = mem_cgroup_css_offline,
6510 .css_released = mem_cgroup_css_released,
6511 .css_free = mem_cgroup_css_free,
6512 .css_reset = mem_cgroup_css_reset,
6513 .css_rstat_flush = mem_cgroup_css_rstat_flush,
6514 .can_attach = mem_cgroup_can_attach,
6515 .cancel_attach = mem_cgroup_cancel_attach,
6516 .post_attach = mem_cgroup_move_task,
6517 .dfl_cftypes = memory_files,
6518 .legacy_cftypes = mem_cgroup_legacy_files,
6523 * This function calculates an individual cgroup's effective
6524 * protection which is derived from its own memory.min/low, its
6525 * parent's and siblings' settings, as well as the actual memory
6526 * distribution in the tree.
6528 * The following rules apply to the effective protection values:
6530 * 1. At the first level of reclaim, effective protection is equal to
6531 * the declared protection in memory.min and memory.low.
6533 * 2. To enable safe delegation of the protection configuration, at
6534 * subsequent levels the effective protection is capped to the
6535 * parent's effective protection.
6537 * 3. To make complex and dynamic subtrees easier to configure, the
6538 * user is allowed to overcommit the declared protection at a given
6539 * level. If that is the case, the parent's effective protection is
6540 * distributed to the children in proportion to how much protection
6541 * they have declared and how much of it they are utilizing.
6543 * This makes distribution proportional, but also work-conserving:
6544 * if one cgroup claims much more protection than it uses memory,
6545 * the unused remainder is available to its siblings.
6547 * 4. Conversely, when the declared protection is undercommitted at a
6548 * given level, the distribution of the larger parental protection
6549 * budget is NOT proportional. A cgroup's protection from a sibling
6550 * is capped to its own memory.min/low setting.
6552 * 5. However, to allow protecting recursive subtrees from each other
6553 * without having to declare each individual cgroup's fixed share
6554 * of the ancestor's claim to protection, any unutilized -
6555 * "floating" - protection from up the tree is distributed in
6556 * proportion to each cgroup's *usage*. This makes the protection
6557 * neutral wrt sibling cgroups and lets them compete freely over
6558 * the shared parental protection budget, but it protects the
6559 * subtree as a whole from neighboring subtrees.
6561 * Note that 4. and 5. are not in conflict: 4. is about protecting
6562 * against immediate siblings whereas 5. is about protecting against
6563 * neighboring subtrees.
6565 static unsigned long effective_protection(unsigned long usage,
6566 unsigned long parent_usage,
6567 unsigned long setting,
6568 unsigned long parent_effective,
6569 unsigned long siblings_protected)
6571 unsigned long protected;
6574 protected = min(usage, setting);
6576 * If all cgroups at this level combined claim and use more
6577 * protection then what the parent affords them, distribute
6578 * shares in proportion to utilization.
6580 * We are using actual utilization rather than the statically
6581 * claimed protection in order to be work-conserving: claimed
6582 * but unused protection is available to siblings that would
6583 * otherwise get a smaller chunk than what they claimed.
6585 if (siblings_protected > parent_effective)
6586 return protected * parent_effective / siblings_protected;
6589 * Ok, utilized protection of all children is within what the
6590 * parent affords them, so we know whatever this child claims
6591 * and utilizes is effectively protected.
6593 * If there is unprotected usage beyond this value, reclaim
6594 * will apply pressure in proportion to that amount.
6596 * If there is unutilized protection, the cgroup will be fully
6597 * shielded from reclaim, but we do return a smaller value for
6598 * protection than what the group could enjoy in theory. This
6599 * is okay. With the overcommit distribution above, effective
6600 * protection is always dependent on how memory is actually
6601 * consumed among the siblings anyway.
6606 * If the children aren't claiming (all of) the protection
6607 * afforded to them by the parent, distribute the remainder in
6608 * proportion to the (unprotected) memory of each cgroup. That
6609 * way, cgroups that aren't explicitly prioritized wrt each
6610 * other compete freely over the allowance, but they are
6611 * collectively protected from neighboring trees.
6613 * We're using unprotected memory for the weight so that if
6614 * some cgroups DO claim explicit protection, we don't protect
6615 * the same bytes twice.
6617 * Check both usage and parent_usage against the respective
6618 * protected values. One should imply the other, but they
6619 * aren't read atomically - make sure the division is sane.
6621 if (!(cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT))
6623 if (parent_effective > siblings_protected &&
6624 parent_usage > siblings_protected &&
6625 usage > protected) {
6626 unsigned long unclaimed;
6628 unclaimed = parent_effective - siblings_protected;
6629 unclaimed *= usage - protected;
6630 unclaimed /= parent_usage - siblings_protected;
6639 * mem_cgroup_calculate_protection - check if memory consumption is in the normal range
6640 * @root: the top ancestor of the sub-tree being checked
6641 * @memcg: the memory cgroup to check
6643 * WARNING: This function is not stateless! It can only be used as part
6644 * of a top-down tree iteration, not for isolated queries.
6646 void mem_cgroup_calculate_protection(struct mem_cgroup *root,
6647 struct mem_cgroup *memcg)
6649 unsigned long usage, parent_usage;
6650 struct mem_cgroup *parent;
6652 if (mem_cgroup_disabled())
6656 root = root_mem_cgroup;
6659 * Effective values of the reclaim targets are ignored so they
6660 * can be stale. Have a look at mem_cgroup_protection for more
6662 * TODO: calculation should be more robust so that we do not need
6663 * that special casing.
6668 usage = page_counter_read(&memcg->memory);
6672 parent = parent_mem_cgroup(memcg);
6673 /* No parent means a non-hierarchical mode on v1 memcg */
6677 if (parent == root) {
6678 memcg->memory.emin = READ_ONCE(memcg->memory.min);
6679 memcg->memory.elow = READ_ONCE(memcg->memory.low);
6683 parent_usage = page_counter_read(&parent->memory);
6685 WRITE_ONCE(memcg->memory.emin, effective_protection(usage, parent_usage,
6686 READ_ONCE(memcg->memory.min),
6687 READ_ONCE(parent->memory.emin),
6688 atomic_long_read(&parent->memory.children_min_usage)));
6690 WRITE_ONCE(memcg->memory.elow, effective_protection(usage, parent_usage,
6691 READ_ONCE(memcg->memory.low),
6692 READ_ONCE(parent->memory.elow),
6693 atomic_long_read(&parent->memory.children_low_usage)));
6696 static int __mem_cgroup_charge(struct page *page, struct mem_cgroup *memcg,
6699 unsigned int nr_pages = thp_nr_pages(page);
6702 ret = try_charge(memcg, gfp, nr_pages);
6706 css_get(&memcg->css);
6707 commit_charge(page, memcg);
6709 local_irq_disable();
6710 mem_cgroup_charge_statistics(memcg, page, nr_pages);
6711 memcg_check_events(memcg, page);
6718 * mem_cgroup_charge - charge a newly allocated page to a cgroup
6719 * @page: page to charge
6720 * @mm: mm context of the victim
6721 * @gfp_mask: reclaim mode
6723 * Try to charge @page to the memcg that @mm belongs to, reclaiming
6724 * pages according to @gfp_mask if necessary. if @mm is NULL, try to
6725 * charge to the active memcg.
6727 * Do not use this for pages allocated for swapin.
6729 * Returns 0 on success. Otherwise, an error code is returned.
6731 int mem_cgroup_charge(struct page *page, struct mm_struct *mm, gfp_t gfp_mask)
6733 struct mem_cgroup *memcg;
6736 if (mem_cgroup_disabled())
6739 memcg = get_mem_cgroup_from_mm(mm);
6740 ret = __mem_cgroup_charge(page, memcg, gfp_mask);
6741 css_put(&memcg->css);
6747 * mem_cgroup_swapin_charge_page - charge a newly allocated page for swapin
6748 * @page: page to charge
6749 * @mm: mm context of the victim
6750 * @gfp: reclaim mode
6751 * @entry: swap entry for which the page is allocated
6753 * This function charges a page allocated for swapin. Please call this before
6754 * adding the page to the swapcache.
6756 * Returns 0 on success. Otherwise, an error code is returned.
6758 int mem_cgroup_swapin_charge_page(struct page *page, struct mm_struct *mm,
6759 gfp_t gfp, swp_entry_t entry)
6761 struct mem_cgroup *memcg;
6765 if (mem_cgroup_disabled())
6768 id = lookup_swap_cgroup_id(entry);
6770 memcg = mem_cgroup_from_id(id);
6771 if (!memcg || !css_tryget_online(&memcg->css))
6772 memcg = get_mem_cgroup_from_mm(mm);
6775 ret = __mem_cgroup_charge(page, memcg, gfp);
6777 css_put(&memcg->css);
6782 * mem_cgroup_swapin_uncharge_swap - uncharge swap slot
6783 * @entry: swap entry for which the page is charged
6785 * Call this function after successfully adding the charged page to swapcache.
6787 * Note: This function assumes the page for which swap slot is being uncharged
6790 void mem_cgroup_swapin_uncharge_swap(swp_entry_t entry)
6793 * Cgroup1's unified memory+swap counter has been charged with the
6794 * new swapcache page, finish the transfer by uncharging the swap
6795 * slot. The swap slot would also get uncharged when it dies, but
6796 * it can stick around indefinitely and we'd count the page twice
6799 * Cgroup2 has separate resource counters for memory and swap,
6800 * so this is a non-issue here. Memory and swap charge lifetimes
6801 * correspond 1:1 to page and swap slot lifetimes: we charge the
6802 * page to memory here, and uncharge swap when the slot is freed.
6804 if (!mem_cgroup_disabled() && do_memsw_account()) {
6806 * The swap entry might not get freed for a long time,
6807 * let's not wait for it. The page already received a
6808 * memory+swap charge, drop the swap entry duplicate.
6810 mem_cgroup_uncharge_swap(entry, 1);
6814 struct uncharge_gather {
6815 struct mem_cgroup *memcg;
6816 unsigned long nr_memory;
6817 unsigned long pgpgout;
6818 unsigned long nr_kmem;
6819 struct page *dummy_page;
6822 static inline void uncharge_gather_clear(struct uncharge_gather *ug)
6824 memset(ug, 0, sizeof(*ug));
6827 static void uncharge_batch(const struct uncharge_gather *ug)
6829 unsigned long flags;
6831 if (ug->nr_memory) {
6832 page_counter_uncharge(&ug->memcg->memory, ug->nr_memory);
6833 if (do_memsw_account())
6834 page_counter_uncharge(&ug->memcg->memsw, ug->nr_memory);
6835 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && ug->nr_kmem)
6836 page_counter_uncharge(&ug->memcg->kmem, ug->nr_kmem);
6837 memcg_oom_recover(ug->memcg);
6840 local_irq_save(flags);
6841 __count_memcg_events(ug->memcg, PGPGOUT, ug->pgpgout);
6842 __this_cpu_add(ug->memcg->vmstats_percpu->nr_page_events, ug->nr_memory);
6843 memcg_check_events(ug->memcg, ug->dummy_page);
6844 local_irq_restore(flags);
6846 /* drop reference from uncharge_page */
6847 css_put(&ug->memcg->css);
6850 static void uncharge_page(struct page *page, struct uncharge_gather *ug)
6852 unsigned long nr_pages;
6853 struct mem_cgroup *memcg;
6854 struct obj_cgroup *objcg;
6855 bool use_objcg = PageMemcgKmem(page);
6857 VM_BUG_ON_PAGE(PageLRU(page), page);
6860 * Nobody should be changing or seriously looking at
6861 * page memcg or objcg at this point, we have fully
6862 * exclusive access to the page.
6865 objcg = __page_objcg(page);
6867 * This get matches the put at the end of the function and
6868 * kmem pages do not hold memcg references anymore.
6870 memcg = get_mem_cgroup_from_objcg(objcg);
6872 memcg = __page_memcg(page);
6878 if (ug->memcg != memcg) {
6881 uncharge_gather_clear(ug);
6884 ug->dummy_page = page;
6886 /* pairs with css_put in uncharge_batch */
6887 css_get(&memcg->css);
6890 nr_pages = compound_nr(page);
6893 ug->nr_memory += nr_pages;
6894 ug->nr_kmem += nr_pages;
6896 page->memcg_data = 0;
6897 obj_cgroup_put(objcg);
6899 /* LRU pages aren't accounted at the root level */
6900 if (!mem_cgroup_is_root(memcg))
6901 ug->nr_memory += nr_pages;
6904 page->memcg_data = 0;
6907 css_put(&memcg->css);
6911 * mem_cgroup_uncharge - uncharge a page
6912 * @page: page to uncharge
6914 * Uncharge a page previously charged with mem_cgroup_charge().
6916 void mem_cgroup_uncharge(struct page *page)
6918 struct uncharge_gather ug;
6920 if (mem_cgroup_disabled())
6923 /* Don't touch page->lru of any random page, pre-check: */
6924 if (!page_memcg(page))
6927 uncharge_gather_clear(&ug);
6928 uncharge_page(page, &ug);
6929 uncharge_batch(&ug);
6933 * mem_cgroup_uncharge_list - uncharge a list of page
6934 * @page_list: list of pages to uncharge
6936 * Uncharge a list of pages previously charged with
6937 * mem_cgroup_charge().
6939 void mem_cgroup_uncharge_list(struct list_head *page_list)
6941 struct uncharge_gather ug;
6944 if (mem_cgroup_disabled())
6947 uncharge_gather_clear(&ug);
6948 list_for_each_entry(page, page_list, lru)
6949 uncharge_page(page, &ug);
6951 uncharge_batch(&ug);
6955 * mem_cgroup_migrate - charge a page's replacement
6956 * @oldpage: currently circulating page
6957 * @newpage: replacement page
6959 * Charge @newpage as a replacement page for @oldpage. @oldpage will
6960 * be uncharged upon free.
6962 * Both pages must be locked, @newpage->mapping must be set up.
6964 void mem_cgroup_migrate(struct page *oldpage, struct page *newpage)
6966 struct mem_cgroup *memcg;
6967 unsigned int nr_pages;
6968 unsigned long flags;
6970 VM_BUG_ON_PAGE(!PageLocked(oldpage), oldpage);
6971 VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
6972 VM_BUG_ON_PAGE(PageAnon(oldpage) != PageAnon(newpage), newpage);
6973 VM_BUG_ON_PAGE(PageTransHuge(oldpage) != PageTransHuge(newpage),
6976 if (mem_cgroup_disabled())
6979 /* Page cache replacement: new page already charged? */
6980 if (page_memcg(newpage))
6983 memcg = page_memcg(oldpage);
6984 VM_WARN_ON_ONCE_PAGE(!memcg, oldpage);
6988 /* Force-charge the new page. The old one will be freed soon */
6989 nr_pages = thp_nr_pages(newpage);
6991 if (!mem_cgroup_is_root(memcg)) {
6992 page_counter_charge(&memcg->memory, nr_pages);
6993 if (do_memsw_account())
6994 page_counter_charge(&memcg->memsw, nr_pages);
6997 css_get(&memcg->css);
6998 commit_charge(newpage, memcg);
7000 local_irq_save(flags);
7001 mem_cgroup_charge_statistics(memcg, newpage, nr_pages);
7002 memcg_check_events(memcg, newpage);
7003 local_irq_restore(flags);
7006 DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
7007 EXPORT_SYMBOL(memcg_sockets_enabled_key);
7009 void mem_cgroup_sk_alloc(struct sock *sk)
7011 struct mem_cgroup *memcg;
7013 if (!mem_cgroup_sockets_enabled)
7016 /* Do not associate the sock with unrelated interrupted task's memcg. */
7021 memcg = mem_cgroup_from_task(current);
7022 if (memcg == root_mem_cgroup)
7024 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg->tcpmem_active)
7026 if (css_tryget(&memcg->css))
7027 sk->sk_memcg = memcg;
7032 void mem_cgroup_sk_free(struct sock *sk)
7035 css_put(&sk->sk_memcg->css);
7039 * mem_cgroup_charge_skmem - charge socket memory
7040 * @memcg: memcg to charge
7041 * @nr_pages: number of pages to charge
7043 * Charges @nr_pages to @memcg. Returns %true if the charge fit within
7044 * @memcg's configured limit, %false if the charge had to be forced.
7046 bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
7048 gfp_t gfp_mask = GFP_KERNEL;
7050 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
7051 struct page_counter *fail;
7053 if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) {
7054 memcg->tcpmem_pressure = 0;
7057 page_counter_charge(&memcg->tcpmem, nr_pages);
7058 memcg->tcpmem_pressure = 1;
7062 /* Don't block in the packet receive path */
7064 gfp_mask = GFP_NOWAIT;
7066 mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
7068 if (try_charge(memcg, gfp_mask, nr_pages) == 0)
7071 try_charge(memcg, gfp_mask|__GFP_NOFAIL, nr_pages);
7076 * mem_cgroup_uncharge_skmem - uncharge socket memory
7077 * @memcg: memcg to uncharge
7078 * @nr_pages: number of pages to uncharge
7080 void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
7082 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
7083 page_counter_uncharge(&memcg->tcpmem, nr_pages);
7087 mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
7089 refill_stock(memcg, nr_pages);
7092 static int __init cgroup_memory(char *s)
7096 while ((token = strsep(&s, ",")) != NULL) {
7099 if (!strcmp(token, "nosocket"))
7100 cgroup_memory_nosocket = true;
7101 if (!strcmp(token, "nokmem"))
7102 cgroup_memory_nokmem = true;
7106 __setup("cgroup.memory=", cgroup_memory);
7109 * subsys_initcall() for memory controller.
7111 * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
7112 * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
7113 * basically everything that doesn't depend on a specific mem_cgroup structure
7114 * should be initialized from here.
7116 static int __init mem_cgroup_init(void)
7121 * Currently s32 type (can refer to struct batched_lruvec_stat) is
7122 * used for per-memcg-per-cpu caching of per-node statistics. In order
7123 * to work fine, we should make sure that the overfill threshold can't
7124 * exceed S32_MAX / PAGE_SIZE.
7126 BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE);
7128 cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
7129 memcg_hotplug_cpu_dead);
7131 for_each_possible_cpu(cpu)
7132 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
7135 for_each_node(node) {
7136 struct mem_cgroup_tree_per_node *rtpn;
7138 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL,
7139 node_online(node) ? node : NUMA_NO_NODE);
7141 rtpn->rb_root = RB_ROOT;
7142 rtpn->rb_rightmost = NULL;
7143 spin_lock_init(&rtpn->lock);
7144 soft_limit_tree.rb_tree_per_node[node] = rtpn;
7149 subsys_initcall(mem_cgroup_init);
7151 #ifdef CONFIG_MEMCG_SWAP
7152 static struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
7154 while (!refcount_inc_not_zero(&memcg->id.ref)) {
7156 * The root cgroup cannot be destroyed, so it's refcount must
7159 if (WARN_ON_ONCE(memcg == root_mem_cgroup)) {
7163 memcg = parent_mem_cgroup(memcg);
7165 memcg = root_mem_cgroup;
7171 * mem_cgroup_swapout - transfer a memsw charge to swap
7172 * @page: page whose memsw charge to transfer
7173 * @entry: swap entry to move the charge to
7175 * Transfer the memsw charge of @page to @entry.
7177 void mem_cgroup_swapout(struct page *page, swp_entry_t entry)
7179 struct mem_cgroup *memcg, *swap_memcg;
7180 unsigned int nr_entries;
7181 unsigned short oldid;
7183 VM_BUG_ON_PAGE(PageLRU(page), page);
7184 VM_BUG_ON_PAGE(page_count(page), page);
7186 if (mem_cgroup_disabled())
7189 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
7192 memcg = page_memcg(page);
7194 VM_WARN_ON_ONCE_PAGE(!memcg, page);
7199 * In case the memcg owning these pages has been offlined and doesn't
7200 * have an ID allocated to it anymore, charge the closest online
7201 * ancestor for the swap instead and transfer the memory+swap charge.
7203 swap_memcg = mem_cgroup_id_get_online(memcg);
7204 nr_entries = thp_nr_pages(page);
7205 /* Get references for the tail pages, too */
7207 mem_cgroup_id_get_many(swap_memcg, nr_entries - 1);
7208 oldid = swap_cgroup_record(entry, mem_cgroup_id(swap_memcg),
7210 VM_BUG_ON_PAGE(oldid, page);
7211 mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries);
7213 page->memcg_data = 0;
7215 if (!mem_cgroup_is_root(memcg))
7216 page_counter_uncharge(&memcg->memory, nr_entries);
7218 if (!cgroup_memory_noswap && memcg != swap_memcg) {
7219 if (!mem_cgroup_is_root(swap_memcg))
7220 page_counter_charge(&swap_memcg->memsw, nr_entries);
7221 page_counter_uncharge(&memcg->memsw, nr_entries);
7225 * Interrupts should be disabled here because the caller holds the
7226 * i_pages lock which is taken with interrupts-off. It is
7227 * important here to have the interrupts disabled because it is the
7228 * only synchronisation we have for updating the per-CPU variables.
7230 VM_BUG_ON(!irqs_disabled());
7231 mem_cgroup_charge_statistics(memcg, page, -nr_entries);
7232 memcg_check_events(memcg, page);
7234 css_put(&memcg->css);
7238 * mem_cgroup_try_charge_swap - try charging swap space for a page
7239 * @page: page being added to swap
7240 * @entry: swap entry to charge
7242 * Try to charge @page's memcg for the swap space at @entry.
7244 * Returns 0 on success, -ENOMEM on failure.
7246 int mem_cgroup_try_charge_swap(struct page *page, swp_entry_t entry)
7248 unsigned int nr_pages = thp_nr_pages(page);
7249 struct page_counter *counter;
7250 struct mem_cgroup *memcg;
7251 unsigned short oldid;
7253 if (mem_cgroup_disabled())
7256 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
7259 memcg = page_memcg(page);
7261 VM_WARN_ON_ONCE_PAGE(!memcg, page);
7266 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7270 memcg = mem_cgroup_id_get_online(memcg);
7272 if (!cgroup_memory_noswap && !mem_cgroup_is_root(memcg) &&
7273 !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
7274 memcg_memory_event(memcg, MEMCG_SWAP_MAX);
7275 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7276 mem_cgroup_id_put(memcg);
7280 /* Get references for the tail pages, too */
7282 mem_cgroup_id_get_many(memcg, nr_pages - 1);
7283 oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg), nr_pages);
7284 VM_BUG_ON_PAGE(oldid, page);
7285 mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
7291 * mem_cgroup_uncharge_swap - uncharge swap space
7292 * @entry: swap entry to uncharge
7293 * @nr_pages: the amount of swap space to uncharge
7295 void mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
7297 struct mem_cgroup *memcg;
7300 id = swap_cgroup_record(entry, 0, nr_pages);
7302 memcg = mem_cgroup_from_id(id);
7304 if (!cgroup_memory_noswap && !mem_cgroup_is_root(memcg)) {
7305 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
7306 page_counter_uncharge(&memcg->swap, nr_pages);
7308 page_counter_uncharge(&memcg->memsw, nr_pages);
7310 mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
7311 mem_cgroup_id_put_many(memcg, nr_pages);
7316 long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
7318 long nr_swap_pages = get_nr_swap_pages();
7320 if (cgroup_memory_noswap || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
7321 return nr_swap_pages;
7322 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg))
7323 nr_swap_pages = min_t(long, nr_swap_pages,
7324 READ_ONCE(memcg->swap.max) -
7325 page_counter_read(&memcg->swap));
7326 return nr_swap_pages;
7329 bool mem_cgroup_swap_full(struct page *page)
7331 struct mem_cgroup *memcg;
7333 VM_BUG_ON_PAGE(!PageLocked(page), page);
7337 if (cgroup_memory_noswap || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
7340 memcg = page_memcg(page);
7344 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg)) {
7345 unsigned long usage = page_counter_read(&memcg->swap);
7347 if (usage * 2 >= READ_ONCE(memcg->swap.high) ||
7348 usage * 2 >= READ_ONCE(memcg->swap.max))
7355 static int __init setup_swap_account(char *s)
7357 if (!strcmp(s, "1"))
7358 cgroup_memory_noswap = false;
7359 else if (!strcmp(s, "0"))
7360 cgroup_memory_noswap = true;
7363 __setup("swapaccount=", setup_swap_account);
7365 static u64 swap_current_read(struct cgroup_subsys_state *css,
7368 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7370 return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
7373 static int swap_high_show(struct seq_file *m, void *v)
7375 return seq_puts_memcg_tunable(m,
7376 READ_ONCE(mem_cgroup_from_seq(m)->swap.high));
7379 static ssize_t swap_high_write(struct kernfs_open_file *of,
7380 char *buf, size_t nbytes, loff_t off)
7382 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7386 buf = strstrip(buf);
7387 err = page_counter_memparse(buf, "max", &high);
7391 page_counter_set_high(&memcg->swap, high);
7396 static int swap_max_show(struct seq_file *m, void *v)
7398 return seq_puts_memcg_tunable(m,
7399 READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
7402 static ssize_t swap_max_write(struct kernfs_open_file *of,
7403 char *buf, size_t nbytes, loff_t off)
7405 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7409 buf = strstrip(buf);
7410 err = page_counter_memparse(buf, "max", &max);
7414 xchg(&memcg->swap.max, max);
7419 static int swap_events_show(struct seq_file *m, void *v)
7421 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
7423 seq_printf(m, "high %lu\n",
7424 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH]));
7425 seq_printf(m, "max %lu\n",
7426 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
7427 seq_printf(m, "fail %lu\n",
7428 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
7433 static struct cftype swap_files[] = {
7435 .name = "swap.current",
7436 .flags = CFTYPE_NOT_ON_ROOT,
7437 .read_u64 = swap_current_read,
7440 .name = "swap.high",
7441 .flags = CFTYPE_NOT_ON_ROOT,
7442 .seq_show = swap_high_show,
7443 .write = swap_high_write,
7447 .flags = CFTYPE_NOT_ON_ROOT,
7448 .seq_show = swap_max_show,
7449 .write = swap_max_write,
7452 .name = "swap.events",
7453 .flags = CFTYPE_NOT_ON_ROOT,
7454 .file_offset = offsetof(struct mem_cgroup, swap_events_file),
7455 .seq_show = swap_events_show,
7460 static struct cftype memsw_files[] = {
7462 .name = "memsw.usage_in_bytes",
7463 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
7464 .read_u64 = mem_cgroup_read_u64,
7467 .name = "memsw.max_usage_in_bytes",
7468 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
7469 .write = mem_cgroup_reset,
7470 .read_u64 = mem_cgroup_read_u64,
7473 .name = "memsw.limit_in_bytes",
7474 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
7475 .write = mem_cgroup_write,
7476 .read_u64 = mem_cgroup_read_u64,
7479 .name = "memsw.failcnt",
7480 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
7481 .write = mem_cgroup_reset,
7482 .read_u64 = mem_cgroup_read_u64,
7484 { }, /* terminate */
7488 * If mem_cgroup_swap_init() is implemented as a subsys_initcall()
7489 * instead of a core_initcall(), this could mean cgroup_memory_noswap still
7490 * remains set to false even when memcg is disabled via "cgroup_disable=memory"
7491 * boot parameter. This may result in premature OOPS inside
7492 * mem_cgroup_get_nr_swap_pages() function in corner cases.
7494 static int __init mem_cgroup_swap_init(void)
7496 /* No memory control -> no swap control */
7497 if (mem_cgroup_disabled())
7498 cgroup_memory_noswap = true;
7500 if (cgroup_memory_noswap)
7503 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files));
7504 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files));
7508 core_initcall(mem_cgroup_swap_init);
7510 #endif /* CONFIG_MEMCG_SWAP */