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 #define MEM_CGROUP_RECLAIM_RETRIES 5
78 /* Socket memory accounting disabled? */
79 static bool cgroup_memory_nosocket;
81 /* Kernel memory accounting disabled? */
82 static bool cgroup_memory_nokmem;
84 /* Whether the swap controller is active */
85 #ifdef CONFIG_MEMCG_SWAP
86 int do_swap_account __read_mostly;
88 #define do_swap_account 0
91 #ifdef CONFIG_CGROUP_WRITEBACK
92 static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq);
95 /* Whether legacy memory+swap accounting is active */
96 static bool do_memsw_account(void)
98 return !cgroup_subsys_on_dfl(memory_cgrp_subsys) && do_swap_account;
101 static const char *const mem_cgroup_lru_names[] = {
109 #define THRESHOLDS_EVENTS_TARGET 128
110 #define SOFTLIMIT_EVENTS_TARGET 1024
111 #define NUMAINFO_EVENTS_TARGET 1024
114 * Cgroups above their limits are maintained in a RB-Tree, independent of
115 * their hierarchy representation
118 struct mem_cgroup_tree_per_node {
119 struct rb_root rb_root;
120 struct rb_node *rb_rightmost;
124 struct mem_cgroup_tree {
125 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
128 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
131 struct mem_cgroup_eventfd_list {
132 struct list_head list;
133 struct eventfd_ctx *eventfd;
137 * cgroup_event represents events which userspace want to receive.
139 struct mem_cgroup_event {
141 * memcg which the event belongs to.
143 struct mem_cgroup *memcg;
145 * eventfd to signal userspace about the event.
147 struct eventfd_ctx *eventfd;
149 * Each of these stored in a list by the cgroup.
151 struct list_head list;
153 * register_event() callback will be used to add new userspace
154 * waiter for changes related to this event. Use eventfd_signal()
155 * on eventfd to send notification to userspace.
157 int (*register_event)(struct mem_cgroup *memcg,
158 struct eventfd_ctx *eventfd, const char *args);
160 * unregister_event() callback will be called when userspace closes
161 * the eventfd or on cgroup removing. This callback must be set,
162 * if you want provide notification functionality.
164 void (*unregister_event)(struct mem_cgroup *memcg,
165 struct eventfd_ctx *eventfd);
167 * All fields below needed to unregister event when
168 * userspace closes eventfd.
171 wait_queue_head_t *wqh;
172 wait_queue_entry_t wait;
173 struct work_struct remove;
176 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
177 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
179 /* Stuffs for move charges at task migration. */
181 * Types of charges to be moved.
183 #define MOVE_ANON 0x1U
184 #define MOVE_FILE 0x2U
185 #define MOVE_MASK (MOVE_ANON | MOVE_FILE)
187 /* "mc" and its members are protected by cgroup_mutex */
188 static struct move_charge_struct {
189 spinlock_t lock; /* for from, to */
190 struct mm_struct *mm;
191 struct mem_cgroup *from;
192 struct mem_cgroup *to;
194 unsigned long precharge;
195 unsigned long moved_charge;
196 unsigned long moved_swap;
197 struct task_struct *moving_task; /* a task moving charges */
198 wait_queue_head_t waitq; /* a waitq for other context */
200 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
201 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
205 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
206 * limit reclaim to prevent infinite loops, if they ever occur.
208 #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
209 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
212 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
213 MEM_CGROUP_CHARGE_TYPE_ANON,
214 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
215 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
219 /* for encoding cft->private value on file */
228 #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
229 #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
230 #define MEMFILE_ATTR(val) ((val) & 0xffff)
231 /* Used for OOM nofiier */
232 #define OOM_CONTROL (0)
235 * Iteration constructs for visiting all cgroups (under a tree). If
236 * loops are exited prematurely (break), mem_cgroup_iter_break() must
237 * be used for reference counting.
239 #define for_each_mem_cgroup_tree(iter, root) \
240 for (iter = mem_cgroup_iter(root, NULL, NULL); \
242 iter = mem_cgroup_iter(root, iter, NULL))
244 #define for_each_mem_cgroup(iter) \
245 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
247 iter = mem_cgroup_iter(NULL, iter, NULL))
249 static inline bool should_force_charge(void)
251 return tsk_is_oom_victim(current) || fatal_signal_pending(current) ||
252 (current->flags & PF_EXITING);
255 /* Some nice accessors for the vmpressure. */
256 struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
259 memcg = root_mem_cgroup;
260 return &memcg->vmpressure;
263 struct cgroup_subsys_state *vmpressure_to_css(struct vmpressure *vmpr)
265 return &container_of(vmpr, struct mem_cgroup, vmpressure)->css;
268 #ifdef CONFIG_MEMCG_KMEM
270 * This will be the memcg's index in each cache's ->memcg_params.memcg_caches.
271 * The main reason for not using cgroup id for this:
272 * this works better in sparse environments, where we have a lot of memcgs,
273 * but only a few kmem-limited. Or also, if we have, for instance, 200
274 * memcgs, and none but the 200th is kmem-limited, we'd have to have a
275 * 200 entry array for that.
277 * The current size of the caches array is stored in memcg_nr_cache_ids. It
278 * will double each time we have to increase it.
280 static DEFINE_IDA(memcg_cache_ida);
281 int memcg_nr_cache_ids;
283 /* Protects memcg_nr_cache_ids */
284 static DECLARE_RWSEM(memcg_cache_ids_sem);
286 void memcg_get_cache_ids(void)
288 down_read(&memcg_cache_ids_sem);
291 void memcg_put_cache_ids(void)
293 up_read(&memcg_cache_ids_sem);
297 * MIN_SIZE is different than 1, because we would like to avoid going through
298 * the alloc/free process all the time. In a small machine, 4 kmem-limited
299 * cgroups is a reasonable guess. In the future, it could be a parameter or
300 * tunable, but that is strictly not necessary.
302 * MAX_SIZE should be as large as the number of cgrp_ids. Ideally, we could get
303 * this constant directly from cgroup, but it is understandable that this is
304 * better kept as an internal representation in cgroup.c. In any case, the
305 * cgrp_id space is not getting any smaller, and we don't have to necessarily
306 * increase ours as well if it increases.
308 #define MEMCG_CACHES_MIN_SIZE 4
309 #define MEMCG_CACHES_MAX_SIZE MEM_CGROUP_ID_MAX
312 * A lot of the calls to the cache allocation functions are expected to be
313 * inlined by the compiler. Since the calls to memcg_kmem_get_cache are
314 * conditional to this static branch, we'll have to allow modules that does
315 * kmem_cache_alloc and the such to see this symbol as well
317 DEFINE_STATIC_KEY_FALSE(memcg_kmem_enabled_key);
318 EXPORT_SYMBOL(memcg_kmem_enabled_key);
320 struct workqueue_struct *memcg_kmem_cache_wq;
323 static int memcg_shrinker_map_size;
324 static DEFINE_MUTEX(memcg_shrinker_map_mutex);
326 static void memcg_free_shrinker_map_rcu(struct rcu_head *head)
328 kvfree(container_of(head, struct memcg_shrinker_map, rcu));
331 static int memcg_expand_one_shrinker_map(struct mem_cgroup *memcg,
332 int size, int old_size)
334 struct memcg_shrinker_map *new, *old;
337 lockdep_assert_held(&memcg_shrinker_map_mutex);
340 old = rcu_dereference_protected(
341 mem_cgroup_nodeinfo(memcg, nid)->shrinker_map, true);
342 /* Not yet online memcg */
346 new = kvmalloc(sizeof(*new) + size, GFP_KERNEL);
350 /* Set all old bits, clear all new bits */
351 memset(new->map, (int)0xff, old_size);
352 memset((void *)new->map + old_size, 0, size - old_size);
354 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_map, new);
355 call_rcu(&old->rcu, memcg_free_shrinker_map_rcu);
361 static void memcg_free_shrinker_maps(struct mem_cgroup *memcg)
363 struct mem_cgroup_per_node *pn;
364 struct memcg_shrinker_map *map;
367 if (mem_cgroup_is_root(memcg))
371 pn = mem_cgroup_nodeinfo(memcg, nid);
372 map = rcu_dereference_protected(pn->shrinker_map, true);
375 rcu_assign_pointer(pn->shrinker_map, NULL);
379 static int memcg_alloc_shrinker_maps(struct mem_cgroup *memcg)
381 struct memcg_shrinker_map *map;
382 int nid, size, ret = 0;
384 if (mem_cgroup_is_root(memcg))
387 mutex_lock(&memcg_shrinker_map_mutex);
388 size = memcg_shrinker_map_size;
390 map = kvzalloc(sizeof(*map) + size, GFP_KERNEL);
392 memcg_free_shrinker_maps(memcg);
396 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_map, map);
398 mutex_unlock(&memcg_shrinker_map_mutex);
403 int memcg_expand_shrinker_maps(int new_id)
405 int size, old_size, ret = 0;
406 struct mem_cgroup *memcg;
408 size = DIV_ROUND_UP(new_id + 1, BITS_PER_LONG) * sizeof(unsigned long);
409 old_size = memcg_shrinker_map_size;
410 if (size <= old_size)
413 mutex_lock(&memcg_shrinker_map_mutex);
414 if (!root_mem_cgroup)
417 for_each_mem_cgroup(memcg) {
418 if (mem_cgroup_is_root(memcg))
420 ret = memcg_expand_one_shrinker_map(memcg, size, old_size);
422 mem_cgroup_iter_break(NULL, memcg);
428 memcg_shrinker_map_size = size;
429 mutex_unlock(&memcg_shrinker_map_mutex);
433 void memcg_set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
435 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
436 struct memcg_shrinker_map *map;
439 map = rcu_dereference(memcg->nodeinfo[nid]->shrinker_map);
440 /* Pairs with smp mb in shrink_slab() */
441 smp_mb__before_atomic();
442 set_bit(shrinker_id, map->map);
448 * mem_cgroup_css_from_page - css of the memcg associated with a page
449 * @page: page of interest
451 * If memcg is bound to the default hierarchy, css of the memcg associated
452 * with @page is returned. The returned css remains associated with @page
453 * until it is released.
455 * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
458 struct cgroup_subsys_state *mem_cgroup_css_from_page(struct page *page)
460 struct mem_cgroup *memcg;
462 memcg = page->mem_cgroup;
464 if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
465 memcg = root_mem_cgroup;
471 * page_cgroup_ino - return inode number of the memcg a page is charged to
474 * Look up the closest online ancestor of the memory cgroup @page is charged to
475 * and return its inode number or 0 if @page is not charged to any cgroup. It
476 * is safe to call this function without holding a reference to @page.
478 * Note, this function is inherently racy, because there is nothing to prevent
479 * the cgroup inode from getting torn down and potentially reallocated a moment
480 * after page_cgroup_ino() returns, so it only should be used by callers that
481 * do not care (such as procfs interfaces).
483 ino_t page_cgroup_ino(struct page *page)
485 struct mem_cgroup *memcg;
486 unsigned long ino = 0;
489 if (PageSlab(page) && !PageTail(page))
490 memcg = memcg_from_slab_page(page);
492 memcg = READ_ONCE(page->mem_cgroup);
493 while (memcg && !(memcg->css.flags & CSS_ONLINE))
494 memcg = parent_mem_cgroup(memcg);
496 ino = cgroup_ino(memcg->css.cgroup);
501 static struct mem_cgroup_per_node *
502 mem_cgroup_page_nodeinfo(struct mem_cgroup *memcg, struct page *page)
504 int nid = page_to_nid(page);
506 return memcg->nodeinfo[nid];
509 static struct mem_cgroup_tree_per_node *
510 soft_limit_tree_node(int nid)
512 return soft_limit_tree.rb_tree_per_node[nid];
515 static struct mem_cgroup_tree_per_node *
516 soft_limit_tree_from_page(struct page *page)
518 int nid = page_to_nid(page);
520 return soft_limit_tree.rb_tree_per_node[nid];
523 static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_node *mz,
524 struct mem_cgroup_tree_per_node *mctz,
525 unsigned long new_usage_in_excess)
527 struct rb_node **p = &mctz->rb_root.rb_node;
528 struct rb_node *parent = NULL;
529 struct mem_cgroup_per_node *mz_node;
530 bool rightmost = true;
535 mz->usage_in_excess = new_usage_in_excess;
536 if (!mz->usage_in_excess)
540 mz_node = rb_entry(parent, struct mem_cgroup_per_node,
542 if (mz->usage_in_excess < mz_node->usage_in_excess) {
548 * We can't avoid mem cgroups that are over their soft
549 * limit by the same amount
551 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
556 mctz->rb_rightmost = &mz->tree_node;
558 rb_link_node(&mz->tree_node, parent, p);
559 rb_insert_color(&mz->tree_node, &mctz->rb_root);
563 static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
564 struct mem_cgroup_tree_per_node *mctz)
569 if (&mz->tree_node == mctz->rb_rightmost)
570 mctz->rb_rightmost = rb_prev(&mz->tree_node);
572 rb_erase(&mz->tree_node, &mctz->rb_root);
576 static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
577 struct mem_cgroup_tree_per_node *mctz)
581 spin_lock_irqsave(&mctz->lock, flags);
582 __mem_cgroup_remove_exceeded(mz, mctz);
583 spin_unlock_irqrestore(&mctz->lock, flags);
586 static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
588 unsigned long nr_pages = page_counter_read(&memcg->memory);
589 unsigned long soft_limit = READ_ONCE(memcg->soft_limit);
590 unsigned long excess = 0;
592 if (nr_pages > soft_limit)
593 excess = nr_pages - soft_limit;
598 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
600 unsigned long excess;
601 struct mem_cgroup_per_node *mz;
602 struct mem_cgroup_tree_per_node *mctz;
604 mctz = soft_limit_tree_from_page(page);
608 * Necessary to update all ancestors when hierarchy is used.
609 * because their event counter is not touched.
611 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
612 mz = mem_cgroup_page_nodeinfo(memcg, page);
613 excess = soft_limit_excess(memcg);
615 * We have to update the tree if mz is on RB-tree or
616 * mem is over its softlimit.
618 if (excess || mz->on_tree) {
621 spin_lock_irqsave(&mctz->lock, flags);
622 /* if on-tree, remove it */
624 __mem_cgroup_remove_exceeded(mz, mctz);
626 * Insert again. mz->usage_in_excess will be updated.
627 * If excess is 0, no tree ops.
629 __mem_cgroup_insert_exceeded(mz, mctz, excess);
630 spin_unlock_irqrestore(&mctz->lock, flags);
635 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
637 struct mem_cgroup_tree_per_node *mctz;
638 struct mem_cgroup_per_node *mz;
642 mz = mem_cgroup_nodeinfo(memcg, nid);
643 mctz = soft_limit_tree_node(nid);
645 mem_cgroup_remove_exceeded(mz, mctz);
649 static struct mem_cgroup_per_node *
650 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
652 struct mem_cgroup_per_node *mz;
656 if (!mctz->rb_rightmost)
657 goto done; /* Nothing to reclaim from */
659 mz = rb_entry(mctz->rb_rightmost,
660 struct mem_cgroup_per_node, tree_node);
662 * Remove the node now but someone else can add it back,
663 * we will to add it back at the end of reclaim to its correct
664 * position in the tree.
666 __mem_cgroup_remove_exceeded(mz, mctz);
667 if (!soft_limit_excess(mz->memcg) ||
668 !css_tryget_online(&mz->memcg->css))
674 static struct mem_cgroup_per_node *
675 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
677 struct mem_cgroup_per_node *mz;
679 spin_lock_irq(&mctz->lock);
680 mz = __mem_cgroup_largest_soft_limit_node(mctz);
681 spin_unlock_irq(&mctz->lock);
686 * __mod_memcg_state - update cgroup memory statistics
687 * @memcg: the memory cgroup
688 * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item
689 * @val: delta to add to the counter, can be negative
691 void __mod_memcg_state(struct mem_cgroup *memcg, int idx, int val)
695 if (mem_cgroup_disabled())
698 x = val + __this_cpu_read(memcg->vmstats_percpu->stat[idx]);
699 if (unlikely(abs(x) > MEMCG_CHARGE_BATCH)) {
700 struct mem_cgroup *mi;
703 * Batch local counters to keep them in sync with
704 * the hierarchical ones.
706 __this_cpu_add(memcg->vmstats_local->stat[idx], x);
707 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
708 atomic_long_add(x, &mi->vmstats[idx]);
711 __this_cpu_write(memcg->vmstats_percpu->stat[idx], x);
714 static struct mem_cgroup_per_node *
715 parent_nodeinfo(struct mem_cgroup_per_node *pn, int nid)
717 struct mem_cgroup *parent;
719 parent = parent_mem_cgroup(pn->memcg);
722 return mem_cgroup_nodeinfo(parent, nid);
726 * __mod_lruvec_state - update lruvec memory statistics
727 * @lruvec: the lruvec
728 * @idx: the stat item
729 * @val: delta to add to the counter, can be negative
731 * The lruvec is the intersection of the NUMA node and a cgroup. This
732 * function updates the all three counters that are affected by a
733 * change of state at this level: per-node, per-cgroup, per-lruvec.
735 void __mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
738 pg_data_t *pgdat = lruvec_pgdat(lruvec);
739 struct mem_cgroup_per_node *pn;
740 struct mem_cgroup *memcg;
744 __mod_node_page_state(pgdat, idx, val);
746 if (mem_cgroup_disabled())
749 pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
753 __mod_memcg_state(memcg, idx, val);
756 __this_cpu_add(pn->lruvec_stat_local->count[idx], val);
758 x = val + __this_cpu_read(pn->lruvec_stat_cpu->count[idx]);
759 if (unlikely(abs(x) > MEMCG_CHARGE_BATCH)) {
760 struct mem_cgroup_per_node *pi;
762 for (pi = pn; pi; pi = parent_nodeinfo(pi, pgdat->node_id))
763 atomic_long_add(x, &pi->lruvec_stat[idx]);
766 __this_cpu_write(pn->lruvec_stat_cpu->count[idx], x);
769 void __mod_lruvec_slab_state(void *p, enum node_stat_item idx, int val)
771 struct page *page = virt_to_head_page(p);
772 pg_data_t *pgdat = page_pgdat(page);
773 struct mem_cgroup *memcg;
774 struct lruvec *lruvec;
777 memcg = memcg_from_slab_page(page);
779 /* Untracked pages have no memcg, no lruvec. Update only the node */
780 if (!memcg || memcg == root_mem_cgroup) {
781 __mod_node_page_state(pgdat, idx, val);
783 lruvec = mem_cgroup_lruvec(memcg, pgdat);
784 __mod_lruvec_state(lruvec, idx, val);
789 void mod_memcg_obj_state(void *p, int idx, int val)
791 struct mem_cgroup *memcg;
794 memcg = mem_cgroup_from_obj(p);
796 mod_memcg_state(memcg, idx, val);
801 * __count_memcg_events - account VM events in a cgroup
802 * @memcg: the memory cgroup
803 * @idx: the event item
804 * @count: the number of events that occured
806 void __count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx,
811 if (mem_cgroup_disabled())
814 x = count + __this_cpu_read(memcg->vmstats_percpu->events[idx]);
815 if (unlikely(x > MEMCG_CHARGE_BATCH)) {
816 struct mem_cgroup *mi;
819 * Batch local counters to keep them in sync with
820 * the hierarchical ones.
822 __this_cpu_add(memcg->vmstats_local->events[idx], x);
823 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
824 atomic_long_add(x, &mi->vmevents[idx]);
827 __this_cpu_write(memcg->vmstats_percpu->events[idx], x);
830 static unsigned long memcg_events(struct mem_cgroup *memcg, int event)
832 return atomic_long_read(&memcg->vmevents[event]);
835 static unsigned long memcg_events_local(struct mem_cgroup *memcg, int event)
840 for_each_possible_cpu(cpu)
841 x += per_cpu(memcg->vmstats_local->events[event], cpu);
845 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
847 bool compound, int nr_pages)
850 * Here, RSS means 'mapped anon' and anon's SwapCache. Shmem/tmpfs is
851 * counted as CACHE even if it's on ANON LRU.
854 __mod_memcg_state(memcg, MEMCG_RSS, nr_pages);
856 __mod_memcg_state(memcg, MEMCG_CACHE, nr_pages);
857 if (PageSwapBacked(page))
858 __mod_memcg_state(memcg, NR_SHMEM, nr_pages);
862 VM_BUG_ON_PAGE(!PageTransHuge(page), page);
863 __mod_memcg_state(memcg, MEMCG_RSS_HUGE, nr_pages);
866 /* pagein of a big page is an event. So, ignore page size */
868 __count_memcg_events(memcg, PGPGIN, 1);
870 __count_memcg_events(memcg, PGPGOUT, 1);
871 nr_pages = -nr_pages; /* for event */
874 __this_cpu_add(memcg->vmstats_percpu->nr_page_events, nr_pages);
877 static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
878 enum mem_cgroup_events_target target)
880 unsigned long val, next;
882 val = __this_cpu_read(memcg->vmstats_percpu->nr_page_events);
883 next = __this_cpu_read(memcg->vmstats_percpu->targets[target]);
884 /* from time_after() in jiffies.h */
885 if ((long)(next - val) < 0) {
887 case MEM_CGROUP_TARGET_THRESH:
888 next = val + THRESHOLDS_EVENTS_TARGET;
890 case MEM_CGROUP_TARGET_SOFTLIMIT:
891 next = val + SOFTLIMIT_EVENTS_TARGET;
893 case MEM_CGROUP_TARGET_NUMAINFO:
894 next = val + NUMAINFO_EVENTS_TARGET;
899 __this_cpu_write(memcg->vmstats_percpu->targets[target], next);
906 * Check events in order.
909 static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
911 /* threshold event is triggered in finer grain than soft limit */
912 if (unlikely(mem_cgroup_event_ratelimit(memcg,
913 MEM_CGROUP_TARGET_THRESH))) {
915 bool do_numainfo __maybe_unused;
917 do_softlimit = mem_cgroup_event_ratelimit(memcg,
918 MEM_CGROUP_TARGET_SOFTLIMIT);
920 do_numainfo = mem_cgroup_event_ratelimit(memcg,
921 MEM_CGROUP_TARGET_NUMAINFO);
923 mem_cgroup_threshold(memcg);
924 if (unlikely(do_softlimit))
925 mem_cgroup_update_tree(memcg, page);
927 if (unlikely(do_numainfo))
928 atomic_inc(&memcg->numainfo_events);
933 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
936 * mm_update_next_owner() may clear mm->owner to NULL
937 * if it races with swapoff, page migration, etc.
938 * So this can be called with p == NULL.
943 return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
945 EXPORT_SYMBOL(mem_cgroup_from_task);
948 * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
949 * @mm: mm from which memcg should be extracted. It can be NULL.
951 * Obtain a reference on mm->memcg and returns it if successful. Otherwise
952 * root_mem_cgroup is returned. However if mem_cgroup is disabled, NULL is
955 struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
957 struct mem_cgroup *memcg;
959 if (mem_cgroup_disabled())
965 * Page cache insertions can happen withou an
966 * actual mm context, e.g. during disk probing
967 * on boot, loopback IO, acct() writes etc.
970 memcg = root_mem_cgroup;
972 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
973 if (unlikely(!memcg))
974 memcg = root_mem_cgroup;
976 } while (!css_tryget(&memcg->css));
980 EXPORT_SYMBOL(get_mem_cgroup_from_mm);
983 * get_mem_cgroup_from_page: Obtain a reference on given page's memcg.
984 * @page: page from which memcg should be extracted.
986 * Obtain a reference on page->memcg and returns it if successful. Otherwise
987 * root_mem_cgroup is returned.
989 struct mem_cgroup *get_mem_cgroup_from_page(struct page *page)
991 struct mem_cgroup *memcg = page->mem_cgroup;
993 if (mem_cgroup_disabled())
997 if (!memcg || !css_tryget_online(&memcg->css))
998 memcg = root_mem_cgroup;
1002 EXPORT_SYMBOL(get_mem_cgroup_from_page);
1005 * If current->active_memcg is non-NULL, do not fallback to current->mm->memcg.
1007 static __always_inline struct mem_cgroup *get_mem_cgroup_from_current(void)
1009 if (unlikely(current->active_memcg)) {
1010 struct mem_cgroup *memcg = root_mem_cgroup;
1013 if (css_tryget_online(¤t->active_memcg->css))
1014 memcg = current->active_memcg;
1018 return get_mem_cgroup_from_mm(current->mm);
1022 * mem_cgroup_iter - iterate over memory cgroup hierarchy
1023 * @root: hierarchy root
1024 * @prev: previously returned memcg, NULL on first invocation
1025 * @reclaim: cookie for shared reclaim walks, NULL for full walks
1027 * Returns references to children of the hierarchy below @root, or
1028 * @root itself, or %NULL after a full round-trip.
1030 * Caller must pass the return value in @prev on subsequent
1031 * invocations for reference counting, or use mem_cgroup_iter_break()
1032 * to cancel a hierarchy walk before the round-trip is complete.
1034 * Reclaimers can specify a node and a priority level in @reclaim to
1035 * divide up the memcgs in the hierarchy among all concurrent
1036 * reclaimers operating on the same node and priority.
1038 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
1039 struct mem_cgroup *prev,
1040 struct mem_cgroup_reclaim_cookie *reclaim)
1042 struct mem_cgroup_reclaim_iter *uninitialized_var(iter);
1043 struct cgroup_subsys_state *css = NULL;
1044 struct mem_cgroup *memcg = NULL;
1045 struct mem_cgroup *pos = NULL;
1047 if (mem_cgroup_disabled())
1051 root = root_mem_cgroup;
1053 if (prev && !reclaim)
1056 if (!root->use_hierarchy && root != root_mem_cgroup) {
1065 struct mem_cgroup_per_node *mz;
1067 mz = mem_cgroup_nodeinfo(root, reclaim->pgdat->node_id);
1068 iter = &mz->iter[reclaim->priority];
1070 if (prev && reclaim->generation != iter->generation)
1074 pos = READ_ONCE(iter->position);
1075 if (!pos || css_tryget(&pos->css))
1078 * css reference reached zero, so iter->position will
1079 * be cleared by ->css_released. However, we should not
1080 * rely on this happening soon, because ->css_released
1081 * is called from a work queue, and by busy-waiting we
1082 * might block it. So we clear iter->position right
1085 (void)cmpxchg(&iter->position, pos, NULL);
1093 css = css_next_descendant_pre(css, &root->css);
1096 * Reclaimers share the hierarchy walk, and a
1097 * new one might jump in right at the end of
1098 * the hierarchy - make sure they see at least
1099 * one group and restart from the beginning.
1107 * Verify the css and acquire a reference. The root
1108 * is provided by the caller, so we know it's alive
1109 * and kicking, and don't take an extra reference.
1111 memcg = mem_cgroup_from_css(css);
1113 if (css == &root->css)
1116 if (css_tryget(css))
1124 * The position could have already been updated by a competing
1125 * thread, so check that the value hasn't changed since we read
1126 * it to avoid reclaiming from the same cgroup twice.
1128 (void)cmpxchg(&iter->position, pos, memcg);
1136 reclaim->generation = iter->generation;
1142 if (prev && prev != root)
1143 css_put(&prev->css);
1149 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1150 * @root: hierarchy root
1151 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1153 void mem_cgroup_iter_break(struct mem_cgroup *root,
1154 struct mem_cgroup *prev)
1157 root = root_mem_cgroup;
1158 if (prev && prev != root)
1159 css_put(&prev->css);
1162 static void __invalidate_reclaim_iterators(struct mem_cgroup *from,
1163 struct mem_cgroup *dead_memcg)
1165 struct mem_cgroup_reclaim_iter *iter;
1166 struct mem_cgroup_per_node *mz;
1170 for_each_node(nid) {
1171 mz = mem_cgroup_nodeinfo(from, nid);
1172 for (i = 0; i <= DEF_PRIORITY; i++) {
1173 iter = &mz->iter[i];
1174 cmpxchg(&iter->position,
1180 static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
1182 struct mem_cgroup *memcg = dead_memcg;
1183 struct mem_cgroup *last;
1186 __invalidate_reclaim_iterators(memcg, dead_memcg);
1188 } while ((memcg = parent_mem_cgroup(memcg)));
1191 * When cgruop1 non-hierarchy mode is used,
1192 * parent_mem_cgroup() does not walk all the way up to the
1193 * cgroup root (root_mem_cgroup). So we have to handle
1194 * dead_memcg from cgroup root separately.
1196 if (last != root_mem_cgroup)
1197 __invalidate_reclaim_iterators(root_mem_cgroup,
1202 * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
1203 * @memcg: hierarchy root
1204 * @fn: function to call for each task
1205 * @arg: argument passed to @fn
1207 * This function iterates over tasks attached to @memcg or to any of its
1208 * descendants and calls @fn for each task. If @fn returns a non-zero
1209 * value, the function breaks the iteration loop and returns the value.
1210 * Otherwise, it will iterate over all tasks and return 0.
1212 * This function must not be called for the root memory cgroup.
1214 int mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
1215 int (*fn)(struct task_struct *, void *), void *arg)
1217 struct mem_cgroup *iter;
1220 BUG_ON(memcg == root_mem_cgroup);
1222 for_each_mem_cgroup_tree(iter, memcg) {
1223 struct css_task_iter it;
1224 struct task_struct *task;
1226 css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it);
1227 while (!ret && (task = css_task_iter_next(&it)))
1228 ret = fn(task, arg);
1229 css_task_iter_end(&it);
1231 mem_cgroup_iter_break(memcg, iter);
1239 * mem_cgroup_page_lruvec - return lruvec for isolating/putting an LRU page
1241 * @pgdat: pgdat of the page
1243 * This function is only safe when following the LRU page isolation
1244 * and putback protocol: the LRU lock must be held, and the page must
1245 * either be PageLRU() or the caller must have isolated/allocated it.
1247 struct lruvec *mem_cgroup_page_lruvec(struct page *page, struct pglist_data *pgdat)
1249 struct mem_cgroup_per_node *mz;
1250 struct mem_cgroup *memcg;
1251 struct lruvec *lruvec;
1253 if (mem_cgroup_disabled()) {
1254 lruvec = &pgdat->__lruvec;
1258 memcg = page->mem_cgroup;
1259 VM_WARN_ON_ONCE_PAGE(!memcg, page);
1261 memcg = root_mem_cgroup;
1263 mz = mem_cgroup_page_nodeinfo(memcg, page);
1264 lruvec = &mz->lruvec;
1267 * Since a node can be onlined after the mem_cgroup was created,
1268 * we have to be prepared to initialize lruvec->zone here;
1269 * and if offlined then reonlined, we need to reinitialize it.
1271 if (unlikely(lruvec->pgdat != pgdat))
1272 lruvec->pgdat = pgdat;
1277 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1278 * @lruvec: mem_cgroup per zone lru vector
1279 * @lru: index of lru list the page is sitting on
1280 * @zid: zone id of the accounted pages
1281 * @nr_pages: positive when adding or negative when removing
1283 * This function must be called under lru_lock, just before a page is added
1284 * to or just after a page is removed from an lru list (that ordering being
1285 * so as to allow it to check that lru_size 0 is consistent with list_empty).
1287 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1288 int zid, int nr_pages)
1290 struct mem_cgroup_per_node *mz;
1291 unsigned long *lru_size;
1294 if (mem_cgroup_disabled())
1297 mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
1298 lru_size = &mz->lru_zone_size[zid][lru];
1301 *lru_size += nr_pages;
1304 if (WARN_ONCE(size < 0,
1305 "%s(%p, %d, %d): lru_size %ld\n",
1306 __func__, lruvec, lru, nr_pages, size)) {
1312 *lru_size += nr_pages;
1316 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1317 * @memcg: the memory cgroup
1319 * Returns the maximum amount of memory @mem can be charged with, in
1322 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1324 unsigned long margin = 0;
1325 unsigned long count;
1326 unsigned long limit;
1328 count = page_counter_read(&memcg->memory);
1329 limit = READ_ONCE(memcg->memory.max);
1331 margin = limit - count;
1333 if (do_memsw_account()) {
1334 count = page_counter_read(&memcg->memsw);
1335 limit = READ_ONCE(memcg->memsw.max);
1337 margin = min(margin, limit - count);
1346 * A routine for checking "mem" is under move_account() or not.
1348 * Checking a cgroup is mc.from or mc.to or under hierarchy of
1349 * moving cgroups. This is for waiting at high-memory pressure
1352 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1354 struct mem_cgroup *from;
1355 struct mem_cgroup *to;
1358 * Unlike task_move routines, we access mc.to, mc.from not under
1359 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1361 spin_lock(&mc.lock);
1367 ret = mem_cgroup_is_descendant(from, memcg) ||
1368 mem_cgroup_is_descendant(to, memcg);
1370 spin_unlock(&mc.lock);
1374 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1376 if (mc.moving_task && current != mc.moving_task) {
1377 if (mem_cgroup_under_move(memcg)) {
1379 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1380 /* moving charge context might have finished. */
1383 finish_wait(&mc.waitq, &wait);
1390 static char *memory_stat_format(struct mem_cgroup *memcg)
1395 seq_buf_init(&s, kmalloc(PAGE_SIZE, GFP_KERNEL), PAGE_SIZE);
1400 * Provide statistics on the state of the memory subsystem as
1401 * well as cumulative event counters that show past behavior.
1403 * This list is ordered following a combination of these gradients:
1404 * 1) generic big picture -> specifics and details
1405 * 2) reflecting userspace activity -> reflecting kernel heuristics
1407 * Current memory state:
1410 seq_buf_printf(&s, "anon %llu\n",
1411 (u64)memcg_page_state(memcg, MEMCG_RSS) *
1413 seq_buf_printf(&s, "file %llu\n",
1414 (u64)memcg_page_state(memcg, MEMCG_CACHE) *
1416 seq_buf_printf(&s, "kernel_stack %llu\n",
1417 (u64)memcg_page_state(memcg, MEMCG_KERNEL_STACK_KB) *
1419 seq_buf_printf(&s, "slab %llu\n",
1420 (u64)(memcg_page_state(memcg, NR_SLAB_RECLAIMABLE) +
1421 memcg_page_state(memcg, NR_SLAB_UNRECLAIMABLE)) *
1423 seq_buf_printf(&s, "sock %llu\n",
1424 (u64)memcg_page_state(memcg, MEMCG_SOCK) *
1427 seq_buf_printf(&s, "shmem %llu\n",
1428 (u64)memcg_page_state(memcg, NR_SHMEM) *
1430 seq_buf_printf(&s, "file_mapped %llu\n",
1431 (u64)memcg_page_state(memcg, NR_FILE_MAPPED) *
1433 seq_buf_printf(&s, "file_dirty %llu\n",
1434 (u64)memcg_page_state(memcg, NR_FILE_DIRTY) *
1436 seq_buf_printf(&s, "file_writeback %llu\n",
1437 (u64)memcg_page_state(memcg, NR_WRITEBACK) *
1441 * TODO: We should eventually replace our own MEMCG_RSS_HUGE counter
1442 * with the NR_ANON_THP vm counter, but right now it's a pain in the
1443 * arse because it requires migrating the work out of rmap to a place
1444 * where the page->mem_cgroup is set up and stable.
1446 seq_buf_printf(&s, "anon_thp %llu\n",
1447 (u64)memcg_page_state(memcg, MEMCG_RSS_HUGE) *
1450 for (i = 0; i < NR_LRU_LISTS; i++)
1451 seq_buf_printf(&s, "%s %llu\n", mem_cgroup_lru_names[i],
1452 (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
1455 seq_buf_printf(&s, "slab_reclaimable %llu\n",
1456 (u64)memcg_page_state(memcg, NR_SLAB_RECLAIMABLE) *
1458 seq_buf_printf(&s, "slab_unreclaimable %llu\n",
1459 (u64)memcg_page_state(memcg, NR_SLAB_UNRECLAIMABLE) *
1462 /* Accumulated memory events */
1464 seq_buf_printf(&s, "pgfault %lu\n", memcg_events(memcg, PGFAULT));
1465 seq_buf_printf(&s, "pgmajfault %lu\n", memcg_events(memcg, PGMAJFAULT));
1467 seq_buf_printf(&s, "workingset_refault %lu\n",
1468 memcg_page_state(memcg, WORKINGSET_REFAULT));
1469 seq_buf_printf(&s, "workingset_activate %lu\n",
1470 memcg_page_state(memcg, WORKINGSET_ACTIVATE));
1471 seq_buf_printf(&s, "workingset_nodereclaim %lu\n",
1472 memcg_page_state(memcg, WORKINGSET_NODERECLAIM));
1474 seq_buf_printf(&s, "pgrefill %lu\n", memcg_events(memcg, PGREFILL));
1475 seq_buf_printf(&s, "pgscan %lu\n",
1476 memcg_events(memcg, PGSCAN_KSWAPD) +
1477 memcg_events(memcg, PGSCAN_DIRECT));
1478 seq_buf_printf(&s, "pgsteal %lu\n",
1479 memcg_events(memcg, PGSTEAL_KSWAPD) +
1480 memcg_events(memcg, PGSTEAL_DIRECT));
1481 seq_buf_printf(&s, "pgactivate %lu\n", memcg_events(memcg, PGACTIVATE));
1482 seq_buf_printf(&s, "pgdeactivate %lu\n", memcg_events(memcg, PGDEACTIVATE));
1483 seq_buf_printf(&s, "pglazyfree %lu\n", memcg_events(memcg, PGLAZYFREE));
1484 seq_buf_printf(&s, "pglazyfreed %lu\n", memcg_events(memcg, PGLAZYFREED));
1486 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1487 seq_buf_printf(&s, "thp_fault_alloc %lu\n",
1488 memcg_events(memcg, THP_FAULT_ALLOC));
1489 seq_buf_printf(&s, "thp_collapse_alloc %lu\n",
1490 memcg_events(memcg, THP_COLLAPSE_ALLOC));
1491 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
1493 /* The above should easily fit into one page */
1494 WARN_ON_ONCE(seq_buf_has_overflowed(&s));
1499 #define K(x) ((x) << (PAGE_SHIFT-10))
1501 * mem_cgroup_print_oom_context: Print OOM information relevant to
1502 * memory controller.
1503 * @memcg: The memory cgroup that went over limit
1504 * @p: Task that is going to be killed
1506 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1509 void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p)
1514 pr_cont(",oom_memcg=");
1515 pr_cont_cgroup_path(memcg->css.cgroup);
1517 pr_cont(",global_oom");
1519 pr_cont(",task_memcg=");
1520 pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
1526 * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
1527 * memory controller.
1528 * @memcg: The memory cgroup that went over limit
1530 void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
1534 pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1535 K((u64)page_counter_read(&memcg->memory)),
1536 K((u64)memcg->memory.max), memcg->memory.failcnt);
1537 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1538 pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n",
1539 K((u64)page_counter_read(&memcg->swap)),
1540 K((u64)memcg->swap.max), memcg->swap.failcnt);
1542 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1543 K((u64)page_counter_read(&memcg->memsw)),
1544 K((u64)memcg->memsw.max), memcg->memsw.failcnt);
1545 pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1546 K((u64)page_counter_read(&memcg->kmem)),
1547 K((u64)memcg->kmem.max), memcg->kmem.failcnt);
1550 pr_info("Memory cgroup stats for ");
1551 pr_cont_cgroup_path(memcg->css.cgroup);
1553 buf = memory_stat_format(memcg);
1561 * Return the memory (and swap, if configured) limit for a memcg.
1563 unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg)
1567 max = memcg->memory.max;
1568 if (mem_cgroup_swappiness(memcg)) {
1569 unsigned long memsw_max;
1570 unsigned long swap_max;
1572 memsw_max = memcg->memsw.max;
1573 swap_max = memcg->swap.max;
1574 swap_max = min(swap_max, (unsigned long)total_swap_pages);
1575 max = min(max + swap_max, memsw_max);
1580 unsigned long mem_cgroup_size(struct mem_cgroup *memcg)
1582 return page_counter_read(&memcg->memory);
1585 static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1588 struct oom_control oc = {
1592 .gfp_mask = gfp_mask,
1597 if (mutex_lock_killable(&oom_lock))
1600 * A few threads which were not waiting at mutex_lock_killable() can
1601 * fail to bail out. Therefore, check again after holding oom_lock.
1603 ret = should_force_charge() || out_of_memory(&oc);
1604 mutex_unlock(&oom_lock);
1608 #if MAX_NUMNODES > 1
1611 * test_mem_cgroup_node_reclaimable
1612 * @memcg: the target memcg
1613 * @nid: the node ID to be checked.
1614 * @noswap : specify true here if the user wants flle only information.
1616 * This function returns whether the specified memcg contains any
1617 * reclaimable pages on a node. Returns true if there are any reclaimable
1618 * pages in the node.
1620 static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
1621 int nid, bool noswap)
1623 struct lruvec *lruvec = mem_cgroup_lruvec(NODE_DATA(nid), memcg);
1625 if (lruvec_page_state(lruvec, NR_INACTIVE_FILE) ||
1626 lruvec_page_state(lruvec, NR_ACTIVE_FILE))
1628 if (noswap || !total_swap_pages)
1630 if (lruvec_page_state(lruvec, NR_INACTIVE_ANON) ||
1631 lruvec_page_state(lruvec, NR_ACTIVE_ANON))
1638 * Always updating the nodemask is not very good - even if we have an empty
1639 * list or the wrong list here, we can start from some node and traverse all
1640 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1643 static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
1647 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1648 * pagein/pageout changes since the last update.
1650 if (!atomic_read(&memcg->numainfo_events))
1652 if (atomic_inc_return(&memcg->numainfo_updating) > 1)
1655 /* make a nodemask where this memcg uses memory from */
1656 memcg->scan_nodes = node_states[N_MEMORY];
1658 for_each_node_mask(nid, node_states[N_MEMORY]) {
1660 if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
1661 node_clear(nid, memcg->scan_nodes);
1664 atomic_set(&memcg->numainfo_events, 0);
1665 atomic_set(&memcg->numainfo_updating, 0);
1669 * Selecting a node where we start reclaim from. Because what we need is just
1670 * reducing usage counter, start from anywhere is O,K. Considering
1671 * memory reclaim from current node, there are pros. and cons.
1673 * Freeing memory from current node means freeing memory from a node which
1674 * we'll use or we've used. So, it may make LRU bad. And if several threads
1675 * hit limits, it will see a contention on a node. But freeing from remote
1676 * node means more costs for memory reclaim because of memory latency.
1678 * Now, we use round-robin. Better algorithm is welcomed.
1680 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1684 mem_cgroup_may_update_nodemask(memcg);
1685 node = memcg->last_scanned_node;
1687 node = next_node_in(node, memcg->scan_nodes);
1689 * mem_cgroup_may_update_nodemask might have seen no reclaimmable pages
1690 * last time it really checked all the LRUs due to rate limiting.
1691 * Fallback to the current node in that case for simplicity.
1693 if (unlikely(node == MAX_NUMNODES))
1694 node = numa_node_id();
1696 memcg->last_scanned_node = node;
1700 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1706 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
1709 unsigned long *total_scanned)
1711 struct mem_cgroup *victim = NULL;
1714 unsigned long excess;
1715 unsigned long nr_scanned;
1716 struct mem_cgroup_reclaim_cookie reclaim = {
1721 excess = soft_limit_excess(root_memcg);
1724 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1729 * If we have not been able to reclaim
1730 * anything, it might because there are
1731 * no reclaimable pages under this hierarchy
1736 * We want to do more targeted reclaim.
1737 * excess >> 2 is not to excessive so as to
1738 * reclaim too much, nor too less that we keep
1739 * coming back to reclaim from this cgroup
1741 if (total >= (excess >> 2) ||
1742 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1747 total += mem_cgroup_shrink_node(victim, gfp_mask, false,
1748 pgdat, &nr_scanned);
1749 *total_scanned += nr_scanned;
1750 if (!soft_limit_excess(root_memcg))
1753 mem_cgroup_iter_break(root_memcg, victim);
1757 #ifdef CONFIG_LOCKDEP
1758 static struct lockdep_map memcg_oom_lock_dep_map = {
1759 .name = "memcg_oom_lock",
1763 static DEFINE_SPINLOCK(memcg_oom_lock);
1766 * Check OOM-Killer is already running under our hierarchy.
1767 * If someone is running, return false.
1769 static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
1771 struct mem_cgroup *iter, *failed = NULL;
1773 spin_lock(&memcg_oom_lock);
1775 for_each_mem_cgroup_tree(iter, memcg) {
1776 if (iter->oom_lock) {
1778 * this subtree of our hierarchy is already locked
1779 * so we cannot give a lock.
1782 mem_cgroup_iter_break(memcg, iter);
1785 iter->oom_lock = true;
1790 * OK, we failed to lock the whole subtree so we have
1791 * to clean up what we set up to the failing subtree
1793 for_each_mem_cgroup_tree(iter, memcg) {
1794 if (iter == failed) {
1795 mem_cgroup_iter_break(memcg, iter);
1798 iter->oom_lock = false;
1801 mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
1803 spin_unlock(&memcg_oom_lock);
1808 static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1810 struct mem_cgroup *iter;
1812 spin_lock(&memcg_oom_lock);
1813 mutex_release(&memcg_oom_lock_dep_map, 1, _RET_IP_);
1814 for_each_mem_cgroup_tree(iter, memcg)
1815 iter->oom_lock = false;
1816 spin_unlock(&memcg_oom_lock);
1819 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1821 struct mem_cgroup *iter;
1823 spin_lock(&memcg_oom_lock);
1824 for_each_mem_cgroup_tree(iter, memcg)
1826 spin_unlock(&memcg_oom_lock);
1829 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1831 struct mem_cgroup *iter;
1834 * When a new child is created while the hierarchy is under oom,
1835 * mem_cgroup_oom_lock() may not be called. Watch for underflow.
1837 spin_lock(&memcg_oom_lock);
1838 for_each_mem_cgroup_tree(iter, memcg)
1839 if (iter->under_oom > 0)
1841 spin_unlock(&memcg_oom_lock);
1844 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1846 struct oom_wait_info {
1847 struct mem_cgroup *memcg;
1848 wait_queue_entry_t wait;
1851 static int memcg_oom_wake_function(wait_queue_entry_t *wait,
1852 unsigned mode, int sync, void *arg)
1854 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
1855 struct mem_cgroup *oom_wait_memcg;
1856 struct oom_wait_info *oom_wait_info;
1858 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1859 oom_wait_memcg = oom_wait_info->memcg;
1861 if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
1862 !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
1864 return autoremove_wake_function(wait, mode, sync, arg);
1867 static void memcg_oom_recover(struct mem_cgroup *memcg)
1870 * For the following lockless ->under_oom test, the only required
1871 * guarantee is that it must see the state asserted by an OOM when
1872 * this function is called as a result of userland actions
1873 * triggered by the notification of the OOM. This is trivially
1874 * achieved by invoking mem_cgroup_mark_under_oom() before
1875 * triggering notification.
1877 if (memcg && memcg->under_oom)
1878 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
1888 static enum oom_status mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
1890 enum oom_status ret;
1893 if (order > PAGE_ALLOC_COSTLY_ORDER)
1896 memcg_memory_event(memcg, MEMCG_OOM);
1899 * We are in the middle of the charge context here, so we
1900 * don't want to block when potentially sitting on a callstack
1901 * that holds all kinds of filesystem and mm locks.
1903 * cgroup1 allows disabling the OOM killer and waiting for outside
1904 * handling until the charge can succeed; remember the context and put
1905 * the task to sleep at the end of the page fault when all locks are
1908 * On the other hand, in-kernel OOM killer allows for an async victim
1909 * memory reclaim (oom_reaper) and that means that we are not solely
1910 * relying on the oom victim to make a forward progress and we can
1911 * invoke the oom killer here.
1913 * Please note that mem_cgroup_out_of_memory might fail to find a
1914 * victim and then we have to bail out from the charge path.
1916 if (memcg->oom_kill_disable) {
1917 if (!current->in_user_fault)
1919 css_get(&memcg->css);
1920 current->memcg_in_oom = memcg;
1921 current->memcg_oom_gfp_mask = mask;
1922 current->memcg_oom_order = order;
1927 mem_cgroup_mark_under_oom(memcg);
1929 locked = mem_cgroup_oom_trylock(memcg);
1932 mem_cgroup_oom_notify(memcg);
1934 mem_cgroup_unmark_under_oom(memcg);
1935 if (mem_cgroup_out_of_memory(memcg, mask, order))
1941 mem_cgroup_oom_unlock(memcg);
1947 * mem_cgroup_oom_synchronize - complete memcg OOM handling
1948 * @handle: actually kill/wait or just clean up the OOM state
1950 * This has to be called at the end of a page fault if the memcg OOM
1951 * handler was enabled.
1953 * Memcg supports userspace OOM handling where failed allocations must
1954 * sleep on a waitqueue until the userspace task resolves the
1955 * situation. Sleeping directly in the charge context with all kinds
1956 * of locks held is not a good idea, instead we remember an OOM state
1957 * in the task and mem_cgroup_oom_synchronize() has to be called at
1958 * the end of the page fault to complete the OOM handling.
1960 * Returns %true if an ongoing memcg OOM situation was detected and
1961 * completed, %false otherwise.
1963 bool mem_cgroup_oom_synchronize(bool handle)
1965 struct mem_cgroup *memcg = current->memcg_in_oom;
1966 struct oom_wait_info owait;
1969 /* OOM is global, do not handle */
1976 owait.memcg = memcg;
1977 owait.wait.flags = 0;
1978 owait.wait.func = memcg_oom_wake_function;
1979 owait.wait.private = current;
1980 INIT_LIST_HEAD(&owait.wait.entry);
1982 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
1983 mem_cgroup_mark_under_oom(memcg);
1985 locked = mem_cgroup_oom_trylock(memcg);
1988 mem_cgroup_oom_notify(memcg);
1990 if (locked && !memcg->oom_kill_disable) {
1991 mem_cgroup_unmark_under_oom(memcg);
1992 finish_wait(&memcg_oom_waitq, &owait.wait);
1993 mem_cgroup_out_of_memory(memcg, current->memcg_oom_gfp_mask,
1994 current->memcg_oom_order);
1997 mem_cgroup_unmark_under_oom(memcg);
1998 finish_wait(&memcg_oom_waitq, &owait.wait);
2002 mem_cgroup_oom_unlock(memcg);
2004 * There is no guarantee that an OOM-lock contender
2005 * sees the wakeups triggered by the OOM kill
2006 * uncharges. Wake any sleepers explicitely.
2008 memcg_oom_recover(memcg);
2011 current->memcg_in_oom = NULL;
2012 css_put(&memcg->css);
2017 * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
2018 * @victim: task to be killed by the OOM killer
2019 * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
2021 * Returns a pointer to a memory cgroup, which has to be cleaned up
2022 * by killing all belonging OOM-killable tasks.
2024 * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
2026 struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim,
2027 struct mem_cgroup *oom_domain)
2029 struct mem_cgroup *oom_group = NULL;
2030 struct mem_cgroup *memcg;
2032 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
2036 oom_domain = root_mem_cgroup;
2040 memcg = mem_cgroup_from_task(victim);
2041 if (memcg == root_mem_cgroup)
2045 * Traverse the memory cgroup hierarchy from the victim task's
2046 * cgroup up to the OOMing cgroup (or root) to find the
2047 * highest-level memory cgroup with oom.group set.
2049 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
2050 if (memcg->oom_group)
2053 if (memcg == oom_domain)
2058 css_get(&oom_group->css);
2065 void mem_cgroup_print_oom_group(struct mem_cgroup *memcg)
2067 pr_info("Tasks in ");
2068 pr_cont_cgroup_path(memcg->css.cgroup);
2069 pr_cont(" are going to be killed due to memory.oom.group set\n");
2073 * lock_page_memcg - lock a page->mem_cgroup binding
2076 * This function protects unlocked LRU pages from being moved to
2079 * It ensures lifetime of the returned memcg. Caller is responsible
2080 * for the lifetime of the page; __unlock_page_memcg() is available
2081 * when @page might get freed inside the locked section.
2083 struct mem_cgroup *lock_page_memcg(struct page *page)
2085 struct mem_cgroup *memcg;
2086 unsigned long flags;
2089 * The RCU lock is held throughout the transaction. The fast
2090 * path can get away without acquiring the memcg->move_lock
2091 * because page moving starts with an RCU grace period.
2093 * The RCU lock also protects the memcg from being freed when
2094 * the page state that is going to change is the only thing
2095 * preventing the page itself from being freed. E.g. writeback
2096 * doesn't hold a page reference and relies on PG_writeback to
2097 * keep off truncation, migration and so forth.
2101 if (mem_cgroup_disabled())
2104 memcg = page->mem_cgroup;
2105 if (unlikely(!memcg))
2108 if (atomic_read(&memcg->moving_account) <= 0)
2111 spin_lock_irqsave(&memcg->move_lock, flags);
2112 if (memcg != page->mem_cgroup) {
2113 spin_unlock_irqrestore(&memcg->move_lock, flags);
2118 * When charge migration first begins, we can have locked and
2119 * unlocked page stat updates happening concurrently. Track
2120 * the task who has the lock for unlock_page_memcg().
2122 memcg->move_lock_task = current;
2123 memcg->move_lock_flags = flags;
2127 EXPORT_SYMBOL(lock_page_memcg);
2130 * __unlock_page_memcg - unlock and unpin a memcg
2133 * Unlock and unpin a memcg returned by lock_page_memcg().
2135 void __unlock_page_memcg(struct mem_cgroup *memcg)
2137 if (memcg && memcg->move_lock_task == current) {
2138 unsigned long flags = memcg->move_lock_flags;
2140 memcg->move_lock_task = NULL;
2141 memcg->move_lock_flags = 0;
2143 spin_unlock_irqrestore(&memcg->move_lock, flags);
2150 * unlock_page_memcg - unlock a page->mem_cgroup binding
2153 void unlock_page_memcg(struct page *page)
2155 __unlock_page_memcg(page->mem_cgroup);
2157 EXPORT_SYMBOL(unlock_page_memcg);
2159 struct memcg_stock_pcp {
2160 struct mem_cgroup *cached; /* this never be root cgroup */
2161 unsigned int nr_pages;
2162 struct work_struct work;
2163 unsigned long flags;
2164 #define FLUSHING_CACHED_CHARGE 0
2166 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
2167 static DEFINE_MUTEX(percpu_charge_mutex);
2170 * consume_stock: Try to consume stocked charge on this cpu.
2171 * @memcg: memcg to consume from.
2172 * @nr_pages: how many pages to charge.
2174 * The charges will only happen if @memcg matches the current cpu's memcg
2175 * stock, and at least @nr_pages are available in that stock. Failure to
2176 * service an allocation will refill the stock.
2178 * returns true if successful, false otherwise.
2180 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2182 struct memcg_stock_pcp *stock;
2183 unsigned long flags;
2186 if (nr_pages > MEMCG_CHARGE_BATCH)
2189 local_irq_save(flags);
2191 stock = this_cpu_ptr(&memcg_stock);
2192 if (memcg == stock->cached && stock->nr_pages >= nr_pages) {
2193 stock->nr_pages -= nr_pages;
2197 local_irq_restore(flags);
2203 * Returns stocks cached in percpu and reset cached information.
2205 static void drain_stock(struct memcg_stock_pcp *stock)
2207 struct mem_cgroup *old = stock->cached;
2209 if (stock->nr_pages) {
2210 page_counter_uncharge(&old->memory, stock->nr_pages);
2211 if (do_memsw_account())
2212 page_counter_uncharge(&old->memsw, stock->nr_pages);
2213 css_put_many(&old->css, stock->nr_pages);
2214 stock->nr_pages = 0;
2216 stock->cached = NULL;
2219 static void drain_local_stock(struct work_struct *dummy)
2221 struct memcg_stock_pcp *stock;
2222 unsigned long flags;
2225 * The only protection from memory hotplug vs. drain_stock races is
2226 * that we always operate on local CPU stock here with IRQ disabled
2228 local_irq_save(flags);
2230 stock = this_cpu_ptr(&memcg_stock);
2232 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2234 local_irq_restore(flags);
2238 * Cache charges(val) to local per_cpu area.
2239 * This will be consumed by consume_stock() function, later.
2241 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2243 struct memcg_stock_pcp *stock;
2244 unsigned long flags;
2246 local_irq_save(flags);
2248 stock = this_cpu_ptr(&memcg_stock);
2249 if (stock->cached != memcg) { /* reset if necessary */
2251 stock->cached = memcg;
2253 stock->nr_pages += nr_pages;
2255 if (stock->nr_pages > MEMCG_CHARGE_BATCH)
2258 local_irq_restore(flags);
2262 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2263 * of the hierarchy under it.
2265 static void drain_all_stock(struct mem_cgroup *root_memcg)
2269 /* If someone's already draining, avoid adding running more workers. */
2270 if (!mutex_trylock(&percpu_charge_mutex))
2273 * Notify other cpus that system-wide "drain" is running
2274 * We do not care about races with the cpu hotplug because cpu down
2275 * as well as workers from this path always operate on the local
2276 * per-cpu data. CPU up doesn't touch memcg_stock at all.
2279 for_each_online_cpu(cpu) {
2280 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2281 struct mem_cgroup *memcg;
2285 memcg = stock->cached;
2286 if (memcg && stock->nr_pages &&
2287 mem_cgroup_is_descendant(memcg, root_memcg))
2292 !test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2294 drain_local_stock(&stock->work);
2296 schedule_work_on(cpu, &stock->work);
2300 mutex_unlock(&percpu_charge_mutex);
2303 static int memcg_hotplug_cpu_dead(unsigned int cpu)
2305 struct memcg_stock_pcp *stock;
2306 struct mem_cgroup *memcg, *mi;
2308 stock = &per_cpu(memcg_stock, cpu);
2311 for_each_mem_cgroup(memcg) {
2314 for (i = 0; i < MEMCG_NR_STAT; i++) {
2318 x = this_cpu_xchg(memcg->vmstats_percpu->stat[i], 0);
2320 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
2321 atomic_long_add(x, &memcg->vmstats[i]);
2323 if (i >= NR_VM_NODE_STAT_ITEMS)
2326 for_each_node(nid) {
2327 struct mem_cgroup_per_node *pn;
2329 pn = mem_cgroup_nodeinfo(memcg, nid);
2330 x = this_cpu_xchg(pn->lruvec_stat_cpu->count[i], 0);
2333 atomic_long_add(x, &pn->lruvec_stat[i]);
2334 } while ((pn = parent_nodeinfo(pn, nid)));
2338 for (i = 0; i < NR_VM_EVENT_ITEMS; i++) {
2341 x = this_cpu_xchg(memcg->vmstats_percpu->events[i], 0);
2343 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
2344 atomic_long_add(x, &memcg->vmevents[i]);
2351 static void reclaim_high(struct mem_cgroup *memcg,
2352 unsigned int nr_pages,
2356 if (page_counter_read(&memcg->memory) <= memcg->high)
2358 memcg_memory_event(memcg, MEMCG_HIGH);
2359 try_to_free_mem_cgroup_pages(memcg, nr_pages, gfp_mask, true);
2360 } while ((memcg = parent_mem_cgroup(memcg)));
2363 static void high_work_func(struct work_struct *work)
2365 struct mem_cgroup *memcg;
2367 memcg = container_of(work, struct mem_cgroup, high_work);
2368 reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
2372 * Clamp the maximum sleep time per allocation batch to 2 seconds. This is
2373 * enough to still cause a significant slowdown in most cases, while still
2374 * allowing diagnostics and tracing to proceed without becoming stuck.
2376 #define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ)
2379 * When calculating the delay, we use these either side of the exponentiation to
2380 * maintain precision and scale to a reasonable number of jiffies (see the table
2383 * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the
2384 * overage ratio to a delay.
2385 * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down down the
2386 * proposed penalty in order to reduce to a reasonable number of jiffies, and
2387 * to produce a reasonable delay curve.
2389 * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a
2390 * reasonable delay curve compared to precision-adjusted overage, not
2391 * penalising heavily at first, but still making sure that growth beyond the
2392 * limit penalises misbehaviour cgroups by slowing them down exponentially. For
2393 * example, with a high of 100 megabytes:
2395 * +-------+------------------------+
2396 * | usage | time to allocate in ms |
2397 * +-------+------------------------+
2419 * +-------+------------------------+
2421 #define MEMCG_DELAY_PRECISION_SHIFT 20
2422 #define MEMCG_DELAY_SCALING_SHIFT 14
2425 * Get the number of jiffies that we should penalise a mischievous cgroup which
2426 * is exceeding its memory.high by checking both it and its ancestors.
2428 static unsigned long calculate_high_delay(struct mem_cgroup *memcg,
2429 unsigned int nr_pages)
2431 unsigned long penalty_jiffies;
2432 u64 max_overage = 0;
2435 unsigned long usage, high;
2438 usage = page_counter_read(&memcg->memory);
2439 high = READ_ONCE(memcg->high);
2445 * Prevent division by 0 in overage calculation by acting as if
2446 * it was a threshold of 1 page
2448 high = max(high, 1UL);
2450 overage = usage - high;
2451 overage <<= MEMCG_DELAY_PRECISION_SHIFT;
2452 overage = div64_u64(overage, high);
2454 if (overage > max_overage)
2455 max_overage = overage;
2456 } while ((memcg = parent_mem_cgroup(memcg)) &&
2457 !mem_cgroup_is_root(memcg));
2463 * We use overage compared to memory.high to calculate the number of
2464 * jiffies to sleep (penalty_jiffies). Ideally this value should be
2465 * fairly lenient on small overages, and increasingly harsh when the
2466 * memcg in question makes it clear that it has no intention of stopping
2467 * its crazy behaviour, so we exponentially increase the delay based on
2470 penalty_jiffies = max_overage * max_overage * HZ;
2471 penalty_jiffies >>= MEMCG_DELAY_PRECISION_SHIFT;
2472 penalty_jiffies >>= MEMCG_DELAY_SCALING_SHIFT;
2475 * Factor in the task's own contribution to the overage, such that four
2476 * N-sized allocations are throttled approximately the same as one
2477 * 4N-sized allocation.
2479 * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or
2480 * larger the current charge patch is than that.
2482 penalty_jiffies = penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH;
2485 * Clamp the max delay per usermode return so as to still keep the
2486 * application moving forwards and also permit diagnostics, albeit
2489 return min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES);
2493 * Scheduled by try_charge() to be executed from the userland return path
2494 * and reclaims memory over the high limit.
2496 void mem_cgroup_handle_over_high(void)
2498 unsigned long penalty_jiffies;
2499 unsigned long pflags;
2500 unsigned int nr_pages = current->memcg_nr_pages_over_high;
2501 struct mem_cgroup *memcg;
2503 if (likely(!nr_pages))
2506 memcg = get_mem_cgroup_from_mm(current->mm);
2507 reclaim_high(memcg, nr_pages, GFP_KERNEL);
2508 current->memcg_nr_pages_over_high = 0;
2511 * memory.high is breached and reclaim is unable to keep up. Throttle
2512 * allocators proactively to slow down excessive growth.
2514 penalty_jiffies = calculate_high_delay(memcg, nr_pages);
2517 * Don't sleep if the amount of jiffies this memcg owes us is so low
2518 * that it's not even worth doing, in an attempt to be nice to those who
2519 * go only a small amount over their memory.high value and maybe haven't
2520 * been aggressively reclaimed enough yet.
2522 if (penalty_jiffies <= HZ / 100)
2526 * If we exit early, we're guaranteed to die (since
2527 * schedule_timeout_killable sets TASK_KILLABLE). This means we don't
2528 * need to account for any ill-begotten jiffies to pay them off later.
2530 psi_memstall_enter(&pflags);
2531 schedule_timeout_killable(penalty_jiffies);
2532 psi_memstall_leave(&pflags);
2535 css_put(&memcg->css);
2538 static int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2539 unsigned int nr_pages)
2541 unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
2542 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
2543 struct mem_cgroup *mem_over_limit;
2544 struct page_counter *counter;
2545 unsigned long nr_reclaimed;
2546 bool may_swap = true;
2547 bool drained = false;
2548 enum oom_status oom_status;
2550 if (mem_cgroup_is_root(memcg))
2553 if (consume_stock(memcg, nr_pages))
2556 if (!do_memsw_account() ||
2557 page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2558 if (page_counter_try_charge(&memcg->memory, batch, &counter))
2560 if (do_memsw_account())
2561 page_counter_uncharge(&memcg->memsw, batch);
2562 mem_over_limit = mem_cgroup_from_counter(counter, memory);
2564 mem_over_limit = mem_cgroup_from_counter(counter, memsw);
2568 if (batch > nr_pages) {
2574 * Memcg doesn't have a dedicated reserve for atomic
2575 * allocations. But like the global atomic pool, we need to
2576 * put the burden of reclaim on regular allocation requests
2577 * and let these go through as privileged allocations.
2579 if (gfp_mask & __GFP_ATOMIC)
2583 * Unlike in global OOM situations, memcg is not in a physical
2584 * memory shortage. Allow dying and OOM-killed tasks to
2585 * bypass the last charges so that they can exit quickly and
2586 * free their memory.
2588 if (unlikely(should_force_charge()))
2592 * Prevent unbounded recursion when reclaim operations need to
2593 * allocate memory. This might exceed the limits temporarily,
2594 * but we prefer facilitating memory reclaim and getting back
2595 * under the limit over triggering OOM kills in these cases.
2597 if (unlikely(current->flags & PF_MEMALLOC))
2600 if (unlikely(task_in_memcg_oom(current)))
2603 if (!gfpflags_allow_blocking(gfp_mask))
2606 memcg_memory_event(mem_over_limit, MEMCG_MAX);
2608 nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
2609 gfp_mask, may_swap);
2611 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2615 drain_all_stock(mem_over_limit);
2620 if (gfp_mask & __GFP_NORETRY)
2623 * Even though the limit is exceeded at this point, reclaim
2624 * may have been able to free some pages. Retry the charge
2625 * before killing the task.
2627 * Only for regular pages, though: huge pages are rather
2628 * unlikely to succeed so close to the limit, and we fall back
2629 * to regular pages anyway in case of failure.
2631 if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
2634 * At task move, charge accounts can be doubly counted. So, it's
2635 * better to wait until the end of task_move if something is going on.
2637 if (mem_cgroup_wait_acct_move(mem_over_limit))
2643 if (gfp_mask & __GFP_RETRY_MAYFAIL)
2646 if (gfp_mask & __GFP_NOFAIL)
2649 if (fatal_signal_pending(current))
2653 * keep retrying as long as the memcg oom killer is able to make
2654 * a forward progress or bypass the charge if the oom killer
2655 * couldn't make any progress.
2657 oom_status = mem_cgroup_oom(mem_over_limit, gfp_mask,
2658 get_order(nr_pages * PAGE_SIZE));
2659 switch (oom_status) {
2661 nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
2669 if (!(gfp_mask & __GFP_NOFAIL))
2673 * The allocation either can't fail or will lead to more memory
2674 * being freed very soon. Allow memory usage go over the limit
2675 * temporarily by force charging it.
2677 page_counter_charge(&memcg->memory, nr_pages);
2678 if (do_memsw_account())
2679 page_counter_charge(&memcg->memsw, nr_pages);
2680 css_get_many(&memcg->css, nr_pages);
2685 css_get_many(&memcg->css, batch);
2686 if (batch > nr_pages)
2687 refill_stock(memcg, batch - nr_pages);
2690 * If the hierarchy is above the normal consumption range, schedule
2691 * reclaim on returning to userland. We can perform reclaim here
2692 * if __GFP_RECLAIM but let's always punt for simplicity and so that
2693 * GFP_KERNEL can consistently be used during reclaim. @memcg is
2694 * not recorded as it most likely matches current's and won't
2695 * change in the meantime. As high limit is checked again before
2696 * reclaim, the cost of mismatch is negligible.
2699 if (page_counter_read(&memcg->memory) > memcg->high) {
2700 /* Don't bother a random interrupted task */
2701 if (in_interrupt()) {
2702 schedule_work(&memcg->high_work);
2705 current->memcg_nr_pages_over_high += batch;
2706 set_notify_resume(current);
2709 } while ((memcg = parent_mem_cgroup(memcg)));
2714 static void cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
2716 if (mem_cgroup_is_root(memcg))
2719 page_counter_uncharge(&memcg->memory, nr_pages);
2720 if (do_memsw_account())
2721 page_counter_uncharge(&memcg->memsw, nr_pages);
2723 css_put_many(&memcg->css, nr_pages);
2726 static void lock_page_lru(struct page *page, int *isolated)
2728 pg_data_t *pgdat = page_pgdat(page);
2730 spin_lock_irq(&pgdat->lru_lock);
2731 if (PageLRU(page)) {
2732 struct lruvec *lruvec;
2734 lruvec = mem_cgroup_page_lruvec(page, pgdat);
2736 del_page_from_lru_list(page, lruvec, page_lru(page));
2742 static void unlock_page_lru(struct page *page, int isolated)
2744 pg_data_t *pgdat = page_pgdat(page);
2747 struct lruvec *lruvec;
2749 lruvec = mem_cgroup_page_lruvec(page, pgdat);
2750 VM_BUG_ON_PAGE(PageLRU(page), page);
2752 add_page_to_lru_list(page, lruvec, page_lru(page));
2754 spin_unlock_irq(&pgdat->lru_lock);
2757 static void commit_charge(struct page *page, struct mem_cgroup *memcg,
2762 VM_BUG_ON_PAGE(page->mem_cgroup, page);
2765 * In some cases, SwapCache and FUSE(splice_buf->radixtree), the page
2766 * may already be on some other mem_cgroup's LRU. Take care of it.
2769 lock_page_lru(page, &isolated);
2772 * Nobody should be changing or seriously looking at
2773 * page->mem_cgroup at this point:
2775 * - the page is uncharged
2777 * - the page is off-LRU
2779 * - an anonymous fault has exclusive page access, except for
2780 * a locked page table
2782 * - a page cache insertion, a swapin fault, or a migration
2783 * have the page locked
2785 page->mem_cgroup = memcg;
2788 unlock_page_lru(page, isolated);
2791 #ifdef CONFIG_MEMCG_KMEM
2793 * Returns a pointer to the memory cgroup to which the kernel object is charged.
2795 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
2796 * cgroup_mutex, etc.
2798 struct mem_cgroup *mem_cgroup_from_obj(void *p)
2802 if (mem_cgroup_disabled())
2805 page = virt_to_head_page(p);
2808 * Slab pages don't have page->mem_cgroup set because corresponding
2809 * kmem caches can be reparented during the lifetime. That's why
2810 * memcg_from_slab_page() should be used instead.
2813 return memcg_from_slab_page(page);
2815 /* All other pages use page->mem_cgroup */
2816 return page->mem_cgroup;
2819 static int memcg_alloc_cache_id(void)
2824 id = ida_simple_get(&memcg_cache_ida,
2825 0, MEMCG_CACHES_MAX_SIZE, GFP_KERNEL);
2829 if (id < memcg_nr_cache_ids)
2833 * There's no space for the new id in memcg_caches arrays,
2834 * so we have to grow them.
2836 down_write(&memcg_cache_ids_sem);
2838 size = 2 * (id + 1);
2839 if (size < MEMCG_CACHES_MIN_SIZE)
2840 size = MEMCG_CACHES_MIN_SIZE;
2841 else if (size > MEMCG_CACHES_MAX_SIZE)
2842 size = MEMCG_CACHES_MAX_SIZE;
2844 err = memcg_update_all_caches(size);
2846 err = memcg_update_all_list_lrus(size);
2848 memcg_nr_cache_ids = size;
2850 up_write(&memcg_cache_ids_sem);
2853 ida_simple_remove(&memcg_cache_ida, id);
2859 static void memcg_free_cache_id(int id)
2861 ida_simple_remove(&memcg_cache_ida, id);
2864 struct memcg_kmem_cache_create_work {
2865 struct mem_cgroup *memcg;
2866 struct kmem_cache *cachep;
2867 struct work_struct work;
2870 static void memcg_kmem_cache_create_func(struct work_struct *w)
2872 struct memcg_kmem_cache_create_work *cw =
2873 container_of(w, struct memcg_kmem_cache_create_work, work);
2874 struct mem_cgroup *memcg = cw->memcg;
2875 struct kmem_cache *cachep = cw->cachep;
2877 memcg_create_kmem_cache(memcg, cachep);
2879 css_put(&memcg->css);
2884 * Enqueue the creation of a per-memcg kmem_cache.
2886 static void memcg_schedule_kmem_cache_create(struct mem_cgroup *memcg,
2887 struct kmem_cache *cachep)
2889 struct memcg_kmem_cache_create_work *cw;
2891 if (!css_tryget_online(&memcg->css))
2894 cw = kmalloc(sizeof(*cw), GFP_NOWAIT | __GFP_NOWARN);
2896 css_put(&memcg->css);
2901 cw->cachep = cachep;
2902 INIT_WORK(&cw->work, memcg_kmem_cache_create_func);
2904 queue_work(memcg_kmem_cache_wq, &cw->work);
2907 static inline bool memcg_kmem_bypass(void)
2909 if (in_interrupt() || !current->mm || (current->flags & PF_KTHREAD))
2915 * memcg_kmem_get_cache: select the correct per-memcg cache for allocation
2916 * @cachep: the original global kmem cache
2918 * Return the kmem_cache we're supposed to use for a slab allocation.
2919 * We try to use the current memcg's version of the cache.
2921 * If the cache does not exist yet, if we are the first user of it, we
2922 * create it asynchronously in a workqueue and let the current allocation
2923 * go through with the original cache.
2925 * This function takes a reference to the cache it returns to assure it
2926 * won't get destroyed while we are working with it. Once the caller is
2927 * done with it, memcg_kmem_put_cache() must be called to release the
2930 struct kmem_cache *memcg_kmem_get_cache(struct kmem_cache *cachep)
2932 struct mem_cgroup *memcg;
2933 struct kmem_cache *memcg_cachep;
2934 struct memcg_cache_array *arr;
2937 VM_BUG_ON(!is_root_cache(cachep));
2939 if (memcg_kmem_bypass())
2944 if (unlikely(current->active_memcg))
2945 memcg = current->active_memcg;
2947 memcg = mem_cgroup_from_task(current);
2949 if (!memcg || memcg == root_mem_cgroup)
2952 kmemcg_id = READ_ONCE(memcg->kmemcg_id);
2956 arr = rcu_dereference(cachep->memcg_params.memcg_caches);
2959 * Make sure we will access the up-to-date value. The code updating
2960 * memcg_caches issues a write barrier to match the data dependency
2961 * barrier inside READ_ONCE() (see memcg_create_kmem_cache()).
2963 memcg_cachep = READ_ONCE(arr->entries[kmemcg_id]);
2966 * If we are in a safe context (can wait, and not in interrupt
2967 * context), we could be be predictable and return right away.
2968 * This would guarantee that the allocation being performed
2969 * already belongs in the new cache.
2971 * However, there are some clashes that can arrive from locking.
2972 * For instance, because we acquire the slab_mutex while doing
2973 * memcg_create_kmem_cache, this means no further allocation
2974 * could happen with the slab_mutex held. So it's better to
2977 * If the memcg is dying or memcg_cache is about to be released,
2978 * don't bother creating new kmem_caches. Because memcg_cachep
2979 * is ZEROed as the fist step of kmem offlining, we don't need
2980 * percpu_ref_tryget_live() here. css_tryget_online() check in
2981 * memcg_schedule_kmem_cache_create() will prevent us from
2982 * creation of a new kmem_cache.
2984 if (unlikely(!memcg_cachep))
2985 memcg_schedule_kmem_cache_create(memcg, cachep);
2986 else if (percpu_ref_tryget(&memcg_cachep->memcg_params.refcnt))
2987 cachep = memcg_cachep;
2994 * memcg_kmem_put_cache: drop reference taken by memcg_kmem_get_cache
2995 * @cachep: the cache returned by memcg_kmem_get_cache
2997 void memcg_kmem_put_cache(struct kmem_cache *cachep)
2999 if (!is_root_cache(cachep))
3000 percpu_ref_put(&cachep->memcg_params.refcnt);
3004 * __memcg_kmem_charge_memcg: charge a kmem page
3005 * @page: page to charge
3006 * @gfp: reclaim mode
3007 * @order: allocation order
3008 * @memcg: memory cgroup to charge
3010 * Returns 0 on success, an error code on failure.
3012 int __memcg_kmem_charge_memcg(struct page *page, gfp_t gfp, int order,
3013 struct mem_cgroup *memcg)
3015 unsigned int nr_pages = 1 << order;
3016 struct page_counter *counter;
3019 ret = try_charge(memcg, gfp, nr_pages);
3023 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) &&
3024 !page_counter_try_charge(&memcg->kmem, nr_pages, &counter)) {
3027 * Enforce __GFP_NOFAIL allocation because callers are not
3028 * prepared to see failures and likely do not have any failure
3031 if (gfp & __GFP_NOFAIL) {
3032 page_counter_charge(&memcg->kmem, nr_pages);
3035 cancel_charge(memcg, nr_pages);
3042 * __memcg_kmem_charge: charge a kmem page to the current memory cgroup
3043 * @page: page to charge
3044 * @gfp: reclaim mode
3045 * @order: allocation order
3047 * Returns 0 on success, an error code on failure.
3049 int __memcg_kmem_charge(struct page *page, gfp_t gfp, int order)
3051 struct mem_cgroup *memcg;
3054 if (memcg_kmem_bypass())
3057 memcg = get_mem_cgroup_from_current();
3058 if (!mem_cgroup_is_root(memcg)) {
3059 ret = __memcg_kmem_charge_memcg(page, gfp, order, memcg);
3061 page->mem_cgroup = memcg;
3062 __SetPageKmemcg(page);
3065 css_put(&memcg->css);
3070 * __memcg_kmem_uncharge_memcg: uncharge a kmem page
3071 * @memcg: memcg to uncharge
3072 * @nr_pages: number of pages to uncharge
3074 void __memcg_kmem_uncharge_memcg(struct mem_cgroup *memcg,
3075 unsigned int nr_pages)
3077 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
3078 page_counter_uncharge(&memcg->kmem, nr_pages);
3080 page_counter_uncharge(&memcg->memory, nr_pages);
3081 if (do_memsw_account())
3082 page_counter_uncharge(&memcg->memsw, nr_pages);
3085 * __memcg_kmem_uncharge: uncharge a kmem page
3086 * @page: page to uncharge
3087 * @order: allocation order
3089 void __memcg_kmem_uncharge(struct page *page, int order)
3091 struct mem_cgroup *memcg = page->mem_cgroup;
3092 unsigned int nr_pages = 1 << order;
3097 VM_BUG_ON_PAGE(mem_cgroup_is_root(memcg), page);
3098 __memcg_kmem_uncharge_memcg(memcg, nr_pages);
3099 page->mem_cgroup = NULL;
3101 /* slab pages do not have PageKmemcg flag set */
3102 if (PageKmemcg(page))
3103 __ClearPageKmemcg(page);
3105 css_put_many(&memcg->css, nr_pages);
3107 #endif /* CONFIG_MEMCG_KMEM */
3109 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3112 * Because tail pages are not marked as "used", set it. We're under
3113 * pgdat->lru_lock and migration entries setup in all page mappings.
3115 void mem_cgroup_split_huge_fixup(struct page *head)
3119 if (mem_cgroup_disabled())
3122 for (i = 1; i < HPAGE_PMD_NR; i++)
3123 head[i].mem_cgroup = head->mem_cgroup;
3125 __mod_memcg_state(head->mem_cgroup, MEMCG_RSS_HUGE, -HPAGE_PMD_NR);
3127 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
3129 #ifdef CONFIG_MEMCG_SWAP
3131 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3132 * @entry: swap entry to be moved
3133 * @from: mem_cgroup which the entry is moved from
3134 * @to: mem_cgroup which the entry is moved to
3136 * It succeeds only when the swap_cgroup's record for this entry is the same
3137 * as the mem_cgroup's id of @from.
3139 * Returns 0 on success, -EINVAL on failure.
3141 * The caller must have charged to @to, IOW, called page_counter_charge() about
3142 * both res and memsw, and called css_get().
3144 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3145 struct mem_cgroup *from, struct mem_cgroup *to)
3147 unsigned short old_id, new_id;
3149 old_id = mem_cgroup_id(from);
3150 new_id = mem_cgroup_id(to);
3152 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3153 mod_memcg_state(from, MEMCG_SWAP, -1);
3154 mod_memcg_state(to, MEMCG_SWAP, 1);
3160 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3161 struct mem_cgroup *from, struct mem_cgroup *to)
3167 static DEFINE_MUTEX(memcg_max_mutex);
3169 static int mem_cgroup_resize_max(struct mem_cgroup *memcg,
3170 unsigned long max, bool memsw)
3172 bool enlarge = false;
3173 bool drained = false;
3175 bool limits_invariant;
3176 struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory;
3179 if (signal_pending(current)) {
3184 mutex_lock(&memcg_max_mutex);
3186 * Make sure that the new limit (memsw or memory limit) doesn't
3187 * break our basic invariant rule memory.max <= memsw.max.
3189 limits_invariant = memsw ? max >= memcg->memory.max :
3190 max <= memcg->memsw.max;
3191 if (!limits_invariant) {
3192 mutex_unlock(&memcg_max_mutex);
3196 if (max > counter->max)
3198 ret = page_counter_set_max(counter, max);
3199 mutex_unlock(&memcg_max_mutex);
3205 drain_all_stock(memcg);
3210 if (!try_to_free_mem_cgroup_pages(memcg, 1,
3211 GFP_KERNEL, !memsw)) {
3217 if (!ret && enlarge)
3218 memcg_oom_recover(memcg);
3223 unsigned long mem_cgroup_soft_limit_reclaim(pg_data_t *pgdat, int order,
3225 unsigned long *total_scanned)
3227 unsigned long nr_reclaimed = 0;
3228 struct mem_cgroup_per_node *mz, *next_mz = NULL;
3229 unsigned long reclaimed;
3231 struct mem_cgroup_tree_per_node *mctz;
3232 unsigned long excess;
3233 unsigned long nr_scanned;
3238 mctz = soft_limit_tree_node(pgdat->node_id);
3241 * Do not even bother to check the largest node if the root
3242 * is empty. Do it lockless to prevent lock bouncing. Races
3243 * are acceptable as soft limit is best effort anyway.
3245 if (!mctz || RB_EMPTY_ROOT(&mctz->rb_root))
3249 * This loop can run a while, specially if mem_cgroup's continuously
3250 * keep exceeding their soft limit and putting the system under
3257 mz = mem_cgroup_largest_soft_limit_node(mctz);
3262 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, pgdat,
3263 gfp_mask, &nr_scanned);
3264 nr_reclaimed += reclaimed;
3265 *total_scanned += nr_scanned;
3266 spin_lock_irq(&mctz->lock);
3267 __mem_cgroup_remove_exceeded(mz, mctz);
3270 * If we failed to reclaim anything from this memory cgroup
3271 * it is time to move on to the next cgroup
3275 next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
3277 excess = soft_limit_excess(mz->memcg);
3279 * One school of thought says that we should not add
3280 * back the node to the tree if reclaim returns 0.
3281 * But our reclaim could return 0, simply because due
3282 * to priority we are exposing a smaller subset of
3283 * memory to reclaim from. Consider this as a longer
3286 /* If excess == 0, no tree ops */
3287 __mem_cgroup_insert_exceeded(mz, mctz, excess);
3288 spin_unlock_irq(&mctz->lock);
3289 css_put(&mz->memcg->css);
3292 * Could not reclaim anything and there are no more
3293 * mem cgroups to try or we seem to be looping without
3294 * reclaiming anything.
3296 if (!nr_reclaimed &&
3298 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3300 } while (!nr_reclaimed);
3302 css_put(&next_mz->memcg->css);
3303 return nr_reclaimed;
3307 * Test whether @memcg has children, dead or alive. Note that this
3308 * function doesn't care whether @memcg has use_hierarchy enabled and
3309 * returns %true if there are child csses according to the cgroup
3310 * hierarchy. Testing use_hierarchy is the caller's responsiblity.
3312 static inline bool memcg_has_children(struct mem_cgroup *memcg)
3317 ret = css_next_child(NULL, &memcg->css);
3323 * Reclaims as many pages from the given memcg as possible.
3325 * Caller is responsible for holding css reference for memcg.
3327 static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
3329 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
3331 /* we call try-to-free pages for make this cgroup empty */
3332 lru_add_drain_all();
3334 drain_all_stock(memcg);
3336 /* try to free all pages in this cgroup */
3337 while (nr_retries && page_counter_read(&memcg->memory)) {
3340 if (signal_pending(current))
3343 progress = try_to_free_mem_cgroup_pages(memcg, 1,
3347 /* maybe some writeback is necessary */
3348 congestion_wait(BLK_RW_ASYNC, HZ/10);
3356 static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
3357 char *buf, size_t nbytes,
3360 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3362 if (mem_cgroup_is_root(memcg))
3364 return mem_cgroup_force_empty(memcg) ?: nbytes;
3367 #ifdef CONFIG_MEMCG_SWAP
3368 static int mem_cgroup_force_reclaim(struct cgroup_subsys_state *css,
3369 struct cftype *cft, u64 val)
3371 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3372 unsigned long nr_to_reclaim = val;
3373 unsigned long total = 0;
3376 for (loop = 0; loop < MEM_CGROUP_MAX_RECLAIM_LOOPS; loop++) {
3377 total += try_to_free_mem_cgroup_pages(memcg, nr_to_reclaim,
3381 * If nothing was reclaimed after two attempts, there
3382 * may be no reclaimable pages in this hierarchy.
3383 * If more than nr_to_reclaim pages were already reclaimed,
3384 * finish force reclaim.
3386 if (loop && (!total || total > nr_to_reclaim))
3390 pr_info("%s: [Mem_reclaim] Loop: %d - Total_reclaimed: %lu - nr_to_reclaim: %lu\n",
3391 __func__, loop, total, nr_to_reclaim);
3397 static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
3400 return mem_cgroup_from_css(css)->use_hierarchy;
3403 static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
3404 struct cftype *cft, u64 val)
3407 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3408 struct mem_cgroup *parent_memcg = mem_cgroup_from_css(memcg->css.parent);
3410 if (memcg->use_hierarchy == val)
3414 * If parent's use_hierarchy is set, we can't make any modifications
3415 * in the child subtrees. If it is unset, then the change can
3416 * occur, provided the current cgroup has no children.
3418 * For the root cgroup, parent_mem is NULL, we allow value to be
3419 * set if there are no children.
3421 if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
3422 (val == 1 || val == 0)) {
3423 if (!memcg_has_children(memcg))
3424 memcg->use_hierarchy = val;
3433 static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3437 if (mem_cgroup_is_root(memcg)) {
3438 val = memcg_page_state(memcg, MEMCG_CACHE) +
3439 memcg_page_state(memcg, MEMCG_RSS);
3441 val += memcg_page_state(memcg, MEMCG_SWAP);
3444 val = page_counter_read(&memcg->memory);
3446 val = page_counter_read(&memcg->memsw);
3459 static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
3462 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3463 struct page_counter *counter;
3465 switch (MEMFILE_TYPE(cft->private)) {
3467 counter = &memcg->memory;
3470 counter = &memcg->memsw;
3473 counter = &memcg->kmem;
3476 counter = &memcg->tcpmem;
3482 switch (MEMFILE_ATTR(cft->private)) {
3484 if (counter == &memcg->memory)
3485 return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
3486 if (counter == &memcg->memsw)
3487 return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
3488 return (u64)page_counter_read(counter) * PAGE_SIZE;
3490 return (u64)counter->max * PAGE_SIZE;
3492 return (u64)counter->watermark * PAGE_SIZE;
3494 return counter->failcnt;
3495 case RES_SOFT_LIMIT:
3496 return (u64)memcg->soft_limit * PAGE_SIZE;
3502 static void memcg_flush_percpu_vmstats(struct mem_cgroup *memcg)
3504 unsigned long stat[MEMCG_NR_STAT] = {0};
3505 struct mem_cgroup *mi;
3508 for_each_online_cpu(cpu)
3509 for (i = 0; i < MEMCG_NR_STAT; i++)
3510 stat[i] += per_cpu(memcg->vmstats_percpu->stat[i], cpu);
3512 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
3513 for (i = 0; i < MEMCG_NR_STAT; i++)
3514 atomic_long_add(stat[i], &mi->vmstats[i]);
3516 for_each_node(node) {
3517 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
3518 struct mem_cgroup_per_node *pi;
3520 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++)
3523 for_each_online_cpu(cpu)
3524 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++)
3526 pn->lruvec_stat_cpu->count[i], cpu);
3528 for (pi = pn; pi; pi = parent_nodeinfo(pi, node))
3529 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++)
3530 atomic_long_add(stat[i], &pi->lruvec_stat[i]);
3534 static void memcg_flush_percpu_vmevents(struct mem_cgroup *memcg)
3536 unsigned long events[NR_VM_EVENT_ITEMS];
3537 struct mem_cgroup *mi;
3540 for (i = 0; i < NR_VM_EVENT_ITEMS; i++)
3543 for_each_online_cpu(cpu)
3544 for (i = 0; i < NR_VM_EVENT_ITEMS; i++)
3545 events[i] += per_cpu(memcg->vmstats_percpu->events[i],
3548 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
3549 for (i = 0; i < NR_VM_EVENT_ITEMS; i++)
3550 atomic_long_add(events[i], &mi->vmevents[i]);
3553 #ifdef CONFIG_MEMCG_KMEM
3554 static int memcg_online_kmem(struct mem_cgroup *memcg)
3558 if (cgroup_memory_nokmem)
3561 BUG_ON(memcg->kmemcg_id >= 0);
3562 BUG_ON(memcg->kmem_state);
3564 memcg_id = memcg_alloc_cache_id();
3568 static_branch_inc(&memcg_kmem_enabled_key);
3570 * A memory cgroup is considered kmem-online as soon as it gets
3571 * kmemcg_id. Setting the id after enabling static branching will
3572 * guarantee no one starts accounting before all call sites are
3575 memcg->kmemcg_id = memcg_id;
3576 memcg->kmem_state = KMEM_ONLINE;
3577 INIT_LIST_HEAD(&memcg->kmem_caches);
3582 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3584 struct cgroup_subsys_state *css;
3585 struct mem_cgroup *parent, *child;
3588 if (memcg->kmem_state != KMEM_ONLINE)
3591 * Clear the online state before clearing memcg_caches array
3592 * entries. The slab_mutex in memcg_deactivate_kmem_caches()
3593 * guarantees that no cache will be created for this cgroup
3594 * after we are done (see memcg_create_kmem_cache()).
3596 memcg->kmem_state = KMEM_ALLOCATED;
3598 parent = parent_mem_cgroup(memcg);
3600 parent = root_mem_cgroup;
3603 * Deactivate and reparent kmem_caches.
3605 memcg_deactivate_kmem_caches(memcg, parent);
3607 kmemcg_id = memcg->kmemcg_id;
3608 BUG_ON(kmemcg_id < 0);
3611 * Change kmemcg_id of this cgroup and all its descendants to the
3612 * parent's id, and then move all entries from this cgroup's list_lrus
3613 * to ones of the parent. After we have finished, all list_lrus
3614 * corresponding to this cgroup are guaranteed to remain empty. The
3615 * ordering is imposed by list_lru_node->lock taken by
3616 * memcg_drain_all_list_lrus().
3618 rcu_read_lock(); /* can be called from css_free w/o cgroup_mutex */
3619 css_for_each_descendant_pre(css, &memcg->css) {
3620 child = mem_cgroup_from_css(css);
3621 BUG_ON(child->kmemcg_id != kmemcg_id);
3622 child->kmemcg_id = parent->kmemcg_id;
3623 if (!memcg->use_hierarchy)
3628 memcg_drain_all_list_lrus(kmemcg_id, parent);
3630 memcg_free_cache_id(kmemcg_id);
3633 static void memcg_free_kmem(struct mem_cgroup *memcg)
3635 /* css_alloc() failed, offlining didn't happen */
3636 if (unlikely(memcg->kmem_state == KMEM_ONLINE))
3637 memcg_offline_kmem(memcg);
3639 if (memcg->kmem_state == KMEM_ALLOCATED) {
3640 WARN_ON(!list_empty(&memcg->kmem_caches));
3641 static_branch_dec(&memcg_kmem_enabled_key);
3645 static int memcg_online_kmem(struct mem_cgroup *memcg)
3649 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3652 static void memcg_free_kmem(struct mem_cgroup *memcg)
3655 #endif /* CONFIG_MEMCG_KMEM */
3657 static int memcg_update_kmem_max(struct mem_cgroup *memcg,
3662 mutex_lock(&memcg_max_mutex);
3663 ret = page_counter_set_max(&memcg->kmem, max);
3664 mutex_unlock(&memcg_max_mutex);
3668 static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max)
3672 mutex_lock(&memcg_max_mutex);
3674 ret = page_counter_set_max(&memcg->tcpmem, max);
3678 if (!memcg->tcpmem_active) {
3680 * The active flag needs to be written after the static_key
3681 * update. This is what guarantees that the socket activation
3682 * function is the last one to run. See mem_cgroup_sk_alloc()
3683 * for details, and note that we don't mark any socket as
3684 * belonging to this memcg until that flag is up.
3686 * We need to do this, because static_keys will span multiple
3687 * sites, but we can't control their order. If we mark a socket
3688 * as accounted, but the accounting functions are not patched in
3689 * yet, we'll lose accounting.
3691 * We never race with the readers in mem_cgroup_sk_alloc(),
3692 * because when this value change, the code to process it is not
3695 static_branch_inc(&memcg_sockets_enabled_key);
3696 memcg->tcpmem_active = true;
3699 mutex_unlock(&memcg_max_mutex);
3704 * The user of this function is...
3707 static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
3708 char *buf, size_t nbytes, loff_t off)
3710 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3711 unsigned long nr_pages;
3714 buf = strstrip(buf);
3715 ret = page_counter_memparse(buf, "-1", &nr_pages);
3719 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3721 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3725 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3727 ret = mem_cgroup_resize_max(memcg, nr_pages, false);
3730 ret = mem_cgroup_resize_max(memcg, nr_pages, true);
3733 pr_warn_once("kmem.limit_in_bytes is deprecated and will be removed. "
3734 "Please report your usecase to linux-mm@kvack.org if you "
3735 "depend on this functionality.\n");
3736 ret = memcg_update_kmem_max(memcg, nr_pages);
3739 ret = memcg_update_tcp_max(memcg, nr_pages);
3743 case RES_SOFT_LIMIT:
3744 memcg->soft_limit = nr_pages;
3748 return ret ?: nbytes;
3751 static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
3752 size_t nbytes, loff_t off)
3754 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3755 struct page_counter *counter;
3757 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3759 counter = &memcg->memory;
3762 counter = &memcg->memsw;
3765 counter = &memcg->kmem;
3768 counter = &memcg->tcpmem;
3774 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3776 page_counter_reset_watermark(counter);
3779 counter->failcnt = 0;
3788 static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
3791 return mem_cgroup_from_css(css)->move_charge_at_immigrate;
3795 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3796 struct cftype *cft, u64 val)
3798 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3800 if (val & ~MOVE_MASK)
3804 * No kind of locking is needed in here, because ->can_attach() will
3805 * check this value once in the beginning of the process, and then carry
3806 * on with stale data. This means that changes to this value will only
3807 * affect task migrations starting after the change.
3809 memcg->move_charge_at_immigrate = val;
3813 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3814 struct cftype *cft, u64 val)
3822 #define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE))
3823 #define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON))
3824 #define LRU_ALL ((1 << NR_LRU_LISTS) - 1)
3826 static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
3827 int nid, unsigned int lru_mask)
3829 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
3830 unsigned long nr = 0;
3833 VM_BUG_ON((unsigned)nid >= nr_node_ids);
3836 if (!(BIT(lru) & lru_mask))
3838 nr += lruvec_page_state_local(lruvec, NR_LRU_BASE + lru);
3843 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
3844 unsigned int lru_mask)
3846 unsigned long nr = 0;
3850 if (!(BIT(lru) & lru_mask))
3852 nr += memcg_page_state_local(memcg, NR_LRU_BASE + lru);
3857 static int memcg_numa_stat_show(struct seq_file *m, void *v)
3861 unsigned int lru_mask;
3864 static const struct numa_stat stats[] = {
3865 { "total", LRU_ALL },
3866 { "file", LRU_ALL_FILE },
3867 { "anon", LRU_ALL_ANON },
3868 { "unevictable", BIT(LRU_UNEVICTABLE) },
3870 const struct numa_stat *stat;
3873 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
3875 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
3876 nr = mem_cgroup_nr_lru_pages(memcg, stat->lru_mask);
3877 seq_printf(m, "%s=%lu", stat->name, nr);
3878 for_each_node_state(nid, N_MEMORY) {
3879 nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
3881 seq_printf(m, " N%d=%lu", nid, nr);
3886 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
3887 struct mem_cgroup *iter;
3890 for_each_mem_cgroup_tree(iter, memcg)
3891 nr += mem_cgroup_nr_lru_pages(iter, stat->lru_mask);
3892 seq_printf(m, "hierarchical_%s=%lu", stat->name, nr);
3893 for_each_node_state(nid, N_MEMORY) {
3895 for_each_mem_cgroup_tree(iter, memcg)
3896 nr += mem_cgroup_node_nr_lru_pages(
3897 iter, nid, stat->lru_mask);
3898 seq_printf(m, " N%d=%lu", nid, nr);
3905 #endif /* CONFIG_NUMA */
3907 static const unsigned int memcg1_stats[] = {
3918 static const char *const memcg1_stat_names[] = {
3929 /* Universal VM events cgroup1 shows, original sort order */
3930 static const unsigned int memcg1_events[] = {
3937 static const char *const memcg1_event_names[] = {
3944 static int memcg_stat_show(struct seq_file *m, void *v)
3946 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
3947 unsigned long memory, memsw;
3948 struct mem_cgroup *mi;
3951 BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats));
3952 BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_lru_names) != NR_LRU_LISTS);
3954 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
3955 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
3957 seq_printf(m, "%s %lu\n", memcg1_stat_names[i],
3958 memcg_page_state_local(memcg, memcg1_stats[i]) *
3962 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
3963 seq_printf(m, "%s %lu\n", memcg1_event_names[i],
3964 memcg_events_local(memcg, memcg1_events[i]));
3966 for (i = 0; i < NR_LRU_LISTS; i++)
3967 seq_printf(m, "%s %lu\n", mem_cgroup_lru_names[i],
3968 memcg_page_state_local(memcg, NR_LRU_BASE + i) *
3971 /* Hierarchical information */
3972 memory = memsw = PAGE_COUNTER_MAX;
3973 for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
3974 memory = min(memory, mi->memory.max);
3975 memsw = min(memsw, mi->memsw.max);
3977 seq_printf(m, "hierarchical_memory_limit %llu\n",
3978 (u64)memory * PAGE_SIZE);
3979 if (do_memsw_account())
3980 seq_printf(m, "hierarchical_memsw_limit %llu\n",
3981 (u64)memsw * PAGE_SIZE);
3983 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
3984 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
3986 seq_printf(m, "total_%s %llu\n", memcg1_stat_names[i],
3987 (u64)memcg_page_state(memcg, memcg1_stats[i]) *
3991 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
3992 seq_printf(m, "total_%s %llu\n", memcg1_event_names[i],
3993 (u64)memcg_events(memcg, memcg1_events[i]));
3995 for (i = 0; i < NR_LRU_LISTS; i++)
3996 seq_printf(m, "total_%s %llu\n", mem_cgroup_lru_names[i],
3997 (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
4000 #ifdef CONFIG_DEBUG_VM
4003 struct mem_cgroup_per_node *mz;
4004 struct zone_reclaim_stat *rstat;
4005 unsigned long recent_rotated[2] = {0, 0};
4006 unsigned long recent_scanned[2] = {0, 0};
4008 for_each_online_pgdat(pgdat) {
4009 mz = mem_cgroup_nodeinfo(memcg, pgdat->node_id);
4010 rstat = &mz->lruvec.reclaim_stat;
4012 recent_rotated[0] += rstat->recent_rotated[0];
4013 recent_rotated[1] += rstat->recent_rotated[1];
4014 recent_scanned[0] += rstat->recent_scanned[0];
4015 recent_scanned[1] += rstat->recent_scanned[1];
4017 seq_printf(m, "recent_rotated_anon %lu\n", recent_rotated[0]);
4018 seq_printf(m, "recent_rotated_file %lu\n", recent_rotated[1]);
4019 seq_printf(m, "recent_scanned_anon %lu\n", recent_scanned[0]);
4020 seq_printf(m, "recent_scanned_file %lu\n", recent_scanned[1]);
4027 static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
4030 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4032 return mem_cgroup_swappiness(memcg);
4035 static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
4036 struct cftype *cft, u64 val)
4038 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4044 memcg->swappiness = val;
4046 vm_swappiness = val;
4051 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4053 struct mem_cgroup_threshold_ary *t;
4054 unsigned long usage;
4059 t = rcu_dereference(memcg->thresholds.primary);
4061 t = rcu_dereference(memcg->memsw_thresholds.primary);
4066 usage = mem_cgroup_usage(memcg, swap);
4069 * current_threshold points to threshold just below or equal to usage.
4070 * If it's not true, a threshold was crossed after last
4071 * call of __mem_cgroup_threshold().
4073 i = t->current_threshold;
4076 * Iterate backward over array of thresholds starting from
4077 * current_threshold and check if a threshold is crossed.
4078 * If none of thresholds below usage is crossed, we read
4079 * only one element of the array here.
4081 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4082 eventfd_signal(t->entries[i].eventfd, 1);
4084 /* i = current_threshold + 1 */
4088 * Iterate forward over array of thresholds starting from
4089 * current_threshold+1 and check if a threshold is crossed.
4090 * If none of thresholds above usage is crossed, we read
4091 * only one element of the array here.
4093 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4094 eventfd_signal(t->entries[i].eventfd, 1);
4096 /* Update current_threshold */
4097 t->current_threshold = i - 1;
4102 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4105 __mem_cgroup_threshold(memcg, false);
4106 if (do_memsw_account())
4107 __mem_cgroup_threshold(memcg, true);
4109 memcg = parent_mem_cgroup(memcg);
4113 static int compare_thresholds(const void *a, const void *b)
4115 const struct mem_cgroup_threshold *_a = a;
4116 const struct mem_cgroup_threshold *_b = b;
4118 if (_a->threshold > _b->threshold)
4121 if (_a->threshold < _b->threshold)
4127 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
4129 struct mem_cgroup_eventfd_list *ev;
4131 spin_lock(&memcg_oom_lock);
4133 list_for_each_entry(ev, &memcg->oom_notify, list)
4134 eventfd_signal(ev->eventfd, 1);
4136 spin_unlock(&memcg_oom_lock);
4140 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
4142 struct mem_cgroup *iter;
4144 for_each_mem_cgroup_tree(iter, memcg)
4145 mem_cgroup_oom_notify_cb(iter);
4148 static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4149 struct eventfd_ctx *eventfd, const char *args, enum res_type type)
4151 struct mem_cgroup_thresholds *thresholds;
4152 struct mem_cgroup_threshold_ary *new;
4153 unsigned long threshold;
4154 unsigned long usage;
4157 ret = page_counter_memparse(args, "-1", &threshold);
4161 mutex_lock(&memcg->thresholds_lock);
4164 thresholds = &memcg->thresholds;
4165 usage = mem_cgroup_usage(memcg, false);
4166 } else if (type == _MEMSWAP) {
4167 thresholds = &memcg->memsw_thresholds;
4168 usage = mem_cgroup_usage(memcg, true);
4172 /* Check if a threshold crossed before adding a new one */
4173 if (thresholds->primary)
4174 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4176 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4178 /* Allocate memory for new array of thresholds */
4179 new = kmalloc(struct_size(new, entries, size), GFP_KERNEL);
4186 /* Copy thresholds (if any) to new array */
4187 if (thresholds->primary) {
4188 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
4189 sizeof(struct mem_cgroup_threshold));
4192 /* Add new threshold */
4193 new->entries[size - 1].eventfd = eventfd;
4194 new->entries[size - 1].threshold = threshold;
4196 /* Sort thresholds. Registering of new threshold isn't time-critical */
4197 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
4198 compare_thresholds, NULL);
4200 /* Find current threshold */
4201 new->current_threshold = -1;
4202 for (i = 0; i < size; i++) {
4203 if (new->entries[i].threshold <= usage) {
4205 * new->current_threshold will not be used until
4206 * rcu_assign_pointer(), so it's safe to increment
4209 ++new->current_threshold;
4214 /* Free old spare buffer and save old primary buffer as spare */
4215 kfree(thresholds->spare);
4216 thresholds->spare = thresholds->primary;
4218 rcu_assign_pointer(thresholds->primary, new);
4220 /* To be sure that nobody uses thresholds */
4224 mutex_unlock(&memcg->thresholds_lock);
4229 static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4230 struct eventfd_ctx *eventfd, const char *args)
4232 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
4235 static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
4236 struct eventfd_ctx *eventfd, const char *args)
4238 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
4241 static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4242 struct eventfd_ctx *eventfd, enum res_type type)
4244 struct mem_cgroup_thresholds *thresholds;
4245 struct mem_cgroup_threshold_ary *new;
4246 unsigned long usage;
4247 int i, j, size, entries;
4249 mutex_lock(&memcg->thresholds_lock);
4252 thresholds = &memcg->thresholds;
4253 usage = mem_cgroup_usage(memcg, false);
4254 } else if (type == _MEMSWAP) {
4255 thresholds = &memcg->memsw_thresholds;
4256 usage = mem_cgroup_usage(memcg, true);
4260 if (!thresholds->primary)
4263 /* Check if a threshold crossed before removing */
4264 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4266 /* Calculate new number of threshold */
4268 for (i = 0; i < thresholds->primary->size; i++) {
4269 if (thresholds->primary->entries[i].eventfd != eventfd)
4275 new = thresholds->spare;
4277 /* If no items related to eventfd have been cleared, nothing to do */
4281 /* Set thresholds array to NULL if we don't have thresholds */
4290 /* Copy thresholds and find current threshold */
4291 new->current_threshold = -1;
4292 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4293 if (thresholds->primary->entries[i].eventfd == eventfd)
4296 new->entries[j] = thresholds->primary->entries[i];
4297 if (new->entries[j].threshold <= usage) {
4299 * new->current_threshold will not be used
4300 * until rcu_assign_pointer(), so it's safe to increment
4303 ++new->current_threshold;
4309 /* Swap primary and spare array */
4310 thresholds->spare = thresholds->primary;
4312 rcu_assign_pointer(thresholds->primary, new);
4314 /* To be sure that nobody uses thresholds */
4317 /* If all events are unregistered, free the spare array */
4319 kfree(thresholds->spare);
4320 thresholds->spare = NULL;
4323 mutex_unlock(&memcg->thresholds_lock);
4326 static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4327 struct eventfd_ctx *eventfd)
4329 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
4332 static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4333 struct eventfd_ctx *eventfd)
4335 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
4338 static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
4339 struct eventfd_ctx *eventfd, const char *args)
4341 struct mem_cgroup_eventfd_list *event;
4343 event = kmalloc(sizeof(*event), GFP_KERNEL);
4347 spin_lock(&memcg_oom_lock);
4349 event->eventfd = eventfd;
4350 list_add(&event->list, &memcg->oom_notify);
4352 /* already in OOM ? */
4353 if (memcg->under_oom)
4354 eventfd_signal(eventfd, 1);
4355 spin_unlock(&memcg_oom_lock);
4360 static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
4361 struct eventfd_ctx *eventfd)
4363 struct mem_cgroup_eventfd_list *ev, *tmp;
4365 spin_lock(&memcg_oom_lock);
4367 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
4368 if (ev->eventfd == eventfd) {
4369 list_del(&ev->list);
4374 spin_unlock(&memcg_oom_lock);
4377 static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
4379 struct mem_cgroup *memcg = mem_cgroup_from_seq(sf);
4381 seq_printf(sf, "oom_kill_disable %d\n", memcg->oom_kill_disable);
4382 seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
4383 seq_printf(sf, "oom_kill %lu\n",
4384 atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
4388 static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
4389 struct cftype *cft, u64 val)
4391 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4393 /* cannot set to root cgroup and only 0 and 1 are allowed */
4394 if (!css->parent || !((val == 0) || (val == 1)))
4397 memcg->oom_kill_disable = val;
4399 memcg_oom_recover(memcg);
4404 #ifdef CONFIG_CGROUP_WRITEBACK
4406 #include <trace/events/writeback.h>
4408 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4410 return wb_domain_init(&memcg->cgwb_domain, gfp);
4413 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4415 wb_domain_exit(&memcg->cgwb_domain);
4418 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4420 wb_domain_size_changed(&memcg->cgwb_domain);
4423 struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
4425 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4427 if (!memcg->css.parent)
4430 return &memcg->cgwb_domain;
4434 * idx can be of type enum memcg_stat_item or node_stat_item.
4435 * Keep in sync with memcg_exact_page().
4437 static unsigned long memcg_exact_page_state(struct mem_cgroup *memcg, int idx)
4439 long x = atomic_long_read(&memcg->vmstats[idx]);
4442 for_each_online_cpu(cpu)
4443 x += per_cpu_ptr(memcg->vmstats_percpu, cpu)->stat[idx];
4450 * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
4451 * @wb: bdi_writeback in question
4452 * @pfilepages: out parameter for number of file pages
4453 * @pheadroom: out parameter for number of allocatable pages according to memcg
4454 * @pdirty: out parameter for number of dirty pages
4455 * @pwriteback: out parameter for number of pages under writeback
4457 * Determine the numbers of file, headroom, dirty, and writeback pages in
4458 * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom
4459 * is a bit more involved.
4461 * A memcg's headroom is "min(max, high) - used". In the hierarchy, the
4462 * headroom is calculated as the lowest headroom of itself and the
4463 * ancestors. Note that this doesn't consider the actual amount of
4464 * available memory in the system. The caller should further cap
4465 * *@pheadroom accordingly.
4467 void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
4468 unsigned long *pheadroom, unsigned long *pdirty,
4469 unsigned long *pwriteback)
4471 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4472 struct mem_cgroup *parent;
4474 *pdirty = memcg_exact_page_state(memcg, NR_FILE_DIRTY);
4476 /* this should eventually include NR_UNSTABLE_NFS */
4477 *pwriteback = memcg_exact_page_state(memcg, NR_WRITEBACK);
4478 *pfilepages = memcg_exact_page_state(memcg, NR_INACTIVE_FILE) +
4479 memcg_exact_page_state(memcg, NR_ACTIVE_FILE);
4480 *pheadroom = PAGE_COUNTER_MAX;
4482 while ((parent = parent_mem_cgroup(memcg))) {
4483 unsigned long ceiling = min(memcg->memory.max, memcg->high);
4484 unsigned long used = page_counter_read(&memcg->memory);
4486 *pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
4492 * Foreign dirty flushing
4494 * There's an inherent mismatch between memcg and writeback. The former
4495 * trackes ownership per-page while the latter per-inode. This was a
4496 * deliberate design decision because honoring per-page ownership in the
4497 * writeback path is complicated, may lead to higher CPU and IO overheads
4498 * and deemed unnecessary given that write-sharing an inode across
4499 * different cgroups isn't a common use-case.
4501 * Combined with inode majority-writer ownership switching, this works well
4502 * enough in most cases but there are some pathological cases. For
4503 * example, let's say there are two cgroups A and B which keep writing to
4504 * different but confined parts of the same inode. B owns the inode and
4505 * A's memory is limited far below B's. A's dirty ratio can rise enough to
4506 * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
4507 * triggering background writeback. A will be slowed down without a way to
4508 * make writeback of the dirty pages happen.
4510 * Conditions like the above can lead to a cgroup getting repatedly and
4511 * severely throttled after making some progress after each
4512 * dirty_expire_interval while the underyling IO device is almost
4515 * Solving this problem completely requires matching the ownership tracking
4516 * granularities between memcg and writeback in either direction. However,
4517 * the more egregious behaviors can be avoided by simply remembering the
4518 * most recent foreign dirtying events and initiating remote flushes on
4519 * them when local writeback isn't enough to keep the memory clean enough.
4521 * The following two functions implement such mechanism. When a foreign
4522 * page - a page whose memcg and writeback ownerships don't match - is
4523 * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
4524 * bdi_writeback on the page owning memcg. When balance_dirty_pages()
4525 * decides that the memcg needs to sleep due to high dirty ratio, it calls
4526 * mem_cgroup_flush_foreign() which queues writeback on the recorded
4527 * foreign bdi_writebacks which haven't expired. Both the numbers of
4528 * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
4529 * limited to MEMCG_CGWB_FRN_CNT.
4531 * The mechanism only remembers IDs and doesn't hold any object references.
4532 * As being wrong occasionally doesn't matter, updates and accesses to the
4533 * records are lockless and racy.
4535 void mem_cgroup_track_foreign_dirty_slowpath(struct page *page,
4536 struct bdi_writeback *wb)
4538 struct mem_cgroup *memcg = page->mem_cgroup;
4539 struct memcg_cgwb_frn *frn;
4540 u64 now = get_jiffies_64();
4541 u64 oldest_at = now;
4545 trace_track_foreign_dirty(page, wb);
4548 * Pick the slot to use. If there is already a slot for @wb, keep
4549 * using it. If not replace the oldest one which isn't being
4552 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4553 frn = &memcg->cgwb_frn[i];
4554 if (frn->bdi_id == wb->bdi->id &&
4555 frn->memcg_id == wb->memcg_css->id)
4557 if (time_before64(frn->at, oldest_at) &&
4558 atomic_read(&frn->done.cnt) == 1) {
4560 oldest_at = frn->at;
4564 if (i < MEMCG_CGWB_FRN_CNT) {
4566 * Re-using an existing one. Update timestamp lazily to
4567 * avoid making the cacheline hot. We want them to be
4568 * reasonably up-to-date and significantly shorter than
4569 * dirty_expire_interval as that's what expires the record.
4570 * Use the shorter of 1s and dirty_expire_interval / 8.
4572 unsigned long update_intv =
4573 min_t(unsigned long, HZ,
4574 msecs_to_jiffies(dirty_expire_interval * 10) / 8);
4576 if (time_before64(frn->at, now - update_intv))
4578 } else if (oldest >= 0) {
4579 /* replace the oldest free one */
4580 frn = &memcg->cgwb_frn[oldest];
4581 frn->bdi_id = wb->bdi->id;
4582 frn->memcg_id = wb->memcg_css->id;
4587 /* issue foreign writeback flushes for recorded foreign dirtying events */
4588 void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
4590 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4591 unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
4592 u64 now = jiffies_64;
4595 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4596 struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
4599 * If the record is older than dirty_expire_interval,
4600 * writeback on it has already started. No need to kick it
4601 * off again. Also, don't start a new one if there's
4602 * already one in flight.
4604 if (time_after64(frn->at, now - intv) &&
4605 atomic_read(&frn->done.cnt) == 1) {
4607 trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
4608 cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id, 0,
4609 WB_REASON_FOREIGN_FLUSH,
4615 #else /* CONFIG_CGROUP_WRITEBACK */
4617 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4622 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4626 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4630 #endif /* CONFIG_CGROUP_WRITEBACK */
4633 * DO NOT USE IN NEW FILES.
4635 * "cgroup.event_control" implementation.
4637 * This is way over-engineered. It tries to support fully configurable
4638 * events for each user. Such level of flexibility is completely
4639 * unnecessary especially in the light of the planned unified hierarchy.
4641 * Please deprecate this and replace with something simpler if at all
4646 * Unregister event and free resources.
4648 * Gets called from workqueue.
4650 static void memcg_event_remove(struct work_struct *work)
4652 struct mem_cgroup_event *event =
4653 container_of(work, struct mem_cgroup_event, remove);
4654 struct mem_cgroup *memcg = event->memcg;
4656 remove_wait_queue(event->wqh, &event->wait);
4658 event->unregister_event(memcg, event->eventfd);
4660 /* Notify userspace the event is going away. */
4661 eventfd_signal(event->eventfd, 1);
4663 eventfd_ctx_put(event->eventfd);
4665 css_put(&memcg->css);
4669 * Gets called on EPOLLHUP on eventfd when user closes it.
4671 * Called with wqh->lock held and interrupts disabled.
4673 static int memcg_event_wake(wait_queue_entry_t *wait, unsigned mode,
4674 int sync, void *key)
4676 struct mem_cgroup_event *event =
4677 container_of(wait, struct mem_cgroup_event, wait);
4678 struct mem_cgroup *memcg = event->memcg;
4679 __poll_t flags = key_to_poll(key);
4681 if (flags & EPOLLHUP) {
4683 * If the event has been detached at cgroup removal, we
4684 * can simply return knowing the other side will cleanup
4687 * We can't race against event freeing since the other
4688 * side will require wqh->lock via remove_wait_queue(),
4691 spin_lock(&memcg->event_list_lock);
4692 if (!list_empty(&event->list)) {
4693 list_del_init(&event->list);
4695 * We are in atomic context, but cgroup_event_remove()
4696 * may sleep, so we have to call it in workqueue.
4698 schedule_work(&event->remove);
4700 spin_unlock(&memcg->event_list_lock);
4706 static void memcg_event_ptable_queue_proc(struct file *file,
4707 wait_queue_head_t *wqh, poll_table *pt)
4709 struct mem_cgroup_event *event =
4710 container_of(pt, struct mem_cgroup_event, pt);
4713 add_wait_queue(wqh, &event->wait);
4717 * DO NOT USE IN NEW FILES.
4719 * Parse input and register new cgroup event handler.
4721 * Input must be in format '<event_fd> <control_fd> <args>'.
4722 * Interpretation of args is defined by control file implementation.
4724 static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
4725 char *buf, size_t nbytes, loff_t off)
4727 struct cgroup_subsys_state *css = of_css(of);
4728 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4729 struct mem_cgroup_event *event;
4730 struct cgroup_subsys_state *cfile_css;
4731 unsigned int efd, cfd;
4738 buf = strstrip(buf);
4740 efd = simple_strtoul(buf, &endp, 10);
4745 cfd = simple_strtoul(buf, &endp, 10);
4746 if ((*endp != ' ') && (*endp != '\0'))
4750 event = kzalloc(sizeof(*event), GFP_KERNEL);
4754 event->memcg = memcg;
4755 INIT_LIST_HEAD(&event->list);
4756 init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
4757 init_waitqueue_func_entry(&event->wait, memcg_event_wake);
4758 INIT_WORK(&event->remove, memcg_event_remove);
4766 event->eventfd = eventfd_ctx_fileget(efile.file);
4767 if (IS_ERR(event->eventfd)) {
4768 ret = PTR_ERR(event->eventfd);
4775 goto out_put_eventfd;
4778 /* the process need read permission on control file */
4779 /* AV: shouldn't we check that it's been opened for read instead? */
4780 ret = inode_permission(file_inode(cfile.file), MAY_READ);
4785 * Determine the event callbacks and set them in @event. This used
4786 * to be done via struct cftype but cgroup core no longer knows
4787 * about these events. The following is crude but the whole thing
4788 * is for compatibility anyway.
4790 * DO NOT ADD NEW FILES.
4792 name = cfile.file->f_path.dentry->d_name.name;
4794 if (!strcmp(name, "memory.usage_in_bytes")) {
4795 event->register_event = mem_cgroup_usage_register_event;
4796 event->unregister_event = mem_cgroup_usage_unregister_event;
4797 } else if (!strcmp(name, "memory.oom_control")) {
4798 event->register_event = mem_cgroup_oom_register_event;
4799 event->unregister_event = mem_cgroup_oom_unregister_event;
4800 } else if (!strcmp(name, "memory.pressure_level")) {
4801 event->register_event = vmpressure_register_event;
4802 event->unregister_event = vmpressure_unregister_event;
4803 } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
4804 event->register_event = memsw_cgroup_usage_register_event;
4805 event->unregister_event = memsw_cgroup_usage_unregister_event;
4812 * Verify @cfile should belong to @css. Also, remaining events are
4813 * automatically removed on cgroup destruction but the removal is
4814 * asynchronous, so take an extra ref on @css.
4816 cfile_css = css_tryget_online_from_dir(cfile.file->f_path.dentry->d_parent,
4817 &memory_cgrp_subsys);
4819 if (IS_ERR(cfile_css))
4821 if (cfile_css != css) {
4826 ret = event->register_event(memcg, event->eventfd, buf);
4830 vfs_poll(efile.file, &event->pt);
4832 spin_lock(&memcg->event_list_lock);
4833 list_add(&event->list, &memcg->event_list);
4834 spin_unlock(&memcg->event_list_lock);
4846 eventfd_ctx_put(event->eventfd);
4855 static struct cftype mem_cgroup_legacy_files[] = {
4857 .name = "usage_in_bytes",
4858 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
4859 .read_u64 = mem_cgroup_read_u64,
4862 .name = "max_usage_in_bytes",
4863 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
4864 .write = mem_cgroup_reset,
4865 .read_u64 = mem_cgroup_read_u64,
4868 .name = "limit_in_bytes",
4869 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
4870 .write = mem_cgroup_write,
4871 .read_u64 = mem_cgroup_read_u64,
4874 .name = "soft_limit_in_bytes",
4875 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
4876 .write = mem_cgroup_write,
4877 .read_u64 = mem_cgroup_read_u64,
4881 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
4882 .write = mem_cgroup_reset,
4883 .read_u64 = mem_cgroup_read_u64,
4887 .seq_show = memcg_stat_show,
4890 .name = "force_empty",
4891 .write = mem_cgroup_force_empty_write,
4894 .name = "use_hierarchy",
4895 .write_u64 = mem_cgroup_hierarchy_write,
4896 .read_u64 = mem_cgroup_hierarchy_read,
4899 .name = "cgroup.event_control", /* XXX: for compat */
4900 .write = memcg_write_event_control,
4901 .flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE,
4904 .name = "swappiness",
4905 .read_u64 = mem_cgroup_swappiness_read,
4906 .write_u64 = mem_cgroup_swappiness_write,
4909 .name = "move_charge_at_immigrate",
4910 .read_u64 = mem_cgroup_move_charge_read,
4911 .write_u64 = mem_cgroup_move_charge_write,
4914 .name = "oom_control",
4915 .seq_show = mem_cgroup_oom_control_read,
4916 .write_u64 = mem_cgroup_oom_control_write,
4917 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
4920 .name = "pressure_level",
4924 .name = "numa_stat",
4925 .seq_show = memcg_numa_stat_show,
4929 .name = "kmem.limit_in_bytes",
4930 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
4931 .write = mem_cgroup_write,
4932 .read_u64 = mem_cgroup_read_u64,
4935 .name = "kmem.usage_in_bytes",
4936 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
4937 .read_u64 = mem_cgroup_read_u64,
4940 .name = "kmem.failcnt",
4941 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
4942 .write = mem_cgroup_reset,
4943 .read_u64 = mem_cgroup_read_u64,
4946 .name = "kmem.max_usage_in_bytes",
4947 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
4948 .write = mem_cgroup_reset,
4949 .read_u64 = mem_cgroup_read_u64,
4951 #if defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG)
4953 .name = "kmem.slabinfo",
4954 .seq_start = memcg_slab_start,
4955 .seq_next = memcg_slab_next,
4956 .seq_stop = memcg_slab_stop,
4957 .seq_show = memcg_slab_show,
4961 .name = "kmem.tcp.limit_in_bytes",
4962 .private = MEMFILE_PRIVATE(_TCP, RES_LIMIT),
4963 .write = mem_cgroup_write,
4964 .read_u64 = mem_cgroup_read_u64,
4967 .name = "kmem.tcp.usage_in_bytes",
4968 .private = MEMFILE_PRIVATE(_TCP, RES_USAGE),
4969 .read_u64 = mem_cgroup_read_u64,
4972 .name = "kmem.tcp.failcnt",
4973 .private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT),
4974 .write = mem_cgroup_reset,
4975 .read_u64 = mem_cgroup_read_u64,
4978 .name = "kmem.tcp.max_usage_in_bytes",
4979 .private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE),
4980 .write = mem_cgroup_reset,
4981 .read_u64 = mem_cgroup_read_u64,
4983 { }, /* terminate */
4987 * Private memory cgroup IDR
4989 * Swap-out records and page cache shadow entries need to store memcg
4990 * references in constrained space, so we maintain an ID space that is
4991 * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
4992 * memory-controlled cgroups to 64k.
4994 * However, there usually are many references to the oflline CSS after
4995 * the cgroup has been destroyed, such as page cache or reclaimable
4996 * slab objects, that don't need to hang on to the ID. We want to keep
4997 * those dead CSS from occupying IDs, or we might quickly exhaust the
4998 * relatively small ID space and prevent the creation of new cgroups
4999 * even when there are much fewer than 64k cgroups - possibly none.
5001 * Maintain a private 16-bit ID space for memcg, and allow the ID to
5002 * be freed and recycled when it's no longer needed, which is usually
5003 * when the CSS is offlined.
5005 * The only exception to that are records of swapped out tmpfs/shmem
5006 * pages that need to be attributed to live ancestors on swapin. But
5007 * those references are manageable from userspace.
5010 static DEFINE_IDR(mem_cgroup_idr);
5012 static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
5014 if (memcg->id.id > 0) {
5015 idr_remove(&mem_cgroup_idr, memcg->id.id);
5020 static void mem_cgroup_id_get_many(struct mem_cgroup *memcg, unsigned int n)
5022 refcount_add(n, &memcg->id.ref);
5025 static void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
5027 if (refcount_sub_and_test(n, &memcg->id.ref)) {
5028 mem_cgroup_id_remove(memcg);
5030 /* Memcg ID pins CSS */
5031 css_put(&memcg->css);
5035 static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
5037 mem_cgroup_id_put_many(memcg, 1);
5041 * mem_cgroup_from_id - look up a memcg from a memcg id
5042 * @id: the memcg id to look up
5044 * Caller must hold rcu_read_lock().
5046 struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
5048 WARN_ON_ONCE(!rcu_read_lock_held());
5049 return idr_find(&mem_cgroup_idr, id);
5052 static int alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5054 struct mem_cgroup_per_node *pn;
5057 * This routine is called against possible nodes.
5058 * But it's BUG to call kmalloc() against offline node.
5060 * TODO: this routine can waste much memory for nodes which will
5061 * never be onlined. It's better to use memory hotplug callback
5064 if (!node_state(node, N_NORMAL_MEMORY))
5066 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
5070 pn->lruvec_stat_local = alloc_percpu(struct lruvec_stat);
5071 if (!pn->lruvec_stat_local) {
5076 pn->lruvec_stat_cpu = alloc_percpu(struct lruvec_stat);
5077 if (!pn->lruvec_stat_cpu) {
5078 free_percpu(pn->lruvec_stat_local);
5083 lruvec_init(&pn->lruvec);
5084 pn->usage_in_excess = 0;
5085 pn->on_tree = false;
5088 memcg->nodeinfo[node] = pn;
5092 static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5094 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
5099 free_percpu(pn->lruvec_stat_cpu);
5100 free_percpu(pn->lruvec_stat_local);
5104 static void __mem_cgroup_free(struct mem_cgroup *memcg)
5109 free_mem_cgroup_per_node_info(memcg, node);
5110 free_percpu(memcg->vmstats_percpu);
5111 free_percpu(memcg->vmstats_local);
5115 static void mem_cgroup_free(struct mem_cgroup *memcg)
5117 memcg_wb_domain_exit(memcg);
5119 * Flush percpu vmstats and vmevents to guarantee the value correctness
5120 * on parent's and all ancestor levels.
5122 memcg_flush_percpu_vmstats(memcg);
5123 memcg_flush_percpu_vmevents(memcg);
5124 __mem_cgroup_free(memcg);
5127 static struct mem_cgroup *mem_cgroup_alloc(void)
5129 struct mem_cgroup *memcg;
5132 int __maybe_unused i;
5133 long error = -ENOMEM;
5135 size = sizeof(struct mem_cgroup);
5136 size += nr_node_ids * sizeof(struct mem_cgroup_per_node *);
5138 memcg = kzalloc(size, GFP_KERNEL);
5140 return ERR_PTR(error);
5142 memcg->id.id = idr_alloc(&mem_cgroup_idr, NULL,
5143 1, MEM_CGROUP_ID_MAX,
5145 if (memcg->id.id < 0) {
5146 error = memcg->id.id;
5150 memcg->vmstats_local = alloc_percpu(struct memcg_vmstats_percpu);
5151 if (!memcg->vmstats_local)
5154 memcg->vmstats_percpu = alloc_percpu(struct memcg_vmstats_percpu);
5155 if (!memcg->vmstats_percpu)
5159 if (alloc_mem_cgroup_per_node_info(memcg, node))
5162 if (memcg_wb_domain_init(memcg, GFP_KERNEL))
5165 INIT_WORK(&memcg->high_work, high_work_func);
5166 memcg->last_scanned_node = MAX_NUMNODES;
5167 INIT_LIST_HEAD(&memcg->oom_notify);
5168 mutex_init(&memcg->thresholds_lock);
5169 spin_lock_init(&memcg->move_lock);
5170 vmpressure_init(&memcg->vmpressure);
5171 INIT_LIST_HEAD(&memcg->event_list);
5172 spin_lock_init(&memcg->event_list_lock);
5173 memcg->socket_pressure = jiffies;
5174 #ifdef CONFIG_MEMCG_KMEM
5175 memcg->kmemcg_id = -1;
5177 #ifdef CONFIG_CGROUP_WRITEBACK
5178 INIT_LIST_HEAD(&memcg->cgwb_list);
5179 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5180 memcg->cgwb_frn[i].done =
5181 __WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
5183 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5184 spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
5185 INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
5186 memcg->deferred_split_queue.split_queue_len = 0;
5188 idr_replace(&mem_cgroup_idr, memcg, memcg->id.id);
5191 mem_cgroup_id_remove(memcg);
5192 __mem_cgroup_free(memcg);
5193 return ERR_PTR(error);
5196 static struct cgroup_subsys_state * __ref
5197 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
5199 struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
5200 struct mem_cgroup *memcg;
5201 long error = -ENOMEM;
5203 memcg = mem_cgroup_alloc();
5205 return ERR_CAST(memcg);
5207 memcg->high = PAGE_COUNTER_MAX;
5208 memcg->soft_limit = PAGE_COUNTER_MAX;
5210 memcg->swappiness = mem_cgroup_swappiness(parent);
5211 memcg->oom_kill_disable = parent->oom_kill_disable;
5213 if (parent && parent->use_hierarchy) {
5214 memcg->use_hierarchy = true;
5215 page_counter_init(&memcg->memory, &parent->memory);
5216 page_counter_init(&memcg->swap, &parent->swap);
5217 page_counter_init(&memcg->memsw, &parent->memsw);
5218 page_counter_init(&memcg->kmem, &parent->kmem);
5219 page_counter_init(&memcg->tcpmem, &parent->tcpmem);
5221 page_counter_init(&memcg->memory, NULL);
5222 page_counter_init(&memcg->swap, NULL);
5223 page_counter_init(&memcg->memsw, NULL);
5224 page_counter_init(&memcg->kmem, NULL);
5225 page_counter_init(&memcg->tcpmem, NULL);
5227 * Deeper hierachy with use_hierarchy == false doesn't make
5228 * much sense so let cgroup subsystem know about this
5229 * unfortunate state in our controller.
5231 if (parent != root_mem_cgroup)
5232 memory_cgrp_subsys.broken_hierarchy = true;
5235 /* The following stuff does not apply to the root */
5237 #ifdef CONFIG_MEMCG_KMEM
5238 INIT_LIST_HEAD(&memcg->kmem_caches);
5240 root_mem_cgroup = memcg;
5244 error = memcg_online_kmem(memcg);
5248 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5249 static_branch_inc(&memcg_sockets_enabled_key);
5253 mem_cgroup_id_remove(memcg);
5254 mem_cgroup_free(memcg);
5255 return ERR_PTR(error);
5258 static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
5260 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5263 * A memcg must be visible for memcg_expand_shrinker_maps()
5264 * by the time the maps are allocated. So, we allocate maps
5265 * here, when for_each_mem_cgroup() can't skip it.
5267 if (memcg_alloc_shrinker_maps(memcg)) {
5268 mem_cgroup_id_remove(memcg);
5272 /* Online state pins memcg ID, memcg ID pins CSS */
5273 refcount_set(&memcg->id.ref, 1);
5278 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
5280 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5281 struct mem_cgroup_event *event, *tmp;
5284 * Unregister events and notify userspace.
5285 * Notify userspace about cgroup removing only after rmdir of cgroup
5286 * directory to avoid race between userspace and kernelspace.
5288 spin_lock(&memcg->event_list_lock);
5289 list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
5290 list_del_init(&event->list);
5291 schedule_work(&event->remove);
5293 spin_unlock(&memcg->event_list_lock);
5295 page_counter_set_min(&memcg->memory, 0);
5296 page_counter_set_low(&memcg->memory, 0);
5298 memcg_offline_kmem(memcg);
5299 wb_memcg_offline(memcg);
5301 drain_all_stock(memcg);
5303 mem_cgroup_id_put(memcg);
5306 static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
5308 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5310 invalidate_reclaim_iterators(memcg);
5313 static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
5315 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5316 int __maybe_unused i;
5318 #ifdef CONFIG_CGROUP_WRITEBACK
5319 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5320 wb_wait_for_completion(&memcg->cgwb_frn[i].done);
5322 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5323 static_branch_dec(&memcg_sockets_enabled_key);
5325 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg->tcpmem_active)
5326 static_branch_dec(&memcg_sockets_enabled_key);
5328 vmpressure_cleanup(&memcg->vmpressure);
5329 cancel_work_sync(&memcg->high_work);
5330 mem_cgroup_remove_from_trees(memcg);
5331 memcg_free_shrinker_maps(memcg);
5332 memcg_free_kmem(memcg);
5333 mem_cgroup_free(memcg);
5337 * mem_cgroup_css_reset - reset the states of a mem_cgroup
5338 * @css: the target css
5340 * Reset the states of the mem_cgroup associated with @css. This is
5341 * invoked when the userland requests disabling on the default hierarchy
5342 * but the memcg is pinned through dependency. The memcg should stop
5343 * applying policies and should revert to the vanilla state as it may be
5344 * made visible again.
5346 * The current implementation only resets the essential configurations.
5347 * This needs to be expanded to cover all the visible parts.
5349 static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
5351 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5353 page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
5354 page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
5355 page_counter_set_max(&memcg->memsw, PAGE_COUNTER_MAX);
5356 page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
5357 page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
5358 page_counter_set_min(&memcg->memory, 0);
5359 page_counter_set_low(&memcg->memory, 0);
5360 memcg->high = PAGE_COUNTER_MAX;
5361 memcg->soft_limit = PAGE_COUNTER_MAX;
5362 memcg_wb_domain_size_changed(memcg);
5366 /* Handlers for move charge at task migration. */
5367 static int mem_cgroup_do_precharge(unsigned long count)
5371 /* Try a single bulk charge without reclaim first, kswapd may wake */
5372 ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count);
5374 mc.precharge += count;
5378 /* Try charges one by one with reclaim, but do not retry */
5380 ret = try_charge(mc.to, GFP_KERNEL | __GFP_NORETRY, 1);
5394 enum mc_target_type {
5401 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5402 unsigned long addr, pte_t ptent)
5404 struct page *page = vm_normal_page(vma, addr, ptent);
5406 if (!page || !page_mapped(page))
5408 if (PageAnon(page)) {
5409 if (!(mc.flags & MOVE_ANON))
5412 if (!(mc.flags & MOVE_FILE))
5415 if (!get_page_unless_zero(page))
5421 #if defined(CONFIG_SWAP) || defined(CONFIG_DEVICE_PRIVATE)
5422 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5423 pte_t ptent, swp_entry_t *entry)
5425 struct page *page = NULL;
5426 swp_entry_t ent = pte_to_swp_entry(ptent);
5428 if (!(mc.flags & MOVE_ANON) || non_swap_entry(ent))
5432 * Handle MEMORY_DEVICE_PRIVATE which are ZONE_DEVICE page belonging to
5433 * a device and because they are not accessible by CPU they are store
5434 * as special swap entry in the CPU page table.
5436 if (is_device_private_entry(ent)) {
5437 page = device_private_entry_to_page(ent);
5439 * MEMORY_DEVICE_PRIVATE means ZONE_DEVICE page and which have
5440 * a refcount of 1 when free (unlike normal page)
5442 if (!page_ref_add_unless(page, 1, 1))
5448 * Because lookup_swap_cache() updates some statistics counter,
5449 * we call find_get_page() with swapper_space directly.
5451 page = find_get_page(swap_address_space(ent), swp_offset(ent));
5452 if (do_memsw_account())
5453 entry->val = ent.val;
5458 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5459 pte_t ptent, swp_entry_t *entry)
5465 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5466 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5468 struct page *page = NULL;
5469 struct address_space *mapping;
5472 if (!vma->vm_file) /* anonymous vma */
5474 if (!(mc.flags & MOVE_FILE))
5477 mapping = vma->vm_file->f_mapping;
5478 pgoff = linear_page_index(vma, addr);
5480 /* page is moved even if it's not RSS of this task(page-faulted). */
5482 /* shmem/tmpfs may report page out on swap: account for that too. */
5483 if (shmem_mapping(mapping)) {
5484 page = find_get_entry(mapping, pgoff);
5485 if (xa_is_value(page)) {
5486 swp_entry_t swp = radix_to_swp_entry(page);
5487 if (do_memsw_account())
5489 page = find_get_page(swap_address_space(swp),
5493 page = find_get_page(mapping, pgoff);
5495 page = find_get_page(mapping, pgoff);
5501 * mem_cgroup_move_account - move account of the page
5503 * @compound: charge the page as compound or small page
5504 * @from: mem_cgroup which the page is moved from.
5505 * @to: mem_cgroup which the page is moved to. @from != @to.
5507 * The caller must make sure the page is not on LRU (isolate_page() is useful.)
5509 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
5512 static int mem_cgroup_move_account(struct page *page,
5514 struct mem_cgroup *from,
5515 struct mem_cgroup *to)
5517 struct lruvec *from_vec, *to_vec;
5518 struct pglist_data *pgdat;
5519 unsigned long flags;
5520 unsigned int nr_pages = compound ? hpage_nr_pages(page) : 1;
5524 VM_BUG_ON(from == to);
5525 VM_BUG_ON_PAGE(PageLRU(page), page);
5526 VM_BUG_ON(compound && !PageTransHuge(page));
5529 * Prevent mem_cgroup_migrate() from looking at
5530 * page->mem_cgroup of its source page while we change it.
5533 if (!trylock_page(page))
5537 if (page->mem_cgroup != from)
5540 anon = PageAnon(page);
5542 pgdat = page_pgdat(page);
5543 from_vec = mem_cgroup_lruvec(from, pgdat);
5544 to_vec = mem_cgroup_lruvec(to, pgdat);
5546 spin_lock_irqsave(&from->move_lock, flags);
5548 if (!anon && page_mapped(page)) {
5549 __mod_lruvec_state(from_vec, NR_FILE_MAPPED, -nr_pages);
5550 __mod_lruvec_state(to_vec, NR_FILE_MAPPED, nr_pages);
5554 * move_lock grabbed above and caller set from->moving_account, so
5555 * mod_memcg_page_state will serialize updates to PageDirty.
5556 * So mapping should be stable for dirty pages.
5558 if (!anon && PageDirty(page)) {
5559 struct address_space *mapping = page_mapping(page);
5561 if (mapping_cap_account_dirty(mapping)) {
5562 __mod_lruvec_state(from_vec, NR_FILE_DIRTY, -nr_pages);
5563 __mod_lruvec_state(to_vec, NR_FILE_DIRTY, nr_pages);
5567 if (PageWriteback(page)) {
5568 __mod_lruvec_state(from_vec, NR_WRITEBACK, -nr_pages);
5569 __mod_lruvec_state(to_vec, NR_WRITEBACK, nr_pages);
5573 * It is safe to change page->mem_cgroup here because the page
5574 * is referenced, charged, and isolated - we can't race with
5575 * uncharging, charging, migration, or LRU putback.
5578 /* caller should have done css_get */
5579 page->mem_cgroup = to;
5581 spin_unlock_irqrestore(&from->move_lock, flags);
5585 local_irq_disable();
5586 mem_cgroup_charge_statistics(to, page, compound, nr_pages);
5587 memcg_check_events(to, page);
5588 mem_cgroup_charge_statistics(from, page, compound, -nr_pages);
5589 memcg_check_events(from, page);
5598 * get_mctgt_type - get target type of moving charge
5599 * @vma: the vma the pte to be checked belongs
5600 * @addr: the address corresponding to the pte to be checked
5601 * @ptent: the pte to be checked
5602 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5605 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5606 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5607 * move charge. if @target is not NULL, the page is stored in target->page
5608 * with extra refcnt got(Callers should handle it).
5609 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5610 * target for charge migration. if @target is not NULL, the entry is stored
5612 * 3(MC_TARGET_DEVICE): like MC_TARGET_PAGE but page is MEMORY_DEVICE_PRIVATE
5613 * (so ZONE_DEVICE page and thus not on the lru).
5614 * For now we such page is charge like a regular page would be as for all
5615 * intent and purposes it is just special memory taking the place of a
5618 * See Documentations/vm/hmm.txt and include/linux/hmm.h
5620 * Called with pte lock held.
5623 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
5624 unsigned long addr, pte_t ptent, union mc_target *target)
5626 struct page *page = NULL;
5627 enum mc_target_type ret = MC_TARGET_NONE;
5628 swp_entry_t ent = { .val = 0 };
5630 if (pte_present(ptent))
5631 page = mc_handle_present_pte(vma, addr, ptent);
5632 else if (is_swap_pte(ptent))
5633 page = mc_handle_swap_pte(vma, ptent, &ent);
5634 else if (pte_none(ptent))
5635 page = mc_handle_file_pte(vma, addr, ptent, &ent);
5637 if (!page && !ent.val)
5641 * Do only loose check w/o serialization.
5642 * mem_cgroup_move_account() checks the page is valid or
5643 * not under LRU exclusion.
5645 if (page->mem_cgroup == mc.from) {
5646 ret = MC_TARGET_PAGE;
5647 if (is_device_private_page(page))
5648 ret = MC_TARGET_DEVICE;
5650 target->page = page;
5652 if (!ret || !target)
5656 * There is a swap entry and a page doesn't exist or isn't charged.
5657 * But we cannot move a tail-page in a THP.
5659 if (ent.val && !ret && (!page || !PageTransCompound(page)) &&
5660 mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
5661 ret = MC_TARGET_SWAP;
5668 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5670 * We don't consider PMD mapped swapping or file mapped pages because THP does
5671 * not support them for now.
5672 * Caller should make sure that pmd_trans_huge(pmd) is true.
5674 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5675 unsigned long addr, pmd_t pmd, union mc_target *target)
5677 struct page *page = NULL;
5678 enum mc_target_type ret = MC_TARGET_NONE;
5680 if (unlikely(is_swap_pmd(pmd))) {
5681 VM_BUG_ON(thp_migration_supported() &&
5682 !is_pmd_migration_entry(pmd));
5685 page = pmd_page(pmd);
5686 VM_BUG_ON_PAGE(!page || !PageHead(page), page);
5687 if (!(mc.flags & MOVE_ANON))
5689 if (page->mem_cgroup == mc.from) {
5690 ret = MC_TARGET_PAGE;
5693 target->page = page;
5699 static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5700 unsigned long addr, pmd_t pmd, union mc_target *target)
5702 return MC_TARGET_NONE;
5706 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5707 unsigned long addr, unsigned long end,
5708 struct mm_walk *walk)
5710 struct vm_area_struct *vma = walk->vma;
5714 ptl = pmd_trans_huge_lock(pmd, vma);
5717 * Note their can not be MC_TARGET_DEVICE for now as we do not
5718 * support transparent huge page with MEMORY_DEVICE_PRIVATE but
5719 * this might change.
5721 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
5722 mc.precharge += HPAGE_PMD_NR;
5727 if (pmd_trans_unstable(pmd))
5729 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5730 for (; addr != end; pte++, addr += PAGE_SIZE)
5731 if (get_mctgt_type(vma, addr, *pte, NULL))
5732 mc.precharge++; /* increment precharge temporarily */
5733 pte_unmap_unlock(pte - 1, ptl);
5739 static const struct mm_walk_ops precharge_walk_ops = {
5740 .pmd_entry = mem_cgroup_count_precharge_pte_range,
5743 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5745 unsigned long precharge;
5747 down_read(&mm->mmap_sem);
5748 walk_page_range(mm, 0, mm->highest_vm_end, &precharge_walk_ops, NULL);
5749 up_read(&mm->mmap_sem);
5751 precharge = mc.precharge;
5757 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5759 unsigned long precharge = mem_cgroup_count_precharge(mm);
5761 VM_BUG_ON(mc.moving_task);
5762 mc.moving_task = current;
5763 return mem_cgroup_do_precharge(precharge);
5766 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5767 static void __mem_cgroup_clear_mc(void)
5769 struct mem_cgroup *from = mc.from;
5770 struct mem_cgroup *to = mc.to;
5772 /* we must uncharge all the leftover precharges from mc.to */
5774 cancel_charge(mc.to, mc.precharge);
5778 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5779 * we must uncharge here.
5781 if (mc.moved_charge) {
5782 cancel_charge(mc.from, mc.moved_charge);
5783 mc.moved_charge = 0;
5785 /* we must fixup refcnts and charges */
5786 if (mc.moved_swap) {
5787 /* uncharge swap account from the old cgroup */
5788 if (!mem_cgroup_is_root(mc.from))
5789 page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
5791 mem_cgroup_id_put_many(mc.from, mc.moved_swap);
5794 * we charged both to->memory and to->memsw, so we
5795 * should uncharge to->memory.
5797 if (!mem_cgroup_is_root(mc.to))
5798 page_counter_uncharge(&mc.to->memory, mc.moved_swap);
5800 mem_cgroup_id_get_many(mc.to, mc.moved_swap);
5801 css_put_many(&mc.to->css, mc.moved_swap);
5805 memcg_oom_recover(from);
5806 memcg_oom_recover(to);
5807 wake_up_all(&mc.waitq);
5810 static void mem_cgroup_clear_mc(void)
5812 struct mm_struct *mm = mc.mm;
5815 * we must clear moving_task before waking up waiters at the end of
5818 mc.moving_task = NULL;
5819 __mem_cgroup_clear_mc();
5820 spin_lock(&mc.lock);
5824 spin_unlock(&mc.lock);
5829 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
5831 struct cgroup_subsys_state *css;
5832 struct mem_cgroup *memcg = NULL; /* unneeded init to make gcc happy */
5833 struct mem_cgroup *from;
5834 struct task_struct *leader, *p;
5835 struct mm_struct *mm;
5836 unsigned long move_flags;
5839 /* charge immigration isn't supported on the default hierarchy */
5840 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
5844 * Multi-process migrations only happen on the default hierarchy
5845 * where charge immigration is not used. Perform charge
5846 * immigration if @tset contains a leader and whine if there are
5850 cgroup_taskset_for_each_leader(leader, css, tset) {
5853 memcg = mem_cgroup_from_css(css);
5859 * We are now commited to this value whatever it is. Changes in this
5860 * tunable will only affect upcoming migrations, not the current one.
5861 * So we need to save it, and keep it going.
5863 move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
5867 from = mem_cgroup_from_task(p);
5869 VM_BUG_ON(from == memcg);
5871 mm = get_task_mm(p);
5874 /* We move charges only when we move a owner of the mm */
5875 if (mm->owner == p) {
5878 VM_BUG_ON(mc.precharge);
5879 VM_BUG_ON(mc.moved_charge);
5880 VM_BUG_ON(mc.moved_swap);
5882 spin_lock(&mc.lock);
5886 mc.flags = move_flags;
5887 spin_unlock(&mc.lock);
5888 /* We set mc.moving_task later */
5890 ret = mem_cgroup_precharge_mc(mm);
5892 mem_cgroup_clear_mc();
5899 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
5902 mem_cgroup_clear_mc();
5905 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
5906 unsigned long addr, unsigned long end,
5907 struct mm_walk *walk)
5910 struct vm_area_struct *vma = walk->vma;
5913 enum mc_target_type target_type;
5914 union mc_target target;
5917 ptl = pmd_trans_huge_lock(pmd, vma);
5919 if (mc.precharge < HPAGE_PMD_NR) {
5923 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
5924 if (target_type == MC_TARGET_PAGE) {
5926 if (!isolate_lru_page(page)) {
5927 if (!mem_cgroup_move_account(page, true,
5929 mc.precharge -= HPAGE_PMD_NR;
5930 mc.moved_charge += HPAGE_PMD_NR;
5932 putback_lru_page(page);
5935 } else if (target_type == MC_TARGET_DEVICE) {
5937 if (!mem_cgroup_move_account(page, true,
5939 mc.precharge -= HPAGE_PMD_NR;
5940 mc.moved_charge += HPAGE_PMD_NR;
5948 if (pmd_trans_unstable(pmd))
5951 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5952 for (; addr != end; addr += PAGE_SIZE) {
5953 pte_t ptent = *(pte++);
5954 bool device = false;
5960 switch (get_mctgt_type(vma, addr, ptent, &target)) {
5961 case MC_TARGET_DEVICE:
5964 case MC_TARGET_PAGE:
5967 * We can have a part of the split pmd here. Moving it
5968 * can be done but it would be too convoluted so simply
5969 * ignore such a partial THP and keep it in original
5970 * memcg. There should be somebody mapping the head.
5972 if (PageTransCompound(page))
5974 if (!device && isolate_lru_page(page))
5976 if (!mem_cgroup_move_account(page, false,
5979 /* we uncharge from mc.from later. */
5983 putback_lru_page(page);
5984 put: /* get_mctgt_type() gets the page */
5987 case MC_TARGET_SWAP:
5989 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
5991 /* we fixup refcnts and charges later. */
5999 pte_unmap_unlock(pte - 1, ptl);
6004 * We have consumed all precharges we got in can_attach().
6005 * We try charge one by one, but don't do any additional
6006 * charges to mc.to if we have failed in charge once in attach()
6009 ret = mem_cgroup_do_precharge(1);
6017 static const struct mm_walk_ops charge_walk_ops = {
6018 .pmd_entry = mem_cgroup_move_charge_pte_range,
6021 static void mem_cgroup_move_charge(void)
6023 lru_add_drain_all();
6025 * Signal lock_page_memcg() to take the memcg's move_lock
6026 * while we're moving its pages to another memcg. Then wait
6027 * for already started RCU-only updates to finish.
6029 atomic_inc(&mc.from->moving_account);
6032 if (unlikely(!down_read_trylock(&mc.mm->mmap_sem))) {
6034 * Someone who are holding the mmap_sem might be waiting in
6035 * waitq. So we cancel all extra charges, wake up all waiters,
6036 * and retry. Because we cancel precharges, we might not be able
6037 * to move enough charges, but moving charge is a best-effort
6038 * feature anyway, so it wouldn't be a big problem.
6040 __mem_cgroup_clear_mc();
6045 * When we have consumed all precharges and failed in doing
6046 * additional charge, the page walk just aborts.
6048 walk_page_range(mc.mm, 0, mc.mm->highest_vm_end, &charge_walk_ops,
6051 up_read(&mc.mm->mmap_sem);
6052 atomic_dec(&mc.from->moving_account);
6055 static void mem_cgroup_move_task(void)
6058 mem_cgroup_move_charge();
6059 mem_cgroup_clear_mc();
6062 #else /* !CONFIG_MMU */
6063 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
6067 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6070 static void mem_cgroup_move_task(void)
6076 * Cgroup retains root cgroups across [un]mount cycles making it necessary
6077 * to verify whether we're attached to the default hierarchy on each mount
6080 static void mem_cgroup_bind(struct cgroup_subsys_state *root_css)
6083 * use_hierarchy is forced on the default hierarchy. cgroup core
6084 * guarantees that @root doesn't have any children, so turning it
6085 * on for the root memcg is enough.
6087 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
6088 root_mem_cgroup->use_hierarchy = true;
6090 root_mem_cgroup->use_hierarchy = false;
6093 static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
6095 if (value == PAGE_COUNTER_MAX)
6096 seq_puts(m, "max\n");
6098 seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
6103 static u64 memory_current_read(struct cgroup_subsys_state *css,
6106 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6108 return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
6111 static int memory_min_show(struct seq_file *m, void *v)
6113 return seq_puts_memcg_tunable(m,
6114 READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
6117 static ssize_t memory_min_write(struct kernfs_open_file *of,
6118 char *buf, size_t nbytes, loff_t off)
6120 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6124 buf = strstrip(buf);
6125 err = page_counter_memparse(buf, "max", &min);
6129 page_counter_set_min(&memcg->memory, min);
6134 static int memory_low_show(struct seq_file *m, void *v)
6136 return seq_puts_memcg_tunable(m,
6137 READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
6140 static ssize_t memory_low_write(struct kernfs_open_file *of,
6141 char *buf, size_t nbytes, loff_t off)
6143 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6147 buf = strstrip(buf);
6148 err = page_counter_memparse(buf, "max", &low);
6152 page_counter_set_low(&memcg->memory, low);
6157 static int memory_high_show(struct seq_file *m, void *v)
6159 return seq_puts_memcg_tunable(m, READ_ONCE(mem_cgroup_from_seq(m)->high));
6162 static ssize_t memory_high_write(struct kernfs_open_file *of,
6163 char *buf, size_t nbytes, loff_t off)
6165 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6166 unsigned long nr_pages;
6170 buf = strstrip(buf);
6171 err = page_counter_memparse(buf, "max", &high);
6177 nr_pages = page_counter_read(&memcg->memory);
6178 if (nr_pages > high)
6179 try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
6182 memcg_wb_domain_size_changed(memcg);
6186 static int memory_max_show(struct seq_file *m, void *v)
6188 return seq_puts_memcg_tunable(m,
6189 READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
6192 static ssize_t memory_max_write(struct kernfs_open_file *of,
6193 char *buf, size_t nbytes, loff_t off)
6195 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6196 unsigned int nr_reclaims = MEM_CGROUP_RECLAIM_RETRIES;
6197 bool drained = false;
6201 buf = strstrip(buf);
6202 err = page_counter_memparse(buf, "max", &max);
6206 xchg(&memcg->memory.max, max);
6209 unsigned long nr_pages = page_counter_read(&memcg->memory);
6211 if (nr_pages <= max)
6214 if (signal_pending(current)) {
6220 drain_all_stock(memcg);
6226 if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
6232 memcg_memory_event(memcg, MEMCG_OOM);
6233 if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
6237 memcg_wb_domain_size_changed(memcg);
6241 static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
6243 seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
6244 seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
6245 seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
6246 seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
6247 seq_printf(m, "oom_kill %lu\n",
6248 atomic_long_read(&events[MEMCG_OOM_KILL]));
6251 static int memory_events_show(struct seq_file *m, void *v)
6253 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6255 __memory_events_show(m, memcg->memory_events);
6259 static int memory_events_local_show(struct seq_file *m, void *v)
6261 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6263 __memory_events_show(m, memcg->memory_events_local);
6267 static int memory_stat_show(struct seq_file *m, void *v)
6269 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6272 buf = memory_stat_format(memcg);
6280 static int memory_oom_group_show(struct seq_file *m, void *v)
6282 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6284 seq_printf(m, "%d\n", memcg->oom_group);
6289 static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
6290 char *buf, size_t nbytes, loff_t off)
6292 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6295 buf = strstrip(buf);
6299 ret = kstrtoint(buf, 0, &oom_group);
6303 if (oom_group != 0 && oom_group != 1)
6306 memcg->oom_group = oom_group;
6311 static struct cftype memory_files[] = {
6314 .flags = CFTYPE_NOT_ON_ROOT,
6315 .read_u64 = memory_current_read,
6319 .flags = CFTYPE_NOT_ON_ROOT,
6320 .seq_show = memory_min_show,
6321 .write = memory_min_write,
6325 .flags = CFTYPE_NOT_ON_ROOT,
6326 .seq_show = memory_low_show,
6327 .write = memory_low_write,
6331 .flags = CFTYPE_NOT_ON_ROOT,
6332 .seq_show = memory_high_show,
6333 .write = memory_high_write,
6337 .flags = CFTYPE_NOT_ON_ROOT,
6338 .seq_show = memory_max_show,
6339 .write = memory_max_write,
6343 .flags = CFTYPE_NOT_ON_ROOT,
6344 .file_offset = offsetof(struct mem_cgroup, events_file),
6345 .seq_show = memory_events_show,
6348 .name = "events.local",
6349 .flags = CFTYPE_NOT_ON_ROOT,
6350 .file_offset = offsetof(struct mem_cgroup, events_local_file),
6351 .seq_show = memory_events_local_show,
6355 .flags = CFTYPE_NOT_ON_ROOT,
6356 .seq_show = memory_stat_show,
6359 .name = "oom.group",
6360 .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
6361 .seq_show = memory_oom_group_show,
6362 .write = memory_oom_group_write,
6367 struct cgroup_subsys memory_cgrp_subsys = {
6368 .css_alloc = mem_cgroup_css_alloc,
6369 .css_online = mem_cgroup_css_online,
6370 .css_offline = mem_cgroup_css_offline,
6371 .css_released = mem_cgroup_css_released,
6372 .css_free = mem_cgroup_css_free,
6373 .css_reset = mem_cgroup_css_reset,
6374 .can_attach = mem_cgroup_can_attach,
6375 .cancel_attach = mem_cgroup_cancel_attach,
6376 .post_attach = mem_cgroup_move_task,
6377 .bind = mem_cgroup_bind,
6378 .dfl_cftypes = memory_files,
6379 .legacy_cftypes = mem_cgroup_legacy_files,
6384 * mem_cgroup_protected - check if memory consumption is in the normal range
6385 * @root: the top ancestor of the sub-tree being checked
6386 * @memcg: the memory cgroup to check
6388 * WARNING: This function is not stateless! It can only be used as part
6389 * of a top-down tree iteration, not for isolated queries.
6391 * Returns one of the following:
6392 * MEMCG_PROT_NONE: cgroup memory is not protected
6393 * MEMCG_PROT_LOW: cgroup memory is protected as long there is
6394 * an unprotected supply of reclaimable memory from other cgroups.
6395 * MEMCG_PROT_MIN: cgroup memory is protected
6397 * @root is exclusive; it is never protected when looked at directly
6399 * To provide a proper hierarchical behavior, effective memory.min/low values
6400 * are used. Below is the description of how effective memory.low is calculated.
6401 * Effective memory.min values is calculated in the same way.
6403 * Effective memory.low is always equal or less than the original memory.low.
6404 * If there is no memory.low overcommittment (which is always true for
6405 * top-level memory cgroups), these two values are equal.
6406 * Otherwise, it's a part of parent's effective memory.low,
6407 * calculated as a cgroup's memory.low usage divided by sum of sibling's
6408 * memory.low usages, where memory.low usage is the size of actually
6412 * elow = min( memory.low, parent->elow * ------------------ ),
6413 * siblings_low_usage
6415 * | memory.current, if memory.current < memory.low
6420 * Such definition of the effective memory.low provides the expected
6421 * hierarchical behavior: parent's memory.low value is limiting
6422 * children, unprotected memory is reclaimed first and cgroups,
6423 * which are not using their guarantee do not affect actual memory
6426 * For example, if there are memcgs A, A/B, A/C, A/D and A/E:
6428 * A A/memory.low = 2G, A/memory.current = 6G
6430 * BC DE B/memory.low = 3G B/memory.current = 2G
6431 * C/memory.low = 1G C/memory.current = 2G
6432 * D/memory.low = 0 D/memory.current = 2G
6433 * E/memory.low = 10G E/memory.current = 0
6435 * and the memory pressure is applied, the following memory distribution
6436 * is expected (approximately):
6438 * A/memory.current = 2G
6440 * B/memory.current = 1.3G
6441 * C/memory.current = 0.6G
6442 * D/memory.current = 0
6443 * E/memory.current = 0
6445 * These calculations require constant tracking of the actual low usages
6446 * (see propagate_protected_usage()), as well as recursive calculation of
6447 * effective memory.low values. But as we do call mem_cgroup_protected()
6448 * path for each memory cgroup top-down from the reclaim,
6449 * it's possible to optimize this part, and save calculated elow
6450 * for next usage. This part is intentionally racy, but it's ok,
6451 * as memory.low is a best-effort mechanism.
6453 void mem_cgroup_calculate_protection(struct mem_cgroup *root,
6454 struct mem_cgroup *memcg)
6456 struct mem_cgroup *parent;
6457 unsigned long emin, parent_emin;
6458 unsigned long elow, parent_elow;
6459 unsigned long usage;
6461 if (mem_cgroup_disabled())
6465 root = root_mem_cgroup;
6469 usage = page_counter_read(&memcg->memory);
6473 emin = memcg->memory.min;
6474 elow = memcg->memory.low;
6476 parent = parent_mem_cgroup(memcg);
6477 /* No parent means a non-hierarchical mode on v1 memcg */
6484 parent_emin = READ_ONCE(parent->memory.emin);
6485 emin = min(emin, parent_emin);
6486 if (emin && parent_emin) {
6487 unsigned long min_usage, siblings_min_usage;
6489 min_usage = min(usage, memcg->memory.min);
6490 siblings_min_usage = atomic_long_read(
6491 &parent->memory.children_min_usage);
6493 if (min_usage && siblings_min_usage)
6494 emin = min(emin, parent_emin * min_usage /
6495 siblings_min_usage);
6498 parent_elow = READ_ONCE(parent->memory.elow);
6499 elow = min(elow, parent_elow);
6500 if (elow && parent_elow) {
6501 unsigned long low_usage, siblings_low_usage;
6503 low_usage = min(usage, memcg->memory.low);
6504 siblings_low_usage = atomic_long_read(
6505 &parent->memory.children_low_usage);
6507 if (low_usage && siblings_low_usage)
6508 elow = min(elow, parent_elow * low_usage /
6509 siblings_low_usage);
6515 * mem_cgroup_try_charge - try charging a page
6516 * @page: page to charge
6517 * @mm: mm context of the victim
6518 * @gfp_mask: reclaim mode
6519 * @memcgp: charged memcg return
6520 * @compound: charge the page as compound or small page
6522 * Try to charge @page to the memcg that @mm belongs to, reclaiming
6523 * pages according to @gfp_mask if necessary.
6525 * Returns 0 on success, with *@memcgp pointing to the charged memcg.
6526 * Otherwise, an error code is returned.
6528 * After page->mapping has been set up, the caller must finalize the
6529 * charge with mem_cgroup_commit_charge(). Or abort the transaction
6530 * with mem_cgroup_cancel_charge() in case page instantiation fails.
6532 int mem_cgroup_try_charge(struct page *page, struct mm_struct *mm,
6533 gfp_t gfp_mask, struct mem_cgroup **memcgp,
6536 struct mem_cgroup *memcg = NULL;
6537 unsigned int nr_pages = compound ? hpage_nr_pages(page) : 1;
6540 if (mem_cgroup_disabled())
6543 if (PageSwapCache(page)) {
6545 * Every swap fault against a single page tries to charge the
6546 * page, bail as early as possible. shmem_unuse() encounters
6547 * already charged pages, too. The USED bit is protected by
6548 * the page lock, which serializes swap cache removal, which
6549 * in turn serializes uncharging.
6551 VM_BUG_ON_PAGE(!PageLocked(page), page);
6552 if (compound_head(page)->mem_cgroup)
6555 if (do_swap_account) {
6556 swp_entry_t ent = { .val = page_private(page), };
6557 unsigned short id = lookup_swap_cgroup_id(ent);
6560 memcg = mem_cgroup_from_id(id);
6561 if (memcg && !css_tryget_online(&memcg->css))
6568 memcg = get_mem_cgroup_from_mm(mm);
6570 ret = try_charge(memcg, gfp_mask, nr_pages);
6572 css_put(&memcg->css);
6578 int mem_cgroup_try_charge_delay(struct page *page, struct mm_struct *mm,
6579 gfp_t gfp_mask, struct mem_cgroup **memcgp,
6582 struct mem_cgroup *memcg;
6585 ret = mem_cgroup_try_charge(page, mm, gfp_mask, memcgp, compound);
6587 mem_cgroup_throttle_swaprate(memcg, page_to_nid(page), gfp_mask);
6592 * mem_cgroup_commit_charge - commit a page charge
6593 * @page: page to charge
6594 * @memcg: memcg to charge the page to
6595 * @lrucare: page might be on LRU already
6596 * @compound: charge the page as compound or small page
6598 * Finalize a charge transaction started by mem_cgroup_try_charge(),
6599 * after page->mapping has been set up. This must happen atomically
6600 * as part of the page instantiation, i.e. under the page table lock
6601 * for anonymous pages, under the page lock for page and swap cache.
6603 * In addition, the page must not be on the LRU during the commit, to
6604 * prevent racing with task migration. If it might be, use @lrucare.
6606 * Use mem_cgroup_cancel_charge() to cancel the transaction instead.
6608 void mem_cgroup_commit_charge(struct page *page, struct mem_cgroup *memcg,
6609 bool lrucare, bool compound)
6611 unsigned int nr_pages = compound ? hpage_nr_pages(page) : 1;
6613 VM_BUG_ON_PAGE(!page->mapping, page);
6614 VM_BUG_ON_PAGE(PageLRU(page) && !lrucare, page);
6616 if (mem_cgroup_disabled())
6619 * Swap faults will attempt to charge the same page multiple
6620 * times. But reuse_swap_page() might have removed the page
6621 * from swapcache already, so we can't check PageSwapCache().
6626 commit_charge(page, memcg, lrucare);
6628 local_irq_disable();
6629 mem_cgroup_charge_statistics(memcg, page, compound, nr_pages);
6630 memcg_check_events(memcg, page);
6633 if (do_memsw_account() && PageSwapCache(page)) {
6634 swp_entry_t entry = { .val = page_private(page) };
6636 * The swap entry might not get freed for a long time,
6637 * let's not wait for it. The page already received a
6638 * memory+swap charge, drop the swap entry duplicate.
6640 mem_cgroup_uncharge_swap(entry, nr_pages);
6645 * mem_cgroup_cancel_charge - cancel a page charge
6646 * @page: page to charge
6647 * @memcg: memcg to charge the page to
6648 * @compound: charge the page as compound or small page
6650 * Cancel a charge transaction started by mem_cgroup_try_charge().
6652 void mem_cgroup_cancel_charge(struct page *page, struct mem_cgroup *memcg,
6655 unsigned int nr_pages = compound ? hpage_nr_pages(page) : 1;
6657 if (mem_cgroup_disabled())
6660 * Swap faults will attempt to charge the same page multiple
6661 * times. But reuse_swap_page() might have removed the page
6662 * from swapcache already, so we can't check PageSwapCache().
6667 cancel_charge(memcg, nr_pages);
6670 struct uncharge_gather {
6671 struct mem_cgroup *memcg;
6672 unsigned long pgpgout;
6673 unsigned long nr_anon;
6674 unsigned long nr_file;
6675 unsigned long nr_kmem;
6676 unsigned long nr_huge;
6677 unsigned long nr_shmem;
6678 struct page *dummy_page;
6681 static inline void uncharge_gather_clear(struct uncharge_gather *ug)
6683 memset(ug, 0, sizeof(*ug));
6686 static void uncharge_batch(const struct uncharge_gather *ug)
6688 unsigned long nr_pages = ug->nr_anon + ug->nr_file + ug->nr_kmem;
6689 unsigned long flags;
6691 if (!mem_cgroup_is_root(ug->memcg)) {
6692 page_counter_uncharge(&ug->memcg->memory, nr_pages);
6693 if (do_memsw_account())
6694 page_counter_uncharge(&ug->memcg->memsw, nr_pages);
6695 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && ug->nr_kmem)
6696 page_counter_uncharge(&ug->memcg->kmem, ug->nr_kmem);
6697 memcg_oom_recover(ug->memcg);
6700 local_irq_save(flags);
6701 __mod_memcg_state(ug->memcg, MEMCG_RSS, -ug->nr_anon);
6702 __mod_memcg_state(ug->memcg, MEMCG_CACHE, -ug->nr_file);
6703 __mod_memcg_state(ug->memcg, MEMCG_RSS_HUGE, -ug->nr_huge);
6704 __mod_memcg_state(ug->memcg, NR_SHMEM, -ug->nr_shmem);
6705 __count_memcg_events(ug->memcg, PGPGOUT, ug->pgpgout);
6706 __this_cpu_add(ug->memcg->vmstats_percpu->nr_page_events, nr_pages);
6707 memcg_check_events(ug->memcg, ug->dummy_page);
6708 local_irq_restore(flags);
6710 if (!mem_cgroup_is_root(ug->memcg))
6711 css_put_many(&ug->memcg->css, nr_pages);
6714 static void uncharge_page(struct page *page, struct uncharge_gather *ug)
6716 VM_BUG_ON_PAGE(PageLRU(page), page);
6717 VM_BUG_ON_PAGE(page_count(page) && !is_zone_device_page(page) &&
6718 !PageHWPoison(page) , page);
6720 if (!page->mem_cgroup)
6724 * Nobody should be changing or seriously looking at
6725 * page->mem_cgroup at this point, we have fully
6726 * exclusive access to the page.
6729 if (ug->memcg != page->mem_cgroup) {
6732 uncharge_gather_clear(ug);
6734 ug->memcg = page->mem_cgroup;
6737 if (!PageKmemcg(page)) {
6738 unsigned int nr_pages = 1;
6740 if (PageTransHuge(page)) {
6741 nr_pages = compound_nr(page);
6742 ug->nr_huge += nr_pages;
6745 ug->nr_anon += nr_pages;
6747 ug->nr_file += nr_pages;
6748 if (PageSwapBacked(page))
6749 ug->nr_shmem += nr_pages;
6753 ug->nr_kmem += compound_nr(page);
6754 __ClearPageKmemcg(page);
6757 ug->dummy_page = page;
6758 page->mem_cgroup = NULL;
6761 static void uncharge_list(struct list_head *page_list)
6763 struct uncharge_gather ug;
6764 struct list_head *next;
6766 uncharge_gather_clear(&ug);
6769 * Note that the list can be a single page->lru; hence the
6770 * do-while loop instead of a simple list_for_each_entry().
6772 next = page_list->next;
6776 page = list_entry(next, struct page, lru);
6777 next = page->lru.next;
6779 uncharge_page(page, &ug);
6780 } while (next != page_list);
6783 uncharge_batch(&ug);
6787 * mem_cgroup_uncharge - uncharge a page
6788 * @page: page to uncharge
6790 * Uncharge a page previously charged with mem_cgroup_try_charge() and
6791 * mem_cgroup_commit_charge().
6793 void mem_cgroup_uncharge(struct page *page)
6795 struct uncharge_gather ug;
6797 if (mem_cgroup_disabled())
6800 /* Don't touch page->lru of any random page, pre-check: */
6801 if (!page->mem_cgroup)
6804 uncharge_gather_clear(&ug);
6805 uncharge_page(page, &ug);
6806 uncharge_batch(&ug);
6810 * mem_cgroup_uncharge_list - uncharge a list of page
6811 * @page_list: list of pages to uncharge
6813 * Uncharge a list of pages previously charged with
6814 * mem_cgroup_try_charge() and mem_cgroup_commit_charge().
6816 void mem_cgroup_uncharge_list(struct list_head *page_list)
6818 if (mem_cgroup_disabled())
6821 if (!list_empty(page_list))
6822 uncharge_list(page_list);
6826 * mem_cgroup_migrate - charge a page's replacement
6827 * @oldpage: currently circulating page
6828 * @newpage: replacement page
6830 * Charge @newpage as a replacement page for @oldpage. @oldpage will
6831 * be uncharged upon free.
6833 * Both pages must be locked, @newpage->mapping must be set up.
6835 void mem_cgroup_migrate(struct page *oldpage, struct page *newpage)
6837 struct mem_cgroup *memcg;
6838 unsigned int nr_pages;
6840 unsigned long flags;
6842 VM_BUG_ON_PAGE(!PageLocked(oldpage), oldpage);
6843 VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
6844 VM_BUG_ON_PAGE(PageAnon(oldpage) != PageAnon(newpage), newpage);
6845 VM_BUG_ON_PAGE(PageTransHuge(oldpage) != PageTransHuge(newpage),
6848 if (mem_cgroup_disabled())
6851 /* Page cache replacement: new page already charged? */
6852 if (newpage->mem_cgroup)
6855 /* Swapcache readahead pages can get replaced before being charged */
6856 memcg = oldpage->mem_cgroup;
6860 /* Force-charge the new page. The old one will be freed soon */
6861 compound = PageTransHuge(newpage);
6862 nr_pages = compound ? hpage_nr_pages(newpage) : 1;
6864 page_counter_charge(&memcg->memory, nr_pages);
6865 if (do_memsw_account())
6866 page_counter_charge(&memcg->memsw, nr_pages);
6867 css_get_many(&memcg->css, nr_pages);
6869 commit_charge(newpage, memcg, false);
6871 local_irq_save(flags);
6872 mem_cgroup_charge_statistics(memcg, newpage, compound, nr_pages);
6873 memcg_check_events(memcg, newpage);
6874 local_irq_restore(flags);
6877 DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
6878 EXPORT_SYMBOL(memcg_sockets_enabled_key);
6880 void mem_cgroup_sk_alloc(struct sock *sk)
6882 struct mem_cgroup *memcg;
6884 if (!mem_cgroup_sockets_enabled)
6887 /* Do not associate the sock with unrelated interrupted task's memcg. */
6892 memcg = mem_cgroup_from_task(current);
6893 if (memcg == root_mem_cgroup)
6895 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg->tcpmem_active)
6897 if (css_tryget_online(&memcg->css))
6898 sk->sk_memcg = memcg;
6903 void mem_cgroup_sk_free(struct sock *sk)
6906 css_put(&sk->sk_memcg->css);
6910 * mem_cgroup_charge_skmem - charge socket memory
6911 * @memcg: memcg to charge
6912 * @nr_pages: number of pages to charge
6914 * Charges @nr_pages to @memcg. Returns %true if the charge fit within
6915 * @memcg's configured limit, %false if the charge had to be forced.
6917 bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
6919 gfp_t gfp_mask = GFP_KERNEL;
6921 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
6922 struct page_counter *fail;
6924 if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) {
6925 memcg->tcpmem_pressure = 0;
6928 page_counter_charge(&memcg->tcpmem, nr_pages);
6929 memcg->tcpmem_pressure = 1;
6933 /* Don't block in the packet receive path */
6935 gfp_mask = GFP_NOWAIT;
6937 mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
6939 if (try_charge(memcg, gfp_mask, nr_pages) == 0)
6942 try_charge(memcg, gfp_mask|__GFP_NOFAIL, nr_pages);
6947 * mem_cgroup_uncharge_skmem - uncharge socket memory
6948 * @memcg: memcg to uncharge
6949 * @nr_pages: number of pages to uncharge
6951 void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
6953 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
6954 page_counter_uncharge(&memcg->tcpmem, nr_pages);
6958 mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
6960 refill_stock(memcg, nr_pages);
6963 static int __init cgroup_memory(char *s)
6967 while ((token = strsep(&s, ",")) != NULL) {
6970 if (!strcmp(token, "nosocket"))
6971 cgroup_memory_nosocket = true;
6972 if (!strcmp(token, "nokmem"))
6973 cgroup_memory_nokmem = true;
6977 __setup("cgroup.memory=", cgroup_memory);
6980 * subsys_initcall() for memory controller.
6982 * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
6983 * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
6984 * basically everything that doesn't depend on a specific mem_cgroup structure
6985 * should be initialized from here.
6987 static int __init mem_cgroup_init(void)
6991 #ifdef CONFIG_MEMCG_KMEM
6993 * Kmem cache creation is mostly done with the slab_mutex held,
6994 * so use a workqueue with limited concurrency to avoid stalling
6995 * all worker threads in case lots of cgroups are created and
6996 * destroyed simultaneously.
6998 memcg_kmem_cache_wq = alloc_workqueue("memcg_kmem_cache", 0, 1);
6999 BUG_ON(!memcg_kmem_cache_wq);
7002 cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
7003 memcg_hotplug_cpu_dead);
7005 for_each_possible_cpu(cpu)
7006 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
7009 for_each_node(node) {
7010 struct mem_cgroup_tree_per_node *rtpn;
7012 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL,
7013 node_online(node) ? node : NUMA_NO_NODE);
7015 rtpn->rb_root = RB_ROOT;
7016 rtpn->rb_rightmost = NULL;
7017 spin_lock_init(&rtpn->lock);
7018 soft_limit_tree.rb_tree_per_node[node] = rtpn;
7023 subsys_initcall(mem_cgroup_init);
7025 #ifdef CONFIG_MEMCG_SWAP
7026 static struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
7028 while (!refcount_inc_not_zero(&memcg->id.ref)) {
7030 * The root cgroup cannot be destroyed, so it's refcount must
7033 if (WARN_ON_ONCE(memcg == root_mem_cgroup)) {
7037 memcg = parent_mem_cgroup(memcg);
7039 memcg = root_mem_cgroup;
7045 * mem_cgroup_swapout - transfer a memsw charge to swap
7046 * @page: page whose memsw charge to transfer
7047 * @entry: swap entry to move the charge to
7049 * Transfer the memsw charge of @page to @entry.
7051 void mem_cgroup_swapout(struct page *page, swp_entry_t entry)
7053 struct mem_cgroup *memcg, *swap_memcg;
7054 unsigned int nr_entries;
7055 unsigned short oldid;
7057 VM_BUG_ON_PAGE(PageLRU(page), page);
7058 VM_BUG_ON_PAGE(page_count(page), page);
7060 if (!do_memsw_account())
7063 memcg = page->mem_cgroup;
7065 VM_WARN_ON_ONCE_PAGE(!memcg, page);
7070 * In case the memcg owning these pages has been offlined and doesn't
7071 * have an ID allocated to it anymore, charge the closest online
7072 * ancestor for the swap instead and transfer the memory+swap charge.
7074 swap_memcg = mem_cgroup_id_get_online(memcg);
7075 nr_entries = hpage_nr_pages(page);
7076 /* Get references for the tail pages, too */
7078 mem_cgroup_id_get_many(swap_memcg, nr_entries - 1);
7079 oldid = swap_cgroup_record(entry, mem_cgroup_id(swap_memcg),
7081 VM_BUG_ON_PAGE(oldid, page);
7082 mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries);
7084 page->mem_cgroup = NULL;
7086 if (!mem_cgroup_is_root(memcg))
7087 page_counter_uncharge(&memcg->memory, nr_entries);
7089 if (memcg != swap_memcg) {
7090 if (!mem_cgroup_is_root(swap_memcg))
7091 page_counter_charge(&swap_memcg->memsw, nr_entries);
7092 page_counter_uncharge(&memcg->memsw, nr_entries);
7096 * Interrupts should be disabled here because the caller holds the
7097 * i_pages lock which is taken with interrupts-off. It is
7098 * important here to have the interrupts disabled because it is the
7099 * only synchronisation we have for updating the per-CPU variables.
7101 VM_BUG_ON(!irqs_disabled());
7102 mem_cgroup_charge_statistics(memcg, page, PageTransHuge(page),
7104 memcg_check_events(memcg, page);
7106 if (!mem_cgroup_is_root(memcg))
7107 css_put_many(&memcg->css, nr_entries);
7111 * mem_cgroup_try_charge_swap - try charging swap space for a page
7112 * @page: page being added to swap
7113 * @entry: swap entry to charge
7115 * Try to charge @page's memcg for the swap space at @entry.
7117 * Returns 0 on success, -ENOMEM on failure.
7119 int mem_cgroup_try_charge_swap(struct page *page, swp_entry_t entry)
7121 unsigned int nr_pages = hpage_nr_pages(page);
7122 struct page_counter *counter;
7123 struct mem_cgroup *memcg;
7124 unsigned short oldid;
7126 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) || !do_swap_account)
7129 memcg = page->mem_cgroup;
7131 VM_WARN_ON_ONCE_PAGE(!memcg, page);
7136 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7140 memcg = mem_cgroup_id_get_online(memcg);
7142 if (!mem_cgroup_is_root(memcg) &&
7143 !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
7144 memcg_memory_event(memcg, MEMCG_SWAP_MAX);
7145 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7146 mem_cgroup_id_put(memcg);
7150 /* Get references for the tail pages, too */
7152 mem_cgroup_id_get_many(memcg, nr_pages - 1);
7153 oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg), nr_pages);
7154 VM_BUG_ON_PAGE(oldid, page);
7155 mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
7161 * mem_cgroup_uncharge_swap - uncharge swap space
7162 * @entry: swap entry to uncharge
7163 * @nr_pages: the amount of swap space to uncharge
7165 void mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
7167 struct mem_cgroup *memcg;
7170 if (!do_swap_account)
7173 id = swap_cgroup_record(entry, 0, nr_pages);
7175 memcg = mem_cgroup_from_id(id);
7177 if (!mem_cgroup_is_root(memcg)) {
7178 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
7179 page_counter_uncharge(&memcg->swap, nr_pages);
7181 page_counter_uncharge(&memcg->memsw, nr_pages);
7183 mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
7184 mem_cgroup_id_put_many(memcg, nr_pages);
7189 long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
7191 long nr_swap_pages = get_nr_swap_pages();
7193 if (!do_swap_account || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
7194 return nr_swap_pages;
7195 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg))
7196 nr_swap_pages = min_t(long, nr_swap_pages,
7197 READ_ONCE(memcg->swap.max) -
7198 page_counter_read(&memcg->swap));
7199 return nr_swap_pages;
7202 bool mem_cgroup_swap_full(struct page *page)
7204 struct mem_cgroup *memcg;
7206 VM_BUG_ON_PAGE(!PageLocked(page), page);
7210 if (!do_swap_account || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
7213 memcg = page->mem_cgroup;
7217 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg))
7218 if (page_counter_read(&memcg->swap) * 2 >= memcg->swap.max)
7224 /* for remember boot option*/
7225 #ifdef CONFIG_MEMCG_SWAP_ENABLED
7226 static int really_do_swap_account __initdata = 1;
7228 static int really_do_swap_account __initdata;
7231 static int __init enable_swap_account(char *s)
7233 if (!strcmp(s, "1"))
7234 really_do_swap_account = 1;
7235 else if (!strcmp(s, "0"))
7236 really_do_swap_account = 0;
7239 __setup("swapaccount=", enable_swap_account);
7241 static u64 swap_current_read(struct cgroup_subsys_state *css,
7244 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7246 return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
7249 static int swap_max_show(struct seq_file *m, void *v)
7251 return seq_puts_memcg_tunable(m,
7252 READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
7255 static ssize_t swap_max_write(struct kernfs_open_file *of,
7256 char *buf, size_t nbytes, loff_t off)
7258 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7262 buf = strstrip(buf);
7263 err = page_counter_memparse(buf, "max", &max);
7267 xchg(&memcg->swap.max, max);
7272 static int swap_events_show(struct seq_file *m, void *v)
7274 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
7276 seq_printf(m, "max %lu\n",
7277 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
7278 seq_printf(m, "fail %lu\n",
7279 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
7284 static struct cftype swap_files[] = {
7286 .name = "swap.current",
7287 .flags = CFTYPE_NOT_ON_ROOT,
7288 .read_u64 = swap_current_read,
7292 .flags = CFTYPE_NOT_ON_ROOT,
7293 .seq_show = swap_max_show,
7294 .write = swap_max_write,
7297 .name = "swap.events",
7298 .flags = CFTYPE_NOT_ON_ROOT,
7299 .file_offset = offsetof(struct mem_cgroup, swap_events_file),
7300 .seq_show = swap_events_show,
7305 static struct cftype memsw_cgroup_files[] = {
7307 .name = "memsw.usage_in_bytes",
7308 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
7309 .read_u64 = mem_cgroup_read_u64,
7312 .name = "memsw.max_usage_in_bytes",
7313 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
7314 .write = mem_cgroup_reset,
7315 .read_u64 = mem_cgroup_read_u64,
7318 .name = "memsw.limit_in_bytes",
7319 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
7320 .write = mem_cgroup_write,
7321 .read_u64 = mem_cgroup_read_u64,
7324 .name = "memsw.failcnt",
7325 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
7326 .write = mem_cgroup_reset,
7327 .read_u64 = mem_cgroup_read_u64,
7330 .name = "force_reclaim",
7331 .write_u64 = mem_cgroup_force_reclaim,
7333 { }, /* terminate */
7336 static int __init mem_cgroup_swap_init(void)
7338 if (!mem_cgroup_disabled() && really_do_swap_account) {
7339 do_swap_account = 1;
7340 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys,
7342 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys,
7343 memsw_cgroup_files));
7347 subsys_initcall(mem_cgroup_swap_init);
7349 #endif /* CONFIG_MEMCG_SWAP */