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
25 #include <linux/page_counter.h>
26 #include <linux/memcontrol.h>
27 #include <linux/cgroup.h>
28 #include <linux/pagewalk.h>
29 #include <linux/sched/mm.h>
30 #include <linux/shmem_fs.h>
31 #include <linux/hugetlb.h>
32 #include <linux/pagemap.h>
33 #include <linux/vm_event_item.h>
34 #include <linux/smp.h>
35 #include <linux/page-flags.h>
36 #include <linux/backing-dev.h>
37 #include <linux/bit_spinlock.h>
38 #include <linux/rcupdate.h>
39 #include <linux/limits.h>
40 #include <linux/export.h>
41 #include <linux/mutex.h>
42 #include <linux/rbtree.h>
43 #include <linux/slab.h>
44 #include <linux/swap.h>
45 #include <linux/swapops.h>
46 #include <linux/spinlock.h>
47 #include <linux/eventfd.h>
48 #include <linux/poll.h>
49 #include <linux/sort.h>
51 #include <linux/seq_file.h>
52 #include <linux/vmpressure.h>
53 #include <linux/mm_inline.h>
54 #include <linux/swap_cgroup.h>
55 #include <linux/cpu.h>
56 #include <linux/oom.h>
57 #include <linux/lockdep.h>
58 #include <linux/file.h>
59 #include <linux/tracehook.h>
60 #include <linux/psi.h>
61 #include <linux/seq_buf.h>
67 #include <linux/uaccess.h>
69 #include <trace/events/vmscan.h>
71 struct cgroup_subsys memory_cgrp_subsys __read_mostly;
72 EXPORT_SYMBOL(memory_cgrp_subsys);
74 struct mem_cgroup *root_mem_cgroup __read_mostly;
76 /* Active memory cgroup to use from an interrupt context */
77 DEFINE_PER_CPU(struct mem_cgroup *, int_active_memcg);
79 /* Socket memory accounting disabled? */
80 static bool cgroup_memory_nosocket;
82 /* Kernel memory accounting disabled? */
83 static bool cgroup_memory_nokmem;
85 /* Whether the swap controller is active */
86 #ifdef CONFIG_MEMCG_SWAP
87 bool cgroup_memory_noswap __read_mostly;
89 #define cgroup_memory_noswap 1
92 #ifdef CONFIG_CGROUP_WRITEBACK
93 static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq);
96 /* Whether legacy memory+swap accounting is active */
97 static bool do_memsw_account(void)
99 return !cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_noswap;
102 #define THRESHOLDS_EVENTS_TARGET 128
103 #define SOFTLIMIT_EVENTS_TARGET 1024
106 * Cgroups above their limits are maintained in a RB-Tree, independent of
107 * their hierarchy representation
110 struct mem_cgroup_tree_per_node {
111 struct rb_root rb_root;
112 struct rb_node *rb_rightmost;
116 struct mem_cgroup_tree {
117 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
120 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
123 struct mem_cgroup_eventfd_list {
124 struct list_head list;
125 struct eventfd_ctx *eventfd;
129 * cgroup_event represents events which userspace want to receive.
131 struct mem_cgroup_event {
133 * memcg which the event belongs to.
135 struct mem_cgroup *memcg;
137 * eventfd to signal userspace about the event.
139 struct eventfd_ctx *eventfd;
141 * Each of these stored in a list by the cgroup.
143 struct list_head list;
145 * register_event() callback will be used to add new userspace
146 * waiter for changes related to this event. Use eventfd_signal()
147 * on eventfd to send notification to userspace.
149 int (*register_event)(struct mem_cgroup *memcg,
150 struct eventfd_ctx *eventfd, const char *args);
152 * unregister_event() callback will be called when userspace closes
153 * the eventfd or on cgroup removing. This callback must be set,
154 * if you want provide notification functionality.
156 void (*unregister_event)(struct mem_cgroup *memcg,
157 struct eventfd_ctx *eventfd);
159 * All fields below needed to unregister event when
160 * userspace closes eventfd.
163 wait_queue_head_t *wqh;
164 wait_queue_entry_t wait;
165 struct work_struct remove;
168 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
169 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
171 /* Stuffs for move charges at task migration. */
173 * Types of charges to be moved.
175 #define MOVE_ANON 0x1U
176 #define MOVE_FILE 0x2U
177 #define MOVE_MASK (MOVE_ANON | MOVE_FILE)
179 /* "mc" and its members are protected by cgroup_mutex */
180 static struct move_charge_struct {
181 spinlock_t lock; /* for from, to */
182 struct mm_struct *mm;
183 struct mem_cgroup *from;
184 struct mem_cgroup *to;
186 unsigned long precharge;
187 unsigned long moved_charge;
188 unsigned long moved_swap;
189 struct task_struct *moving_task; /* a task moving charges */
190 wait_queue_head_t waitq; /* a waitq for other context */
192 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
193 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
197 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
198 * limit reclaim to prevent infinite loops, if they ever occur.
200 #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
201 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
203 /* for encoding cft->private value on file */
212 #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
213 #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
214 #define MEMFILE_ATTR(val) ((val) & 0xffff)
215 /* Used for OOM nofiier */
216 #define OOM_CONTROL (0)
219 * Iteration constructs for visiting all cgroups (under a tree). If
220 * loops are exited prematurely (break), mem_cgroup_iter_break() must
221 * be used for reference counting.
223 #define for_each_mem_cgroup_tree(iter, root) \
224 for (iter = mem_cgroup_iter(root, NULL, NULL); \
226 iter = mem_cgroup_iter(root, iter, NULL))
228 #define for_each_mem_cgroup(iter) \
229 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
231 iter = mem_cgroup_iter(NULL, iter, NULL))
233 static inline bool should_force_charge(void)
235 return tsk_is_oom_victim(current) || fatal_signal_pending(current) ||
236 (current->flags & PF_EXITING);
239 /* Some nice accessors for the vmpressure. */
240 struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
243 memcg = root_mem_cgroup;
244 return &memcg->vmpressure;
247 struct cgroup_subsys_state *vmpressure_to_css(struct vmpressure *vmpr)
249 return &container_of(vmpr, struct mem_cgroup, vmpressure)->css;
252 #ifdef CONFIG_MEMCG_KMEM
253 extern spinlock_t css_set_lock;
255 static void obj_cgroup_release(struct percpu_ref *ref)
257 struct obj_cgroup *objcg = container_of(ref, struct obj_cgroup, refcnt);
258 struct mem_cgroup *memcg;
259 unsigned int nr_bytes;
260 unsigned int nr_pages;
264 * At this point all allocated objects are freed, and
265 * objcg->nr_charged_bytes can't have an arbitrary byte value.
266 * However, it can be PAGE_SIZE or (x * PAGE_SIZE).
268 * The following sequence can lead to it:
269 * 1) CPU0: objcg == stock->cached_objcg
270 * 2) CPU1: we do a small allocation (e.g. 92 bytes),
271 * PAGE_SIZE bytes are charged
272 * 3) CPU1: a process from another memcg is allocating something,
273 * the stock if flushed,
274 * objcg->nr_charged_bytes = PAGE_SIZE - 92
275 * 5) CPU0: we do release this object,
276 * 92 bytes are added to stock->nr_bytes
277 * 6) CPU0: stock is flushed,
278 * 92 bytes are added to objcg->nr_charged_bytes
280 * In the result, nr_charged_bytes == PAGE_SIZE.
281 * This page will be uncharged in obj_cgroup_release().
283 nr_bytes = atomic_read(&objcg->nr_charged_bytes);
284 WARN_ON_ONCE(nr_bytes & (PAGE_SIZE - 1));
285 nr_pages = nr_bytes >> PAGE_SHIFT;
287 spin_lock_irqsave(&css_set_lock, flags);
288 memcg = obj_cgroup_memcg(objcg);
290 __memcg_kmem_uncharge(memcg, nr_pages);
291 list_del(&objcg->list);
292 mem_cgroup_put(memcg);
293 spin_unlock_irqrestore(&css_set_lock, flags);
295 percpu_ref_exit(ref);
296 kfree_rcu(objcg, rcu);
299 static struct obj_cgroup *obj_cgroup_alloc(void)
301 struct obj_cgroup *objcg;
304 objcg = kzalloc(sizeof(struct obj_cgroup), GFP_KERNEL);
308 ret = percpu_ref_init(&objcg->refcnt, obj_cgroup_release, 0,
314 INIT_LIST_HEAD(&objcg->list);
318 static void memcg_reparent_objcgs(struct mem_cgroup *memcg,
319 struct mem_cgroup *parent)
321 struct obj_cgroup *objcg, *iter;
323 objcg = rcu_replace_pointer(memcg->objcg, NULL, true);
325 spin_lock_irq(&css_set_lock);
327 /* Move active objcg to the parent's list */
328 xchg(&objcg->memcg, parent);
329 css_get(&parent->css);
330 list_add(&objcg->list, &parent->objcg_list);
332 /* Move already reparented objcgs to the parent's list */
333 list_for_each_entry(iter, &memcg->objcg_list, list) {
334 css_get(&parent->css);
335 xchg(&iter->memcg, parent);
336 css_put(&memcg->css);
338 list_splice(&memcg->objcg_list, &parent->objcg_list);
340 spin_unlock_irq(&css_set_lock);
342 percpu_ref_kill(&objcg->refcnt);
346 * This will be used as a shrinker list's index.
347 * The main reason for not using cgroup id for this:
348 * this works better in sparse environments, where we have a lot of memcgs,
349 * but only a few kmem-limited. Or also, if we have, for instance, 200
350 * memcgs, and none but the 200th is kmem-limited, we'd have to have a
351 * 200 entry array for that.
353 * The current size of the caches array is stored in memcg_nr_cache_ids. It
354 * will double each time we have to increase it.
356 static DEFINE_IDA(memcg_cache_ida);
357 int memcg_nr_cache_ids;
359 /* Protects memcg_nr_cache_ids */
360 static DECLARE_RWSEM(memcg_cache_ids_sem);
362 void memcg_get_cache_ids(void)
364 down_read(&memcg_cache_ids_sem);
367 void memcg_put_cache_ids(void)
369 up_read(&memcg_cache_ids_sem);
373 * MIN_SIZE is different than 1, because we would like to avoid going through
374 * the alloc/free process all the time. In a small machine, 4 kmem-limited
375 * cgroups is a reasonable guess. In the future, it could be a parameter or
376 * tunable, but that is strictly not necessary.
378 * MAX_SIZE should be as large as the number of cgrp_ids. Ideally, we could get
379 * this constant directly from cgroup, but it is understandable that this is
380 * better kept as an internal representation in cgroup.c. In any case, the
381 * cgrp_id space is not getting any smaller, and we don't have to necessarily
382 * increase ours as well if it increases.
384 #define MEMCG_CACHES_MIN_SIZE 4
385 #define MEMCG_CACHES_MAX_SIZE MEM_CGROUP_ID_MAX
388 * A lot of the calls to the cache allocation functions are expected to be
389 * inlined by the compiler. Since the calls to memcg_slab_pre_alloc_hook() are
390 * conditional to this static branch, we'll have to allow modules that does
391 * kmem_cache_alloc and the such to see this symbol as well
393 DEFINE_STATIC_KEY_FALSE(memcg_kmem_enabled_key);
394 EXPORT_SYMBOL(memcg_kmem_enabled_key);
397 static int memcg_shrinker_map_size;
398 static DEFINE_MUTEX(memcg_shrinker_map_mutex);
400 static void memcg_free_shrinker_map_rcu(struct rcu_head *head)
402 kvfree(container_of(head, struct memcg_shrinker_map, rcu));
405 static int memcg_expand_one_shrinker_map(struct mem_cgroup *memcg,
406 int size, int old_size)
408 struct memcg_shrinker_map *new, *old;
411 lockdep_assert_held(&memcg_shrinker_map_mutex);
414 old = rcu_dereference_protected(
415 mem_cgroup_nodeinfo(memcg, nid)->shrinker_map, true);
416 /* Not yet online memcg */
420 new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
424 /* Set all old bits, clear all new bits */
425 memset(new->map, (int)0xff, old_size);
426 memset((void *)new->map + old_size, 0, size - old_size);
428 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_map, new);
429 call_rcu(&old->rcu, memcg_free_shrinker_map_rcu);
435 static void memcg_free_shrinker_maps(struct mem_cgroup *memcg)
437 struct mem_cgroup_per_node *pn;
438 struct memcg_shrinker_map *map;
441 if (mem_cgroup_is_root(memcg))
445 pn = mem_cgroup_nodeinfo(memcg, nid);
446 map = rcu_dereference_protected(pn->shrinker_map, true);
449 rcu_assign_pointer(pn->shrinker_map, NULL);
453 static int memcg_alloc_shrinker_maps(struct mem_cgroup *memcg)
455 struct memcg_shrinker_map *map;
456 int nid, size, ret = 0;
458 if (mem_cgroup_is_root(memcg))
461 mutex_lock(&memcg_shrinker_map_mutex);
462 size = memcg_shrinker_map_size;
464 map = kvzalloc_node(sizeof(*map) + size, GFP_KERNEL, nid);
466 memcg_free_shrinker_maps(memcg);
470 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_map, map);
472 mutex_unlock(&memcg_shrinker_map_mutex);
477 int memcg_expand_shrinker_maps(int new_id)
479 int size, old_size, ret = 0;
480 struct mem_cgroup *memcg;
482 size = DIV_ROUND_UP(new_id + 1, BITS_PER_LONG) * sizeof(unsigned long);
483 old_size = memcg_shrinker_map_size;
484 if (size <= old_size)
487 mutex_lock(&memcg_shrinker_map_mutex);
488 if (!root_mem_cgroup)
491 for_each_mem_cgroup(memcg) {
492 if (mem_cgroup_is_root(memcg))
494 ret = memcg_expand_one_shrinker_map(memcg, size, old_size);
496 mem_cgroup_iter_break(NULL, memcg);
502 memcg_shrinker_map_size = size;
503 mutex_unlock(&memcg_shrinker_map_mutex);
507 void memcg_set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
509 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
510 struct memcg_shrinker_map *map;
513 map = rcu_dereference(memcg->nodeinfo[nid]->shrinker_map);
514 /* Pairs with smp mb in shrink_slab() */
515 smp_mb__before_atomic();
516 set_bit(shrinker_id, map->map);
522 * mem_cgroup_css_from_page - css of the memcg associated with a page
523 * @page: page of interest
525 * If memcg is bound to the default hierarchy, css of the memcg associated
526 * with @page is returned. The returned css remains associated with @page
527 * until it is released.
529 * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
532 struct cgroup_subsys_state *mem_cgroup_css_from_page(struct page *page)
534 struct mem_cgroup *memcg;
536 memcg = page_memcg(page);
538 if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
539 memcg = root_mem_cgroup;
545 * page_cgroup_ino - return inode number of the memcg a page is charged to
548 * Look up the closest online ancestor of the memory cgroup @page is charged to
549 * and return its inode number or 0 if @page is not charged to any cgroup. It
550 * is safe to call this function without holding a reference to @page.
552 * Note, this function is inherently racy, because there is nothing to prevent
553 * the cgroup inode from getting torn down and potentially reallocated a moment
554 * after page_cgroup_ino() returns, so it only should be used by callers that
555 * do not care (such as procfs interfaces).
557 ino_t page_cgroup_ino(struct page *page)
559 struct mem_cgroup *memcg;
560 unsigned long ino = 0;
563 memcg = page_memcg_check(page);
565 while (memcg && !(memcg->css.flags & CSS_ONLINE))
566 memcg = parent_mem_cgroup(memcg);
568 ino = cgroup_ino(memcg->css.cgroup);
573 static struct mem_cgroup_per_node *
574 mem_cgroup_page_nodeinfo(struct mem_cgroup *memcg, struct page *page)
576 int nid = page_to_nid(page);
578 return memcg->nodeinfo[nid];
581 static struct mem_cgroup_tree_per_node *
582 soft_limit_tree_node(int nid)
584 return soft_limit_tree.rb_tree_per_node[nid];
587 static struct mem_cgroup_tree_per_node *
588 soft_limit_tree_from_page(struct page *page)
590 int nid = page_to_nid(page);
592 return soft_limit_tree.rb_tree_per_node[nid];
595 static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_node *mz,
596 struct mem_cgroup_tree_per_node *mctz,
597 unsigned long new_usage_in_excess)
599 struct rb_node **p = &mctz->rb_root.rb_node;
600 struct rb_node *parent = NULL;
601 struct mem_cgroup_per_node *mz_node;
602 bool rightmost = true;
607 mz->usage_in_excess = new_usage_in_excess;
608 if (!mz->usage_in_excess)
612 mz_node = rb_entry(parent, struct mem_cgroup_per_node,
614 if (mz->usage_in_excess < mz_node->usage_in_excess) {
620 * We can't avoid mem cgroups that are over their soft
621 * limit by the same amount
623 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
628 mctz->rb_rightmost = &mz->tree_node;
630 rb_link_node(&mz->tree_node, parent, p);
631 rb_insert_color(&mz->tree_node, &mctz->rb_root);
635 static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
636 struct mem_cgroup_tree_per_node *mctz)
641 if (&mz->tree_node == mctz->rb_rightmost)
642 mctz->rb_rightmost = rb_prev(&mz->tree_node);
644 rb_erase(&mz->tree_node, &mctz->rb_root);
648 static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
649 struct mem_cgroup_tree_per_node *mctz)
653 spin_lock_irqsave(&mctz->lock, flags);
654 __mem_cgroup_remove_exceeded(mz, mctz);
655 spin_unlock_irqrestore(&mctz->lock, flags);
658 static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
660 unsigned long nr_pages = page_counter_read(&memcg->memory);
661 unsigned long soft_limit = READ_ONCE(memcg->soft_limit);
662 unsigned long excess = 0;
664 if (nr_pages > soft_limit)
665 excess = nr_pages - soft_limit;
670 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
672 unsigned long excess;
673 struct mem_cgroup_per_node *mz;
674 struct mem_cgroup_tree_per_node *mctz;
676 mctz = soft_limit_tree_from_page(page);
680 * Necessary to update all ancestors when hierarchy is used.
681 * because their event counter is not touched.
683 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
684 mz = mem_cgroup_page_nodeinfo(memcg, page);
685 excess = soft_limit_excess(memcg);
687 * We have to update the tree if mz is on RB-tree or
688 * mem is over its softlimit.
690 if (excess || mz->on_tree) {
693 spin_lock_irqsave(&mctz->lock, flags);
694 /* if on-tree, remove it */
696 __mem_cgroup_remove_exceeded(mz, mctz);
698 * Insert again. mz->usage_in_excess will be updated.
699 * If excess is 0, no tree ops.
701 __mem_cgroup_insert_exceeded(mz, mctz, excess);
702 spin_unlock_irqrestore(&mctz->lock, flags);
707 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
709 struct mem_cgroup_tree_per_node *mctz;
710 struct mem_cgroup_per_node *mz;
714 mz = mem_cgroup_nodeinfo(memcg, nid);
715 mctz = soft_limit_tree_node(nid);
717 mem_cgroup_remove_exceeded(mz, mctz);
721 static struct mem_cgroup_per_node *
722 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
724 struct mem_cgroup_per_node *mz;
728 if (!mctz->rb_rightmost)
729 goto done; /* Nothing to reclaim from */
731 mz = rb_entry(mctz->rb_rightmost,
732 struct mem_cgroup_per_node, tree_node);
734 * Remove the node now but someone else can add it back,
735 * we will to add it back at the end of reclaim to its correct
736 * position in the tree.
738 __mem_cgroup_remove_exceeded(mz, mctz);
739 if (!soft_limit_excess(mz->memcg) ||
740 !css_tryget(&mz->memcg->css))
746 static struct mem_cgroup_per_node *
747 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
749 struct mem_cgroup_per_node *mz;
751 spin_lock_irq(&mctz->lock);
752 mz = __mem_cgroup_largest_soft_limit_node(mctz);
753 spin_unlock_irq(&mctz->lock);
758 * __mod_memcg_state - update cgroup memory statistics
759 * @memcg: the memory cgroup
760 * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item
761 * @val: delta to add to the counter, can be negative
763 void __mod_memcg_state(struct mem_cgroup *memcg, int idx, int val)
765 long x, threshold = MEMCG_CHARGE_BATCH;
767 if (mem_cgroup_disabled())
770 if (memcg_stat_item_in_bytes(idx))
771 threshold <<= PAGE_SHIFT;
773 x = val + __this_cpu_read(memcg->vmstats_percpu->stat[idx]);
774 if (unlikely(abs(x) > threshold)) {
775 struct mem_cgroup *mi;
778 * Batch local counters to keep them in sync with
779 * the hierarchical ones.
781 __this_cpu_add(memcg->vmstats_local->stat[idx], x);
782 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
783 atomic_long_add(x, &mi->vmstats[idx]);
786 __this_cpu_write(memcg->vmstats_percpu->stat[idx], x);
789 static struct mem_cgroup_per_node *
790 parent_nodeinfo(struct mem_cgroup_per_node *pn, int nid)
792 struct mem_cgroup *parent;
794 parent = parent_mem_cgroup(pn->memcg);
797 return mem_cgroup_nodeinfo(parent, nid);
800 void __mod_memcg_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
803 struct mem_cgroup_per_node *pn;
804 struct mem_cgroup *memcg;
805 long x, threshold = MEMCG_CHARGE_BATCH;
807 pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
811 __mod_memcg_state(memcg, idx, val);
814 __this_cpu_add(pn->lruvec_stat_local->count[idx], val);
816 if (vmstat_item_in_bytes(idx))
817 threshold <<= PAGE_SHIFT;
819 x = val + __this_cpu_read(pn->lruvec_stat_cpu->count[idx]);
820 if (unlikely(abs(x) > threshold)) {
821 pg_data_t *pgdat = lruvec_pgdat(lruvec);
822 struct mem_cgroup_per_node *pi;
824 for (pi = pn; pi; pi = parent_nodeinfo(pi, pgdat->node_id))
825 atomic_long_add(x, &pi->lruvec_stat[idx]);
828 __this_cpu_write(pn->lruvec_stat_cpu->count[idx], x);
832 * __mod_lruvec_state - update lruvec memory statistics
833 * @lruvec: the lruvec
834 * @idx: the stat item
835 * @val: delta to add to the counter, can be negative
837 * The lruvec is the intersection of the NUMA node and a cgroup. This
838 * function updates the all three counters that are affected by a
839 * change of state at this level: per-node, per-cgroup, per-lruvec.
841 void __mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
845 __mod_node_page_state(lruvec_pgdat(lruvec), idx, val);
847 /* Update memcg and lruvec */
848 if (!mem_cgroup_disabled())
849 __mod_memcg_lruvec_state(lruvec, idx, val);
852 void __mod_lruvec_slab_state(void *p, enum node_stat_item idx, int val)
854 pg_data_t *pgdat = page_pgdat(virt_to_page(p));
855 struct mem_cgroup *memcg;
856 struct lruvec *lruvec;
859 memcg = mem_cgroup_from_obj(p);
862 * Untracked pages have no memcg, no lruvec. Update only the
863 * node. If we reparent the slab objects to the root memcg,
864 * when we free the slab object, we need to update the per-memcg
865 * vmstats to keep it correct for the root memcg.
868 __mod_node_page_state(pgdat, idx, val);
870 lruvec = mem_cgroup_lruvec(memcg, pgdat);
871 __mod_lruvec_state(lruvec, idx, val);
876 void mod_memcg_obj_state(void *p, int idx, int val)
878 struct mem_cgroup *memcg;
881 memcg = mem_cgroup_from_obj(p);
883 mod_memcg_state(memcg, idx, val);
888 * __count_memcg_events - account VM events in a cgroup
889 * @memcg: the memory cgroup
890 * @idx: the event item
891 * @count: the number of events that occured
893 void __count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx,
898 if (mem_cgroup_disabled())
901 x = count + __this_cpu_read(memcg->vmstats_percpu->events[idx]);
902 if (unlikely(x > MEMCG_CHARGE_BATCH)) {
903 struct mem_cgroup *mi;
906 * Batch local counters to keep them in sync with
907 * the hierarchical ones.
909 __this_cpu_add(memcg->vmstats_local->events[idx], x);
910 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
911 atomic_long_add(x, &mi->vmevents[idx]);
914 __this_cpu_write(memcg->vmstats_percpu->events[idx], x);
917 static unsigned long memcg_events(struct mem_cgroup *memcg, int event)
919 return atomic_long_read(&memcg->vmevents[event]);
922 static unsigned long memcg_events_local(struct mem_cgroup *memcg, int event)
927 for_each_possible_cpu(cpu)
928 x += per_cpu(memcg->vmstats_local->events[event], cpu);
932 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
936 /* pagein of a big page is an event. So, ignore page size */
938 __count_memcg_events(memcg, PGPGIN, 1);
940 __count_memcg_events(memcg, PGPGOUT, 1);
941 nr_pages = -nr_pages; /* for event */
944 __this_cpu_add(memcg->vmstats_percpu->nr_page_events, nr_pages);
947 static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
948 enum mem_cgroup_events_target target)
950 unsigned long val, next;
952 val = __this_cpu_read(memcg->vmstats_percpu->nr_page_events);
953 next = __this_cpu_read(memcg->vmstats_percpu->targets[target]);
954 /* from time_after() in jiffies.h */
955 if ((long)(next - val) < 0) {
957 case MEM_CGROUP_TARGET_THRESH:
958 next = val + THRESHOLDS_EVENTS_TARGET;
960 case MEM_CGROUP_TARGET_SOFTLIMIT:
961 next = val + SOFTLIMIT_EVENTS_TARGET;
966 __this_cpu_write(memcg->vmstats_percpu->targets[target], next);
973 * Check events in order.
976 static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
978 /* threshold event is triggered in finer grain than soft limit */
979 if (unlikely(mem_cgroup_event_ratelimit(memcg,
980 MEM_CGROUP_TARGET_THRESH))) {
983 do_softlimit = mem_cgroup_event_ratelimit(memcg,
984 MEM_CGROUP_TARGET_SOFTLIMIT);
985 mem_cgroup_threshold(memcg);
986 if (unlikely(do_softlimit))
987 mem_cgroup_update_tree(memcg, page);
991 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
994 * mm_update_next_owner() may clear mm->owner to NULL
995 * if it races with swapoff, page migration, etc.
996 * So this can be called with p == NULL.
1001 return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
1003 EXPORT_SYMBOL(mem_cgroup_from_task);
1006 * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
1007 * @mm: mm from which memcg should be extracted. It can be NULL.
1009 * Obtain a reference on mm->memcg and returns it if successful. Otherwise
1010 * root_mem_cgroup is returned. However if mem_cgroup is disabled, NULL is
1013 struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
1015 struct mem_cgroup *memcg;
1017 if (mem_cgroup_disabled())
1023 * Page cache insertions can happen withou an
1024 * actual mm context, e.g. during disk probing
1025 * on boot, loopback IO, acct() writes etc.
1028 memcg = root_mem_cgroup;
1030 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1031 if (unlikely(!memcg))
1032 memcg = root_mem_cgroup;
1034 } while (!css_tryget(&memcg->css));
1038 EXPORT_SYMBOL(get_mem_cgroup_from_mm);
1041 * get_mem_cgroup_from_page: Obtain a reference on given page's memcg.
1042 * @page: page from which memcg should be extracted.
1044 * Obtain a reference on page->memcg and returns it if successful. Otherwise
1045 * root_mem_cgroup is returned.
1047 struct mem_cgroup *get_mem_cgroup_from_page(struct page *page)
1049 struct mem_cgroup *memcg = page_memcg(page);
1051 if (mem_cgroup_disabled())
1055 /* Page should not get uncharged and freed memcg under us. */
1056 if (!memcg || WARN_ON_ONCE(!css_tryget(&memcg->css)))
1057 memcg = root_mem_cgroup;
1061 EXPORT_SYMBOL(get_mem_cgroup_from_page);
1063 static __always_inline struct mem_cgroup *active_memcg(void)
1066 return this_cpu_read(int_active_memcg);
1068 return current->active_memcg;
1071 static __always_inline struct mem_cgroup *get_active_memcg(void)
1073 struct mem_cgroup *memcg;
1076 memcg = active_memcg();
1078 /* current->active_memcg must hold a ref. */
1079 if (WARN_ON_ONCE(!css_tryget(&memcg->css)))
1080 memcg = root_mem_cgroup;
1082 memcg = current->active_memcg;
1089 static __always_inline bool memcg_kmem_bypass(void)
1091 /* Allow remote memcg charging from any context. */
1092 if (unlikely(active_memcg()))
1095 /* Memcg to charge can't be determined. */
1096 if (in_interrupt() || !current->mm || (current->flags & PF_KTHREAD))
1103 * If active memcg is set, do not fallback to current->mm->memcg.
1105 static __always_inline struct mem_cgroup *get_mem_cgroup_from_current(void)
1107 if (memcg_kmem_bypass())
1110 if (unlikely(active_memcg()))
1111 return get_active_memcg();
1113 return get_mem_cgroup_from_mm(current->mm);
1117 * mem_cgroup_iter - iterate over memory cgroup hierarchy
1118 * @root: hierarchy root
1119 * @prev: previously returned memcg, NULL on first invocation
1120 * @reclaim: cookie for shared reclaim walks, NULL for full walks
1122 * Returns references to children of the hierarchy below @root, or
1123 * @root itself, or %NULL after a full round-trip.
1125 * Caller must pass the return value in @prev on subsequent
1126 * invocations for reference counting, or use mem_cgroup_iter_break()
1127 * to cancel a hierarchy walk before the round-trip is complete.
1129 * Reclaimers can specify a node in @reclaim to divide up the memcgs
1130 * in the hierarchy among all concurrent reclaimers operating on the
1133 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
1134 struct mem_cgroup *prev,
1135 struct mem_cgroup_reclaim_cookie *reclaim)
1137 struct mem_cgroup_reclaim_iter *iter;
1138 struct cgroup_subsys_state *css = NULL;
1139 struct mem_cgroup *memcg = NULL;
1140 struct mem_cgroup *pos = NULL;
1142 if (mem_cgroup_disabled())
1146 root = root_mem_cgroup;
1148 if (prev && !reclaim)
1151 if (!root->use_hierarchy && root != root_mem_cgroup) {
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;
1237 if (prev && prev != root)
1238 css_put(&prev->css);
1244 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1245 * @root: hierarchy root
1246 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1248 void mem_cgroup_iter_break(struct mem_cgroup *root,
1249 struct mem_cgroup *prev)
1252 root = root_mem_cgroup;
1253 if (prev && prev != root)
1254 css_put(&prev->css);
1257 static void __invalidate_reclaim_iterators(struct mem_cgroup *from,
1258 struct mem_cgroup *dead_memcg)
1260 struct mem_cgroup_reclaim_iter *iter;
1261 struct mem_cgroup_per_node *mz;
1264 for_each_node(nid) {
1265 mz = mem_cgroup_nodeinfo(from, nid);
1267 cmpxchg(&iter->position, dead_memcg, NULL);
1271 static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
1273 struct mem_cgroup *memcg = dead_memcg;
1274 struct mem_cgroup *last;
1277 __invalidate_reclaim_iterators(memcg, dead_memcg);
1279 } while ((memcg = parent_mem_cgroup(memcg)));
1282 * When cgruop1 non-hierarchy mode is used,
1283 * parent_mem_cgroup() does not walk all the way up to the
1284 * cgroup root (root_mem_cgroup). So we have to handle
1285 * dead_memcg from cgroup root separately.
1287 if (last != root_mem_cgroup)
1288 __invalidate_reclaim_iterators(root_mem_cgroup,
1293 * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
1294 * @memcg: hierarchy root
1295 * @fn: function to call for each task
1296 * @arg: argument passed to @fn
1298 * This function iterates over tasks attached to @memcg or to any of its
1299 * descendants and calls @fn for each task. If @fn returns a non-zero
1300 * value, the function breaks the iteration loop and returns the value.
1301 * Otherwise, it will iterate over all tasks and return 0.
1303 * This function must not be called for the root memory cgroup.
1305 int mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
1306 int (*fn)(struct task_struct *, void *), void *arg)
1308 struct mem_cgroup *iter;
1311 BUG_ON(memcg == root_mem_cgroup);
1313 for_each_mem_cgroup_tree(iter, memcg) {
1314 struct css_task_iter it;
1315 struct task_struct *task;
1317 css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it);
1318 while (!ret && (task = css_task_iter_next(&it)))
1319 ret = fn(task, arg);
1320 css_task_iter_end(&it);
1322 mem_cgroup_iter_break(memcg, iter);
1330 * mem_cgroup_page_lruvec - return lruvec for isolating/putting an LRU page
1332 * @pgdat: pgdat of the page
1334 * This function relies on page->mem_cgroup being stable - see the
1335 * access rules in commit_charge().
1337 struct lruvec *mem_cgroup_page_lruvec(struct page *page, struct pglist_data *pgdat)
1339 struct mem_cgroup_per_node *mz;
1340 struct mem_cgroup *memcg;
1341 struct lruvec *lruvec;
1343 if (mem_cgroup_disabled()) {
1344 lruvec = &pgdat->__lruvec;
1348 memcg = page_memcg(page);
1350 * Swapcache readahead pages are added to the LRU - and
1351 * possibly migrated - before they are charged.
1354 memcg = root_mem_cgroup;
1356 mz = mem_cgroup_page_nodeinfo(memcg, page);
1357 lruvec = &mz->lruvec;
1360 * Since a node can be onlined after the mem_cgroup was created,
1361 * we have to be prepared to initialize lruvec->zone here;
1362 * and if offlined then reonlined, we need to reinitialize it.
1364 if (unlikely(lruvec->pgdat != pgdat))
1365 lruvec->pgdat = pgdat;
1370 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1371 * @lruvec: mem_cgroup per zone lru vector
1372 * @lru: index of lru list the page is sitting on
1373 * @zid: zone id of the accounted pages
1374 * @nr_pages: positive when adding or negative when removing
1376 * This function must be called under lru_lock, just before a page is added
1377 * to or just after a page is removed from an lru list (that ordering being
1378 * so as to allow it to check that lru_size 0 is consistent with list_empty).
1380 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1381 int zid, int nr_pages)
1383 struct mem_cgroup_per_node *mz;
1384 unsigned long *lru_size;
1387 if (mem_cgroup_disabled())
1390 mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
1391 lru_size = &mz->lru_zone_size[zid][lru];
1394 *lru_size += nr_pages;
1397 if (WARN_ONCE(size < 0,
1398 "%s(%p, %d, %d): lru_size %ld\n",
1399 __func__, lruvec, lru, nr_pages, size)) {
1405 *lru_size += nr_pages;
1409 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1410 * @memcg: the memory cgroup
1412 * Returns the maximum amount of memory @mem can be charged with, in
1415 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1417 unsigned long margin = 0;
1418 unsigned long count;
1419 unsigned long limit;
1421 count = page_counter_read(&memcg->memory);
1422 limit = READ_ONCE(memcg->memory.max);
1424 margin = limit - count;
1426 if (do_memsw_account()) {
1427 count = page_counter_read(&memcg->memsw);
1428 limit = READ_ONCE(memcg->memsw.max);
1430 margin = min(margin, limit - count);
1439 * A routine for checking "mem" is under move_account() or not.
1441 * Checking a cgroup is mc.from or mc.to or under hierarchy of
1442 * moving cgroups. This is for waiting at high-memory pressure
1445 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1447 struct mem_cgroup *from;
1448 struct mem_cgroup *to;
1451 * Unlike task_move routines, we access mc.to, mc.from not under
1452 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1454 spin_lock(&mc.lock);
1460 ret = mem_cgroup_is_descendant(from, memcg) ||
1461 mem_cgroup_is_descendant(to, memcg);
1463 spin_unlock(&mc.lock);
1467 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1469 if (mc.moving_task && current != mc.moving_task) {
1470 if (mem_cgroup_under_move(memcg)) {
1472 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1473 /* moving charge context might have finished. */
1476 finish_wait(&mc.waitq, &wait);
1483 struct memory_stat {
1489 static struct memory_stat memory_stats[] = {
1490 { "anon", PAGE_SIZE, NR_ANON_MAPPED },
1491 { "file", PAGE_SIZE, NR_FILE_PAGES },
1492 { "kernel_stack", 1024, NR_KERNEL_STACK_KB },
1493 { "percpu", 1, MEMCG_PERCPU_B },
1494 { "sock", PAGE_SIZE, MEMCG_SOCK },
1495 { "shmem", PAGE_SIZE, NR_SHMEM },
1496 { "file_mapped", PAGE_SIZE, NR_FILE_MAPPED },
1497 { "file_dirty", PAGE_SIZE, NR_FILE_DIRTY },
1498 { "file_writeback", PAGE_SIZE, NR_WRITEBACK },
1499 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1501 * The ratio will be initialized in memory_stats_init(). Because
1502 * on some architectures, the macro of HPAGE_PMD_SIZE is not
1503 * constant(e.g. powerpc).
1505 { "anon_thp", 0, NR_ANON_THPS },
1507 { "inactive_anon", PAGE_SIZE, NR_INACTIVE_ANON },
1508 { "active_anon", PAGE_SIZE, NR_ACTIVE_ANON },
1509 { "inactive_file", PAGE_SIZE, NR_INACTIVE_FILE },
1510 { "active_file", PAGE_SIZE, NR_ACTIVE_FILE },
1511 { "unevictable", PAGE_SIZE, NR_UNEVICTABLE },
1514 * Note: The slab_reclaimable and slab_unreclaimable must be
1515 * together and slab_reclaimable must be in front.
1517 { "slab_reclaimable", 1, NR_SLAB_RECLAIMABLE_B },
1518 { "slab_unreclaimable", 1, NR_SLAB_UNRECLAIMABLE_B },
1520 /* The memory events */
1521 { "workingset_refault_anon", 1, WORKINGSET_REFAULT_ANON },
1522 { "workingset_refault_file", 1, WORKINGSET_REFAULT_FILE },
1523 { "workingset_activate_anon", 1, WORKINGSET_ACTIVATE_ANON },
1524 { "workingset_activate_file", 1, WORKINGSET_ACTIVATE_FILE },
1525 { "workingset_restore_anon", 1, WORKINGSET_RESTORE_ANON },
1526 { "workingset_restore_file", 1, WORKINGSET_RESTORE_FILE },
1527 { "workingset_nodereclaim", 1, WORKINGSET_NODERECLAIM },
1530 static int __init memory_stats_init(void)
1534 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
1535 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1536 if (memory_stats[i].idx == NR_ANON_THPS)
1537 memory_stats[i].ratio = HPAGE_PMD_SIZE;
1539 VM_BUG_ON(!memory_stats[i].ratio);
1540 VM_BUG_ON(memory_stats[i].idx >= MEMCG_NR_STAT);
1545 pure_initcall(memory_stats_init);
1547 static char *memory_stat_format(struct mem_cgroup *memcg)
1552 seq_buf_init(&s, kmalloc(PAGE_SIZE, GFP_KERNEL), PAGE_SIZE);
1557 * Provide statistics on the state of the memory subsystem as
1558 * well as cumulative event counters that show past behavior.
1560 * This list is ordered following a combination of these gradients:
1561 * 1) generic big picture -> specifics and details
1562 * 2) reflecting userspace activity -> reflecting kernel heuristics
1564 * Current memory state:
1567 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
1570 size = memcg_page_state(memcg, memory_stats[i].idx);
1571 size *= memory_stats[i].ratio;
1572 seq_buf_printf(&s, "%s %llu\n", memory_stats[i].name, size);
1574 if (unlikely(memory_stats[i].idx == NR_SLAB_UNRECLAIMABLE_B)) {
1575 size = memcg_page_state(memcg, NR_SLAB_RECLAIMABLE_B) +
1576 memcg_page_state(memcg, NR_SLAB_UNRECLAIMABLE_B);
1577 seq_buf_printf(&s, "slab %llu\n", size);
1581 /* Accumulated memory events */
1583 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGFAULT),
1584 memcg_events(memcg, PGFAULT));
1585 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGMAJFAULT),
1586 memcg_events(memcg, PGMAJFAULT));
1587 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGREFILL),
1588 memcg_events(memcg, PGREFILL));
1589 seq_buf_printf(&s, "pgscan %lu\n",
1590 memcg_events(memcg, PGSCAN_KSWAPD) +
1591 memcg_events(memcg, PGSCAN_DIRECT));
1592 seq_buf_printf(&s, "pgsteal %lu\n",
1593 memcg_events(memcg, PGSTEAL_KSWAPD) +
1594 memcg_events(memcg, PGSTEAL_DIRECT));
1595 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGACTIVATE),
1596 memcg_events(memcg, PGACTIVATE));
1597 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGDEACTIVATE),
1598 memcg_events(memcg, PGDEACTIVATE));
1599 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGLAZYFREE),
1600 memcg_events(memcg, PGLAZYFREE));
1601 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGLAZYFREED),
1602 memcg_events(memcg, PGLAZYFREED));
1604 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1605 seq_buf_printf(&s, "%s %lu\n", vm_event_name(THP_FAULT_ALLOC),
1606 memcg_events(memcg, THP_FAULT_ALLOC));
1607 seq_buf_printf(&s, "%s %lu\n", vm_event_name(THP_COLLAPSE_ALLOC),
1608 memcg_events(memcg, THP_COLLAPSE_ALLOC));
1609 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
1611 /* The above should easily fit into one page */
1612 WARN_ON_ONCE(seq_buf_has_overflowed(&s));
1617 #define K(x) ((x) << (PAGE_SHIFT-10))
1619 * mem_cgroup_print_oom_context: Print OOM information relevant to
1620 * memory controller.
1621 * @memcg: The memory cgroup that went over limit
1622 * @p: Task that is going to be killed
1624 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1627 void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p)
1632 pr_cont(",oom_memcg=");
1633 pr_cont_cgroup_path(memcg->css.cgroup);
1635 pr_cont(",global_oom");
1637 pr_cont(",task_memcg=");
1638 pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
1644 * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
1645 * memory controller.
1646 * @memcg: The memory cgroup that went over limit
1648 void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
1652 pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1653 K((u64)page_counter_read(&memcg->memory)),
1654 K((u64)READ_ONCE(memcg->memory.max)), memcg->memory.failcnt);
1655 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1656 pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n",
1657 K((u64)page_counter_read(&memcg->swap)),
1658 K((u64)READ_ONCE(memcg->swap.max)), memcg->swap.failcnt);
1660 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1661 K((u64)page_counter_read(&memcg->memsw)),
1662 K((u64)memcg->memsw.max), memcg->memsw.failcnt);
1663 pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1664 K((u64)page_counter_read(&memcg->kmem)),
1665 K((u64)memcg->kmem.max), memcg->kmem.failcnt);
1668 pr_info("Memory cgroup stats for ");
1669 pr_cont_cgroup_path(memcg->css.cgroup);
1671 buf = memory_stat_format(memcg);
1679 * Return the memory (and swap, if configured) limit for a memcg.
1681 unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg)
1683 unsigned long max = READ_ONCE(memcg->memory.max);
1685 if (cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
1686 if (mem_cgroup_swappiness(memcg))
1687 max += min(READ_ONCE(memcg->swap.max),
1688 (unsigned long)total_swap_pages);
1690 if (mem_cgroup_swappiness(memcg)) {
1691 /* Calculate swap excess capacity from memsw limit */
1692 unsigned long swap = READ_ONCE(memcg->memsw.max) - max;
1694 max += min(swap, (unsigned long)total_swap_pages);
1700 unsigned long mem_cgroup_size(struct mem_cgroup *memcg)
1702 return page_counter_read(&memcg->memory);
1705 static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1708 struct oom_control oc = {
1712 .gfp_mask = gfp_mask,
1717 if (mutex_lock_killable(&oom_lock))
1720 if (mem_cgroup_margin(memcg) >= (1 << order))
1724 * A few threads which were not waiting at mutex_lock_killable() can
1725 * fail to bail out. Therefore, check again after holding oom_lock.
1727 ret = should_force_charge() || out_of_memory(&oc);
1730 mutex_unlock(&oom_lock);
1734 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
1737 unsigned long *total_scanned)
1739 struct mem_cgroup *victim = NULL;
1742 unsigned long excess;
1743 unsigned long nr_scanned;
1744 struct mem_cgroup_reclaim_cookie reclaim = {
1748 excess = soft_limit_excess(root_memcg);
1751 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1756 * If we have not been able to reclaim
1757 * anything, it might because there are
1758 * no reclaimable pages under this hierarchy
1763 * We want to do more targeted reclaim.
1764 * excess >> 2 is not to excessive so as to
1765 * reclaim too much, nor too less that we keep
1766 * coming back to reclaim from this cgroup
1768 if (total >= (excess >> 2) ||
1769 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1774 total += mem_cgroup_shrink_node(victim, gfp_mask, false,
1775 pgdat, &nr_scanned);
1776 *total_scanned += nr_scanned;
1777 if (!soft_limit_excess(root_memcg))
1780 mem_cgroup_iter_break(root_memcg, victim);
1784 #ifdef CONFIG_LOCKDEP
1785 static struct lockdep_map memcg_oom_lock_dep_map = {
1786 .name = "memcg_oom_lock",
1790 static DEFINE_SPINLOCK(memcg_oom_lock);
1793 * Check OOM-Killer is already running under our hierarchy.
1794 * If someone is running, return false.
1796 static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
1798 struct mem_cgroup *iter, *failed = NULL;
1800 spin_lock(&memcg_oom_lock);
1802 for_each_mem_cgroup_tree(iter, memcg) {
1803 if (iter->oom_lock) {
1805 * this subtree of our hierarchy is already locked
1806 * so we cannot give a lock.
1809 mem_cgroup_iter_break(memcg, iter);
1812 iter->oom_lock = true;
1817 * OK, we failed to lock the whole subtree so we have
1818 * to clean up what we set up to the failing subtree
1820 for_each_mem_cgroup_tree(iter, memcg) {
1821 if (iter == failed) {
1822 mem_cgroup_iter_break(memcg, iter);
1825 iter->oom_lock = false;
1828 mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
1830 spin_unlock(&memcg_oom_lock);
1835 static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1837 struct mem_cgroup *iter;
1839 spin_lock(&memcg_oom_lock);
1840 mutex_release(&memcg_oom_lock_dep_map, _RET_IP_);
1841 for_each_mem_cgroup_tree(iter, memcg)
1842 iter->oom_lock = false;
1843 spin_unlock(&memcg_oom_lock);
1846 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1848 struct mem_cgroup *iter;
1850 spin_lock(&memcg_oom_lock);
1851 for_each_mem_cgroup_tree(iter, memcg)
1853 spin_unlock(&memcg_oom_lock);
1856 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1858 struct mem_cgroup *iter;
1861 * Be careful about under_oom underflows becase a child memcg
1862 * could have been added after mem_cgroup_mark_under_oom.
1864 spin_lock(&memcg_oom_lock);
1865 for_each_mem_cgroup_tree(iter, memcg)
1866 if (iter->under_oom > 0)
1868 spin_unlock(&memcg_oom_lock);
1871 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1873 struct oom_wait_info {
1874 struct mem_cgroup *memcg;
1875 wait_queue_entry_t wait;
1878 static int memcg_oom_wake_function(wait_queue_entry_t *wait,
1879 unsigned mode, int sync, void *arg)
1881 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
1882 struct mem_cgroup *oom_wait_memcg;
1883 struct oom_wait_info *oom_wait_info;
1885 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1886 oom_wait_memcg = oom_wait_info->memcg;
1888 if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
1889 !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
1891 return autoremove_wake_function(wait, mode, sync, arg);
1894 static void memcg_oom_recover(struct mem_cgroup *memcg)
1897 * For the following lockless ->under_oom test, the only required
1898 * guarantee is that it must see the state asserted by an OOM when
1899 * this function is called as a result of userland actions
1900 * triggered by the notification of the OOM. This is trivially
1901 * achieved by invoking mem_cgroup_mark_under_oom() before
1902 * triggering notification.
1904 if (memcg && memcg->under_oom)
1905 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
1915 static enum oom_status mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
1917 enum oom_status ret;
1920 if (order > PAGE_ALLOC_COSTLY_ORDER)
1923 memcg_memory_event(memcg, MEMCG_OOM);
1926 * We are in the middle of the charge context here, so we
1927 * don't want to block when potentially sitting on a callstack
1928 * that holds all kinds of filesystem and mm locks.
1930 * cgroup1 allows disabling the OOM killer and waiting for outside
1931 * handling until the charge can succeed; remember the context and put
1932 * the task to sleep at the end of the page fault when all locks are
1935 * On the other hand, in-kernel OOM killer allows for an async victim
1936 * memory reclaim (oom_reaper) and that means that we are not solely
1937 * relying on the oom victim to make a forward progress and we can
1938 * invoke the oom killer here.
1940 * Please note that mem_cgroup_out_of_memory might fail to find a
1941 * victim and then we have to bail out from the charge path.
1943 if (memcg->oom_kill_disable) {
1944 if (!current->in_user_fault)
1946 css_get(&memcg->css);
1947 current->memcg_in_oom = memcg;
1948 current->memcg_oom_gfp_mask = mask;
1949 current->memcg_oom_order = order;
1954 mem_cgroup_mark_under_oom(memcg);
1956 locked = mem_cgroup_oom_trylock(memcg);
1959 mem_cgroup_oom_notify(memcg);
1961 mem_cgroup_unmark_under_oom(memcg);
1962 if (mem_cgroup_out_of_memory(memcg, mask, order))
1968 mem_cgroup_oom_unlock(memcg);
1974 * mem_cgroup_oom_synchronize - complete memcg OOM handling
1975 * @handle: actually kill/wait or just clean up the OOM state
1977 * This has to be called at the end of a page fault if the memcg OOM
1978 * handler was enabled.
1980 * Memcg supports userspace OOM handling where failed allocations must
1981 * sleep on a waitqueue until the userspace task resolves the
1982 * situation. Sleeping directly in the charge context with all kinds
1983 * of locks held is not a good idea, instead we remember an OOM state
1984 * in the task and mem_cgroup_oom_synchronize() has to be called at
1985 * the end of the page fault to complete the OOM handling.
1987 * Returns %true if an ongoing memcg OOM situation was detected and
1988 * completed, %false otherwise.
1990 bool mem_cgroup_oom_synchronize(bool handle)
1992 struct mem_cgroup *memcg = current->memcg_in_oom;
1993 struct oom_wait_info owait;
1996 /* OOM is global, do not handle */
2003 owait.memcg = memcg;
2004 owait.wait.flags = 0;
2005 owait.wait.func = memcg_oom_wake_function;
2006 owait.wait.private = current;
2007 INIT_LIST_HEAD(&owait.wait.entry);
2009 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
2010 mem_cgroup_mark_under_oom(memcg);
2012 locked = mem_cgroup_oom_trylock(memcg);
2015 mem_cgroup_oom_notify(memcg);
2017 if (locked && !memcg->oom_kill_disable) {
2018 mem_cgroup_unmark_under_oom(memcg);
2019 finish_wait(&memcg_oom_waitq, &owait.wait);
2020 mem_cgroup_out_of_memory(memcg, current->memcg_oom_gfp_mask,
2021 current->memcg_oom_order);
2024 mem_cgroup_unmark_under_oom(memcg);
2025 finish_wait(&memcg_oom_waitq, &owait.wait);
2029 mem_cgroup_oom_unlock(memcg);
2031 * There is no guarantee that an OOM-lock contender
2032 * sees the wakeups triggered by the OOM kill
2033 * uncharges. Wake any sleepers explicitely.
2035 memcg_oom_recover(memcg);
2038 current->memcg_in_oom = NULL;
2039 css_put(&memcg->css);
2044 * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
2045 * @victim: task to be killed by the OOM killer
2046 * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
2048 * Returns a pointer to a memory cgroup, which has to be cleaned up
2049 * by killing all belonging OOM-killable tasks.
2051 * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
2053 struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim,
2054 struct mem_cgroup *oom_domain)
2056 struct mem_cgroup *oom_group = NULL;
2057 struct mem_cgroup *memcg;
2059 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
2063 oom_domain = root_mem_cgroup;
2067 memcg = mem_cgroup_from_task(victim);
2068 if (memcg == root_mem_cgroup)
2072 * If the victim task has been asynchronously moved to a different
2073 * memory cgroup, we might end up killing tasks outside oom_domain.
2074 * In this case it's better to ignore memory.group.oom.
2076 if (unlikely(!mem_cgroup_is_descendant(memcg, oom_domain)))
2080 * Traverse the memory cgroup hierarchy from the victim task's
2081 * cgroup up to the OOMing cgroup (or root) to find the
2082 * highest-level memory cgroup with oom.group set.
2084 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
2085 if (memcg->oom_group)
2088 if (memcg == oom_domain)
2093 css_get(&oom_group->css);
2100 void mem_cgroup_print_oom_group(struct mem_cgroup *memcg)
2102 pr_info("Tasks in ");
2103 pr_cont_cgroup_path(memcg->css.cgroup);
2104 pr_cont(" are going to be killed due to memory.oom.group set\n");
2108 * lock_page_memcg - lock a page and memcg binding
2111 * This function protects unlocked LRU pages from being moved to
2114 * It ensures lifetime of the returned memcg. Caller is responsible
2115 * for the lifetime of the page; __unlock_page_memcg() is available
2116 * when @page might get freed inside the locked section.
2118 struct mem_cgroup *lock_page_memcg(struct page *page)
2120 struct page *head = compound_head(page); /* rmap on tail pages */
2121 struct mem_cgroup *memcg;
2122 unsigned long flags;
2125 * The RCU lock is held throughout the transaction. The fast
2126 * path can get away without acquiring the memcg->move_lock
2127 * because page moving starts with an RCU grace period.
2129 * The RCU lock also protects the memcg from being freed when
2130 * the page state that is going to change is the only thing
2131 * preventing the page itself from being freed. E.g. writeback
2132 * doesn't hold a page reference and relies on PG_writeback to
2133 * keep off truncation, migration and so forth.
2137 if (mem_cgroup_disabled())
2140 memcg = page_memcg(head);
2141 if (unlikely(!memcg))
2144 if (atomic_read(&memcg->moving_account) <= 0)
2147 spin_lock_irqsave(&memcg->move_lock, flags);
2148 if (memcg != page_memcg(head)) {
2149 spin_unlock_irqrestore(&memcg->move_lock, flags);
2154 * When charge migration first begins, we can have locked and
2155 * unlocked page stat updates happening concurrently. Track
2156 * the task who has the lock for unlock_page_memcg().
2158 memcg->move_lock_task = current;
2159 memcg->move_lock_flags = flags;
2163 EXPORT_SYMBOL(lock_page_memcg);
2166 * __unlock_page_memcg - unlock and unpin a memcg
2169 * Unlock and unpin a memcg returned by lock_page_memcg().
2171 void __unlock_page_memcg(struct mem_cgroup *memcg)
2173 if (memcg && memcg->move_lock_task == current) {
2174 unsigned long flags = memcg->move_lock_flags;
2176 memcg->move_lock_task = NULL;
2177 memcg->move_lock_flags = 0;
2179 spin_unlock_irqrestore(&memcg->move_lock, flags);
2186 * unlock_page_memcg - unlock a page and memcg binding
2189 void unlock_page_memcg(struct page *page)
2191 struct page *head = compound_head(page);
2193 __unlock_page_memcg(page_memcg(head));
2195 EXPORT_SYMBOL(unlock_page_memcg);
2197 struct memcg_stock_pcp {
2198 struct mem_cgroup *cached; /* this never be root cgroup */
2199 unsigned int nr_pages;
2201 #ifdef CONFIG_MEMCG_KMEM
2202 struct obj_cgroup *cached_objcg;
2203 unsigned int nr_bytes;
2206 struct work_struct work;
2207 unsigned long flags;
2208 #define FLUSHING_CACHED_CHARGE 0
2210 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
2211 static DEFINE_MUTEX(percpu_charge_mutex);
2213 #ifdef CONFIG_MEMCG_KMEM
2214 static void drain_obj_stock(struct memcg_stock_pcp *stock);
2215 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2216 struct mem_cgroup *root_memcg);
2219 static inline void drain_obj_stock(struct memcg_stock_pcp *stock)
2222 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2223 struct mem_cgroup *root_memcg)
2230 * consume_stock: Try to consume stocked charge on this cpu.
2231 * @memcg: memcg to consume from.
2232 * @nr_pages: how many pages to charge.
2234 * The charges will only happen if @memcg matches the current cpu's memcg
2235 * stock, and at least @nr_pages are available in that stock. Failure to
2236 * service an allocation will refill the stock.
2238 * returns true if successful, false otherwise.
2240 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2242 struct memcg_stock_pcp *stock;
2243 unsigned long flags;
2246 if (nr_pages > MEMCG_CHARGE_BATCH)
2249 local_irq_save(flags);
2251 stock = this_cpu_ptr(&memcg_stock);
2252 if (memcg == stock->cached && stock->nr_pages >= nr_pages) {
2253 stock->nr_pages -= nr_pages;
2257 local_irq_restore(flags);
2263 * Returns stocks cached in percpu and reset cached information.
2265 static void drain_stock(struct memcg_stock_pcp *stock)
2267 struct mem_cgroup *old = stock->cached;
2272 if (stock->nr_pages) {
2273 page_counter_uncharge(&old->memory, stock->nr_pages);
2274 if (do_memsw_account())
2275 page_counter_uncharge(&old->memsw, stock->nr_pages);
2276 stock->nr_pages = 0;
2280 stock->cached = NULL;
2283 static void drain_local_stock(struct work_struct *dummy)
2285 struct memcg_stock_pcp *stock;
2286 unsigned long flags;
2289 * The only protection from memory hotplug vs. drain_stock races is
2290 * that we always operate on local CPU stock here with IRQ disabled
2292 local_irq_save(flags);
2294 stock = this_cpu_ptr(&memcg_stock);
2295 drain_obj_stock(stock);
2297 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2299 local_irq_restore(flags);
2303 * Cache charges(val) to local per_cpu area.
2304 * This will be consumed by consume_stock() function, later.
2306 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2308 struct memcg_stock_pcp *stock;
2309 unsigned long flags;
2311 local_irq_save(flags);
2313 stock = this_cpu_ptr(&memcg_stock);
2314 if (stock->cached != memcg) { /* reset if necessary */
2316 css_get(&memcg->css);
2317 stock->cached = memcg;
2319 stock->nr_pages += nr_pages;
2321 if (stock->nr_pages > MEMCG_CHARGE_BATCH)
2324 local_irq_restore(flags);
2328 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2329 * of the hierarchy under it.
2331 static void drain_all_stock(struct mem_cgroup *root_memcg)
2335 /* If someone's already draining, avoid adding running more workers. */
2336 if (!mutex_trylock(&percpu_charge_mutex))
2339 * Notify other cpus that system-wide "drain" is running
2340 * We do not care about races with the cpu hotplug because cpu down
2341 * as well as workers from this path always operate on the local
2342 * per-cpu data. CPU up doesn't touch memcg_stock at all.
2345 for_each_online_cpu(cpu) {
2346 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2347 struct mem_cgroup *memcg;
2351 memcg = stock->cached;
2352 if (memcg && stock->nr_pages &&
2353 mem_cgroup_is_descendant(memcg, root_memcg))
2355 if (obj_stock_flush_required(stock, root_memcg))
2360 !test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2362 drain_local_stock(&stock->work);
2364 schedule_work_on(cpu, &stock->work);
2368 mutex_unlock(&percpu_charge_mutex);
2371 static int memcg_hotplug_cpu_dead(unsigned int cpu)
2373 struct memcg_stock_pcp *stock;
2374 struct mem_cgroup *memcg, *mi;
2376 stock = &per_cpu(memcg_stock, cpu);
2379 for_each_mem_cgroup(memcg) {
2382 for (i = 0; i < MEMCG_NR_STAT; i++) {
2386 x = this_cpu_xchg(memcg->vmstats_percpu->stat[i], 0);
2388 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
2389 atomic_long_add(x, &memcg->vmstats[i]);
2391 if (i >= NR_VM_NODE_STAT_ITEMS)
2394 for_each_node(nid) {
2395 struct mem_cgroup_per_node *pn;
2397 pn = mem_cgroup_nodeinfo(memcg, nid);
2398 x = this_cpu_xchg(pn->lruvec_stat_cpu->count[i], 0);
2401 atomic_long_add(x, &pn->lruvec_stat[i]);
2402 } while ((pn = parent_nodeinfo(pn, nid)));
2406 for (i = 0; i < NR_VM_EVENT_ITEMS; i++) {
2409 x = this_cpu_xchg(memcg->vmstats_percpu->events[i], 0);
2411 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
2412 atomic_long_add(x, &memcg->vmevents[i]);
2419 static unsigned long reclaim_high(struct mem_cgroup *memcg,
2420 unsigned int nr_pages,
2423 unsigned long nr_reclaimed = 0;
2426 unsigned long pflags;
2428 if (page_counter_read(&memcg->memory) <=
2429 READ_ONCE(memcg->memory.high))
2432 memcg_memory_event(memcg, MEMCG_HIGH);
2434 psi_memstall_enter(&pflags);
2435 nr_reclaimed += try_to_free_mem_cgroup_pages(memcg, nr_pages,
2437 psi_memstall_leave(&pflags);
2438 } while ((memcg = parent_mem_cgroup(memcg)) &&
2439 !mem_cgroup_is_root(memcg));
2441 return nr_reclaimed;
2444 static void high_work_func(struct work_struct *work)
2446 struct mem_cgroup *memcg;
2448 memcg = container_of(work, struct mem_cgroup, high_work);
2449 reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
2453 * Clamp the maximum sleep time per allocation batch to 2 seconds. This is
2454 * enough to still cause a significant slowdown in most cases, while still
2455 * allowing diagnostics and tracing to proceed without becoming stuck.
2457 #define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ)
2460 * When calculating the delay, we use these either side of the exponentiation to
2461 * maintain precision and scale to a reasonable number of jiffies (see the table
2464 * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the
2465 * overage ratio to a delay.
2466 * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down the
2467 * proposed penalty in order to reduce to a reasonable number of jiffies, and
2468 * to produce a reasonable delay curve.
2470 * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a
2471 * reasonable delay curve compared to precision-adjusted overage, not
2472 * penalising heavily at first, but still making sure that growth beyond the
2473 * limit penalises misbehaviour cgroups by slowing them down exponentially. For
2474 * example, with a high of 100 megabytes:
2476 * +-------+------------------------+
2477 * | usage | time to allocate in ms |
2478 * +-------+------------------------+
2500 * +-------+------------------------+
2502 #define MEMCG_DELAY_PRECISION_SHIFT 20
2503 #define MEMCG_DELAY_SCALING_SHIFT 14
2505 static u64 calculate_overage(unsigned long usage, unsigned long high)
2513 * Prevent division by 0 in overage calculation by acting as if
2514 * it was a threshold of 1 page
2516 high = max(high, 1UL);
2518 overage = usage - high;
2519 overage <<= MEMCG_DELAY_PRECISION_SHIFT;
2520 return div64_u64(overage, high);
2523 static u64 mem_find_max_overage(struct mem_cgroup *memcg)
2525 u64 overage, max_overage = 0;
2528 overage = calculate_overage(page_counter_read(&memcg->memory),
2529 READ_ONCE(memcg->memory.high));
2530 max_overage = max(overage, max_overage);
2531 } while ((memcg = parent_mem_cgroup(memcg)) &&
2532 !mem_cgroup_is_root(memcg));
2537 static u64 swap_find_max_overage(struct mem_cgroup *memcg)
2539 u64 overage, max_overage = 0;
2542 overage = calculate_overage(page_counter_read(&memcg->swap),
2543 READ_ONCE(memcg->swap.high));
2545 memcg_memory_event(memcg, MEMCG_SWAP_HIGH);
2546 max_overage = max(overage, max_overage);
2547 } while ((memcg = parent_mem_cgroup(memcg)) &&
2548 !mem_cgroup_is_root(memcg));
2554 * Get the number of jiffies that we should penalise a mischievous cgroup which
2555 * is exceeding its memory.high by checking both it and its ancestors.
2557 static unsigned long calculate_high_delay(struct mem_cgroup *memcg,
2558 unsigned int nr_pages,
2561 unsigned long penalty_jiffies;
2567 * We use overage compared to memory.high to calculate the number of
2568 * jiffies to sleep (penalty_jiffies). Ideally this value should be
2569 * fairly lenient on small overages, and increasingly harsh when the
2570 * memcg in question makes it clear that it has no intention of stopping
2571 * its crazy behaviour, so we exponentially increase the delay based on
2574 penalty_jiffies = max_overage * max_overage * HZ;
2575 penalty_jiffies >>= MEMCG_DELAY_PRECISION_SHIFT;
2576 penalty_jiffies >>= MEMCG_DELAY_SCALING_SHIFT;
2579 * Factor in the task's own contribution to the overage, such that four
2580 * N-sized allocations are throttled approximately the same as one
2581 * 4N-sized allocation.
2583 * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or
2584 * larger the current charge patch is than that.
2586 return penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH;
2590 * Scheduled by try_charge() to be executed from the userland return path
2591 * and reclaims memory over the high limit.
2593 void mem_cgroup_handle_over_high(void)
2595 unsigned long penalty_jiffies;
2596 unsigned long pflags;
2597 unsigned long nr_reclaimed;
2598 unsigned int nr_pages = current->memcg_nr_pages_over_high;
2599 int nr_retries = MAX_RECLAIM_RETRIES;
2600 struct mem_cgroup *memcg;
2601 bool in_retry = false;
2603 if (likely(!nr_pages))
2606 memcg = get_mem_cgroup_from_mm(current->mm);
2607 current->memcg_nr_pages_over_high = 0;
2611 * The allocating task should reclaim at least the batch size, but for
2612 * subsequent retries we only want to do what's necessary to prevent oom
2613 * or breaching resource isolation.
2615 * This is distinct from memory.max or page allocator behaviour because
2616 * memory.high is currently batched, whereas memory.max and the page
2617 * allocator run every time an allocation is made.
2619 nr_reclaimed = reclaim_high(memcg,
2620 in_retry ? SWAP_CLUSTER_MAX : nr_pages,
2624 * memory.high is breached and reclaim is unable to keep up. Throttle
2625 * allocators proactively to slow down excessive growth.
2627 penalty_jiffies = calculate_high_delay(memcg, nr_pages,
2628 mem_find_max_overage(memcg));
2630 penalty_jiffies += calculate_high_delay(memcg, nr_pages,
2631 swap_find_max_overage(memcg));
2634 * Clamp the max delay per usermode return so as to still keep the
2635 * application moving forwards and also permit diagnostics, albeit
2638 penalty_jiffies = min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES);
2641 * Don't sleep if the amount of jiffies this memcg owes us is so low
2642 * that it's not even worth doing, in an attempt to be nice to those who
2643 * go only a small amount over their memory.high value and maybe haven't
2644 * been aggressively reclaimed enough yet.
2646 if (penalty_jiffies <= HZ / 100)
2650 * If reclaim is making forward progress but we're still over
2651 * memory.high, we want to encourage that rather than doing allocator
2654 if (nr_reclaimed || nr_retries--) {
2660 * If we exit early, we're guaranteed to die (since
2661 * schedule_timeout_killable sets TASK_KILLABLE). This means we don't
2662 * need to account for any ill-begotten jiffies to pay them off later.
2664 psi_memstall_enter(&pflags);
2665 schedule_timeout_killable(penalty_jiffies);
2666 psi_memstall_leave(&pflags);
2669 css_put(&memcg->css);
2672 static int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2673 unsigned int nr_pages)
2675 unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
2676 int nr_retries = MAX_RECLAIM_RETRIES;
2677 struct mem_cgroup *mem_over_limit;
2678 struct page_counter *counter;
2679 enum oom_status oom_status;
2680 unsigned long nr_reclaimed;
2681 bool may_swap = true;
2682 bool drained = false;
2683 unsigned long pflags;
2685 if (mem_cgroup_is_root(memcg))
2688 if (consume_stock(memcg, nr_pages))
2691 if (!do_memsw_account() ||
2692 page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2693 if (page_counter_try_charge(&memcg->memory, batch, &counter))
2695 if (do_memsw_account())
2696 page_counter_uncharge(&memcg->memsw, batch);
2697 mem_over_limit = mem_cgroup_from_counter(counter, memory);
2699 mem_over_limit = mem_cgroup_from_counter(counter, memsw);
2703 if (batch > nr_pages) {
2709 * Memcg doesn't have a dedicated reserve for atomic
2710 * allocations. But like the global atomic pool, we need to
2711 * put the burden of reclaim on regular allocation requests
2712 * and let these go through as privileged allocations.
2714 if (gfp_mask & __GFP_ATOMIC)
2718 * Unlike in global OOM situations, memcg is not in a physical
2719 * memory shortage. Allow dying and OOM-killed tasks to
2720 * bypass the last charges so that they can exit quickly and
2721 * free their memory.
2723 if (unlikely(should_force_charge()))
2727 * Prevent unbounded recursion when reclaim operations need to
2728 * allocate memory. This might exceed the limits temporarily,
2729 * but we prefer facilitating memory reclaim and getting back
2730 * under the limit over triggering OOM kills in these cases.
2732 if (unlikely(current->flags & PF_MEMALLOC))
2735 if (unlikely(task_in_memcg_oom(current)))
2738 if (!gfpflags_allow_blocking(gfp_mask))
2741 memcg_memory_event(mem_over_limit, MEMCG_MAX);
2743 psi_memstall_enter(&pflags);
2744 nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
2745 gfp_mask, may_swap);
2746 psi_memstall_leave(&pflags);
2748 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2752 drain_all_stock(mem_over_limit);
2757 if (gfp_mask & __GFP_NORETRY)
2760 * Even though the limit is exceeded at this point, reclaim
2761 * may have been able to free some pages. Retry the charge
2762 * before killing the task.
2764 * Only for regular pages, though: huge pages are rather
2765 * unlikely to succeed so close to the limit, and we fall back
2766 * to regular pages anyway in case of failure.
2768 if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
2771 * At task move, charge accounts can be doubly counted. So, it's
2772 * better to wait until the end of task_move if something is going on.
2774 if (mem_cgroup_wait_acct_move(mem_over_limit))
2780 if (gfp_mask & __GFP_RETRY_MAYFAIL)
2783 if (gfp_mask & __GFP_NOFAIL)
2786 if (fatal_signal_pending(current))
2790 * keep retrying as long as the memcg oom killer is able to make
2791 * a forward progress or bypass the charge if the oom killer
2792 * couldn't make any progress.
2794 oom_status = mem_cgroup_oom(mem_over_limit, gfp_mask,
2795 get_order(nr_pages * PAGE_SIZE));
2796 switch (oom_status) {
2798 nr_retries = MAX_RECLAIM_RETRIES;
2806 if (!(gfp_mask & __GFP_NOFAIL))
2810 * The allocation either can't fail or will lead to more memory
2811 * being freed very soon. Allow memory usage go over the limit
2812 * temporarily by force charging it.
2814 page_counter_charge(&memcg->memory, nr_pages);
2815 if (do_memsw_account())
2816 page_counter_charge(&memcg->memsw, nr_pages);
2821 if (batch > nr_pages)
2822 refill_stock(memcg, batch - nr_pages);
2825 * If the hierarchy is above the normal consumption range, schedule
2826 * reclaim on returning to userland. We can perform reclaim here
2827 * if __GFP_RECLAIM but let's always punt for simplicity and so that
2828 * GFP_KERNEL can consistently be used during reclaim. @memcg is
2829 * not recorded as it most likely matches current's and won't
2830 * change in the meantime. As high limit is checked again before
2831 * reclaim, the cost of mismatch is negligible.
2834 bool mem_high, swap_high;
2836 mem_high = page_counter_read(&memcg->memory) >
2837 READ_ONCE(memcg->memory.high);
2838 swap_high = page_counter_read(&memcg->swap) >
2839 READ_ONCE(memcg->swap.high);
2841 /* Don't bother a random interrupted task */
2842 if (in_interrupt()) {
2844 schedule_work(&memcg->high_work);
2850 if (mem_high || swap_high) {
2852 * The allocating tasks in this cgroup will need to do
2853 * reclaim or be throttled to prevent further growth
2854 * of the memory or swap footprints.
2856 * Target some best-effort fairness between the tasks,
2857 * and distribute reclaim work and delay penalties
2858 * based on how much each task is actually allocating.
2860 current->memcg_nr_pages_over_high += batch;
2861 set_notify_resume(current);
2864 } while ((memcg = parent_mem_cgroup(memcg)));
2869 #if defined(CONFIG_MEMCG_KMEM) || defined(CONFIG_MMU)
2870 static void cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
2872 if (mem_cgroup_is_root(memcg))
2875 page_counter_uncharge(&memcg->memory, nr_pages);
2876 if (do_memsw_account())
2877 page_counter_uncharge(&memcg->memsw, nr_pages);
2881 static void commit_charge(struct page *page, struct mem_cgroup *memcg)
2883 VM_BUG_ON_PAGE(page_memcg(page), page);
2885 * Any of the following ensures page->mem_cgroup stability:
2889 * - lock_page_memcg()
2890 * - exclusive reference
2892 page->memcg_data = (unsigned long)memcg;
2895 #ifdef CONFIG_MEMCG_KMEM
2896 int memcg_alloc_page_obj_cgroups(struct page *page, struct kmem_cache *s,
2899 unsigned int objects = objs_per_slab_page(s, page);
2902 vec = kcalloc_node(objects, sizeof(struct obj_cgroup *), gfp,
2907 if (!set_page_objcgs(page, vec))
2910 kmemleak_not_leak(vec);
2916 * Returns a pointer to the memory cgroup to which the kernel object is charged.
2918 * A passed kernel object can be a slab object or a generic kernel page, so
2919 * different mechanisms for getting the memory cgroup pointer should be used.
2920 * In certain cases (e.g. kernel stacks or large kmallocs with SLUB) the caller
2921 * can not know for sure how the kernel object is implemented.
2922 * mem_cgroup_from_obj() can be safely used in such cases.
2924 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
2925 * cgroup_mutex, etc.
2927 struct mem_cgroup *mem_cgroup_from_obj(void *p)
2931 if (mem_cgroup_disabled())
2934 page = virt_to_head_page(p);
2937 * Slab objects are accounted individually, not per-page.
2938 * Memcg membership data for each individual object is saved in
2939 * the page->obj_cgroups.
2941 if (page_objcgs_check(page)) {
2942 struct obj_cgroup *objcg;
2945 off = obj_to_index(page->slab_cache, page, p);
2946 objcg = page_objcgs(page)[off];
2948 return obj_cgroup_memcg(objcg);
2954 * page_memcg_check() is used here, because page_has_obj_cgroups()
2955 * check above could fail because the object cgroups vector wasn't set
2956 * at that moment, but it can be set concurrently.
2957 * page_memcg_check(page) will guarantee that a proper memory
2958 * cgroup pointer or NULL will be returned.
2960 return page_memcg_check(page);
2963 __always_inline struct obj_cgroup *get_obj_cgroup_from_current(void)
2965 struct obj_cgroup *objcg = NULL;
2966 struct mem_cgroup *memcg;
2968 if (memcg_kmem_bypass())
2972 if (unlikely(active_memcg()))
2973 memcg = active_memcg();
2975 memcg = mem_cgroup_from_task(current);
2977 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg)) {
2978 objcg = rcu_dereference(memcg->objcg);
2979 if (objcg && obj_cgroup_tryget(objcg))
2987 static int memcg_alloc_cache_id(void)
2992 id = ida_simple_get(&memcg_cache_ida,
2993 0, MEMCG_CACHES_MAX_SIZE, GFP_KERNEL);
2997 if (id < memcg_nr_cache_ids)
3001 * There's no space for the new id in memcg_caches arrays,
3002 * so we have to grow them.
3004 down_write(&memcg_cache_ids_sem);
3006 size = 2 * (id + 1);
3007 if (size < MEMCG_CACHES_MIN_SIZE)
3008 size = MEMCG_CACHES_MIN_SIZE;
3009 else if (size > MEMCG_CACHES_MAX_SIZE)
3010 size = MEMCG_CACHES_MAX_SIZE;
3012 err = memcg_update_all_list_lrus(size);
3014 memcg_nr_cache_ids = size;
3016 up_write(&memcg_cache_ids_sem);
3019 ida_simple_remove(&memcg_cache_ida, id);
3025 static void memcg_free_cache_id(int id)
3027 ida_simple_remove(&memcg_cache_ida, id);
3031 * __memcg_kmem_charge: charge a number of kernel pages to a memcg
3032 * @memcg: memory cgroup to charge
3033 * @gfp: reclaim mode
3034 * @nr_pages: number of pages to charge
3036 * Returns 0 on success, an error code on failure.
3038 int __memcg_kmem_charge(struct mem_cgroup *memcg, gfp_t gfp,
3039 unsigned int nr_pages)
3041 struct page_counter *counter;
3044 ret = try_charge(memcg, gfp, nr_pages);
3048 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) &&
3049 !page_counter_try_charge(&memcg->kmem, nr_pages, &counter)) {
3052 * Enforce __GFP_NOFAIL allocation because callers are not
3053 * prepared to see failures and likely do not have any failure
3056 if (gfp & __GFP_NOFAIL) {
3057 page_counter_charge(&memcg->kmem, nr_pages);
3060 cancel_charge(memcg, nr_pages);
3067 * __memcg_kmem_uncharge: uncharge a number of kernel pages from a memcg
3068 * @memcg: memcg to uncharge
3069 * @nr_pages: number of pages to uncharge
3071 void __memcg_kmem_uncharge(struct mem_cgroup *memcg, unsigned int nr_pages)
3073 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
3074 page_counter_uncharge(&memcg->kmem, nr_pages);
3076 page_counter_uncharge(&memcg->memory, nr_pages);
3077 if (do_memsw_account())
3078 page_counter_uncharge(&memcg->memsw, nr_pages);
3082 * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup
3083 * @page: page to charge
3084 * @gfp: reclaim mode
3085 * @order: allocation order
3087 * Returns 0 on success, an error code on failure.
3089 int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
3091 struct mem_cgroup *memcg;
3094 memcg = get_mem_cgroup_from_current();
3095 if (memcg && !mem_cgroup_is_root(memcg)) {
3096 ret = __memcg_kmem_charge(memcg, gfp, 1 << order);
3098 page->memcg_data = (unsigned long)memcg |
3102 css_put(&memcg->css);
3108 * __memcg_kmem_uncharge_page: uncharge a kmem page
3109 * @page: page to uncharge
3110 * @order: allocation order
3112 void __memcg_kmem_uncharge_page(struct page *page, int order)
3114 struct mem_cgroup *memcg = page_memcg(page);
3115 unsigned int nr_pages = 1 << order;
3120 VM_BUG_ON_PAGE(mem_cgroup_is_root(memcg), page);
3121 __memcg_kmem_uncharge(memcg, nr_pages);
3122 page->memcg_data = 0;
3123 css_put(&memcg->css);
3126 static bool consume_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes)
3128 struct memcg_stock_pcp *stock;
3129 unsigned long flags;
3132 local_irq_save(flags);
3134 stock = this_cpu_ptr(&memcg_stock);
3135 if (objcg == stock->cached_objcg && stock->nr_bytes >= nr_bytes) {
3136 stock->nr_bytes -= nr_bytes;
3140 local_irq_restore(flags);
3145 static void drain_obj_stock(struct memcg_stock_pcp *stock)
3147 struct obj_cgroup *old = stock->cached_objcg;
3152 if (stock->nr_bytes) {
3153 unsigned int nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3154 unsigned int nr_bytes = stock->nr_bytes & (PAGE_SIZE - 1);
3158 __memcg_kmem_uncharge(obj_cgroup_memcg(old), nr_pages);
3163 * The leftover is flushed to the centralized per-memcg value.
3164 * On the next attempt to refill obj stock it will be moved
3165 * to a per-cpu stock (probably, on an other CPU), see
3166 * refill_obj_stock().
3168 * How often it's flushed is a trade-off between the memory
3169 * limit enforcement accuracy and potential CPU contention,
3170 * so it might be changed in the future.
3172 atomic_add(nr_bytes, &old->nr_charged_bytes);
3173 stock->nr_bytes = 0;
3176 obj_cgroup_put(old);
3177 stock->cached_objcg = NULL;
3180 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
3181 struct mem_cgroup *root_memcg)
3183 struct mem_cgroup *memcg;
3185 if (stock->cached_objcg) {
3186 memcg = obj_cgroup_memcg(stock->cached_objcg);
3187 if (memcg && mem_cgroup_is_descendant(memcg, root_memcg))
3194 static void refill_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes)
3196 struct memcg_stock_pcp *stock;
3197 unsigned long flags;
3199 local_irq_save(flags);
3201 stock = this_cpu_ptr(&memcg_stock);
3202 if (stock->cached_objcg != objcg) { /* reset if necessary */
3203 drain_obj_stock(stock);
3204 obj_cgroup_get(objcg);
3205 stock->cached_objcg = objcg;
3206 stock->nr_bytes = atomic_xchg(&objcg->nr_charged_bytes, 0);
3208 stock->nr_bytes += nr_bytes;
3210 if (stock->nr_bytes > PAGE_SIZE)
3211 drain_obj_stock(stock);
3213 local_irq_restore(flags);
3216 int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size)
3218 struct mem_cgroup *memcg;
3219 unsigned int nr_pages, nr_bytes;
3222 if (consume_obj_stock(objcg, size))
3226 * In theory, memcg->nr_charged_bytes can have enough
3227 * pre-charged bytes to satisfy the allocation. However,
3228 * flushing memcg->nr_charged_bytes requires two atomic
3229 * operations, and memcg->nr_charged_bytes can't be big,
3230 * so it's better to ignore it and try grab some new pages.
3231 * memcg->nr_charged_bytes will be flushed in
3232 * refill_obj_stock(), called from this function or
3233 * independently later.
3236 memcg = obj_cgroup_memcg(objcg);
3237 css_get(&memcg->css);
3240 nr_pages = size >> PAGE_SHIFT;
3241 nr_bytes = size & (PAGE_SIZE - 1);
3246 ret = __memcg_kmem_charge(memcg, gfp, nr_pages);
3247 if (!ret && nr_bytes)
3248 refill_obj_stock(objcg, PAGE_SIZE - nr_bytes);
3250 css_put(&memcg->css);
3254 void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size)
3256 refill_obj_stock(objcg, size);
3259 #endif /* CONFIG_MEMCG_KMEM */
3261 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3264 * Because tail pages are not marked as "used", set it. We're under
3265 * pgdat->lru_lock and migration entries setup in all page mappings.
3267 void mem_cgroup_split_huge_fixup(struct page *head)
3269 struct mem_cgroup *memcg = page_memcg(head);
3272 if (mem_cgroup_disabled())
3275 for (i = 1; i < HPAGE_PMD_NR; i++) {
3276 css_get(&memcg->css);
3277 head[i].memcg_data = (unsigned long)memcg;
3280 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
3282 #ifdef CONFIG_MEMCG_SWAP
3284 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3285 * @entry: swap entry to be moved
3286 * @from: mem_cgroup which the entry is moved from
3287 * @to: mem_cgroup which the entry is moved to
3289 * It succeeds only when the swap_cgroup's record for this entry is the same
3290 * as the mem_cgroup's id of @from.
3292 * Returns 0 on success, -EINVAL on failure.
3294 * The caller must have charged to @to, IOW, called page_counter_charge() about
3295 * both res and memsw, and called css_get().
3297 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3298 struct mem_cgroup *from, struct mem_cgroup *to)
3300 unsigned short old_id, new_id;
3302 old_id = mem_cgroup_id(from);
3303 new_id = mem_cgroup_id(to);
3305 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3306 mod_memcg_state(from, MEMCG_SWAP, -1);
3307 mod_memcg_state(to, MEMCG_SWAP, 1);
3313 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3314 struct mem_cgroup *from, struct mem_cgroup *to)
3320 static DEFINE_MUTEX(memcg_max_mutex);
3322 static int mem_cgroup_resize_max(struct mem_cgroup *memcg,
3323 unsigned long max, bool memsw)
3325 bool enlarge = false;
3326 bool drained = false;
3328 bool limits_invariant;
3329 struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory;
3332 if (signal_pending(current)) {
3337 mutex_lock(&memcg_max_mutex);
3339 * Make sure that the new limit (memsw or memory limit) doesn't
3340 * break our basic invariant rule memory.max <= memsw.max.
3342 limits_invariant = memsw ? max >= READ_ONCE(memcg->memory.max) :
3343 max <= memcg->memsw.max;
3344 if (!limits_invariant) {
3345 mutex_unlock(&memcg_max_mutex);
3349 if (max > counter->max)
3351 ret = page_counter_set_max(counter, max);
3352 mutex_unlock(&memcg_max_mutex);
3358 drain_all_stock(memcg);
3363 if (!try_to_free_mem_cgroup_pages(memcg, 1,
3364 GFP_KERNEL, !memsw)) {
3370 if (!ret && enlarge)
3371 memcg_oom_recover(memcg);
3376 unsigned long mem_cgroup_soft_limit_reclaim(pg_data_t *pgdat, int order,
3378 unsigned long *total_scanned)
3380 unsigned long nr_reclaimed = 0;
3381 struct mem_cgroup_per_node *mz, *next_mz = NULL;
3382 unsigned long reclaimed;
3384 struct mem_cgroup_tree_per_node *mctz;
3385 unsigned long excess;
3386 unsigned long nr_scanned;
3391 mctz = soft_limit_tree_node(pgdat->node_id);
3394 * Do not even bother to check the largest node if the root
3395 * is empty. Do it lockless to prevent lock bouncing. Races
3396 * are acceptable as soft limit is best effort anyway.
3398 if (!mctz || RB_EMPTY_ROOT(&mctz->rb_root))
3402 * This loop can run a while, specially if mem_cgroup's continuously
3403 * keep exceeding their soft limit and putting the system under
3410 mz = mem_cgroup_largest_soft_limit_node(mctz);
3415 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, pgdat,
3416 gfp_mask, &nr_scanned);
3417 nr_reclaimed += reclaimed;
3418 *total_scanned += nr_scanned;
3419 spin_lock_irq(&mctz->lock);
3420 __mem_cgroup_remove_exceeded(mz, mctz);
3423 * If we failed to reclaim anything from this memory cgroup
3424 * it is time to move on to the next cgroup
3428 next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
3430 excess = soft_limit_excess(mz->memcg);
3432 * One school of thought says that we should not add
3433 * back the node to the tree if reclaim returns 0.
3434 * But our reclaim could return 0, simply because due
3435 * to priority we are exposing a smaller subset of
3436 * memory to reclaim from. Consider this as a longer
3439 /* If excess == 0, no tree ops */
3440 __mem_cgroup_insert_exceeded(mz, mctz, excess);
3441 spin_unlock_irq(&mctz->lock);
3442 css_put(&mz->memcg->css);
3445 * Could not reclaim anything and there are no more
3446 * mem cgroups to try or we seem to be looping without
3447 * reclaiming anything.
3449 if (!nr_reclaimed &&
3451 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3453 } while (!nr_reclaimed);
3455 css_put(&next_mz->memcg->css);
3456 return nr_reclaimed;
3460 * Test whether @memcg has children, dead or alive. Note that this
3461 * function doesn't care whether @memcg has use_hierarchy enabled and
3462 * returns %true if there are child csses according to the cgroup
3463 * hierarchy. Testing use_hierarchy is the caller's responsibility.
3465 static inline bool memcg_has_children(struct mem_cgroup *memcg)
3470 ret = css_next_child(NULL, &memcg->css);
3476 * Reclaims as many pages from the given memcg as possible.
3478 * Caller is responsible for holding css reference for memcg.
3480 static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
3482 int nr_retries = MAX_RECLAIM_RETRIES;
3484 /* we call try-to-free pages for make this cgroup empty */
3485 lru_add_drain_all();
3487 drain_all_stock(memcg);
3489 /* try to free all pages in this cgroup */
3490 while (nr_retries && page_counter_read(&memcg->memory)) {
3493 if (signal_pending(current))
3496 progress = try_to_free_mem_cgroup_pages(memcg, 1,
3500 /* maybe some writeback is necessary */
3501 congestion_wait(BLK_RW_ASYNC, HZ/10);
3509 static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
3510 char *buf, size_t nbytes,
3513 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3515 if (mem_cgroup_is_root(memcg))
3517 return mem_cgroup_force_empty(memcg) ?: nbytes;
3520 static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
3523 return mem_cgroup_from_css(css)->use_hierarchy;
3526 static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
3527 struct cftype *cft, u64 val)
3530 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3531 struct mem_cgroup *parent_memcg = mem_cgroup_from_css(memcg->css.parent);
3533 if (memcg->use_hierarchy == val)
3537 * If parent's use_hierarchy is set, we can't make any modifications
3538 * in the child subtrees. If it is unset, then the change can
3539 * occur, provided the current cgroup has no children.
3541 * For the root cgroup, parent_mem is NULL, we allow value to be
3542 * set if there are no children.
3544 if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
3545 (val == 1 || val == 0)) {
3546 if (!memcg_has_children(memcg))
3547 memcg->use_hierarchy = val;
3556 static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3560 if (mem_cgroup_is_root(memcg)) {
3561 val = memcg_page_state(memcg, NR_FILE_PAGES) +
3562 memcg_page_state(memcg, NR_ANON_MAPPED);
3564 val += memcg_page_state(memcg, MEMCG_SWAP);
3567 val = page_counter_read(&memcg->memory);
3569 val = page_counter_read(&memcg->memsw);
3582 static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
3585 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3586 struct page_counter *counter;
3588 switch (MEMFILE_TYPE(cft->private)) {
3590 counter = &memcg->memory;
3593 counter = &memcg->memsw;
3596 counter = &memcg->kmem;
3599 counter = &memcg->tcpmem;
3605 switch (MEMFILE_ATTR(cft->private)) {
3607 if (counter == &memcg->memory)
3608 return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
3609 if (counter == &memcg->memsw)
3610 return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
3611 return (u64)page_counter_read(counter) * PAGE_SIZE;
3613 return (u64)counter->max * PAGE_SIZE;
3615 return (u64)counter->watermark * PAGE_SIZE;
3617 return counter->failcnt;
3618 case RES_SOFT_LIMIT:
3619 return (u64)memcg->soft_limit * PAGE_SIZE;
3625 static void memcg_flush_percpu_vmstats(struct mem_cgroup *memcg)
3627 unsigned long stat[MEMCG_NR_STAT] = {0};
3628 struct mem_cgroup *mi;
3631 for_each_online_cpu(cpu)
3632 for (i = 0; i < MEMCG_NR_STAT; i++)
3633 stat[i] += per_cpu(memcg->vmstats_percpu->stat[i], cpu);
3635 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
3636 for (i = 0; i < MEMCG_NR_STAT; i++)
3637 atomic_long_add(stat[i], &mi->vmstats[i]);
3639 for_each_node(node) {
3640 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
3641 struct mem_cgroup_per_node *pi;
3643 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++)
3646 for_each_online_cpu(cpu)
3647 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++)
3649 pn->lruvec_stat_cpu->count[i], cpu);
3651 for (pi = pn; pi; pi = parent_nodeinfo(pi, node))
3652 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++)
3653 atomic_long_add(stat[i], &pi->lruvec_stat[i]);
3657 static void memcg_flush_percpu_vmevents(struct mem_cgroup *memcg)
3659 unsigned long events[NR_VM_EVENT_ITEMS];
3660 struct mem_cgroup *mi;
3663 for (i = 0; i < NR_VM_EVENT_ITEMS; i++)
3666 for_each_online_cpu(cpu)
3667 for (i = 0; i < NR_VM_EVENT_ITEMS; i++)
3668 events[i] += per_cpu(memcg->vmstats_percpu->events[i],
3671 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
3672 for (i = 0; i < NR_VM_EVENT_ITEMS; i++)
3673 atomic_long_add(events[i], &mi->vmevents[i]);
3676 #ifdef CONFIG_MEMCG_KMEM
3677 static int memcg_online_kmem(struct mem_cgroup *memcg)
3679 struct obj_cgroup *objcg;
3682 if (cgroup_memory_nokmem)
3685 BUG_ON(memcg->kmemcg_id >= 0);
3686 BUG_ON(memcg->kmem_state);
3688 memcg_id = memcg_alloc_cache_id();
3692 objcg = obj_cgroup_alloc();
3694 memcg_free_cache_id(memcg_id);
3697 objcg->memcg = memcg;
3698 rcu_assign_pointer(memcg->objcg, objcg);
3700 static_branch_enable(&memcg_kmem_enabled_key);
3703 * A memory cgroup is considered kmem-online as soon as it gets
3704 * kmemcg_id. Setting the id after enabling static branching will
3705 * guarantee no one starts accounting before all call sites are
3708 memcg->kmemcg_id = memcg_id;
3709 memcg->kmem_state = KMEM_ONLINE;
3714 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3716 struct cgroup_subsys_state *css;
3717 struct mem_cgroup *parent, *child;
3720 if (memcg->kmem_state != KMEM_ONLINE)
3723 memcg->kmem_state = KMEM_ALLOCATED;
3725 parent = parent_mem_cgroup(memcg);
3727 parent = root_mem_cgroup;
3729 memcg_reparent_objcgs(memcg, parent);
3731 kmemcg_id = memcg->kmemcg_id;
3732 BUG_ON(kmemcg_id < 0);
3735 * Change kmemcg_id of this cgroup and all its descendants to the
3736 * parent's id, and then move all entries from this cgroup's list_lrus
3737 * to ones of the parent. After we have finished, all list_lrus
3738 * corresponding to this cgroup are guaranteed to remain empty. The
3739 * ordering is imposed by list_lru_node->lock taken by
3740 * memcg_drain_all_list_lrus().
3742 rcu_read_lock(); /* can be called from css_free w/o cgroup_mutex */
3743 css_for_each_descendant_pre(css, &memcg->css) {
3744 child = mem_cgroup_from_css(css);
3745 BUG_ON(child->kmemcg_id != kmemcg_id);
3746 child->kmemcg_id = parent->kmemcg_id;
3747 if (!memcg->use_hierarchy)
3752 memcg_drain_all_list_lrus(kmemcg_id, parent);
3754 memcg_free_cache_id(kmemcg_id);
3757 static void memcg_free_kmem(struct mem_cgroup *memcg)
3759 /* css_alloc() failed, offlining didn't happen */
3760 if (unlikely(memcg->kmem_state == KMEM_ONLINE))
3761 memcg_offline_kmem(memcg);
3764 static int memcg_online_kmem(struct mem_cgroup *memcg)
3768 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3771 static void memcg_free_kmem(struct mem_cgroup *memcg)
3774 #endif /* CONFIG_MEMCG_KMEM */
3776 static int memcg_update_kmem_max(struct mem_cgroup *memcg,
3781 mutex_lock(&memcg_max_mutex);
3782 ret = page_counter_set_max(&memcg->kmem, max);
3783 mutex_unlock(&memcg_max_mutex);
3787 static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max)
3791 mutex_lock(&memcg_max_mutex);
3793 ret = page_counter_set_max(&memcg->tcpmem, max);
3797 if (!memcg->tcpmem_active) {
3799 * The active flag needs to be written after the static_key
3800 * update. This is what guarantees that the socket activation
3801 * function is the last one to run. See mem_cgroup_sk_alloc()
3802 * for details, and note that we don't mark any socket as
3803 * belonging to this memcg until that flag is up.
3805 * We need to do this, because static_keys will span multiple
3806 * sites, but we can't control their order. If we mark a socket
3807 * as accounted, but the accounting functions are not patched in
3808 * yet, we'll lose accounting.
3810 * We never race with the readers in mem_cgroup_sk_alloc(),
3811 * because when this value change, the code to process it is not
3814 static_branch_inc(&memcg_sockets_enabled_key);
3815 memcg->tcpmem_active = true;
3818 mutex_unlock(&memcg_max_mutex);
3823 * The user of this function is...
3826 static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
3827 char *buf, size_t nbytes, loff_t off)
3829 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3830 unsigned long nr_pages;
3833 buf = strstrip(buf);
3834 ret = page_counter_memparse(buf, "-1", &nr_pages);
3838 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3840 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3844 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3846 ret = mem_cgroup_resize_max(memcg, nr_pages, false);
3849 ret = mem_cgroup_resize_max(memcg, nr_pages, true);
3852 pr_warn_once("kmem.limit_in_bytes is deprecated and will be removed. "
3853 "Please report your usecase to linux-mm@kvack.org if you "
3854 "depend on this functionality.\n");
3855 ret = memcg_update_kmem_max(memcg, nr_pages);
3858 ret = memcg_update_tcp_max(memcg, nr_pages);
3862 case RES_SOFT_LIMIT:
3863 memcg->soft_limit = nr_pages;
3867 return ret ?: nbytes;
3870 static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
3871 size_t nbytes, loff_t off)
3873 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3874 struct page_counter *counter;
3876 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3878 counter = &memcg->memory;
3881 counter = &memcg->memsw;
3884 counter = &memcg->kmem;
3887 counter = &memcg->tcpmem;
3893 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3895 page_counter_reset_watermark(counter);
3898 counter->failcnt = 0;
3907 static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
3910 return mem_cgroup_from_css(css)->move_charge_at_immigrate;
3914 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3915 struct cftype *cft, u64 val)
3917 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3919 if (val & ~MOVE_MASK)
3923 * No kind of locking is needed in here, because ->can_attach() will
3924 * check this value once in the beginning of the process, and then carry
3925 * on with stale data. This means that changes to this value will only
3926 * affect task migrations starting after the change.
3928 memcg->move_charge_at_immigrate = val;
3932 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3933 struct cftype *cft, u64 val)
3941 #define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE))
3942 #define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON))
3943 #define LRU_ALL ((1 << NR_LRU_LISTS) - 1)
3945 static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
3946 int nid, unsigned int lru_mask, bool tree)
3948 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
3949 unsigned long nr = 0;
3952 VM_BUG_ON((unsigned)nid >= nr_node_ids);
3955 if (!(BIT(lru) & lru_mask))
3958 nr += lruvec_page_state(lruvec, NR_LRU_BASE + lru);
3960 nr += lruvec_page_state_local(lruvec, NR_LRU_BASE + lru);
3965 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
3966 unsigned int lru_mask,
3969 unsigned long nr = 0;
3973 if (!(BIT(lru) & lru_mask))
3976 nr += memcg_page_state(memcg, NR_LRU_BASE + lru);
3978 nr += memcg_page_state_local(memcg, NR_LRU_BASE + lru);
3983 static int memcg_numa_stat_show(struct seq_file *m, void *v)
3987 unsigned int lru_mask;
3990 static const struct numa_stat stats[] = {
3991 { "total", LRU_ALL },
3992 { "file", LRU_ALL_FILE },
3993 { "anon", LRU_ALL_ANON },
3994 { "unevictable", BIT(LRU_UNEVICTABLE) },
3996 const struct numa_stat *stat;
3998 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
4000 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
4001 seq_printf(m, "%s=%lu", stat->name,
4002 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
4004 for_each_node_state(nid, N_MEMORY)
4005 seq_printf(m, " N%d=%lu", nid,
4006 mem_cgroup_node_nr_lru_pages(memcg, nid,
4007 stat->lru_mask, false));
4011 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
4013 seq_printf(m, "hierarchical_%s=%lu", stat->name,
4014 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
4016 for_each_node_state(nid, N_MEMORY)
4017 seq_printf(m, " N%d=%lu", nid,
4018 mem_cgroup_node_nr_lru_pages(memcg, nid,
4019 stat->lru_mask, true));
4025 #endif /* CONFIG_NUMA */
4027 static const unsigned int memcg1_stats[] = {
4030 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4040 static const char *const memcg1_stat_names[] = {
4043 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4053 /* Universal VM events cgroup1 shows, original sort order */
4054 static const unsigned int memcg1_events[] = {
4061 static int memcg_stat_show(struct seq_file *m, void *v)
4063 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
4064 unsigned long memory, memsw;
4065 struct mem_cgroup *mi;
4068 BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats));
4070 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
4073 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
4075 nr = memcg_page_state_local(memcg, memcg1_stats[i]);
4076 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4077 if (memcg1_stats[i] == NR_ANON_THPS)
4080 seq_printf(m, "%s %lu\n", memcg1_stat_names[i], nr * PAGE_SIZE);
4083 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
4084 seq_printf(m, "%s %lu\n", vm_event_name(memcg1_events[i]),
4085 memcg_events_local(memcg, memcg1_events[i]));
4087 for (i = 0; i < NR_LRU_LISTS; i++)
4088 seq_printf(m, "%s %lu\n", lru_list_name(i),
4089 memcg_page_state_local(memcg, NR_LRU_BASE + i) *
4092 /* Hierarchical information */
4093 memory = memsw = PAGE_COUNTER_MAX;
4094 for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
4095 memory = min(memory, READ_ONCE(mi->memory.max));
4096 memsw = min(memsw, READ_ONCE(mi->memsw.max));
4098 seq_printf(m, "hierarchical_memory_limit %llu\n",
4099 (u64)memory * PAGE_SIZE);
4100 if (do_memsw_account())
4101 seq_printf(m, "hierarchical_memsw_limit %llu\n",
4102 (u64)memsw * PAGE_SIZE);
4104 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
4107 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
4109 nr = memcg_page_state(memcg, memcg1_stats[i]);
4110 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4111 if (memcg1_stats[i] == NR_ANON_THPS)
4114 seq_printf(m, "total_%s %llu\n", memcg1_stat_names[i],
4115 (u64)nr * PAGE_SIZE);
4118 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
4119 seq_printf(m, "total_%s %llu\n",
4120 vm_event_name(memcg1_events[i]),
4121 (u64)memcg_events(memcg, memcg1_events[i]));
4123 for (i = 0; i < NR_LRU_LISTS; i++)
4124 seq_printf(m, "total_%s %llu\n", lru_list_name(i),
4125 (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
4128 #ifdef CONFIG_DEBUG_VM
4131 struct mem_cgroup_per_node *mz;
4132 unsigned long anon_cost = 0;
4133 unsigned long file_cost = 0;
4135 for_each_online_pgdat(pgdat) {
4136 mz = mem_cgroup_nodeinfo(memcg, pgdat->node_id);
4138 anon_cost += mz->lruvec.anon_cost;
4139 file_cost += mz->lruvec.file_cost;
4141 seq_printf(m, "anon_cost %lu\n", anon_cost);
4142 seq_printf(m, "file_cost %lu\n", file_cost);
4149 static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
4152 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4154 return mem_cgroup_swappiness(memcg);
4157 static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
4158 struct cftype *cft, u64 val)
4160 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4166 memcg->swappiness = val;
4168 vm_swappiness = val;
4173 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4175 struct mem_cgroup_threshold_ary *t;
4176 unsigned long usage;
4181 t = rcu_dereference(memcg->thresholds.primary);
4183 t = rcu_dereference(memcg->memsw_thresholds.primary);
4188 usage = mem_cgroup_usage(memcg, swap);
4191 * current_threshold points to threshold just below or equal to usage.
4192 * If it's not true, a threshold was crossed after last
4193 * call of __mem_cgroup_threshold().
4195 i = t->current_threshold;
4198 * Iterate backward over array of thresholds starting from
4199 * current_threshold and check if a threshold is crossed.
4200 * If none of thresholds below usage is crossed, we read
4201 * only one element of the array here.
4203 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4204 eventfd_signal(t->entries[i].eventfd, 1);
4206 /* i = current_threshold + 1 */
4210 * Iterate forward over array of thresholds starting from
4211 * current_threshold+1 and check if a threshold is crossed.
4212 * If none of thresholds above usage is crossed, we read
4213 * only one element of the array here.
4215 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4216 eventfd_signal(t->entries[i].eventfd, 1);
4218 /* Update current_threshold */
4219 t->current_threshold = i - 1;
4224 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4227 __mem_cgroup_threshold(memcg, false);
4228 if (do_memsw_account())
4229 __mem_cgroup_threshold(memcg, true);
4231 memcg = parent_mem_cgroup(memcg);
4235 static int compare_thresholds(const void *a, const void *b)
4237 const struct mem_cgroup_threshold *_a = a;
4238 const struct mem_cgroup_threshold *_b = b;
4240 if (_a->threshold > _b->threshold)
4243 if (_a->threshold < _b->threshold)
4249 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
4251 struct mem_cgroup_eventfd_list *ev;
4253 spin_lock(&memcg_oom_lock);
4255 list_for_each_entry(ev, &memcg->oom_notify, list)
4256 eventfd_signal(ev->eventfd, 1);
4258 spin_unlock(&memcg_oom_lock);
4262 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
4264 struct mem_cgroup *iter;
4266 for_each_mem_cgroup_tree(iter, memcg)
4267 mem_cgroup_oom_notify_cb(iter);
4270 static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4271 struct eventfd_ctx *eventfd, const char *args, enum res_type type)
4273 struct mem_cgroup_thresholds *thresholds;
4274 struct mem_cgroup_threshold_ary *new;
4275 unsigned long threshold;
4276 unsigned long usage;
4279 ret = page_counter_memparse(args, "-1", &threshold);
4283 mutex_lock(&memcg->thresholds_lock);
4286 thresholds = &memcg->thresholds;
4287 usage = mem_cgroup_usage(memcg, false);
4288 } else if (type == _MEMSWAP) {
4289 thresholds = &memcg->memsw_thresholds;
4290 usage = mem_cgroup_usage(memcg, true);
4294 /* Check if a threshold crossed before adding a new one */
4295 if (thresholds->primary)
4296 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4298 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4300 /* Allocate memory for new array of thresholds */
4301 new = kmalloc(struct_size(new, entries, size), GFP_KERNEL);
4308 /* Copy thresholds (if any) to new array */
4309 if (thresholds->primary)
4310 memcpy(new->entries, thresholds->primary->entries,
4311 flex_array_size(new, entries, size - 1));
4313 /* Add new threshold */
4314 new->entries[size - 1].eventfd = eventfd;
4315 new->entries[size - 1].threshold = threshold;
4317 /* Sort thresholds. Registering of new threshold isn't time-critical */
4318 sort(new->entries, size, sizeof(*new->entries),
4319 compare_thresholds, NULL);
4321 /* Find current threshold */
4322 new->current_threshold = -1;
4323 for (i = 0; i < size; i++) {
4324 if (new->entries[i].threshold <= usage) {
4326 * new->current_threshold will not be used until
4327 * rcu_assign_pointer(), so it's safe to increment
4330 ++new->current_threshold;
4335 /* Free old spare buffer and save old primary buffer as spare */
4336 kfree(thresholds->spare);
4337 thresholds->spare = thresholds->primary;
4339 rcu_assign_pointer(thresholds->primary, new);
4341 /* To be sure that nobody uses thresholds */
4345 mutex_unlock(&memcg->thresholds_lock);
4350 static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4351 struct eventfd_ctx *eventfd, const char *args)
4353 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
4356 static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
4357 struct eventfd_ctx *eventfd, const char *args)
4359 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
4362 static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4363 struct eventfd_ctx *eventfd, enum res_type type)
4365 struct mem_cgroup_thresholds *thresholds;
4366 struct mem_cgroup_threshold_ary *new;
4367 unsigned long usage;
4368 int i, j, size, entries;
4370 mutex_lock(&memcg->thresholds_lock);
4373 thresholds = &memcg->thresholds;
4374 usage = mem_cgroup_usage(memcg, false);
4375 } else if (type == _MEMSWAP) {
4376 thresholds = &memcg->memsw_thresholds;
4377 usage = mem_cgroup_usage(memcg, true);
4381 if (!thresholds->primary)
4384 /* Check if a threshold crossed before removing */
4385 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4387 /* Calculate new number of threshold */
4389 for (i = 0; i < thresholds->primary->size; i++) {
4390 if (thresholds->primary->entries[i].eventfd != eventfd)
4396 new = thresholds->spare;
4398 /* If no items related to eventfd have been cleared, nothing to do */
4402 /* Set thresholds array to NULL if we don't have thresholds */
4411 /* Copy thresholds and find current threshold */
4412 new->current_threshold = -1;
4413 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4414 if (thresholds->primary->entries[i].eventfd == eventfd)
4417 new->entries[j] = thresholds->primary->entries[i];
4418 if (new->entries[j].threshold <= usage) {
4420 * new->current_threshold will not be used
4421 * until rcu_assign_pointer(), so it's safe to increment
4424 ++new->current_threshold;
4430 /* Swap primary and spare array */
4431 thresholds->spare = thresholds->primary;
4433 rcu_assign_pointer(thresholds->primary, new);
4435 /* To be sure that nobody uses thresholds */
4438 /* If all events are unregistered, free the spare array */
4440 kfree(thresholds->spare);
4441 thresholds->spare = NULL;
4444 mutex_unlock(&memcg->thresholds_lock);
4447 static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4448 struct eventfd_ctx *eventfd)
4450 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
4453 static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4454 struct eventfd_ctx *eventfd)
4456 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
4459 static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
4460 struct eventfd_ctx *eventfd, const char *args)
4462 struct mem_cgroup_eventfd_list *event;
4464 event = kmalloc(sizeof(*event), GFP_KERNEL);
4468 spin_lock(&memcg_oom_lock);
4470 event->eventfd = eventfd;
4471 list_add(&event->list, &memcg->oom_notify);
4473 /* already in OOM ? */
4474 if (memcg->under_oom)
4475 eventfd_signal(eventfd, 1);
4476 spin_unlock(&memcg_oom_lock);
4481 static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
4482 struct eventfd_ctx *eventfd)
4484 struct mem_cgroup_eventfd_list *ev, *tmp;
4486 spin_lock(&memcg_oom_lock);
4488 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
4489 if (ev->eventfd == eventfd) {
4490 list_del(&ev->list);
4495 spin_unlock(&memcg_oom_lock);
4498 static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
4500 struct mem_cgroup *memcg = mem_cgroup_from_seq(sf);
4502 seq_printf(sf, "oom_kill_disable %d\n", memcg->oom_kill_disable);
4503 seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
4504 seq_printf(sf, "oom_kill %lu\n",
4505 atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
4509 static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
4510 struct cftype *cft, u64 val)
4512 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4514 /* cannot set to root cgroup and only 0 and 1 are allowed */
4515 if (!css->parent || !((val == 0) || (val == 1)))
4518 memcg->oom_kill_disable = val;
4520 memcg_oom_recover(memcg);
4525 #ifdef CONFIG_CGROUP_WRITEBACK
4527 #include <trace/events/writeback.h>
4529 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4531 return wb_domain_init(&memcg->cgwb_domain, gfp);
4534 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4536 wb_domain_exit(&memcg->cgwb_domain);
4539 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4541 wb_domain_size_changed(&memcg->cgwb_domain);
4544 struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
4546 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4548 if (!memcg->css.parent)
4551 return &memcg->cgwb_domain;
4555 * idx can be of type enum memcg_stat_item or node_stat_item.
4556 * Keep in sync with memcg_exact_page().
4558 static unsigned long memcg_exact_page_state(struct mem_cgroup *memcg, int idx)
4560 long x = atomic_long_read(&memcg->vmstats[idx]);
4563 for_each_online_cpu(cpu)
4564 x += per_cpu_ptr(memcg->vmstats_percpu, cpu)->stat[idx];
4571 * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
4572 * @wb: bdi_writeback in question
4573 * @pfilepages: out parameter for number of file pages
4574 * @pheadroom: out parameter for number of allocatable pages according to memcg
4575 * @pdirty: out parameter for number of dirty pages
4576 * @pwriteback: out parameter for number of pages under writeback
4578 * Determine the numbers of file, headroom, dirty, and writeback pages in
4579 * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom
4580 * is a bit more involved.
4582 * A memcg's headroom is "min(max, high) - used". In the hierarchy, the
4583 * headroom is calculated as the lowest headroom of itself and the
4584 * ancestors. Note that this doesn't consider the actual amount of
4585 * available memory in the system. The caller should further cap
4586 * *@pheadroom accordingly.
4588 void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
4589 unsigned long *pheadroom, unsigned long *pdirty,
4590 unsigned long *pwriteback)
4592 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4593 struct mem_cgroup *parent;
4595 *pdirty = memcg_exact_page_state(memcg, NR_FILE_DIRTY);
4597 *pwriteback = memcg_exact_page_state(memcg, NR_WRITEBACK);
4598 *pfilepages = memcg_exact_page_state(memcg, NR_INACTIVE_FILE) +
4599 memcg_exact_page_state(memcg, NR_ACTIVE_FILE);
4600 *pheadroom = PAGE_COUNTER_MAX;
4602 while ((parent = parent_mem_cgroup(memcg))) {
4603 unsigned long ceiling = min(READ_ONCE(memcg->memory.max),
4604 READ_ONCE(memcg->memory.high));
4605 unsigned long used = page_counter_read(&memcg->memory);
4607 *pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
4613 * Foreign dirty flushing
4615 * There's an inherent mismatch between memcg and writeback. The former
4616 * trackes ownership per-page while the latter per-inode. This was a
4617 * deliberate design decision because honoring per-page ownership in the
4618 * writeback path is complicated, may lead to higher CPU and IO overheads
4619 * and deemed unnecessary given that write-sharing an inode across
4620 * different cgroups isn't a common use-case.
4622 * Combined with inode majority-writer ownership switching, this works well
4623 * enough in most cases but there are some pathological cases. For
4624 * example, let's say there are two cgroups A and B which keep writing to
4625 * different but confined parts of the same inode. B owns the inode and
4626 * A's memory is limited far below B's. A's dirty ratio can rise enough to
4627 * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
4628 * triggering background writeback. A will be slowed down without a way to
4629 * make writeback of the dirty pages happen.
4631 * Conditions like the above can lead to a cgroup getting repatedly and
4632 * severely throttled after making some progress after each
4633 * dirty_expire_interval while the underyling IO device is almost
4636 * Solving this problem completely requires matching the ownership tracking
4637 * granularities between memcg and writeback in either direction. However,
4638 * the more egregious behaviors can be avoided by simply remembering the
4639 * most recent foreign dirtying events and initiating remote flushes on
4640 * them when local writeback isn't enough to keep the memory clean enough.
4642 * The following two functions implement such mechanism. When a foreign
4643 * page - a page whose memcg and writeback ownerships don't match - is
4644 * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
4645 * bdi_writeback on the page owning memcg. When balance_dirty_pages()
4646 * decides that the memcg needs to sleep due to high dirty ratio, it calls
4647 * mem_cgroup_flush_foreign() which queues writeback on the recorded
4648 * foreign bdi_writebacks which haven't expired. Both the numbers of
4649 * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
4650 * limited to MEMCG_CGWB_FRN_CNT.
4652 * The mechanism only remembers IDs and doesn't hold any object references.
4653 * As being wrong occasionally doesn't matter, updates and accesses to the
4654 * records are lockless and racy.
4656 void mem_cgroup_track_foreign_dirty_slowpath(struct page *page,
4657 struct bdi_writeback *wb)
4659 struct mem_cgroup *memcg = page_memcg(page);
4660 struct memcg_cgwb_frn *frn;
4661 u64 now = get_jiffies_64();
4662 u64 oldest_at = now;
4666 trace_track_foreign_dirty(page, wb);
4669 * Pick the slot to use. If there is already a slot for @wb, keep
4670 * using it. If not replace the oldest one which isn't being
4673 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4674 frn = &memcg->cgwb_frn[i];
4675 if (frn->bdi_id == wb->bdi->id &&
4676 frn->memcg_id == wb->memcg_css->id)
4678 if (time_before64(frn->at, oldest_at) &&
4679 atomic_read(&frn->done.cnt) == 1) {
4681 oldest_at = frn->at;
4685 if (i < MEMCG_CGWB_FRN_CNT) {
4687 * Re-using an existing one. Update timestamp lazily to
4688 * avoid making the cacheline hot. We want them to be
4689 * reasonably up-to-date and significantly shorter than
4690 * dirty_expire_interval as that's what expires the record.
4691 * Use the shorter of 1s and dirty_expire_interval / 8.
4693 unsigned long update_intv =
4694 min_t(unsigned long, HZ,
4695 msecs_to_jiffies(dirty_expire_interval * 10) / 8);
4697 if (time_before64(frn->at, now - update_intv))
4699 } else if (oldest >= 0) {
4700 /* replace the oldest free one */
4701 frn = &memcg->cgwb_frn[oldest];
4702 frn->bdi_id = wb->bdi->id;
4703 frn->memcg_id = wb->memcg_css->id;
4708 /* issue foreign writeback flushes for recorded foreign dirtying events */
4709 void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
4711 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4712 unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
4713 u64 now = jiffies_64;
4716 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4717 struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
4720 * If the record is older than dirty_expire_interval,
4721 * writeback on it has already started. No need to kick it
4722 * off again. Also, don't start a new one if there's
4723 * already one in flight.
4725 if (time_after64(frn->at, now - intv) &&
4726 atomic_read(&frn->done.cnt) == 1) {
4728 trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
4729 cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id, 0,
4730 WB_REASON_FOREIGN_FLUSH,
4736 #else /* CONFIG_CGROUP_WRITEBACK */
4738 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4743 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4747 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4751 #endif /* CONFIG_CGROUP_WRITEBACK */
4754 * DO NOT USE IN NEW FILES.
4756 * "cgroup.event_control" implementation.
4758 * This is way over-engineered. It tries to support fully configurable
4759 * events for each user. Such level of flexibility is completely
4760 * unnecessary especially in the light of the planned unified hierarchy.
4762 * Please deprecate this and replace with something simpler if at all
4767 * Unregister event and free resources.
4769 * Gets called from workqueue.
4771 static void memcg_event_remove(struct work_struct *work)
4773 struct mem_cgroup_event *event =
4774 container_of(work, struct mem_cgroup_event, remove);
4775 struct mem_cgroup *memcg = event->memcg;
4777 remove_wait_queue(event->wqh, &event->wait);
4779 event->unregister_event(memcg, event->eventfd);
4781 /* Notify userspace the event is going away. */
4782 eventfd_signal(event->eventfd, 1);
4784 eventfd_ctx_put(event->eventfd);
4786 css_put(&memcg->css);
4790 * Gets called on EPOLLHUP on eventfd when user closes it.
4792 * Called with wqh->lock held and interrupts disabled.
4794 static int memcg_event_wake(wait_queue_entry_t *wait, unsigned mode,
4795 int sync, void *key)
4797 struct mem_cgroup_event *event =
4798 container_of(wait, struct mem_cgroup_event, wait);
4799 struct mem_cgroup *memcg = event->memcg;
4800 __poll_t flags = key_to_poll(key);
4802 if (flags & EPOLLHUP) {
4804 * If the event has been detached at cgroup removal, we
4805 * can simply return knowing the other side will cleanup
4808 * We can't race against event freeing since the other
4809 * side will require wqh->lock via remove_wait_queue(),
4812 spin_lock(&memcg->event_list_lock);
4813 if (!list_empty(&event->list)) {
4814 list_del_init(&event->list);
4816 * We are in atomic context, but cgroup_event_remove()
4817 * may sleep, so we have to call it in workqueue.
4819 schedule_work(&event->remove);
4821 spin_unlock(&memcg->event_list_lock);
4827 static void memcg_event_ptable_queue_proc(struct file *file,
4828 wait_queue_head_t *wqh, poll_table *pt)
4830 struct mem_cgroup_event *event =
4831 container_of(pt, struct mem_cgroup_event, pt);
4834 add_wait_queue(wqh, &event->wait);
4838 * DO NOT USE IN NEW FILES.
4840 * Parse input and register new cgroup event handler.
4842 * Input must be in format '<event_fd> <control_fd> <args>'.
4843 * Interpretation of args is defined by control file implementation.
4845 static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
4846 char *buf, size_t nbytes, loff_t off)
4848 struct cgroup_subsys_state *css = of_css(of);
4849 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4850 struct mem_cgroup_event *event;
4851 struct cgroup_subsys_state *cfile_css;
4852 unsigned int efd, cfd;
4859 buf = strstrip(buf);
4861 efd = simple_strtoul(buf, &endp, 10);
4866 cfd = simple_strtoul(buf, &endp, 10);
4867 if ((*endp != ' ') && (*endp != '\0'))
4871 event = kzalloc(sizeof(*event), GFP_KERNEL);
4875 event->memcg = memcg;
4876 INIT_LIST_HEAD(&event->list);
4877 init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
4878 init_waitqueue_func_entry(&event->wait, memcg_event_wake);
4879 INIT_WORK(&event->remove, memcg_event_remove);
4887 event->eventfd = eventfd_ctx_fileget(efile.file);
4888 if (IS_ERR(event->eventfd)) {
4889 ret = PTR_ERR(event->eventfd);
4896 goto out_put_eventfd;
4899 /* the process need read permission on control file */
4900 /* AV: shouldn't we check that it's been opened for read instead? */
4901 ret = inode_permission(file_inode(cfile.file), MAY_READ);
4906 * Determine the event callbacks and set them in @event. This used
4907 * to be done via struct cftype but cgroup core no longer knows
4908 * about these events. The following is crude but the whole thing
4909 * is for compatibility anyway.
4911 * DO NOT ADD NEW FILES.
4913 name = cfile.file->f_path.dentry->d_name.name;
4915 if (!strcmp(name, "memory.usage_in_bytes")) {
4916 event->register_event = mem_cgroup_usage_register_event;
4917 event->unregister_event = mem_cgroup_usage_unregister_event;
4918 } else if (!strcmp(name, "memory.oom_control")) {
4919 event->register_event = mem_cgroup_oom_register_event;
4920 event->unregister_event = mem_cgroup_oom_unregister_event;
4921 } else if (!strcmp(name, "memory.pressure_level")) {
4922 event->register_event = vmpressure_register_event;
4923 event->unregister_event = vmpressure_unregister_event;
4924 } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
4925 event->register_event = memsw_cgroup_usage_register_event;
4926 event->unregister_event = memsw_cgroup_usage_unregister_event;
4933 * Verify @cfile should belong to @css. Also, remaining events are
4934 * automatically removed on cgroup destruction but the removal is
4935 * asynchronous, so take an extra ref on @css.
4937 cfile_css = css_tryget_online_from_dir(cfile.file->f_path.dentry->d_parent,
4938 &memory_cgrp_subsys);
4940 if (IS_ERR(cfile_css))
4942 if (cfile_css != css) {
4947 ret = event->register_event(memcg, event->eventfd, buf);
4951 vfs_poll(efile.file, &event->pt);
4953 spin_lock(&memcg->event_list_lock);
4954 list_add(&event->list, &memcg->event_list);
4955 spin_unlock(&memcg->event_list_lock);
4967 eventfd_ctx_put(event->eventfd);
4976 static struct cftype mem_cgroup_legacy_files[] = {
4978 .name = "usage_in_bytes",
4979 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
4980 .read_u64 = mem_cgroup_read_u64,
4983 .name = "max_usage_in_bytes",
4984 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
4985 .write = mem_cgroup_reset,
4986 .read_u64 = mem_cgroup_read_u64,
4989 .name = "limit_in_bytes",
4990 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
4991 .write = mem_cgroup_write,
4992 .read_u64 = mem_cgroup_read_u64,
4995 .name = "soft_limit_in_bytes",
4996 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
4997 .write = mem_cgroup_write,
4998 .read_u64 = mem_cgroup_read_u64,
5002 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
5003 .write = mem_cgroup_reset,
5004 .read_u64 = mem_cgroup_read_u64,
5008 .seq_show = memcg_stat_show,
5011 .name = "force_empty",
5012 .write = mem_cgroup_force_empty_write,
5015 .name = "use_hierarchy",
5016 .write_u64 = mem_cgroup_hierarchy_write,
5017 .read_u64 = mem_cgroup_hierarchy_read,
5020 .name = "cgroup.event_control", /* XXX: for compat */
5021 .write = memcg_write_event_control,
5022 .flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE,
5025 .name = "swappiness",
5026 .read_u64 = mem_cgroup_swappiness_read,
5027 .write_u64 = mem_cgroup_swappiness_write,
5030 .name = "move_charge_at_immigrate",
5031 .read_u64 = mem_cgroup_move_charge_read,
5032 .write_u64 = mem_cgroup_move_charge_write,
5035 .name = "oom_control",
5036 .seq_show = mem_cgroup_oom_control_read,
5037 .write_u64 = mem_cgroup_oom_control_write,
5038 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
5041 .name = "pressure_level",
5045 .name = "numa_stat",
5046 .seq_show = memcg_numa_stat_show,
5050 .name = "kmem.limit_in_bytes",
5051 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
5052 .write = mem_cgroup_write,
5053 .read_u64 = mem_cgroup_read_u64,
5056 .name = "kmem.usage_in_bytes",
5057 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
5058 .read_u64 = mem_cgroup_read_u64,
5061 .name = "kmem.failcnt",
5062 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
5063 .write = mem_cgroup_reset,
5064 .read_u64 = mem_cgroup_read_u64,
5067 .name = "kmem.max_usage_in_bytes",
5068 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
5069 .write = mem_cgroup_reset,
5070 .read_u64 = mem_cgroup_read_u64,
5072 #if defined(CONFIG_MEMCG_KMEM) && \
5073 (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG))
5075 .name = "kmem.slabinfo",
5076 .seq_show = memcg_slab_show,
5080 .name = "kmem.tcp.limit_in_bytes",
5081 .private = MEMFILE_PRIVATE(_TCP, RES_LIMIT),
5082 .write = mem_cgroup_write,
5083 .read_u64 = mem_cgroup_read_u64,
5086 .name = "kmem.tcp.usage_in_bytes",
5087 .private = MEMFILE_PRIVATE(_TCP, RES_USAGE),
5088 .read_u64 = mem_cgroup_read_u64,
5091 .name = "kmem.tcp.failcnt",
5092 .private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT),
5093 .write = mem_cgroup_reset,
5094 .read_u64 = mem_cgroup_read_u64,
5097 .name = "kmem.tcp.max_usage_in_bytes",
5098 .private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE),
5099 .write = mem_cgroup_reset,
5100 .read_u64 = mem_cgroup_read_u64,
5102 { }, /* terminate */
5106 * Private memory cgroup IDR
5108 * Swap-out records and page cache shadow entries need to store memcg
5109 * references in constrained space, so we maintain an ID space that is
5110 * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
5111 * memory-controlled cgroups to 64k.
5113 * However, there usually are many references to the offline CSS after
5114 * the cgroup has been destroyed, such as page cache or reclaimable
5115 * slab objects, that don't need to hang on to the ID. We want to keep
5116 * those dead CSS from occupying IDs, or we might quickly exhaust the
5117 * relatively small ID space and prevent the creation of new cgroups
5118 * even when there are much fewer than 64k cgroups - possibly none.
5120 * Maintain a private 16-bit ID space for memcg, and allow the ID to
5121 * be freed and recycled when it's no longer needed, which is usually
5122 * when the CSS is offlined.
5124 * The only exception to that are records of swapped out tmpfs/shmem
5125 * pages that need to be attributed to live ancestors on swapin. But
5126 * those references are manageable from userspace.
5129 static DEFINE_IDR(mem_cgroup_idr);
5131 static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
5133 if (memcg->id.id > 0) {
5134 idr_remove(&mem_cgroup_idr, memcg->id.id);
5139 static void __maybe_unused mem_cgroup_id_get_many(struct mem_cgroup *memcg,
5142 refcount_add(n, &memcg->id.ref);
5145 static void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
5147 if (refcount_sub_and_test(n, &memcg->id.ref)) {
5148 mem_cgroup_id_remove(memcg);
5150 /* Memcg ID pins CSS */
5151 css_put(&memcg->css);
5155 static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
5157 mem_cgroup_id_put_many(memcg, 1);
5161 * mem_cgroup_from_id - look up a memcg from a memcg id
5162 * @id: the memcg id to look up
5164 * Caller must hold rcu_read_lock().
5166 struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
5168 WARN_ON_ONCE(!rcu_read_lock_held());
5169 return idr_find(&mem_cgroup_idr, id);
5172 static int alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5174 struct mem_cgroup_per_node *pn;
5177 * This routine is called against possible nodes.
5178 * But it's BUG to call kmalloc() against offline node.
5180 * TODO: this routine can waste much memory for nodes which will
5181 * never be onlined. It's better to use memory hotplug callback
5184 if (!node_state(node, N_NORMAL_MEMORY))
5186 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
5190 pn->lruvec_stat_local = alloc_percpu_gfp(struct lruvec_stat,
5191 GFP_KERNEL_ACCOUNT);
5192 if (!pn->lruvec_stat_local) {
5197 pn->lruvec_stat_cpu = alloc_percpu_gfp(struct lruvec_stat,
5198 GFP_KERNEL_ACCOUNT);
5199 if (!pn->lruvec_stat_cpu) {
5200 free_percpu(pn->lruvec_stat_local);
5205 lruvec_init(&pn->lruvec);
5206 pn->usage_in_excess = 0;
5207 pn->on_tree = false;
5210 memcg->nodeinfo[node] = pn;
5214 static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5216 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
5221 free_percpu(pn->lruvec_stat_cpu);
5222 free_percpu(pn->lruvec_stat_local);
5226 static void __mem_cgroup_free(struct mem_cgroup *memcg)
5231 free_mem_cgroup_per_node_info(memcg, node);
5232 free_percpu(memcg->vmstats_percpu);
5233 free_percpu(memcg->vmstats_local);
5237 static void mem_cgroup_free(struct mem_cgroup *memcg)
5239 memcg_wb_domain_exit(memcg);
5241 * Flush percpu vmstats and vmevents to guarantee the value correctness
5242 * on parent's and all ancestor levels.
5244 memcg_flush_percpu_vmstats(memcg);
5245 memcg_flush_percpu_vmevents(memcg);
5246 __mem_cgroup_free(memcg);
5249 static struct mem_cgroup *mem_cgroup_alloc(void)
5251 struct mem_cgroup *memcg;
5254 int __maybe_unused i;
5255 long error = -ENOMEM;
5257 size = sizeof(struct mem_cgroup);
5258 size += nr_node_ids * sizeof(struct mem_cgroup_per_node *);
5260 memcg = kzalloc(size, GFP_KERNEL);
5262 return ERR_PTR(error);
5264 memcg->id.id = idr_alloc(&mem_cgroup_idr, NULL,
5265 1, MEM_CGROUP_ID_MAX,
5267 if (memcg->id.id < 0) {
5268 error = memcg->id.id;
5272 memcg->vmstats_local = alloc_percpu_gfp(struct memcg_vmstats_percpu,
5273 GFP_KERNEL_ACCOUNT);
5274 if (!memcg->vmstats_local)
5277 memcg->vmstats_percpu = alloc_percpu_gfp(struct memcg_vmstats_percpu,
5278 GFP_KERNEL_ACCOUNT);
5279 if (!memcg->vmstats_percpu)
5283 if (alloc_mem_cgroup_per_node_info(memcg, node))
5286 if (memcg_wb_domain_init(memcg, GFP_KERNEL))
5289 INIT_WORK(&memcg->high_work, high_work_func);
5290 INIT_LIST_HEAD(&memcg->oom_notify);
5291 mutex_init(&memcg->thresholds_lock);
5292 spin_lock_init(&memcg->move_lock);
5293 vmpressure_init(&memcg->vmpressure);
5294 INIT_LIST_HEAD(&memcg->event_list);
5295 spin_lock_init(&memcg->event_list_lock);
5296 memcg->socket_pressure = jiffies;
5297 #ifdef CONFIG_MEMCG_KMEM
5298 memcg->kmemcg_id = -1;
5299 INIT_LIST_HEAD(&memcg->objcg_list);
5301 #ifdef CONFIG_CGROUP_WRITEBACK
5302 INIT_LIST_HEAD(&memcg->cgwb_list);
5303 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5304 memcg->cgwb_frn[i].done =
5305 __WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
5307 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5308 spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
5309 INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
5310 memcg->deferred_split_queue.split_queue_len = 0;
5312 idr_replace(&mem_cgroup_idr, memcg, memcg->id.id);
5315 mem_cgroup_id_remove(memcg);
5316 __mem_cgroup_free(memcg);
5317 return ERR_PTR(error);
5320 static struct cgroup_subsys_state * __ref
5321 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
5323 struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
5324 struct mem_cgroup *memcg, *old_memcg;
5325 long error = -ENOMEM;
5327 old_memcg = set_active_memcg(parent);
5328 memcg = mem_cgroup_alloc();
5329 set_active_memcg(old_memcg);
5331 return ERR_CAST(memcg);
5333 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5334 memcg->soft_limit = PAGE_COUNTER_MAX;
5335 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5337 memcg->swappiness = mem_cgroup_swappiness(parent);
5338 memcg->oom_kill_disable = parent->oom_kill_disable;
5341 page_counter_init(&memcg->memory, NULL);
5342 page_counter_init(&memcg->swap, NULL);
5343 page_counter_init(&memcg->kmem, NULL);
5344 page_counter_init(&memcg->tcpmem, NULL);
5345 } else if (parent->use_hierarchy) {
5346 memcg->use_hierarchy = true;
5347 page_counter_init(&memcg->memory, &parent->memory);
5348 page_counter_init(&memcg->swap, &parent->swap);
5349 page_counter_init(&memcg->kmem, &parent->kmem);
5350 page_counter_init(&memcg->tcpmem, &parent->tcpmem);
5352 page_counter_init(&memcg->memory, &root_mem_cgroup->memory);
5353 page_counter_init(&memcg->swap, &root_mem_cgroup->swap);
5354 page_counter_init(&memcg->kmem, &root_mem_cgroup->kmem);
5355 page_counter_init(&memcg->tcpmem, &root_mem_cgroup->tcpmem);
5357 * Deeper hierachy with use_hierarchy == false doesn't make
5358 * much sense so let cgroup subsystem know about this
5359 * unfortunate state in our controller.
5361 if (parent != root_mem_cgroup)
5362 memory_cgrp_subsys.broken_hierarchy = true;
5365 /* The following stuff does not apply to the root */
5367 root_mem_cgroup = memcg;
5371 error = memcg_online_kmem(memcg);
5375 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5376 static_branch_inc(&memcg_sockets_enabled_key);
5380 mem_cgroup_id_remove(memcg);
5381 mem_cgroup_free(memcg);
5382 return ERR_PTR(error);
5385 static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
5387 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5390 * A memcg must be visible for memcg_expand_shrinker_maps()
5391 * by the time the maps are allocated. So, we allocate maps
5392 * here, when for_each_mem_cgroup() can't skip it.
5394 if (memcg_alloc_shrinker_maps(memcg)) {
5395 mem_cgroup_id_remove(memcg);
5399 /* Online state pins memcg ID, memcg ID pins CSS */
5400 refcount_set(&memcg->id.ref, 1);
5405 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
5407 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5408 struct mem_cgroup_event *event, *tmp;
5411 * Unregister events and notify userspace.
5412 * Notify userspace about cgroup removing only after rmdir of cgroup
5413 * directory to avoid race between userspace and kernelspace.
5415 spin_lock(&memcg->event_list_lock);
5416 list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
5417 list_del_init(&event->list);
5418 schedule_work(&event->remove);
5420 spin_unlock(&memcg->event_list_lock);
5422 page_counter_set_min(&memcg->memory, 0);
5423 page_counter_set_low(&memcg->memory, 0);
5425 memcg_offline_kmem(memcg);
5426 wb_memcg_offline(memcg);
5428 drain_all_stock(memcg);
5430 mem_cgroup_id_put(memcg);
5433 static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
5435 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5437 invalidate_reclaim_iterators(memcg);
5440 static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
5442 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5443 int __maybe_unused i;
5445 #ifdef CONFIG_CGROUP_WRITEBACK
5446 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5447 wb_wait_for_completion(&memcg->cgwb_frn[i].done);
5449 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5450 static_branch_dec(&memcg_sockets_enabled_key);
5452 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg->tcpmem_active)
5453 static_branch_dec(&memcg_sockets_enabled_key);
5455 vmpressure_cleanup(&memcg->vmpressure);
5456 cancel_work_sync(&memcg->high_work);
5457 mem_cgroup_remove_from_trees(memcg);
5458 memcg_free_shrinker_maps(memcg);
5459 memcg_free_kmem(memcg);
5460 mem_cgroup_free(memcg);
5464 * mem_cgroup_css_reset - reset the states of a mem_cgroup
5465 * @css: the target css
5467 * Reset the states of the mem_cgroup associated with @css. This is
5468 * invoked when the userland requests disabling on the default hierarchy
5469 * but the memcg is pinned through dependency. The memcg should stop
5470 * applying policies and should revert to the vanilla state as it may be
5471 * made visible again.
5473 * The current implementation only resets the essential configurations.
5474 * This needs to be expanded to cover all the visible parts.
5476 static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
5478 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5480 page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
5481 page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
5482 page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
5483 page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
5484 page_counter_set_min(&memcg->memory, 0);
5485 page_counter_set_low(&memcg->memory, 0);
5486 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5487 memcg->soft_limit = PAGE_COUNTER_MAX;
5488 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5489 memcg_wb_domain_size_changed(memcg);
5493 /* Handlers for move charge at task migration. */
5494 static int mem_cgroup_do_precharge(unsigned long count)
5498 /* Try a single bulk charge without reclaim first, kswapd may wake */
5499 ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count);
5501 mc.precharge += count;
5505 /* Try charges one by one with reclaim, but do not retry */
5507 ret = try_charge(mc.to, GFP_KERNEL | __GFP_NORETRY, 1);
5521 enum mc_target_type {
5528 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5529 unsigned long addr, pte_t ptent)
5531 struct page *page = vm_normal_page(vma, addr, ptent);
5533 if (!page || !page_mapped(page))
5535 if (PageAnon(page)) {
5536 if (!(mc.flags & MOVE_ANON))
5539 if (!(mc.flags & MOVE_FILE))
5542 if (!get_page_unless_zero(page))
5548 #if defined(CONFIG_SWAP) || defined(CONFIG_DEVICE_PRIVATE)
5549 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5550 pte_t ptent, swp_entry_t *entry)
5552 struct page *page = NULL;
5553 swp_entry_t ent = pte_to_swp_entry(ptent);
5555 if (!(mc.flags & MOVE_ANON))
5559 * Handle MEMORY_DEVICE_PRIVATE which are ZONE_DEVICE page belonging to
5560 * a device and because they are not accessible by CPU they are store
5561 * as special swap entry in the CPU page table.
5563 if (is_device_private_entry(ent)) {
5564 page = device_private_entry_to_page(ent);
5566 * MEMORY_DEVICE_PRIVATE means ZONE_DEVICE page and which have
5567 * a refcount of 1 when free (unlike normal page)
5569 if (!page_ref_add_unless(page, 1, 1))
5574 if (non_swap_entry(ent))
5578 * Because lookup_swap_cache() updates some statistics counter,
5579 * we call find_get_page() with swapper_space directly.
5581 page = find_get_page(swap_address_space(ent), swp_offset(ent));
5582 entry->val = ent.val;
5587 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5588 pte_t ptent, swp_entry_t *entry)
5594 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5595 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5597 if (!vma->vm_file) /* anonymous vma */
5599 if (!(mc.flags & MOVE_FILE))
5602 /* page is moved even if it's not RSS of this task(page-faulted). */
5603 /* shmem/tmpfs may report page out on swap: account for that too. */
5604 return find_get_incore_page(vma->vm_file->f_mapping,
5605 linear_page_index(vma, addr));
5609 * mem_cgroup_move_account - move account of the page
5611 * @compound: charge the page as compound or small page
5612 * @from: mem_cgroup which the page is moved from.
5613 * @to: mem_cgroup which the page is moved to. @from != @to.
5615 * The caller must make sure the page is not on LRU (isolate_page() is useful.)
5617 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
5620 static int mem_cgroup_move_account(struct page *page,
5622 struct mem_cgroup *from,
5623 struct mem_cgroup *to)
5625 struct lruvec *from_vec, *to_vec;
5626 struct pglist_data *pgdat;
5627 unsigned int nr_pages = compound ? thp_nr_pages(page) : 1;
5630 VM_BUG_ON(from == to);
5631 VM_BUG_ON_PAGE(PageLRU(page), page);
5632 VM_BUG_ON(compound && !PageTransHuge(page));
5635 * Prevent mem_cgroup_migrate() from looking at
5636 * page's memory cgroup of its source page while we change it.
5639 if (!trylock_page(page))
5643 if (page_memcg(page) != from)
5646 pgdat = page_pgdat(page);
5647 from_vec = mem_cgroup_lruvec(from, pgdat);
5648 to_vec = mem_cgroup_lruvec(to, pgdat);
5650 lock_page_memcg(page);
5652 if (PageAnon(page)) {
5653 if (page_mapped(page)) {
5654 __mod_lruvec_state(from_vec, NR_ANON_MAPPED, -nr_pages);
5655 __mod_lruvec_state(to_vec, NR_ANON_MAPPED, nr_pages);
5656 if (PageTransHuge(page)) {
5657 __mod_lruvec_state(from_vec, NR_ANON_THPS,
5659 __mod_lruvec_state(to_vec, NR_ANON_THPS,
5665 __mod_lruvec_state(from_vec, NR_FILE_PAGES, -nr_pages);
5666 __mod_lruvec_state(to_vec, NR_FILE_PAGES, nr_pages);
5668 if (PageSwapBacked(page)) {
5669 __mod_lruvec_state(from_vec, NR_SHMEM, -nr_pages);
5670 __mod_lruvec_state(to_vec, NR_SHMEM, nr_pages);
5673 if (page_mapped(page)) {
5674 __mod_lruvec_state(from_vec, NR_FILE_MAPPED, -nr_pages);
5675 __mod_lruvec_state(to_vec, NR_FILE_MAPPED, nr_pages);
5678 if (PageDirty(page)) {
5679 struct address_space *mapping = page_mapping(page);
5681 if (mapping_can_writeback(mapping)) {
5682 __mod_lruvec_state(from_vec, NR_FILE_DIRTY,
5684 __mod_lruvec_state(to_vec, NR_FILE_DIRTY,
5690 if (PageWriteback(page)) {
5691 __mod_lruvec_state(from_vec, NR_WRITEBACK, -nr_pages);
5692 __mod_lruvec_state(to_vec, NR_WRITEBACK, nr_pages);
5696 * All state has been migrated, let's switch to the new memcg.
5698 * It is safe to change page's memcg here because the page
5699 * is referenced, charged, isolated, and locked: we can't race
5700 * with (un)charging, migration, LRU putback, or anything else
5701 * that would rely on a stable page's memory cgroup.
5703 * Note that lock_page_memcg is a memcg lock, not a page lock,
5704 * to save space. As soon as we switch page's memory cgroup to a
5705 * new memcg that isn't locked, the above state can change
5706 * concurrently again. Make sure we're truly done with it.
5711 css_put(&from->css);
5713 page->memcg_data = (unsigned long)to;
5715 __unlock_page_memcg(from);
5719 local_irq_disable();
5720 mem_cgroup_charge_statistics(to, page, nr_pages);
5721 memcg_check_events(to, page);
5722 mem_cgroup_charge_statistics(from, page, -nr_pages);
5723 memcg_check_events(from, page);
5732 * get_mctgt_type - get target type of moving charge
5733 * @vma: the vma the pte to be checked belongs
5734 * @addr: the address corresponding to the pte to be checked
5735 * @ptent: the pte to be checked
5736 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5739 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5740 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5741 * move charge. if @target is not NULL, the page is stored in target->page
5742 * with extra refcnt got(Callers should handle it).
5743 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5744 * target for charge migration. if @target is not NULL, the entry is stored
5746 * 3(MC_TARGET_DEVICE): like MC_TARGET_PAGE but page is MEMORY_DEVICE_PRIVATE
5747 * (so ZONE_DEVICE page and thus not on the lru).
5748 * For now we such page is charge like a regular page would be as for all
5749 * intent and purposes it is just special memory taking the place of a
5752 * See Documentations/vm/hmm.txt and include/linux/hmm.h
5754 * Called with pte lock held.
5757 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
5758 unsigned long addr, pte_t ptent, union mc_target *target)
5760 struct page *page = NULL;
5761 enum mc_target_type ret = MC_TARGET_NONE;
5762 swp_entry_t ent = { .val = 0 };
5764 if (pte_present(ptent))
5765 page = mc_handle_present_pte(vma, addr, ptent);
5766 else if (is_swap_pte(ptent))
5767 page = mc_handle_swap_pte(vma, ptent, &ent);
5768 else if (pte_none(ptent))
5769 page = mc_handle_file_pte(vma, addr, ptent, &ent);
5771 if (!page && !ent.val)
5775 * Do only loose check w/o serialization.
5776 * mem_cgroup_move_account() checks the page is valid or
5777 * not under LRU exclusion.
5779 if (page_memcg(page) == mc.from) {
5780 ret = MC_TARGET_PAGE;
5781 if (is_device_private_page(page))
5782 ret = MC_TARGET_DEVICE;
5784 target->page = page;
5786 if (!ret || !target)
5790 * There is a swap entry and a page doesn't exist or isn't charged.
5791 * But we cannot move a tail-page in a THP.
5793 if (ent.val && !ret && (!page || !PageTransCompound(page)) &&
5794 mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
5795 ret = MC_TARGET_SWAP;
5802 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5804 * We don't consider PMD mapped swapping or file mapped pages because THP does
5805 * not support them for now.
5806 * Caller should make sure that pmd_trans_huge(pmd) is true.
5808 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5809 unsigned long addr, pmd_t pmd, union mc_target *target)
5811 struct page *page = NULL;
5812 enum mc_target_type ret = MC_TARGET_NONE;
5814 if (unlikely(is_swap_pmd(pmd))) {
5815 VM_BUG_ON(thp_migration_supported() &&
5816 !is_pmd_migration_entry(pmd));
5819 page = pmd_page(pmd);
5820 VM_BUG_ON_PAGE(!page || !PageHead(page), page);
5821 if (!(mc.flags & MOVE_ANON))
5823 if (page_memcg(page) == mc.from) {
5824 ret = MC_TARGET_PAGE;
5827 target->page = page;
5833 static inline 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 return MC_TARGET_NONE;
5840 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5841 unsigned long addr, unsigned long end,
5842 struct mm_walk *walk)
5844 struct vm_area_struct *vma = walk->vma;
5848 ptl = pmd_trans_huge_lock(pmd, vma);
5851 * Note their can not be MC_TARGET_DEVICE for now as we do not
5852 * support transparent huge page with MEMORY_DEVICE_PRIVATE but
5853 * this might change.
5855 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
5856 mc.precharge += HPAGE_PMD_NR;
5861 if (pmd_trans_unstable(pmd))
5863 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5864 for (; addr != end; pte++, addr += PAGE_SIZE)
5865 if (get_mctgt_type(vma, addr, *pte, NULL))
5866 mc.precharge++; /* increment precharge temporarily */
5867 pte_unmap_unlock(pte - 1, ptl);
5873 static const struct mm_walk_ops precharge_walk_ops = {
5874 .pmd_entry = mem_cgroup_count_precharge_pte_range,
5877 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5879 unsigned long precharge;
5882 walk_page_range(mm, 0, mm->highest_vm_end, &precharge_walk_ops, NULL);
5883 mmap_read_unlock(mm);
5885 precharge = mc.precharge;
5891 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5893 unsigned long precharge = mem_cgroup_count_precharge(mm);
5895 VM_BUG_ON(mc.moving_task);
5896 mc.moving_task = current;
5897 return mem_cgroup_do_precharge(precharge);
5900 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5901 static void __mem_cgroup_clear_mc(void)
5903 struct mem_cgroup *from = mc.from;
5904 struct mem_cgroup *to = mc.to;
5906 /* we must uncharge all the leftover precharges from mc.to */
5908 cancel_charge(mc.to, mc.precharge);
5912 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5913 * we must uncharge here.
5915 if (mc.moved_charge) {
5916 cancel_charge(mc.from, mc.moved_charge);
5917 mc.moved_charge = 0;
5919 /* we must fixup refcnts and charges */
5920 if (mc.moved_swap) {
5921 /* uncharge swap account from the old cgroup */
5922 if (!mem_cgroup_is_root(mc.from))
5923 page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
5925 mem_cgroup_id_put_many(mc.from, mc.moved_swap);
5928 * we charged both to->memory and to->memsw, so we
5929 * should uncharge to->memory.
5931 if (!mem_cgroup_is_root(mc.to))
5932 page_counter_uncharge(&mc.to->memory, mc.moved_swap);
5936 memcg_oom_recover(from);
5937 memcg_oom_recover(to);
5938 wake_up_all(&mc.waitq);
5941 static void mem_cgroup_clear_mc(void)
5943 struct mm_struct *mm = mc.mm;
5946 * we must clear moving_task before waking up waiters at the end of
5949 mc.moving_task = NULL;
5950 __mem_cgroup_clear_mc();
5951 spin_lock(&mc.lock);
5955 spin_unlock(&mc.lock);
5960 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
5962 struct cgroup_subsys_state *css;
5963 struct mem_cgroup *memcg = NULL; /* unneeded init to make gcc happy */
5964 struct mem_cgroup *from;
5965 struct task_struct *leader, *p;
5966 struct mm_struct *mm;
5967 unsigned long move_flags;
5970 /* charge immigration isn't supported on the default hierarchy */
5971 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
5975 * Multi-process migrations only happen on the default hierarchy
5976 * where charge immigration is not used. Perform charge
5977 * immigration if @tset contains a leader and whine if there are
5981 cgroup_taskset_for_each_leader(leader, css, tset) {
5984 memcg = mem_cgroup_from_css(css);
5990 * We are now commited to this value whatever it is. Changes in this
5991 * tunable will only affect upcoming migrations, not the current one.
5992 * So we need to save it, and keep it going.
5994 move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
5998 from = mem_cgroup_from_task(p);
6000 VM_BUG_ON(from == memcg);
6002 mm = get_task_mm(p);
6005 /* We move charges only when we move a owner of the mm */
6006 if (mm->owner == p) {
6009 VM_BUG_ON(mc.precharge);
6010 VM_BUG_ON(mc.moved_charge);
6011 VM_BUG_ON(mc.moved_swap);
6013 spin_lock(&mc.lock);
6017 mc.flags = move_flags;
6018 spin_unlock(&mc.lock);
6019 /* We set mc.moving_task later */
6021 ret = mem_cgroup_precharge_mc(mm);
6023 mem_cgroup_clear_mc();
6030 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6033 mem_cgroup_clear_mc();
6036 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
6037 unsigned long addr, unsigned long end,
6038 struct mm_walk *walk)
6041 struct vm_area_struct *vma = walk->vma;
6044 enum mc_target_type target_type;
6045 union mc_target target;
6048 ptl = pmd_trans_huge_lock(pmd, vma);
6050 if (mc.precharge < HPAGE_PMD_NR) {
6054 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
6055 if (target_type == MC_TARGET_PAGE) {
6057 if (!isolate_lru_page(page)) {
6058 if (!mem_cgroup_move_account(page, true,
6060 mc.precharge -= HPAGE_PMD_NR;
6061 mc.moved_charge += HPAGE_PMD_NR;
6063 putback_lru_page(page);
6066 } else if (target_type == MC_TARGET_DEVICE) {
6068 if (!mem_cgroup_move_account(page, true,
6070 mc.precharge -= HPAGE_PMD_NR;
6071 mc.moved_charge += HPAGE_PMD_NR;
6079 if (pmd_trans_unstable(pmd))
6082 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6083 for (; addr != end; addr += PAGE_SIZE) {
6084 pte_t ptent = *(pte++);
6085 bool device = false;
6091 switch (get_mctgt_type(vma, addr, ptent, &target)) {
6092 case MC_TARGET_DEVICE:
6095 case MC_TARGET_PAGE:
6098 * We can have a part of the split pmd here. Moving it
6099 * can be done but it would be too convoluted so simply
6100 * ignore such a partial THP and keep it in original
6101 * memcg. There should be somebody mapping the head.
6103 if (PageTransCompound(page))
6105 if (!device && isolate_lru_page(page))
6107 if (!mem_cgroup_move_account(page, false,
6110 /* we uncharge from mc.from later. */
6114 putback_lru_page(page);
6115 put: /* get_mctgt_type() gets the page */
6118 case MC_TARGET_SWAP:
6120 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
6122 mem_cgroup_id_get_many(mc.to, 1);
6123 /* we fixup other refcnts and charges later. */
6131 pte_unmap_unlock(pte - 1, ptl);
6136 * We have consumed all precharges we got in can_attach().
6137 * We try charge one by one, but don't do any additional
6138 * charges to mc.to if we have failed in charge once in attach()
6141 ret = mem_cgroup_do_precharge(1);
6149 static const struct mm_walk_ops charge_walk_ops = {
6150 .pmd_entry = mem_cgroup_move_charge_pte_range,
6153 static void mem_cgroup_move_charge(void)
6155 lru_add_drain_all();
6157 * Signal lock_page_memcg() to take the memcg's move_lock
6158 * while we're moving its pages to another memcg. Then wait
6159 * for already started RCU-only updates to finish.
6161 atomic_inc(&mc.from->moving_account);
6164 if (unlikely(!mmap_read_trylock(mc.mm))) {
6166 * Someone who are holding the mmap_lock might be waiting in
6167 * waitq. So we cancel all extra charges, wake up all waiters,
6168 * and retry. Because we cancel precharges, we might not be able
6169 * to move enough charges, but moving charge is a best-effort
6170 * feature anyway, so it wouldn't be a big problem.
6172 __mem_cgroup_clear_mc();
6177 * When we have consumed all precharges and failed in doing
6178 * additional charge, the page walk just aborts.
6180 walk_page_range(mc.mm, 0, mc.mm->highest_vm_end, &charge_walk_ops,
6183 mmap_read_unlock(mc.mm);
6184 atomic_dec(&mc.from->moving_account);
6187 static void mem_cgroup_move_task(void)
6190 mem_cgroup_move_charge();
6191 mem_cgroup_clear_mc();
6194 #else /* !CONFIG_MMU */
6195 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
6199 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6202 static void mem_cgroup_move_task(void)
6208 * Cgroup retains root cgroups across [un]mount cycles making it necessary
6209 * to verify whether we're attached to the default hierarchy on each mount
6212 static void mem_cgroup_bind(struct cgroup_subsys_state *root_css)
6215 * use_hierarchy is forced on the default hierarchy. cgroup core
6216 * guarantees that @root doesn't have any children, so turning it
6217 * on for the root memcg is enough.
6219 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
6220 root_mem_cgroup->use_hierarchy = true;
6222 root_mem_cgroup->use_hierarchy = false;
6225 static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
6227 if (value == PAGE_COUNTER_MAX)
6228 seq_puts(m, "max\n");
6230 seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
6235 static u64 memory_current_read(struct cgroup_subsys_state *css,
6238 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6240 return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
6243 static int memory_min_show(struct seq_file *m, void *v)
6245 return seq_puts_memcg_tunable(m,
6246 READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
6249 static ssize_t memory_min_write(struct kernfs_open_file *of,
6250 char *buf, size_t nbytes, loff_t off)
6252 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6256 buf = strstrip(buf);
6257 err = page_counter_memparse(buf, "max", &min);
6261 page_counter_set_min(&memcg->memory, min);
6266 static int memory_low_show(struct seq_file *m, void *v)
6268 return seq_puts_memcg_tunable(m,
6269 READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
6272 static ssize_t memory_low_write(struct kernfs_open_file *of,
6273 char *buf, size_t nbytes, loff_t off)
6275 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6279 buf = strstrip(buf);
6280 err = page_counter_memparse(buf, "max", &low);
6284 page_counter_set_low(&memcg->memory, low);
6289 static int memory_high_show(struct seq_file *m, void *v)
6291 return seq_puts_memcg_tunable(m,
6292 READ_ONCE(mem_cgroup_from_seq(m)->memory.high));
6295 static ssize_t memory_high_write(struct kernfs_open_file *of,
6296 char *buf, size_t nbytes, loff_t off)
6298 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6299 unsigned int nr_retries = MAX_RECLAIM_RETRIES;
6300 bool drained = false;
6304 buf = strstrip(buf);
6305 err = page_counter_memparse(buf, "max", &high);
6310 unsigned long nr_pages = page_counter_read(&memcg->memory);
6311 unsigned long reclaimed;
6313 if (nr_pages <= high)
6316 if (signal_pending(current))
6320 drain_all_stock(memcg);
6325 reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
6328 if (!reclaimed && !nr_retries--)
6332 page_counter_set_high(&memcg->memory, high);
6334 memcg_wb_domain_size_changed(memcg);
6339 static int memory_max_show(struct seq_file *m, void *v)
6341 return seq_puts_memcg_tunable(m,
6342 READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
6345 static ssize_t memory_max_write(struct kernfs_open_file *of,
6346 char *buf, size_t nbytes, loff_t off)
6348 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6349 unsigned int nr_reclaims = MAX_RECLAIM_RETRIES;
6350 bool drained = false;
6354 buf = strstrip(buf);
6355 err = page_counter_memparse(buf, "max", &max);
6359 xchg(&memcg->memory.max, max);
6362 unsigned long nr_pages = page_counter_read(&memcg->memory);
6364 if (nr_pages <= max)
6367 if (signal_pending(current))
6371 drain_all_stock(memcg);
6377 if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
6383 memcg_memory_event(memcg, MEMCG_OOM);
6384 if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
6388 memcg_wb_domain_size_changed(memcg);
6392 static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
6394 seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
6395 seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
6396 seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
6397 seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
6398 seq_printf(m, "oom_kill %lu\n",
6399 atomic_long_read(&events[MEMCG_OOM_KILL]));
6402 static int memory_events_show(struct seq_file *m, void *v)
6404 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6406 __memory_events_show(m, memcg->memory_events);
6410 static int memory_events_local_show(struct seq_file *m, void *v)
6412 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6414 __memory_events_show(m, memcg->memory_events_local);
6418 static int memory_stat_show(struct seq_file *m, void *v)
6420 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6423 buf = memory_stat_format(memcg);
6432 static int memory_numa_stat_show(struct seq_file *m, void *v)
6435 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6437 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
6440 if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS)
6443 seq_printf(m, "%s", memory_stats[i].name);
6444 for_each_node_state(nid, N_MEMORY) {
6446 struct lruvec *lruvec;
6448 lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
6449 size = lruvec_page_state(lruvec, memory_stats[i].idx);
6450 size *= memory_stats[i].ratio;
6451 seq_printf(m, " N%d=%llu", nid, size);
6460 static int memory_oom_group_show(struct seq_file *m, void *v)
6462 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6464 seq_printf(m, "%d\n", memcg->oom_group);
6469 static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
6470 char *buf, size_t nbytes, loff_t off)
6472 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6475 buf = strstrip(buf);
6479 ret = kstrtoint(buf, 0, &oom_group);
6483 if (oom_group != 0 && oom_group != 1)
6486 memcg->oom_group = oom_group;
6491 static struct cftype memory_files[] = {
6494 .flags = CFTYPE_NOT_ON_ROOT,
6495 .read_u64 = memory_current_read,
6499 .flags = CFTYPE_NOT_ON_ROOT,
6500 .seq_show = memory_min_show,
6501 .write = memory_min_write,
6505 .flags = CFTYPE_NOT_ON_ROOT,
6506 .seq_show = memory_low_show,
6507 .write = memory_low_write,
6511 .flags = CFTYPE_NOT_ON_ROOT,
6512 .seq_show = memory_high_show,
6513 .write = memory_high_write,
6517 .flags = CFTYPE_NOT_ON_ROOT,
6518 .seq_show = memory_max_show,
6519 .write = memory_max_write,
6523 .flags = CFTYPE_NOT_ON_ROOT,
6524 .file_offset = offsetof(struct mem_cgroup, events_file),
6525 .seq_show = memory_events_show,
6528 .name = "events.local",
6529 .flags = CFTYPE_NOT_ON_ROOT,
6530 .file_offset = offsetof(struct mem_cgroup, events_local_file),
6531 .seq_show = memory_events_local_show,
6535 .seq_show = memory_stat_show,
6539 .name = "numa_stat",
6540 .seq_show = memory_numa_stat_show,
6544 .name = "oom.group",
6545 .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
6546 .seq_show = memory_oom_group_show,
6547 .write = memory_oom_group_write,
6552 struct cgroup_subsys memory_cgrp_subsys = {
6553 .css_alloc = mem_cgroup_css_alloc,
6554 .css_online = mem_cgroup_css_online,
6555 .css_offline = mem_cgroup_css_offline,
6556 .css_released = mem_cgroup_css_released,
6557 .css_free = mem_cgroup_css_free,
6558 .css_reset = mem_cgroup_css_reset,
6559 .can_attach = mem_cgroup_can_attach,
6560 .cancel_attach = mem_cgroup_cancel_attach,
6561 .post_attach = mem_cgroup_move_task,
6562 .bind = mem_cgroup_bind,
6563 .dfl_cftypes = memory_files,
6564 .legacy_cftypes = mem_cgroup_legacy_files,
6569 * This function calculates an individual cgroup's effective
6570 * protection which is derived from its own memory.min/low, its
6571 * parent's and siblings' settings, as well as the actual memory
6572 * distribution in the tree.
6574 * The following rules apply to the effective protection values:
6576 * 1. At the first level of reclaim, effective protection is equal to
6577 * the declared protection in memory.min and memory.low.
6579 * 2. To enable safe delegation of the protection configuration, at
6580 * subsequent levels the effective protection is capped to the
6581 * parent's effective protection.
6583 * 3. To make complex and dynamic subtrees easier to configure, the
6584 * user is allowed to overcommit the declared protection at a given
6585 * level. If that is the case, the parent's effective protection is
6586 * distributed to the children in proportion to how much protection
6587 * they have declared and how much of it they are utilizing.
6589 * This makes distribution proportional, but also work-conserving:
6590 * if one cgroup claims much more protection than it uses memory,
6591 * the unused remainder is available to its siblings.
6593 * 4. Conversely, when the declared protection is undercommitted at a
6594 * given level, the distribution of the larger parental protection
6595 * budget is NOT proportional. A cgroup's protection from a sibling
6596 * is capped to its own memory.min/low setting.
6598 * 5. However, to allow protecting recursive subtrees from each other
6599 * without having to declare each individual cgroup's fixed share
6600 * of the ancestor's claim to protection, any unutilized -
6601 * "floating" - protection from up the tree is distributed in
6602 * proportion to each cgroup's *usage*. This makes the protection
6603 * neutral wrt sibling cgroups and lets them compete freely over
6604 * the shared parental protection budget, but it protects the
6605 * subtree as a whole from neighboring subtrees.
6607 * Note that 4. and 5. are not in conflict: 4. is about protecting
6608 * against immediate siblings whereas 5. is about protecting against
6609 * neighboring subtrees.
6611 static unsigned long effective_protection(unsigned long usage,
6612 unsigned long parent_usage,
6613 unsigned long setting,
6614 unsigned long parent_effective,
6615 unsigned long siblings_protected)
6617 unsigned long protected;
6620 protected = min(usage, setting);
6622 * If all cgroups at this level combined claim and use more
6623 * protection then what the parent affords them, distribute
6624 * shares in proportion to utilization.
6626 * We are using actual utilization rather than the statically
6627 * claimed protection in order to be work-conserving: claimed
6628 * but unused protection is available to siblings that would
6629 * otherwise get a smaller chunk than what they claimed.
6631 if (siblings_protected > parent_effective)
6632 return protected * parent_effective / siblings_protected;
6635 * Ok, utilized protection of all children is within what the
6636 * parent affords them, so we know whatever this child claims
6637 * and utilizes is effectively protected.
6639 * If there is unprotected usage beyond this value, reclaim
6640 * will apply pressure in proportion to that amount.
6642 * If there is unutilized protection, the cgroup will be fully
6643 * shielded from reclaim, but we do return a smaller value for
6644 * protection than what the group could enjoy in theory. This
6645 * is okay. With the overcommit distribution above, effective
6646 * protection is always dependent on how memory is actually
6647 * consumed among the siblings anyway.
6652 * If the children aren't claiming (all of) the protection
6653 * afforded to them by the parent, distribute the remainder in
6654 * proportion to the (unprotected) memory of each cgroup. That
6655 * way, cgroups that aren't explicitly prioritized wrt each
6656 * other compete freely over the allowance, but they are
6657 * collectively protected from neighboring trees.
6659 * We're using unprotected memory for the weight so that if
6660 * some cgroups DO claim explicit protection, we don't protect
6661 * the same bytes twice.
6663 * Check both usage and parent_usage against the respective
6664 * protected values. One should imply the other, but they
6665 * aren't read atomically - make sure the division is sane.
6667 if (!(cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT))
6669 if (parent_effective > siblings_protected &&
6670 parent_usage > siblings_protected &&
6671 usage > protected) {
6672 unsigned long unclaimed;
6674 unclaimed = parent_effective - siblings_protected;
6675 unclaimed *= usage - protected;
6676 unclaimed /= parent_usage - siblings_protected;
6685 * mem_cgroup_protected - check if memory consumption is in the normal range
6686 * @root: the top ancestor of the sub-tree being checked
6687 * @memcg: the memory cgroup to check
6689 * WARNING: This function is not stateless! It can only be used as part
6690 * of a top-down tree iteration, not for isolated queries.
6692 void mem_cgroup_calculate_protection(struct mem_cgroup *root,
6693 struct mem_cgroup *memcg)
6695 unsigned long usage, parent_usage;
6696 struct mem_cgroup *parent;
6698 if (mem_cgroup_disabled())
6702 root = root_mem_cgroup;
6705 * Effective values of the reclaim targets are ignored so they
6706 * can be stale. Have a look at mem_cgroup_protection for more
6708 * TODO: calculation should be more robust so that we do not need
6709 * that special casing.
6714 usage = page_counter_read(&memcg->memory);
6718 parent = parent_mem_cgroup(memcg);
6719 /* No parent means a non-hierarchical mode on v1 memcg */
6723 if (parent == root) {
6724 memcg->memory.emin = READ_ONCE(memcg->memory.min);
6725 memcg->memory.elow = READ_ONCE(memcg->memory.low);
6729 parent_usage = page_counter_read(&parent->memory);
6731 WRITE_ONCE(memcg->memory.emin, effective_protection(usage, parent_usage,
6732 READ_ONCE(memcg->memory.min),
6733 READ_ONCE(parent->memory.emin),
6734 atomic_long_read(&parent->memory.children_min_usage)));
6736 WRITE_ONCE(memcg->memory.elow, effective_protection(usage, parent_usage,
6737 READ_ONCE(memcg->memory.low),
6738 READ_ONCE(parent->memory.elow),
6739 atomic_long_read(&parent->memory.children_low_usage)));
6743 * mem_cgroup_charge - charge a newly allocated page to a cgroup
6744 * @page: page to charge
6745 * @mm: mm context of the victim
6746 * @gfp_mask: reclaim mode
6748 * Try to charge @page to the memcg that @mm belongs to, reclaiming
6749 * pages according to @gfp_mask if necessary.
6751 * Returns 0 on success. Otherwise, an error code is returned.
6753 int mem_cgroup_charge(struct page *page, struct mm_struct *mm, gfp_t gfp_mask)
6755 unsigned int nr_pages = thp_nr_pages(page);
6756 struct mem_cgroup *memcg = NULL;
6759 if (mem_cgroup_disabled())
6762 if (PageSwapCache(page)) {
6763 swp_entry_t ent = { .val = page_private(page), };
6767 * Every swap fault against a single page tries to charge the
6768 * page, bail as early as possible. shmem_unuse() encounters
6769 * already charged pages, too. page and memcg binding is
6770 * protected by the page lock, which serializes swap cache
6771 * removal, which in turn serializes uncharging.
6773 VM_BUG_ON_PAGE(!PageLocked(page), page);
6774 if (page_memcg(compound_head(page)))
6777 id = lookup_swap_cgroup_id(ent);
6779 memcg = mem_cgroup_from_id(id);
6780 if (memcg && !css_tryget_online(&memcg->css))
6786 memcg = get_mem_cgroup_from_mm(mm);
6788 ret = try_charge(memcg, gfp_mask, nr_pages);
6792 css_get(&memcg->css);
6793 commit_charge(page, memcg);
6795 local_irq_disable();
6796 mem_cgroup_charge_statistics(memcg, page, nr_pages);
6797 memcg_check_events(memcg, page);
6800 if (PageSwapCache(page)) {
6801 swp_entry_t entry = { .val = page_private(page) };
6803 * The swap entry might not get freed for a long time,
6804 * let's not wait for it. The page already received a
6805 * memory+swap charge, drop the swap entry duplicate.
6807 mem_cgroup_uncharge_swap(entry, nr_pages);
6811 css_put(&memcg->css);
6816 struct uncharge_gather {
6817 struct mem_cgroup *memcg;
6818 unsigned long nr_pages;
6819 unsigned long pgpgout;
6820 unsigned long nr_kmem;
6821 struct page *dummy_page;
6824 static inline void uncharge_gather_clear(struct uncharge_gather *ug)
6826 memset(ug, 0, sizeof(*ug));
6829 static void uncharge_batch(const struct uncharge_gather *ug)
6831 unsigned long flags;
6833 if (!mem_cgroup_is_root(ug->memcg)) {
6834 page_counter_uncharge(&ug->memcg->memory, ug->nr_pages);
6835 if (do_memsw_account())
6836 page_counter_uncharge(&ug->memcg->memsw, ug->nr_pages);
6837 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && ug->nr_kmem)
6838 page_counter_uncharge(&ug->memcg->kmem, ug->nr_kmem);
6839 memcg_oom_recover(ug->memcg);
6842 local_irq_save(flags);
6843 __count_memcg_events(ug->memcg, PGPGOUT, ug->pgpgout);
6844 __this_cpu_add(ug->memcg->vmstats_percpu->nr_page_events, ug->nr_pages);
6845 memcg_check_events(ug->memcg, ug->dummy_page);
6846 local_irq_restore(flags);
6848 /* drop reference from uncharge_page */
6849 css_put(&ug->memcg->css);
6852 static void uncharge_page(struct page *page, struct uncharge_gather *ug)
6854 unsigned long nr_pages;
6856 VM_BUG_ON_PAGE(PageLRU(page), page);
6858 if (!page_memcg(page))
6862 * Nobody should be changing or seriously looking at
6863 * page_memcg(page) at this point, we have fully
6864 * exclusive access to the page.
6867 if (ug->memcg != page_memcg(page)) {
6870 uncharge_gather_clear(ug);
6872 ug->memcg = page_memcg(page);
6874 /* pairs with css_put in uncharge_batch */
6875 css_get(&ug->memcg->css);
6878 nr_pages = compound_nr(page);
6879 ug->nr_pages += nr_pages;
6881 if (PageMemcgKmem(page))
6882 ug->nr_kmem += nr_pages;
6886 ug->dummy_page = page;
6887 page->memcg_data = 0;
6888 css_put(&ug->memcg->css);
6891 static void uncharge_list(struct list_head *page_list)
6893 struct uncharge_gather ug;
6894 struct list_head *next;
6896 uncharge_gather_clear(&ug);
6899 * Note that the list can be a single page->lru; hence the
6900 * do-while loop instead of a simple list_for_each_entry().
6902 next = page_list->next;
6906 page = list_entry(next, struct page, lru);
6907 next = page->lru.next;
6909 uncharge_page(page, &ug);
6910 } while (next != page_list);
6913 uncharge_batch(&ug);
6917 * mem_cgroup_uncharge - uncharge a page
6918 * @page: page to uncharge
6920 * Uncharge a page previously charged with mem_cgroup_charge().
6922 void mem_cgroup_uncharge(struct page *page)
6924 struct uncharge_gather ug;
6926 if (mem_cgroup_disabled())
6929 /* Don't touch page->lru of any random page, pre-check: */
6930 if (!page_memcg(page))
6933 uncharge_gather_clear(&ug);
6934 uncharge_page(page, &ug);
6935 uncharge_batch(&ug);
6939 * mem_cgroup_uncharge_list - uncharge a list of page
6940 * @page_list: list of pages to uncharge
6942 * Uncharge a list of pages previously charged with
6943 * mem_cgroup_charge().
6945 void mem_cgroup_uncharge_list(struct list_head *page_list)
6947 if (mem_cgroup_disabled())
6950 if (!list_empty(page_list))
6951 uncharge_list(page_list);
6955 * mem_cgroup_migrate - charge a page's replacement
6956 * @oldpage: currently circulating page
6957 * @newpage: replacement page
6959 * Charge @newpage as a replacement page for @oldpage. @oldpage will
6960 * be uncharged upon free.
6962 * Both pages must be locked, @newpage->mapping must be set up.
6964 void mem_cgroup_migrate(struct page *oldpage, struct page *newpage)
6966 struct mem_cgroup *memcg;
6967 unsigned int nr_pages;
6968 unsigned long flags;
6970 VM_BUG_ON_PAGE(!PageLocked(oldpage), oldpage);
6971 VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
6972 VM_BUG_ON_PAGE(PageAnon(oldpage) != PageAnon(newpage), newpage);
6973 VM_BUG_ON_PAGE(PageTransHuge(oldpage) != PageTransHuge(newpage),
6976 if (mem_cgroup_disabled())
6979 /* Page cache replacement: new page already charged? */
6980 if (page_memcg(newpage))
6983 /* Swapcache readahead pages can get replaced before being charged */
6984 memcg = page_memcg(oldpage);
6988 /* Force-charge the new page. The old one will be freed soon */
6989 nr_pages = thp_nr_pages(newpage);
6991 page_counter_charge(&memcg->memory, nr_pages);
6992 if (do_memsw_account())
6993 page_counter_charge(&memcg->memsw, nr_pages);
6995 css_get(&memcg->css);
6996 commit_charge(newpage, memcg);
6998 local_irq_save(flags);
6999 mem_cgroup_charge_statistics(memcg, newpage, nr_pages);
7000 memcg_check_events(memcg, newpage);
7001 local_irq_restore(flags);
7004 DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
7005 EXPORT_SYMBOL(memcg_sockets_enabled_key);
7007 void mem_cgroup_sk_alloc(struct sock *sk)
7009 struct mem_cgroup *memcg;
7011 if (!mem_cgroup_sockets_enabled)
7014 /* Do not associate the sock with unrelated interrupted task's memcg. */
7019 memcg = mem_cgroup_from_task(current);
7020 if (memcg == root_mem_cgroup)
7022 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg->tcpmem_active)
7024 if (css_tryget(&memcg->css))
7025 sk->sk_memcg = memcg;
7030 void mem_cgroup_sk_free(struct sock *sk)
7033 css_put(&sk->sk_memcg->css);
7037 * mem_cgroup_charge_skmem - charge socket memory
7038 * @memcg: memcg to charge
7039 * @nr_pages: number of pages to charge
7041 * Charges @nr_pages to @memcg. Returns %true if the charge fit within
7042 * @memcg's configured limit, %false if the charge had to be forced.
7044 bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
7046 gfp_t gfp_mask = GFP_KERNEL;
7048 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
7049 struct page_counter *fail;
7051 if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) {
7052 memcg->tcpmem_pressure = 0;
7055 page_counter_charge(&memcg->tcpmem, nr_pages);
7056 memcg->tcpmem_pressure = 1;
7060 /* Don't block in the packet receive path */
7062 gfp_mask = GFP_NOWAIT;
7064 mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
7066 if (try_charge(memcg, gfp_mask, nr_pages) == 0)
7069 try_charge(memcg, gfp_mask|__GFP_NOFAIL, nr_pages);
7074 * mem_cgroup_uncharge_skmem - uncharge socket memory
7075 * @memcg: memcg to uncharge
7076 * @nr_pages: number of pages to uncharge
7078 void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
7080 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
7081 page_counter_uncharge(&memcg->tcpmem, nr_pages);
7085 mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
7087 refill_stock(memcg, nr_pages);
7090 static int __init cgroup_memory(char *s)
7094 while ((token = strsep(&s, ",")) != NULL) {
7097 if (!strcmp(token, "nosocket"))
7098 cgroup_memory_nosocket = true;
7099 if (!strcmp(token, "nokmem"))
7100 cgroup_memory_nokmem = true;
7104 __setup("cgroup.memory=", cgroup_memory);
7107 * subsys_initcall() for memory controller.
7109 * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
7110 * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
7111 * basically everything that doesn't depend on a specific mem_cgroup structure
7112 * should be initialized from here.
7114 static int __init mem_cgroup_init(void)
7118 cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
7119 memcg_hotplug_cpu_dead);
7121 for_each_possible_cpu(cpu)
7122 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
7125 for_each_node(node) {
7126 struct mem_cgroup_tree_per_node *rtpn;
7128 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL,
7129 node_online(node) ? node : NUMA_NO_NODE);
7131 rtpn->rb_root = RB_ROOT;
7132 rtpn->rb_rightmost = NULL;
7133 spin_lock_init(&rtpn->lock);
7134 soft_limit_tree.rb_tree_per_node[node] = rtpn;
7139 subsys_initcall(mem_cgroup_init);
7141 #ifdef CONFIG_MEMCG_SWAP
7142 static struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
7144 while (!refcount_inc_not_zero(&memcg->id.ref)) {
7146 * The root cgroup cannot be destroyed, so it's refcount must
7149 if (WARN_ON_ONCE(memcg == root_mem_cgroup)) {
7153 memcg = parent_mem_cgroup(memcg);
7155 memcg = root_mem_cgroup;
7161 * mem_cgroup_swapout - transfer a memsw charge to swap
7162 * @page: page whose memsw charge to transfer
7163 * @entry: swap entry to move the charge to
7165 * Transfer the memsw charge of @page to @entry.
7167 void mem_cgroup_swapout(struct page *page, swp_entry_t entry)
7169 struct mem_cgroup *memcg, *swap_memcg;
7170 unsigned int nr_entries;
7171 unsigned short oldid;
7173 VM_BUG_ON_PAGE(PageLRU(page), page);
7174 VM_BUG_ON_PAGE(page_count(page), page);
7176 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
7179 memcg = page_memcg(page);
7181 /* Readahead page, never charged */
7186 * In case the memcg owning these pages has been offlined and doesn't
7187 * have an ID allocated to it anymore, charge the closest online
7188 * ancestor for the swap instead and transfer the memory+swap charge.
7190 swap_memcg = mem_cgroup_id_get_online(memcg);
7191 nr_entries = thp_nr_pages(page);
7192 /* Get references for the tail pages, too */
7194 mem_cgroup_id_get_many(swap_memcg, nr_entries - 1);
7195 oldid = swap_cgroup_record(entry, mem_cgroup_id(swap_memcg),
7197 VM_BUG_ON_PAGE(oldid, page);
7198 mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries);
7200 page->memcg_data = 0;
7202 if (!mem_cgroup_is_root(memcg))
7203 page_counter_uncharge(&memcg->memory, nr_entries);
7205 if (!cgroup_memory_noswap && memcg != swap_memcg) {
7206 if (!mem_cgroup_is_root(swap_memcg))
7207 page_counter_charge(&swap_memcg->memsw, nr_entries);
7208 page_counter_uncharge(&memcg->memsw, nr_entries);
7212 * Interrupts should be disabled here because the caller holds the
7213 * i_pages lock which is taken with interrupts-off. It is
7214 * important here to have the interrupts disabled because it is the
7215 * only synchronisation we have for updating the per-CPU variables.
7217 VM_BUG_ON(!irqs_disabled());
7218 mem_cgroup_charge_statistics(memcg, page, -nr_entries);
7219 memcg_check_events(memcg, page);
7221 css_put(&memcg->css);
7225 * mem_cgroup_try_charge_swap - try charging swap space for a page
7226 * @page: page being added to swap
7227 * @entry: swap entry to charge
7229 * Try to charge @page's memcg for the swap space at @entry.
7231 * Returns 0 on success, -ENOMEM on failure.
7233 int mem_cgroup_try_charge_swap(struct page *page, swp_entry_t entry)
7235 unsigned int nr_pages = thp_nr_pages(page);
7236 struct page_counter *counter;
7237 struct mem_cgroup *memcg;
7238 unsigned short oldid;
7240 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
7243 memcg = page_memcg(page);
7245 /* Readahead page, never charged */
7250 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7254 memcg = mem_cgroup_id_get_online(memcg);
7256 if (!cgroup_memory_noswap && !mem_cgroup_is_root(memcg) &&
7257 !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
7258 memcg_memory_event(memcg, MEMCG_SWAP_MAX);
7259 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7260 mem_cgroup_id_put(memcg);
7264 /* Get references for the tail pages, too */
7266 mem_cgroup_id_get_many(memcg, nr_pages - 1);
7267 oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg), nr_pages);
7268 VM_BUG_ON_PAGE(oldid, page);
7269 mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
7275 * mem_cgroup_uncharge_swap - uncharge swap space
7276 * @entry: swap entry to uncharge
7277 * @nr_pages: the amount of swap space to uncharge
7279 void mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
7281 struct mem_cgroup *memcg;
7284 id = swap_cgroup_record(entry, 0, nr_pages);
7286 memcg = mem_cgroup_from_id(id);
7288 if (!cgroup_memory_noswap && !mem_cgroup_is_root(memcg)) {
7289 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
7290 page_counter_uncharge(&memcg->swap, nr_pages);
7292 page_counter_uncharge(&memcg->memsw, nr_pages);
7294 mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
7295 mem_cgroup_id_put_many(memcg, nr_pages);
7300 long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
7302 long nr_swap_pages = get_nr_swap_pages();
7304 if (cgroup_memory_noswap || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
7305 return nr_swap_pages;
7306 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg))
7307 nr_swap_pages = min_t(long, nr_swap_pages,
7308 READ_ONCE(memcg->swap.max) -
7309 page_counter_read(&memcg->swap));
7310 return nr_swap_pages;
7313 bool mem_cgroup_swap_full(struct page *page)
7315 struct mem_cgroup *memcg;
7317 VM_BUG_ON_PAGE(!PageLocked(page), page);
7321 if (cgroup_memory_noswap || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
7324 memcg = page_memcg(page);
7328 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg)) {
7329 unsigned long usage = page_counter_read(&memcg->swap);
7331 if (usage * 2 >= READ_ONCE(memcg->swap.high) ||
7332 usage * 2 >= READ_ONCE(memcg->swap.max))
7339 static int __init setup_swap_account(char *s)
7341 if (!strcmp(s, "1"))
7342 cgroup_memory_noswap = 0;
7343 else if (!strcmp(s, "0"))
7344 cgroup_memory_noswap = 1;
7347 __setup("swapaccount=", setup_swap_account);
7349 static u64 swap_current_read(struct cgroup_subsys_state *css,
7352 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7354 return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
7357 static int swap_high_show(struct seq_file *m, void *v)
7359 return seq_puts_memcg_tunable(m,
7360 READ_ONCE(mem_cgroup_from_seq(m)->swap.high));
7363 static ssize_t swap_high_write(struct kernfs_open_file *of,
7364 char *buf, size_t nbytes, loff_t off)
7366 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7370 buf = strstrip(buf);
7371 err = page_counter_memparse(buf, "max", &high);
7375 page_counter_set_high(&memcg->swap, high);
7380 static int swap_max_show(struct seq_file *m, void *v)
7382 return seq_puts_memcg_tunable(m,
7383 READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
7386 static ssize_t swap_max_write(struct kernfs_open_file *of,
7387 char *buf, size_t nbytes, loff_t off)
7389 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7393 buf = strstrip(buf);
7394 err = page_counter_memparse(buf, "max", &max);
7398 xchg(&memcg->swap.max, max);
7403 static int swap_events_show(struct seq_file *m, void *v)
7405 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
7407 seq_printf(m, "high %lu\n",
7408 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH]));
7409 seq_printf(m, "max %lu\n",
7410 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
7411 seq_printf(m, "fail %lu\n",
7412 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
7417 static struct cftype swap_files[] = {
7419 .name = "swap.current",
7420 .flags = CFTYPE_NOT_ON_ROOT,
7421 .read_u64 = swap_current_read,
7424 .name = "swap.high",
7425 .flags = CFTYPE_NOT_ON_ROOT,
7426 .seq_show = swap_high_show,
7427 .write = swap_high_write,
7431 .flags = CFTYPE_NOT_ON_ROOT,
7432 .seq_show = swap_max_show,
7433 .write = swap_max_write,
7436 .name = "swap.events",
7437 .flags = CFTYPE_NOT_ON_ROOT,
7438 .file_offset = offsetof(struct mem_cgroup, swap_events_file),
7439 .seq_show = swap_events_show,
7444 static struct cftype memsw_files[] = {
7446 .name = "memsw.usage_in_bytes",
7447 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
7448 .read_u64 = mem_cgroup_read_u64,
7451 .name = "memsw.max_usage_in_bytes",
7452 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
7453 .write = mem_cgroup_reset,
7454 .read_u64 = mem_cgroup_read_u64,
7457 .name = "memsw.limit_in_bytes",
7458 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
7459 .write = mem_cgroup_write,
7460 .read_u64 = mem_cgroup_read_u64,
7463 .name = "memsw.failcnt",
7464 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
7465 .write = mem_cgroup_reset,
7466 .read_u64 = mem_cgroup_read_u64,
7468 { }, /* terminate */
7472 * If mem_cgroup_swap_init() is implemented as a subsys_initcall()
7473 * instead of a core_initcall(), this could mean cgroup_memory_noswap still
7474 * remains set to false even when memcg is disabled via "cgroup_disable=memory"
7475 * boot parameter. This may result in premature OOPS inside
7476 * mem_cgroup_get_nr_swap_pages() function in corner cases.
7478 static int __init mem_cgroup_swap_init(void)
7480 /* No memory control -> no swap control */
7481 if (mem_cgroup_disabled())
7482 cgroup_memory_noswap = true;
7484 if (cgroup_memory_noswap)
7487 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files));
7488 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files));
7492 core_initcall(mem_cgroup_swap_init);
7494 #endif /* CONFIG_MEMCG_SWAP */