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);
82 /* Socket memory accounting disabled? */
83 static bool cgroup_memory_nosocket;
85 /* Kernel memory accounting disabled? */
86 static bool cgroup_memory_nokmem;
88 /* Whether the swap controller is active */
89 #ifdef CONFIG_MEMCG_SWAP
90 bool cgroup_memory_noswap __read_mostly;
92 #define cgroup_memory_noswap 1
95 #ifdef CONFIG_CGROUP_WRITEBACK
96 static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq);
99 /* Whether legacy memory+swap accounting is active */
100 static bool do_memsw_account(void)
102 return !cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_noswap;
105 #define THRESHOLDS_EVENTS_TARGET 128
106 #define SOFTLIMIT_EVENTS_TARGET 1024
109 * Cgroups above their limits are maintained in a RB-Tree, independent of
110 * their hierarchy representation
113 struct mem_cgroup_tree_per_node {
114 struct rb_root rb_root;
115 struct rb_node *rb_rightmost;
119 struct mem_cgroup_tree {
120 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
123 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
126 struct mem_cgroup_eventfd_list {
127 struct list_head list;
128 struct eventfd_ctx *eventfd;
132 * cgroup_event represents events which userspace want to receive.
134 struct mem_cgroup_event {
136 * memcg which the event belongs to.
138 struct mem_cgroup *memcg;
140 * eventfd to signal userspace about the event.
142 struct eventfd_ctx *eventfd;
144 * Each of these stored in a list by the cgroup.
146 struct list_head list;
148 * register_event() callback will be used to add new userspace
149 * waiter for changes related to this event. Use eventfd_signal()
150 * on eventfd to send notification to userspace.
152 int (*register_event)(struct mem_cgroup *memcg,
153 struct eventfd_ctx *eventfd, const char *args);
155 * unregister_event() callback will be called when userspace closes
156 * the eventfd or on cgroup removing. This callback must be set,
157 * if you want provide notification functionality.
159 void (*unregister_event)(struct mem_cgroup *memcg,
160 struct eventfd_ctx *eventfd);
162 * All fields below needed to unregister event when
163 * userspace closes eventfd.
166 wait_queue_head_t *wqh;
167 wait_queue_entry_t wait;
168 struct work_struct remove;
171 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
172 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
174 /* Stuffs for move charges at task migration. */
176 * Types of charges to be moved.
178 #define MOVE_ANON 0x1U
179 #define MOVE_FILE 0x2U
180 #define MOVE_MASK (MOVE_ANON | MOVE_FILE)
182 /* "mc" and its members are protected by cgroup_mutex */
183 static struct move_charge_struct {
184 spinlock_t lock; /* for from, to */
185 struct mm_struct *mm;
186 struct mem_cgroup *from;
187 struct mem_cgroup *to;
189 unsigned long precharge;
190 unsigned long moved_charge;
191 unsigned long moved_swap;
192 struct task_struct *moving_task; /* a task moving charges */
193 wait_queue_head_t waitq; /* a waitq for other context */
195 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
196 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
200 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
201 * limit reclaim to prevent infinite loops, if they ever occur.
203 #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
204 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
206 /* for encoding cft->private value on file */
215 #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
216 #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
217 #define MEMFILE_ATTR(val) ((val) & 0xffff)
218 /* Used for OOM nofiier */
219 #define OOM_CONTROL (0)
222 * Iteration constructs for visiting all cgroups (under a tree). If
223 * loops are exited prematurely (break), mem_cgroup_iter_break() must
224 * be used for reference counting.
226 #define for_each_mem_cgroup_tree(iter, root) \
227 for (iter = mem_cgroup_iter(root, NULL, NULL); \
229 iter = mem_cgroup_iter(root, iter, NULL))
231 #define for_each_mem_cgroup(iter) \
232 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
234 iter = mem_cgroup_iter(NULL, iter, NULL))
236 static inline bool should_force_charge(void)
238 return tsk_is_oom_victim(current) || fatal_signal_pending(current) ||
239 (current->flags & PF_EXITING);
242 /* Some nice accessors for the vmpressure. */
243 struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
246 memcg = root_mem_cgroup;
247 return &memcg->vmpressure;
250 struct cgroup_subsys_state *vmpressure_to_css(struct vmpressure *vmpr)
252 return &container_of(vmpr, struct mem_cgroup, vmpressure)->css;
255 #ifdef CONFIG_MEMCG_KMEM
256 extern spinlock_t css_set_lock;
258 static void obj_cgroup_release(struct percpu_ref *ref)
260 struct obj_cgroup *objcg = container_of(ref, struct obj_cgroup, refcnt);
261 struct mem_cgroup *memcg;
262 unsigned int nr_bytes;
263 unsigned int nr_pages;
267 * At this point all allocated objects are freed, and
268 * objcg->nr_charged_bytes can't have an arbitrary byte value.
269 * However, it can be PAGE_SIZE or (x * PAGE_SIZE).
271 * The following sequence can lead to it:
272 * 1) CPU0: objcg == stock->cached_objcg
273 * 2) CPU1: we do a small allocation (e.g. 92 bytes),
274 * PAGE_SIZE bytes are charged
275 * 3) CPU1: a process from another memcg is allocating something,
276 * the stock if flushed,
277 * objcg->nr_charged_bytes = PAGE_SIZE - 92
278 * 5) CPU0: we do release this object,
279 * 92 bytes are added to stock->nr_bytes
280 * 6) CPU0: stock is flushed,
281 * 92 bytes are added to objcg->nr_charged_bytes
283 * In the result, nr_charged_bytes == PAGE_SIZE.
284 * This page will be uncharged in obj_cgroup_release().
286 nr_bytes = atomic_read(&objcg->nr_charged_bytes);
287 WARN_ON_ONCE(nr_bytes & (PAGE_SIZE - 1));
288 nr_pages = nr_bytes >> PAGE_SHIFT;
290 spin_lock_irqsave(&css_set_lock, flags);
291 memcg = obj_cgroup_memcg(objcg);
293 __memcg_kmem_uncharge(memcg, nr_pages);
294 list_del(&objcg->list);
295 mem_cgroup_put(memcg);
296 spin_unlock_irqrestore(&css_set_lock, flags);
298 percpu_ref_exit(ref);
299 kfree_rcu(objcg, rcu);
302 static struct obj_cgroup *obj_cgroup_alloc(void)
304 struct obj_cgroup *objcg;
307 objcg = kzalloc(sizeof(struct obj_cgroup), GFP_KERNEL);
311 ret = percpu_ref_init(&objcg->refcnt, obj_cgroup_release, 0,
317 INIT_LIST_HEAD(&objcg->list);
321 static void memcg_reparent_objcgs(struct mem_cgroup *memcg,
322 struct mem_cgroup *parent)
324 struct obj_cgroup *objcg, *iter;
326 objcg = rcu_replace_pointer(memcg->objcg, NULL, true);
328 spin_lock_irq(&css_set_lock);
330 /* Move active objcg to the parent's list */
331 xchg(&objcg->memcg, parent);
332 css_get(&parent->css);
333 list_add(&objcg->list, &parent->objcg_list);
335 /* Move already reparented objcgs to the parent's list */
336 list_for_each_entry(iter, &memcg->objcg_list, list) {
337 css_get(&parent->css);
338 xchg(&iter->memcg, parent);
339 css_put(&memcg->css);
341 list_splice(&memcg->objcg_list, &parent->objcg_list);
343 spin_unlock_irq(&css_set_lock);
345 percpu_ref_kill(&objcg->refcnt);
349 * This will be used as a shrinker list's index.
350 * The main reason for not using cgroup id for this:
351 * this works better in sparse environments, where we have a lot of memcgs,
352 * but only a few kmem-limited. Or also, if we have, for instance, 200
353 * memcgs, and none but the 200th is kmem-limited, we'd have to have a
354 * 200 entry array for that.
356 * The current size of the caches array is stored in memcg_nr_cache_ids. It
357 * will double each time we have to increase it.
359 static DEFINE_IDA(memcg_cache_ida);
360 int memcg_nr_cache_ids;
362 /* Protects memcg_nr_cache_ids */
363 static DECLARE_RWSEM(memcg_cache_ids_sem);
365 void memcg_get_cache_ids(void)
367 down_read(&memcg_cache_ids_sem);
370 void memcg_put_cache_ids(void)
372 up_read(&memcg_cache_ids_sem);
376 * MIN_SIZE is different than 1, because we would like to avoid going through
377 * the alloc/free process all the time. In a small machine, 4 kmem-limited
378 * cgroups is a reasonable guess. In the future, it could be a parameter or
379 * tunable, but that is strictly not necessary.
381 * MAX_SIZE should be as large as the number of cgrp_ids. Ideally, we could get
382 * this constant directly from cgroup, but it is understandable that this is
383 * better kept as an internal representation in cgroup.c. In any case, the
384 * cgrp_id space is not getting any smaller, and we don't have to necessarily
385 * increase ours as well if it increases.
387 #define MEMCG_CACHES_MIN_SIZE 4
388 #define MEMCG_CACHES_MAX_SIZE MEM_CGROUP_ID_MAX
391 * A lot of the calls to the cache allocation functions are expected to be
392 * inlined by the compiler. Since the calls to memcg_slab_pre_alloc_hook() are
393 * conditional to this static branch, we'll have to allow modules that does
394 * kmem_cache_alloc and the such to see this symbol as well
396 DEFINE_STATIC_KEY_FALSE(memcg_kmem_enabled_key);
397 EXPORT_SYMBOL(memcg_kmem_enabled_key);
400 static int memcg_shrinker_map_size;
401 static DEFINE_MUTEX(memcg_shrinker_map_mutex);
403 static void memcg_free_shrinker_map_rcu(struct rcu_head *head)
405 kvfree(container_of(head, struct memcg_shrinker_map, rcu));
408 static int memcg_expand_one_shrinker_map(struct mem_cgroup *memcg,
409 int size, int old_size)
411 struct memcg_shrinker_map *new, *old;
414 lockdep_assert_held(&memcg_shrinker_map_mutex);
417 old = rcu_dereference_protected(
418 mem_cgroup_nodeinfo(memcg, nid)->shrinker_map, true);
419 /* Not yet online memcg */
423 new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
427 /* Set all old bits, clear all new bits */
428 memset(new->map, (int)0xff, old_size);
429 memset((void *)new->map + old_size, 0, size - old_size);
431 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_map, new);
432 call_rcu(&old->rcu, memcg_free_shrinker_map_rcu);
438 static void memcg_free_shrinker_maps(struct mem_cgroup *memcg)
440 struct mem_cgroup_per_node *pn;
441 struct memcg_shrinker_map *map;
444 if (mem_cgroup_is_root(memcg))
448 pn = mem_cgroup_nodeinfo(memcg, nid);
449 map = rcu_dereference_protected(pn->shrinker_map, true);
452 rcu_assign_pointer(pn->shrinker_map, NULL);
456 static int memcg_alloc_shrinker_maps(struct mem_cgroup *memcg)
458 struct memcg_shrinker_map *map;
459 int nid, size, ret = 0;
461 if (mem_cgroup_is_root(memcg))
464 mutex_lock(&memcg_shrinker_map_mutex);
465 size = memcg_shrinker_map_size;
467 map = kvzalloc_node(sizeof(*map) + size, GFP_KERNEL, nid);
469 memcg_free_shrinker_maps(memcg);
473 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_map, map);
475 mutex_unlock(&memcg_shrinker_map_mutex);
480 int memcg_expand_shrinker_maps(int new_id)
482 int size, old_size, ret = 0;
483 struct mem_cgroup *memcg;
485 size = DIV_ROUND_UP(new_id + 1, BITS_PER_LONG) * sizeof(unsigned long);
486 old_size = memcg_shrinker_map_size;
487 if (size <= old_size)
490 mutex_lock(&memcg_shrinker_map_mutex);
491 if (!root_mem_cgroup)
494 for_each_mem_cgroup(memcg) {
495 if (mem_cgroup_is_root(memcg))
497 ret = memcg_expand_one_shrinker_map(memcg, size, old_size);
499 mem_cgroup_iter_break(NULL, memcg);
505 memcg_shrinker_map_size = size;
506 mutex_unlock(&memcg_shrinker_map_mutex);
510 void memcg_set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
512 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
513 struct memcg_shrinker_map *map;
516 map = rcu_dereference(memcg->nodeinfo[nid]->shrinker_map);
517 /* Pairs with smp mb in shrink_slab() */
518 smp_mb__before_atomic();
519 set_bit(shrinker_id, map->map);
525 * mem_cgroup_css_from_page - css of the memcg associated with a page
526 * @page: page of interest
528 * If memcg is bound to the default hierarchy, css of the memcg associated
529 * with @page is returned. The returned css remains associated with @page
530 * until it is released.
532 * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
535 struct cgroup_subsys_state *mem_cgroup_css_from_page(struct page *page)
537 struct mem_cgroup *memcg;
539 memcg = page_memcg(page);
541 if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
542 memcg = root_mem_cgroup;
548 * page_cgroup_ino - return inode number of the memcg a page is charged to
551 * Look up the closest online ancestor of the memory cgroup @page is charged to
552 * and return its inode number or 0 if @page is not charged to any cgroup. It
553 * is safe to call this function without holding a reference to @page.
555 * Note, this function is inherently racy, because there is nothing to prevent
556 * the cgroup inode from getting torn down and potentially reallocated a moment
557 * after page_cgroup_ino() returns, so it only should be used by callers that
558 * do not care (such as procfs interfaces).
560 ino_t page_cgroup_ino(struct page *page)
562 struct mem_cgroup *memcg;
563 unsigned long ino = 0;
566 memcg = page_memcg_check(page);
568 while (memcg && !(memcg->css.flags & CSS_ONLINE))
569 memcg = parent_mem_cgroup(memcg);
571 ino = cgroup_ino(memcg->css.cgroup);
576 static struct mem_cgroup_per_node *
577 mem_cgroup_page_nodeinfo(struct mem_cgroup *memcg, struct page *page)
579 int nid = page_to_nid(page);
581 return memcg->nodeinfo[nid];
584 static struct mem_cgroup_tree_per_node *
585 soft_limit_tree_node(int nid)
587 return soft_limit_tree.rb_tree_per_node[nid];
590 static struct mem_cgroup_tree_per_node *
591 soft_limit_tree_from_page(struct page *page)
593 int nid = page_to_nid(page);
595 return soft_limit_tree.rb_tree_per_node[nid];
598 static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_node *mz,
599 struct mem_cgroup_tree_per_node *mctz,
600 unsigned long new_usage_in_excess)
602 struct rb_node **p = &mctz->rb_root.rb_node;
603 struct rb_node *parent = NULL;
604 struct mem_cgroup_per_node *mz_node;
605 bool rightmost = true;
610 mz->usage_in_excess = new_usage_in_excess;
611 if (!mz->usage_in_excess)
615 mz_node = rb_entry(parent, struct mem_cgroup_per_node,
617 if (mz->usage_in_excess < mz_node->usage_in_excess) {
626 mctz->rb_rightmost = &mz->tree_node;
628 rb_link_node(&mz->tree_node, parent, p);
629 rb_insert_color(&mz->tree_node, &mctz->rb_root);
633 static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
634 struct mem_cgroup_tree_per_node *mctz)
639 if (&mz->tree_node == mctz->rb_rightmost)
640 mctz->rb_rightmost = rb_prev(&mz->tree_node);
642 rb_erase(&mz->tree_node, &mctz->rb_root);
646 static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
647 struct mem_cgroup_tree_per_node *mctz)
651 spin_lock_irqsave(&mctz->lock, flags);
652 __mem_cgroup_remove_exceeded(mz, mctz);
653 spin_unlock_irqrestore(&mctz->lock, flags);
656 static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
658 unsigned long nr_pages = page_counter_read(&memcg->memory);
659 unsigned long soft_limit = READ_ONCE(memcg->soft_limit);
660 unsigned long excess = 0;
662 if (nr_pages > soft_limit)
663 excess = nr_pages - soft_limit;
668 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
670 unsigned long excess;
671 struct mem_cgroup_per_node *mz;
672 struct mem_cgroup_tree_per_node *mctz;
674 mctz = soft_limit_tree_from_page(page);
678 * Necessary to update all ancestors when hierarchy is used.
679 * because their event counter is not touched.
681 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
682 mz = mem_cgroup_page_nodeinfo(memcg, page);
683 excess = soft_limit_excess(memcg);
685 * We have to update the tree if mz is on RB-tree or
686 * mem is over its softlimit.
688 if (excess || mz->on_tree) {
691 spin_lock_irqsave(&mctz->lock, flags);
692 /* if on-tree, remove it */
694 __mem_cgroup_remove_exceeded(mz, mctz);
696 * Insert again. mz->usage_in_excess will be updated.
697 * If excess is 0, no tree ops.
699 __mem_cgroup_insert_exceeded(mz, mctz, excess);
700 spin_unlock_irqrestore(&mctz->lock, flags);
705 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
707 struct mem_cgroup_tree_per_node *mctz;
708 struct mem_cgroup_per_node *mz;
712 mz = mem_cgroup_nodeinfo(memcg, nid);
713 mctz = soft_limit_tree_node(nid);
715 mem_cgroup_remove_exceeded(mz, mctz);
719 static struct mem_cgroup_per_node *
720 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
722 struct mem_cgroup_per_node *mz;
726 if (!mctz->rb_rightmost)
727 goto done; /* Nothing to reclaim from */
729 mz = rb_entry(mctz->rb_rightmost,
730 struct mem_cgroup_per_node, tree_node);
732 * Remove the node now but someone else can add it back,
733 * we will to add it back at the end of reclaim to its correct
734 * position in the tree.
736 __mem_cgroup_remove_exceeded(mz, mctz);
737 if (!soft_limit_excess(mz->memcg) ||
738 !css_tryget(&mz->memcg->css))
744 static struct mem_cgroup_per_node *
745 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
747 struct mem_cgroup_per_node *mz;
749 spin_lock_irq(&mctz->lock);
750 mz = __mem_cgroup_largest_soft_limit_node(mctz);
751 spin_unlock_irq(&mctz->lock);
756 * __mod_memcg_state - update cgroup memory statistics
757 * @memcg: the memory cgroup
758 * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item
759 * @val: delta to add to the counter, can be negative
761 void __mod_memcg_state(struct mem_cgroup *memcg, int idx, int val)
763 long x, threshold = MEMCG_CHARGE_BATCH;
765 if (mem_cgroup_disabled())
768 if (memcg_stat_item_in_bytes(idx))
769 threshold <<= PAGE_SHIFT;
771 x = val + __this_cpu_read(memcg->vmstats_percpu->stat[idx]);
772 if (unlikely(abs(x) > threshold)) {
773 struct mem_cgroup *mi;
776 * Batch local counters to keep them in sync with
777 * the hierarchical ones.
779 __this_cpu_add(memcg->vmstats_local->stat[idx], x);
780 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
781 atomic_long_add(x, &mi->vmstats[idx]);
784 __this_cpu_write(memcg->vmstats_percpu->stat[idx], x);
787 static struct mem_cgroup_per_node *
788 parent_nodeinfo(struct mem_cgroup_per_node *pn, int nid)
790 struct mem_cgroup *parent;
792 parent = parent_mem_cgroup(pn->memcg);
795 return mem_cgroup_nodeinfo(parent, nid);
798 void __mod_memcg_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
801 struct mem_cgroup_per_node *pn;
802 struct mem_cgroup *memcg;
803 long x, threshold = MEMCG_CHARGE_BATCH;
805 pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
809 __mod_memcg_state(memcg, idx, val);
812 __this_cpu_add(pn->lruvec_stat_local->count[idx], val);
814 if (vmstat_item_in_bytes(idx))
815 threshold <<= PAGE_SHIFT;
817 x = val + __this_cpu_read(pn->lruvec_stat_cpu->count[idx]);
818 if (unlikely(abs(x) > threshold)) {
819 pg_data_t *pgdat = lruvec_pgdat(lruvec);
820 struct mem_cgroup_per_node *pi;
822 for (pi = pn; pi; pi = parent_nodeinfo(pi, pgdat->node_id))
823 atomic_long_add(x, &pi->lruvec_stat[idx]);
826 __this_cpu_write(pn->lruvec_stat_cpu->count[idx], x);
830 * __mod_lruvec_state - update lruvec memory statistics
831 * @lruvec: the lruvec
832 * @idx: the stat item
833 * @val: delta to add to the counter, can be negative
835 * The lruvec is the intersection of the NUMA node and a cgroup. This
836 * function updates the all three counters that are affected by a
837 * change of state at this level: per-node, per-cgroup, per-lruvec.
839 void __mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
843 __mod_node_page_state(lruvec_pgdat(lruvec), idx, val);
845 /* Update memcg and lruvec */
846 if (!mem_cgroup_disabled())
847 __mod_memcg_lruvec_state(lruvec, idx, val);
850 void __mod_lruvec_page_state(struct page *page, enum node_stat_item idx,
853 struct page *head = compound_head(page); /* rmap on tail pages */
854 struct mem_cgroup *memcg = page_memcg(head);
855 pg_data_t *pgdat = page_pgdat(page);
856 struct lruvec *lruvec;
858 /* Untracked pages have no memcg, no lruvec. Update only the node */
860 __mod_node_page_state(pgdat, idx, val);
864 lruvec = mem_cgroup_lruvec(memcg, pgdat);
865 __mod_lruvec_state(lruvec, idx, val);
867 EXPORT_SYMBOL(__mod_lruvec_page_state);
869 void __mod_lruvec_kmem_state(void *p, enum node_stat_item idx, int val)
871 pg_data_t *pgdat = page_pgdat(virt_to_page(p));
872 struct mem_cgroup *memcg;
873 struct lruvec *lruvec;
876 memcg = mem_cgroup_from_obj(p);
879 * Untracked pages have no memcg, no lruvec. Update only the
880 * node. If we reparent the slab objects to the root memcg,
881 * when we free the slab object, we need to update the per-memcg
882 * vmstats to keep it correct for the root memcg.
885 __mod_node_page_state(pgdat, idx, val);
887 lruvec = mem_cgroup_lruvec(memcg, pgdat);
888 __mod_lruvec_state(lruvec, idx, val);
894 * __count_memcg_events - account VM events in a cgroup
895 * @memcg: the memory cgroup
896 * @idx: the event item
897 * @count: the number of events that occured
899 void __count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx,
904 if (mem_cgroup_disabled())
907 x = count + __this_cpu_read(memcg->vmstats_percpu->events[idx]);
908 if (unlikely(x > MEMCG_CHARGE_BATCH)) {
909 struct mem_cgroup *mi;
912 * Batch local counters to keep them in sync with
913 * the hierarchical ones.
915 __this_cpu_add(memcg->vmstats_local->events[idx], x);
916 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
917 atomic_long_add(x, &mi->vmevents[idx]);
920 __this_cpu_write(memcg->vmstats_percpu->events[idx], x);
923 static unsigned long memcg_events(struct mem_cgroup *memcg, int event)
925 return atomic_long_read(&memcg->vmevents[event]);
928 static unsigned long memcg_events_local(struct mem_cgroup *memcg, int event)
933 for_each_possible_cpu(cpu)
934 x += per_cpu(memcg->vmstats_local->events[event], cpu);
938 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
942 /* pagein of a big page is an event. So, ignore page size */
944 __count_memcg_events(memcg, PGPGIN, 1);
946 __count_memcg_events(memcg, PGPGOUT, 1);
947 nr_pages = -nr_pages; /* for event */
950 __this_cpu_add(memcg->vmstats_percpu->nr_page_events, nr_pages);
953 static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
954 enum mem_cgroup_events_target target)
956 unsigned long val, next;
958 val = __this_cpu_read(memcg->vmstats_percpu->nr_page_events);
959 next = __this_cpu_read(memcg->vmstats_percpu->targets[target]);
960 /* from time_after() in jiffies.h */
961 if ((long)(next - val) < 0) {
963 case MEM_CGROUP_TARGET_THRESH:
964 next = val + THRESHOLDS_EVENTS_TARGET;
966 case MEM_CGROUP_TARGET_SOFTLIMIT:
967 next = val + SOFTLIMIT_EVENTS_TARGET;
972 __this_cpu_write(memcg->vmstats_percpu->targets[target], next);
979 * Check events in order.
982 static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
984 /* threshold event is triggered in finer grain than soft limit */
985 if (unlikely(mem_cgroup_event_ratelimit(memcg,
986 MEM_CGROUP_TARGET_THRESH))) {
989 do_softlimit = mem_cgroup_event_ratelimit(memcg,
990 MEM_CGROUP_TARGET_SOFTLIMIT);
991 mem_cgroup_threshold(memcg);
992 if (unlikely(do_softlimit))
993 mem_cgroup_update_tree(memcg, page);
997 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
1000 * mm_update_next_owner() may clear mm->owner to NULL
1001 * if it races with swapoff, page migration, etc.
1002 * So this can be called with p == NULL.
1007 return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
1009 EXPORT_SYMBOL(mem_cgroup_from_task);
1012 * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
1013 * @mm: mm from which memcg should be extracted. It can be NULL.
1015 * Obtain a reference on mm->memcg and returns it if successful. Otherwise
1016 * root_mem_cgroup is returned. However if mem_cgroup is disabled, NULL is
1019 struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
1021 struct mem_cgroup *memcg;
1023 if (mem_cgroup_disabled())
1029 * Page cache insertions can happen withou an
1030 * actual mm context, e.g. during disk probing
1031 * on boot, loopback IO, acct() writes etc.
1034 memcg = root_mem_cgroup;
1036 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1037 if (unlikely(!memcg))
1038 memcg = root_mem_cgroup;
1040 } while (!css_tryget(&memcg->css));
1044 EXPORT_SYMBOL(get_mem_cgroup_from_mm);
1047 * get_mem_cgroup_from_page: Obtain a reference on given page's memcg.
1048 * @page: page from which memcg should be extracted.
1050 * Obtain a reference on page->memcg and returns it if successful. Otherwise
1051 * root_mem_cgroup is returned.
1053 struct mem_cgroup *get_mem_cgroup_from_page(struct page *page)
1055 struct mem_cgroup *memcg = page_memcg(page);
1057 if (mem_cgroup_disabled())
1061 /* Page should not get uncharged and freed memcg under us. */
1062 if (!memcg || WARN_ON_ONCE(!css_tryget(&memcg->css)))
1063 memcg = root_mem_cgroup;
1067 EXPORT_SYMBOL(get_mem_cgroup_from_page);
1069 static __always_inline struct mem_cgroup *active_memcg(void)
1072 return this_cpu_read(int_active_memcg);
1074 return current->active_memcg;
1077 static __always_inline struct mem_cgroup *get_active_memcg(void)
1079 struct mem_cgroup *memcg;
1082 memcg = active_memcg();
1084 /* current->active_memcg must hold a ref. */
1085 if (WARN_ON_ONCE(!css_tryget(&memcg->css)))
1086 memcg = root_mem_cgroup;
1088 memcg = current->active_memcg;
1095 static __always_inline bool memcg_kmem_bypass(void)
1097 /* Allow remote memcg charging from any context. */
1098 if (unlikely(active_memcg()))
1101 /* Memcg to charge can't be determined. */
1102 if (in_interrupt() || !current->mm || (current->flags & PF_KTHREAD))
1109 * If active memcg is set, do not fallback to current->mm->memcg.
1111 static __always_inline struct mem_cgroup *get_mem_cgroup_from_current(void)
1113 if (memcg_kmem_bypass())
1116 if (unlikely(active_memcg()))
1117 return get_active_memcg();
1119 return get_mem_cgroup_from_mm(current->mm);
1123 * mem_cgroup_iter - iterate over memory cgroup hierarchy
1124 * @root: hierarchy root
1125 * @prev: previously returned memcg, NULL on first invocation
1126 * @reclaim: cookie for shared reclaim walks, NULL for full walks
1128 * Returns references to children of the hierarchy below @root, or
1129 * @root itself, or %NULL after a full round-trip.
1131 * Caller must pass the return value in @prev on subsequent
1132 * invocations for reference counting, or use mem_cgroup_iter_break()
1133 * to cancel a hierarchy walk before the round-trip is complete.
1135 * Reclaimers can specify a node in @reclaim to divide up the memcgs
1136 * in the hierarchy among all concurrent reclaimers operating on the
1139 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
1140 struct mem_cgroup *prev,
1141 struct mem_cgroup_reclaim_cookie *reclaim)
1143 struct mem_cgroup_reclaim_iter *iter;
1144 struct cgroup_subsys_state *css = NULL;
1145 struct mem_cgroup *memcg = NULL;
1146 struct mem_cgroup *pos = NULL;
1148 if (mem_cgroup_disabled())
1152 root = root_mem_cgroup;
1154 if (prev && !reclaim)
1160 struct mem_cgroup_per_node *mz;
1162 mz = mem_cgroup_nodeinfo(root, reclaim->pgdat->node_id);
1165 if (prev && reclaim->generation != iter->generation)
1169 pos = READ_ONCE(iter->position);
1170 if (!pos || css_tryget(&pos->css))
1173 * css reference reached zero, so iter->position will
1174 * be cleared by ->css_released. However, we should not
1175 * rely on this happening soon, because ->css_released
1176 * is called from a work queue, and by busy-waiting we
1177 * might block it. So we clear iter->position right
1180 (void)cmpxchg(&iter->position, pos, NULL);
1188 css = css_next_descendant_pre(css, &root->css);
1191 * Reclaimers share the hierarchy walk, and a
1192 * new one might jump in right at the end of
1193 * the hierarchy - make sure they see at least
1194 * one group and restart from the beginning.
1202 * Verify the css and acquire a reference. The root
1203 * is provided by the caller, so we know it's alive
1204 * and kicking, and don't take an extra reference.
1206 memcg = mem_cgroup_from_css(css);
1208 if (css == &root->css)
1211 if (css_tryget(css))
1219 * The position could have already been updated by a competing
1220 * thread, so check that the value hasn't changed since we read
1221 * it to avoid reclaiming from the same cgroup twice.
1223 (void)cmpxchg(&iter->position, pos, memcg);
1231 reclaim->generation = iter->generation;
1236 if (prev && prev != root)
1237 css_put(&prev->css);
1243 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1244 * @root: hierarchy root
1245 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1247 void mem_cgroup_iter_break(struct mem_cgroup *root,
1248 struct mem_cgroup *prev)
1251 root = root_mem_cgroup;
1252 if (prev && prev != root)
1253 css_put(&prev->css);
1256 static void __invalidate_reclaim_iterators(struct mem_cgroup *from,
1257 struct mem_cgroup *dead_memcg)
1259 struct mem_cgroup_reclaim_iter *iter;
1260 struct mem_cgroup_per_node *mz;
1263 for_each_node(nid) {
1264 mz = mem_cgroup_nodeinfo(from, nid);
1266 cmpxchg(&iter->position, dead_memcg, NULL);
1270 static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
1272 struct mem_cgroup *memcg = dead_memcg;
1273 struct mem_cgroup *last;
1276 __invalidate_reclaim_iterators(memcg, dead_memcg);
1278 } while ((memcg = parent_mem_cgroup(memcg)));
1281 * When cgruop1 non-hierarchy mode is used,
1282 * parent_mem_cgroup() does not walk all the way up to the
1283 * cgroup root (root_mem_cgroup). So we have to handle
1284 * dead_memcg from cgroup root separately.
1286 if (last != root_mem_cgroup)
1287 __invalidate_reclaim_iterators(root_mem_cgroup,
1292 * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
1293 * @memcg: hierarchy root
1294 * @fn: function to call for each task
1295 * @arg: argument passed to @fn
1297 * This function iterates over tasks attached to @memcg or to any of its
1298 * descendants and calls @fn for each task. If @fn returns a non-zero
1299 * value, the function breaks the iteration loop and returns the value.
1300 * Otherwise, it will iterate over all tasks and return 0.
1302 * This function must not be called for the root memory cgroup.
1304 int mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
1305 int (*fn)(struct task_struct *, void *), void *arg)
1307 struct mem_cgroup *iter;
1310 BUG_ON(memcg == root_mem_cgroup);
1312 for_each_mem_cgroup_tree(iter, memcg) {
1313 struct css_task_iter it;
1314 struct task_struct *task;
1316 css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it);
1317 while (!ret && (task = css_task_iter_next(&it)))
1318 ret = fn(task, arg);
1319 css_task_iter_end(&it);
1321 mem_cgroup_iter_break(memcg, iter);
1328 #ifdef CONFIG_DEBUG_VM
1329 void lruvec_memcg_debug(struct lruvec *lruvec, struct page *page)
1331 struct mem_cgroup *memcg;
1333 if (mem_cgroup_disabled())
1336 memcg = page_memcg(page);
1339 VM_BUG_ON_PAGE(lruvec_memcg(lruvec) != root_mem_cgroup, page);
1341 VM_BUG_ON_PAGE(lruvec_memcg(lruvec) != memcg, page);
1346 * mem_cgroup_page_lruvec - return lruvec for isolating/putting an LRU page
1348 * @pgdat: pgdat of the page
1350 * This function relies on page's memcg being stable - see the
1351 * access rules in commit_charge().
1353 struct lruvec *mem_cgroup_page_lruvec(struct page *page, struct pglist_data *pgdat)
1355 struct mem_cgroup_per_node *mz;
1356 struct mem_cgroup *memcg;
1357 struct lruvec *lruvec;
1359 if (mem_cgroup_disabled()) {
1360 lruvec = &pgdat->__lruvec;
1364 memcg = page_memcg(page);
1366 * Swapcache readahead pages are added to the LRU - and
1367 * possibly migrated - before they are charged.
1370 memcg = root_mem_cgroup;
1372 mz = mem_cgroup_page_nodeinfo(memcg, page);
1373 lruvec = &mz->lruvec;
1376 * Since a node can be onlined after the mem_cgroup was created,
1377 * we have to be prepared to initialize lruvec->zone here;
1378 * and if offlined then reonlined, we need to reinitialize it.
1380 if (unlikely(lruvec->pgdat != pgdat))
1381 lruvec->pgdat = pgdat;
1386 * lock_page_lruvec - lock and return lruvec for a given page.
1389 * This series functions should be used in either conditions:
1390 * PageLRU is cleared or unset
1391 * or page->_refcount is zero
1392 * or page is locked.
1394 struct lruvec *lock_page_lruvec(struct page *page)
1396 struct lruvec *lruvec;
1397 struct pglist_data *pgdat = page_pgdat(page);
1400 lruvec = mem_cgroup_page_lruvec(page, pgdat);
1401 spin_lock(&lruvec->lru_lock);
1404 lruvec_memcg_debug(lruvec, page);
1409 struct lruvec *lock_page_lruvec_irq(struct page *page)
1411 struct lruvec *lruvec;
1412 struct pglist_data *pgdat = page_pgdat(page);
1415 lruvec = mem_cgroup_page_lruvec(page, pgdat);
1416 spin_lock_irq(&lruvec->lru_lock);
1419 lruvec_memcg_debug(lruvec, page);
1424 struct lruvec *lock_page_lruvec_irqsave(struct page *page, unsigned long *flags)
1426 struct lruvec *lruvec;
1427 struct pglist_data *pgdat = page_pgdat(page);
1430 lruvec = mem_cgroup_page_lruvec(page, pgdat);
1431 spin_lock_irqsave(&lruvec->lru_lock, *flags);
1434 lruvec_memcg_debug(lruvec, page);
1440 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1441 * @lruvec: mem_cgroup per zone lru vector
1442 * @lru: index of lru list the page is sitting on
1443 * @zid: zone id of the accounted pages
1444 * @nr_pages: positive when adding or negative when removing
1446 * This function must be called under lru_lock, just before a page is added
1447 * to or just after a page is removed from an lru list (that ordering being
1448 * so as to allow it to check that lru_size 0 is consistent with list_empty).
1450 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1451 int zid, int nr_pages)
1453 struct mem_cgroup_per_node *mz;
1454 unsigned long *lru_size;
1457 if (mem_cgroup_disabled())
1460 mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
1461 lru_size = &mz->lru_zone_size[zid][lru];
1464 *lru_size += nr_pages;
1467 if (WARN_ONCE(size < 0,
1468 "%s(%p, %d, %d): lru_size %ld\n",
1469 __func__, lruvec, lru, nr_pages, size)) {
1475 *lru_size += nr_pages;
1479 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1480 * @memcg: the memory cgroup
1482 * Returns the maximum amount of memory @mem can be charged with, in
1485 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1487 unsigned long margin = 0;
1488 unsigned long count;
1489 unsigned long limit;
1491 count = page_counter_read(&memcg->memory);
1492 limit = READ_ONCE(memcg->memory.max);
1494 margin = limit - count;
1496 if (do_memsw_account()) {
1497 count = page_counter_read(&memcg->memsw);
1498 limit = READ_ONCE(memcg->memsw.max);
1500 margin = min(margin, limit - count);
1509 * A routine for checking "mem" is under move_account() or not.
1511 * Checking a cgroup is mc.from or mc.to or under hierarchy of
1512 * moving cgroups. This is for waiting at high-memory pressure
1515 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1517 struct mem_cgroup *from;
1518 struct mem_cgroup *to;
1521 * Unlike task_move routines, we access mc.to, mc.from not under
1522 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1524 spin_lock(&mc.lock);
1530 ret = mem_cgroup_is_descendant(from, memcg) ||
1531 mem_cgroup_is_descendant(to, memcg);
1533 spin_unlock(&mc.lock);
1537 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1539 if (mc.moving_task && current != mc.moving_task) {
1540 if (mem_cgroup_under_move(memcg)) {
1542 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1543 /* moving charge context might have finished. */
1546 finish_wait(&mc.waitq, &wait);
1553 struct memory_stat {
1559 static struct memory_stat memory_stats[] = {
1560 { "anon", PAGE_SIZE, NR_ANON_MAPPED },
1561 { "file", PAGE_SIZE, NR_FILE_PAGES },
1562 { "kernel_stack", 1024, NR_KERNEL_STACK_KB },
1563 { "pagetables", PAGE_SIZE, NR_PAGETABLE },
1564 { "percpu", 1, MEMCG_PERCPU_B },
1565 { "sock", PAGE_SIZE, MEMCG_SOCK },
1566 { "shmem", PAGE_SIZE, NR_SHMEM },
1567 { "file_mapped", PAGE_SIZE, NR_FILE_MAPPED },
1568 { "file_dirty", PAGE_SIZE, NR_FILE_DIRTY },
1569 { "file_writeback", PAGE_SIZE, NR_WRITEBACK },
1570 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1572 * The ratio will be initialized in memory_stats_init(). Because
1573 * on some architectures, the macro of HPAGE_PMD_SIZE is not
1574 * constant(e.g. powerpc).
1576 { "anon_thp", 0, NR_ANON_THPS },
1577 { "file_thp", 0, NR_FILE_THPS },
1578 { "shmem_thp", 0, NR_SHMEM_THPS },
1580 { "inactive_anon", PAGE_SIZE, NR_INACTIVE_ANON },
1581 { "active_anon", PAGE_SIZE, NR_ACTIVE_ANON },
1582 { "inactive_file", PAGE_SIZE, NR_INACTIVE_FILE },
1583 { "active_file", PAGE_SIZE, NR_ACTIVE_FILE },
1584 { "unevictable", PAGE_SIZE, NR_UNEVICTABLE },
1587 * Note: The slab_reclaimable and slab_unreclaimable must be
1588 * together and slab_reclaimable must be in front.
1590 { "slab_reclaimable", 1, NR_SLAB_RECLAIMABLE_B },
1591 { "slab_unreclaimable", 1, NR_SLAB_UNRECLAIMABLE_B },
1593 /* The memory events */
1594 { "workingset_refault_anon", 1, WORKINGSET_REFAULT_ANON },
1595 { "workingset_refault_file", 1, WORKINGSET_REFAULT_FILE },
1596 { "workingset_activate_anon", 1, WORKINGSET_ACTIVATE_ANON },
1597 { "workingset_activate_file", 1, WORKINGSET_ACTIVATE_FILE },
1598 { "workingset_restore_anon", 1, WORKINGSET_RESTORE_ANON },
1599 { "workingset_restore_file", 1, WORKINGSET_RESTORE_FILE },
1600 { "workingset_nodereclaim", 1, WORKINGSET_NODERECLAIM },
1603 static int __init memory_stats_init(void)
1607 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
1608 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1609 if (memory_stats[i].idx == NR_ANON_THPS ||
1610 memory_stats[i].idx == NR_FILE_THPS ||
1611 memory_stats[i].idx == NR_SHMEM_THPS)
1612 memory_stats[i].ratio = HPAGE_PMD_SIZE;
1614 VM_BUG_ON(!memory_stats[i].ratio);
1615 VM_BUG_ON(memory_stats[i].idx >= MEMCG_NR_STAT);
1620 pure_initcall(memory_stats_init);
1622 static char *memory_stat_format(struct mem_cgroup *memcg)
1627 seq_buf_init(&s, kmalloc(PAGE_SIZE, GFP_KERNEL), PAGE_SIZE);
1632 * Provide statistics on the state of the memory subsystem as
1633 * well as cumulative event counters that show past behavior.
1635 * This list is ordered following a combination of these gradients:
1636 * 1) generic big picture -> specifics and details
1637 * 2) reflecting userspace activity -> reflecting kernel heuristics
1639 * Current memory state:
1642 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
1645 size = memcg_page_state(memcg, memory_stats[i].idx);
1646 size *= memory_stats[i].ratio;
1647 seq_buf_printf(&s, "%s %llu\n", memory_stats[i].name, size);
1649 if (unlikely(memory_stats[i].idx == NR_SLAB_UNRECLAIMABLE_B)) {
1650 size = memcg_page_state(memcg, NR_SLAB_RECLAIMABLE_B) +
1651 memcg_page_state(memcg, NR_SLAB_UNRECLAIMABLE_B);
1652 seq_buf_printf(&s, "slab %llu\n", size);
1656 /* Accumulated memory events */
1658 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGFAULT),
1659 memcg_events(memcg, PGFAULT));
1660 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGMAJFAULT),
1661 memcg_events(memcg, PGMAJFAULT));
1662 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGREFILL),
1663 memcg_events(memcg, PGREFILL));
1664 seq_buf_printf(&s, "pgscan %lu\n",
1665 memcg_events(memcg, PGSCAN_KSWAPD) +
1666 memcg_events(memcg, PGSCAN_DIRECT));
1667 seq_buf_printf(&s, "pgsteal %lu\n",
1668 memcg_events(memcg, PGSTEAL_KSWAPD) +
1669 memcg_events(memcg, PGSTEAL_DIRECT));
1670 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGACTIVATE),
1671 memcg_events(memcg, PGACTIVATE));
1672 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGDEACTIVATE),
1673 memcg_events(memcg, PGDEACTIVATE));
1674 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGLAZYFREE),
1675 memcg_events(memcg, PGLAZYFREE));
1676 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGLAZYFREED),
1677 memcg_events(memcg, PGLAZYFREED));
1679 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1680 seq_buf_printf(&s, "%s %lu\n", vm_event_name(THP_FAULT_ALLOC),
1681 memcg_events(memcg, THP_FAULT_ALLOC));
1682 seq_buf_printf(&s, "%s %lu\n", vm_event_name(THP_COLLAPSE_ALLOC),
1683 memcg_events(memcg, THP_COLLAPSE_ALLOC));
1684 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
1686 /* The above should easily fit into one page */
1687 WARN_ON_ONCE(seq_buf_has_overflowed(&s));
1692 #define K(x) ((x) << (PAGE_SHIFT-10))
1694 * mem_cgroup_print_oom_context: Print OOM information relevant to
1695 * memory controller.
1696 * @memcg: The memory cgroup that went over limit
1697 * @p: Task that is going to be killed
1699 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1702 void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p)
1707 pr_cont(",oom_memcg=");
1708 pr_cont_cgroup_path(memcg->css.cgroup);
1710 pr_cont(",global_oom");
1712 pr_cont(",task_memcg=");
1713 pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
1719 * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
1720 * memory controller.
1721 * @memcg: The memory cgroup that went over limit
1723 void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
1727 pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1728 K((u64)page_counter_read(&memcg->memory)),
1729 K((u64)READ_ONCE(memcg->memory.max)), memcg->memory.failcnt);
1730 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1731 pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n",
1732 K((u64)page_counter_read(&memcg->swap)),
1733 K((u64)READ_ONCE(memcg->swap.max)), memcg->swap.failcnt);
1735 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1736 K((u64)page_counter_read(&memcg->memsw)),
1737 K((u64)memcg->memsw.max), memcg->memsw.failcnt);
1738 pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1739 K((u64)page_counter_read(&memcg->kmem)),
1740 K((u64)memcg->kmem.max), memcg->kmem.failcnt);
1743 pr_info("Memory cgroup stats for ");
1744 pr_cont_cgroup_path(memcg->css.cgroup);
1746 buf = memory_stat_format(memcg);
1754 * Return the memory (and swap, if configured) limit for a memcg.
1756 unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg)
1758 unsigned long max = READ_ONCE(memcg->memory.max);
1760 if (cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
1761 if (mem_cgroup_swappiness(memcg))
1762 max += min(READ_ONCE(memcg->swap.max),
1763 (unsigned long)total_swap_pages);
1765 if (mem_cgroup_swappiness(memcg)) {
1766 /* Calculate swap excess capacity from memsw limit */
1767 unsigned long swap = READ_ONCE(memcg->memsw.max) - max;
1769 max += min(swap, (unsigned long)total_swap_pages);
1775 unsigned long mem_cgroup_size(struct mem_cgroup *memcg)
1777 return page_counter_read(&memcg->memory);
1780 static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1783 struct oom_control oc = {
1787 .gfp_mask = gfp_mask,
1792 if (mutex_lock_killable(&oom_lock))
1795 if (mem_cgroup_margin(memcg) >= (1 << order))
1799 * A few threads which were not waiting at mutex_lock_killable() can
1800 * fail to bail out. Therefore, check again after holding oom_lock.
1802 ret = should_force_charge() || out_of_memory(&oc);
1805 mutex_unlock(&oom_lock);
1809 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
1812 unsigned long *total_scanned)
1814 struct mem_cgroup *victim = NULL;
1817 unsigned long excess;
1818 unsigned long nr_scanned;
1819 struct mem_cgroup_reclaim_cookie reclaim = {
1823 excess = soft_limit_excess(root_memcg);
1826 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1831 * If we have not been able to reclaim
1832 * anything, it might because there are
1833 * no reclaimable pages under this hierarchy
1838 * We want to do more targeted reclaim.
1839 * excess >> 2 is not to excessive so as to
1840 * reclaim too much, nor too less that we keep
1841 * coming back to reclaim from this cgroup
1843 if (total >= (excess >> 2) ||
1844 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1849 total += mem_cgroup_shrink_node(victim, gfp_mask, false,
1850 pgdat, &nr_scanned);
1851 *total_scanned += nr_scanned;
1852 if (!soft_limit_excess(root_memcg))
1855 mem_cgroup_iter_break(root_memcg, victim);
1859 #ifdef CONFIG_LOCKDEP
1860 static struct lockdep_map memcg_oom_lock_dep_map = {
1861 .name = "memcg_oom_lock",
1865 static DEFINE_SPINLOCK(memcg_oom_lock);
1868 * Check OOM-Killer is already running under our hierarchy.
1869 * If someone is running, return false.
1871 static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
1873 struct mem_cgroup *iter, *failed = NULL;
1875 spin_lock(&memcg_oom_lock);
1877 for_each_mem_cgroup_tree(iter, memcg) {
1878 if (iter->oom_lock) {
1880 * this subtree of our hierarchy is already locked
1881 * so we cannot give a lock.
1884 mem_cgroup_iter_break(memcg, iter);
1887 iter->oom_lock = true;
1892 * OK, we failed to lock the whole subtree so we have
1893 * to clean up what we set up to the failing subtree
1895 for_each_mem_cgroup_tree(iter, memcg) {
1896 if (iter == failed) {
1897 mem_cgroup_iter_break(memcg, iter);
1900 iter->oom_lock = false;
1903 mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
1905 spin_unlock(&memcg_oom_lock);
1910 static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1912 struct mem_cgroup *iter;
1914 spin_lock(&memcg_oom_lock);
1915 mutex_release(&memcg_oom_lock_dep_map, _RET_IP_);
1916 for_each_mem_cgroup_tree(iter, memcg)
1917 iter->oom_lock = false;
1918 spin_unlock(&memcg_oom_lock);
1921 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1923 struct mem_cgroup *iter;
1925 spin_lock(&memcg_oom_lock);
1926 for_each_mem_cgroup_tree(iter, memcg)
1928 spin_unlock(&memcg_oom_lock);
1931 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1933 struct mem_cgroup *iter;
1936 * Be careful about under_oom underflows becase a child memcg
1937 * could have been added after mem_cgroup_mark_under_oom.
1939 spin_lock(&memcg_oom_lock);
1940 for_each_mem_cgroup_tree(iter, memcg)
1941 if (iter->under_oom > 0)
1943 spin_unlock(&memcg_oom_lock);
1946 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1948 struct oom_wait_info {
1949 struct mem_cgroup *memcg;
1950 wait_queue_entry_t wait;
1953 static int memcg_oom_wake_function(wait_queue_entry_t *wait,
1954 unsigned mode, int sync, void *arg)
1956 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
1957 struct mem_cgroup *oom_wait_memcg;
1958 struct oom_wait_info *oom_wait_info;
1960 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1961 oom_wait_memcg = oom_wait_info->memcg;
1963 if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
1964 !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
1966 return autoremove_wake_function(wait, mode, sync, arg);
1969 static void memcg_oom_recover(struct mem_cgroup *memcg)
1972 * For the following lockless ->under_oom test, the only required
1973 * guarantee is that it must see the state asserted by an OOM when
1974 * this function is called as a result of userland actions
1975 * triggered by the notification of the OOM. This is trivially
1976 * achieved by invoking mem_cgroup_mark_under_oom() before
1977 * triggering notification.
1979 if (memcg && memcg->under_oom)
1980 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
1990 static enum oom_status mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
1992 enum oom_status ret;
1995 if (order > PAGE_ALLOC_COSTLY_ORDER)
1998 memcg_memory_event(memcg, MEMCG_OOM);
2001 * We are in the middle of the charge context here, so we
2002 * don't want to block when potentially sitting on a callstack
2003 * that holds all kinds of filesystem and mm locks.
2005 * cgroup1 allows disabling the OOM killer and waiting for outside
2006 * handling until the charge can succeed; remember the context and put
2007 * the task to sleep at the end of the page fault when all locks are
2010 * On the other hand, in-kernel OOM killer allows for an async victim
2011 * memory reclaim (oom_reaper) and that means that we are not solely
2012 * relying on the oom victim to make a forward progress and we can
2013 * invoke the oom killer here.
2015 * Please note that mem_cgroup_out_of_memory might fail to find a
2016 * victim and then we have to bail out from the charge path.
2018 if (memcg->oom_kill_disable) {
2019 if (!current->in_user_fault)
2021 css_get(&memcg->css);
2022 current->memcg_in_oom = memcg;
2023 current->memcg_oom_gfp_mask = mask;
2024 current->memcg_oom_order = order;
2029 mem_cgroup_mark_under_oom(memcg);
2031 locked = mem_cgroup_oom_trylock(memcg);
2034 mem_cgroup_oom_notify(memcg);
2036 mem_cgroup_unmark_under_oom(memcg);
2037 if (mem_cgroup_out_of_memory(memcg, mask, order))
2043 mem_cgroup_oom_unlock(memcg);
2049 * mem_cgroup_oom_synchronize - complete memcg OOM handling
2050 * @handle: actually kill/wait or just clean up the OOM state
2052 * This has to be called at the end of a page fault if the memcg OOM
2053 * handler was enabled.
2055 * Memcg supports userspace OOM handling where failed allocations must
2056 * sleep on a waitqueue until the userspace task resolves the
2057 * situation. Sleeping directly in the charge context with all kinds
2058 * of locks held is not a good idea, instead we remember an OOM state
2059 * in the task and mem_cgroup_oom_synchronize() has to be called at
2060 * the end of the page fault to complete the OOM handling.
2062 * Returns %true if an ongoing memcg OOM situation was detected and
2063 * completed, %false otherwise.
2065 bool mem_cgroup_oom_synchronize(bool handle)
2067 struct mem_cgroup *memcg = current->memcg_in_oom;
2068 struct oom_wait_info owait;
2071 /* OOM is global, do not handle */
2078 owait.memcg = memcg;
2079 owait.wait.flags = 0;
2080 owait.wait.func = memcg_oom_wake_function;
2081 owait.wait.private = current;
2082 INIT_LIST_HEAD(&owait.wait.entry);
2084 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
2085 mem_cgroup_mark_under_oom(memcg);
2087 locked = mem_cgroup_oom_trylock(memcg);
2090 mem_cgroup_oom_notify(memcg);
2092 if (locked && !memcg->oom_kill_disable) {
2093 mem_cgroup_unmark_under_oom(memcg);
2094 finish_wait(&memcg_oom_waitq, &owait.wait);
2095 mem_cgroup_out_of_memory(memcg, current->memcg_oom_gfp_mask,
2096 current->memcg_oom_order);
2099 mem_cgroup_unmark_under_oom(memcg);
2100 finish_wait(&memcg_oom_waitq, &owait.wait);
2104 mem_cgroup_oom_unlock(memcg);
2106 * There is no guarantee that an OOM-lock contender
2107 * sees the wakeups triggered by the OOM kill
2108 * uncharges. Wake any sleepers explicitely.
2110 memcg_oom_recover(memcg);
2113 current->memcg_in_oom = NULL;
2114 css_put(&memcg->css);
2119 * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
2120 * @victim: task to be killed by the OOM killer
2121 * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
2123 * Returns a pointer to a memory cgroup, which has to be cleaned up
2124 * by killing all belonging OOM-killable tasks.
2126 * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
2128 struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim,
2129 struct mem_cgroup *oom_domain)
2131 struct mem_cgroup *oom_group = NULL;
2132 struct mem_cgroup *memcg;
2134 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
2138 oom_domain = root_mem_cgroup;
2142 memcg = mem_cgroup_from_task(victim);
2143 if (memcg == root_mem_cgroup)
2147 * If the victim task has been asynchronously moved to a different
2148 * memory cgroup, we might end up killing tasks outside oom_domain.
2149 * In this case it's better to ignore memory.group.oom.
2151 if (unlikely(!mem_cgroup_is_descendant(memcg, oom_domain)))
2155 * Traverse the memory cgroup hierarchy from the victim task's
2156 * cgroup up to the OOMing cgroup (or root) to find the
2157 * highest-level memory cgroup with oom.group set.
2159 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
2160 if (memcg->oom_group)
2163 if (memcg == oom_domain)
2168 css_get(&oom_group->css);
2175 void mem_cgroup_print_oom_group(struct mem_cgroup *memcg)
2177 pr_info("Tasks in ");
2178 pr_cont_cgroup_path(memcg->css.cgroup);
2179 pr_cont(" are going to be killed due to memory.oom.group set\n");
2183 * lock_page_memcg - lock a page and memcg binding
2186 * This function protects unlocked LRU pages from being moved to
2189 * It ensures lifetime of the returned memcg. Caller is responsible
2190 * for the lifetime of the page; __unlock_page_memcg() is available
2191 * when @page might get freed inside the locked section.
2193 struct mem_cgroup *lock_page_memcg(struct page *page)
2195 struct page *head = compound_head(page); /* rmap on tail pages */
2196 struct mem_cgroup *memcg;
2197 unsigned long flags;
2200 * The RCU lock is held throughout the transaction. The fast
2201 * path can get away without acquiring the memcg->move_lock
2202 * because page moving starts with an RCU grace period.
2204 * The RCU lock also protects the memcg from being freed when
2205 * the page state that is going to change is the only thing
2206 * preventing the page itself from being freed. E.g. writeback
2207 * doesn't hold a page reference and relies on PG_writeback to
2208 * keep off truncation, migration and so forth.
2212 if (mem_cgroup_disabled())
2215 memcg = page_memcg(head);
2216 if (unlikely(!memcg))
2219 #ifdef CONFIG_PROVE_LOCKING
2220 local_irq_save(flags);
2221 might_lock(&memcg->move_lock);
2222 local_irq_restore(flags);
2225 if (atomic_read(&memcg->moving_account) <= 0)
2228 spin_lock_irqsave(&memcg->move_lock, flags);
2229 if (memcg != page_memcg(head)) {
2230 spin_unlock_irqrestore(&memcg->move_lock, flags);
2235 * When charge migration first begins, we can have locked and
2236 * unlocked page stat updates happening concurrently. Track
2237 * the task who has the lock for unlock_page_memcg().
2239 memcg->move_lock_task = current;
2240 memcg->move_lock_flags = flags;
2244 EXPORT_SYMBOL(lock_page_memcg);
2247 * __unlock_page_memcg - unlock and unpin a memcg
2250 * Unlock and unpin a memcg returned by lock_page_memcg().
2252 void __unlock_page_memcg(struct mem_cgroup *memcg)
2254 if (memcg && memcg->move_lock_task == current) {
2255 unsigned long flags = memcg->move_lock_flags;
2257 memcg->move_lock_task = NULL;
2258 memcg->move_lock_flags = 0;
2260 spin_unlock_irqrestore(&memcg->move_lock, flags);
2267 * unlock_page_memcg - unlock a page and memcg binding
2270 void unlock_page_memcg(struct page *page)
2272 struct page *head = compound_head(page);
2274 __unlock_page_memcg(page_memcg(head));
2276 EXPORT_SYMBOL(unlock_page_memcg);
2278 struct memcg_stock_pcp {
2279 struct mem_cgroup *cached; /* this never be root cgroup */
2280 unsigned int nr_pages;
2282 #ifdef CONFIG_MEMCG_KMEM
2283 struct obj_cgroup *cached_objcg;
2284 unsigned int nr_bytes;
2287 struct work_struct work;
2288 unsigned long flags;
2289 #define FLUSHING_CACHED_CHARGE 0
2291 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
2292 static DEFINE_MUTEX(percpu_charge_mutex);
2294 #ifdef CONFIG_MEMCG_KMEM
2295 static void drain_obj_stock(struct memcg_stock_pcp *stock);
2296 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2297 struct mem_cgroup *root_memcg);
2300 static inline void drain_obj_stock(struct memcg_stock_pcp *stock)
2303 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2304 struct mem_cgroup *root_memcg)
2311 * consume_stock: Try to consume stocked charge on this cpu.
2312 * @memcg: memcg to consume from.
2313 * @nr_pages: how many pages to charge.
2315 * The charges will only happen if @memcg matches the current cpu's memcg
2316 * stock, and at least @nr_pages are available in that stock. Failure to
2317 * service an allocation will refill the stock.
2319 * returns true if successful, false otherwise.
2321 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2323 struct memcg_stock_pcp *stock;
2324 unsigned long flags;
2327 if (nr_pages > MEMCG_CHARGE_BATCH)
2330 local_irq_save(flags);
2332 stock = this_cpu_ptr(&memcg_stock);
2333 if (memcg == stock->cached && stock->nr_pages >= nr_pages) {
2334 stock->nr_pages -= nr_pages;
2338 local_irq_restore(flags);
2344 * Returns stocks cached in percpu and reset cached information.
2346 static void drain_stock(struct memcg_stock_pcp *stock)
2348 struct mem_cgroup *old = stock->cached;
2353 if (stock->nr_pages) {
2354 page_counter_uncharge(&old->memory, stock->nr_pages);
2355 if (do_memsw_account())
2356 page_counter_uncharge(&old->memsw, stock->nr_pages);
2357 stock->nr_pages = 0;
2361 stock->cached = NULL;
2364 static void drain_local_stock(struct work_struct *dummy)
2366 struct memcg_stock_pcp *stock;
2367 unsigned long flags;
2370 * The only protection from memory hotplug vs. drain_stock races is
2371 * that we always operate on local CPU stock here with IRQ disabled
2373 local_irq_save(flags);
2375 stock = this_cpu_ptr(&memcg_stock);
2376 drain_obj_stock(stock);
2378 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2380 local_irq_restore(flags);
2384 * Cache charges(val) to local per_cpu area.
2385 * This will be consumed by consume_stock() function, later.
2387 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2389 struct memcg_stock_pcp *stock;
2390 unsigned long flags;
2392 local_irq_save(flags);
2394 stock = this_cpu_ptr(&memcg_stock);
2395 if (stock->cached != memcg) { /* reset if necessary */
2397 css_get(&memcg->css);
2398 stock->cached = memcg;
2400 stock->nr_pages += nr_pages;
2402 if (stock->nr_pages > MEMCG_CHARGE_BATCH)
2405 local_irq_restore(flags);
2409 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2410 * of the hierarchy under it.
2412 static void drain_all_stock(struct mem_cgroup *root_memcg)
2416 /* If someone's already draining, avoid adding running more workers. */
2417 if (!mutex_trylock(&percpu_charge_mutex))
2420 * Notify other cpus that system-wide "drain" is running
2421 * We do not care about races with the cpu hotplug because cpu down
2422 * as well as workers from this path always operate on the local
2423 * per-cpu data. CPU up doesn't touch memcg_stock at all.
2426 for_each_online_cpu(cpu) {
2427 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2428 struct mem_cgroup *memcg;
2432 memcg = stock->cached;
2433 if (memcg && stock->nr_pages &&
2434 mem_cgroup_is_descendant(memcg, root_memcg))
2436 if (obj_stock_flush_required(stock, root_memcg))
2441 !test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2443 drain_local_stock(&stock->work);
2445 schedule_work_on(cpu, &stock->work);
2449 mutex_unlock(&percpu_charge_mutex);
2452 static int memcg_hotplug_cpu_dead(unsigned int cpu)
2454 struct memcg_stock_pcp *stock;
2455 struct mem_cgroup *memcg, *mi;
2457 stock = &per_cpu(memcg_stock, cpu);
2460 for_each_mem_cgroup(memcg) {
2463 for (i = 0; i < MEMCG_NR_STAT; i++) {
2467 x = this_cpu_xchg(memcg->vmstats_percpu->stat[i], 0);
2469 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
2470 atomic_long_add(x, &memcg->vmstats[i]);
2472 if (i >= NR_VM_NODE_STAT_ITEMS)
2475 for_each_node(nid) {
2476 struct mem_cgroup_per_node *pn;
2478 pn = mem_cgroup_nodeinfo(memcg, nid);
2479 x = this_cpu_xchg(pn->lruvec_stat_cpu->count[i], 0);
2482 atomic_long_add(x, &pn->lruvec_stat[i]);
2483 } while ((pn = parent_nodeinfo(pn, nid)));
2487 for (i = 0; i < NR_VM_EVENT_ITEMS; i++) {
2490 x = this_cpu_xchg(memcg->vmstats_percpu->events[i], 0);
2492 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
2493 atomic_long_add(x, &memcg->vmevents[i]);
2500 static unsigned long reclaim_high(struct mem_cgroup *memcg,
2501 unsigned int nr_pages,
2504 unsigned long nr_reclaimed = 0;
2507 unsigned long pflags;
2509 if (page_counter_read(&memcg->memory) <=
2510 READ_ONCE(memcg->memory.high))
2513 memcg_memory_event(memcg, MEMCG_HIGH);
2515 psi_memstall_enter(&pflags);
2516 nr_reclaimed += try_to_free_mem_cgroup_pages(memcg, nr_pages,
2518 psi_memstall_leave(&pflags);
2519 } while ((memcg = parent_mem_cgroup(memcg)) &&
2520 !mem_cgroup_is_root(memcg));
2522 return nr_reclaimed;
2525 static void high_work_func(struct work_struct *work)
2527 struct mem_cgroup *memcg;
2529 memcg = container_of(work, struct mem_cgroup, high_work);
2530 reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
2534 * Clamp the maximum sleep time per allocation batch to 2 seconds. This is
2535 * enough to still cause a significant slowdown in most cases, while still
2536 * allowing diagnostics and tracing to proceed without becoming stuck.
2538 #define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ)
2541 * When calculating the delay, we use these either side of the exponentiation to
2542 * maintain precision and scale to a reasonable number of jiffies (see the table
2545 * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the
2546 * overage ratio to a delay.
2547 * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down the
2548 * proposed penalty in order to reduce to a reasonable number of jiffies, and
2549 * to produce a reasonable delay curve.
2551 * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a
2552 * reasonable delay curve compared to precision-adjusted overage, not
2553 * penalising heavily at first, but still making sure that growth beyond the
2554 * limit penalises misbehaviour cgroups by slowing them down exponentially. For
2555 * example, with a high of 100 megabytes:
2557 * +-------+------------------------+
2558 * | usage | time to allocate in ms |
2559 * +-------+------------------------+
2581 * +-------+------------------------+
2583 #define MEMCG_DELAY_PRECISION_SHIFT 20
2584 #define MEMCG_DELAY_SCALING_SHIFT 14
2586 static u64 calculate_overage(unsigned long usage, unsigned long high)
2594 * Prevent division by 0 in overage calculation by acting as if
2595 * it was a threshold of 1 page
2597 high = max(high, 1UL);
2599 overage = usage - high;
2600 overage <<= MEMCG_DELAY_PRECISION_SHIFT;
2601 return div64_u64(overage, high);
2604 static u64 mem_find_max_overage(struct mem_cgroup *memcg)
2606 u64 overage, max_overage = 0;
2609 overage = calculate_overage(page_counter_read(&memcg->memory),
2610 READ_ONCE(memcg->memory.high));
2611 max_overage = max(overage, max_overage);
2612 } while ((memcg = parent_mem_cgroup(memcg)) &&
2613 !mem_cgroup_is_root(memcg));
2618 static u64 swap_find_max_overage(struct mem_cgroup *memcg)
2620 u64 overage, max_overage = 0;
2623 overage = calculate_overage(page_counter_read(&memcg->swap),
2624 READ_ONCE(memcg->swap.high));
2626 memcg_memory_event(memcg, MEMCG_SWAP_HIGH);
2627 max_overage = max(overage, max_overage);
2628 } while ((memcg = parent_mem_cgroup(memcg)) &&
2629 !mem_cgroup_is_root(memcg));
2635 * Get the number of jiffies that we should penalise a mischievous cgroup which
2636 * is exceeding its memory.high by checking both it and its ancestors.
2638 static unsigned long calculate_high_delay(struct mem_cgroup *memcg,
2639 unsigned int nr_pages,
2642 unsigned long penalty_jiffies;
2648 * We use overage compared to memory.high to calculate the number of
2649 * jiffies to sleep (penalty_jiffies). Ideally this value should be
2650 * fairly lenient on small overages, and increasingly harsh when the
2651 * memcg in question makes it clear that it has no intention of stopping
2652 * its crazy behaviour, so we exponentially increase the delay based on
2655 penalty_jiffies = max_overage * max_overage * HZ;
2656 penalty_jiffies >>= MEMCG_DELAY_PRECISION_SHIFT;
2657 penalty_jiffies >>= MEMCG_DELAY_SCALING_SHIFT;
2660 * Factor in the task's own contribution to the overage, such that four
2661 * N-sized allocations are throttled approximately the same as one
2662 * 4N-sized allocation.
2664 * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or
2665 * larger the current charge patch is than that.
2667 return penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH;
2671 * Scheduled by try_charge() to be executed from the userland return path
2672 * and reclaims memory over the high limit.
2674 void mem_cgroup_handle_over_high(void)
2676 unsigned long penalty_jiffies;
2677 unsigned long pflags;
2678 unsigned long nr_reclaimed;
2679 unsigned int nr_pages = current->memcg_nr_pages_over_high;
2680 int nr_retries = MAX_RECLAIM_RETRIES;
2681 struct mem_cgroup *memcg;
2682 bool in_retry = false;
2684 if (likely(!nr_pages))
2687 memcg = get_mem_cgroup_from_mm(current->mm);
2688 current->memcg_nr_pages_over_high = 0;
2692 * The allocating task should reclaim at least the batch size, but for
2693 * subsequent retries we only want to do what's necessary to prevent oom
2694 * or breaching resource isolation.
2696 * This is distinct from memory.max or page allocator behaviour because
2697 * memory.high is currently batched, whereas memory.max and the page
2698 * allocator run every time an allocation is made.
2700 nr_reclaimed = reclaim_high(memcg,
2701 in_retry ? SWAP_CLUSTER_MAX : nr_pages,
2705 * memory.high is breached and reclaim is unable to keep up. Throttle
2706 * allocators proactively to slow down excessive growth.
2708 penalty_jiffies = calculate_high_delay(memcg, nr_pages,
2709 mem_find_max_overage(memcg));
2711 penalty_jiffies += calculate_high_delay(memcg, nr_pages,
2712 swap_find_max_overage(memcg));
2715 * Clamp the max delay per usermode return so as to still keep the
2716 * application moving forwards and also permit diagnostics, albeit
2719 penalty_jiffies = min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES);
2722 * Don't sleep if the amount of jiffies this memcg owes us is so low
2723 * that it's not even worth doing, in an attempt to be nice to those who
2724 * go only a small amount over their memory.high value and maybe haven't
2725 * been aggressively reclaimed enough yet.
2727 if (penalty_jiffies <= HZ / 100)
2731 * If reclaim is making forward progress but we're still over
2732 * memory.high, we want to encourage that rather than doing allocator
2735 if (nr_reclaimed || nr_retries--) {
2741 * If we exit early, we're guaranteed to die (since
2742 * schedule_timeout_killable sets TASK_KILLABLE). This means we don't
2743 * need to account for any ill-begotten jiffies to pay them off later.
2745 psi_memstall_enter(&pflags);
2746 schedule_timeout_killable(penalty_jiffies);
2747 psi_memstall_leave(&pflags);
2750 css_put(&memcg->css);
2753 static int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2754 unsigned int nr_pages)
2756 unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
2757 int nr_retries = MAX_RECLAIM_RETRIES;
2758 struct mem_cgroup *mem_over_limit;
2759 struct page_counter *counter;
2760 enum oom_status oom_status;
2761 unsigned long nr_reclaimed;
2762 bool may_swap = true;
2763 bool drained = false;
2764 unsigned long pflags;
2766 if (mem_cgroup_is_root(memcg))
2769 if (consume_stock(memcg, nr_pages))
2772 if (!do_memsw_account() ||
2773 page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2774 if (page_counter_try_charge(&memcg->memory, batch, &counter))
2776 if (do_memsw_account())
2777 page_counter_uncharge(&memcg->memsw, batch);
2778 mem_over_limit = mem_cgroup_from_counter(counter, memory);
2780 mem_over_limit = mem_cgroup_from_counter(counter, memsw);
2784 if (batch > nr_pages) {
2790 * Memcg doesn't have a dedicated reserve for atomic
2791 * allocations. But like the global atomic pool, we need to
2792 * put the burden of reclaim on regular allocation requests
2793 * and let these go through as privileged allocations.
2795 if (gfp_mask & __GFP_ATOMIC)
2799 * Unlike in global OOM situations, memcg is not in a physical
2800 * memory shortage. Allow dying and OOM-killed tasks to
2801 * bypass the last charges so that they can exit quickly and
2802 * free their memory.
2804 if (unlikely(should_force_charge()))
2808 * Prevent unbounded recursion when reclaim operations need to
2809 * allocate memory. This might exceed the limits temporarily,
2810 * but we prefer facilitating memory reclaim and getting back
2811 * under the limit over triggering OOM kills in these cases.
2813 if (unlikely(current->flags & PF_MEMALLOC))
2816 if (unlikely(task_in_memcg_oom(current)))
2819 if (!gfpflags_allow_blocking(gfp_mask))
2822 memcg_memory_event(mem_over_limit, MEMCG_MAX);
2824 psi_memstall_enter(&pflags);
2825 nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
2826 gfp_mask, may_swap);
2827 psi_memstall_leave(&pflags);
2829 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2833 drain_all_stock(mem_over_limit);
2838 if (gfp_mask & __GFP_NORETRY)
2841 * Even though the limit is exceeded at this point, reclaim
2842 * may have been able to free some pages. Retry the charge
2843 * before killing the task.
2845 * Only for regular pages, though: huge pages are rather
2846 * unlikely to succeed so close to the limit, and we fall back
2847 * to regular pages anyway in case of failure.
2849 if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
2852 * At task move, charge accounts can be doubly counted. So, it's
2853 * better to wait until the end of task_move if something is going on.
2855 if (mem_cgroup_wait_acct_move(mem_over_limit))
2861 if (gfp_mask & __GFP_RETRY_MAYFAIL)
2864 if (gfp_mask & __GFP_NOFAIL)
2867 if (fatal_signal_pending(current))
2871 * keep retrying as long as the memcg oom killer is able to make
2872 * a forward progress or bypass the charge if the oom killer
2873 * couldn't make any progress.
2875 oom_status = mem_cgroup_oom(mem_over_limit, gfp_mask,
2876 get_order(nr_pages * PAGE_SIZE));
2877 switch (oom_status) {
2879 nr_retries = MAX_RECLAIM_RETRIES;
2887 if (!(gfp_mask & __GFP_NOFAIL))
2891 * The allocation either can't fail or will lead to more memory
2892 * being freed very soon. Allow memory usage go over the limit
2893 * temporarily by force charging it.
2895 page_counter_charge(&memcg->memory, nr_pages);
2896 if (do_memsw_account())
2897 page_counter_charge(&memcg->memsw, nr_pages);
2902 if (batch > nr_pages)
2903 refill_stock(memcg, batch - nr_pages);
2906 * If the hierarchy is above the normal consumption range, schedule
2907 * reclaim on returning to userland. We can perform reclaim here
2908 * if __GFP_RECLAIM but let's always punt for simplicity and so that
2909 * GFP_KERNEL can consistently be used during reclaim. @memcg is
2910 * not recorded as it most likely matches current's and won't
2911 * change in the meantime. As high limit is checked again before
2912 * reclaim, the cost of mismatch is negligible.
2915 bool mem_high, swap_high;
2917 mem_high = page_counter_read(&memcg->memory) >
2918 READ_ONCE(memcg->memory.high);
2919 swap_high = page_counter_read(&memcg->swap) >
2920 READ_ONCE(memcg->swap.high);
2922 /* Don't bother a random interrupted task */
2923 if (in_interrupt()) {
2925 schedule_work(&memcg->high_work);
2931 if (mem_high || swap_high) {
2933 * The allocating tasks in this cgroup will need to do
2934 * reclaim or be throttled to prevent further growth
2935 * of the memory or swap footprints.
2937 * Target some best-effort fairness between the tasks,
2938 * and distribute reclaim work and delay penalties
2939 * based on how much each task is actually allocating.
2941 current->memcg_nr_pages_over_high += batch;
2942 set_notify_resume(current);
2945 } while ((memcg = parent_mem_cgroup(memcg)));
2950 #if defined(CONFIG_MEMCG_KMEM) || defined(CONFIG_MMU)
2951 static void cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
2953 if (mem_cgroup_is_root(memcg))
2956 page_counter_uncharge(&memcg->memory, nr_pages);
2957 if (do_memsw_account())
2958 page_counter_uncharge(&memcg->memsw, nr_pages);
2962 static void commit_charge(struct page *page, struct mem_cgroup *memcg)
2964 VM_BUG_ON_PAGE(page_memcg(page), page);
2966 * Any of the following ensures page's memcg stability:
2970 * - lock_page_memcg()
2971 * - exclusive reference
2973 page->memcg_data = (unsigned long)memcg;
2976 #ifdef CONFIG_MEMCG_KMEM
2977 int memcg_alloc_page_obj_cgroups(struct page *page, struct kmem_cache *s,
2980 unsigned int objects = objs_per_slab_page(s, page);
2983 vec = kcalloc_node(objects, sizeof(struct obj_cgroup *), gfp,
2988 if (!set_page_objcgs(page, vec))
2991 kmemleak_not_leak(vec);
2997 * Returns a pointer to the memory cgroup to which the kernel object is charged.
2999 * A passed kernel object can be a slab object or a generic kernel page, so
3000 * different mechanisms for getting the memory cgroup pointer should be used.
3001 * In certain cases (e.g. kernel stacks or large kmallocs with SLUB) the caller
3002 * can not know for sure how the kernel object is implemented.
3003 * mem_cgroup_from_obj() can be safely used in such cases.
3005 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
3006 * cgroup_mutex, etc.
3008 struct mem_cgroup *mem_cgroup_from_obj(void *p)
3012 if (mem_cgroup_disabled())
3015 page = virt_to_head_page(p);
3018 * Slab objects are accounted individually, not per-page.
3019 * Memcg membership data for each individual object is saved in
3020 * the page->obj_cgroups.
3022 if (page_objcgs_check(page)) {
3023 struct obj_cgroup *objcg;
3026 off = obj_to_index(page->slab_cache, page, p);
3027 objcg = page_objcgs(page)[off];
3029 return obj_cgroup_memcg(objcg);
3035 * page_memcg_check() is used here, because page_has_obj_cgroups()
3036 * check above could fail because the object cgroups vector wasn't set
3037 * at that moment, but it can be set concurrently.
3038 * page_memcg_check(page) will guarantee that a proper memory
3039 * cgroup pointer or NULL will be returned.
3041 return page_memcg_check(page);
3044 __always_inline struct obj_cgroup *get_obj_cgroup_from_current(void)
3046 struct obj_cgroup *objcg = NULL;
3047 struct mem_cgroup *memcg;
3049 if (memcg_kmem_bypass())
3053 if (unlikely(active_memcg()))
3054 memcg = active_memcg();
3056 memcg = mem_cgroup_from_task(current);
3058 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg)) {
3059 objcg = rcu_dereference(memcg->objcg);
3060 if (objcg && obj_cgroup_tryget(objcg))
3069 static int memcg_alloc_cache_id(void)
3074 id = ida_simple_get(&memcg_cache_ida,
3075 0, MEMCG_CACHES_MAX_SIZE, GFP_KERNEL);
3079 if (id < memcg_nr_cache_ids)
3083 * There's no space for the new id in memcg_caches arrays,
3084 * so we have to grow them.
3086 down_write(&memcg_cache_ids_sem);
3088 size = 2 * (id + 1);
3089 if (size < MEMCG_CACHES_MIN_SIZE)
3090 size = MEMCG_CACHES_MIN_SIZE;
3091 else if (size > MEMCG_CACHES_MAX_SIZE)
3092 size = MEMCG_CACHES_MAX_SIZE;
3094 err = memcg_update_all_list_lrus(size);
3096 memcg_nr_cache_ids = size;
3098 up_write(&memcg_cache_ids_sem);
3101 ida_simple_remove(&memcg_cache_ida, id);
3107 static void memcg_free_cache_id(int id)
3109 ida_simple_remove(&memcg_cache_ida, id);
3113 * __memcg_kmem_charge: charge a number of kernel pages to a memcg
3114 * @memcg: memory cgroup to charge
3115 * @gfp: reclaim mode
3116 * @nr_pages: number of pages to charge
3118 * Returns 0 on success, an error code on failure.
3120 int __memcg_kmem_charge(struct mem_cgroup *memcg, gfp_t gfp,
3121 unsigned int nr_pages)
3123 struct page_counter *counter;
3126 ret = try_charge(memcg, gfp, nr_pages);
3130 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) &&
3131 !page_counter_try_charge(&memcg->kmem, nr_pages, &counter)) {
3134 * Enforce __GFP_NOFAIL allocation because callers are not
3135 * prepared to see failures and likely do not have any failure
3138 if (gfp & __GFP_NOFAIL) {
3139 page_counter_charge(&memcg->kmem, nr_pages);
3142 cancel_charge(memcg, nr_pages);
3149 * __memcg_kmem_uncharge: uncharge a number of kernel pages from a memcg
3150 * @memcg: memcg to uncharge
3151 * @nr_pages: number of pages to uncharge
3153 void __memcg_kmem_uncharge(struct mem_cgroup *memcg, unsigned int nr_pages)
3155 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
3156 page_counter_uncharge(&memcg->kmem, nr_pages);
3158 page_counter_uncharge(&memcg->memory, nr_pages);
3159 if (do_memsw_account())
3160 page_counter_uncharge(&memcg->memsw, nr_pages);
3164 * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup
3165 * @page: page to charge
3166 * @gfp: reclaim mode
3167 * @order: allocation order
3169 * Returns 0 on success, an error code on failure.
3171 int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
3173 struct mem_cgroup *memcg;
3176 memcg = get_mem_cgroup_from_current();
3177 if (memcg && !mem_cgroup_is_root(memcg)) {
3178 ret = __memcg_kmem_charge(memcg, gfp, 1 << order);
3180 page->memcg_data = (unsigned long)memcg |
3184 css_put(&memcg->css);
3190 * __memcg_kmem_uncharge_page: uncharge a kmem page
3191 * @page: page to uncharge
3192 * @order: allocation order
3194 void __memcg_kmem_uncharge_page(struct page *page, int order)
3196 struct mem_cgroup *memcg = page_memcg(page);
3197 unsigned int nr_pages = 1 << order;
3202 VM_BUG_ON_PAGE(mem_cgroup_is_root(memcg), page);
3203 __memcg_kmem_uncharge(memcg, nr_pages);
3204 page->memcg_data = 0;
3205 css_put(&memcg->css);
3208 static bool consume_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes)
3210 struct memcg_stock_pcp *stock;
3211 unsigned long flags;
3214 local_irq_save(flags);
3216 stock = this_cpu_ptr(&memcg_stock);
3217 if (objcg == stock->cached_objcg && stock->nr_bytes >= nr_bytes) {
3218 stock->nr_bytes -= nr_bytes;
3222 local_irq_restore(flags);
3227 static void drain_obj_stock(struct memcg_stock_pcp *stock)
3229 struct obj_cgroup *old = stock->cached_objcg;
3234 if (stock->nr_bytes) {
3235 unsigned int nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3236 unsigned int nr_bytes = stock->nr_bytes & (PAGE_SIZE - 1);
3240 __memcg_kmem_uncharge(obj_cgroup_memcg(old), nr_pages);
3245 * The leftover is flushed to the centralized per-memcg value.
3246 * On the next attempt to refill obj stock it will be moved
3247 * to a per-cpu stock (probably, on an other CPU), see
3248 * refill_obj_stock().
3250 * How often it's flushed is a trade-off between the memory
3251 * limit enforcement accuracy and potential CPU contention,
3252 * so it might be changed in the future.
3254 atomic_add(nr_bytes, &old->nr_charged_bytes);
3255 stock->nr_bytes = 0;
3258 obj_cgroup_put(old);
3259 stock->cached_objcg = NULL;
3262 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
3263 struct mem_cgroup *root_memcg)
3265 struct mem_cgroup *memcg;
3267 if (stock->cached_objcg) {
3268 memcg = obj_cgroup_memcg(stock->cached_objcg);
3269 if (memcg && mem_cgroup_is_descendant(memcg, root_memcg))
3276 static void refill_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes)
3278 struct memcg_stock_pcp *stock;
3279 unsigned long flags;
3281 local_irq_save(flags);
3283 stock = this_cpu_ptr(&memcg_stock);
3284 if (stock->cached_objcg != objcg) { /* reset if necessary */
3285 drain_obj_stock(stock);
3286 obj_cgroup_get(objcg);
3287 stock->cached_objcg = objcg;
3288 stock->nr_bytes = atomic_xchg(&objcg->nr_charged_bytes, 0);
3290 stock->nr_bytes += nr_bytes;
3292 if (stock->nr_bytes > PAGE_SIZE)
3293 drain_obj_stock(stock);
3295 local_irq_restore(flags);
3298 int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size)
3300 struct mem_cgroup *memcg;
3301 unsigned int nr_pages, nr_bytes;
3304 if (consume_obj_stock(objcg, size))
3308 * In theory, memcg->nr_charged_bytes can have enough
3309 * pre-charged bytes to satisfy the allocation. However,
3310 * flushing memcg->nr_charged_bytes requires two atomic
3311 * operations, and memcg->nr_charged_bytes can't be big,
3312 * so it's better to ignore it and try grab some new pages.
3313 * memcg->nr_charged_bytes will be flushed in
3314 * refill_obj_stock(), called from this function or
3315 * independently later.
3319 memcg = obj_cgroup_memcg(objcg);
3320 if (unlikely(!css_tryget(&memcg->css)))
3324 nr_pages = size >> PAGE_SHIFT;
3325 nr_bytes = size & (PAGE_SIZE - 1);
3330 ret = __memcg_kmem_charge(memcg, gfp, nr_pages);
3331 if (!ret && nr_bytes)
3332 refill_obj_stock(objcg, PAGE_SIZE - nr_bytes);
3334 css_put(&memcg->css);
3338 void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size)
3340 refill_obj_stock(objcg, size);
3343 #endif /* CONFIG_MEMCG_KMEM */
3345 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3347 * Because page_memcg(head) is not set on compound tails, set it now.
3349 void mem_cgroup_split_huge_fixup(struct page *head)
3351 struct mem_cgroup *memcg = page_memcg(head);
3354 if (mem_cgroup_disabled())
3357 for (i = 1; i < HPAGE_PMD_NR; i++) {
3358 css_get(&memcg->css);
3359 head[i].memcg_data = (unsigned long)memcg;
3362 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
3364 #ifdef CONFIG_MEMCG_SWAP
3366 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3367 * @entry: swap entry to be moved
3368 * @from: mem_cgroup which the entry is moved from
3369 * @to: mem_cgroup which the entry is moved to
3371 * It succeeds only when the swap_cgroup's record for this entry is the same
3372 * as the mem_cgroup's id of @from.
3374 * Returns 0 on success, -EINVAL on failure.
3376 * The caller must have charged to @to, IOW, called page_counter_charge() about
3377 * both res and memsw, and called css_get().
3379 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3380 struct mem_cgroup *from, struct mem_cgroup *to)
3382 unsigned short old_id, new_id;
3384 old_id = mem_cgroup_id(from);
3385 new_id = mem_cgroup_id(to);
3387 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3388 mod_memcg_state(from, MEMCG_SWAP, -1);
3389 mod_memcg_state(to, MEMCG_SWAP, 1);
3395 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3396 struct mem_cgroup *from, struct mem_cgroup *to)
3402 static DEFINE_MUTEX(memcg_max_mutex);
3404 static int mem_cgroup_resize_max(struct mem_cgroup *memcg,
3405 unsigned long max, bool memsw)
3407 bool enlarge = false;
3408 bool drained = false;
3410 bool limits_invariant;
3411 struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory;
3414 if (signal_pending(current)) {
3419 mutex_lock(&memcg_max_mutex);
3421 * Make sure that the new limit (memsw or memory limit) doesn't
3422 * break our basic invariant rule memory.max <= memsw.max.
3424 limits_invariant = memsw ? max >= READ_ONCE(memcg->memory.max) :
3425 max <= memcg->memsw.max;
3426 if (!limits_invariant) {
3427 mutex_unlock(&memcg_max_mutex);
3431 if (max > counter->max)
3433 ret = page_counter_set_max(counter, max);
3434 mutex_unlock(&memcg_max_mutex);
3440 drain_all_stock(memcg);
3445 if (!try_to_free_mem_cgroup_pages(memcg, 1,
3446 GFP_KERNEL, !memsw)) {
3452 if (!ret && enlarge)
3453 memcg_oom_recover(memcg);
3458 unsigned long mem_cgroup_soft_limit_reclaim(pg_data_t *pgdat, int order,
3460 unsigned long *total_scanned)
3462 unsigned long nr_reclaimed = 0;
3463 struct mem_cgroup_per_node *mz, *next_mz = NULL;
3464 unsigned long reclaimed;
3466 struct mem_cgroup_tree_per_node *mctz;
3467 unsigned long excess;
3468 unsigned long nr_scanned;
3473 mctz = soft_limit_tree_node(pgdat->node_id);
3476 * Do not even bother to check the largest node if the root
3477 * is empty. Do it lockless to prevent lock bouncing. Races
3478 * are acceptable as soft limit is best effort anyway.
3480 if (!mctz || RB_EMPTY_ROOT(&mctz->rb_root))
3484 * This loop can run a while, specially if mem_cgroup's continuously
3485 * keep exceeding their soft limit and putting the system under
3492 mz = mem_cgroup_largest_soft_limit_node(mctz);
3497 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, pgdat,
3498 gfp_mask, &nr_scanned);
3499 nr_reclaimed += reclaimed;
3500 *total_scanned += nr_scanned;
3501 spin_lock_irq(&mctz->lock);
3502 __mem_cgroup_remove_exceeded(mz, mctz);
3505 * If we failed to reclaim anything from this memory cgroup
3506 * it is time to move on to the next cgroup
3510 next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
3512 excess = soft_limit_excess(mz->memcg);
3514 * One school of thought says that we should not add
3515 * back the node to the tree if reclaim returns 0.
3516 * But our reclaim could return 0, simply because due
3517 * to priority we are exposing a smaller subset of
3518 * memory to reclaim from. Consider this as a longer
3521 /* If excess == 0, no tree ops */
3522 __mem_cgroup_insert_exceeded(mz, mctz, excess);
3523 spin_unlock_irq(&mctz->lock);
3524 css_put(&mz->memcg->css);
3527 * Could not reclaim anything and there are no more
3528 * mem cgroups to try or we seem to be looping without
3529 * reclaiming anything.
3531 if (!nr_reclaimed &&
3533 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3535 } while (!nr_reclaimed);
3537 css_put(&next_mz->memcg->css);
3538 return nr_reclaimed;
3542 * Reclaims as many pages from the given memcg as possible.
3544 * Caller is responsible for holding css reference for memcg.
3546 static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
3548 int nr_retries = MAX_RECLAIM_RETRIES;
3550 /* we call try-to-free pages for make this cgroup empty */
3551 lru_add_drain_all();
3553 drain_all_stock(memcg);
3555 /* try to free all pages in this cgroup */
3556 while (nr_retries && page_counter_read(&memcg->memory)) {
3559 if (signal_pending(current))
3562 progress = try_to_free_mem_cgroup_pages(memcg, 1,
3566 /* maybe some writeback is necessary */
3567 congestion_wait(BLK_RW_ASYNC, HZ/10);
3575 static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
3576 char *buf, size_t nbytes,
3579 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3581 if (mem_cgroup_is_root(memcg))
3583 return mem_cgroup_force_empty(memcg) ?: nbytes;
3586 static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
3592 static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
3593 struct cftype *cft, u64 val)
3598 pr_warn_once("Non-hierarchical mode is deprecated. "
3599 "Please report your usecase to linux-mm@kvack.org if you "
3600 "depend on this functionality.\n");
3605 static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3609 if (mem_cgroup_is_root(memcg)) {
3610 val = memcg_page_state(memcg, NR_FILE_PAGES) +
3611 memcg_page_state(memcg, NR_ANON_MAPPED);
3613 val += memcg_page_state(memcg, MEMCG_SWAP);
3616 val = page_counter_read(&memcg->memory);
3618 val = page_counter_read(&memcg->memsw);
3631 static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
3634 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3635 struct page_counter *counter;
3637 switch (MEMFILE_TYPE(cft->private)) {
3639 counter = &memcg->memory;
3642 counter = &memcg->memsw;
3645 counter = &memcg->kmem;
3648 counter = &memcg->tcpmem;
3654 switch (MEMFILE_ATTR(cft->private)) {
3656 if (counter == &memcg->memory)
3657 return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
3658 if (counter == &memcg->memsw)
3659 return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
3660 return (u64)page_counter_read(counter) * PAGE_SIZE;
3662 return (u64)counter->max * PAGE_SIZE;
3664 return (u64)counter->watermark * PAGE_SIZE;
3666 return counter->failcnt;
3667 case RES_SOFT_LIMIT:
3668 return (u64)memcg->soft_limit * PAGE_SIZE;
3674 static void memcg_flush_percpu_vmstats(struct mem_cgroup *memcg)
3676 unsigned long stat[MEMCG_NR_STAT] = {0};
3677 struct mem_cgroup *mi;
3680 for_each_online_cpu(cpu)
3681 for (i = 0; i < MEMCG_NR_STAT; i++)
3682 stat[i] += per_cpu(memcg->vmstats_percpu->stat[i], cpu);
3684 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
3685 for (i = 0; i < MEMCG_NR_STAT; i++)
3686 atomic_long_add(stat[i], &mi->vmstats[i]);
3688 for_each_node(node) {
3689 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
3690 struct mem_cgroup_per_node *pi;
3692 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++)
3695 for_each_online_cpu(cpu)
3696 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++)
3698 pn->lruvec_stat_cpu->count[i], cpu);
3700 for (pi = pn; pi; pi = parent_nodeinfo(pi, node))
3701 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++)
3702 atomic_long_add(stat[i], &pi->lruvec_stat[i]);
3706 static void memcg_flush_percpu_vmevents(struct mem_cgroup *memcg)
3708 unsigned long events[NR_VM_EVENT_ITEMS];
3709 struct mem_cgroup *mi;
3712 for (i = 0; i < NR_VM_EVENT_ITEMS; i++)
3715 for_each_online_cpu(cpu)
3716 for (i = 0; i < NR_VM_EVENT_ITEMS; i++)
3717 events[i] += per_cpu(memcg->vmstats_percpu->events[i],
3720 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
3721 for (i = 0; i < NR_VM_EVENT_ITEMS; i++)
3722 atomic_long_add(events[i], &mi->vmevents[i]);
3725 #ifdef CONFIG_MEMCG_KMEM
3726 static int memcg_online_kmem(struct mem_cgroup *memcg)
3728 struct obj_cgroup *objcg;
3731 if (cgroup_memory_nokmem)
3734 BUG_ON(memcg->kmemcg_id >= 0);
3735 BUG_ON(memcg->kmem_state);
3737 memcg_id = memcg_alloc_cache_id();
3741 objcg = obj_cgroup_alloc();
3743 memcg_free_cache_id(memcg_id);
3746 objcg->memcg = memcg;
3747 rcu_assign_pointer(memcg->objcg, objcg);
3749 static_branch_enable(&memcg_kmem_enabled_key);
3751 memcg->kmemcg_id = memcg_id;
3752 memcg->kmem_state = KMEM_ONLINE;
3757 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3759 struct cgroup_subsys_state *css;
3760 struct mem_cgroup *parent, *child;
3763 if (memcg->kmem_state != KMEM_ONLINE)
3766 memcg->kmem_state = KMEM_ALLOCATED;
3768 parent = parent_mem_cgroup(memcg);
3770 parent = root_mem_cgroup;
3772 memcg_reparent_objcgs(memcg, parent);
3774 kmemcg_id = memcg->kmemcg_id;
3775 BUG_ON(kmemcg_id < 0);
3778 * Change kmemcg_id of this cgroup and all its descendants to the
3779 * parent's id, and then move all entries from this cgroup's list_lrus
3780 * to ones of the parent. After we have finished, all list_lrus
3781 * corresponding to this cgroup are guaranteed to remain empty. The
3782 * ordering is imposed by list_lru_node->lock taken by
3783 * memcg_drain_all_list_lrus().
3785 rcu_read_lock(); /* can be called from css_free w/o cgroup_mutex */
3786 css_for_each_descendant_pre(css, &memcg->css) {
3787 child = mem_cgroup_from_css(css);
3788 BUG_ON(child->kmemcg_id != kmemcg_id);
3789 child->kmemcg_id = parent->kmemcg_id;
3793 memcg_drain_all_list_lrus(kmemcg_id, parent);
3795 memcg_free_cache_id(kmemcg_id);
3798 static void memcg_free_kmem(struct mem_cgroup *memcg)
3800 /* css_alloc() failed, offlining didn't happen */
3801 if (unlikely(memcg->kmem_state == KMEM_ONLINE))
3802 memcg_offline_kmem(memcg);
3805 static int memcg_online_kmem(struct mem_cgroup *memcg)
3809 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3812 static void memcg_free_kmem(struct mem_cgroup *memcg)
3815 #endif /* CONFIG_MEMCG_KMEM */
3817 static int memcg_update_kmem_max(struct mem_cgroup *memcg,
3822 mutex_lock(&memcg_max_mutex);
3823 ret = page_counter_set_max(&memcg->kmem, max);
3824 mutex_unlock(&memcg_max_mutex);
3828 static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max)
3832 mutex_lock(&memcg_max_mutex);
3834 ret = page_counter_set_max(&memcg->tcpmem, max);
3838 if (!memcg->tcpmem_active) {
3840 * The active flag needs to be written after the static_key
3841 * update. This is what guarantees that the socket activation
3842 * function is the last one to run. See mem_cgroup_sk_alloc()
3843 * for details, and note that we don't mark any socket as
3844 * belonging to this memcg until that flag is up.
3846 * We need to do this, because static_keys will span multiple
3847 * sites, but we can't control their order. If we mark a socket
3848 * as accounted, but the accounting functions are not patched in
3849 * yet, we'll lose accounting.
3851 * We never race with the readers in mem_cgroup_sk_alloc(),
3852 * because when this value change, the code to process it is not
3855 static_branch_inc(&memcg_sockets_enabled_key);
3856 memcg->tcpmem_active = true;
3859 mutex_unlock(&memcg_max_mutex);
3864 * The user of this function is...
3867 static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
3868 char *buf, size_t nbytes, loff_t off)
3870 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3871 unsigned long nr_pages;
3874 buf = strstrip(buf);
3875 ret = page_counter_memparse(buf, "-1", &nr_pages);
3879 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3881 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3885 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3887 ret = mem_cgroup_resize_max(memcg, nr_pages, false);
3890 ret = mem_cgroup_resize_max(memcg, nr_pages, true);
3893 pr_warn_once("kmem.limit_in_bytes is deprecated and will be removed. "
3894 "Please report your usecase to linux-mm@kvack.org if you "
3895 "depend on this functionality.\n");
3896 ret = memcg_update_kmem_max(memcg, nr_pages);
3899 ret = memcg_update_tcp_max(memcg, nr_pages);
3903 case RES_SOFT_LIMIT:
3904 memcg->soft_limit = nr_pages;
3908 return ret ?: nbytes;
3911 static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
3912 size_t nbytes, loff_t off)
3914 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3915 struct page_counter *counter;
3917 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3919 counter = &memcg->memory;
3922 counter = &memcg->memsw;
3925 counter = &memcg->kmem;
3928 counter = &memcg->tcpmem;
3934 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3936 page_counter_reset_watermark(counter);
3939 counter->failcnt = 0;
3948 static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
3951 return mem_cgroup_from_css(css)->move_charge_at_immigrate;
3955 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3956 struct cftype *cft, u64 val)
3958 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3960 if (val & ~MOVE_MASK)
3964 * No kind of locking is needed in here, because ->can_attach() will
3965 * check this value once in the beginning of the process, and then carry
3966 * on with stale data. This means that changes to this value will only
3967 * affect task migrations starting after the change.
3969 memcg->move_charge_at_immigrate = val;
3973 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3974 struct cftype *cft, u64 val)
3982 #define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE))
3983 #define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON))
3984 #define LRU_ALL ((1 << NR_LRU_LISTS) - 1)
3986 static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
3987 int nid, unsigned int lru_mask, bool tree)
3989 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
3990 unsigned long nr = 0;
3993 VM_BUG_ON((unsigned)nid >= nr_node_ids);
3996 if (!(BIT(lru) & lru_mask))
3999 nr += lruvec_page_state(lruvec, NR_LRU_BASE + lru);
4001 nr += lruvec_page_state_local(lruvec, NR_LRU_BASE + lru);
4006 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
4007 unsigned int lru_mask,
4010 unsigned long nr = 0;
4014 if (!(BIT(lru) & lru_mask))
4017 nr += memcg_page_state(memcg, NR_LRU_BASE + lru);
4019 nr += memcg_page_state_local(memcg, NR_LRU_BASE + lru);
4024 static int memcg_numa_stat_show(struct seq_file *m, void *v)
4028 unsigned int lru_mask;
4031 static const struct numa_stat stats[] = {
4032 { "total", LRU_ALL },
4033 { "file", LRU_ALL_FILE },
4034 { "anon", LRU_ALL_ANON },
4035 { "unevictable", BIT(LRU_UNEVICTABLE) },
4037 const struct numa_stat *stat;
4039 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
4041 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
4042 seq_printf(m, "%s=%lu", stat->name,
4043 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
4045 for_each_node_state(nid, N_MEMORY)
4046 seq_printf(m, " N%d=%lu", nid,
4047 mem_cgroup_node_nr_lru_pages(memcg, nid,
4048 stat->lru_mask, false));
4052 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
4054 seq_printf(m, "hierarchical_%s=%lu", stat->name,
4055 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
4057 for_each_node_state(nid, N_MEMORY)
4058 seq_printf(m, " N%d=%lu", nid,
4059 mem_cgroup_node_nr_lru_pages(memcg, nid,
4060 stat->lru_mask, true));
4066 #endif /* CONFIG_NUMA */
4068 static const unsigned int memcg1_stats[] = {
4071 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4081 static const char *const memcg1_stat_names[] = {
4084 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4094 /* Universal VM events cgroup1 shows, original sort order */
4095 static const unsigned int memcg1_events[] = {
4102 static int memcg_stat_show(struct seq_file *m, void *v)
4104 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
4105 unsigned long memory, memsw;
4106 struct mem_cgroup *mi;
4109 BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats));
4111 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
4114 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
4116 nr = memcg_page_state_local(memcg, memcg1_stats[i]);
4117 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4118 if (memcg1_stats[i] == NR_ANON_THPS)
4121 seq_printf(m, "%s %lu\n", memcg1_stat_names[i], nr * PAGE_SIZE);
4124 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
4125 seq_printf(m, "%s %lu\n", vm_event_name(memcg1_events[i]),
4126 memcg_events_local(memcg, memcg1_events[i]));
4128 for (i = 0; i < NR_LRU_LISTS; i++)
4129 seq_printf(m, "%s %lu\n", lru_list_name(i),
4130 memcg_page_state_local(memcg, NR_LRU_BASE + i) *
4133 /* Hierarchical information */
4134 memory = memsw = PAGE_COUNTER_MAX;
4135 for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
4136 memory = min(memory, READ_ONCE(mi->memory.max));
4137 memsw = min(memsw, READ_ONCE(mi->memsw.max));
4139 seq_printf(m, "hierarchical_memory_limit %llu\n",
4140 (u64)memory * PAGE_SIZE);
4141 if (do_memsw_account())
4142 seq_printf(m, "hierarchical_memsw_limit %llu\n",
4143 (u64)memsw * PAGE_SIZE);
4145 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
4148 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
4150 nr = memcg_page_state(memcg, memcg1_stats[i]);
4151 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4152 if (memcg1_stats[i] == NR_ANON_THPS)
4155 seq_printf(m, "total_%s %llu\n", memcg1_stat_names[i],
4156 (u64)nr * PAGE_SIZE);
4159 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
4160 seq_printf(m, "total_%s %llu\n",
4161 vm_event_name(memcg1_events[i]),
4162 (u64)memcg_events(memcg, memcg1_events[i]));
4164 for (i = 0; i < NR_LRU_LISTS; i++)
4165 seq_printf(m, "total_%s %llu\n", lru_list_name(i),
4166 (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
4169 #ifdef CONFIG_DEBUG_VM
4172 struct mem_cgroup_per_node *mz;
4173 unsigned long anon_cost = 0;
4174 unsigned long file_cost = 0;
4176 for_each_online_pgdat(pgdat) {
4177 mz = mem_cgroup_nodeinfo(memcg, pgdat->node_id);
4179 anon_cost += mz->lruvec.anon_cost;
4180 file_cost += mz->lruvec.file_cost;
4182 seq_printf(m, "anon_cost %lu\n", anon_cost);
4183 seq_printf(m, "file_cost %lu\n", file_cost);
4190 static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
4193 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4195 return mem_cgroup_swappiness(memcg);
4198 static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
4199 struct cftype *cft, u64 val)
4201 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4207 memcg->swappiness = val;
4209 vm_swappiness = val;
4214 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4216 struct mem_cgroup_threshold_ary *t;
4217 unsigned long usage;
4222 t = rcu_dereference(memcg->thresholds.primary);
4224 t = rcu_dereference(memcg->memsw_thresholds.primary);
4229 usage = mem_cgroup_usage(memcg, swap);
4232 * current_threshold points to threshold just below or equal to usage.
4233 * If it's not true, a threshold was crossed after last
4234 * call of __mem_cgroup_threshold().
4236 i = t->current_threshold;
4239 * Iterate backward over array of thresholds starting from
4240 * current_threshold and check if a threshold is crossed.
4241 * If none of thresholds below usage is crossed, we read
4242 * only one element of the array here.
4244 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4245 eventfd_signal(t->entries[i].eventfd, 1);
4247 /* i = current_threshold + 1 */
4251 * Iterate forward over array of thresholds starting from
4252 * current_threshold+1 and check if a threshold is crossed.
4253 * If none of thresholds above usage is crossed, we read
4254 * only one element of the array here.
4256 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4257 eventfd_signal(t->entries[i].eventfd, 1);
4259 /* Update current_threshold */
4260 t->current_threshold = i - 1;
4265 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4268 __mem_cgroup_threshold(memcg, false);
4269 if (do_memsw_account())
4270 __mem_cgroup_threshold(memcg, true);
4272 memcg = parent_mem_cgroup(memcg);
4276 static int compare_thresholds(const void *a, const void *b)
4278 const struct mem_cgroup_threshold *_a = a;
4279 const struct mem_cgroup_threshold *_b = b;
4281 if (_a->threshold > _b->threshold)
4284 if (_a->threshold < _b->threshold)
4290 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
4292 struct mem_cgroup_eventfd_list *ev;
4294 spin_lock(&memcg_oom_lock);
4296 list_for_each_entry(ev, &memcg->oom_notify, list)
4297 eventfd_signal(ev->eventfd, 1);
4299 spin_unlock(&memcg_oom_lock);
4303 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
4305 struct mem_cgroup *iter;
4307 for_each_mem_cgroup_tree(iter, memcg)
4308 mem_cgroup_oom_notify_cb(iter);
4311 static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4312 struct eventfd_ctx *eventfd, const char *args, enum res_type type)
4314 struct mem_cgroup_thresholds *thresholds;
4315 struct mem_cgroup_threshold_ary *new;
4316 unsigned long threshold;
4317 unsigned long usage;
4320 ret = page_counter_memparse(args, "-1", &threshold);
4324 mutex_lock(&memcg->thresholds_lock);
4327 thresholds = &memcg->thresholds;
4328 usage = mem_cgroup_usage(memcg, false);
4329 } else if (type == _MEMSWAP) {
4330 thresholds = &memcg->memsw_thresholds;
4331 usage = mem_cgroup_usage(memcg, true);
4335 /* Check if a threshold crossed before adding a new one */
4336 if (thresholds->primary)
4337 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4339 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4341 /* Allocate memory for new array of thresholds */
4342 new = kmalloc(struct_size(new, entries, size), GFP_KERNEL);
4349 /* Copy thresholds (if any) to new array */
4350 if (thresholds->primary)
4351 memcpy(new->entries, thresholds->primary->entries,
4352 flex_array_size(new, entries, size - 1));
4354 /* Add new threshold */
4355 new->entries[size - 1].eventfd = eventfd;
4356 new->entries[size - 1].threshold = threshold;
4358 /* Sort thresholds. Registering of new threshold isn't time-critical */
4359 sort(new->entries, size, sizeof(*new->entries),
4360 compare_thresholds, NULL);
4362 /* Find current threshold */
4363 new->current_threshold = -1;
4364 for (i = 0; i < size; i++) {
4365 if (new->entries[i].threshold <= usage) {
4367 * new->current_threshold will not be used until
4368 * rcu_assign_pointer(), so it's safe to increment
4371 ++new->current_threshold;
4376 /* Free old spare buffer and save old primary buffer as spare */
4377 kfree(thresholds->spare);
4378 thresholds->spare = thresholds->primary;
4380 rcu_assign_pointer(thresholds->primary, new);
4382 /* To be sure that nobody uses thresholds */
4386 mutex_unlock(&memcg->thresholds_lock);
4391 static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4392 struct eventfd_ctx *eventfd, const char *args)
4394 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
4397 static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
4398 struct eventfd_ctx *eventfd, const char *args)
4400 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
4403 static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4404 struct eventfd_ctx *eventfd, enum res_type type)
4406 struct mem_cgroup_thresholds *thresholds;
4407 struct mem_cgroup_threshold_ary *new;
4408 unsigned long usage;
4409 int i, j, size, entries;
4411 mutex_lock(&memcg->thresholds_lock);
4414 thresholds = &memcg->thresholds;
4415 usage = mem_cgroup_usage(memcg, false);
4416 } else if (type == _MEMSWAP) {
4417 thresholds = &memcg->memsw_thresholds;
4418 usage = mem_cgroup_usage(memcg, true);
4422 if (!thresholds->primary)
4425 /* Check if a threshold crossed before removing */
4426 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4428 /* Calculate new number of threshold */
4430 for (i = 0; i < thresholds->primary->size; i++) {
4431 if (thresholds->primary->entries[i].eventfd != eventfd)
4437 new = thresholds->spare;
4439 /* If no items related to eventfd have been cleared, nothing to do */
4443 /* Set thresholds array to NULL if we don't have thresholds */
4452 /* Copy thresholds and find current threshold */
4453 new->current_threshold = -1;
4454 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4455 if (thresholds->primary->entries[i].eventfd == eventfd)
4458 new->entries[j] = thresholds->primary->entries[i];
4459 if (new->entries[j].threshold <= usage) {
4461 * new->current_threshold will not be used
4462 * until rcu_assign_pointer(), so it's safe to increment
4465 ++new->current_threshold;
4471 /* Swap primary and spare array */
4472 thresholds->spare = thresholds->primary;
4474 rcu_assign_pointer(thresholds->primary, new);
4476 /* To be sure that nobody uses thresholds */
4479 /* If all events are unregistered, free the spare array */
4481 kfree(thresholds->spare);
4482 thresholds->spare = NULL;
4485 mutex_unlock(&memcg->thresholds_lock);
4488 static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4489 struct eventfd_ctx *eventfd)
4491 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
4494 static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4495 struct eventfd_ctx *eventfd)
4497 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
4500 static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
4501 struct eventfd_ctx *eventfd, const char *args)
4503 struct mem_cgroup_eventfd_list *event;
4505 event = kmalloc(sizeof(*event), GFP_KERNEL);
4509 spin_lock(&memcg_oom_lock);
4511 event->eventfd = eventfd;
4512 list_add(&event->list, &memcg->oom_notify);
4514 /* already in OOM ? */
4515 if (memcg->under_oom)
4516 eventfd_signal(eventfd, 1);
4517 spin_unlock(&memcg_oom_lock);
4522 static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
4523 struct eventfd_ctx *eventfd)
4525 struct mem_cgroup_eventfd_list *ev, *tmp;
4527 spin_lock(&memcg_oom_lock);
4529 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
4530 if (ev->eventfd == eventfd) {
4531 list_del(&ev->list);
4536 spin_unlock(&memcg_oom_lock);
4539 static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
4541 struct mem_cgroup *memcg = mem_cgroup_from_seq(sf);
4543 seq_printf(sf, "oom_kill_disable %d\n", memcg->oom_kill_disable);
4544 seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
4545 seq_printf(sf, "oom_kill %lu\n",
4546 atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
4550 static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
4551 struct cftype *cft, u64 val)
4553 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4555 /* cannot set to root cgroup and only 0 and 1 are allowed */
4556 if (!css->parent || !((val == 0) || (val == 1)))
4559 memcg->oom_kill_disable = val;
4561 memcg_oom_recover(memcg);
4566 #ifdef CONFIG_CGROUP_WRITEBACK
4568 #include <trace/events/writeback.h>
4570 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4572 return wb_domain_init(&memcg->cgwb_domain, gfp);
4575 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4577 wb_domain_exit(&memcg->cgwb_domain);
4580 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4582 wb_domain_size_changed(&memcg->cgwb_domain);
4585 struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
4587 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4589 if (!memcg->css.parent)
4592 return &memcg->cgwb_domain;
4596 * idx can be of type enum memcg_stat_item or node_stat_item.
4597 * Keep in sync with memcg_exact_page().
4599 static unsigned long memcg_exact_page_state(struct mem_cgroup *memcg, int idx)
4601 long x = atomic_long_read(&memcg->vmstats[idx]);
4604 for_each_online_cpu(cpu)
4605 x += per_cpu_ptr(memcg->vmstats_percpu, cpu)->stat[idx];
4612 * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
4613 * @wb: bdi_writeback in question
4614 * @pfilepages: out parameter for number of file pages
4615 * @pheadroom: out parameter for number of allocatable pages according to memcg
4616 * @pdirty: out parameter for number of dirty pages
4617 * @pwriteback: out parameter for number of pages under writeback
4619 * Determine the numbers of file, headroom, dirty, and writeback pages in
4620 * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom
4621 * is a bit more involved.
4623 * A memcg's headroom is "min(max, high) - used". In the hierarchy, the
4624 * headroom is calculated as the lowest headroom of itself and the
4625 * ancestors. Note that this doesn't consider the actual amount of
4626 * available memory in the system. The caller should further cap
4627 * *@pheadroom accordingly.
4629 void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
4630 unsigned long *pheadroom, unsigned long *pdirty,
4631 unsigned long *pwriteback)
4633 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4634 struct mem_cgroup *parent;
4636 *pdirty = memcg_exact_page_state(memcg, NR_FILE_DIRTY);
4638 *pwriteback = memcg_exact_page_state(memcg, NR_WRITEBACK);
4639 *pfilepages = memcg_exact_page_state(memcg, NR_INACTIVE_FILE) +
4640 memcg_exact_page_state(memcg, NR_ACTIVE_FILE);
4641 *pheadroom = PAGE_COUNTER_MAX;
4643 while ((parent = parent_mem_cgroup(memcg))) {
4644 unsigned long ceiling = min(READ_ONCE(memcg->memory.max),
4645 READ_ONCE(memcg->memory.high));
4646 unsigned long used = page_counter_read(&memcg->memory);
4648 *pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
4654 * Foreign dirty flushing
4656 * There's an inherent mismatch between memcg and writeback. The former
4657 * trackes ownership per-page while the latter per-inode. This was a
4658 * deliberate design decision because honoring per-page ownership in the
4659 * writeback path is complicated, may lead to higher CPU and IO overheads
4660 * and deemed unnecessary given that write-sharing an inode across
4661 * different cgroups isn't a common use-case.
4663 * Combined with inode majority-writer ownership switching, this works well
4664 * enough in most cases but there are some pathological cases. For
4665 * example, let's say there are two cgroups A and B which keep writing to
4666 * different but confined parts of the same inode. B owns the inode and
4667 * A's memory is limited far below B's. A's dirty ratio can rise enough to
4668 * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
4669 * triggering background writeback. A will be slowed down without a way to
4670 * make writeback of the dirty pages happen.
4672 * Conditions like the above can lead to a cgroup getting repatedly and
4673 * severely throttled after making some progress after each
4674 * dirty_expire_interval while the underyling IO device is almost
4677 * Solving this problem completely requires matching the ownership tracking
4678 * granularities between memcg and writeback in either direction. However,
4679 * the more egregious behaviors can be avoided by simply remembering the
4680 * most recent foreign dirtying events and initiating remote flushes on
4681 * them when local writeback isn't enough to keep the memory clean enough.
4683 * The following two functions implement such mechanism. When a foreign
4684 * page - a page whose memcg and writeback ownerships don't match - is
4685 * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
4686 * bdi_writeback on the page owning memcg. When balance_dirty_pages()
4687 * decides that the memcg needs to sleep due to high dirty ratio, it calls
4688 * mem_cgroup_flush_foreign() which queues writeback on the recorded
4689 * foreign bdi_writebacks which haven't expired. Both the numbers of
4690 * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
4691 * limited to MEMCG_CGWB_FRN_CNT.
4693 * The mechanism only remembers IDs and doesn't hold any object references.
4694 * As being wrong occasionally doesn't matter, updates and accesses to the
4695 * records are lockless and racy.
4697 void mem_cgroup_track_foreign_dirty_slowpath(struct page *page,
4698 struct bdi_writeback *wb)
4700 struct mem_cgroup *memcg = page_memcg(page);
4701 struct memcg_cgwb_frn *frn;
4702 u64 now = get_jiffies_64();
4703 u64 oldest_at = now;
4707 trace_track_foreign_dirty(page, wb);
4710 * Pick the slot to use. If there is already a slot for @wb, keep
4711 * using it. If not replace the oldest one which isn't being
4714 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4715 frn = &memcg->cgwb_frn[i];
4716 if (frn->bdi_id == wb->bdi->id &&
4717 frn->memcg_id == wb->memcg_css->id)
4719 if (time_before64(frn->at, oldest_at) &&
4720 atomic_read(&frn->done.cnt) == 1) {
4722 oldest_at = frn->at;
4726 if (i < MEMCG_CGWB_FRN_CNT) {
4728 * Re-using an existing one. Update timestamp lazily to
4729 * avoid making the cacheline hot. We want them to be
4730 * reasonably up-to-date and significantly shorter than
4731 * dirty_expire_interval as that's what expires the record.
4732 * Use the shorter of 1s and dirty_expire_interval / 8.
4734 unsigned long update_intv =
4735 min_t(unsigned long, HZ,
4736 msecs_to_jiffies(dirty_expire_interval * 10) / 8);
4738 if (time_before64(frn->at, now - update_intv))
4740 } else if (oldest >= 0) {
4741 /* replace the oldest free one */
4742 frn = &memcg->cgwb_frn[oldest];
4743 frn->bdi_id = wb->bdi->id;
4744 frn->memcg_id = wb->memcg_css->id;
4749 /* issue foreign writeback flushes for recorded foreign dirtying events */
4750 void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
4752 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4753 unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
4754 u64 now = jiffies_64;
4757 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4758 struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
4761 * If the record is older than dirty_expire_interval,
4762 * writeback on it has already started. No need to kick it
4763 * off again. Also, don't start a new one if there's
4764 * already one in flight.
4766 if (time_after64(frn->at, now - intv) &&
4767 atomic_read(&frn->done.cnt) == 1) {
4769 trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
4770 cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id, 0,
4771 WB_REASON_FOREIGN_FLUSH,
4777 #else /* CONFIG_CGROUP_WRITEBACK */
4779 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4784 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4788 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4792 #endif /* CONFIG_CGROUP_WRITEBACK */
4795 * DO NOT USE IN NEW FILES.
4797 * "cgroup.event_control" implementation.
4799 * This is way over-engineered. It tries to support fully configurable
4800 * events for each user. Such level of flexibility is completely
4801 * unnecessary especially in the light of the planned unified hierarchy.
4803 * Please deprecate this and replace with something simpler if at all
4808 * Unregister event and free resources.
4810 * Gets called from workqueue.
4812 static void memcg_event_remove(struct work_struct *work)
4814 struct mem_cgroup_event *event =
4815 container_of(work, struct mem_cgroup_event, remove);
4816 struct mem_cgroup *memcg = event->memcg;
4818 remove_wait_queue(event->wqh, &event->wait);
4820 event->unregister_event(memcg, event->eventfd);
4822 /* Notify userspace the event is going away. */
4823 eventfd_signal(event->eventfd, 1);
4825 eventfd_ctx_put(event->eventfd);
4827 css_put(&memcg->css);
4831 * Gets called on EPOLLHUP on eventfd when user closes it.
4833 * Called with wqh->lock held and interrupts disabled.
4835 static int memcg_event_wake(wait_queue_entry_t *wait, unsigned mode,
4836 int sync, void *key)
4838 struct mem_cgroup_event *event =
4839 container_of(wait, struct mem_cgroup_event, wait);
4840 struct mem_cgroup *memcg = event->memcg;
4841 __poll_t flags = key_to_poll(key);
4843 if (flags & EPOLLHUP) {
4845 * If the event has been detached at cgroup removal, we
4846 * can simply return knowing the other side will cleanup
4849 * We can't race against event freeing since the other
4850 * side will require wqh->lock via remove_wait_queue(),
4853 spin_lock(&memcg->event_list_lock);
4854 if (!list_empty(&event->list)) {
4855 list_del_init(&event->list);
4857 * We are in atomic context, but cgroup_event_remove()
4858 * may sleep, so we have to call it in workqueue.
4860 schedule_work(&event->remove);
4862 spin_unlock(&memcg->event_list_lock);
4868 static void memcg_event_ptable_queue_proc(struct file *file,
4869 wait_queue_head_t *wqh, poll_table *pt)
4871 struct mem_cgroup_event *event =
4872 container_of(pt, struct mem_cgroup_event, pt);
4875 add_wait_queue(wqh, &event->wait);
4879 * DO NOT USE IN NEW FILES.
4881 * Parse input and register new cgroup event handler.
4883 * Input must be in format '<event_fd> <control_fd> <args>'.
4884 * Interpretation of args is defined by control file implementation.
4886 static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
4887 char *buf, size_t nbytes, loff_t off)
4889 struct cgroup_subsys_state *css = of_css(of);
4890 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4891 struct mem_cgroup_event *event;
4892 struct cgroup_subsys_state *cfile_css;
4893 unsigned int efd, cfd;
4900 buf = strstrip(buf);
4902 efd = simple_strtoul(buf, &endp, 10);
4907 cfd = simple_strtoul(buf, &endp, 10);
4908 if ((*endp != ' ') && (*endp != '\0'))
4912 event = kzalloc(sizeof(*event), GFP_KERNEL);
4916 event->memcg = memcg;
4917 INIT_LIST_HEAD(&event->list);
4918 init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
4919 init_waitqueue_func_entry(&event->wait, memcg_event_wake);
4920 INIT_WORK(&event->remove, memcg_event_remove);
4928 event->eventfd = eventfd_ctx_fileget(efile.file);
4929 if (IS_ERR(event->eventfd)) {
4930 ret = PTR_ERR(event->eventfd);
4937 goto out_put_eventfd;
4940 /* the process need read permission on control file */
4941 /* AV: shouldn't we check that it's been opened for read instead? */
4942 ret = inode_permission(file_inode(cfile.file), MAY_READ);
4947 * Determine the event callbacks and set them in @event. This used
4948 * to be done via struct cftype but cgroup core no longer knows
4949 * about these events. The following is crude but the whole thing
4950 * is for compatibility anyway.
4952 * DO NOT ADD NEW FILES.
4954 name = cfile.file->f_path.dentry->d_name.name;
4956 if (!strcmp(name, "memory.usage_in_bytes")) {
4957 event->register_event = mem_cgroup_usage_register_event;
4958 event->unregister_event = mem_cgroup_usage_unregister_event;
4959 } else if (!strcmp(name, "memory.oom_control")) {
4960 event->register_event = mem_cgroup_oom_register_event;
4961 event->unregister_event = mem_cgroup_oom_unregister_event;
4962 } else if (!strcmp(name, "memory.pressure_level")) {
4963 event->register_event = vmpressure_register_event;
4964 event->unregister_event = vmpressure_unregister_event;
4965 } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
4966 event->register_event = memsw_cgroup_usage_register_event;
4967 event->unregister_event = memsw_cgroup_usage_unregister_event;
4974 * Verify @cfile should belong to @css. Also, remaining events are
4975 * automatically removed on cgroup destruction but the removal is
4976 * asynchronous, so take an extra ref on @css.
4978 cfile_css = css_tryget_online_from_dir(cfile.file->f_path.dentry->d_parent,
4979 &memory_cgrp_subsys);
4981 if (IS_ERR(cfile_css))
4983 if (cfile_css != css) {
4988 ret = event->register_event(memcg, event->eventfd, buf);
4992 vfs_poll(efile.file, &event->pt);
4994 spin_lock(&memcg->event_list_lock);
4995 list_add(&event->list, &memcg->event_list);
4996 spin_unlock(&memcg->event_list_lock);
5008 eventfd_ctx_put(event->eventfd);
5017 static struct cftype mem_cgroup_legacy_files[] = {
5019 .name = "usage_in_bytes",
5020 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
5021 .read_u64 = mem_cgroup_read_u64,
5024 .name = "max_usage_in_bytes",
5025 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
5026 .write = mem_cgroup_reset,
5027 .read_u64 = mem_cgroup_read_u64,
5030 .name = "limit_in_bytes",
5031 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
5032 .write = mem_cgroup_write,
5033 .read_u64 = mem_cgroup_read_u64,
5036 .name = "soft_limit_in_bytes",
5037 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
5038 .write = mem_cgroup_write,
5039 .read_u64 = mem_cgroup_read_u64,
5043 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
5044 .write = mem_cgroup_reset,
5045 .read_u64 = mem_cgroup_read_u64,
5049 .seq_show = memcg_stat_show,
5052 .name = "force_empty",
5053 .write = mem_cgroup_force_empty_write,
5056 .name = "use_hierarchy",
5057 .write_u64 = mem_cgroup_hierarchy_write,
5058 .read_u64 = mem_cgroup_hierarchy_read,
5061 .name = "cgroup.event_control", /* XXX: for compat */
5062 .write = memcg_write_event_control,
5063 .flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE,
5066 .name = "swappiness",
5067 .read_u64 = mem_cgroup_swappiness_read,
5068 .write_u64 = mem_cgroup_swappiness_write,
5071 .name = "move_charge_at_immigrate",
5072 .read_u64 = mem_cgroup_move_charge_read,
5073 .write_u64 = mem_cgroup_move_charge_write,
5076 .name = "oom_control",
5077 .seq_show = mem_cgroup_oom_control_read,
5078 .write_u64 = mem_cgroup_oom_control_write,
5079 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
5082 .name = "pressure_level",
5086 .name = "numa_stat",
5087 .seq_show = memcg_numa_stat_show,
5091 .name = "kmem.limit_in_bytes",
5092 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
5093 .write = mem_cgroup_write,
5094 .read_u64 = mem_cgroup_read_u64,
5097 .name = "kmem.usage_in_bytes",
5098 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
5099 .read_u64 = mem_cgroup_read_u64,
5102 .name = "kmem.failcnt",
5103 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
5104 .write = mem_cgroup_reset,
5105 .read_u64 = mem_cgroup_read_u64,
5108 .name = "kmem.max_usage_in_bytes",
5109 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
5110 .write = mem_cgroup_reset,
5111 .read_u64 = mem_cgroup_read_u64,
5113 #if defined(CONFIG_MEMCG_KMEM) && \
5114 (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG))
5116 .name = "kmem.slabinfo",
5117 .seq_show = memcg_slab_show,
5121 .name = "kmem.tcp.limit_in_bytes",
5122 .private = MEMFILE_PRIVATE(_TCP, RES_LIMIT),
5123 .write = mem_cgroup_write,
5124 .read_u64 = mem_cgroup_read_u64,
5127 .name = "kmem.tcp.usage_in_bytes",
5128 .private = MEMFILE_PRIVATE(_TCP, RES_USAGE),
5129 .read_u64 = mem_cgroup_read_u64,
5132 .name = "kmem.tcp.failcnt",
5133 .private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT),
5134 .write = mem_cgroup_reset,
5135 .read_u64 = mem_cgroup_read_u64,
5138 .name = "kmem.tcp.max_usage_in_bytes",
5139 .private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE),
5140 .write = mem_cgroup_reset,
5141 .read_u64 = mem_cgroup_read_u64,
5143 { }, /* terminate */
5147 * Private memory cgroup IDR
5149 * Swap-out records and page cache shadow entries need to store memcg
5150 * references in constrained space, so we maintain an ID space that is
5151 * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
5152 * memory-controlled cgroups to 64k.
5154 * However, there usually are many references to the offline CSS after
5155 * the cgroup has been destroyed, such as page cache or reclaimable
5156 * slab objects, that don't need to hang on to the ID. We want to keep
5157 * those dead CSS from occupying IDs, or we might quickly exhaust the
5158 * relatively small ID space and prevent the creation of new cgroups
5159 * even when there are much fewer than 64k cgroups - possibly none.
5161 * Maintain a private 16-bit ID space for memcg, and allow the ID to
5162 * be freed and recycled when it's no longer needed, which is usually
5163 * when the CSS is offlined.
5165 * The only exception to that are records of swapped out tmpfs/shmem
5166 * pages that need to be attributed to live ancestors on swapin. But
5167 * those references are manageable from userspace.
5170 static DEFINE_IDR(mem_cgroup_idr);
5172 static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
5174 if (memcg->id.id > 0) {
5175 idr_remove(&mem_cgroup_idr, memcg->id.id);
5180 static void __maybe_unused mem_cgroup_id_get_many(struct mem_cgroup *memcg,
5183 refcount_add(n, &memcg->id.ref);
5186 static void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
5188 if (refcount_sub_and_test(n, &memcg->id.ref)) {
5189 mem_cgroup_id_remove(memcg);
5191 /* Memcg ID pins CSS */
5192 css_put(&memcg->css);
5196 static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
5198 mem_cgroup_id_put_many(memcg, 1);
5202 * mem_cgroup_from_id - look up a memcg from a memcg id
5203 * @id: the memcg id to look up
5205 * Caller must hold rcu_read_lock().
5207 struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
5209 WARN_ON_ONCE(!rcu_read_lock_held());
5210 return idr_find(&mem_cgroup_idr, id);
5213 static int alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5215 struct mem_cgroup_per_node *pn;
5218 * This routine is called against possible nodes.
5219 * But it's BUG to call kmalloc() against offline node.
5221 * TODO: this routine can waste much memory for nodes which will
5222 * never be onlined. It's better to use memory hotplug callback
5225 if (!node_state(node, N_NORMAL_MEMORY))
5227 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
5231 pn->lruvec_stat_local = alloc_percpu_gfp(struct lruvec_stat,
5232 GFP_KERNEL_ACCOUNT);
5233 if (!pn->lruvec_stat_local) {
5238 pn->lruvec_stat_cpu = alloc_percpu_gfp(struct lruvec_stat,
5239 GFP_KERNEL_ACCOUNT);
5240 if (!pn->lruvec_stat_cpu) {
5241 free_percpu(pn->lruvec_stat_local);
5246 lruvec_init(&pn->lruvec);
5247 pn->usage_in_excess = 0;
5248 pn->on_tree = false;
5251 memcg->nodeinfo[node] = pn;
5255 static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5257 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
5262 free_percpu(pn->lruvec_stat_cpu);
5263 free_percpu(pn->lruvec_stat_local);
5267 static void __mem_cgroup_free(struct mem_cgroup *memcg)
5272 free_mem_cgroup_per_node_info(memcg, node);
5273 free_percpu(memcg->vmstats_percpu);
5274 free_percpu(memcg->vmstats_local);
5278 static void mem_cgroup_free(struct mem_cgroup *memcg)
5280 memcg_wb_domain_exit(memcg);
5282 * Flush percpu vmstats and vmevents to guarantee the value correctness
5283 * on parent's and all ancestor levels.
5285 memcg_flush_percpu_vmstats(memcg);
5286 memcg_flush_percpu_vmevents(memcg);
5287 __mem_cgroup_free(memcg);
5290 static struct mem_cgroup *mem_cgroup_alloc(void)
5292 struct mem_cgroup *memcg;
5295 int __maybe_unused i;
5296 long error = -ENOMEM;
5298 size = sizeof(struct mem_cgroup);
5299 size += nr_node_ids * sizeof(struct mem_cgroup_per_node *);
5301 memcg = kzalloc(size, GFP_KERNEL);
5303 return ERR_PTR(error);
5305 memcg->id.id = idr_alloc(&mem_cgroup_idr, NULL,
5306 1, MEM_CGROUP_ID_MAX,
5308 if (memcg->id.id < 0) {
5309 error = memcg->id.id;
5313 memcg->vmstats_local = alloc_percpu_gfp(struct memcg_vmstats_percpu,
5314 GFP_KERNEL_ACCOUNT);
5315 if (!memcg->vmstats_local)
5318 memcg->vmstats_percpu = alloc_percpu_gfp(struct memcg_vmstats_percpu,
5319 GFP_KERNEL_ACCOUNT);
5320 if (!memcg->vmstats_percpu)
5324 if (alloc_mem_cgroup_per_node_info(memcg, node))
5327 if (memcg_wb_domain_init(memcg, GFP_KERNEL))
5330 INIT_WORK(&memcg->high_work, high_work_func);
5331 INIT_LIST_HEAD(&memcg->oom_notify);
5332 mutex_init(&memcg->thresholds_lock);
5333 spin_lock_init(&memcg->move_lock);
5334 vmpressure_init(&memcg->vmpressure);
5335 INIT_LIST_HEAD(&memcg->event_list);
5336 spin_lock_init(&memcg->event_list_lock);
5337 memcg->socket_pressure = jiffies;
5338 #ifdef CONFIG_MEMCG_KMEM
5339 memcg->kmemcg_id = -1;
5340 INIT_LIST_HEAD(&memcg->objcg_list);
5342 #ifdef CONFIG_CGROUP_WRITEBACK
5343 INIT_LIST_HEAD(&memcg->cgwb_list);
5344 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5345 memcg->cgwb_frn[i].done =
5346 __WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
5348 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5349 spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
5350 INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
5351 memcg->deferred_split_queue.split_queue_len = 0;
5353 idr_replace(&mem_cgroup_idr, memcg, memcg->id.id);
5356 mem_cgroup_id_remove(memcg);
5357 __mem_cgroup_free(memcg);
5358 return ERR_PTR(error);
5361 static struct cgroup_subsys_state * __ref
5362 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
5364 struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
5365 struct mem_cgroup *memcg, *old_memcg;
5366 long error = -ENOMEM;
5368 old_memcg = set_active_memcg(parent);
5369 memcg = mem_cgroup_alloc();
5370 set_active_memcg(old_memcg);
5372 return ERR_CAST(memcg);
5374 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5375 memcg->soft_limit = PAGE_COUNTER_MAX;
5376 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5378 memcg->swappiness = mem_cgroup_swappiness(parent);
5379 memcg->oom_kill_disable = parent->oom_kill_disable;
5381 page_counter_init(&memcg->memory, &parent->memory);
5382 page_counter_init(&memcg->swap, &parent->swap);
5383 page_counter_init(&memcg->kmem, &parent->kmem);
5384 page_counter_init(&memcg->tcpmem, &parent->tcpmem);
5386 page_counter_init(&memcg->memory, NULL);
5387 page_counter_init(&memcg->swap, NULL);
5388 page_counter_init(&memcg->kmem, NULL);
5389 page_counter_init(&memcg->tcpmem, NULL);
5391 root_mem_cgroup = memcg;
5395 /* The following stuff does not apply to the root */
5396 error = memcg_online_kmem(memcg);
5400 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5401 static_branch_inc(&memcg_sockets_enabled_key);
5405 mem_cgroup_id_remove(memcg);
5406 mem_cgroup_free(memcg);
5407 return ERR_PTR(error);
5410 static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
5412 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5415 * A memcg must be visible for memcg_expand_shrinker_maps()
5416 * by the time the maps are allocated. So, we allocate maps
5417 * here, when for_each_mem_cgroup() can't skip it.
5419 if (memcg_alloc_shrinker_maps(memcg)) {
5420 mem_cgroup_id_remove(memcg);
5424 /* Online state pins memcg ID, memcg ID pins CSS */
5425 refcount_set(&memcg->id.ref, 1);
5430 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
5432 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5433 struct mem_cgroup_event *event, *tmp;
5436 * Unregister events and notify userspace.
5437 * Notify userspace about cgroup removing only after rmdir of cgroup
5438 * directory to avoid race between userspace and kernelspace.
5440 spin_lock(&memcg->event_list_lock);
5441 list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
5442 list_del_init(&event->list);
5443 schedule_work(&event->remove);
5445 spin_unlock(&memcg->event_list_lock);
5447 page_counter_set_min(&memcg->memory, 0);
5448 page_counter_set_low(&memcg->memory, 0);
5450 memcg_offline_kmem(memcg);
5451 wb_memcg_offline(memcg);
5453 drain_all_stock(memcg);
5455 mem_cgroup_id_put(memcg);
5458 static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
5460 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5462 invalidate_reclaim_iterators(memcg);
5465 static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
5467 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5468 int __maybe_unused i;
5470 #ifdef CONFIG_CGROUP_WRITEBACK
5471 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5472 wb_wait_for_completion(&memcg->cgwb_frn[i].done);
5474 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5475 static_branch_dec(&memcg_sockets_enabled_key);
5477 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg->tcpmem_active)
5478 static_branch_dec(&memcg_sockets_enabled_key);
5480 vmpressure_cleanup(&memcg->vmpressure);
5481 cancel_work_sync(&memcg->high_work);
5482 mem_cgroup_remove_from_trees(memcg);
5483 memcg_free_shrinker_maps(memcg);
5484 memcg_free_kmem(memcg);
5485 mem_cgroup_free(memcg);
5489 * mem_cgroup_css_reset - reset the states of a mem_cgroup
5490 * @css: the target css
5492 * Reset the states of the mem_cgroup associated with @css. This is
5493 * invoked when the userland requests disabling on the default hierarchy
5494 * but the memcg is pinned through dependency. The memcg should stop
5495 * applying policies and should revert to the vanilla state as it may be
5496 * made visible again.
5498 * The current implementation only resets the essential configurations.
5499 * This needs to be expanded to cover all the visible parts.
5501 static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
5503 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5505 page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
5506 page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
5507 page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
5508 page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
5509 page_counter_set_min(&memcg->memory, 0);
5510 page_counter_set_low(&memcg->memory, 0);
5511 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5512 memcg->soft_limit = PAGE_COUNTER_MAX;
5513 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5514 memcg_wb_domain_size_changed(memcg);
5518 /* Handlers for move charge at task migration. */
5519 static int mem_cgroup_do_precharge(unsigned long count)
5523 /* Try a single bulk charge without reclaim first, kswapd may wake */
5524 ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count);
5526 mc.precharge += count;
5530 /* Try charges one by one with reclaim, but do not retry */
5532 ret = try_charge(mc.to, GFP_KERNEL | __GFP_NORETRY, 1);
5546 enum mc_target_type {
5553 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5554 unsigned long addr, pte_t ptent)
5556 struct page *page = vm_normal_page(vma, addr, ptent);
5558 if (!page || !page_mapped(page))
5560 if (PageAnon(page)) {
5561 if (!(mc.flags & MOVE_ANON))
5564 if (!(mc.flags & MOVE_FILE))
5567 if (!get_page_unless_zero(page))
5573 #if defined(CONFIG_SWAP) || defined(CONFIG_DEVICE_PRIVATE)
5574 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5575 pte_t ptent, swp_entry_t *entry)
5577 struct page *page = NULL;
5578 swp_entry_t ent = pte_to_swp_entry(ptent);
5580 if (!(mc.flags & MOVE_ANON))
5584 * Handle MEMORY_DEVICE_PRIVATE which are ZONE_DEVICE page belonging to
5585 * a device and because they are not accessible by CPU they are store
5586 * as special swap entry in the CPU page table.
5588 if (is_device_private_entry(ent)) {
5589 page = device_private_entry_to_page(ent);
5591 * MEMORY_DEVICE_PRIVATE means ZONE_DEVICE page and which have
5592 * a refcount of 1 when free (unlike normal page)
5594 if (!page_ref_add_unless(page, 1, 1))
5599 if (non_swap_entry(ent))
5603 * Because lookup_swap_cache() updates some statistics counter,
5604 * we call find_get_page() with swapper_space directly.
5606 page = find_get_page(swap_address_space(ent), swp_offset(ent));
5607 entry->val = ent.val;
5612 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5613 pte_t ptent, swp_entry_t *entry)
5619 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5620 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5622 if (!vma->vm_file) /* anonymous vma */
5624 if (!(mc.flags & MOVE_FILE))
5627 /* page is moved even if it's not RSS of this task(page-faulted). */
5628 /* shmem/tmpfs may report page out on swap: account for that too. */
5629 return find_get_incore_page(vma->vm_file->f_mapping,
5630 linear_page_index(vma, addr));
5634 * mem_cgroup_move_account - move account of the page
5636 * @compound: charge the page as compound or small page
5637 * @from: mem_cgroup which the page is moved from.
5638 * @to: mem_cgroup which the page is moved to. @from != @to.
5640 * The caller must make sure the page is not on LRU (isolate_page() is useful.)
5642 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
5645 static int mem_cgroup_move_account(struct page *page,
5647 struct mem_cgroup *from,
5648 struct mem_cgroup *to)
5650 struct lruvec *from_vec, *to_vec;
5651 struct pglist_data *pgdat;
5652 unsigned int nr_pages = compound ? thp_nr_pages(page) : 1;
5655 VM_BUG_ON(from == to);
5656 VM_BUG_ON_PAGE(PageLRU(page), page);
5657 VM_BUG_ON(compound && !PageTransHuge(page));
5660 * Prevent mem_cgroup_migrate() from looking at
5661 * page's memory cgroup of its source page while we change it.
5664 if (!trylock_page(page))
5668 if (page_memcg(page) != from)
5671 pgdat = page_pgdat(page);
5672 from_vec = mem_cgroup_lruvec(from, pgdat);
5673 to_vec = mem_cgroup_lruvec(to, pgdat);
5675 lock_page_memcg(page);
5677 if (PageAnon(page)) {
5678 if (page_mapped(page)) {
5679 __mod_lruvec_state(from_vec, NR_ANON_MAPPED, -nr_pages);
5680 __mod_lruvec_state(to_vec, NR_ANON_MAPPED, nr_pages);
5681 if (PageTransHuge(page)) {
5682 __mod_lruvec_state(from_vec, NR_ANON_THPS,
5684 __mod_lruvec_state(to_vec, NR_ANON_THPS,
5690 __mod_lruvec_state(from_vec, NR_FILE_PAGES, -nr_pages);
5691 __mod_lruvec_state(to_vec, NR_FILE_PAGES, nr_pages);
5693 if (PageSwapBacked(page)) {
5694 __mod_lruvec_state(from_vec, NR_SHMEM, -nr_pages);
5695 __mod_lruvec_state(to_vec, NR_SHMEM, nr_pages);
5698 if (page_mapped(page)) {
5699 __mod_lruvec_state(from_vec, NR_FILE_MAPPED, -nr_pages);
5700 __mod_lruvec_state(to_vec, NR_FILE_MAPPED, nr_pages);
5703 if (PageDirty(page)) {
5704 struct address_space *mapping = page_mapping(page);
5706 if (mapping_can_writeback(mapping)) {
5707 __mod_lruvec_state(from_vec, NR_FILE_DIRTY,
5709 __mod_lruvec_state(to_vec, NR_FILE_DIRTY,
5715 if (PageWriteback(page)) {
5716 __mod_lruvec_state(from_vec, NR_WRITEBACK, -nr_pages);
5717 __mod_lruvec_state(to_vec, NR_WRITEBACK, nr_pages);
5721 * All state has been migrated, let's switch to the new memcg.
5723 * It is safe to change page's memcg here because the page
5724 * is referenced, charged, isolated, and locked: we can't race
5725 * with (un)charging, migration, LRU putback, or anything else
5726 * that would rely on a stable page's memory cgroup.
5728 * Note that lock_page_memcg is a memcg lock, not a page lock,
5729 * to save space. As soon as we switch page's memory cgroup to a
5730 * new memcg that isn't locked, the above state can change
5731 * concurrently again. Make sure we're truly done with it.
5736 css_put(&from->css);
5738 page->memcg_data = (unsigned long)to;
5740 __unlock_page_memcg(from);
5744 local_irq_disable();
5745 mem_cgroup_charge_statistics(to, page, nr_pages);
5746 memcg_check_events(to, page);
5747 mem_cgroup_charge_statistics(from, page, -nr_pages);
5748 memcg_check_events(from, page);
5757 * get_mctgt_type - get target type of moving charge
5758 * @vma: the vma the pte to be checked belongs
5759 * @addr: the address corresponding to the pte to be checked
5760 * @ptent: the pte to be checked
5761 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5764 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5765 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5766 * move charge. if @target is not NULL, the page is stored in target->page
5767 * with extra refcnt got(Callers should handle it).
5768 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5769 * target for charge migration. if @target is not NULL, the entry is stored
5771 * 3(MC_TARGET_DEVICE): like MC_TARGET_PAGE but page is MEMORY_DEVICE_PRIVATE
5772 * (so ZONE_DEVICE page and thus not on the lru).
5773 * For now we such page is charge like a regular page would be as for all
5774 * intent and purposes it is just special memory taking the place of a
5777 * See Documentations/vm/hmm.txt and include/linux/hmm.h
5779 * Called with pte lock held.
5782 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
5783 unsigned long addr, pte_t ptent, union mc_target *target)
5785 struct page *page = NULL;
5786 enum mc_target_type ret = MC_TARGET_NONE;
5787 swp_entry_t ent = { .val = 0 };
5789 if (pte_present(ptent))
5790 page = mc_handle_present_pte(vma, addr, ptent);
5791 else if (is_swap_pte(ptent))
5792 page = mc_handle_swap_pte(vma, ptent, &ent);
5793 else if (pte_none(ptent))
5794 page = mc_handle_file_pte(vma, addr, ptent, &ent);
5796 if (!page && !ent.val)
5800 * Do only loose check w/o serialization.
5801 * mem_cgroup_move_account() checks the page is valid or
5802 * not under LRU exclusion.
5804 if (page_memcg(page) == mc.from) {
5805 ret = MC_TARGET_PAGE;
5806 if (is_device_private_page(page))
5807 ret = MC_TARGET_DEVICE;
5809 target->page = page;
5811 if (!ret || !target)
5815 * There is a swap entry and a page doesn't exist or isn't charged.
5816 * But we cannot move a tail-page in a THP.
5818 if (ent.val && !ret && (!page || !PageTransCompound(page)) &&
5819 mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
5820 ret = MC_TARGET_SWAP;
5827 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5829 * We don't consider PMD mapped swapping or file mapped pages because THP does
5830 * not support them for now.
5831 * Caller should make sure that pmd_trans_huge(pmd) is true.
5833 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5834 unsigned long addr, pmd_t pmd, union mc_target *target)
5836 struct page *page = NULL;
5837 enum mc_target_type ret = MC_TARGET_NONE;
5839 if (unlikely(is_swap_pmd(pmd))) {
5840 VM_BUG_ON(thp_migration_supported() &&
5841 !is_pmd_migration_entry(pmd));
5844 page = pmd_page(pmd);
5845 VM_BUG_ON_PAGE(!page || !PageHead(page), page);
5846 if (!(mc.flags & MOVE_ANON))
5848 if (page_memcg(page) == mc.from) {
5849 ret = MC_TARGET_PAGE;
5852 target->page = page;
5858 static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5859 unsigned long addr, pmd_t pmd, union mc_target *target)
5861 return MC_TARGET_NONE;
5865 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5866 unsigned long addr, unsigned long end,
5867 struct mm_walk *walk)
5869 struct vm_area_struct *vma = walk->vma;
5873 ptl = pmd_trans_huge_lock(pmd, vma);
5876 * Note their can not be MC_TARGET_DEVICE for now as we do not
5877 * support transparent huge page with MEMORY_DEVICE_PRIVATE but
5878 * this might change.
5880 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
5881 mc.precharge += HPAGE_PMD_NR;
5886 if (pmd_trans_unstable(pmd))
5888 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5889 for (; addr != end; pte++, addr += PAGE_SIZE)
5890 if (get_mctgt_type(vma, addr, *pte, NULL))
5891 mc.precharge++; /* increment precharge temporarily */
5892 pte_unmap_unlock(pte - 1, ptl);
5898 static const struct mm_walk_ops precharge_walk_ops = {
5899 .pmd_entry = mem_cgroup_count_precharge_pte_range,
5902 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5904 unsigned long precharge;
5907 walk_page_range(mm, 0, mm->highest_vm_end, &precharge_walk_ops, NULL);
5908 mmap_read_unlock(mm);
5910 precharge = mc.precharge;
5916 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5918 unsigned long precharge = mem_cgroup_count_precharge(mm);
5920 VM_BUG_ON(mc.moving_task);
5921 mc.moving_task = current;
5922 return mem_cgroup_do_precharge(precharge);
5925 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5926 static void __mem_cgroup_clear_mc(void)
5928 struct mem_cgroup *from = mc.from;
5929 struct mem_cgroup *to = mc.to;
5931 /* we must uncharge all the leftover precharges from mc.to */
5933 cancel_charge(mc.to, mc.precharge);
5937 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5938 * we must uncharge here.
5940 if (mc.moved_charge) {
5941 cancel_charge(mc.from, mc.moved_charge);
5942 mc.moved_charge = 0;
5944 /* we must fixup refcnts and charges */
5945 if (mc.moved_swap) {
5946 /* uncharge swap account from the old cgroup */
5947 if (!mem_cgroup_is_root(mc.from))
5948 page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
5950 mem_cgroup_id_put_many(mc.from, mc.moved_swap);
5953 * we charged both to->memory and to->memsw, so we
5954 * should uncharge to->memory.
5956 if (!mem_cgroup_is_root(mc.to))
5957 page_counter_uncharge(&mc.to->memory, mc.moved_swap);
5961 memcg_oom_recover(from);
5962 memcg_oom_recover(to);
5963 wake_up_all(&mc.waitq);
5966 static void mem_cgroup_clear_mc(void)
5968 struct mm_struct *mm = mc.mm;
5971 * we must clear moving_task before waking up waiters at the end of
5974 mc.moving_task = NULL;
5975 __mem_cgroup_clear_mc();
5976 spin_lock(&mc.lock);
5980 spin_unlock(&mc.lock);
5985 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
5987 struct cgroup_subsys_state *css;
5988 struct mem_cgroup *memcg = NULL; /* unneeded init to make gcc happy */
5989 struct mem_cgroup *from;
5990 struct task_struct *leader, *p;
5991 struct mm_struct *mm;
5992 unsigned long move_flags;
5995 /* charge immigration isn't supported on the default hierarchy */
5996 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
6000 * Multi-process migrations only happen on the default hierarchy
6001 * where charge immigration is not used. Perform charge
6002 * immigration if @tset contains a leader and whine if there are
6006 cgroup_taskset_for_each_leader(leader, css, tset) {
6009 memcg = mem_cgroup_from_css(css);
6015 * We are now commited to this value whatever it is. Changes in this
6016 * tunable will only affect upcoming migrations, not the current one.
6017 * So we need to save it, and keep it going.
6019 move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
6023 from = mem_cgroup_from_task(p);
6025 VM_BUG_ON(from == memcg);
6027 mm = get_task_mm(p);
6030 /* We move charges only when we move a owner of the mm */
6031 if (mm->owner == p) {
6034 VM_BUG_ON(mc.precharge);
6035 VM_BUG_ON(mc.moved_charge);
6036 VM_BUG_ON(mc.moved_swap);
6038 spin_lock(&mc.lock);
6042 mc.flags = move_flags;
6043 spin_unlock(&mc.lock);
6044 /* We set mc.moving_task later */
6046 ret = mem_cgroup_precharge_mc(mm);
6048 mem_cgroup_clear_mc();
6055 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6058 mem_cgroup_clear_mc();
6061 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
6062 unsigned long addr, unsigned long end,
6063 struct mm_walk *walk)
6066 struct vm_area_struct *vma = walk->vma;
6069 enum mc_target_type target_type;
6070 union mc_target target;
6073 ptl = pmd_trans_huge_lock(pmd, vma);
6075 if (mc.precharge < HPAGE_PMD_NR) {
6079 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
6080 if (target_type == MC_TARGET_PAGE) {
6082 if (!isolate_lru_page(page)) {
6083 if (!mem_cgroup_move_account(page, true,
6085 mc.precharge -= HPAGE_PMD_NR;
6086 mc.moved_charge += HPAGE_PMD_NR;
6088 putback_lru_page(page);
6091 } else if (target_type == MC_TARGET_DEVICE) {
6093 if (!mem_cgroup_move_account(page, true,
6095 mc.precharge -= HPAGE_PMD_NR;
6096 mc.moved_charge += HPAGE_PMD_NR;
6104 if (pmd_trans_unstable(pmd))
6107 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6108 for (; addr != end; addr += PAGE_SIZE) {
6109 pte_t ptent = *(pte++);
6110 bool device = false;
6116 switch (get_mctgt_type(vma, addr, ptent, &target)) {
6117 case MC_TARGET_DEVICE:
6120 case MC_TARGET_PAGE:
6123 * We can have a part of the split pmd here. Moving it
6124 * can be done but it would be too convoluted so simply
6125 * ignore such a partial THP and keep it in original
6126 * memcg. There should be somebody mapping the head.
6128 if (PageTransCompound(page))
6130 if (!device && isolate_lru_page(page))
6132 if (!mem_cgroup_move_account(page, false,
6135 /* we uncharge from mc.from later. */
6139 putback_lru_page(page);
6140 put: /* get_mctgt_type() gets the page */
6143 case MC_TARGET_SWAP:
6145 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
6147 mem_cgroup_id_get_many(mc.to, 1);
6148 /* we fixup other refcnts and charges later. */
6156 pte_unmap_unlock(pte - 1, ptl);
6161 * We have consumed all precharges we got in can_attach().
6162 * We try charge one by one, but don't do any additional
6163 * charges to mc.to if we have failed in charge once in attach()
6166 ret = mem_cgroup_do_precharge(1);
6174 static const struct mm_walk_ops charge_walk_ops = {
6175 .pmd_entry = mem_cgroup_move_charge_pte_range,
6178 static void mem_cgroup_move_charge(void)
6180 lru_add_drain_all();
6182 * Signal lock_page_memcg() to take the memcg's move_lock
6183 * while we're moving its pages to another memcg. Then wait
6184 * for already started RCU-only updates to finish.
6186 atomic_inc(&mc.from->moving_account);
6189 if (unlikely(!mmap_read_trylock(mc.mm))) {
6191 * Someone who are holding the mmap_lock might be waiting in
6192 * waitq. So we cancel all extra charges, wake up all waiters,
6193 * and retry. Because we cancel precharges, we might not be able
6194 * to move enough charges, but moving charge is a best-effort
6195 * feature anyway, so it wouldn't be a big problem.
6197 __mem_cgroup_clear_mc();
6202 * When we have consumed all precharges and failed in doing
6203 * additional charge, the page walk just aborts.
6205 walk_page_range(mc.mm, 0, mc.mm->highest_vm_end, &charge_walk_ops,
6208 mmap_read_unlock(mc.mm);
6209 atomic_dec(&mc.from->moving_account);
6212 static void mem_cgroup_move_task(void)
6215 mem_cgroup_move_charge();
6216 mem_cgroup_clear_mc();
6219 #else /* !CONFIG_MMU */
6220 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
6224 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6227 static void mem_cgroup_move_task(void)
6232 static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
6234 if (value == PAGE_COUNTER_MAX)
6235 seq_puts(m, "max\n");
6237 seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
6242 static u64 memory_current_read(struct cgroup_subsys_state *css,
6245 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6247 return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
6250 static int memory_min_show(struct seq_file *m, void *v)
6252 return seq_puts_memcg_tunable(m,
6253 READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
6256 static ssize_t memory_min_write(struct kernfs_open_file *of,
6257 char *buf, size_t nbytes, loff_t off)
6259 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6263 buf = strstrip(buf);
6264 err = page_counter_memparse(buf, "max", &min);
6268 page_counter_set_min(&memcg->memory, min);
6273 static int memory_low_show(struct seq_file *m, void *v)
6275 return seq_puts_memcg_tunable(m,
6276 READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
6279 static ssize_t memory_low_write(struct kernfs_open_file *of,
6280 char *buf, size_t nbytes, loff_t off)
6282 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6286 buf = strstrip(buf);
6287 err = page_counter_memparse(buf, "max", &low);
6291 page_counter_set_low(&memcg->memory, low);
6296 static int memory_high_show(struct seq_file *m, void *v)
6298 return seq_puts_memcg_tunable(m,
6299 READ_ONCE(mem_cgroup_from_seq(m)->memory.high));
6302 static ssize_t memory_high_write(struct kernfs_open_file *of,
6303 char *buf, size_t nbytes, loff_t off)
6305 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6306 unsigned int nr_retries = MAX_RECLAIM_RETRIES;
6307 bool drained = false;
6311 buf = strstrip(buf);
6312 err = page_counter_memparse(buf, "max", &high);
6317 unsigned long nr_pages = page_counter_read(&memcg->memory);
6318 unsigned long reclaimed;
6320 if (nr_pages <= high)
6323 if (signal_pending(current))
6327 drain_all_stock(memcg);
6332 reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
6335 if (!reclaimed && !nr_retries--)
6339 page_counter_set_high(&memcg->memory, high);
6341 memcg_wb_domain_size_changed(memcg);
6346 static int memory_max_show(struct seq_file *m, void *v)
6348 return seq_puts_memcg_tunable(m,
6349 READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
6352 static ssize_t memory_max_write(struct kernfs_open_file *of,
6353 char *buf, size_t nbytes, loff_t off)
6355 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6356 unsigned int nr_reclaims = MAX_RECLAIM_RETRIES;
6357 bool drained = false;
6361 buf = strstrip(buf);
6362 err = page_counter_memparse(buf, "max", &max);
6366 xchg(&memcg->memory.max, max);
6369 unsigned long nr_pages = page_counter_read(&memcg->memory);
6371 if (nr_pages <= max)
6374 if (signal_pending(current))
6378 drain_all_stock(memcg);
6384 if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
6390 memcg_memory_event(memcg, MEMCG_OOM);
6391 if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
6395 memcg_wb_domain_size_changed(memcg);
6399 static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
6401 seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
6402 seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
6403 seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
6404 seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
6405 seq_printf(m, "oom_kill %lu\n",
6406 atomic_long_read(&events[MEMCG_OOM_KILL]));
6409 static int memory_events_show(struct seq_file *m, void *v)
6411 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6413 __memory_events_show(m, memcg->memory_events);
6417 static int memory_events_local_show(struct seq_file *m, void *v)
6419 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6421 __memory_events_show(m, memcg->memory_events_local);
6425 static int memory_stat_show(struct seq_file *m, void *v)
6427 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6430 buf = memory_stat_format(memcg);
6439 static int memory_numa_stat_show(struct seq_file *m, void *v)
6442 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6444 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
6447 if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS)
6450 seq_printf(m, "%s", memory_stats[i].name);
6451 for_each_node_state(nid, N_MEMORY) {
6453 struct lruvec *lruvec;
6455 lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
6456 size = lruvec_page_state(lruvec, memory_stats[i].idx);
6457 size *= memory_stats[i].ratio;
6458 seq_printf(m, " N%d=%llu", nid, size);
6467 static int memory_oom_group_show(struct seq_file *m, void *v)
6469 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6471 seq_printf(m, "%d\n", memcg->oom_group);
6476 static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
6477 char *buf, size_t nbytes, loff_t off)
6479 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6482 buf = strstrip(buf);
6486 ret = kstrtoint(buf, 0, &oom_group);
6490 if (oom_group != 0 && oom_group != 1)
6493 memcg->oom_group = oom_group;
6498 static struct cftype memory_files[] = {
6501 .flags = CFTYPE_NOT_ON_ROOT,
6502 .read_u64 = memory_current_read,
6506 .flags = CFTYPE_NOT_ON_ROOT,
6507 .seq_show = memory_min_show,
6508 .write = memory_min_write,
6512 .flags = CFTYPE_NOT_ON_ROOT,
6513 .seq_show = memory_low_show,
6514 .write = memory_low_write,
6518 .flags = CFTYPE_NOT_ON_ROOT,
6519 .seq_show = memory_high_show,
6520 .write = memory_high_write,
6524 .flags = CFTYPE_NOT_ON_ROOT,
6525 .seq_show = memory_max_show,
6526 .write = memory_max_write,
6530 .flags = CFTYPE_NOT_ON_ROOT,
6531 .file_offset = offsetof(struct mem_cgroup, events_file),
6532 .seq_show = memory_events_show,
6535 .name = "events.local",
6536 .flags = CFTYPE_NOT_ON_ROOT,
6537 .file_offset = offsetof(struct mem_cgroup, events_local_file),
6538 .seq_show = memory_events_local_show,
6542 .seq_show = memory_stat_show,
6546 .name = "numa_stat",
6547 .seq_show = memory_numa_stat_show,
6551 .name = "oom.group",
6552 .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
6553 .seq_show = memory_oom_group_show,
6554 .write = memory_oom_group_write,
6559 struct cgroup_subsys memory_cgrp_subsys = {
6560 .css_alloc = mem_cgroup_css_alloc,
6561 .css_online = mem_cgroup_css_online,
6562 .css_offline = mem_cgroup_css_offline,
6563 .css_released = mem_cgroup_css_released,
6564 .css_free = mem_cgroup_css_free,
6565 .css_reset = mem_cgroup_css_reset,
6566 .can_attach = mem_cgroup_can_attach,
6567 .cancel_attach = mem_cgroup_cancel_attach,
6568 .post_attach = mem_cgroup_move_task,
6569 .dfl_cftypes = memory_files,
6570 .legacy_cftypes = mem_cgroup_legacy_files,
6575 * This function calculates an individual cgroup's effective
6576 * protection which is derived from its own memory.min/low, its
6577 * parent's and siblings' settings, as well as the actual memory
6578 * distribution in the tree.
6580 * The following rules apply to the effective protection values:
6582 * 1. At the first level of reclaim, effective protection is equal to
6583 * the declared protection in memory.min and memory.low.
6585 * 2. To enable safe delegation of the protection configuration, at
6586 * subsequent levels the effective protection is capped to the
6587 * parent's effective protection.
6589 * 3. To make complex and dynamic subtrees easier to configure, the
6590 * user is allowed to overcommit the declared protection at a given
6591 * level. If that is the case, the parent's effective protection is
6592 * distributed to the children in proportion to how much protection
6593 * they have declared and how much of it they are utilizing.
6595 * This makes distribution proportional, but also work-conserving:
6596 * if one cgroup claims much more protection than it uses memory,
6597 * the unused remainder is available to its siblings.
6599 * 4. Conversely, when the declared protection is undercommitted at a
6600 * given level, the distribution of the larger parental protection
6601 * budget is NOT proportional. A cgroup's protection from a sibling
6602 * is capped to its own memory.min/low setting.
6604 * 5. However, to allow protecting recursive subtrees from each other
6605 * without having to declare each individual cgroup's fixed share
6606 * of the ancestor's claim to protection, any unutilized -
6607 * "floating" - protection from up the tree is distributed in
6608 * proportion to each cgroup's *usage*. This makes the protection
6609 * neutral wrt sibling cgroups and lets them compete freely over
6610 * the shared parental protection budget, but it protects the
6611 * subtree as a whole from neighboring subtrees.
6613 * Note that 4. and 5. are not in conflict: 4. is about protecting
6614 * against immediate siblings whereas 5. is about protecting against
6615 * neighboring subtrees.
6617 static unsigned long effective_protection(unsigned long usage,
6618 unsigned long parent_usage,
6619 unsigned long setting,
6620 unsigned long parent_effective,
6621 unsigned long siblings_protected)
6623 unsigned long protected;
6626 protected = min(usage, setting);
6628 * If all cgroups at this level combined claim and use more
6629 * protection then what the parent affords them, distribute
6630 * shares in proportion to utilization.
6632 * We are using actual utilization rather than the statically
6633 * claimed protection in order to be work-conserving: claimed
6634 * but unused protection is available to siblings that would
6635 * otherwise get a smaller chunk than what they claimed.
6637 if (siblings_protected > parent_effective)
6638 return protected * parent_effective / siblings_protected;
6641 * Ok, utilized protection of all children is within what the
6642 * parent affords them, so we know whatever this child claims
6643 * and utilizes is effectively protected.
6645 * If there is unprotected usage beyond this value, reclaim
6646 * will apply pressure in proportion to that amount.
6648 * If there is unutilized protection, the cgroup will be fully
6649 * shielded from reclaim, but we do return a smaller value for
6650 * protection than what the group could enjoy in theory. This
6651 * is okay. With the overcommit distribution above, effective
6652 * protection is always dependent on how memory is actually
6653 * consumed among the siblings anyway.
6658 * If the children aren't claiming (all of) the protection
6659 * afforded to them by the parent, distribute the remainder in
6660 * proportion to the (unprotected) memory of each cgroup. That
6661 * way, cgroups that aren't explicitly prioritized wrt each
6662 * other compete freely over the allowance, but they are
6663 * collectively protected from neighboring trees.
6665 * We're using unprotected memory for the weight so that if
6666 * some cgroups DO claim explicit protection, we don't protect
6667 * the same bytes twice.
6669 * Check both usage and parent_usage against the respective
6670 * protected values. One should imply the other, but they
6671 * aren't read atomically - make sure the division is sane.
6673 if (!(cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT))
6675 if (parent_effective > siblings_protected &&
6676 parent_usage > siblings_protected &&
6677 usage > protected) {
6678 unsigned long unclaimed;
6680 unclaimed = parent_effective - siblings_protected;
6681 unclaimed *= usage - protected;
6682 unclaimed /= parent_usage - siblings_protected;
6691 * mem_cgroup_protected - check if memory consumption is in the normal range
6692 * @root: the top ancestor of the sub-tree being checked
6693 * @memcg: the memory cgroup to check
6695 * WARNING: This function is not stateless! It can only be used as part
6696 * of a top-down tree iteration, not for isolated queries.
6698 void mem_cgroup_calculate_protection(struct mem_cgroup *root,
6699 struct mem_cgroup *memcg)
6701 unsigned long usage, parent_usage;
6702 struct mem_cgroup *parent;
6704 if (mem_cgroup_disabled())
6708 root = root_mem_cgroup;
6711 * Effective values of the reclaim targets are ignored so they
6712 * can be stale. Have a look at mem_cgroup_protection for more
6714 * TODO: calculation should be more robust so that we do not need
6715 * that special casing.
6720 usage = page_counter_read(&memcg->memory);
6724 parent = parent_mem_cgroup(memcg);
6725 /* No parent means a non-hierarchical mode on v1 memcg */
6729 if (parent == root) {
6730 memcg->memory.emin = READ_ONCE(memcg->memory.min);
6731 memcg->memory.elow = READ_ONCE(memcg->memory.low);
6735 parent_usage = page_counter_read(&parent->memory);
6737 WRITE_ONCE(memcg->memory.emin, effective_protection(usage, parent_usage,
6738 READ_ONCE(memcg->memory.min),
6739 READ_ONCE(parent->memory.emin),
6740 atomic_long_read(&parent->memory.children_min_usage)));
6742 WRITE_ONCE(memcg->memory.elow, effective_protection(usage, parent_usage,
6743 READ_ONCE(memcg->memory.low),
6744 READ_ONCE(parent->memory.elow),
6745 atomic_long_read(&parent->memory.children_low_usage)));
6749 * mem_cgroup_charge - charge a newly allocated page to a cgroup
6750 * @page: page to charge
6751 * @mm: mm context of the victim
6752 * @gfp_mask: reclaim mode
6754 * Try to charge @page to the memcg that @mm belongs to, reclaiming
6755 * pages according to @gfp_mask if necessary.
6757 * Returns 0 on success. Otherwise, an error code is returned.
6759 int mem_cgroup_charge(struct page *page, struct mm_struct *mm, gfp_t gfp_mask)
6761 unsigned int nr_pages = thp_nr_pages(page);
6762 struct mem_cgroup *memcg = NULL;
6765 if (mem_cgroup_disabled())
6768 if (PageSwapCache(page)) {
6769 swp_entry_t ent = { .val = page_private(page), };
6773 * Every swap fault against a single page tries to charge the
6774 * page, bail as early as possible. shmem_unuse() encounters
6775 * already charged pages, too. page and memcg binding is
6776 * protected by the page lock, which serializes swap cache
6777 * removal, which in turn serializes uncharging.
6779 VM_BUG_ON_PAGE(!PageLocked(page), page);
6780 if (page_memcg(compound_head(page)))
6783 id = lookup_swap_cgroup_id(ent);
6785 memcg = mem_cgroup_from_id(id);
6786 if (memcg && !css_tryget_online(&memcg->css))
6792 memcg = get_mem_cgroup_from_mm(mm);
6794 ret = try_charge(memcg, gfp_mask, nr_pages);
6798 css_get(&memcg->css);
6799 commit_charge(page, memcg);
6801 local_irq_disable();
6802 mem_cgroup_charge_statistics(memcg, page, nr_pages);
6803 memcg_check_events(memcg, page);
6806 if (PageSwapCache(page)) {
6807 swp_entry_t entry = { .val = page_private(page) };
6809 * The swap entry might not get freed for a long time,
6810 * let's not wait for it. The page already received a
6811 * memory+swap charge, drop the swap entry duplicate.
6813 mem_cgroup_uncharge_swap(entry, nr_pages);
6817 css_put(&memcg->css);
6822 struct uncharge_gather {
6823 struct mem_cgroup *memcg;
6824 unsigned long nr_pages;
6825 unsigned long pgpgout;
6826 unsigned long nr_kmem;
6827 struct page *dummy_page;
6830 static inline void uncharge_gather_clear(struct uncharge_gather *ug)
6832 memset(ug, 0, sizeof(*ug));
6835 static void uncharge_batch(const struct uncharge_gather *ug)
6837 unsigned long flags;
6839 if (!mem_cgroup_is_root(ug->memcg)) {
6840 page_counter_uncharge(&ug->memcg->memory, ug->nr_pages);
6841 if (do_memsw_account())
6842 page_counter_uncharge(&ug->memcg->memsw, ug->nr_pages);
6843 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && ug->nr_kmem)
6844 page_counter_uncharge(&ug->memcg->kmem, ug->nr_kmem);
6845 memcg_oom_recover(ug->memcg);
6848 local_irq_save(flags);
6849 __count_memcg_events(ug->memcg, PGPGOUT, ug->pgpgout);
6850 __this_cpu_add(ug->memcg->vmstats_percpu->nr_page_events, ug->nr_pages);
6851 memcg_check_events(ug->memcg, ug->dummy_page);
6852 local_irq_restore(flags);
6854 /* drop reference from uncharge_page */
6855 css_put(&ug->memcg->css);
6858 static void uncharge_page(struct page *page, struct uncharge_gather *ug)
6860 unsigned long nr_pages;
6862 VM_BUG_ON_PAGE(PageLRU(page), page);
6864 if (!page_memcg(page))
6868 * Nobody should be changing or seriously looking at
6869 * page_memcg(page) at this point, we have fully
6870 * exclusive access to the page.
6873 if (ug->memcg != page_memcg(page)) {
6876 uncharge_gather_clear(ug);
6878 ug->memcg = page_memcg(page);
6880 /* pairs with css_put in uncharge_batch */
6881 css_get(&ug->memcg->css);
6884 nr_pages = compound_nr(page);
6885 ug->nr_pages += nr_pages;
6887 if (PageMemcgKmem(page))
6888 ug->nr_kmem += nr_pages;
6892 ug->dummy_page = page;
6893 page->memcg_data = 0;
6894 css_put(&ug->memcg->css);
6897 static void uncharge_list(struct list_head *page_list)
6899 struct uncharge_gather ug;
6900 struct list_head *next;
6902 uncharge_gather_clear(&ug);
6905 * Note that the list can be a single page->lru; hence the
6906 * do-while loop instead of a simple list_for_each_entry().
6908 next = page_list->next;
6912 page = list_entry(next, struct page, lru);
6913 next = page->lru.next;
6915 uncharge_page(page, &ug);
6916 } while (next != page_list);
6919 uncharge_batch(&ug);
6923 * mem_cgroup_uncharge - uncharge a page
6924 * @page: page to uncharge
6926 * Uncharge a page previously charged with mem_cgroup_charge().
6928 void mem_cgroup_uncharge(struct page *page)
6930 struct uncharge_gather ug;
6932 if (mem_cgroup_disabled())
6935 /* Don't touch page->lru of any random page, pre-check: */
6936 if (!page_memcg(page))
6939 uncharge_gather_clear(&ug);
6940 uncharge_page(page, &ug);
6941 uncharge_batch(&ug);
6945 * mem_cgroup_uncharge_list - uncharge a list of page
6946 * @page_list: list of pages to uncharge
6948 * Uncharge a list of pages previously charged with
6949 * mem_cgroup_charge().
6951 void mem_cgroup_uncharge_list(struct list_head *page_list)
6953 if (mem_cgroup_disabled())
6956 if (!list_empty(page_list))
6957 uncharge_list(page_list);
6961 * mem_cgroup_migrate - charge a page's replacement
6962 * @oldpage: currently circulating page
6963 * @newpage: replacement page
6965 * Charge @newpage as a replacement page for @oldpage. @oldpage will
6966 * be uncharged upon free.
6968 * Both pages must be locked, @newpage->mapping must be set up.
6970 void mem_cgroup_migrate(struct page *oldpage, struct page *newpage)
6972 struct mem_cgroup *memcg;
6973 unsigned int nr_pages;
6974 unsigned long flags;
6976 VM_BUG_ON_PAGE(!PageLocked(oldpage), oldpage);
6977 VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
6978 VM_BUG_ON_PAGE(PageAnon(oldpage) != PageAnon(newpage), newpage);
6979 VM_BUG_ON_PAGE(PageTransHuge(oldpage) != PageTransHuge(newpage),
6982 if (mem_cgroup_disabled())
6985 /* Page cache replacement: new page already charged? */
6986 if (page_memcg(newpage))
6989 memcg = page_memcg(oldpage);
6993 /* Force-charge the new page. The old one will be freed soon */
6994 nr_pages = thp_nr_pages(newpage);
6996 page_counter_charge(&memcg->memory, nr_pages);
6997 if (do_memsw_account())
6998 page_counter_charge(&memcg->memsw, nr_pages);
7000 css_get(&memcg->css);
7001 commit_charge(newpage, memcg);
7003 local_irq_save(flags);
7004 mem_cgroup_charge_statistics(memcg, newpage, nr_pages);
7005 memcg_check_events(memcg, newpage);
7006 local_irq_restore(flags);
7009 DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
7010 EXPORT_SYMBOL(memcg_sockets_enabled_key);
7012 void mem_cgroup_sk_alloc(struct sock *sk)
7014 struct mem_cgroup *memcg;
7016 if (!mem_cgroup_sockets_enabled)
7019 /* Do not associate the sock with unrelated interrupted task's memcg. */
7024 memcg = mem_cgroup_from_task(current);
7025 if (memcg == root_mem_cgroup)
7027 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg->tcpmem_active)
7029 if (css_tryget(&memcg->css))
7030 sk->sk_memcg = memcg;
7035 void mem_cgroup_sk_free(struct sock *sk)
7038 css_put(&sk->sk_memcg->css);
7042 * mem_cgroup_charge_skmem - charge socket memory
7043 * @memcg: memcg to charge
7044 * @nr_pages: number of pages to charge
7046 * Charges @nr_pages to @memcg. Returns %true if the charge fit within
7047 * @memcg's configured limit, %false if the charge had to be forced.
7049 bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
7051 gfp_t gfp_mask = GFP_KERNEL;
7053 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
7054 struct page_counter *fail;
7056 if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) {
7057 memcg->tcpmem_pressure = 0;
7060 page_counter_charge(&memcg->tcpmem, nr_pages);
7061 memcg->tcpmem_pressure = 1;
7065 /* Don't block in the packet receive path */
7067 gfp_mask = GFP_NOWAIT;
7069 mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
7071 if (try_charge(memcg, gfp_mask, nr_pages) == 0)
7074 try_charge(memcg, gfp_mask|__GFP_NOFAIL, nr_pages);
7079 * mem_cgroup_uncharge_skmem - uncharge socket memory
7080 * @memcg: memcg to uncharge
7081 * @nr_pages: number of pages to uncharge
7083 void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
7085 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
7086 page_counter_uncharge(&memcg->tcpmem, nr_pages);
7090 mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
7092 refill_stock(memcg, nr_pages);
7095 static int __init cgroup_memory(char *s)
7099 while ((token = strsep(&s, ",")) != NULL) {
7102 if (!strcmp(token, "nosocket"))
7103 cgroup_memory_nosocket = true;
7104 if (!strcmp(token, "nokmem"))
7105 cgroup_memory_nokmem = true;
7109 __setup("cgroup.memory=", cgroup_memory);
7112 * subsys_initcall() for memory controller.
7114 * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
7115 * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
7116 * basically everything that doesn't depend on a specific mem_cgroup structure
7117 * should be initialized from here.
7119 static int __init mem_cgroup_init(void)
7123 cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
7124 memcg_hotplug_cpu_dead);
7126 for_each_possible_cpu(cpu)
7127 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
7130 for_each_node(node) {
7131 struct mem_cgroup_tree_per_node *rtpn;
7133 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL,
7134 node_online(node) ? node : NUMA_NO_NODE);
7136 rtpn->rb_root = RB_ROOT;
7137 rtpn->rb_rightmost = NULL;
7138 spin_lock_init(&rtpn->lock);
7139 soft_limit_tree.rb_tree_per_node[node] = rtpn;
7144 subsys_initcall(mem_cgroup_init);
7146 #ifdef CONFIG_MEMCG_SWAP
7147 static struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
7149 while (!refcount_inc_not_zero(&memcg->id.ref)) {
7151 * The root cgroup cannot be destroyed, so it's refcount must
7154 if (WARN_ON_ONCE(memcg == root_mem_cgroup)) {
7158 memcg = parent_mem_cgroup(memcg);
7160 memcg = root_mem_cgroup;
7166 * mem_cgroup_swapout - transfer a memsw charge to swap
7167 * @page: page whose memsw charge to transfer
7168 * @entry: swap entry to move the charge to
7170 * Transfer the memsw charge of @page to @entry.
7172 void mem_cgroup_swapout(struct page *page, swp_entry_t entry)
7174 struct mem_cgroup *memcg, *swap_memcg;
7175 unsigned int nr_entries;
7176 unsigned short oldid;
7178 VM_BUG_ON_PAGE(PageLRU(page), page);
7179 VM_BUG_ON_PAGE(page_count(page), page);
7181 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
7184 memcg = page_memcg(page);
7186 /* Readahead page, never charged */
7191 * In case the memcg owning these pages has been offlined and doesn't
7192 * have an ID allocated to it anymore, charge the closest online
7193 * ancestor for the swap instead and transfer the memory+swap charge.
7195 swap_memcg = mem_cgroup_id_get_online(memcg);
7196 nr_entries = thp_nr_pages(page);
7197 /* Get references for the tail pages, too */
7199 mem_cgroup_id_get_many(swap_memcg, nr_entries - 1);
7200 oldid = swap_cgroup_record(entry, mem_cgroup_id(swap_memcg),
7202 VM_BUG_ON_PAGE(oldid, page);
7203 mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries);
7205 page->memcg_data = 0;
7207 if (!mem_cgroup_is_root(memcg))
7208 page_counter_uncharge(&memcg->memory, nr_entries);
7210 if (!cgroup_memory_noswap && memcg != swap_memcg) {
7211 if (!mem_cgroup_is_root(swap_memcg))
7212 page_counter_charge(&swap_memcg->memsw, nr_entries);
7213 page_counter_uncharge(&memcg->memsw, nr_entries);
7217 * Interrupts should be disabled here because the caller holds the
7218 * i_pages lock which is taken with interrupts-off. It is
7219 * important here to have the interrupts disabled because it is the
7220 * only synchronisation we have for updating the per-CPU variables.
7222 VM_BUG_ON(!irqs_disabled());
7223 mem_cgroup_charge_statistics(memcg, page, -nr_entries);
7224 memcg_check_events(memcg, page);
7226 css_put(&memcg->css);
7230 * mem_cgroup_try_charge_swap - try charging swap space for a page
7231 * @page: page being added to swap
7232 * @entry: swap entry to charge
7234 * Try to charge @page's memcg for the swap space at @entry.
7236 * Returns 0 on success, -ENOMEM on failure.
7238 int mem_cgroup_try_charge_swap(struct page *page, swp_entry_t entry)
7240 unsigned int nr_pages = thp_nr_pages(page);
7241 struct page_counter *counter;
7242 struct mem_cgroup *memcg;
7243 unsigned short oldid;
7245 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
7248 memcg = page_memcg(page);
7250 /* Readahead page, never charged */
7255 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7259 memcg = mem_cgroup_id_get_online(memcg);
7261 if (!cgroup_memory_noswap && !mem_cgroup_is_root(memcg) &&
7262 !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
7263 memcg_memory_event(memcg, MEMCG_SWAP_MAX);
7264 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7265 mem_cgroup_id_put(memcg);
7269 /* Get references for the tail pages, too */
7271 mem_cgroup_id_get_many(memcg, nr_pages - 1);
7272 oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg), nr_pages);
7273 VM_BUG_ON_PAGE(oldid, page);
7274 mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
7280 * mem_cgroup_uncharge_swap - uncharge swap space
7281 * @entry: swap entry to uncharge
7282 * @nr_pages: the amount of swap space to uncharge
7284 void mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
7286 struct mem_cgroup *memcg;
7289 id = swap_cgroup_record(entry, 0, nr_pages);
7291 memcg = mem_cgroup_from_id(id);
7293 if (!cgroup_memory_noswap && !mem_cgroup_is_root(memcg)) {
7294 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
7295 page_counter_uncharge(&memcg->swap, nr_pages);
7297 page_counter_uncharge(&memcg->memsw, nr_pages);
7299 mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
7300 mem_cgroup_id_put_many(memcg, nr_pages);
7305 long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
7307 long nr_swap_pages = get_nr_swap_pages();
7309 if (cgroup_memory_noswap || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
7310 return nr_swap_pages;
7311 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg))
7312 nr_swap_pages = min_t(long, nr_swap_pages,
7313 READ_ONCE(memcg->swap.max) -
7314 page_counter_read(&memcg->swap));
7315 return nr_swap_pages;
7318 bool mem_cgroup_swap_full(struct page *page)
7320 struct mem_cgroup *memcg;
7322 VM_BUG_ON_PAGE(!PageLocked(page), page);
7326 if (cgroup_memory_noswap || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
7329 memcg = page_memcg(page);
7333 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg)) {
7334 unsigned long usage = page_counter_read(&memcg->swap);
7336 if (usage * 2 >= READ_ONCE(memcg->swap.high) ||
7337 usage * 2 >= READ_ONCE(memcg->swap.max))
7344 static int __init setup_swap_account(char *s)
7346 if (!strcmp(s, "1"))
7347 cgroup_memory_noswap = false;
7348 else if (!strcmp(s, "0"))
7349 cgroup_memory_noswap = true;
7352 __setup("swapaccount=", setup_swap_account);
7354 static u64 swap_current_read(struct cgroup_subsys_state *css,
7357 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7359 return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
7362 static int swap_high_show(struct seq_file *m, void *v)
7364 return seq_puts_memcg_tunable(m,
7365 READ_ONCE(mem_cgroup_from_seq(m)->swap.high));
7368 static ssize_t swap_high_write(struct kernfs_open_file *of,
7369 char *buf, size_t nbytes, loff_t off)
7371 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7375 buf = strstrip(buf);
7376 err = page_counter_memparse(buf, "max", &high);
7380 page_counter_set_high(&memcg->swap, high);
7385 static int swap_max_show(struct seq_file *m, void *v)
7387 return seq_puts_memcg_tunable(m,
7388 READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
7391 static ssize_t swap_max_write(struct kernfs_open_file *of,
7392 char *buf, size_t nbytes, loff_t off)
7394 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7398 buf = strstrip(buf);
7399 err = page_counter_memparse(buf, "max", &max);
7403 xchg(&memcg->swap.max, max);
7408 static int swap_events_show(struct seq_file *m, void *v)
7410 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
7412 seq_printf(m, "high %lu\n",
7413 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH]));
7414 seq_printf(m, "max %lu\n",
7415 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
7416 seq_printf(m, "fail %lu\n",
7417 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
7422 static struct cftype swap_files[] = {
7424 .name = "swap.current",
7425 .flags = CFTYPE_NOT_ON_ROOT,
7426 .read_u64 = swap_current_read,
7429 .name = "swap.high",
7430 .flags = CFTYPE_NOT_ON_ROOT,
7431 .seq_show = swap_high_show,
7432 .write = swap_high_write,
7436 .flags = CFTYPE_NOT_ON_ROOT,
7437 .seq_show = swap_max_show,
7438 .write = swap_max_write,
7441 .name = "swap.events",
7442 .flags = CFTYPE_NOT_ON_ROOT,
7443 .file_offset = offsetof(struct mem_cgroup, swap_events_file),
7444 .seq_show = swap_events_show,
7449 static struct cftype memsw_files[] = {
7451 .name = "memsw.usage_in_bytes",
7452 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
7453 .read_u64 = mem_cgroup_read_u64,
7456 .name = "memsw.max_usage_in_bytes",
7457 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
7458 .write = mem_cgroup_reset,
7459 .read_u64 = mem_cgroup_read_u64,
7462 .name = "memsw.limit_in_bytes",
7463 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
7464 .write = mem_cgroup_write,
7465 .read_u64 = mem_cgroup_read_u64,
7468 .name = "memsw.failcnt",
7469 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
7470 .write = mem_cgroup_reset,
7471 .read_u64 = mem_cgroup_read_u64,
7473 { }, /* terminate */
7477 * If mem_cgroup_swap_init() is implemented as a subsys_initcall()
7478 * instead of a core_initcall(), this could mean cgroup_memory_noswap still
7479 * remains set to false even when memcg is disabled via "cgroup_disable=memory"
7480 * boot parameter. This may result in premature OOPS inside
7481 * mem_cgroup_get_nr_swap_pages() function in corner cases.
7483 static int __init mem_cgroup_swap_init(void)
7485 /* No memory control -> no swap control */
7486 if (mem_cgroup_disabled())
7487 cgroup_memory_noswap = true;
7489 if (cgroup_memory_noswap)
7492 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files));
7493 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files));
7497 core_initcall(mem_cgroup_swap_init);
7499 #endif /* CONFIG_MEMCG_SWAP */