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>
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/seq_buf.h>
66 #include <linux/uaccess.h>
68 #include <trace/events/vmscan.h>
70 struct cgroup_subsys memory_cgrp_subsys __read_mostly
;
71 EXPORT_SYMBOL(memory_cgrp_subsys
);
73 struct mem_cgroup
*root_mem_cgroup __read_mostly
;
75 #define MEM_CGROUP_RECLAIM_RETRIES 5
77 /* Socket memory accounting disabled? */
78 static bool cgroup_memory_nosocket
;
80 /* Kernel memory accounting disabled? */
81 static bool cgroup_memory_nokmem
;
83 /* Whether the swap controller is active */
84 #ifdef CONFIG_MEMCG_SWAP
85 int do_swap_account __read_mostly
;
87 #define do_swap_account 0
90 /* Whether legacy memory+swap accounting is active */
91 static bool do_memsw_account(void)
93 return !cgroup_subsys_on_dfl(memory_cgrp_subsys
) && do_swap_account
;
96 static const char *const mem_cgroup_lru_names
[] = {
104 #define THRESHOLDS_EVENTS_TARGET 128
105 #define SOFTLIMIT_EVENTS_TARGET 1024
106 #define NUMAINFO_EVENTS_TARGET 1024
109 * Cgroups above their limits are maintained in a RB-Tree, independent of
110 * their hierarchy representation
113 struct mem_cgroup_tree_per_node
{
114 struct rb_root rb_root
;
115 struct rb_node
*rb_rightmost
;
119 struct mem_cgroup_tree
{
120 struct mem_cgroup_tree_per_node
*rb_tree_per_node
[MAX_NUMNODES
];
123 static struct mem_cgroup_tree soft_limit_tree __read_mostly
;
126 struct mem_cgroup_eventfd_list
{
127 struct list_head list
;
128 struct eventfd_ctx
*eventfd
;
132 * cgroup_event represents events which userspace want to receive.
134 struct mem_cgroup_event
{
136 * memcg which the event belongs to.
138 struct mem_cgroup
*memcg
;
140 * eventfd to signal userspace about the event.
142 struct eventfd_ctx
*eventfd
;
144 * Each of these stored in a list by the cgroup.
146 struct list_head list
;
148 * register_event() callback will be used to add new userspace
149 * waiter for changes related to this event. Use eventfd_signal()
150 * on eventfd to send notification to userspace.
152 int (*register_event
)(struct mem_cgroup
*memcg
,
153 struct eventfd_ctx
*eventfd
, const char *args
);
155 * unregister_event() callback will be called when userspace closes
156 * the eventfd or on cgroup removing. This callback must be set,
157 * if you want provide notification functionality.
159 void (*unregister_event
)(struct mem_cgroup
*memcg
,
160 struct eventfd_ctx
*eventfd
);
162 * All fields below needed to unregister event when
163 * userspace closes eventfd.
166 wait_queue_head_t
*wqh
;
167 wait_queue_entry_t wait
;
168 struct work_struct remove
;
171 static void mem_cgroup_threshold(struct mem_cgroup
*memcg
);
172 static void mem_cgroup_oom_notify(struct mem_cgroup
*memcg
);
174 /* Stuffs for move charges at task migration. */
176 * Types of charges to be moved.
178 #define MOVE_ANON 0x1U
179 #define MOVE_FILE 0x2U
180 #define MOVE_MASK (MOVE_ANON | MOVE_FILE)
182 /* "mc" and its members are protected by cgroup_mutex */
183 static struct move_charge_struct
{
184 spinlock_t lock
; /* for from, to */
185 struct mm_struct
*mm
;
186 struct mem_cgroup
*from
;
187 struct mem_cgroup
*to
;
189 unsigned long precharge
;
190 unsigned long moved_charge
;
191 unsigned long moved_swap
;
192 struct task_struct
*moving_task
; /* a task moving charges */
193 wait_queue_head_t waitq
; /* a waitq for other context */
195 .lock
= __SPIN_LOCK_UNLOCKED(mc
.lock
),
196 .waitq
= __WAIT_QUEUE_HEAD_INITIALIZER(mc
.waitq
),
200 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
201 * limit reclaim to prevent infinite loops, if they ever occur.
203 #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
204 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
207 MEM_CGROUP_CHARGE_TYPE_CACHE
= 0,
208 MEM_CGROUP_CHARGE_TYPE_ANON
,
209 MEM_CGROUP_CHARGE_TYPE_SWAPOUT
, /* for accounting swapcache */
210 MEM_CGROUP_CHARGE_TYPE_DROP
, /* a page was unused swap cache */
214 /* for encoding cft->private value on file */
223 #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
224 #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
225 #define MEMFILE_ATTR(val) ((val) & 0xffff)
226 /* Used for OOM nofiier */
227 #define OOM_CONTROL (0)
230 * Iteration constructs for visiting all cgroups (under a tree). If
231 * loops are exited prematurely (break), mem_cgroup_iter_break() must
232 * be used for reference counting.
234 #define for_each_mem_cgroup_tree(iter, root) \
235 for (iter = mem_cgroup_iter(root, NULL, NULL); \
237 iter = mem_cgroup_iter(root, iter, NULL))
239 #define for_each_mem_cgroup(iter) \
240 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
242 iter = mem_cgroup_iter(NULL, iter, NULL))
244 static inline bool should_force_charge(void)
246 return tsk_is_oom_victim(current
) || fatal_signal_pending(current
) ||
247 (current
->flags
& PF_EXITING
);
250 /* Some nice accessors for the vmpressure. */
251 struct vmpressure
*memcg_to_vmpressure(struct mem_cgroup
*memcg
)
254 memcg
= root_mem_cgroup
;
255 return &memcg
->vmpressure
;
258 struct cgroup_subsys_state
*vmpressure_to_css(struct vmpressure
*vmpr
)
260 return &container_of(vmpr
, struct mem_cgroup
, vmpressure
)->css
;
263 #ifdef CONFIG_MEMCG_KMEM
265 * This will be the memcg's index in each cache's ->memcg_params.memcg_caches.
266 * The main reason for not using cgroup id for this:
267 * this works better in sparse environments, where we have a lot of memcgs,
268 * but only a few kmem-limited. Or also, if we have, for instance, 200
269 * memcgs, and none but the 200th is kmem-limited, we'd have to have a
270 * 200 entry array for that.
272 * The current size of the caches array is stored in memcg_nr_cache_ids. It
273 * will double each time we have to increase it.
275 static DEFINE_IDA(memcg_cache_ida
);
276 int memcg_nr_cache_ids
;
278 /* Protects memcg_nr_cache_ids */
279 static DECLARE_RWSEM(memcg_cache_ids_sem
);
281 void memcg_get_cache_ids(void)
283 down_read(&memcg_cache_ids_sem
);
286 void memcg_put_cache_ids(void)
288 up_read(&memcg_cache_ids_sem
);
292 * MIN_SIZE is different than 1, because we would like to avoid going through
293 * the alloc/free process all the time. In a small machine, 4 kmem-limited
294 * cgroups is a reasonable guess. In the future, it could be a parameter or
295 * tunable, but that is strictly not necessary.
297 * MAX_SIZE should be as large as the number of cgrp_ids. Ideally, we could get
298 * this constant directly from cgroup, but it is understandable that this is
299 * better kept as an internal representation in cgroup.c. In any case, the
300 * cgrp_id space is not getting any smaller, and we don't have to necessarily
301 * increase ours as well if it increases.
303 #define MEMCG_CACHES_MIN_SIZE 4
304 #define MEMCG_CACHES_MAX_SIZE MEM_CGROUP_ID_MAX
307 * A lot of the calls to the cache allocation functions are expected to be
308 * inlined by the compiler. Since the calls to memcg_kmem_get_cache are
309 * conditional to this static branch, we'll have to allow modules that does
310 * kmem_cache_alloc and the such to see this symbol as well
312 DEFINE_STATIC_KEY_FALSE(memcg_kmem_enabled_key
);
313 EXPORT_SYMBOL(memcg_kmem_enabled_key
);
315 struct workqueue_struct
*memcg_kmem_cache_wq
;
317 static int memcg_shrinker_map_size
;
318 static DEFINE_MUTEX(memcg_shrinker_map_mutex
);
320 static void memcg_free_shrinker_map_rcu(struct rcu_head
*head
)
322 kvfree(container_of(head
, struct memcg_shrinker_map
, rcu
));
325 static int memcg_expand_one_shrinker_map(struct mem_cgroup
*memcg
,
326 int size
, int old_size
)
328 struct memcg_shrinker_map
*new, *old
;
331 lockdep_assert_held(&memcg_shrinker_map_mutex
);
334 old
= rcu_dereference_protected(
335 mem_cgroup_nodeinfo(memcg
, nid
)->shrinker_map
, true);
336 /* Not yet online memcg */
340 new = kvmalloc(sizeof(*new) + size
, GFP_KERNEL
);
344 /* Set all old bits, clear all new bits */
345 memset(new->map
, (int)0xff, old_size
);
346 memset((void *)new->map
+ old_size
, 0, size
- old_size
);
348 rcu_assign_pointer(memcg
->nodeinfo
[nid
]->shrinker_map
, new);
349 call_rcu(&old
->rcu
, memcg_free_shrinker_map_rcu
);
355 static void memcg_free_shrinker_maps(struct mem_cgroup
*memcg
)
357 struct mem_cgroup_per_node
*pn
;
358 struct memcg_shrinker_map
*map
;
361 if (mem_cgroup_is_root(memcg
))
365 pn
= mem_cgroup_nodeinfo(memcg
, nid
);
366 map
= rcu_dereference_protected(pn
->shrinker_map
, true);
369 rcu_assign_pointer(pn
->shrinker_map
, NULL
);
373 static int memcg_alloc_shrinker_maps(struct mem_cgroup
*memcg
)
375 struct memcg_shrinker_map
*map
;
376 int nid
, size
, ret
= 0;
378 if (mem_cgroup_is_root(memcg
))
381 mutex_lock(&memcg_shrinker_map_mutex
);
382 size
= memcg_shrinker_map_size
;
384 map
= kvzalloc(sizeof(*map
) + size
, GFP_KERNEL
);
386 memcg_free_shrinker_maps(memcg
);
390 rcu_assign_pointer(memcg
->nodeinfo
[nid
]->shrinker_map
, map
);
392 mutex_unlock(&memcg_shrinker_map_mutex
);
397 int memcg_expand_shrinker_maps(int new_id
)
399 int size
, old_size
, ret
= 0;
400 struct mem_cgroup
*memcg
;
402 size
= DIV_ROUND_UP(new_id
+ 1, BITS_PER_LONG
) * sizeof(unsigned long);
403 old_size
= memcg_shrinker_map_size
;
404 if (size
<= old_size
)
407 mutex_lock(&memcg_shrinker_map_mutex
);
408 if (!root_mem_cgroup
)
411 for_each_mem_cgroup(memcg
) {
412 if (mem_cgroup_is_root(memcg
))
414 ret
= memcg_expand_one_shrinker_map(memcg
, size
, old_size
);
420 memcg_shrinker_map_size
= size
;
421 mutex_unlock(&memcg_shrinker_map_mutex
);
425 void memcg_set_shrinker_bit(struct mem_cgroup
*memcg
, int nid
, int shrinker_id
)
427 if (shrinker_id
>= 0 && memcg
&& !mem_cgroup_is_root(memcg
)) {
428 struct memcg_shrinker_map
*map
;
431 map
= rcu_dereference(memcg
->nodeinfo
[nid
]->shrinker_map
);
432 /* Pairs with smp mb in shrink_slab() */
433 smp_mb__before_atomic();
434 set_bit(shrinker_id
, map
->map
);
439 #else /* CONFIG_MEMCG_KMEM */
440 static int memcg_alloc_shrinker_maps(struct mem_cgroup
*memcg
)
444 static void memcg_free_shrinker_maps(struct mem_cgroup
*memcg
) { }
445 #endif /* CONFIG_MEMCG_KMEM */
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 (PageHead(page
) && PageSlab(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
);
755 x
= val
+ __this_cpu_read(pn
->lruvec_stat_cpu
->count
[idx
]);
756 if (unlikely(abs(x
) > MEMCG_CHARGE_BATCH
)) {
757 struct mem_cgroup_per_node
*pi
;
760 * Batch local counters to keep them in sync with
761 * the hierarchical ones.
763 __this_cpu_add(pn
->lruvec_stat_local
->count
[idx
], x
);
764 for (pi
= pn
; pi
; pi
= parent_nodeinfo(pi
, pgdat
->node_id
))
765 atomic_long_add(x
, &pi
->lruvec_stat
[idx
]);
768 __this_cpu_write(pn
->lruvec_stat_cpu
->count
[idx
], x
);
772 * __count_memcg_events - account VM events in a cgroup
773 * @memcg: the memory cgroup
774 * @idx: the event item
775 * @count: the number of events that occured
777 void __count_memcg_events(struct mem_cgroup
*memcg
, enum vm_event_item idx
,
782 if (mem_cgroup_disabled())
785 x
= count
+ __this_cpu_read(memcg
->vmstats_percpu
->events
[idx
]);
786 if (unlikely(x
> MEMCG_CHARGE_BATCH
)) {
787 struct mem_cgroup
*mi
;
790 * Batch local counters to keep them in sync with
791 * the hierarchical ones.
793 __this_cpu_add(memcg
->vmstats_local
->events
[idx
], x
);
794 for (mi
= memcg
; mi
; mi
= parent_mem_cgroup(mi
))
795 atomic_long_add(x
, &mi
->vmevents
[idx
]);
798 __this_cpu_write(memcg
->vmstats_percpu
->events
[idx
], x
);
801 static unsigned long memcg_events(struct mem_cgroup
*memcg
, int event
)
803 return atomic_long_read(&memcg
->vmevents
[event
]);
806 static unsigned long memcg_events_local(struct mem_cgroup
*memcg
, int event
)
811 for_each_possible_cpu(cpu
)
812 x
+= per_cpu(memcg
->vmstats_local
->events
[event
], cpu
);
816 static void mem_cgroup_charge_statistics(struct mem_cgroup
*memcg
,
818 bool compound
, int nr_pages
)
821 * Here, RSS means 'mapped anon' and anon's SwapCache. Shmem/tmpfs is
822 * counted as CACHE even if it's on ANON LRU.
825 __mod_memcg_state(memcg
, MEMCG_RSS
, nr_pages
);
827 __mod_memcg_state(memcg
, MEMCG_CACHE
, nr_pages
);
828 if (PageSwapBacked(page
))
829 __mod_memcg_state(memcg
, NR_SHMEM
, nr_pages
);
833 VM_BUG_ON_PAGE(!PageTransHuge(page
), page
);
834 __mod_memcg_state(memcg
, MEMCG_RSS_HUGE
, nr_pages
);
837 /* pagein of a big page is an event. So, ignore page size */
839 __count_memcg_events(memcg
, PGPGIN
, 1);
841 __count_memcg_events(memcg
, PGPGOUT
, 1);
842 nr_pages
= -nr_pages
; /* for event */
845 __this_cpu_add(memcg
->vmstats_percpu
->nr_page_events
, nr_pages
);
848 static bool mem_cgroup_event_ratelimit(struct mem_cgroup
*memcg
,
849 enum mem_cgroup_events_target target
)
851 unsigned long val
, next
;
853 val
= __this_cpu_read(memcg
->vmstats_percpu
->nr_page_events
);
854 next
= __this_cpu_read(memcg
->vmstats_percpu
->targets
[target
]);
855 /* from time_after() in jiffies.h */
856 if ((long)(next
- val
) < 0) {
858 case MEM_CGROUP_TARGET_THRESH
:
859 next
= val
+ THRESHOLDS_EVENTS_TARGET
;
861 case MEM_CGROUP_TARGET_SOFTLIMIT
:
862 next
= val
+ SOFTLIMIT_EVENTS_TARGET
;
864 case MEM_CGROUP_TARGET_NUMAINFO
:
865 next
= val
+ NUMAINFO_EVENTS_TARGET
;
870 __this_cpu_write(memcg
->vmstats_percpu
->targets
[target
], next
);
877 * Check events in order.
880 static void memcg_check_events(struct mem_cgroup
*memcg
, struct page
*page
)
882 /* threshold event is triggered in finer grain than soft limit */
883 if (unlikely(mem_cgroup_event_ratelimit(memcg
,
884 MEM_CGROUP_TARGET_THRESH
))) {
886 bool do_numainfo __maybe_unused
;
888 do_softlimit
= mem_cgroup_event_ratelimit(memcg
,
889 MEM_CGROUP_TARGET_SOFTLIMIT
);
891 do_numainfo
= mem_cgroup_event_ratelimit(memcg
,
892 MEM_CGROUP_TARGET_NUMAINFO
);
894 mem_cgroup_threshold(memcg
);
895 if (unlikely(do_softlimit
))
896 mem_cgroup_update_tree(memcg
, page
);
898 if (unlikely(do_numainfo
))
899 atomic_inc(&memcg
->numainfo_events
);
904 struct mem_cgroup
*mem_cgroup_from_task(struct task_struct
*p
)
907 * mm_update_next_owner() may clear mm->owner to NULL
908 * if it races with swapoff, page migration, etc.
909 * So this can be called with p == NULL.
914 return mem_cgroup_from_css(task_css(p
, memory_cgrp_id
));
916 EXPORT_SYMBOL(mem_cgroup_from_task
);
919 * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
920 * @mm: mm from which memcg should be extracted. It can be NULL.
922 * Obtain a reference on mm->memcg and returns it if successful. Otherwise
923 * root_mem_cgroup is returned. However if mem_cgroup is disabled, NULL is
926 struct mem_cgroup
*get_mem_cgroup_from_mm(struct mm_struct
*mm
)
928 struct mem_cgroup
*memcg
;
930 if (mem_cgroup_disabled())
936 * Page cache insertions can happen withou an
937 * actual mm context, e.g. during disk probing
938 * on boot, loopback IO, acct() writes etc.
941 memcg
= root_mem_cgroup
;
943 memcg
= mem_cgroup_from_task(rcu_dereference(mm
->owner
));
944 if (unlikely(!memcg
))
945 memcg
= root_mem_cgroup
;
947 } while (!css_tryget_online(&memcg
->css
));
951 EXPORT_SYMBOL(get_mem_cgroup_from_mm
);
954 * get_mem_cgroup_from_page: Obtain a reference on given page's memcg.
955 * @page: page from which memcg should be extracted.
957 * Obtain a reference on page->memcg and returns it if successful. Otherwise
958 * root_mem_cgroup is returned.
960 struct mem_cgroup
*get_mem_cgroup_from_page(struct page
*page
)
962 struct mem_cgroup
*memcg
= page
->mem_cgroup
;
964 if (mem_cgroup_disabled())
968 if (!memcg
|| !css_tryget_online(&memcg
->css
))
969 memcg
= root_mem_cgroup
;
973 EXPORT_SYMBOL(get_mem_cgroup_from_page
);
976 * If current->active_memcg is non-NULL, do not fallback to current->mm->memcg.
978 static __always_inline
struct mem_cgroup
*get_mem_cgroup_from_current(void)
980 if (unlikely(current
->active_memcg
)) {
981 struct mem_cgroup
*memcg
= root_mem_cgroup
;
984 if (css_tryget_online(¤t
->active_memcg
->css
))
985 memcg
= current
->active_memcg
;
989 return get_mem_cgroup_from_mm(current
->mm
);
993 * mem_cgroup_iter - iterate over memory cgroup hierarchy
994 * @root: hierarchy root
995 * @prev: previously returned memcg, NULL on first invocation
996 * @reclaim: cookie for shared reclaim walks, NULL for full walks
998 * Returns references to children of the hierarchy below @root, or
999 * @root itself, or %NULL after a full round-trip.
1001 * Caller must pass the return value in @prev on subsequent
1002 * invocations for reference counting, or use mem_cgroup_iter_break()
1003 * to cancel a hierarchy walk before the round-trip is complete.
1005 * Reclaimers can specify a node and a priority level in @reclaim to
1006 * divide up the memcgs in the hierarchy among all concurrent
1007 * reclaimers operating on the same node and priority.
1009 struct mem_cgroup
*mem_cgroup_iter(struct mem_cgroup
*root
,
1010 struct mem_cgroup
*prev
,
1011 struct mem_cgroup_reclaim_cookie
*reclaim
)
1013 struct mem_cgroup_reclaim_iter
*uninitialized_var(iter
);
1014 struct cgroup_subsys_state
*css
= NULL
;
1015 struct mem_cgroup
*memcg
= NULL
;
1016 struct mem_cgroup
*pos
= NULL
;
1018 if (mem_cgroup_disabled())
1022 root
= root_mem_cgroup
;
1024 if (prev
&& !reclaim
)
1027 if (!root
->use_hierarchy
&& root
!= root_mem_cgroup
) {
1036 struct mem_cgroup_per_node
*mz
;
1038 mz
= mem_cgroup_nodeinfo(root
, reclaim
->pgdat
->node_id
);
1039 iter
= &mz
->iter
[reclaim
->priority
];
1041 if (prev
&& reclaim
->generation
!= iter
->generation
)
1045 pos
= READ_ONCE(iter
->position
);
1046 if (!pos
|| css_tryget(&pos
->css
))
1049 * css reference reached zero, so iter->position will
1050 * be cleared by ->css_released. However, we should not
1051 * rely on this happening soon, because ->css_released
1052 * is called from a work queue, and by busy-waiting we
1053 * might block it. So we clear iter->position right
1056 (void)cmpxchg(&iter
->position
, pos
, NULL
);
1064 css
= css_next_descendant_pre(css
, &root
->css
);
1067 * Reclaimers share the hierarchy walk, and a
1068 * new one might jump in right at the end of
1069 * the hierarchy - make sure they see at least
1070 * one group and restart from the beginning.
1078 * Verify the css and acquire a reference. The root
1079 * is provided by the caller, so we know it's alive
1080 * and kicking, and don't take an extra reference.
1082 memcg
= mem_cgroup_from_css(css
);
1084 if (css
== &root
->css
)
1087 if (css_tryget(css
))
1095 * The position could have already been updated by a competing
1096 * thread, so check that the value hasn't changed since we read
1097 * it to avoid reclaiming from the same cgroup twice.
1099 (void)cmpxchg(&iter
->position
, pos
, memcg
);
1107 reclaim
->generation
= iter
->generation
;
1113 if (prev
&& prev
!= root
)
1114 css_put(&prev
->css
);
1120 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1121 * @root: hierarchy root
1122 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1124 void mem_cgroup_iter_break(struct mem_cgroup
*root
,
1125 struct mem_cgroup
*prev
)
1128 root
= root_mem_cgroup
;
1129 if (prev
&& prev
!= root
)
1130 css_put(&prev
->css
);
1133 static void invalidate_reclaim_iterators(struct mem_cgroup
*dead_memcg
)
1135 struct mem_cgroup
*memcg
= dead_memcg
;
1136 struct mem_cgroup_reclaim_iter
*iter
;
1137 struct mem_cgroup_per_node
*mz
;
1141 for (; memcg
; memcg
= parent_mem_cgroup(memcg
)) {
1142 for_each_node(nid
) {
1143 mz
= mem_cgroup_nodeinfo(memcg
, nid
);
1144 for (i
= 0; i
<= DEF_PRIORITY
; i
++) {
1145 iter
= &mz
->iter
[i
];
1146 cmpxchg(&iter
->position
,
1154 * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
1155 * @memcg: hierarchy root
1156 * @fn: function to call for each task
1157 * @arg: argument passed to @fn
1159 * This function iterates over tasks attached to @memcg or to any of its
1160 * descendants and calls @fn for each task. If @fn returns a non-zero
1161 * value, the function breaks the iteration loop and returns the value.
1162 * Otherwise, it will iterate over all tasks and return 0.
1164 * This function must not be called for the root memory cgroup.
1166 int mem_cgroup_scan_tasks(struct mem_cgroup
*memcg
,
1167 int (*fn
)(struct task_struct
*, void *), void *arg
)
1169 struct mem_cgroup
*iter
;
1172 BUG_ON(memcg
== root_mem_cgroup
);
1174 for_each_mem_cgroup_tree(iter
, memcg
) {
1175 struct css_task_iter it
;
1176 struct task_struct
*task
;
1178 css_task_iter_start(&iter
->css
, CSS_TASK_ITER_PROCS
, &it
);
1179 while (!ret
&& (task
= css_task_iter_next(&it
)))
1180 ret
= fn(task
, arg
);
1181 css_task_iter_end(&it
);
1183 mem_cgroup_iter_break(memcg
, iter
);
1191 * mem_cgroup_page_lruvec - return lruvec for isolating/putting an LRU page
1193 * @pgdat: pgdat of the page
1195 * This function is only safe when following the LRU page isolation
1196 * and putback protocol: the LRU lock must be held, and the page must
1197 * either be PageLRU() or the caller must have isolated/allocated it.
1199 struct lruvec
*mem_cgroup_page_lruvec(struct page
*page
, struct pglist_data
*pgdat
)
1201 struct mem_cgroup_per_node
*mz
;
1202 struct mem_cgroup
*memcg
;
1203 struct lruvec
*lruvec
;
1205 if (mem_cgroup_disabled()) {
1206 lruvec
= &pgdat
->lruvec
;
1210 memcg
= page
->mem_cgroup
;
1212 * Swapcache readahead pages are added to the LRU - and
1213 * possibly migrated - before they are charged.
1216 memcg
= root_mem_cgroup
;
1218 mz
= mem_cgroup_page_nodeinfo(memcg
, page
);
1219 lruvec
= &mz
->lruvec
;
1222 * Since a node can be onlined after the mem_cgroup was created,
1223 * we have to be prepared to initialize lruvec->zone here;
1224 * and if offlined then reonlined, we need to reinitialize it.
1226 if (unlikely(lruvec
->pgdat
!= pgdat
))
1227 lruvec
->pgdat
= pgdat
;
1232 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1233 * @lruvec: mem_cgroup per zone lru vector
1234 * @lru: index of lru list the page is sitting on
1235 * @zid: zone id of the accounted pages
1236 * @nr_pages: positive when adding or negative when removing
1238 * This function must be called under lru_lock, just before a page is added
1239 * to or just after a page is removed from an lru list (that ordering being
1240 * so as to allow it to check that lru_size 0 is consistent with list_empty).
1242 void mem_cgroup_update_lru_size(struct lruvec
*lruvec
, enum lru_list lru
,
1243 int zid
, int nr_pages
)
1245 struct mem_cgroup_per_node
*mz
;
1246 unsigned long *lru_size
;
1249 if (mem_cgroup_disabled())
1252 mz
= container_of(lruvec
, struct mem_cgroup_per_node
, lruvec
);
1253 lru_size
= &mz
->lru_zone_size
[zid
][lru
];
1256 *lru_size
+= nr_pages
;
1259 if (WARN_ONCE(size
< 0,
1260 "%s(%p, %d, %d): lru_size %ld\n",
1261 __func__
, lruvec
, lru
, nr_pages
, size
)) {
1267 *lru_size
+= nr_pages
;
1271 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1272 * @memcg: the memory cgroup
1274 * Returns the maximum amount of memory @mem can be charged with, in
1277 static unsigned long mem_cgroup_margin(struct mem_cgroup
*memcg
)
1279 unsigned long margin
= 0;
1280 unsigned long count
;
1281 unsigned long limit
;
1283 count
= page_counter_read(&memcg
->memory
);
1284 limit
= READ_ONCE(memcg
->memory
.max
);
1286 margin
= limit
- count
;
1288 if (do_memsw_account()) {
1289 count
= page_counter_read(&memcg
->memsw
);
1290 limit
= READ_ONCE(memcg
->memsw
.max
);
1292 margin
= min(margin
, limit
- count
);
1301 * A routine for checking "mem" is under move_account() or not.
1303 * Checking a cgroup is mc.from or mc.to or under hierarchy of
1304 * moving cgroups. This is for waiting at high-memory pressure
1307 static bool mem_cgroup_under_move(struct mem_cgroup
*memcg
)
1309 struct mem_cgroup
*from
;
1310 struct mem_cgroup
*to
;
1313 * Unlike task_move routines, we access mc.to, mc.from not under
1314 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1316 spin_lock(&mc
.lock
);
1322 ret
= mem_cgroup_is_descendant(from
, memcg
) ||
1323 mem_cgroup_is_descendant(to
, memcg
);
1325 spin_unlock(&mc
.lock
);
1329 static bool mem_cgroup_wait_acct_move(struct mem_cgroup
*memcg
)
1331 if (mc
.moving_task
&& current
!= mc
.moving_task
) {
1332 if (mem_cgroup_under_move(memcg
)) {
1334 prepare_to_wait(&mc
.waitq
, &wait
, TASK_INTERRUPTIBLE
);
1335 /* moving charge context might have finished. */
1338 finish_wait(&mc
.waitq
, &wait
);
1345 static char *memory_stat_format(struct mem_cgroup
*memcg
)
1350 seq_buf_init(&s
, kmalloc(PAGE_SIZE
, GFP_KERNEL
), PAGE_SIZE
);
1355 * Provide statistics on the state of the memory subsystem as
1356 * well as cumulative event counters that show past behavior.
1358 * This list is ordered following a combination of these gradients:
1359 * 1) generic big picture -> specifics and details
1360 * 2) reflecting userspace activity -> reflecting kernel heuristics
1362 * Current memory state:
1365 seq_buf_printf(&s
, "anon %llu\n",
1366 (u64
)memcg_page_state(memcg
, MEMCG_RSS
) *
1368 seq_buf_printf(&s
, "file %llu\n",
1369 (u64
)memcg_page_state(memcg
, MEMCG_CACHE
) *
1371 seq_buf_printf(&s
, "kernel_stack %llu\n",
1372 (u64
)memcg_page_state(memcg
, MEMCG_KERNEL_STACK_KB
) *
1374 seq_buf_printf(&s
, "slab %llu\n",
1375 (u64
)(memcg_page_state(memcg
, NR_SLAB_RECLAIMABLE
) +
1376 memcg_page_state(memcg
, NR_SLAB_UNRECLAIMABLE
)) *
1378 seq_buf_printf(&s
, "sock %llu\n",
1379 (u64
)memcg_page_state(memcg
, MEMCG_SOCK
) *
1382 seq_buf_printf(&s
, "shmem %llu\n",
1383 (u64
)memcg_page_state(memcg
, NR_SHMEM
) *
1385 seq_buf_printf(&s
, "file_mapped %llu\n",
1386 (u64
)memcg_page_state(memcg
, NR_FILE_MAPPED
) *
1388 seq_buf_printf(&s
, "file_dirty %llu\n",
1389 (u64
)memcg_page_state(memcg
, NR_FILE_DIRTY
) *
1391 seq_buf_printf(&s
, "file_writeback %llu\n",
1392 (u64
)memcg_page_state(memcg
, NR_WRITEBACK
) *
1396 * TODO: We should eventually replace our own MEMCG_RSS_HUGE counter
1397 * with the NR_ANON_THP vm counter, but right now it's a pain in the
1398 * arse because it requires migrating the work out of rmap to a place
1399 * where the page->mem_cgroup is set up and stable.
1401 seq_buf_printf(&s
, "anon_thp %llu\n",
1402 (u64
)memcg_page_state(memcg
, MEMCG_RSS_HUGE
) *
1405 for (i
= 0; i
< NR_LRU_LISTS
; i
++)
1406 seq_buf_printf(&s
, "%s %llu\n", mem_cgroup_lru_names
[i
],
1407 (u64
)memcg_page_state(memcg
, NR_LRU_BASE
+ i
) *
1410 seq_buf_printf(&s
, "slab_reclaimable %llu\n",
1411 (u64
)memcg_page_state(memcg
, NR_SLAB_RECLAIMABLE
) *
1413 seq_buf_printf(&s
, "slab_unreclaimable %llu\n",
1414 (u64
)memcg_page_state(memcg
, NR_SLAB_UNRECLAIMABLE
) *
1417 /* Accumulated memory events */
1419 seq_buf_printf(&s
, "pgfault %lu\n", memcg_events(memcg
, PGFAULT
));
1420 seq_buf_printf(&s
, "pgmajfault %lu\n", memcg_events(memcg
, PGMAJFAULT
));
1422 seq_buf_printf(&s
, "workingset_refault %lu\n",
1423 memcg_page_state(memcg
, WORKINGSET_REFAULT
));
1424 seq_buf_printf(&s
, "workingset_activate %lu\n",
1425 memcg_page_state(memcg
, WORKINGSET_ACTIVATE
));
1426 seq_buf_printf(&s
, "workingset_nodereclaim %lu\n",
1427 memcg_page_state(memcg
, WORKINGSET_NODERECLAIM
));
1429 seq_buf_printf(&s
, "pgrefill %lu\n", memcg_events(memcg
, PGREFILL
));
1430 seq_buf_printf(&s
, "pgscan %lu\n",
1431 memcg_events(memcg
, PGSCAN_KSWAPD
) +
1432 memcg_events(memcg
, PGSCAN_DIRECT
));
1433 seq_buf_printf(&s
, "pgsteal %lu\n",
1434 memcg_events(memcg
, PGSTEAL_KSWAPD
) +
1435 memcg_events(memcg
, PGSTEAL_DIRECT
));
1436 seq_buf_printf(&s
, "pgactivate %lu\n", memcg_events(memcg
, PGACTIVATE
));
1437 seq_buf_printf(&s
, "pgdeactivate %lu\n", memcg_events(memcg
, PGDEACTIVATE
));
1438 seq_buf_printf(&s
, "pglazyfree %lu\n", memcg_events(memcg
, PGLAZYFREE
));
1439 seq_buf_printf(&s
, "pglazyfreed %lu\n", memcg_events(memcg
, PGLAZYFREED
));
1441 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1442 seq_buf_printf(&s
, "thp_fault_alloc %lu\n",
1443 memcg_events(memcg
, THP_FAULT_ALLOC
));
1444 seq_buf_printf(&s
, "thp_collapse_alloc %lu\n",
1445 memcg_events(memcg
, THP_COLLAPSE_ALLOC
));
1446 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
1448 /* The above should easily fit into one page */
1449 WARN_ON_ONCE(seq_buf_has_overflowed(&s
));
1454 #define K(x) ((x) << (PAGE_SHIFT-10))
1456 * mem_cgroup_print_oom_context: Print OOM information relevant to
1457 * memory controller.
1458 * @memcg: The memory cgroup that went over limit
1459 * @p: Task that is going to be killed
1461 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1464 void mem_cgroup_print_oom_context(struct mem_cgroup
*memcg
, struct task_struct
*p
)
1469 pr_cont(",oom_memcg=");
1470 pr_cont_cgroup_path(memcg
->css
.cgroup
);
1472 pr_cont(",global_oom");
1474 pr_cont(",task_memcg=");
1475 pr_cont_cgroup_path(task_cgroup(p
, memory_cgrp_id
));
1481 * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
1482 * memory controller.
1483 * @memcg: The memory cgroup that went over limit
1485 void mem_cgroup_print_oom_meminfo(struct mem_cgroup
*memcg
)
1489 pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1490 K((u64
)page_counter_read(&memcg
->memory
)),
1491 K((u64
)memcg
->memory
.max
), memcg
->memory
.failcnt
);
1492 if (cgroup_subsys_on_dfl(memory_cgrp_subsys
))
1493 pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n",
1494 K((u64
)page_counter_read(&memcg
->swap
)),
1495 K((u64
)memcg
->swap
.max
), memcg
->swap
.failcnt
);
1497 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1498 K((u64
)page_counter_read(&memcg
->memsw
)),
1499 K((u64
)memcg
->memsw
.max
), memcg
->memsw
.failcnt
);
1500 pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1501 K((u64
)page_counter_read(&memcg
->kmem
)),
1502 K((u64
)memcg
->kmem
.max
), memcg
->kmem
.failcnt
);
1505 pr_info("Memory cgroup stats for ");
1506 pr_cont_cgroup_path(memcg
->css
.cgroup
);
1508 buf
= memory_stat_format(memcg
);
1516 * Return the memory (and swap, if configured) limit for a memcg.
1518 unsigned long mem_cgroup_get_max(struct mem_cgroup
*memcg
)
1522 max
= memcg
->memory
.max
;
1523 if (mem_cgroup_swappiness(memcg
)) {
1524 unsigned long memsw_max
;
1525 unsigned long swap_max
;
1527 memsw_max
= memcg
->memsw
.max
;
1528 swap_max
= memcg
->swap
.max
;
1529 swap_max
= min(swap_max
, (unsigned long)total_swap_pages
);
1530 max
= min(max
+ swap_max
, memsw_max
);
1535 static bool mem_cgroup_out_of_memory(struct mem_cgroup
*memcg
, gfp_t gfp_mask
,
1538 struct oom_control oc
= {
1542 .gfp_mask
= gfp_mask
,
1547 if (mutex_lock_killable(&oom_lock
))
1550 * A few threads which were not waiting at mutex_lock_killable() can
1551 * fail to bail out. Therefore, check again after holding oom_lock.
1553 ret
= should_force_charge() || out_of_memory(&oc
);
1554 mutex_unlock(&oom_lock
);
1558 #if MAX_NUMNODES > 1
1561 * test_mem_cgroup_node_reclaimable
1562 * @memcg: the target memcg
1563 * @nid: the node ID to be checked.
1564 * @noswap : specify true here if the user wants flle only information.
1566 * This function returns whether the specified memcg contains any
1567 * reclaimable pages on a node. Returns true if there are any reclaimable
1568 * pages in the node.
1570 static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup
*memcg
,
1571 int nid
, bool noswap
)
1573 struct lruvec
*lruvec
= mem_cgroup_lruvec(NODE_DATA(nid
), memcg
);
1575 if (lruvec_page_state(lruvec
, NR_INACTIVE_FILE
) ||
1576 lruvec_page_state(lruvec
, NR_ACTIVE_FILE
))
1578 if (noswap
|| !total_swap_pages
)
1580 if (lruvec_page_state(lruvec
, NR_INACTIVE_ANON
) ||
1581 lruvec_page_state(lruvec
, NR_ACTIVE_ANON
))
1588 * Always updating the nodemask is not very good - even if we have an empty
1589 * list or the wrong list here, we can start from some node and traverse all
1590 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1593 static void mem_cgroup_may_update_nodemask(struct mem_cgroup
*memcg
)
1597 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1598 * pagein/pageout changes since the last update.
1600 if (!atomic_read(&memcg
->numainfo_events
))
1602 if (atomic_inc_return(&memcg
->numainfo_updating
) > 1)
1605 /* make a nodemask where this memcg uses memory from */
1606 memcg
->scan_nodes
= node_states
[N_MEMORY
];
1608 for_each_node_mask(nid
, node_states
[N_MEMORY
]) {
1610 if (!test_mem_cgroup_node_reclaimable(memcg
, nid
, false))
1611 node_clear(nid
, memcg
->scan_nodes
);
1614 atomic_set(&memcg
->numainfo_events
, 0);
1615 atomic_set(&memcg
->numainfo_updating
, 0);
1619 * Selecting a node where we start reclaim from. Because what we need is just
1620 * reducing usage counter, start from anywhere is O,K. Considering
1621 * memory reclaim from current node, there are pros. and cons.
1623 * Freeing memory from current node means freeing memory from a node which
1624 * we'll use or we've used. So, it may make LRU bad. And if several threads
1625 * hit limits, it will see a contention on a node. But freeing from remote
1626 * node means more costs for memory reclaim because of memory latency.
1628 * Now, we use round-robin. Better algorithm is welcomed.
1630 int mem_cgroup_select_victim_node(struct mem_cgroup
*memcg
)
1634 mem_cgroup_may_update_nodemask(memcg
);
1635 node
= memcg
->last_scanned_node
;
1637 node
= next_node_in(node
, memcg
->scan_nodes
);
1639 * mem_cgroup_may_update_nodemask might have seen no reclaimmable pages
1640 * last time it really checked all the LRUs due to rate limiting.
1641 * Fallback to the current node in that case for simplicity.
1643 if (unlikely(node
== MAX_NUMNODES
))
1644 node
= numa_node_id();
1646 memcg
->last_scanned_node
= node
;
1650 int mem_cgroup_select_victim_node(struct mem_cgroup
*memcg
)
1656 static int mem_cgroup_soft_reclaim(struct mem_cgroup
*root_memcg
,
1659 unsigned long *total_scanned
)
1661 struct mem_cgroup
*victim
= NULL
;
1664 unsigned long excess
;
1665 unsigned long nr_scanned
;
1666 struct mem_cgroup_reclaim_cookie reclaim
= {
1671 excess
= soft_limit_excess(root_memcg
);
1674 victim
= mem_cgroup_iter(root_memcg
, victim
, &reclaim
);
1679 * If we have not been able to reclaim
1680 * anything, it might because there are
1681 * no reclaimable pages under this hierarchy
1686 * We want to do more targeted reclaim.
1687 * excess >> 2 is not to excessive so as to
1688 * reclaim too much, nor too less that we keep
1689 * coming back to reclaim from this cgroup
1691 if (total
>= (excess
>> 2) ||
1692 (loop
> MEM_CGROUP_MAX_RECLAIM_LOOPS
))
1697 total
+= mem_cgroup_shrink_node(victim
, gfp_mask
, false,
1698 pgdat
, &nr_scanned
);
1699 *total_scanned
+= nr_scanned
;
1700 if (!soft_limit_excess(root_memcg
))
1703 mem_cgroup_iter_break(root_memcg
, victim
);
1707 #ifdef CONFIG_LOCKDEP
1708 static struct lockdep_map memcg_oom_lock_dep_map
= {
1709 .name
= "memcg_oom_lock",
1713 static DEFINE_SPINLOCK(memcg_oom_lock
);
1716 * Check OOM-Killer is already running under our hierarchy.
1717 * If someone is running, return false.
1719 static bool mem_cgroup_oom_trylock(struct mem_cgroup
*memcg
)
1721 struct mem_cgroup
*iter
, *failed
= NULL
;
1723 spin_lock(&memcg_oom_lock
);
1725 for_each_mem_cgroup_tree(iter
, memcg
) {
1726 if (iter
->oom_lock
) {
1728 * this subtree of our hierarchy is already locked
1729 * so we cannot give a lock.
1732 mem_cgroup_iter_break(memcg
, iter
);
1735 iter
->oom_lock
= true;
1740 * OK, we failed to lock the whole subtree so we have
1741 * to clean up what we set up to the failing subtree
1743 for_each_mem_cgroup_tree(iter
, memcg
) {
1744 if (iter
== failed
) {
1745 mem_cgroup_iter_break(memcg
, iter
);
1748 iter
->oom_lock
= false;
1751 mutex_acquire(&memcg_oom_lock_dep_map
, 0, 1, _RET_IP_
);
1753 spin_unlock(&memcg_oom_lock
);
1758 static void mem_cgroup_oom_unlock(struct mem_cgroup
*memcg
)
1760 struct mem_cgroup
*iter
;
1762 spin_lock(&memcg_oom_lock
);
1763 mutex_release(&memcg_oom_lock_dep_map
, 1, _RET_IP_
);
1764 for_each_mem_cgroup_tree(iter
, memcg
)
1765 iter
->oom_lock
= false;
1766 spin_unlock(&memcg_oom_lock
);
1769 static void mem_cgroup_mark_under_oom(struct mem_cgroup
*memcg
)
1771 struct mem_cgroup
*iter
;
1773 spin_lock(&memcg_oom_lock
);
1774 for_each_mem_cgroup_tree(iter
, memcg
)
1776 spin_unlock(&memcg_oom_lock
);
1779 static void mem_cgroup_unmark_under_oom(struct mem_cgroup
*memcg
)
1781 struct mem_cgroup
*iter
;
1784 * When a new child is created while the hierarchy is under oom,
1785 * mem_cgroup_oom_lock() may not be called. Watch for underflow.
1787 spin_lock(&memcg_oom_lock
);
1788 for_each_mem_cgroup_tree(iter
, memcg
)
1789 if (iter
->under_oom
> 0)
1791 spin_unlock(&memcg_oom_lock
);
1794 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq
);
1796 struct oom_wait_info
{
1797 struct mem_cgroup
*memcg
;
1798 wait_queue_entry_t wait
;
1801 static int memcg_oom_wake_function(wait_queue_entry_t
*wait
,
1802 unsigned mode
, int sync
, void *arg
)
1804 struct mem_cgroup
*wake_memcg
= (struct mem_cgroup
*)arg
;
1805 struct mem_cgroup
*oom_wait_memcg
;
1806 struct oom_wait_info
*oom_wait_info
;
1808 oom_wait_info
= container_of(wait
, struct oom_wait_info
, wait
);
1809 oom_wait_memcg
= oom_wait_info
->memcg
;
1811 if (!mem_cgroup_is_descendant(wake_memcg
, oom_wait_memcg
) &&
1812 !mem_cgroup_is_descendant(oom_wait_memcg
, wake_memcg
))
1814 return autoremove_wake_function(wait
, mode
, sync
, arg
);
1817 static void memcg_oom_recover(struct mem_cgroup
*memcg
)
1820 * For the following lockless ->under_oom test, the only required
1821 * guarantee is that it must see the state asserted by an OOM when
1822 * this function is called as a result of userland actions
1823 * triggered by the notification of the OOM. This is trivially
1824 * achieved by invoking mem_cgroup_mark_under_oom() before
1825 * triggering notification.
1827 if (memcg
&& memcg
->under_oom
)
1828 __wake_up(&memcg_oom_waitq
, TASK_NORMAL
, 0, memcg
);
1838 static enum oom_status
mem_cgroup_oom(struct mem_cgroup
*memcg
, gfp_t mask
, int order
)
1840 enum oom_status ret
;
1843 if (order
> PAGE_ALLOC_COSTLY_ORDER
)
1846 memcg_memory_event(memcg
, MEMCG_OOM
);
1849 * We are in the middle of the charge context here, so we
1850 * don't want to block when potentially sitting on a callstack
1851 * that holds all kinds of filesystem and mm locks.
1853 * cgroup1 allows disabling the OOM killer and waiting for outside
1854 * handling until the charge can succeed; remember the context and put
1855 * the task to sleep at the end of the page fault when all locks are
1858 * On the other hand, in-kernel OOM killer allows for an async victim
1859 * memory reclaim (oom_reaper) and that means that we are not solely
1860 * relying on the oom victim to make a forward progress and we can
1861 * invoke the oom killer here.
1863 * Please note that mem_cgroup_out_of_memory might fail to find a
1864 * victim and then we have to bail out from the charge path.
1866 if (memcg
->oom_kill_disable
) {
1867 if (!current
->in_user_fault
)
1869 css_get(&memcg
->css
);
1870 current
->memcg_in_oom
= memcg
;
1871 current
->memcg_oom_gfp_mask
= mask
;
1872 current
->memcg_oom_order
= order
;
1877 mem_cgroup_mark_under_oom(memcg
);
1879 locked
= mem_cgroup_oom_trylock(memcg
);
1882 mem_cgroup_oom_notify(memcg
);
1884 mem_cgroup_unmark_under_oom(memcg
);
1885 if (mem_cgroup_out_of_memory(memcg
, mask
, order
))
1891 mem_cgroup_oom_unlock(memcg
);
1897 * mem_cgroup_oom_synchronize - complete memcg OOM handling
1898 * @handle: actually kill/wait or just clean up the OOM state
1900 * This has to be called at the end of a page fault if the memcg OOM
1901 * handler was enabled.
1903 * Memcg supports userspace OOM handling where failed allocations must
1904 * sleep on a waitqueue until the userspace task resolves the
1905 * situation. Sleeping directly in the charge context with all kinds
1906 * of locks held is not a good idea, instead we remember an OOM state
1907 * in the task and mem_cgroup_oom_synchronize() has to be called at
1908 * the end of the page fault to complete the OOM handling.
1910 * Returns %true if an ongoing memcg OOM situation was detected and
1911 * completed, %false otherwise.
1913 bool mem_cgroup_oom_synchronize(bool handle
)
1915 struct mem_cgroup
*memcg
= current
->memcg_in_oom
;
1916 struct oom_wait_info owait
;
1919 /* OOM is global, do not handle */
1926 owait
.memcg
= memcg
;
1927 owait
.wait
.flags
= 0;
1928 owait
.wait
.func
= memcg_oom_wake_function
;
1929 owait
.wait
.private = current
;
1930 INIT_LIST_HEAD(&owait
.wait
.entry
);
1932 prepare_to_wait(&memcg_oom_waitq
, &owait
.wait
, TASK_KILLABLE
);
1933 mem_cgroup_mark_under_oom(memcg
);
1935 locked
= mem_cgroup_oom_trylock(memcg
);
1938 mem_cgroup_oom_notify(memcg
);
1940 if (locked
&& !memcg
->oom_kill_disable
) {
1941 mem_cgroup_unmark_under_oom(memcg
);
1942 finish_wait(&memcg_oom_waitq
, &owait
.wait
);
1943 mem_cgroup_out_of_memory(memcg
, current
->memcg_oom_gfp_mask
,
1944 current
->memcg_oom_order
);
1947 mem_cgroup_unmark_under_oom(memcg
);
1948 finish_wait(&memcg_oom_waitq
, &owait
.wait
);
1952 mem_cgroup_oom_unlock(memcg
);
1954 * There is no guarantee that an OOM-lock contender
1955 * sees the wakeups triggered by the OOM kill
1956 * uncharges. Wake any sleepers explicitely.
1958 memcg_oom_recover(memcg
);
1961 current
->memcg_in_oom
= NULL
;
1962 css_put(&memcg
->css
);
1967 * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
1968 * @victim: task to be killed by the OOM killer
1969 * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
1971 * Returns a pointer to a memory cgroup, which has to be cleaned up
1972 * by killing all belonging OOM-killable tasks.
1974 * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
1976 struct mem_cgroup
*mem_cgroup_get_oom_group(struct task_struct
*victim
,
1977 struct mem_cgroup
*oom_domain
)
1979 struct mem_cgroup
*oom_group
= NULL
;
1980 struct mem_cgroup
*memcg
;
1982 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys
))
1986 oom_domain
= root_mem_cgroup
;
1990 memcg
= mem_cgroup_from_task(victim
);
1991 if (memcg
== root_mem_cgroup
)
1995 * Traverse the memory cgroup hierarchy from the victim task's
1996 * cgroup up to the OOMing cgroup (or root) to find the
1997 * highest-level memory cgroup with oom.group set.
1999 for (; memcg
; memcg
= parent_mem_cgroup(memcg
)) {
2000 if (memcg
->oom_group
)
2003 if (memcg
== oom_domain
)
2008 css_get(&oom_group
->css
);
2015 void mem_cgroup_print_oom_group(struct mem_cgroup
*memcg
)
2017 pr_info("Tasks in ");
2018 pr_cont_cgroup_path(memcg
->css
.cgroup
);
2019 pr_cont(" are going to be killed due to memory.oom.group set\n");
2023 * lock_page_memcg - lock a page->mem_cgroup binding
2026 * This function protects unlocked LRU pages from being moved to
2029 * It ensures lifetime of the returned memcg. Caller is responsible
2030 * for the lifetime of the page; __unlock_page_memcg() is available
2031 * when @page might get freed inside the locked section.
2033 struct mem_cgroup
*lock_page_memcg(struct page
*page
)
2035 struct mem_cgroup
*memcg
;
2036 unsigned long flags
;
2039 * The RCU lock is held throughout the transaction. The fast
2040 * path can get away without acquiring the memcg->move_lock
2041 * because page moving starts with an RCU grace period.
2043 * The RCU lock also protects the memcg from being freed when
2044 * the page state that is going to change is the only thing
2045 * preventing the page itself from being freed. E.g. writeback
2046 * doesn't hold a page reference and relies on PG_writeback to
2047 * keep off truncation, migration and so forth.
2051 if (mem_cgroup_disabled())
2054 memcg
= page
->mem_cgroup
;
2055 if (unlikely(!memcg
))
2058 if (atomic_read(&memcg
->moving_account
) <= 0)
2061 spin_lock_irqsave(&memcg
->move_lock
, flags
);
2062 if (memcg
!= page
->mem_cgroup
) {
2063 spin_unlock_irqrestore(&memcg
->move_lock
, flags
);
2068 * When charge migration first begins, we can have locked and
2069 * unlocked page stat updates happening concurrently. Track
2070 * the task who has the lock for unlock_page_memcg().
2072 memcg
->move_lock_task
= current
;
2073 memcg
->move_lock_flags
= flags
;
2077 EXPORT_SYMBOL(lock_page_memcg
);
2080 * __unlock_page_memcg - unlock and unpin a memcg
2083 * Unlock and unpin a memcg returned by lock_page_memcg().
2085 void __unlock_page_memcg(struct mem_cgroup
*memcg
)
2087 if (memcg
&& memcg
->move_lock_task
== current
) {
2088 unsigned long flags
= memcg
->move_lock_flags
;
2090 memcg
->move_lock_task
= NULL
;
2091 memcg
->move_lock_flags
= 0;
2093 spin_unlock_irqrestore(&memcg
->move_lock
, flags
);
2100 * unlock_page_memcg - unlock a page->mem_cgroup binding
2103 void unlock_page_memcg(struct page
*page
)
2105 __unlock_page_memcg(page
->mem_cgroup
);
2107 EXPORT_SYMBOL(unlock_page_memcg
);
2109 struct memcg_stock_pcp
{
2110 struct mem_cgroup
*cached
; /* this never be root cgroup */
2111 unsigned int nr_pages
;
2112 struct work_struct work
;
2113 unsigned long flags
;
2114 #define FLUSHING_CACHED_CHARGE 0
2116 static DEFINE_PER_CPU(struct memcg_stock_pcp
, memcg_stock
);
2117 static DEFINE_MUTEX(percpu_charge_mutex
);
2120 * consume_stock: Try to consume stocked charge on this cpu.
2121 * @memcg: memcg to consume from.
2122 * @nr_pages: how many pages to charge.
2124 * The charges will only happen if @memcg matches the current cpu's memcg
2125 * stock, and at least @nr_pages are available in that stock. Failure to
2126 * service an allocation will refill the stock.
2128 * returns true if successful, false otherwise.
2130 static bool consume_stock(struct mem_cgroup
*memcg
, unsigned int nr_pages
)
2132 struct memcg_stock_pcp
*stock
;
2133 unsigned long flags
;
2136 if (nr_pages
> MEMCG_CHARGE_BATCH
)
2139 local_irq_save(flags
);
2141 stock
= this_cpu_ptr(&memcg_stock
);
2142 if (memcg
== stock
->cached
&& stock
->nr_pages
>= nr_pages
) {
2143 stock
->nr_pages
-= nr_pages
;
2147 local_irq_restore(flags
);
2153 * Returns stocks cached in percpu and reset cached information.
2155 static void drain_stock(struct memcg_stock_pcp
*stock
)
2157 struct mem_cgroup
*old
= stock
->cached
;
2159 if (stock
->nr_pages
) {
2160 page_counter_uncharge(&old
->memory
, stock
->nr_pages
);
2161 if (do_memsw_account())
2162 page_counter_uncharge(&old
->memsw
, stock
->nr_pages
);
2163 css_put_many(&old
->css
, stock
->nr_pages
);
2164 stock
->nr_pages
= 0;
2166 stock
->cached
= NULL
;
2169 static void drain_local_stock(struct work_struct
*dummy
)
2171 struct memcg_stock_pcp
*stock
;
2172 unsigned long flags
;
2175 * The only protection from memory hotplug vs. drain_stock races is
2176 * that we always operate on local CPU stock here with IRQ disabled
2178 local_irq_save(flags
);
2180 stock
= this_cpu_ptr(&memcg_stock
);
2182 clear_bit(FLUSHING_CACHED_CHARGE
, &stock
->flags
);
2184 local_irq_restore(flags
);
2188 * Cache charges(val) to local per_cpu area.
2189 * This will be consumed by consume_stock() function, later.
2191 static void refill_stock(struct mem_cgroup
*memcg
, unsigned int nr_pages
)
2193 struct memcg_stock_pcp
*stock
;
2194 unsigned long flags
;
2196 local_irq_save(flags
);
2198 stock
= this_cpu_ptr(&memcg_stock
);
2199 if (stock
->cached
!= memcg
) { /* reset if necessary */
2201 stock
->cached
= memcg
;
2203 stock
->nr_pages
+= nr_pages
;
2205 if (stock
->nr_pages
> MEMCG_CHARGE_BATCH
)
2208 local_irq_restore(flags
);
2212 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2213 * of the hierarchy under it.
2215 static void drain_all_stock(struct mem_cgroup
*root_memcg
)
2219 /* If someone's already draining, avoid adding running more workers. */
2220 if (!mutex_trylock(&percpu_charge_mutex
))
2223 * Notify other cpus that system-wide "drain" is running
2224 * We do not care about races with the cpu hotplug because cpu down
2225 * as well as workers from this path always operate on the local
2226 * per-cpu data. CPU up doesn't touch memcg_stock at all.
2229 for_each_online_cpu(cpu
) {
2230 struct memcg_stock_pcp
*stock
= &per_cpu(memcg_stock
, cpu
);
2231 struct mem_cgroup
*memcg
;
2233 memcg
= stock
->cached
;
2234 if (!memcg
|| !stock
->nr_pages
|| !css_tryget(&memcg
->css
))
2236 if (!mem_cgroup_is_descendant(memcg
, root_memcg
)) {
2237 css_put(&memcg
->css
);
2240 if (!test_and_set_bit(FLUSHING_CACHED_CHARGE
, &stock
->flags
)) {
2242 drain_local_stock(&stock
->work
);
2244 schedule_work_on(cpu
, &stock
->work
);
2246 css_put(&memcg
->css
);
2249 mutex_unlock(&percpu_charge_mutex
);
2252 static int memcg_hotplug_cpu_dead(unsigned int cpu
)
2254 struct memcg_stock_pcp
*stock
;
2255 struct mem_cgroup
*memcg
, *mi
;
2257 stock
= &per_cpu(memcg_stock
, cpu
);
2260 for_each_mem_cgroup(memcg
) {
2263 for (i
= 0; i
< MEMCG_NR_STAT
; i
++) {
2267 x
= this_cpu_xchg(memcg
->vmstats_percpu
->stat
[i
], 0);
2269 for (mi
= memcg
; mi
; mi
= parent_mem_cgroup(mi
))
2270 atomic_long_add(x
, &memcg
->vmstats
[i
]);
2272 if (i
>= NR_VM_NODE_STAT_ITEMS
)
2275 for_each_node(nid
) {
2276 struct mem_cgroup_per_node
*pn
;
2278 pn
= mem_cgroup_nodeinfo(memcg
, nid
);
2279 x
= this_cpu_xchg(pn
->lruvec_stat_cpu
->count
[i
], 0);
2282 atomic_long_add(x
, &pn
->lruvec_stat
[i
]);
2283 } while ((pn
= parent_nodeinfo(pn
, nid
)));
2287 for (i
= 0; i
< NR_VM_EVENT_ITEMS
; i
++) {
2290 x
= this_cpu_xchg(memcg
->vmstats_percpu
->events
[i
], 0);
2292 for (mi
= memcg
; mi
; mi
= parent_mem_cgroup(mi
))
2293 atomic_long_add(x
, &memcg
->vmevents
[i
]);
2300 static void reclaim_high(struct mem_cgroup
*memcg
,
2301 unsigned int nr_pages
,
2305 if (page_counter_read(&memcg
->memory
) <= memcg
->high
)
2307 memcg_memory_event(memcg
, MEMCG_HIGH
);
2308 try_to_free_mem_cgroup_pages(memcg
, nr_pages
, gfp_mask
, true);
2309 } while ((memcg
= parent_mem_cgroup(memcg
)));
2312 static void high_work_func(struct work_struct
*work
)
2314 struct mem_cgroup
*memcg
;
2316 memcg
= container_of(work
, struct mem_cgroup
, high_work
);
2317 reclaim_high(memcg
, MEMCG_CHARGE_BATCH
, GFP_KERNEL
);
2321 * Scheduled by try_charge() to be executed from the userland return path
2322 * and reclaims memory over the high limit.
2324 void mem_cgroup_handle_over_high(void)
2326 unsigned int nr_pages
= current
->memcg_nr_pages_over_high
;
2327 struct mem_cgroup
*memcg
;
2329 if (likely(!nr_pages
))
2332 memcg
= get_mem_cgroup_from_mm(current
->mm
);
2333 reclaim_high(memcg
, nr_pages
, GFP_KERNEL
);
2334 css_put(&memcg
->css
);
2335 current
->memcg_nr_pages_over_high
= 0;
2338 static int try_charge(struct mem_cgroup
*memcg
, gfp_t gfp_mask
,
2339 unsigned int nr_pages
)
2341 unsigned int batch
= max(MEMCG_CHARGE_BATCH
, nr_pages
);
2342 int nr_retries
= MEM_CGROUP_RECLAIM_RETRIES
;
2343 struct mem_cgroup
*mem_over_limit
;
2344 struct page_counter
*counter
;
2345 unsigned long nr_reclaimed
;
2346 bool may_swap
= true;
2347 bool drained
= false;
2348 enum oom_status oom_status
;
2350 if (mem_cgroup_is_root(memcg
))
2353 if (consume_stock(memcg
, nr_pages
))
2356 if (!do_memsw_account() ||
2357 page_counter_try_charge(&memcg
->memsw
, batch
, &counter
)) {
2358 if (page_counter_try_charge(&memcg
->memory
, batch
, &counter
))
2360 if (do_memsw_account())
2361 page_counter_uncharge(&memcg
->memsw
, batch
);
2362 mem_over_limit
= mem_cgroup_from_counter(counter
, memory
);
2364 mem_over_limit
= mem_cgroup_from_counter(counter
, memsw
);
2368 if (batch
> nr_pages
) {
2374 * Unlike in global OOM situations, memcg is not in a physical
2375 * memory shortage. Allow dying and OOM-killed tasks to
2376 * bypass the last charges so that they can exit quickly and
2377 * free their memory.
2379 if (unlikely(should_force_charge()))
2383 * Prevent unbounded recursion when reclaim operations need to
2384 * allocate memory. This might exceed the limits temporarily,
2385 * but we prefer facilitating memory reclaim and getting back
2386 * under the limit over triggering OOM kills in these cases.
2388 if (unlikely(current
->flags
& PF_MEMALLOC
))
2391 if (unlikely(task_in_memcg_oom(current
)))
2394 if (!gfpflags_allow_blocking(gfp_mask
))
2397 memcg_memory_event(mem_over_limit
, MEMCG_MAX
);
2399 nr_reclaimed
= try_to_free_mem_cgroup_pages(mem_over_limit
, nr_pages
,
2400 gfp_mask
, may_swap
);
2402 if (mem_cgroup_margin(mem_over_limit
) >= nr_pages
)
2406 drain_all_stock(mem_over_limit
);
2411 if (gfp_mask
& __GFP_NORETRY
)
2414 * Even though the limit is exceeded at this point, reclaim
2415 * may have been able to free some pages. Retry the charge
2416 * before killing the task.
2418 * Only for regular pages, though: huge pages are rather
2419 * unlikely to succeed so close to the limit, and we fall back
2420 * to regular pages anyway in case of failure.
2422 if (nr_reclaimed
&& nr_pages
<= (1 << PAGE_ALLOC_COSTLY_ORDER
))
2425 * At task move, charge accounts can be doubly counted. So, it's
2426 * better to wait until the end of task_move if something is going on.
2428 if (mem_cgroup_wait_acct_move(mem_over_limit
))
2434 if (gfp_mask
& __GFP_RETRY_MAYFAIL
)
2437 if (gfp_mask
& __GFP_NOFAIL
)
2440 if (fatal_signal_pending(current
))
2444 * keep retrying as long as the memcg oom killer is able to make
2445 * a forward progress or bypass the charge if the oom killer
2446 * couldn't make any progress.
2448 oom_status
= mem_cgroup_oom(mem_over_limit
, gfp_mask
,
2449 get_order(nr_pages
* PAGE_SIZE
));
2450 switch (oom_status
) {
2452 nr_retries
= MEM_CGROUP_RECLAIM_RETRIES
;
2460 if (!(gfp_mask
& __GFP_NOFAIL
))
2464 * The allocation either can't fail or will lead to more memory
2465 * being freed very soon. Allow memory usage go over the limit
2466 * temporarily by force charging it.
2468 page_counter_charge(&memcg
->memory
, nr_pages
);
2469 if (do_memsw_account())
2470 page_counter_charge(&memcg
->memsw
, nr_pages
);
2471 css_get_many(&memcg
->css
, nr_pages
);
2476 css_get_many(&memcg
->css
, batch
);
2477 if (batch
> nr_pages
)
2478 refill_stock(memcg
, batch
- nr_pages
);
2481 * If the hierarchy is above the normal consumption range, schedule
2482 * reclaim on returning to userland. We can perform reclaim here
2483 * if __GFP_RECLAIM but let's always punt for simplicity and so that
2484 * GFP_KERNEL can consistently be used during reclaim. @memcg is
2485 * not recorded as it most likely matches current's and won't
2486 * change in the meantime. As high limit is checked again before
2487 * reclaim, the cost of mismatch is negligible.
2490 if (page_counter_read(&memcg
->memory
) > memcg
->high
) {
2491 /* Don't bother a random interrupted task */
2492 if (in_interrupt()) {
2493 schedule_work(&memcg
->high_work
);
2496 current
->memcg_nr_pages_over_high
+= batch
;
2497 set_notify_resume(current
);
2500 } while ((memcg
= parent_mem_cgroup(memcg
)));
2505 static void cancel_charge(struct mem_cgroup
*memcg
, unsigned int nr_pages
)
2507 if (mem_cgroup_is_root(memcg
))
2510 page_counter_uncharge(&memcg
->memory
, nr_pages
);
2511 if (do_memsw_account())
2512 page_counter_uncharge(&memcg
->memsw
, nr_pages
);
2514 css_put_many(&memcg
->css
, nr_pages
);
2517 static void lock_page_lru(struct page
*page
, int *isolated
)
2519 pg_data_t
*pgdat
= page_pgdat(page
);
2521 spin_lock_irq(&pgdat
->lru_lock
);
2522 if (PageLRU(page
)) {
2523 struct lruvec
*lruvec
;
2525 lruvec
= mem_cgroup_page_lruvec(page
, pgdat
);
2527 del_page_from_lru_list(page
, lruvec
, page_lru(page
));
2533 static void unlock_page_lru(struct page
*page
, int isolated
)
2535 pg_data_t
*pgdat
= page_pgdat(page
);
2538 struct lruvec
*lruvec
;
2540 lruvec
= mem_cgroup_page_lruvec(page
, pgdat
);
2541 VM_BUG_ON_PAGE(PageLRU(page
), page
);
2543 add_page_to_lru_list(page
, lruvec
, page_lru(page
));
2545 spin_unlock_irq(&pgdat
->lru_lock
);
2548 static void commit_charge(struct page
*page
, struct mem_cgroup
*memcg
,
2553 VM_BUG_ON_PAGE(page
->mem_cgroup
, page
);
2556 * In some cases, SwapCache and FUSE(splice_buf->radixtree), the page
2557 * may already be on some other mem_cgroup's LRU. Take care of it.
2560 lock_page_lru(page
, &isolated
);
2563 * Nobody should be changing or seriously looking at
2564 * page->mem_cgroup at this point:
2566 * - the page is uncharged
2568 * - the page is off-LRU
2570 * - an anonymous fault has exclusive page access, except for
2571 * a locked page table
2573 * - a page cache insertion, a swapin fault, or a migration
2574 * have the page locked
2576 page
->mem_cgroup
= memcg
;
2579 unlock_page_lru(page
, isolated
);
2582 #ifdef CONFIG_MEMCG_KMEM
2583 static int memcg_alloc_cache_id(void)
2588 id
= ida_simple_get(&memcg_cache_ida
,
2589 0, MEMCG_CACHES_MAX_SIZE
, GFP_KERNEL
);
2593 if (id
< memcg_nr_cache_ids
)
2597 * There's no space for the new id in memcg_caches arrays,
2598 * so we have to grow them.
2600 down_write(&memcg_cache_ids_sem
);
2602 size
= 2 * (id
+ 1);
2603 if (size
< MEMCG_CACHES_MIN_SIZE
)
2604 size
= MEMCG_CACHES_MIN_SIZE
;
2605 else if (size
> MEMCG_CACHES_MAX_SIZE
)
2606 size
= MEMCG_CACHES_MAX_SIZE
;
2608 err
= memcg_update_all_caches(size
);
2610 err
= memcg_update_all_list_lrus(size
);
2612 memcg_nr_cache_ids
= size
;
2614 up_write(&memcg_cache_ids_sem
);
2617 ida_simple_remove(&memcg_cache_ida
, id
);
2623 static void memcg_free_cache_id(int id
)
2625 ida_simple_remove(&memcg_cache_ida
, id
);
2628 struct memcg_kmem_cache_create_work
{
2629 struct mem_cgroup
*memcg
;
2630 struct kmem_cache
*cachep
;
2631 struct work_struct work
;
2634 static void memcg_kmem_cache_create_func(struct work_struct
*w
)
2636 struct memcg_kmem_cache_create_work
*cw
=
2637 container_of(w
, struct memcg_kmem_cache_create_work
, work
);
2638 struct mem_cgroup
*memcg
= cw
->memcg
;
2639 struct kmem_cache
*cachep
= cw
->cachep
;
2641 memcg_create_kmem_cache(memcg
, cachep
);
2643 css_put(&memcg
->css
);
2648 * Enqueue the creation of a per-memcg kmem_cache.
2650 static void memcg_schedule_kmem_cache_create(struct mem_cgroup
*memcg
,
2651 struct kmem_cache
*cachep
)
2653 struct memcg_kmem_cache_create_work
*cw
;
2655 if (!css_tryget_online(&memcg
->css
))
2658 cw
= kmalloc(sizeof(*cw
), GFP_NOWAIT
| __GFP_NOWARN
);
2663 cw
->cachep
= cachep
;
2664 INIT_WORK(&cw
->work
, memcg_kmem_cache_create_func
);
2666 queue_work(memcg_kmem_cache_wq
, &cw
->work
);
2669 static inline bool memcg_kmem_bypass(void)
2671 if (in_interrupt() || !current
->mm
|| (current
->flags
& PF_KTHREAD
))
2677 * memcg_kmem_get_cache: select the correct per-memcg cache for allocation
2678 * @cachep: the original global kmem cache
2680 * Return the kmem_cache we're supposed to use for a slab allocation.
2681 * We try to use the current memcg's version of the cache.
2683 * If the cache does not exist yet, if we are the first user of it, we
2684 * create it asynchronously in a workqueue and let the current allocation
2685 * go through with the original cache.
2687 * This function takes a reference to the cache it returns to assure it
2688 * won't get destroyed while we are working with it. Once the caller is
2689 * done with it, memcg_kmem_put_cache() must be called to release the
2692 struct kmem_cache
*memcg_kmem_get_cache(struct kmem_cache
*cachep
)
2694 struct mem_cgroup
*memcg
;
2695 struct kmem_cache
*memcg_cachep
;
2696 struct memcg_cache_array
*arr
;
2699 VM_BUG_ON(!is_root_cache(cachep
));
2701 if (memcg_kmem_bypass())
2706 if (unlikely(current
->active_memcg
))
2707 memcg
= current
->active_memcg
;
2709 memcg
= mem_cgroup_from_task(current
);
2711 if (!memcg
|| memcg
== root_mem_cgroup
)
2714 kmemcg_id
= READ_ONCE(memcg
->kmemcg_id
);
2718 arr
= rcu_dereference(cachep
->memcg_params
.memcg_caches
);
2721 * Make sure we will access the up-to-date value. The code updating
2722 * memcg_caches issues a write barrier to match the data dependency
2723 * barrier inside READ_ONCE() (see memcg_create_kmem_cache()).
2725 memcg_cachep
= READ_ONCE(arr
->entries
[kmemcg_id
]);
2728 * If we are in a safe context (can wait, and not in interrupt
2729 * context), we could be be predictable and return right away.
2730 * This would guarantee that the allocation being performed
2731 * already belongs in the new cache.
2733 * However, there are some clashes that can arrive from locking.
2734 * For instance, because we acquire the slab_mutex while doing
2735 * memcg_create_kmem_cache, this means no further allocation
2736 * could happen with the slab_mutex held. So it's better to
2739 * If the memcg is dying or memcg_cache is about to be released,
2740 * don't bother creating new kmem_caches. Because memcg_cachep
2741 * is ZEROed as the fist step of kmem offlining, we don't need
2742 * percpu_ref_tryget_live() here. css_tryget_online() check in
2743 * memcg_schedule_kmem_cache_create() will prevent us from
2744 * creation of a new kmem_cache.
2746 if (unlikely(!memcg_cachep
))
2747 memcg_schedule_kmem_cache_create(memcg
, cachep
);
2748 else if (percpu_ref_tryget(&memcg_cachep
->memcg_params
.refcnt
))
2749 cachep
= memcg_cachep
;
2756 * memcg_kmem_put_cache: drop reference taken by memcg_kmem_get_cache
2757 * @cachep: the cache returned by memcg_kmem_get_cache
2759 void memcg_kmem_put_cache(struct kmem_cache
*cachep
)
2761 if (!is_root_cache(cachep
))
2762 percpu_ref_put(&cachep
->memcg_params
.refcnt
);
2766 * __memcg_kmem_charge_memcg: charge a kmem page
2767 * @page: page to charge
2768 * @gfp: reclaim mode
2769 * @order: allocation order
2770 * @memcg: memory cgroup to charge
2772 * Returns 0 on success, an error code on failure.
2774 int __memcg_kmem_charge_memcg(struct page
*page
, gfp_t gfp
, int order
,
2775 struct mem_cgroup
*memcg
)
2777 unsigned int nr_pages
= 1 << order
;
2778 struct page_counter
*counter
;
2781 ret
= try_charge(memcg
, gfp
, nr_pages
);
2785 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys
) &&
2786 !page_counter_try_charge(&memcg
->kmem
, nr_pages
, &counter
)) {
2787 cancel_charge(memcg
, nr_pages
);
2794 * __memcg_kmem_charge: charge a kmem page to the current memory cgroup
2795 * @page: page to charge
2796 * @gfp: reclaim mode
2797 * @order: allocation order
2799 * Returns 0 on success, an error code on failure.
2801 int __memcg_kmem_charge(struct page
*page
, gfp_t gfp
, int order
)
2803 struct mem_cgroup
*memcg
;
2806 if (memcg_kmem_bypass())
2809 memcg
= get_mem_cgroup_from_current();
2810 if (!mem_cgroup_is_root(memcg
)) {
2811 ret
= __memcg_kmem_charge_memcg(page
, gfp
, order
, memcg
);
2813 page
->mem_cgroup
= memcg
;
2814 __SetPageKmemcg(page
);
2817 css_put(&memcg
->css
);
2822 * __memcg_kmem_uncharge_memcg: uncharge a kmem page
2823 * @memcg: memcg to uncharge
2824 * @nr_pages: number of pages to uncharge
2826 void __memcg_kmem_uncharge_memcg(struct mem_cgroup
*memcg
,
2827 unsigned int nr_pages
)
2829 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys
))
2830 page_counter_uncharge(&memcg
->kmem
, nr_pages
);
2832 page_counter_uncharge(&memcg
->memory
, nr_pages
);
2833 if (do_memsw_account())
2834 page_counter_uncharge(&memcg
->memsw
, nr_pages
);
2837 * __memcg_kmem_uncharge: uncharge a kmem page
2838 * @page: page to uncharge
2839 * @order: allocation order
2841 void __memcg_kmem_uncharge(struct page
*page
, int order
)
2843 struct mem_cgroup
*memcg
= page
->mem_cgroup
;
2844 unsigned int nr_pages
= 1 << order
;
2849 VM_BUG_ON_PAGE(mem_cgroup_is_root(memcg
), page
);
2850 __memcg_kmem_uncharge_memcg(memcg
, nr_pages
);
2851 page
->mem_cgroup
= NULL
;
2853 /* slab pages do not have PageKmemcg flag set */
2854 if (PageKmemcg(page
))
2855 __ClearPageKmemcg(page
);
2857 css_put_many(&memcg
->css
, nr_pages
);
2859 #endif /* CONFIG_MEMCG_KMEM */
2861 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2864 * Because tail pages are not marked as "used", set it. We're under
2865 * pgdat->lru_lock and migration entries setup in all page mappings.
2867 void mem_cgroup_split_huge_fixup(struct page
*head
)
2871 if (mem_cgroup_disabled())
2874 for (i
= 1; i
< HPAGE_PMD_NR
; i
++)
2875 head
[i
].mem_cgroup
= head
->mem_cgroup
;
2877 __mod_memcg_state(head
->mem_cgroup
, MEMCG_RSS_HUGE
, -HPAGE_PMD_NR
);
2879 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
2881 #ifdef CONFIG_MEMCG_SWAP
2883 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
2884 * @entry: swap entry to be moved
2885 * @from: mem_cgroup which the entry is moved from
2886 * @to: mem_cgroup which the entry is moved to
2888 * It succeeds only when the swap_cgroup's record for this entry is the same
2889 * as the mem_cgroup's id of @from.
2891 * Returns 0 on success, -EINVAL on failure.
2893 * The caller must have charged to @to, IOW, called page_counter_charge() about
2894 * both res and memsw, and called css_get().
2896 static int mem_cgroup_move_swap_account(swp_entry_t entry
,
2897 struct mem_cgroup
*from
, struct mem_cgroup
*to
)
2899 unsigned short old_id
, new_id
;
2901 old_id
= mem_cgroup_id(from
);
2902 new_id
= mem_cgroup_id(to
);
2904 if (swap_cgroup_cmpxchg(entry
, old_id
, new_id
) == old_id
) {
2905 mod_memcg_state(from
, MEMCG_SWAP
, -1);
2906 mod_memcg_state(to
, MEMCG_SWAP
, 1);
2912 static inline int mem_cgroup_move_swap_account(swp_entry_t entry
,
2913 struct mem_cgroup
*from
, struct mem_cgroup
*to
)
2919 static DEFINE_MUTEX(memcg_max_mutex
);
2921 static int mem_cgroup_resize_max(struct mem_cgroup
*memcg
,
2922 unsigned long max
, bool memsw
)
2924 bool enlarge
= false;
2925 bool drained
= false;
2927 bool limits_invariant
;
2928 struct page_counter
*counter
= memsw
? &memcg
->memsw
: &memcg
->memory
;
2931 if (signal_pending(current
)) {
2936 mutex_lock(&memcg_max_mutex
);
2938 * Make sure that the new limit (memsw or memory limit) doesn't
2939 * break our basic invariant rule memory.max <= memsw.max.
2941 limits_invariant
= memsw
? max
>= memcg
->memory
.max
:
2942 max
<= memcg
->memsw
.max
;
2943 if (!limits_invariant
) {
2944 mutex_unlock(&memcg_max_mutex
);
2948 if (max
> counter
->max
)
2950 ret
= page_counter_set_max(counter
, max
);
2951 mutex_unlock(&memcg_max_mutex
);
2957 drain_all_stock(memcg
);
2962 if (!try_to_free_mem_cgroup_pages(memcg
, 1,
2963 GFP_KERNEL
, !memsw
)) {
2969 if (!ret
&& enlarge
)
2970 memcg_oom_recover(memcg
);
2975 unsigned long mem_cgroup_soft_limit_reclaim(pg_data_t
*pgdat
, int order
,
2977 unsigned long *total_scanned
)
2979 unsigned long nr_reclaimed
= 0;
2980 struct mem_cgroup_per_node
*mz
, *next_mz
= NULL
;
2981 unsigned long reclaimed
;
2983 struct mem_cgroup_tree_per_node
*mctz
;
2984 unsigned long excess
;
2985 unsigned long nr_scanned
;
2990 mctz
= soft_limit_tree_node(pgdat
->node_id
);
2993 * Do not even bother to check the largest node if the root
2994 * is empty. Do it lockless to prevent lock bouncing. Races
2995 * are acceptable as soft limit is best effort anyway.
2997 if (!mctz
|| RB_EMPTY_ROOT(&mctz
->rb_root
))
3001 * This loop can run a while, specially if mem_cgroup's continuously
3002 * keep exceeding their soft limit and putting the system under
3009 mz
= mem_cgroup_largest_soft_limit_node(mctz
);
3014 reclaimed
= mem_cgroup_soft_reclaim(mz
->memcg
, pgdat
,
3015 gfp_mask
, &nr_scanned
);
3016 nr_reclaimed
+= reclaimed
;
3017 *total_scanned
+= nr_scanned
;
3018 spin_lock_irq(&mctz
->lock
);
3019 __mem_cgroup_remove_exceeded(mz
, mctz
);
3022 * If we failed to reclaim anything from this memory cgroup
3023 * it is time to move on to the next cgroup
3027 next_mz
= __mem_cgroup_largest_soft_limit_node(mctz
);
3029 excess
= soft_limit_excess(mz
->memcg
);
3031 * One school of thought says that we should not add
3032 * back the node to the tree if reclaim returns 0.
3033 * But our reclaim could return 0, simply because due
3034 * to priority we are exposing a smaller subset of
3035 * memory to reclaim from. Consider this as a longer
3038 /* If excess == 0, no tree ops */
3039 __mem_cgroup_insert_exceeded(mz
, mctz
, excess
);
3040 spin_unlock_irq(&mctz
->lock
);
3041 css_put(&mz
->memcg
->css
);
3044 * Could not reclaim anything and there are no more
3045 * mem cgroups to try or we seem to be looping without
3046 * reclaiming anything.
3048 if (!nr_reclaimed
&&
3050 loop
> MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS
))
3052 } while (!nr_reclaimed
);
3054 css_put(&next_mz
->memcg
->css
);
3055 return nr_reclaimed
;
3059 * Test whether @memcg has children, dead or alive. Note that this
3060 * function doesn't care whether @memcg has use_hierarchy enabled and
3061 * returns %true if there are child csses according to the cgroup
3062 * hierarchy. Testing use_hierarchy is the caller's responsiblity.
3064 static inline bool memcg_has_children(struct mem_cgroup
*memcg
)
3069 ret
= css_next_child(NULL
, &memcg
->css
);
3075 * Reclaims as many pages from the given memcg as possible.
3077 * Caller is responsible for holding css reference for memcg.
3079 static int mem_cgroup_force_empty(struct mem_cgroup
*memcg
)
3081 int nr_retries
= MEM_CGROUP_RECLAIM_RETRIES
;
3083 /* we call try-to-free pages for make this cgroup empty */
3084 lru_add_drain_all();
3086 drain_all_stock(memcg
);
3088 /* try to free all pages in this cgroup */
3089 while (nr_retries
&& page_counter_read(&memcg
->memory
)) {
3092 if (signal_pending(current
))
3095 progress
= try_to_free_mem_cgroup_pages(memcg
, 1,
3099 /* maybe some writeback is necessary */
3100 congestion_wait(BLK_RW_ASYNC
, HZ
/10);
3108 static ssize_t
mem_cgroup_force_empty_write(struct kernfs_open_file
*of
,
3109 char *buf
, size_t nbytes
,
3112 struct mem_cgroup
*memcg
= mem_cgroup_from_css(of_css(of
));
3114 if (mem_cgroup_is_root(memcg
))
3116 return mem_cgroup_force_empty(memcg
) ?: nbytes
;
3119 static u64
mem_cgroup_hierarchy_read(struct cgroup_subsys_state
*css
,
3122 return mem_cgroup_from_css(css
)->use_hierarchy
;
3125 static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state
*css
,
3126 struct cftype
*cft
, u64 val
)
3129 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
3130 struct mem_cgroup
*parent_memcg
= mem_cgroup_from_css(memcg
->css
.parent
);
3132 if (memcg
->use_hierarchy
== val
)
3136 * If parent's use_hierarchy is set, we can't make any modifications
3137 * in the child subtrees. If it is unset, then the change can
3138 * occur, provided the current cgroup has no children.
3140 * For the root cgroup, parent_mem is NULL, we allow value to be
3141 * set if there are no children.
3143 if ((!parent_memcg
|| !parent_memcg
->use_hierarchy
) &&
3144 (val
== 1 || val
== 0)) {
3145 if (!memcg_has_children(memcg
))
3146 memcg
->use_hierarchy
= val
;
3155 static unsigned long mem_cgroup_usage(struct mem_cgroup
*memcg
, bool swap
)
3159 if (mem_cgroup_is_root(memcg
)) {
3160 val
= memcg_page_state(memcg
, MEMCG_CACHE
) +
3161 memcg_page_state(memcg
, MEMCG_RSS
);
3163 val
+= memcg_page_state(memcg
, MEMCG_SWAP
);
3166 val
= page_counter_read(&memcg
->memory
);
3168 val
= page_counter_read(&memcg
->memsw
);
3181 static u64
mem_cgroup_read_u64(struct cgroup_subsys_state
*css
,
3184 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
3185 struct page_counter
*counter
;
3187 switch (MEMFILE_TYPE(cft
->private)) {
3189 counter
= &memcg
->memory
;
3192 counter
= &memcg
->memsw
;
3195 counter
= &memcg
->kmem
;
3198 counter
= &memcg
->tcpmem
;
3204 switch (MEMFILE_ATTR(cft
->private)) {
3206 if (counter
== &memcg
->memory
)
3207 return (u64
)mem_cgroup_usage(memcg
, false) * PAGE_SIZE
;
3208 if (counter
== &memcg
->memsw
)
3209 return (u64
)mem_cgroup_usage(memcg
, true) * PAGE_SIZE
;
3210 return (u64
)page_counter_read(counter
) * PAGE_SIZE
;
3212 return (u64
)counter
->max
* PAGE_SIZE
;
3214 return (u64
)counter
->watermark
* PAGE_SIZE
;
3216 return counter
->failcnt
;
3217 case RES_SOFT_LIMIT
:
3218 return (u64
)memcg
->soft_limit
* PAGE_SIZE
;
3224 #ifdef CONFIG_MEMCG_KMEM
3225 static int memcg_online_kmem(struct mem_cgroup
*memcg
)
3229 if (cgroup_memory_nokmem
)
3232 BUG_ON(memcg
->kmemcg_id
>= 0);
3233 BUG_ON(memcg
->kmem_state
);
3235 memcg_id
= memcg_alloc_cache_id();
3239 static_branch_inc(&memcg_kmem_enabled_key
);
3241 * A memory cgroup is considered kmem-online as soon as it gets
3242 * kmemcg_id. Setting the id after enabling static branching will
3243 * guarantee no one starts accounting before all call sites are
3246 memcg
->kmemcg_id
= memcg_id
;
3247 memcg
->kmem_state
= KMEM_ONLINE
;
3248 INIT_LIST_HEAD(&memcg
->kmem_caches
);
3253 static void memcg_offline_kmem(struct mem_cgroup
*memcg
)
3255 struct cgroup_subsys_state
*css
;
3256 struct mem_cgroup
*parent
, *child
;
3259 if (memcg
->kmem_state
!= KMEM_ONLINE
)
3262 * Clear the online state before clearing memcg_caches array
3263 * entries. The slab_mutex in memcg_deactivate_kmem_caches()
3264 * guarantees that no cache will be created for this cgroup
3265 * after we are done (see memcg_create_kmem_cache()).
3267 memcg
->kmem_state
= KMEM_ALLOCATED
;
3269 parent
= parent_mem_cgroup(memcg
);
3271 parent
= root_mem_cgroup
;
3273 memcg_deactivate_kmem_caches(memcg
, parent
);
3275 kmemcg_id
= memcg
->kmemcg_id
;
3276 BUG_ON(kmemcg_id
< 0);
3279 * Change kmemcg_id of this cgroup and all its descendants to the
3280 * parent's id, and then move all entries from this cgroup's list_lrus
3281 * to ones of the parent. After we have finished, all list_lrus
3282 * corresponding to this cgroup are guaranteed to remain empty. The
3283 * ordering is imposed by list_lru_node->lock taken by
3284 * memcg_drain_all_list_lrus().
3286 rcu_read_lock(); /* can be called from css_free w/o cgroup_mutex */
3287 css_for_each_descendant_pre(css
, &memcg
->css
) {
3288 child
= mem_cgroup_from_css(css
);
3289 BUG_ON(child
->kmemcg_id
!= kmemcg_id
);
3290 child
->kmemcg_id
= parent
->kmemcg_id
;
3291 if (!memcg
->use_hierarchy
)
3296 memcg_drain_all_list_lrus(kmemcg_id
, parent
);
3298 memcg_free_cache_id(kmemcg_id
);
3301 static void memcg_free_kmem(struct mem_cgroup
*memcg
)
3303 /* css_alloc() failed, offlining didn't happen */
3304 if (unlikely(memcg
->kmem_state
== KMEM_ONLINE
))
3305 memcg_offline_kmem(memcg
);
3307 if (memcg
->kmem_state
== KMEM_ALLOCATED
) {
3308 WARN_ON(!list_empty(&memcg
->kmem_caches
));
3309 static_branch_dec(&memcg_kmem_enabled_key
);
3313 static int memcg_online_kmem(struct mem_cgroup
*memcg
)
3317 static void memcg_offline_kmem(struct mem_cgroup
*memcg
)
3320 static void memcg_free_kmem(struct mem_cgroup
*memcg
)
3323 #endif /* CONFIG_MEMCG_KMEM */
3325 static int memcg_update_kmem_max(struct mem_cgroup
*memcg
,
3330 mutex_lock(&memcg_max_mutex
);
3331 ret
= page_counter_set_max(&memcg
->kmem
, max
);
3332 mutex_unlock(&memcg_max_mutex
);
3336 static int memcg_update_tcp_max(struct mem_cgroup
*memcg
, unsigned long max
)
3340 mutex_lock(&memcg_max_mutex
);
3342 ret
= page_counter_set_max(&memcg
->tcpmem
, max
);
3346 if (!memcg
->tcpmem_active
) {
3348 * The active flag needs to be written after the static_key
3349 * update. This is what guarantees that the socket activation
3350 * function is the last one to run. See mem_cgroup_sk_alloc()
3351 * for details, and note that we don't mark any socket as
3352 * belonging to this memcg until that flag is up.
3354 * We need to do this, because static_keys will span multiple
3355 * sites, but we can't control their order. If we mark a socket
3356 * as accounted, but the accounting functions are not patched in
3357 * yet, we'll lose accounting.
3359 * We never race with the readers in mem_cgroup_sk_alloc(),
3360 * because when this value change, the code to process it is not
3363 static_branch_inc(&memcg_sockets_enabled_key
);
3364 memcg
->tcpmem_active
= true;
3367 mutex_unlock(&memcg_max_mutex
);
3372 * The user of this function is...
3375 static ssize_t
mem_cgroup_write(struct kernfs_open_file
*of
,
3376 char *buf
, size_t nbytes
, loff_t off
)
3378 struct mem_cgroup
*memcg
= mem_cgroup_from_css(of_css(of
));
3379 unsigned long nr_pages
;
3382 buf
= strstrip(buf
);
3383 ret
= page_counter_memparse(buf
, "-1", &nr_pages
);
3387 switch (MEMFILE_ATTR(of_cft(of
)->private)) {
3389 if (mem_cgroup_is_root(memcg
)) { /* Can't set limit on root */
3393 switch (MEMFILE_TYPE(of_cft(of
)->private)) {
3395 ret
= mem_cgroup_resize_max(memcg
, nr_pages
, false);
3398 ret
= mem_cgroup_resize_max(memcg
, nr_pages
, true);
3401 ret
= memcg_update_kmem_max(memcg
, nr_pages
);
3404 ret
= memcg_update_tcp_max(memcg
, nr_pages
);
3408 case RES_SOFT_LIMIT
:
3409 memcg
->soft_limit
= nr_pages
;
3413 return ret
?: nbytes
;
3416 static ssize_t
mem_cgroup_reset(struct kernfs_open_file
*of
, char *buf
,
3417 size_t nbytes
, loff_t off
)
3419 struct mem_cgroup
*memcg
= mem_cgroup_from_css(of_css(of
));
3420 struct page_counter
*counter
;
3422 switch (MEMFILE_TYPE(of_cft(of
)->private)) {
3424 counter
= &memcg
->memory
;
3427 counter
= &memcg
->memsw
;
3430 counter
= &memcg
->kmem
;
3433 counter
= &memcg
->tcpmem
;
3439 switch (MEMFILE_ATTR(of_cft(of
)->private)) {
3441 page_counter_reset_watermark(counter
);
3444 counter
->failcnt
= 0;
3453 static u64
mem_cgroup_move_charge_read(struct cgroup_subsys_state
*css
,
3456 return mem_cgroup_from_css(css
)->move_charge_at_immigrate
;
3460 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state
*css
,
3461 struct cftype
*cft
, u64 val
)
3463 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
3465 if (val
& ~MOVE_MASK
)
3469 * No kind of locking is needed in here, because ->can_attach() will
3470 * check this value once in the beginning of the process, and then carry
3471 * on with stale data. This means that changes to this value will only
3472 * affect task migrations starting after the change.
3474 memcg
->move_charge_at_immigrate
= val
;
3478 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state
*css
,
3479 struct cftype
*cft
, u64 val
)
3487 #define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE))
3488 #define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON))
3489 #define LRU_ALL ((1 << NR_LRU_LISTS) - 1)
3491 static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup
*memcg
,
3492 int nid
, unsigned int lru_mask
)
3494 struct lruvec
*lruvec
= mem_cgroup_lruvec(NODE_DATA(nid
), memcg
);
3495 unsigned long nr
= 0;
3498 VM_BUG_ON((unsigned)nid
>= nr_node_ids
);
3501 if (!(BIT(lru
) & lru_mask
))
3503 nr
+= lruvec_page_state_local(lruvec
, NR_LRU_BASE
+ lru
);
3508 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup
*memcg
,
3509 unsigned int lru_mask
)
3511 unsigned long nr
= 0;
3515 if (!(BIT(lru
) & lru_mask
))
3517 nr
+= memcg_page_state_local(memcg
, NR_LRU_BASE
+ lru
);
3522 static int memcg_numa_stat_show(struct seq_file
*m
, void *v
)
3526 unsigned int lru_mask
;
3529 static const struct numa_stat stats
[] = {
3530 { "total", LRU_ALL
},
3531 { "file", LRU_ALL_FILE
},
3532 { "anon", LRU_ALL_ANON
},
3533 { "unevictable", BIT(LRU_UNEVICTABLE
) },
3535 const struct numa_stat
*stat
;
3538 struct mem_cgroup
*memcg
= mem_cgroup_from_seq(m
);
3540 for (stat
= stats
; stat
< stats
+ ARRAY_SIZE(stats
); stat
++) {
3541 nr
= mem_cgroup_nr_lru_pages(memcg
, stat
->lru_mask
);
3542 seq_printf(m
, "%s=%lu", stat
->name
, nr
);
3543 for_each_node_state(nid
, N_MEMORY
) {
3544 nr
= mem_cgroup_node_nr_lru_pages(memcg
, nid
,
3546 seq_printf(m
, " N%d=%lu", nid
, nr
);
3551 for (stat
= stats
; stat
< stats
+ ARRAY_SIZE(stats
); stat
++) {
3552 struct mem_cgroup
*iter
;
3555 for_each_mem_cgroup_tree(iter
, memcg
)
3556 nr
+= mem_cgroup_nr_lru_pages(iter
, stat
->lru_mask
);
3557 seq_printf(m
, "hierarchical_%s=%lu", stat
->name
, nr
);
3558 for_each_node_state(nid
, N_MEMORY
) {
3560 for_each_mem_cgroup_tree(iter
, memcg
)
3561 nr
+= mem_cgroup_node_nr_lru_pages(
3562 iter
, nid
, stat
->lru_mask
);
3563 seq_printf(m
, " N%d=%lu", nid
, nr
);
3570 #endif /* CONFIG_NUMA */
3572 static const unsigned int memcg1_stats
[] = {
3583 static const char *const memcg1_stat_names
[] = {
3594 /* Universal VM events cgroup1 shows, original sort order */
3595 static const unsigned int memcg1_events
[] = {
3602 static const char *const memcg1_event_names
[] = {
3609 static int memcg_stat_show(struct seq_file
*m
, void *v
)
3611 struct mem_cgroup
*memcg
= mem_cgroup_from_seq(m
);
3612 unsigned long memory
, memsw
;
3613 struct mem_cgroup
*mi
;
3616 BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names
) != ARRAY_SIZE(memcg1_stats
));
3617 BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_lru_names
) != NR_LRU_LISTS
);
3619 for (i
= 0; i
< ARRAY_SIZE(memcg1_stats
); i
++) {
3620 if (memcg1_stats
[i
] == MEMCG_SWAP
&& !do_memsw_account())
3622 seq_printf(m
, "%s %lu\n", memcg1_stat_names
[i
],
3623 memcg_page_state_local(memcg
, memcg1_stats
[i
]) *
3627 for (i
= 0; i
< ARRAY_SIZE(memcg1_events
); i
++)
3628 seq_printf(m
, "%s %lu\n", memcg1_event_names
[i
],
3629 memcg_events_local(memcg
, memcg1_events
[i
]));
3631 for (i
= 0; i
< NR_LRU_LISTS
; i
++)
3632 seq_printf(m
, "%s %lu\n", mem_cgroup_lru_names
[i
],
3633 memcg_page_state_local(memcg
, NR_LRU_BASE
+ i
) *
3636 /* Hierarchical information */
3637 memory
= memsw
= PAGE_COUNTER_MAX
;
3638 for (mi
= memcg
; mi
; mi
= parent_mem_cgroup(mi
)) {
3639 memory
= min(memory
, mi
->memory
.max
);
3640 memsw
= min(memsw
, mi
->memsw
.max
);
3642 seq_printf(m
, "hierarchical_memory_limit %llu\n",
3643 (u64
)memory
* PAGE_SIZE
);
3644 if (do_memsw_account())
3645 seq_printf(m
, "hierarchical_memsw_limit %llu\n",
3646 (u64
)memsw
* PAGE_SIZE
);
3648 for (i
= 0; i
< ARRAY_SIZE(memcg1_stats
); i
++) {
3649 if (memcg1_stats
[i
] == MEMCG_SWAP
&& !do_memsw_account())
3651 seq_printf(m
, "total_%s %llu\n", memcg1_stat_names
[i
],
3652 (u64
)memcg_page_state(memcg
, memcg1_stats
[i
]) *
3656 for (i
= 0; i
< ARRAY_SIZE(memcg1_events
); i
++)
3657 seq_printf(m
, "total_%s %llu\n", memcg1_event_names
[i
],
3658 (u64
)memcg_events(memcg
, memcg1_events
[i
]));
3660 for (i
= 0; i
< NR_LRU_LISTS
; i
++)
3661 seq_printf(m
, "total_%s %llu\n", mem_cgroup_lru_names
[i
],
3662 (u64
)memcg_page_state(memcg
, NR_LRU_BASE
+ i
) *
3665 #ifdef CONFIG_DEBUG_VM
3668 struct mem_cgroup_per_node
*mz
;
3669 struct zone_reclaim_stat
*rstat
;
3670 unsigned long recent_rotated
[2] = {0, 0};
3671 unsigned long recent_scanned
[2] = {0, 0};
3673 for_each_online_pgdat(pgdat
) {
3674 mz
= mem_cgroup_nodeinfo(memcg
, pgdat
->node_id
);
3675 rstat
= &mz
->lruvec
.reclaim_stat
;
3677 recent_rotated
[0] += rstat
->recent_rotated
[0];
3678 recent_rotated
[1] += rstat
->recent_rotated
[1];
3679 recent_scanned
[0] += rstat
->recent_scanned
[0];
3680 recent_scanned
[1] += rstat
->recent_scanned
[1];
3682 seq_printf(m
, "recent_rotated_anon %lu\n", recent_rotated
[0]);
3683 seq_printf(m
, "recent_rotated_file %lu\n", recent_rotated
[1]);
3684 seq_printf(m
, "recent_scanned_anon %lu\n", recent_scanned
[0]);
3685 seq_printf(m
, "recent_scanned_file %lu\n", recent_scanned
[1]);
3692 static u64
mem_cgroup_swappiness_read(struct cgroup_subsys_state
*css
,
3695 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
3697 return mem_cgroup_swappiness(memcg
);
3700 static int mem_cgroup_swappiness_write(struct cgroup_subsys_state
*css
,
3701 struct cftype
*cft
, u64 val
)
3703 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
3709 memcg
->swappiness
= val
;
3711 vm_swappiness
= val
;
3716 static void __mem_cgroup_threshold(struct mem_cgroup
*memcg
, bool swap
)
3718 struct mem_cgroup_threshold_ary
*t
;
3719 unsigned long usage
;
3724 t
= rcu_dereference(memcg
->thresholds
.primary
);
3726 t
= rcu_dereference(memcg
->memsw_thresholds
.primary
);
3731 usage
= mem_cgroup_usage(memcg
, swap
);
3734 * current_threshold points to threshold just below or equal to usage.
3735 * If it's not true, a threshold was crossed after last
3736 * call of __mem_cgroup_threshold().
3738 i
= t
->current_threshold
;
3741 * Iterate backward over array of thresholds starting from
3742 * current_threshold and check if a threshold is crossed.
3743 * If none of thresholds below usage is crossed, we read
3744 * only one element of the array here.
3746 for (; i
>= 0 && unlikely(t
->entries
[i
].threshold
> usage
); i
--)
3747 eventfd_signal(t
->entries
[i
].eventfd
, 1);
3749 /* i = current_threshold + 1 */
3753 * Iterate forward over array of thresholds starting from
3754 * current_threshold+1 and check if a threshold is crossed.
3755 * If none of thresholds above usage is crossed, we read
3756 * only one element of the array here.
3758 for (; i
< t
->size
&& unlikely(t
->entries
[i
].threshold
<= usage
); i
++)
3759 eventfd_signal(t
->entries
[i
].eventfd
, 1);
3761 /* Update current_threshold */
3762 t
->current_threshold
= i
- 1;
3767 static void mem_cgroup_threshold(struct mem_cgroup
*memcg
)
3770 __mem_cgroup_threshold(memcg
, false);
3771 if (do_memsw_account())
3772 __mem_cgroup_threshold(memcg
, true);
3774 memcg
= parent_mem_cgroup(memcg
);
3778 static int compare_thresholds(const void *a
, const void *b
)
3780 const struct mem_cgroup_threshold
*_a
= a
;
3781 const struct mem_cgroup_threshold
*_b
= b
;
3783 if (_a
->threshold
> _b
->threshold
)
3786 if (_a
->threshold
< _b
->threshold
)
3792 static int mem_cgroup_oom_notify_cb(struct mem_cgroup
*memcg
)
3794 struct mem_cgroup_eventfd_list
*ev
;
3796 spin_lock(&memcg_oom_lock
);
3798 list_for_each_entry(ev
, &memcg
->oom_notify
, list
)
3799 eventfd_signal(ev
->eventfd
, 1);
3801 spin_unlock(&memcg_oom_lock
);
3805 static void mem_cgroup_oom_notify(struct mem_cgroup
*memcg
)
3807 struct mem_cgroup
*iter
;
3809 for_each_mem_cgroup_tree(iter
, memcg
)
3810 mem_cgroup_oom_notify_cb(iter
);
3813 static int __mem_cgroup_usage_register_event(struct mem_cgroup
*memcg
,
3814 struct eventfd_ctx
*eventfd
, const char *args
, enum res_type type
)
3816 struct mem_cgroup_thresholds
*thresholds
;
3817 struct mem_cgroup_threshold_ary
*new;
3818 unsigned long threshold
;
3819 unsigned long usage
;
3822 ret
= page_counter_memparse(args
, "-1", &threshold
);
3826 mutex_lock(&memcg
->thresholds_lock
);
3829 thresholds
= &memcg
->thresholds
;
3830 usage
= mem_cgroup_usage(memcg
, false);
3831 } else if (type
== _MEMSWAP
) {
3832 thresholds
= &memcg
->memsw_thresholds
;
3833 usage
= mem_cgroup_usage(memcg
, true);
3837 /* Check if a threshold crossed before adding a new one */
3838 if (thresholds
->primary
)
3839 __mem_cgroup_threshold(memcg
, type
== _MEMSWAP
);
3841 size
= thresholds
->primary
? thresholds
->primary
->size
+ 1 : 1;
3843 /* Allocate memory for new array of thresholds */
3844 new = kmalloc(struct_size(new, entries
, size
), GFP_KERNEL
);
3851 /* Copy thresholds (if any) to new array */
3852 if (thresholds
->primary
) {
3853 memcpy(new->entries
, thresholds
->primary
->entries
, (size
- 1) *
3854 sizeof(struct mem_cgroup_threshold
));
3857 /* Add new threshold */
3858 new->entries
[size
- 1].eventfd
= eventfd
;
3859 new->entries
[size
- 1].threshold
= threshold
;
3861 /* Sort thresholds. Registering of new threshold isn't time-critical */
3862 sort(new->entries
, size
, sizeof(struct mem_cgroup_threshold
),
3863 compare_thresholds
, NULL
);
3865 /* Find current threshold */
3866 new->current_threshold
= -1;
3867 for (i
= 0; i
< size
; i
++) {
3868 if (new->entries
[i
].threshold
<= usage
) {
3870 * new->current_threshold will not be used until
3871 * rcu_assign_pointer(), so it's safe to increment
3874 ++new->current_threshold
;
3879 /* Free old spare buffer and save old primary buffer as spare */
3880 kfree(thresholds
->spare
);
3881 thresholds
->spare
= thresholds
->primary
;
3883 rcu_assign_pointer(thresholds
->primary
, new);
3885 /* To be sure that nobody uses thresholds */
3889 mutex_unlock(&memcg
->thresholds_lock
);
3894 static int mem_cgroup_usage_register_event(struct mem_cgroup
*memcg
,
3895 struct eventfd_ctx
*eventfd
, const char *args
)
3897 return __mem_cgroup_usage_register_event(memcg
, eventfd
, args
, _MEM
);
3900 static int memsw_cgroup_usage_register_event(struct mem_cgroup
*memcg
,
3901 struct eventfd_ctx
*eventfd
, const char *args
)
3903 return __mem_cgroup_usage_register_event(memcg
, eventfd
, args
, _MEMSWAP
);
3906 static void __mem_cgroup_usage_unregister_event(struct mem_cgroup
*memcg
,
3907 struct eventfd_ctx
*eventfd
, enum res_type type
)
3909 struct mem_cgroup_thresholds
*thresholds
;
3910 struct mem_cgroup_threshold_ary
*new;
3911 unsigned long usage
;
3914 mutex_lock(&memcg
->thresholds_lock
);
3917 thresholds
= &memcg
->thresholds
;
3918 usage
= mem_cgroup_usage(memcg
, false);
3919 } else if (type
== _MEMSWAP
) {
3920 thresholds
= &memcg
->memsw_thresholds
;
3921 usage
= mem_cgroup_usage(memcg
, true);
3925 if (!thresholds
->primary
)
3928 /* Check if a threshold crossed before removing */
3929 __mem_cgroup_threshold(memcg
, type
== _MEMSWAP
);
3931 /* Calculate new number of threshold */
3933 for (i
= 0; i
< thresholds
->primary
->size
; i
++) {
3934 if (thresholds
->primary
->entries
[i
].eventfd
!= eventfd
)
3938 new = thresholds
->spare
;
3940 /* Set thresholds array to NULL if we don't have thresholds */
3949 /* Copy thresholds and find current threshold */
3950 new->current_threshold
= -1;
3951 for (i
= 0, j
= 0; i
< thresholds
->primary
->size
; i
++) {
3952 if (thresholds
->primary
->entries
[i
].eventfd
== eventfd
)
3955 new->entries
[j
] = thresholds
->primary
->entries
[i
];
3956 if (new->entries
[j
].threshold
<= usage
) {
3958 * new->current_threshold will not be used
3959 * until rcu_assign_pointer(), so it's safe to increment
3962 ++new->current_threshold
;
3968 /* Swap primary and spare array */
3969 thresholds
->spare
= thresholds
->primary
;
3971 rcu_assign_pointer(thresholds
->primary
, new);
3973 /* To be sure that nobody uses thresholds */
3976 /* If all events are unregistered, free the spare array */
3978 kfree(thresholds
->spare
);
3979 thresholds
->spare
= NULL
;
3982 mutex_unlock(&memcg
->thresholds_lock
);
3985 static void mem_cgroup_usage_unregister_event(struct mem_cgroup
*memcg
,
3986 struct eventfd_ctx
*eventfd
)
3988 return __mem_cgroup_usage_unregister_event(memcg
, eventfd
, _MEM
);
3991 static void memsw_cgroup_usage_unregister_event(struct mem_cgroup
*memcg
,
3992 struct eventfd_ctx
*eventfd
)
3994 return __mem_cgroup_usage_unregister_event(memcg
, eventfd
, _MEMSWAP
);
3997 static int mem_cgroup_oom_register_event(struct mem_cgroup
*memcg
,
3998 struct eventfd_ctx
*eventfd
, const char *args
)
4000 struct mem_cgroup_eventfd_list
*event
;
4002 event
= kmalloc(sizeof(*event
), GFP_KERNEL
);
4006 spin_lock(&memcg_oom_lock
);
4008 event
->eventfd
= eventfd
;
4009 list_add(&event
->list
, &memcg
->oom_notify
);
4011 /* already in OOM ? */
4012 if (memcg
->under_oom
)
4013 eventfd_signal(eventfd
, 1);
4014 spin_unlock(&memcg_oom_lock
);
4019 static void mem_cgroup_oom_unregister_event(struct mem_cgroup
*memcg
,
4020 struct eventfd_ctx
*eventfd
)
4022 struct mem_cgroup_eventfd_list
*ev
, *tmp
;
4024 spin_lock(&memcg_oom_lock
);
4026 list_for_each_entry_safe(ev
, tmp
, &memcg
->oom_notify
, list
) {
4027 if (ev
->eventfd
== eventfd
) {
4028 list_del(&ev
->list
);
4033 spin_unlock(&memcg_oom_lock
);
4036 static int mem_cgroup_oom_control_read(struct seq_file
*sf
, void *v
)
4038 struct mem_cgroup
*memcg
= mem_cgroup_from_seq(sf
);
4040 seq_printf(sf
, "oom_kill_disable %d\n", memcg
->oom_kill_disable
);
4041 seq_printf(sf
, "under_oom %d\n", (bool)memcg
->under_oom
);
4042 seq_printf(sf
, "oom_kill %lu\n",
4043 atomic_long_read(&memcg
->memory_events
[MEMCG_OOM_KILL
]));
4047 static int mem_cgroup_oom_control_write(struct cgroup_subsys_state
*css
,
4048 struct cftype
*cft
, u64 val
)
4050 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
4052 /* cannot set to root cgroup and only 0 and 1 are allowed */
4053 if (!css
->parent
|| !((val
== 0) || (val
== 1)))
4056 memcg
->oom_kill_disable
= val
;
4058 memcg_oom_recover(memcg
);
4063 #ifdef CONFIG_CGROUP_WRITEBACK
4065 static int memcg_wb_domain_init(struct mem_cgroup
*memcg
, gfp_t gfp
)
4067 return wb_domain_init(&memcg
->cgwb_domain
, gfp
);
4070 static void memcg_wb_domain_exit(struct mem_cgroup
*memcg
)
4072 wb_domain_exit(&memcg
->cgwb_domain
);
4075 static void memcg_wb_domain_size_changed(struct mem_cgroup
*memcg
)
4077 wb_domain_size_changed(&memcg
->cgwb_domain
);
4080 struct wb_domain
*mem_cgroup_wb_domain(struct bdi_writeback
*wb
)
4082 struct mem_cgroup
*memcg
= mem_cgroup_from_css(wb
->memcg_css
);
4084 if (!memcg
->css
.parent
)
4087 return &memcg
->cgwb_domain
;
4091 * idx can be of type enum memcg_stat_item or node_stat_item.
4092 * Keep in sync with memcg_exact_page().
4094 static unsigned long memcg_exact_page_state(struct mem_cgroup
*memcg
, int idx
)
4096 long x
= atomic_long_read(&memcg
->vmstats
[idx
]);
4099 for_each_online_cpu(cpu
)
4100 x
+= per_cpu_ptr(memcg
->vmstats_percpu
, cpu
)->stat
[idx
];
4107 * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
4108 * @wb: bdi_writeback in question
4109 * @pfilepages: out parameter for number of file pages
4110 * @pheadroom: out parameter for number of allocatable pages according to memcg
4111 * @pdirty: out parameter for number of dirty pages
4112 * @pwriteback: out parameter for number of pages under writeback
4114 * Determine the numbers of file, headroom, dirty, and writeback pages in
4115 * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom
4116 * is a bit more involved.
4118 * A memcg's headroom is "min(max, high) - used". In the hierarchy, the
4119 * headroom is calculated as the lowest headroom of itself and the
4120 * ancestors. Note that this doesn't consider the actual amount of
4121 * available memory in the system. The caller should further cap
4122 * *@pheadroom accordingly.
4124 void mem_cgroup_wb_stats(struct bdi_writeback
*wb
, unsigned long *pfilepages
,
4125 unsigned long *pheadroom
, unsigned long *pdirty
,
4126 unsigned long *pwriteback
)
4128 struct mem_cgroup
*memcg
= mem_cgroup_from_css(wb
->memcg_css
);
4129 struct mem_cgroup
*parent
;
4131 *pdirty
= memcg_exact_page_state(memcg
, NR_FILE_DIRTY
);
4133 /* this should eventually include NR_UNSTABLE_NFS */
4134 *pwriteback
= memcg_exact_page_state(memcg
, NR_WRITEBACK
);
4135 *pfilepages
= memcg_exact_page_state(memcg
, NR_INACTIVE_FILE
) +
4136 memcg_exact_page_state(memcg
, NR_ACTIVE_FILE
);
4137 *pheadroom
= PAGE_COUNTER_MAX
;
4139 while ((parent
= parent_mem_cgroup(memcg
))) {
4140 unsigned long ceiling
= min(memcg
->memory
.max
, memcg
->high
);
4141 unsigned long used
= page_counter_read(&memcg
->memory
);
4143 *pheadroom
= min(*pheadroom
, ceiling
- min(ceiling
, used
));
4148 #else /* CONFIG_CGROUP_WRITEBACK */
4150 static int memcg_wb_domain_init(struct mem_cgroup
*memcg
, gfp_t gfp
)
4155 static void memcg_wb_domain_exit(struct mem_cgroup
*memcg
)
4159 static void memcg_wb_domain_size_changed(struct mem_cgroup
*memcg
)
4163 #endif /* CONFIG_CGROUP_WRITEBACK */
4166 * DO NOT USE IN NEW FILES.
4168 * "cgroup.event_control" implementation.
4170 * This is way over-engineered. It tries to support fully configurable
4171 * events for each user. Such level of flexibility is completely
4172 * unnecessary especially in the light of the planned unified hierarchy.
4174 * Please deprecate this and replace with something simpler if at all
4179 * Unregister event and free resources.
4181 * Gets called from workqueue.
4183 static void memcg_event_remove(struct work_struct
*work
)
4185 struct mem_cgroup_event
*event
=
4186 container_of(work
, struct mem_cgroup_event
, remove
);
4187 struct mem_cgroup
*memcg
= event
->memcg
;
4189 remove_wait_queue(event
->wqh
, &event
->wait
);
4191 event
->unregister_event(memcg
, event
->eventfd
);
4193 /* Notify userspace the event is going away. */
4194 eventfd_signal(event
->eventfd
, 1);
4196 eventfd_ctx_put(event
->eventfd
);
4198 css_put(&memcg
->css
);
4202 * Gets called on EPOLLHUP on eventfd when user closes it.
4204 * Called with wqh->lock held and interrupts disabled.
4206 static int memcg_event_wake(wait_queue_entry_t
*wait
, unsigned mode
,
4207 int sync
, void *key
)
4209 struct mem_cgroup_event
*event
=
4210 container_of(wait
, struct mem_cgroup_event
, wait
);
4211 struct mem_cgroup
*memcg
= event
->memcg
;
4212 __poll_t flags
= key_to_poll(key
);
4214 if (flags
& EPOLLHUP
) {
4216 * If the event has been detached at cgroup removal, we
4217 * can simply return knowing the other side will cleanup
4220 * We can't race against event freeing since the other
4221 * side will require wqh->lock via remove_wait_queue(),
4224 spin_lock(&memcg
->event_list_lock
);
4225 if (!list_empty(&event
->list
)) {
4226 list_del_init(&event
->list
);
4228 * We are in atomic context, but cgroup_event_remove()
4229 * may sleep, so we have to call it in workqueue.
4231 schedule_work(&event
->remove
);
4233 spin_unlock(&memcg
->event_list_lock
);
4239 static void memcg_event_ptable_queue_proc(struct file
*file
,
4240 wait_queue_head_t
*wqh
, poll_table
*pt
)
4242 struct mem_cgroup_event
*event
=
4243 container_of(pt
, struct mem_cgroup_event
, pt
);
4246 add_wait_queue(wqh
, &event
->wait
);
4250 * DO NOT USE IN NEW FILES.
4252 * Parse input and register new cgroup event handler.
4254 * Input must be in format '<event_fd> <control_fd> <args>'.
4255 * Interpretation of args is defined by control file implementation.
4257 static ssize_t
memcg_write_event_control(struct kernfs_open_file
*of
,
4258 char *buf
, size_t nbytes
, loff_t off
)
4260 struct cgroup_subsys_state
*css
= of_css(of
);
4261 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
4262 struct mem_cgroup_event
*event
;
4263 struct cgroup_subsys_state
*cfile_css
;
4264 unsigned int efd
, cfd
;
4271 buf
= strstrip(buf
);
4273 efd
= simple_strtoul(buf
, &endp
, 10);
4278 cfd
= simple_strtoul(buf
, &endp
, 10);
4279 if ((*endp
!= ' ') && (*endp
!= '\0'))
4283 event
= kzalloc(sizeof(*event
), GFP_KERNEL
);
4287 event
->memcg
= memcg
;
4288 INIT_LIST_HEAD(&event
->list
);
4289 init_poll_funcptr(&event
->pt
, memcg_event_ptable_queue_proc
);
4290 init_waitqueue_func_entry(&event
->wait
, memcg_event_wake
);
4291 INIT_WORK(&event
->remove
, memcg_event_remove
);
4299 event
->eventfd
= eventfd_ctx_fileget(efile
.file
);
4300 if (IS_ERR(event
->eventfd
)) {
4301 ret
= PTR_ERR(event
->eventfd
);
4308 goto out_put_eventfd
;
4311 /* the process need read permission on control file */
4312 /* AV: shouldn't we check that it's been opened for read instead? */
4313 ret
= inode_permission(file_inode(cfile
.file
), MAY_READ
);
4318 * Determine the event callbacks and set them in @event. This used
4319 * to be done via struct cftype but cgroup core no longer knows
4320 * about these events. The following is crude but the whole thing
4321 * is for compatibility anyway.
4323 * DO NOT ADD NEW FILES.
4325 name
= cfile
.file
->f_path
.dentry
->d_name
.name
;
4327 if (!strcmp(name
, "memory.usage_in_bytes")) {
4328 event
->register_event
= mem_cgroup_usage_register_event
;
4329 event
->unregister_event
= mem_cgroup_usage_unregister_event
;
4330 } else if (!strcmp(name
, "memory.oom_control")) {
4331 event
->register_event
= mem_cgroup_oom_register_event
;
4332 event
->unregister_event
= mem_cgroup_oom_unregister_event
;
4333 } else if (!strcmp(name
, "memory.pressure_level")) {
4334 event
->register_event
= vmpressure_register_event
;
4335 event
->unregister_event
= vmpressure_unregister_event
;
4336 } else if (!strcmp(name
, "memory.memsw.usage_in_bytes")) {
4337 event
->register_event
= memsw_cgroup_usage_register_event
;
4338 event
->unregister_event
= memsw_cgroup_usage_unregister_event
;
4345 * Verify @cfile should belong to @css. Also, remaining events are
4346 * automatically removed on cgroup destruction but the removal is
4347 * asynchronous, so take an extra ref on @css.
4349 cfile_css
= css_tryget_online_from_dir(cfile
.file
->f_path
.dentry
->d_parent
,
4350 &memory_cgrp_subsys
);
4352 if (IS_ERR(cfile_css
))
4354 if (cfile_css
!= css
) {
4359 ret
= event
->register_event(memcg
, event
->eventfd
, buf
);
4363 vfs_poll(efile
.file
, &event
->pt
);
4365 spin_lock(&memcg
->event_list_lock
);
4366 list_add(&event
->list
, &memcg
->event_list
);
4367 spin_unlock(&memcg
->event_list_lock
);
4379 eventfd_ctx_put(event
->eventfd
);
4388 static struct cftype mem_cgroup_legacy_files
[] = {
4390 .name
= "usage_in_bytes",
4391 .private = MEMFILE_PRIVATE(_MEM
, RES_USAGE
),
4392 .read_u64
= mem_cgroup_read_u64
,
4395 .name
= "max_usage_in_bytes",
4396 .private = MEMFILE_PRIVATE(_MEM
, RES_MAX_USAGE
),
4397 .write
= mem_cgroup_reset
,
4398 .read_u64
= mem_cgroup_read_u64
,
4401 .name
= "limit_in_bytes",
4402 .private = MEMFILE_PRIVATE(_MEM
, RES_LIMIT
),
4403 .write
= mem_cgroup_write
,
4404 .read_u64
= mem_cgroup_read_u64
,
4407 .name
= "soft_limit_in_bytes",
4408 .private = MEMFILE_PRIVATE(_MEM
, RES_SOFT_LIMIT
),
4409 .write
= mem_cgroup_write
,
4410 .read_u64
= mem_cgroup_read_u64
,
4414 .private = MEMFILE_PRIVATE(_MEM
, RES_FAILCNT
),
4415 .write
= mem_cgroup_reset
,
4416 .read_u64
= mem_cgroup_read_u64
,
4420 .seq_show
= memcg_stat_show
,
4423 .name
= "force_empty",
4424 .write
= mem_cgroup_force_empty_write
,
4427 .name
= "use_hierarchy",
4428 .write_u64
= mem_cgroup_hierarchy_write
,
4429 .read_u64
= mem_cgroup_hierarchy_read
,
4432 .name
= "cgroup.event_control", /* XXX: for compat */
4433 .write
= memcg_write_event_control
,
4434 .flags
= CFTYPE_NO_PREFIX
| CFTYPE_WORLD_WRITABLE
,
4437 .name
= "swappiness",
4438 .read_u64
= mem_cgroup_swappiness_read
,
4439 .write_u64
= mem_cgroup_swappiness_write
,
4442 .name
= "move_charge_at_immigrate",
4443 .read_u64
= mem_cgroup_move_charge_read
,
4444 .write_u64
= mem_cgroup_move_charge_write
,
4447 .name
= "oom_control",
4448 .seq_show
= mem_cgroup_oom_control_read
,
4449 .write_u64
= mem_cgroup_oom_control_write
,
4450 .private = MEMFILE_PRIVATE(_OOM_TYPE
, OOM_CONTROL
),
4453 .name
= "pressure_level",
4457 .name
= "numa_stat",
4458 .seq_show
= memcg_numa_stat_show
,
4462 .name
= "kmem.limit_in_bytes",
4463 .private = MEMFILE_PRIVATE(_KMEM
, RES_LIMIT
),
4464 .write
= mem_cgroup_write
,
4465 .read_u64
= mem_cgroup_read_u64
,
4468 .name
= "kmem.usage_in_bytes",
4469 .private = MEMFILE_PRIVATE(_KMEM
, RES_USAGE
),
4470 .read_u64
= mem_cgroup_read_u64
,
4473 .name
= "kmem.failcnt",
4474 .private = MEMFILE_PRIVATE(_KMEM
, RES_FAILCNT
),
4475 .write
= mem_cgroup_reset
,
4476 .read_u64
= mem_cgroup_read_u64
,
4479 .name
= "kmem.max_usage_in_bytes",
4480 .private = MEMFILE_PRIVATE(_KMEM
, RES_MAX_USAGE
),
4481 .write
= mem_cgroup_reset
,
4482 .read_u64
= mem_cgroup_read_u64
,
4484 #if defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG)
4486 .name
= "kmem.slabinfo",
4487 .seq_start
= memcg_slab_start
,
4488 .seq_next
= memcg_slab_next
,
4489 .seq_stop
= memcg_slab_stop
,
4490 .seq_show
= memcg_slab_show
,
4494 .name
= "kmem.tcp.limit_in_bytes",
4495 .private = MEMFILE_PRIVATE(_TCP
, RES_LIMIT
),
4496 .write
= mem_cgroup_write
,
4497 .read_u64
= mem_cgroup_read_u64
,
4500 .name
= "kmem.tcp.usage_in_bytes",
4501 .private = MEMFILE_PRIVATE(_TCP
, RES_USAGE
),
4502 .read_u64
= mem_cgroup_read_u64
,
4505 .name
= "kmem.tcp.failcnt",
4506 .private = MEMFILE_PRIVATE(_TCP
, RES_FAILCNT
),
4507 .write
= mem_cgroup_reset
,
4508 .read_u64
= mem_cgroup_read_u64
,
4511 .name
= "kmem.tcp.max_usage_in_bytes",
4512 .private = MEMFILE_PRIVATE(_TCP
, RES_MAX_USAGE
),
4513 .write
= mem_cgroup_reset
,
4514 .read_u64
= mem_cgroup_read_u64
,
4516 { }, /* terminate */
4520 * Private memory cgroup IDR
4522 * Swap-out records and page cache shadow entries need to store memcg
4523 * references in constrained space, so we maintain an ID space that is
4524 * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
4525 * memory-controlled cgroups to 64k.
4527 * However, there usually are many references to the oflline CSS after
4528 * the cgroup has been destroyed, such as page cache or reclaimable
4529 * slab objects, that don't need to hang on to the ID. We want to keep
4530 * those dead CSS from occupying IDs, or we might quickly exhaust the
4531 * relatively small ID space and prevent the creation of new cgroups
4532 * even when there are much fewer than 64k cgroups - possibly none.
4534 * Maintain a private 16-bit ID space for memcg, and allow the ID to
4535 * be freed and recycled when it's no longer needed, which is usually
4536 * when the CSS is offlined.
4538 * The only exception to that are records of swapped out tmpfs/shmem
4539 * pages that need to be attributed to live ancestors on swapin. But
4540 * those references are manageable from userspace.
4543 static DEFINE_IDR(mem_cgroup_idr
);
4545 static void mem_cgroup_id_remove(struct mem_cgroup
*memcg
)
4547 if (memcg
->id
.id
> 0) {
4548 idr_remove(&mem_cgroup_idr
, memcg
->id
.id
);
4553 static void mem_cgroup_id_get_many(struct mem_cgroup
*memcg
, unsigned int n
)
4555 refcount_add(n
, &memcg
->id
.ref
);
4558 static void mem_cgroup_id_put_many(struct mem_cgroup
*memcg
, unsigned int n
)
4560 if (refcount_sub_and_test(n
, &memcg
->id
.ref
)) {
4561 mem_cgroup_id_remove(memcg
);
4563 /* Memcg ID pins CSS */
4564 css_put(&memcg
->css
);
4568 static inline void mem_cgroup_id_get(struct mem_cgroup
*memcg
)
4570 mem_cgroup_id_get_many(memcg
, 1);
4573 static inline void mem_cgroup_id_put(struct mem_cgroup
*memcg
)
4575 mem_cgroup_id_put_many(memcg
, 1);
4579 * mem_cgroup_from_id - look up a memcg from a memcg id
4580 * @id: the memcg id to look up
4582 * Caller must hold rcu_read_lock().
4584 struct mem_cgroup
*mem_cgroup_from_id(unsigned short id
)
4586 WARN_ON_ONCE(!rcu_read_lock_held());
4587 return idr_find(&mem_cgroup_idr
, id
);
4590 static int alloc_mem_cgroup_per_node_info(struct mem_cgroup
*memcg
, int node
)
4592 struct mem_cgroup_per_node
*pn
;
4595 * This routine is called against possible nodes.
4596 * But it's BUG to call kmalloc() against offline node.
4598 * TODO: this routine can waste much memory for nodes which will
4599 * never be onlined. It's better to use memory hotplug callback
4602 if (!node_state(node
, N_NORMAL_MEMORY
))
4604 pn
= kzalloc_node(sizeof(*pn
), GFP_KERNEL
, tmp
);
4608 pn
->lruvec_stat_local
= alloc_percpu(struct lruvec_stat
);
4609 if (!pn
->lruvec_stat_local
) {
4614 pn
->lruvec_stat_cpu
= alloc_percpu(struct lruvec_stat
);
4615 if (!pn
->lruvec_stat_cpu
) {
4616 free_percpu(pn
->lruvec_stat_local
);
4621 lruvec_init(&pn
->lruvec
);
4622 pn
->usage_in_excess
= 0;
4623 pn
->on_tree
= false;
4626 memcg
->nodeinfo
[node
] = pn
;
4630 static void free_mem_cgroup_per_node_info(struct mem_cgroup
*memcg
, int node
)
4632 struct mem_cgroup_per_node
*pn
= memcg
->nodeinfo
[node
];
4637 free_percpu(pn
->lruvec_stat_cpu
);
4638 free_percpu(pn
->lruvec_stat_local
);
4642 static void __mem_cgroup_free(struct mem_cgroup
*memcg
)
4647 free_mem_cgroup_per_node_info(memcg
, node
);
4648 free_percpu(memcg
->vmstats_percpu
);
4649 free_percpu(memcg
->vmstats_local
);
4653 static void mem_cgroup_free(struct mem_cgroup
*memcg
)
4655 memcg_wb_domain_exit(memcg
);
4656 __mem_cgroup_free(memcg
);
4659 static struct mem_cgroup
*mem_cgroup_alloc(void)
4661 struct mem_cgroup
*memcg
;
4665 size
= sizeof(struct mem_cgroup
);
4666 size
+= nr_node_ids
* sizeof(struct mem_cgroup_per_node
*);
4668 memcg
= kzalloc(size
, GFP_KERNEL
);
4672 memcg
->id
.id
= idr_alloc(&mem_cgroup_idr
, NULL
,
4673 1, MEM_CGROUP_ID_MAX
,
4675 if (memcg
->id
.id
< 0)
4678 memcg
->vmstats_local
= alloc_percpu(struct memcg_vmstats_percpu
);
4679 if (!memcg
->vmstats_local
)
4682 memcg
->vmstats_percpu
= alloc_percpu(struct memcg_vmstats_percpu
);
4683 if (!memcg
->vmstats_percpu
)
4687 if (alloc_mem_cgroup_per_node_info(memcg
, node
))
4690 if (memcg_wb_domain_init(memcg
, GFP_KERNEL
))
4693 INIT_WORK(&memcg
->high_work
, high_work_func
);
4694 memcg
->last_scanned_node
= MAX_NUMNODES
;
4695 INIT_LIST_HEAD(&memcg
->oom_notify
);
4696 mutex_init(&memcg
->thresholds_lock
);
4697 spin_lock_init(&memcg
->move_lock
);
4698 vmpressure_init(&memcg
->vmpressure
);
4699 INIT_LIST_HEAD(&memcg
->event_list
);
4700 spin_lock_init(&memcg
->event_list_lock
);
4701 memcg
->socket_pressure
= jiffies
;
4702 #ifdef CONFIG_MEMCG_KMEM
4703 memcg
->kmemcg_id
= -1;
4705 #ifdef CONFIG_CGROUP_WRITEBACK
4706 INIT_LIST_HEAD(&memcg
->cgwb_list
);
4708 idr_replace(&mem_cgroup_idr
, memcg
, memcg
->id
.id
);
4711 mem_cgroup_id_remove(memcg
);
4712 __mem_cgroup_free(memcg
);
4716 static struct cgroup_subsys_state
* __ref
4717 mem_cgroup_css_alloc(struct cgroup_subsys_state
*parent_css
)
4719 struct mem_cgroup
*parent
= mem_cgroup_from_css(parent_css
);
4720 struct mem_cgroup
*memcg
;
4721 long error
= -ENOMEM
;
4723 memcg
= mem_cgroup_alloc();
4725 return ERR_PTR(error
);
4727 memcg
->high
= PAGE_COUNTER_MAX
;
4728 memcg
->soft_limit
= PAGE_COUNTER_MAX
;
4730 memcg
->swappiness
= mem_cgroup_swappiness(parent
);
4731 memcg
->oom_kill_disable
= parent
->oom_kill_disable
;
4733 if (parent
&& parent
->use_hierarchy
) {
4734 memcg
->use_hierarchy
= true;
4735 page_counter_init(&memcg
->memory
, &parent
->memory
);
4736 page_counter_init(&memcg
->swap
, &parent
->swap
);
4737 page_counter_init(&memcg
->memsw
, &parent
->memsw
);
4738 page_counter_init(&memcg
->kmem
, &parent
->kmem
);
4739 page_counter_init(&memcg
->tcpmem
, &parent
->tcpmem
);
4741 page_counter_init(&memcg
->memory
, NULL
);
4742 page_counter_init(&memcg
->swap
, NULL
);
4743 page_counter_init(&memcg
->memsw
, NULL
);
4744 page_counter_init(&memcg
->kmem
, NULL
);
4745 page_counter_init(&memcg
->tcpmem
, NULL
);
4747 * Deeper hierachy with use_hierarchy == false doesn't make
4748 * much sense so let cgroup subsystem know about this
4749 * unfortunate state in our controller.
4751 if (parent
!= root_mem_cgroup
)
4752 memory_cgrp_subsys
.broken_hierarchy
= true;
4755 /* The following stuff does not apply to the root */
4757 #ifdef CONFIG_MEMCG_KMEM
4758 INIT_LIST_HEAD(&memcg
->kmem_caches
);
4760 root_mem_cgroup
= memcg
;
4764 error
= memcg_online_kmem(memcg
);
4768 if (cgroup_subsys_on_dfl(memory_cgrp_subsys
) && !cgroup_memory_nosocket
)
4769 static_branch_inc(&memcg_sockets_enabled_key
);
4773 mem_cgroup_id_remove(memcg
);
4774 mem_cgroup_free(memcg
);
4775 return ERR_PTR(-ENOMEM
);
4778 static int mem_cgroup_css_online(struct cgroup_subsys_state
*css
)
4780 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
4783 * A memcg must be visible for memcg_expand_shrinker_maps()
4784 * by the time the maps are allocated. So, we allocate maps
4785 * here, when for_each_mem_cgroup() can't skip it.
4787 if (memcg_alloc_shrinker_maps(memcg
)) {
4788 mem_cgroup_id_remove(memcg
);
4792 /* Online state pins memcg ID, memcg ID pins CSS */
4793 refcount_set(&memcg
->id
.ref
, 1);
4798 static void mem_cgroup_css_offline(struct cgroup_subsys_state
*css
)
4800 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
4801 struct mem_cgroup_event
*event
, *tmp
;
4804 * Unregister events and notify userspace.
4805 * Notify userspace about cgroup removing only after rmdir of cgroup
4806 * directory to avoid race between userspace and kernelspace.
4808 spin_lock(&memcg
->event_list_lock
);
4809 list_for_each_entry_safe(event
, tmp
, &memcg
->event_list
, list
) {
4810 list_del_init(&event
->list
);
4811 schedule_work(&event
->remove
);
4813 spin_unlock(&memcg
->event_list_lock
);
4815 page_counter_set_min(&memcg
->memory
, 0);
4816 page_counter_set_low(&memcg
->memory
, 0);
4818 memcg_offline_kmem(memcg
);
4819 wb_memcg_offline(memcg
);
4821 drain_all_stock(memcg
);
4823 mem_cgroup_id_put(memcg
);
4826 static void mem_cgroup_css_released(struct cgroup_subsys_state
*css
)
4828 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
4830 invalidate_reclaim_iterators(memcg
);
4833 static void mem_cgroup_css_free(struct cgroup_subsys_state
*css
)
4835 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
4837 if (cgroup_subsys_on_dfl(memory_cgrp_subsys
) && !cgroup_memory_nosocket
)
4838 static_branch_dec(&memcg_sockets_enabled_key
);
4840 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys
) && memcg
->tcpmem_active
)
4841 static_branch_dec(&memcg_sockets_enabled_key
);
4843 vmpressure_cleanup(&memcg
->vmpressure
);
4844 cancel_work_sync(&memcg
->high_work
);
4845 mem_cgroup_remove_from_trees(memcg
);
4846 memcg_free_shrinker_maps(memcg
);
4847 memcg_free_kmem(memcg
);
4848 mem_cgroup_free(memcg
);
4852 * mem_cgroup_css_reset - reset the states of a mem_cgroup
4853 * @css: the target css
4855 * Reset the states of the mem_cgroup associated with @css. This is
4856 * invoked when the userland requests disabling on the default hierarchy
4857 * but the memcg is pinned through dependency. The memcg should stop
4858 * applying policies and should revert to the vanilla state as it may be
4859 * made visible again.
4861 * The current implementation only resets the essential configurations.
4862 * This needs to be expanded to cover all the visible parts.
4864 static void mem_cgroup_css_reset(struct cgroup_subsys_state
*css
)
4866 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
4868 page_counter_set_max(&memcg
->memory
, PAGE_COUNTER_MAX
);
4869 page_counter_set_max(&memcg
->swap
, PAGE_COUNTER_MAX
);
4870 page_counter_set_max(&memcg
->memsw
, PAGE_COUNTER_MAX
);
4871 page_counter_set_max(&memcg
->kmem
, PAGE_COUNTER_MAX
);
4872 page_counter_set_max(&memcg
->tcpmem
, PAGE_COUNTER_MAX
);
4873 page_counter_set_min(&memcg
->memory
, 0);
4874 page_counter_set_low(&memcg
->memory
, 0);
4875 memcg
->high
= PAGE_COUNTER_MAX
;
4876 memcg
->soft_limit
= PAGE_COUNTER_MAX
;
4877 memcg_wb_domain_size_changed(memcg
);
4881 /* Handlers for move charge at task migration. */
4882 static int mem_cgroup_do_precharge(unsigned long count
)
4886 /* Try a single bulk charge without reclaim first, kswapd may wake */
4887 ret
= try_charge(mc
.to
, GFP_KERNEL
& ~__GFP_DIRECT_RECLAIM
, count
);
4889 mc
.precharge
+= count
;
4893 /* Try charges one by one with reclaim, but do not retry */
4895 ret
= try_charge(mc
.to
, GFP_KERNEL
| __GFP_NORETRY
, 1);
4909 enum mc_target_type
{
4916 static struct page
*mc_handle_present_pte(struct vm_area_struct
*vma
,
4917 unsigned long addr
, pte_t ptent
)
4919 struct page
*page
= vm_normal_page(vma
, addr
, ptent
);
4921 if (!page
|| !page_mapped(page
))
4923 if (PageAnon(page
)) {
4924 if (!(mc
.flags
& MOVE_ANON
))
4927 if (!(mc
.flags
& MOVE_FILE
))
4930 if (!get_page_unless_zero(page
))
4936 #if defined(CONFIG_SWAP) || defined(CONFIG_DEVICE_PRIVATE)
4937 static struct page
*mc_handle_swap_pte(struct vm_area_struct
*vma
,
4938 pte_t ptent
, swp_entry_t
*entry
)
4940 struct page
*page
= NULL
;
4941 swp_entry_t ent
= pte_to_swp_entry(ptent
);
4943 if (!(mc
.flags
& MOVE_ANON
) || non_swap_entry(ent
))
4947 * Handle MEMORY_DEVICE_PRIVATE which are ZONE_DEVICE page belonging to
4948 * a device and because they are not accessible by CPU they are store
4949 * as special swap entry in the CPU page table.
4951 if (is_device_private_entry(ent
)) {
4952 page
= device_private_entry_to_page(ent
);
4954 * MEMORY_DEVICE_PRIVATE means ZONE_DEVICE page and which have
4955 * a refcount of 1 when free (unlike normal page)
4957 if (!page_ref_add_unless(page
, 1, 1))
4963 * Because lookup_swap_cache() updates some statistics counter,
4964 * we call find_get_page() with swapper_space directly.
4966 page
= find_get_page(swap_address_space(ent
), swp_offset(ent
));
4967 if (do_memsw_account())
4968 entry
->val
= ent
.val
;
4973 static struct page
*mc_handle_swap_pte(struct vm_area_struct
*vma
,
4974 pte_t ptent
, swp_entry_t
*entry
)
4980 static struct page
*mc_handle_file_pte(struct vm_area_struct
*vma
,
4981 unsigned long addr
, pte_t ptent
, swp_entry_t
*entry
)
4983 struct page
*page
= NULL
;
4984 struct address_space
*mapping
;
4987 if (!vma
->vm_file
) /* anonymous vma */
4989 if (!(mc
.flags
& MOVE_FILE
))
4992 mapping
= vma
->vm_file
->f_mapping
;
4993 pgoff
= linear_page_index(vma
, addr
);
4995 /* page is moved even if it's not RSS of this task(page-faulted). */
4997 /* shmem/tmpfs may report page out on swap: account for that too. */
4998 if (shmem_mapping(mapping
)) {
4999 page
= find_get_entry(mapping
, pgoff
);
5000 if (xa_is_value(page
)) {
5001 swp_entry_t swp
= radix_to_swp_entry(page
);
5002 if (do_memsw_account())
5004 page
= find_get_page(swap_address_space(swp
),
5008 page
= find_get_page(mapping
, pgoff
);
5010 page
= find_get_page(mapping
, pgoff
);
5016 * mem_cgroup_move_account - move account of the page
5018 * @compound: charge the page as compound or small page
5019 * @from: mem_cgroup which the page is moved from.
5020 * @to: mem_cgroup which the page is moved to. @from != @to.
5022 * The caller must make sure the page is not on LRU (isolate_page() is useful.)
5024 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
5027 static int mem_cgroup_move_account(struct page
*page
,
5029 struct mem_cgroup
*from
,
5030 struct mem_cgroup
*to
)
5032 unsigned long flags
;
5033 unsigned int nr_pages
= compound
? hpage_nr_pages(page
) : 1;
5037 VM_BUG_ON(from
== to
);
5038 VM_BUG_ON_PAGE(PageLRU(page
), page
);
5039 VM_BUG_ON(compound
&& !PageTransHuge(page
));
5042 * Prevent mem_cgroup_migrate() from looking at
5043 * page->mem_cgroup of its source page while we change it.
5046 if (!trylock_page(page
))
5050 if (page
->mem_cgroup
!= from
)
5053 anon
= PageAnon(page
);
5055 spin_lock_irqsave(&from
->move_lock
, flags
);
5057 if (!anon
&& page_mapped(page
)) {
5058 __mod_memcg_state(from
, NR_FILE_MAPPED
, -nr_pages
);
5059 __mod_memcg_state(to
, NR_FILE_MAPPED
, nr_pages
);
5063 * move_lock grabbed above and caller set from->moving_account, so
5064 * mod_memcg_page_state will serialize updates to PageDirty.
5065 * So mapping should be stable for dirty pages.
5067 if (!anon
&& PageDirty(page
)) {
5068 struct address_space
*mapping
= page_mapping(page
);
5070 if (mapping_cap_account_dirty(mapping
)) {
5071 __mod_memcg_state(from
, NR_FILE_DIRTY
, -nr_pages
);
5072 __mod_memcg_state(to
, NR_FILE_DIRTY
, nr_pages
);
5076 if (PageWriteback(page
)) {
5077 __mod_memcg_state(from
, NR_WRITEBACK
, -nr_pages
);
5078 __mod_memcg_state(to
, NR_WRITEBACK
, nr_pages
);
5082 * It is safe to change page->mem_cgroup here because the page
5083 * is referenced, charged, and isolated - we can't race with
5084 * uncharging, charging, migration, or LRU putback.
5087 /* caller should have done css_get */
5088 page
->mem_cgroup
= to
;
5089 spin_unlock_irqrestore(&from
->move_lock
, flags
);
5093 local_irq_disable();
5094 mem_cgroup_charge_statistics(to
, page
, compound
, nr_pages
);
5095 memcg_check_events(to
, page
);
5096 mem_cgroup_charge_statistics(from
, page
, compound
, -nr_pages
);
5097 memcg_check_events(from
, page
);
5106 * get_mctgt_type - get target type of moving charge
5107 * @vma: the vma the pte to be checked belongs
5108 * @addr: the address corresponding to the pte to be checked
5109 * @ptent: the pte to be checked
5110 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5113 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5114 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5115 * move charge. if @target is not NULL, the page is stored in target->page
5116 * with extra refcnt got(Callers should handle it).
5117 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5118 * target for charge migration. if @target is not NULL, the entry is stored
5120 * 3(MC_TARGET_DEVICE): like MC_TARGET_PAGE but page is MEMORY_DEVICE_PRIVATE
5121 * (so ZONE_DEVICE page and thus not on the lru).
5122 * For now we such page is charge like a regular page would be as for all
5123 * intent and purposes it is just special memory taking the place of a
5126 * See Documentations/vm/hmm.txt and include/linux/hmm.h
5128 * Called with pte lock held.
5131 static enum mc_target_type
get_mctgt_type(struct vm_area_struct
*vma
,
5132 unsigned long addr
, pte_t ptent
, union mc_target
*target
)
5134 struct page
*page
= NULL
;
5135 enum mc_target_type ret
= MC_TARGET_NONE
;
5136 swp_entry_t ent
= { .val
= 0 };
5138 if (pte_present(ptent
))
5139 page
= mc_handle_present_pte(vma
, addr
, ptent
);
5140 else if (is_swap_pte(ptent
))
5141 page
= mc_handle_swap_pte(vma
, ptent
, &ent
);
5142 else if (pte_none(ptent
))
5143 page
= mc_handle_file_pte(vma
, addr
, ptent
, &ent
);
5145 if (!page
&& !ent
.val
)
5149 * Do only loose check w/o serialization.
5150 * mem_cgroup_move_account() checks the page is valid or
5151 * not under LRU exclusion.
5153 if (page
->mem_cgroup
== mc
.from
) {
5154 ret
= MC_TARGET_PAGE
;
5155 if (is_device_private_page(page
))
5156 ret
= MC_TARGET_DEVICE
;
5158 target
->page
= page
;
5160 if (!ret
|| !target
)
5164 * There is a swap entry and a page doesn't exist or isn't charged.
5165 * But we cannot move a tail-page in a THP.
5167 if (ent
.val
&& !ret
&& (!page
|| !PageTransCompound(page
)) &&
5168 mem_cgroup_id(mc
.from
) == lookup_swap_cgroup_id(ent
)) {
5169 ret
= MC_TARGET_SWAP
;
5176 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5178 * We don't consider PMD mapped swapping or file mapped pages because THP does
5179 * not support them for now.
5180 * Caller should make sure that pmd_trans_huge(pmd) is true.
5182 static enum mc_target_type
get_mctgt_type_thp(struct vm_area_struct
*vma
,
5183 unsigned long addr
, pmd_t pmd
, union mc_target
*target
)
5185 struct page
*page
= NULL
;
5186 enum mc_target_type ret
= MC_TARGET_NONE
;
5188 if (unlikely(is_swap_pmd(pmd
))) {
5189 VM_BUG_ON(thp_migration_supported() &&
5190 !is_pmd_migration_entry(pmd
));
5193 page
= pmd_page(pmd
);
5194 VM_BUG_ON_PAGE(!page
|| !PageHead(page
), page
);
5195 if (!(mc
.flags
& MOVE_ANON
))
5197 if (page
->mem_cgroup
== mc
.from
) {
5198 ret
= MC_TARGET_PAGE
;
5201 target
->page
= page
;
5207 static inline enum mc_target_type
get_mctgt_type_thp(struct vm_area_struct
*vma
,
5208 unsigned long addr
, pmd_t pmd
, union mc_target
*target
)
5210 return MC_TARGET_NONE
;
5214 static int mem_cgroup_count_precharge_pte_range(pmd_t
*pmd
,
5215 unsigned long addr
, unsigned long end
,
5216 struct mm_walk
*walk
)
5218 struct vm_area_struct
*vma
= walk
->vma
;
5222 ptl
= pmd_trans_huge_lock(pmd
, vma
);
5225 * Note their can not be MC_TARGET_DEVICE for now as we do not
5226 * support transparent huge page with MEMORY_DEVICE_PRIVATE but
5227 * this might change.
5229 if (get_mctgt_type_thp(vma
, addr
, *pmd
, NULL
) == MC_TARGET_PAGE
)
5230 mc
.precharge
+= HPAGE_PMD_NR
;
5235 if (pmd_trans_unstable(pmd
))
5237 pte
= pte_offset_map_lock(vma
->vm_mm
, pmd
, addr
, &ptl
);
5238 for (; addr
!= end
; pte
++, addr
+= PAGE_SIZE
)
5239 if (get_mctgt_type(vma
, addr
, *pte
, NULL
))
5240 mc
.precharge
++; /* increment precharge temporarily */
5241 pte_unmap_unlock(pte
- 1, ptl
);
5247 static unsigned long mem_cgroup_count_precharge(struct mm_struct
*mm
)
5249 unsigned long precharge
;
5251 struct mm_walk mem_cgroup_count_precharge_walk
= {
5252 .pmd_entry
= mem_cgroup_count_precharge_pte_range
,
5255 down_read(&mm
->mmap_sem
);
5256 walk_page_range(0, mm
->highest_vm_end
,
5257 &mem_cgroup_count_precharge_walk
);
5258 up_read(&mm
->mmap_sem
);
5260 precharge
= mc
.precharge
;
5266 static int mem_cgroup_precharge_mc(struct mm_struct
*mm
)
5268 unsigned long precharge
= mem_cgroup_count_precharge(mm
);
5270 VM_BUG_ON(mc
.moving_task
);
5271 mc
.moving_task
= current
;
5272 return mem_cgroup_do_precharge(precharge
);
5275 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5276 static void __mem_cgroup_clear_mc(void)
5278 struct mem_cgroup
*from
= mc
.from
;
5279 struct mem_cgroup
*to
= mc
.to
;
5281 /* we must uncharge all the leftover precharges from mc.to */
5283 cancel_charge(mc
.to
, mc
.precharge
);
5287 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5288 * we must uncharge here.
5290 if (mc
.moved_charge
) {
5291 cancel_charge(mc
.from
, mc
.moved_charge
);
5292 mc
.moved_charge
= 0;
5294 /* we must fixup refcnts and charges */
5295 if (mc
.moved_swap
) {
5296 /* uncharge swap account from the old cgroup */
5297 if (!mem_cgroup_is_root(mc
.from
))
5298 page_counter_uncharge(&mc
.from
->memsw
, mc
.moved_swap
);
5300 mem_cgroup_id_put_many(mc
.from
, mc
.moved_swap
);
5303 * we charged both to->memory and to->memsw, so we
5304 * should uncharge to->memory.
5306 if (!mem_cgroup_is_root(mc
.to
))
5307 page_counter_uncharge(&mc
.to
->memory
, mc
.moved_swap
);
5309 mem_cgroup_id_get_many(mc
.to
, mc
.moved_swap
);
5310 css_put_many(&mc
.to
->css
, mc
.moved_swap
);
5314 memcg_oom_recover(from
);
5315 memcg_oom_recover(to
);
5316 wake_up_all(&mc
.waitq
);
5319 static void mem_cgroup_clear_mc(void)
5321 struct mm_struct
*mm
= mc
.mm
;
5324 * we must clear moving_task before waking up waiters at the end of
5327 mc
.moving_task
= NULL
;
5328 __mem_cgroup_clear_mc();
5329 spin_lock(&mc
.lock
);
5333 spin_unlock(&mc
.lock
);
5338 static int mem_cgroup_can_attach(struct cgroup_taskset
*tset
)
5340 struct cgroup_subsys_state
*css
;
5341 struct mem_cgroup
*memcg
= NULL
; /* unneeded init to make gcc happy */
5342 struct mem_cgroup
*from
;
5343 struct task_struct
*leader
, *p
;
5344 struct mm_struct
*mm
;
5345 unsigned long move_flags
;
5348 /* charge immigration isn't supported on the default hierarchy */
5349 if (cgroup_subsys_on_dfl(memory_cgrp_subsys
))
5353 * Multi-process migrations only happen on the default hierarchy
5354 * where charge immigration is not used. Perform charge
5355 * immigration if @tset contains a leader and whine if there are
5359 cgroup_taskset_for_each_leader(leader
, css
, tset
) {
5362 memcg
= mem_cgroup_from_css(css
);
5368 * We are now commited to this value whatever it is. Changes in this
5369 * tunable will only affect upcoming migrations, not the current one.
5370 * So we need to save it, and keep it going.
5372 move_flags
= READ_ONCE(memcg
->move_charge_at_immigrate
);
5376 from
= mem_cgroup_from_task(p
);
5378 VM_BUG_ON(from
== memcg
);
5380 mm
= get_task_mm(p
);
5383 /* We move charges only when we move a owner of the mm */
5384 if (mm
->owner
== p
) {
5387 VM_BUG_ON(mc
.precharge
);
5388 VM_BUG_ON(mc
.moved_charge
);
5389 VM_BUG_ON(mc
.moved_swap
);
5391 spin_lock(&mc
.lock
);
5395 mc
.flags
= move_flags
;
5396 spin_unlock(&mc
.lock
);
5397 /* We set mc.moving_task later */
5399 ret
= mem_cgroup_precharge_mc(mm
);
5401 mem_cgroup_clear_mc();
5408 static void mem_cgroup_cancel_attach(struct cgroup_taskset
*tset
)
5411 mem_cgroup_clear_mc();
5414 static int mem_cgroup_move_charge_pte_range(pmd_t
*pmd
,
5415 unsigned long addr
, unsigned long end
,
5416 struct mm_walk
*walk
)
5419 struct vm_area_struct
*vma
= walk
->vma
;
5422 enum mc_target_type target_type
;
5423 union mc_target target
;
5426 ptl
= pmd_trans_huge_lock(pmd
, vma
);
5428 if (mc
.precharge
< HPAGE_PMD_NR
) {
5432 target_type
= get_mctgt_type_thp(vma
, addr
, *pmd
, &target
);
5433 if (target_type
== MC_TARGET_PAGE
) {
5435 if (!isolate_lru_page(page
)) {
5436 if (!mem_cgroup_move_account(page
, true,
5438 mc
.precharge
-= HPAGE_PMD_NR
;
5439 mc
.moved_charge
+= HPAGE_PMD_NR
;
5441 putback_lru_page(page
);
5444 } else if (target_type
== MC_TARGET_DEVICE
) {
5446 if (!mem_cgroup_move_account(page
, true,
5448 mc
.precharge
-= HPAGE_PMD_NR
;
5449 mc
.moved_charge
+= HPAGE_PMD_NR
;
5457 if (pmd_trans_unstable(pmd
))
5460 pte
= pte_offset_map_lock(vma
->vm_mm
, pmd
, addr
, &ptl
);
5461 for (; addr
!= end
; addr
+= PAGE_SIZE
) {
5462 pte_t ptent
= *(pte
++);
5463 bool device
= false;
5469 switch (get_mctgt_type(vma
, addr
, ptent
, &target
)) {
5470 case MC_TARGET_DEVICE
:
5473 case MC_TARGET_PAGE
:
5476 * We can have a part of the split pmd here. Moving it
5477 * can be done but it would be too convoluted so simply
5478 * ignore such a partial THP and keep it in original
5479 * memcg. There should be somebody mapping the head.
5481 if (PageTransCompound(page
))
5483 if (!device
&& isolate_lru_page(page
))
5485 if (!mem_cgroup_move_account(page
, false,
5488 /* we uncharge from mc.from later. */
5492 putback_lru_page(page
);
5493 put
: /* get_mctgt_type() gets the page */
5496 case MC_TARGET_SWAP
:
5498 if (!mem_cgroup_move_swap_account(ent
, mc
.from
, mc
.to
)) {
5500 /* we fixup refcnts and charges later. */
5508 pte_unmap_unlock(pte
- 1, ptl
);
5513 * We have consumed all precharges we got in can_attach().
5514 * We try charge one by one, but don't do any additional
5515 * charges to mc.to if we have failed in charge once in attach()
5518 ret
= mem_cgroup_do_precharge(1);
5526 static void mem_cgroup_move_charge(void)
5528 struct mm_walk mem_cgroup_move_charge_walk
= {
5529 .pmd_entry
= mem_cgroup_move_charge_pte_range
,
5533 lru_add_drain_all();
5535 * Signal lock_page_memcg() to take the memcg's move_lock
5536 * while we're moving its pages to another memcg. Then wait
5537 * for already started RCU-only updates to finish.
5539 atomic_inc(&mc
.from
->moving_account
);
5542 if (unlikely(!down_read_trylock(&mc
.mm
->mmap_sem
))) {
5544 * Someone who are holding the mmap_sem might be waiting in
5545 * waitq. So we cancel all extra charges, wake up all waiters,
5546 * and retry. Because we cancel precharges, we might not be able
5547 * to move enough charges, but moving charge is a best-effort
5548 * feature anyway, so it wouldn't be a big problem.
5550 __mem_cgroup_clear_mc();
5555 * When we have consumed all precharges and failed in doing
5556 * additional charge, the page walk just aborts.
5558 walk_page_range(0, mc
.mm
->highest_vm_end
, &mem_cgroup_move_charge_walk
);
5560 up_read(&mc
.mm
->mmap_sem
);
5561 atomic_dec(&mc
.from
->moving_account
);
5564 static void mem_cgroup_move_task(void)
5567 mem_cgroup_move_charge();
5568 mem_cgroup_clear_mc();
5571 #else /* !CONFIG_MMU */
5572 static int mem_cgroup_can_attach(struct cgroup_taskset
*tset
)
5576 static void mem_cgroup_cancel_attach(struct cgroup_taskset
*tset
)
5579 static void mem_cgroup_move_task(void)
5585 * Cgroup retains root cgroups across [un]mount cycles making it necessary
5586 * to verify whether we're attached to the default hierarchy on each mount
5589 static void mem_cgroup_bind(struct cgroup_subsys_state
*root_css
)
5592 * use_hierarchy is forced on the default hierarchy. cgroup core
5593 * guarantees that @root doesn't have any children, so turning it
5594 * on for the root memcg is enough.
5596 if (cgroup_subsys_on_dfl(memory_cgrp_subsys
))
5597 root_mem_cgroup
->use_hierarchy
= true;
5599 root_mem_cgroup
->use_hierarchy
= false;
5602 static int seq_puts_memcg_tunable(struct seq_file
*m
, unsigned long value
)
5604 if (value
== PAGE_COUNTER_MAX
)
5605 seq_puts(m
, "max\n");
5607 seq_printf(m
, "%llu\n", (u64
)value
* PAGE_SIZE
);
5612 static u64
memory_current_read(struct cgroup_subsys_state
*css
,
5615 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
5617 return (u64
)page_counter_read(&memcg
->memory
) * PAGE_SIZE
;
5620 static int memory_min_show(struct seq_file
*m
, void *v
)
5622 return seq_puts_memcg_tunable(m
,
5623 READ_ONCE(mem_cgroup_from_seq(m
)->memory
.min
));
5626 static ssize_t
memory_min_write(struct kernfs_open_file
*of
,
5627 char *buf
, size_t nbytes
, loff_t off
)
5629 struct mem_cgroup
*memcg
= mem_cgroup_from_css(of_css(of
));
5633 buf
= strstrip(buf
);
5634 err
= page_counter_memparse(buf
, "max", &min
);
5638 page_counter_set_min(&memcg
->memory
, min
);
5643 static int memory_low_show(struct seq_file
*m
, void *v
)
5645 return seq_puts_memcg_tunable(m
,
5646 READ_ONCE(mem_cgroup_from_seq(m
)->memory
.low
));
5649 static ssize_t
memory_low_write(struct kernfs_open_file
*of
,
5650 char *buf
, size_t nbytes
, loff_t off
)
5652 struct mem_cgroup
*memcg
= mem_cgroup_from_css(of_css(of
));
5656 buf
= strstrip(buf
);
5657 err
= page_counter_memparse(buf
, "max", &low
);
5661 page_counter_set_low(&memcg
->memory
, low
);
5666 static int memory_high_show(struct seq_file
*m
, void *v
)
5668 return seq_puts_memcg_tunable(m
, READ_ONCE(mem_cgroup_from_seq(m
)->high
));
5671 static ssize_t
memory_high_write(struct kernfs_open_file
*of
,
5672 char *buf
, size_t nbytes
, loff_t off
)
5674 struct mem_cgroup
*memcg
= mem_cgroup_from_css(of_css(of
));
5675 unsigned long nr_pages
;
5679 buf
= strstrip(buf
);
5680 err
= page_counter_memparse(buf
, "max", &high
);
5686 nr_pages
= page_counter_read(&memcg
->memory
);
5687 if (nr_pages
> high
)
5688 try_to_free_mem_cgroup_pages(memcg
, nr_pages
- high
,
5691 memcg_wb_domain_size_changed(memcg
);
5695 static int memory_max_show(struct seq_file
*m
, void *v
)
5697 return seq_puts_memcg_tunable(m
,
5698 READ_ONCE(mem_cgroup_from_seq(m
)->memory
.max
));
5701 static ssize_t
memory_max_write(struct kernfs_open_file
*of
,
5702 char *buf
, size_t nbytes
, loff_t off
)
5704 struct mem_cgroup
*memcg
= mem_cgroup_from_css(of_css(of
));
5705 unsigned int nr_reclaims
= MEM_CGROUP_RECLAIM_RETRIES
;
5706 bool drained
= false;
5710 buf
= strstrip(buf
);
5711 err
= page_counter_memparse(buf
, "max", &max
);
5715 xchg(&memcg
->memory
.max
, max
);
5718 unsigned long nr_pages
= page_counter_read(&memcg
->memory
);
5720 if (nr_pages
<= max
)
5723 if (signal_pending(current
)) {
5729 drain_all_stock(memcg
);
5735 if (!try_to_free_mem_cgroup_pages(memcg
, nr_pages
- max
,
5741 memcg_memory_event(memcg
, MEMCG_OOM
);
5742 if (!mem_cgroup_out_of_memory(memcg
, GFP_KERNEL
, 0))
5746 memcg_wb_domain_size_changed(memcg
);
5750 static void __memory_events_show(struct seq_file
*m
, atomic_long_t
*events
)
5752 seq_printf(m
, "low %lu\n", atomic_long_read(&events
[MEMCG_LOW
]));
5753 seq_printf(m
, "high %lu\n", atomic_long_read(&events
[MEMCG_HIGH
]));
5754 seq_printf(m
, "max %lu\n", atomic_long_read(&events
[MEMCG_MAX
]));
5755 seq_printf(m
, "oom %lu\n", atomic_long_read(&events
[MEMCG_OOM
]));
5756 seq_printf(m
, "oom_kill %lu\n",
5757 atomic_long_read(&events
[MEMCG_OOM_KILL
]));
5760 static int memory_events_show(struct seq_file
*m
, void *v
)
5762 struct mem_cgroup
*memcg
= mem_cgroup_from_seq(m
);
5764 __memory_events_show(m
, memcg
->memory_events
);
5768 static int memory_events_local_show(struct seq_file
*m
, void *v
)
5770 struct mem_cgroup
*memcg
= mem_cgroup_from_seq(m
);
5772 __memory_events_show(m
, memcg
->memory_events_local
);
5776 static int memory_stat_show(struct seq_file
*m
, void *v
)
5778 struct mem_cgroup
*memcg
= mem_cgroup_from_seq(m
);
5781 buf
= memory_stat_format(memcg
);
5789 static int memory_oom_group_show(struct seq_file
*m
, void *v
)
5791 struct mem_cgroup
*memcg
= mem_cgroup_from_seq(m
);
5793 seq_printf(m
, "%d\n", memcg
->oom_group
);
5798 static ssize_t
memory_oom_group_write(struct kernfs_open_file
*of
,
5799 char *buf
, size_t nbytes
, loff_t off
)
5801 struct mem_cgroup
*memcg
= mem_cgroup_from_css(of_css(of
));
5804 buf
= strstrip(buf
);
5808 ret
= kstrtoint(buf
, 0, &oom_group
);
5812 if (oom_group
!= 0 && oom_group
!= 1)
5815 memcg
->oom_group
= oom_group
;
5820 static struct cftype memory_files
[] = {
5823 .flags
= CFTYPE_NOT_ON_ROOT
,
5824 .read_u64
= memory_current_read
,
5828 .flags
= CFTYPE_NOT_ON_ROOT
,
5829 .seq_show
= memory_min_show
,
5830 .write
= memory_min_write
,
5834 .flags
= CFTYPE_NOT_ON_ROOT
,
5835 .seq_show
= memory_low_show
,
5836 .write
= memory_low_write
,
5840 .flags
= CFTYPE_NOT_ON_ROOT
,
5841 .seq_show
= memory_high_show
,
5842 .write
= memory_high_write
,
5846 .flags
= CFTYPE_NOT_ON_ROOT
,
5847 .seq_show
= memory_max_show
,
5848 .write
= memory_max_write
,
5852 .flags
= CFTYPE_NOT_ON_ROOT
,
5853 .file_offset
= offsetof(struct mem_cgroup
, events_file
),
5854 .seq_show
= memory_events_show
,
5857 .name
= "events.local",
5858 .flags
= CFTYPE_NOT_ON_ROOT
,
5859 .file_offset
= offsetof(struct mem_cgroup
, events_local_file
),
5860 .seq_show
= memory_events_local_show
,
5864 .flags
= CFTYPE_NOT_ON_ROOT
,
5865 .seq_show
= memory_stat_show
,
5868 .name
= "oom.group",
5869 .flags
= CFTYPE_NOT_ON_ROOT
| CFTYPE_NS_DELEGATABLE
,
5870 .seq_show
= memory_oom_group_show
,
5871 .write
= memory_oom_group_write
,
5876 struct cgroup_subsys memory_cgrp_subsys
= {
5877 .css_alloc
= mem_cgroup_css_alloc
,
5878 .css_online
= mem_cgroup_css_online
,
5879 .css_offline
= mem_cgroup_css_offline
,
5880 .css_released
= mem_cgroup_css_released
,
5881 .css_free
= mem_cgroup_css_free
,
5882 .css_reset
= mem_cgroup_css_reset
,
5883 .can_attach
= mem_cgroup_can_attach
,
5884 .cancel_attach
= mem_cgroup_cancel_attach
,
5885 .post_attach
= mem_cgroup_move_task
,
5886 .bind
= mem_cgroup_bind
,
5887 .dfl_cftypes
= memory_files
,
5888 .legacy_cftypes
= mem_cgroup_legacy_files
,
5893 * mem_cgroup_protected - check if memory consumption is in the normal range
5894 * @root: the top ancestor of the sub-tree being checked
5895 * @memcg: the memory cgroup to check
5897 * WARNING: This function is not stateless! It can only be used as part
5898 * of a top-down tree iteration, not for isolated queries.
5900 * Returns one of the following:
5901 * MEMCG_PROT_NONE: cgroup memory is not protected
5902 * MEMCG_PROT_LOW: cgroup memory is protected as long there is
5903 * an unprotected supply of reclaimable memory from other cgroups.
5904 * MEMCG_PROT_MIN: cgroup memory is protected
5906 * @root is exclusive; it is never protected when looked at directly
5908 * To provide a proper hierarchical behavior, effective memory.min/low values
5909 * are used. Below is the description of how effective memory.low is calculated.
5910 * Effective memory.min values is calculated in the same way.
5912 * Effective memory.low is always equal or less than the original memory.low.
5913 * If there is no memory.low overcommittment (which is always true for
5914 * top-level memory cgroups), these two values are equal.
5915 * Otherwise, it's a part of parent's effective memory.low,
5916 * calculated as a cgroup's memory.low usage divided by sum of sibling's
5917 * memory.low usages, where memory.low usage is the size of actually
5921 * elow = min( memory.low, parent->elow * ------------------ ),
5922 * siblings_low_usage
5924 * | memory.current, if memory.current < memory.low
5929 * Such definition of the effective memory.low provides the expected
5930 * hierarchical behavior: parent's memory.low value is limiting
5931 * children, unprotected memory is reclaimed first and cgroups,
5932 * which are not using their guarantee do not affect actual memory
5935 * For example, if there are memcgs A, A/B, A/C, A/D and A/E:
5937 * A A/memory.low = 2G, A/memory.current = 6G
5939 * BC DE B/memory.low = 3G B/memory.current = 2G
5940 * C/memory.low = 1G C/memory.current = 2G
5941 * D/memory.low = 0 D/memory.current = 2G
5942 * E/memory.low = 10G E/memory.current = 0
5944 * and the memory pressure is applied, the following memory distribution
5945 * is expected (approximately):
5947 * A/memory.current = 2G
5949 * B/memory.current = 1.3G
5950 * C/memory.current = 0.6G
5951 * D/memory.current = 0
5952 * E/memory.current = 0
5954 * These calculations require constant tracking of the actual low usages
5955 * (see propagate_protected_usage()), as well as recursive calculation of
5956 * effective memory.low values. But as we do call mem_cgroup_protected()
5957 * path for each memory cgroup top-down from the reclaim,
5958 * it's possible to optimize this part, and save calculated elow
5959 * for next usage. This part is intentionally racy, but it's ok,
5960 * as memory.low is a best-effort mechanism.
5962 enum mem_cgroup_protection
mem_cgroup_protected(struct mem_cgroup
*root
,
5963 struct mem_cgroup
*memcg
)
5965 struct mem_cgroup
*parent
;
5966 unsigned long emin
, parent_emin
;
5967 unsigned long elow
, parent_elow
;
5968 unsigned long usage
;
5970 if (mem_cgroup_disabled())
5971 return MEMCG_PROT_NONE
;
5974 root
= root_mem_cgroup
;
5976 return MEMCG_PROT_NONE
;
5978 usage
= page_counter_read(&memcg
->memory
);
5980 return MEMCG_PROT_NONE
;
5982 emin
= memcg
->memory
.min
;
5983 elow
= memcg
->memory
.low
;
5985 parent
= parent_mem_cgroup(memcg
);
5986 /* No parent means a non-hierarchical mode on v1 memcg */
5988 return MEMCG_PROT_NONE
;
5993 parent_emin
= READ_ONCE(parent
->memory
.emin
);
5994 emin
= min(emin
, parent_emin
);
5995 if (emin
&& parent_emin
) {
5996 unsigned long min_usage
, siblings_min_usage
;
5998 min_usage
= min(usage
, memcg
->memory
.min
);
5999 siblings_min_usage
= atomic_long_read(
6000 &parent
->memory
.children_min_usage
);
6002 if (min_usage
&& siblings_min_usage
)
6003 emin
= min(emin
, parent_emin
* min_usage
/
6004 siblings_min_usage
);
6007 parent_elow
= READ_ONCE(parent
->memory
.elow
);
6008 elow
= min(elow
, parent_elow
);
6009 if (elow
&& parent_elow
) {
6010 unsigned long low_usage
, siblings_low_usage
;
6012 low_usage
= min(usage
, memcg
->memory
.low
);
6013 siblings_low_usage
= atomic_long_read(
6014 &parent
->memory
.children_low_usage
);
6016 if (low_usage
&& siblings_low_usage
)
6017 elow
= min(elow
, parent_elow
* low_usage
/
6018 siblings_low_usage
);
6022 memcg
->memory
.emin
= emin
;
6023 memcg
->memory
.elow
= elow
;
6026 return MEMCG_PROT_MIN
;
6027 else if (usage
<= elow
)
6028 return MEMCG_PROT_LOW
;
6030 return MEMCG_PROT_NONE
;
6034 * mem_cgroup_try_charge - try charging a page
6035 * @page: page to charge
6036 * @mm: mm context of the victim
6037 * @gfp_mask: reclaim mode
6038 * @memcgp: charged memcg return
6039 * @compound: charge the page as compound or small page
6041 * Try to charge @page to the memcg that @mm belongs to, reclaiming
6042 * pages according to @gfp_mask if necessary.
6044 * Returns 0 on success, with *@memcgp pointing to the charged memcg.
6045 * Otherwise, an error code is returned.
6047 * After page->mapping has been set up, the caller must finalize the
6048 * charge with mem_cgroup_commit_charge(). Or abort the transaction
6049 * with mem_cgroup_cancel_charge() in case page instantiation fails.
6051 int mem_cgroup_try_charge(struct page
*page
, struct mm_struct
*mm
,
6052 gfp_t gfp_mask
, struct mem_cgroup
**memcgp
,
6055 struct mem_cgroup
*memcg
= NULL
;
6056 unsigned int nr_pages
= compound
? hpage_nr_pages(page
) : 1;
6059 if (mem_cgroup_disabled())
6062 if (PageSwapCache(page
)) {
6064 * Every swap fault against a single page tries to charge the
6065 * page, bail as early as possible. shmem_unuse() encounters
6066 * already charged pages, too. The USED bit is protected by
6067 * the page lock, which serializes swap cache removal, which
6068 * in turn serializes uncharging.
6070 VM_BUG_ON_PAGE(!PageLocked(page
), page
);
6071 if (compound_head(page
)->mem_cgroup
)
6074 if (do_swap_account
) {
6075 swp_entry_t ent
= { .val
= page_private(page
), };
6076 unsigned short id
= lookup_swap_cgroup_id(ent
);
6079 memcg
= mem_cgroup_from_id(id
);
6080 if (memcg
&& !css_tryget_online(&memcg
->css
))
6087 memcg
= get_mem_cgroup_from_mm(mm
);
6089 ret
= try_charge(memcg
, gfp_mask
, nr_pages
);
6091 css_put(&memcg
->css
);
6097 int mem_cgroup_try_charge_delay(struct page
*page
, struct mm_struct
*mm
,
6098 gfp_t gfp_mask
, struct mem_cgroup
**memcgp
,
6101 struct mem_cgroup
*memcg
;
6104 ret
= mem_cgroup_try_charge(page
, mm
, gfp_mask
, memcgp
, compound
);
6106 mem_cgroup_throttle_swaprate(memcg
, page_to_nid(page
), gfp_mask
);
6111 * mem_cgroup_commit_charge - commit a page charge
6112 * @page: page to charge
6113 * @memcg: memcg to charge the page to
6114 * @lrucare: page might be on LRU already
6115 * @compound: charge the page as compound or small page
6117 * Finalize a charge transaction started by mem_cgroup_try_charge(),
6118 * after page->mapping has been set up. This must happen atomically
6119 * as part of the page instantiation, i.e. under the page table lock
6120 * for anonymous pages, under the page lock for page and swap cache.
6122 * In addition, the page must not be on the LRU during the commit, to
6123 * prevent racing with task migration. If it might be, use @lrucare.
6125 * Use mem_cgroup_cancel_charge() to cancel the transaction instead.
6127 void mem_cgroup_commit_charge(struct page
*page
, struct mem_cgroup
*memcg
,
6128 bool lrucare
, bool compound
)
6130 unsigned int nr_pages
= compound
? hpage_nr_pages(page
) : 1;
6132 VM_BUG_ON_PAGE(!page
->mapping
, page
);
6133 VM_BUG_ON_PAGE(PageLRU(page
) && !lrucare
, page
);
6135 if (mem_cgroup_disabled())
6138 * Swap faults will attempt to charge the same page multiple
6139 * times. But reuse_swap_page() might have removed the page
6140 * from swapcache already, so we can't check PageSwapCache().
6145 commit_charge(page
, memcg
, lrucare
);
6147 local_irq_disable();
6148 mem_cgroup_charge_statistics(memcg
, page
, compound
, nr_pages
);
6149 memcg_check_events(memcg
, page
);
6152 if (do_memsw_account() && PageSwapCache(page
)) {
6153 swp_entry_t entry
= { .val
= page_private(page
) };
6155 * The swap entry might not get freed for a long time,
6156 * let's not wait for it. The page already received a
6157 * memory+swap charge, drop the swap entry duplicate.
6159 mem_cgroup_uncharge_swap(entry
, nr_pages
);
6164 * mem_cgroup_cancel_charge - cancel a page charge
6165 * @page: page to charge
6166 * @memcg: memcg to charge the page to
6167 * @compound: charge the page as compound or small page
6169 * Cancel a charge transaction started by mem_cgroup_try_charge().
6171 void mem_cgroup_cancel_charge(struct page
*page
, struct mem_cgroup
*memcg
,
6174 unsigned int nr_pages
= compound
? hpage_nr_pages(page
) : 1;
6176 if (mem_cgroup_disabled())
6179 * Swap faults will attempt to charge the same page multiple
6180 * times. But reuse_swap_page() might have removed the page
6181 * from swapcache already, so we can't check PageSwapCache().
6186 cancel_charge(memcg
, nr_pages
);
6189 struct uncharge_gather
{
6190 struct mem_cgroup
*memcg
;
6191 unsigned long pgpgout
;
6192 unsigned long nr_anon
;
6193 unsigned long nr_file
;
6194 unsigned long nr_kmem
;
6195 unsigned long nr_huge
;
6196 unsigned long nr_shmem
;
6197 struct page
*dummy_page
;
6200 static inline void uncharge_gather_clear(struct uncharge_gather
*ug
)
6202 memset(ug
, 0, sizeof(*ug
));
6205 static void uncharge_batch(const struct uncharge_gather
*ug
)
6207 unsigned long nr_pages
= ug
->nr_anon
+ ug
->nr_file
+ ug
->nr_kmem
;
6208 unsigned long flags
;
6210 if (!mem_cgroup_is_root(ug
->memcg
)) {
6211 page_counter_uncharge(&ug
->memcg
->memory
, nr_pages
);
6212 if (do_memsw_account())
6213 page_counter_uncharge(&ug
->memcg
->memsw
, nr_pages
);
6214 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys
) && ug
->nr_kmem
)
6215 page_counter_uncharge(&ug
->memcg
->kmem
, ug
->nr_kmem
);
6216 memcg_oom_recover(ug
->memcg
);
6219 local_irq_save(flags
);
6220 __mod_memcg_state(ug
->memcg
, MEMCG_RSS
, -ug
->nr_anon
);
6221 __mod_memcg_state(ug
->memcg
, MEMCG_CACHE
, -ug
->nr_file
);
6222 __mod_memcg_state(ug
->memcg
, MEMCG_RSS_HUGE
, -ug
->nr_huge
);
6223 __mod_memcg_state(ug
->memcg
, NR_SHMEM
, -ug
->nr_shmem
);
6224 __count_memcg_events(ug
->memcg
, PGPGOUT
, ug
->pgpgout
);
6225 __this_cpu_add(ug
->memcg
->vmstats_percpu
->nr_page_events
, nr_pages
);
6226 memcg_check_events(ug
->memcg
, ug
->dummy_page
);
6227 local_irq_restore(flags
);
6229 if (!mem_cgroup_is_root(ug
->memcg
))
6230 css_put_many(&ug
->memcg
->css
, nr_pages
);
6233 static void uncharge_page(struct page
*page
, struct uncharge_gather
*ug
)
6235 VM_BUG_ON_PAGE(PageLRU(page
), page
);
6236 VM_BUG_ON_PAGE(page_count(page
) && !is_zone_device_page(page
) &&
6237 !PageHWPoison(page
) , page
);
6239 if (!page
->mem_cgroup
)
6243 * Nobody should be changing or seriously looking at
6244 * page->mem_cgroup at this point, we have fully
6245 * exclusive access to the page.
6248 if (ug
->memcg
!= page
->mem_cgroup
) {
6251 uncharge_gather_clear(ug
);
6253 ug
->memcg
= page
->mem_cgroup
;
6256 if (!PageKmemcg(page
)) {
6257 unsigned int nr_pages
= 1;
6259 if (PageTransHuge(page
)) {
6260 nr_pages
<<= compound_order(page
);
6261 ug
->nr_huge
+= nr_pages
;
6264 ug
->nr_anon
+= nr_pages
;
6266 ug
->nr_file
+= nr_pages
;
6267 if (PageSwapBacked(page
))
6268 ug
->nr_shmem
+= nr_pages
;
6272 ug
->nr_kmem
+= 1 << compound_order(page
);
6273 __ClearPageKmemcg(page
);
6276 ug
->dummy_page
= page
;
6277 page
->mem_cgroup
= NULL
;
6280 static void uncharge_list(struct list_head
*page_list
)
6282 struct uncharge_gather ug
;
6283 struct list_head
*next
;
6285 uncharge_gather_clear(&ug
);
6288 * Note that the list can be a single page->lru; hence the
6289 * do-while loop instead of a simple list_for_each_entry().
6291 next
= page_list
->next
;
6295 page
= list_entry(next
, struct page
, lru
);
6296 next
= page
->lru
.next
;
6298 uncharge_page(page
, &ug
);
6299 } while (next
!= page_list
);
6302 uncharge_batch(&ug
);
6306 * mem_cgroup_uncharge - uncharge a page
6307 * @page: page to uncharge
6309 * Uncharge a page previously charged with mem_cgroup_try_charge() and
6310 * mem_cgroup_commit_charge().
6312 void mem_cgroup_uncharge(struct page
*page
)
6314 struct uncharge_gather ug
;
6316 if (mem_cgroup_disabled())
6319 /* Don't touch page->lru of any random page, pre-check: */
6320 if (!page
->mem_cgroup
)
6323 uncharge_gather_clear(&ug
);
6324 uncharge_page(page
, &ug
);
6325 uncharge_batch(&ug
);
6329 * mem_cgroup_uncharge_list - uncharge a list of page
6330 * @page_list: list of pages to uncharge
6332 * Uncharge a list of pages previously charged with
6333 * mem_cgroup_try_charge() and mem_cgroup_commit_charge().
6335 void mem_cgroup_uncharge_list(struct list_head
*page_list
)
6337 if (mem_cgroup_disabled())
6340 if (!list_empty(page_list
))
6341 uncharge_list(page_list
);
6345 * mem_cgroup_migrate - charge a page's replacement
6346 * @oldpage: currently circulating page
6347 * @newpage: replacement page
6349 * Charge @newpage as a replacement page for @oldpage. @oldpage will
6350 * be uncharged upon free.
6352 * Both pages must be locked, @newpage->mapping must be set up.
6354 void mem_cgroup_migrate(struct page
*oldpage
, struct page
*newpage
)
6356 struct mem_cgroup
*memcg
;
6357 unsigned int nr_pages
;
6359 unsigned long flags
;
6361 VM_BUG_ON_PAGE(!PageLocked(oldpage
), oldpage
);
6362 VM_BUG_ON_PAGE(!PageLocked(newpage
), newpage
);
6363 VM_BUG_ON_PAGE(PageAnon(oldpage
) != PageAnon(newpage
), newpage
);
6364 VM_BUG_ON_PAGE(PageTransHuge(oldpage
) != PageTransHuge(newpage
),
6367 if (mem_cgroup_disabled())
6370 /* Page cache replacement: new page already charged? */
6371 if (newpage
->mem_cgroup
)
6374 /* Swapcache readahead pages can get replaced before being charged */
6375 memcg
= oldpage
->mem_cgroup
;
6379 /* Force-charge the new page. The old one will be freed soon */
6380 compound
= PageTransHuge(newpage
);
6381 nr_pages
= compound
? hpage_nr_pages(newpage
) : 1;
6383 page_counter_charge(&memcg
->memory
, nr_pages
);
6384 if (do_memsw_account())
6385 page_counter_charge(&memcg
->memsw
, nr_pages
);
6386 css_get_many(&memcg
->css
, nr_pages
);
6388 commit_charge(newpage
, memcg
, false);
6390 local_irq_save(flags
);
6391 mem_cgroup_charge_statistics(memcg
, newpage
, compound
, nr_pages
);
6392 memcg_check_events(memcg
, newpage
);
6393 local_irq_restore(flags
);
6396 DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key
);
6397 EXPORT_SYMBOL(memcg_sockets_enabled_key
);
6399 void mem_cgroup_sk_alloc(struct sock
*sk
)
6401 struct mem_cgroup
*memcg
;
6403 if (!mem_cgroup_sockets_enabled
)
6407 * Socket cloning can throw us here with sk_memcg already
6408 * filled. It won't however, necessarily happen from
6409 * process context. So the test for root memcg given
6410 * the current task's memcg won't help us in this case.
6412 * Respecting the original socket's memcg is a better
6413 * decision in this case.
6416 css_get(&sk
->sk_memcg
->css
);
6421 memcg
= mem_cgroup_from_task(current
);
6422 if (memcg
== root_mem_cgroup
)
6424 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys
) && !memcg
->tcpmem_active
)
6426 if (css_tryget_online(&memcg
->css
))
6427 sk
->sk_memcg
= memcg
;
6432 void mem_cgroup_sk_free(struct sock
*sk
)
6435 css_put(&sk
->sk_memcg
->css
);
6439 * mem_cgroup_charge_skmem - charge socket memory
6440 * @memcg: memcg to charge
6441 * @nr_pages: number of pages to charge
6443 * Charges @nr_pages to @memcg. Returns %true if the charge fit within
6444 * @memcg's configured limit, %false if the charge had to be forced.
6446 bool mem_cgroup_charge_skmem(struct mem_cgroup
*memcg
, unsigned int nr_pages
)
6448 gfp_t gfp_mask
= GFP_KERNEL
;
6450 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys
)) {
6451 struct page_counter
*fail
;
6453 if (page_counter_try_charge(&memcg
->tcpmem
, nr_pages
, &fail
)) {
6454 memcg
->tcpmem_pressure
= 0;
6457 page_counter_charge(&memcg
->tcpmem
, nr_pages
);
6458 memcg
->tcpmem_pressure
= 1;
6462 /* Don't block in the packet receive path */
6464 gfp_mask
= GFP_NOWAIT
;
6466 mod_memcg_state(memcg
, MEMCG_SOCK
, nr_pages
);
6468 if (try_charge(memcg
, gfp_mask
, nr_pages
) == 0)
6471 try_charge(memcg
, gfp_mask
|__GFP_NOFAIL
, nr_pages
);
6476 * mem_cgroup_uncharge_skmem - uncharge socket memory
6477 * @memcg: memcg to uncharge
6478 * @nr_pages: number of pages to uncharge
6480 void mem_cgroup_uncharge_skmem(struct mem_cgroup
*memcg
, unsigned int nr_pages
)
6482 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys
)) {
6483 page_counter_uncharge(&memcg
->tcpmem
, nr_pages
);
6487 mod_memcg_state(memcg
, MEMCG_SOCK
, -nr_pages
);
6489 refill_stock(memcg
, nr_pages
);
6492 static int __init
cgroup_memory(char *s
)
6496 while ((token
= strsep(&s
, ",")) != NULL
) {
6499 if (!strcmp(token
, "nosocket"))
6500 cgroup_memory_nosocket
= true;
6501 if (!strcmp(token
, "nokmem"))
6502 cgroup_memory_nokmem
= true;
6506 __setup("cgroup.memory=", cgroup_memory
);
6509 * subsys_initcall() for memory controller.
6511 * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
6512 * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
6513 * basically everything that doesn't depend on a specific mem_cgroup structure
6514 * should be initialized from here.
6516 static int __init
mem_cgroup_init(void)
6520 #ifdef CONFIG_MEMCG_KMEM
6522 * Kmem cache creation is mostly done with the slab_mutex held,
6523 * so use a workqueue with limited concurrency to avoid stalling
6524 * all worker threads in case lots of cgroups are created and
6525 * destroyed simultaneously.
6527 memcg_kmem_cache_wq
= alloc_workqueue("memcg_kmem_cache", 0, 1);
6528 BUG_ON(!memcg_kmem_cache_wq
);
6531 cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD
, "mm/memctrl:dead", NULL
,
6532 memcg_hotplug_cpu_dead
);
6534 for_each_possible_cpu(cpu
)
6535 INIT_WORK(&per_cpu_ptr(&memcg_stock
, cpu
)->work
,
6538 for_each_node(node
) {
6539 struct mem_cgroup_tree_per_node
*rtpn
;
6541 rtpn
= kzalloc_node(sizeof(*rtpn
), GFP_KERNEL
,
6542 node_online(node
) ? node
: NUMA_NO_NODE
);
6544 rtpn
->rb_root
= RB_ROOT
;
6545 rtpn
->rb_rightmost
= NULL
;
6546 spin_lock_init(&rtpn
->lock
);
6547 soft_limit_tree
.rb_tree_per_node
[node
] = rtpn
;
6552 subsys_initcall(mem_cgroup_init
);
6554 #ifdef CONFIG_MEMCG_SWAP
6555 static struct mem_cgroup
*mem_cgroup_id_get_online(struct mem_cgroup
*memcg
)
6557 while (!refcount_inc_not_zero(&memcg
->id
.ref
)) {
6559 * The root cgroup cannot be destroyed, so it's refcount must
6562 if (WARN_ON_ONCE(memcg
== root_mem_cgroup
)) {
6566 memcg
= parent_mem_cgroup(memcg
);
6568 memcg
= root_mem_cgroup
;
6574 * mem_cgroup_swapout - transfer a memsw charge to swap
6575 * @page: page whose memsw charge to transfer
6576 * @entry: swap entry to move the charge to
6578 * Transfer the memsw charge of @page to @entry.
6580 void mem_cgroup_swapout(struct page
*page
, swp_entry_t entry
)
6582 struct mem_cgroup
*memcg
, *swap_memcg
;
6583 unsigned int nr_entries
;
6584 unsigned short oldid
;
6586 VM_BUG_ON_PAGE(PageLRU(page
), page
);
6587 VM_BUG_ON_PAGE(page_count(page
), page
);
6589 if (!do_memsw_account())
6592 memcg
= page
->mem_cgroup
;
6594 /* Readahead page, never charged */
6599 * In case the memcg owning these pages has been offlined and doesn't
6600 * have an ID allocated to it anymore, charge the closest online
6601 * ancestor for the swap instead and transfer the memory+swap charge.
6603 swap_memcg
= mem_cgroup_id_get_online(memcg
);
6604 nr_entries
= hpage_nr_pages(page
);
6605 /* Get references for the tail pages, too */
6607 mem_cgroup_id_get_many(swap_memcg
, nr_entries
- 1);
6608 oldid
= swap_cgroup_record(entry
, mem_cgroup_id(swap_memcg
),
6610 VM_BUG_ON_PAGE(oldid
, page
);
6611 mod_memcg_state(swap_memcg
, MEMCG_SWAP
, nr_entries
);
6613 page
->mem_cgroup
= NULL
;
6615 if (!mem_cgroup_is_root(memcg
))
6616 page_counter_uncharge(&memcg
->memory
, nr_entries
);
6618 if (memcg
!= swap_memcg
) {
6619 if (!mem_cgroup_is_root(swap_memcg
))
6620 page_counter_charge(&swap_memcg
->memsw
, nr_entries
);
6621 page_counter_uncharge(&memcg
->memsw
, nr_entries
);
6625 * Interrupts should be disabled here because the caller holds the
6626 * i_pages lock which is taken with interrupts-off. It is
6627 * important here to have the interrupts disabled because it is the
6628 * only synchronisation we have for updating the per-CPU variables.
6630 VM_BUG_ON(!irqs_disabled());
6631 mem_cgroup_charge_statistics(memcg
, page
, PageTransHuge(page
),
6633 memcg_check_events(memcg
, page
);
6635 if (!mem_cgroup_is_root(memcg
))
6636 css_put_many(&memcg
->css
, nr_entries
);
6640 * mem_cgroup_try_charge_swap - try charging swap space for a page
6641 * @page: page being added to swap
6642 * @entry: swap entry to charge
6644 * Try to charge @page's memcg for the swap space at @entry.
6646 * Returns 0 on success, -ENOMEM on failure.
6648 int mem_cgroup_try_charge_swap(struct page
*page
, swp_entry_t entry
)
6650 unsigned int nr_pages
= hpage_nr_pages(page
);
6651 struct page_counter
*counter
;
6652 struct mem_cgroup
*memcg
;
6653 unsigned short oldid
;
6655 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys
) || !do_swap_account
)
6658 memcg
= page
->mem_cgroup
;
6660 /* Readahead page, never charged */
6665 memcg_memory_event(memcg
, MEMCG_SWAP_FAIL
);
6669 memcg
= mem_cgroup_id_get_online(memcg
);
6671 if (!mem_cgroup_is_root(memcg
) &&
6672 !page_counter_try_charge(&memcg
->swap
, nr_pages
, &counter
)) {
6673 memcg_memory_event(memcg
, MEMCG_SWAP_MAX
);
6674 memcg_memory_event(memcg
, MEMCG_SWAP_FAIL
);
6675 mem_cgroup_id_put(memcg
);
6679 /* Get references for the tail pages, too */
6681 mem_cgroup_id_get_many(memcg
, nr_pages
- 1);
6682 oldid
= swap_cgroup_record(entry
, mem_cgroup_id(memcg
), nr_pages
);
6683 VM_BUG_ON_PAGE(oldid
, page
);
6684 mod_memcg_state(memcg
, MEMCG_SWAP
, nr_pages
);
6690 * mem_cgroup_uncharge_swap - uncharge swap space
6691 * @entry: swap entry to uncharge
6692 * @nr_pages: the amount of swap space to uncharge
6694 void mem_cgroup_uncharge_swap(swp_entry_t entry
, unsigned int nr_pages
)
6696 struct mem_cgroup
*memcg
;
6699 if (!do_swap_account
)
6702 id
= swap_cgroup_record(entry
, 0, nr_pages
);
6704 memcg
= mem_cgroup_from_id(id
);
6706 if (!mem_cgroup_is_root(memcg
)) {
6707 if (cgroup_subsys_on_dfl(memory_cgrp_subsys
))
6708 page_counter_uncharge(&memcg
->swap
, nr_pages
);
6710 page_counter_uncharge(&memcg
->memsw
, nr_pages
);
6712 mod_memcg_state(memcg
, MEMCG_SWAP
, -nr_pages
);
6713 mem_cgroup_id_put_many(memcg
, nr_pages
);
6718 long mem_cgroup_get_nr_swap_pages(struct mem_cgroup
*memcg
)
6720 long nr_swap_pages
= get_nr_swap_pages();
6722 if (!do_swap_account
|| !cgroup_subsys_on_dfl(memory_cgrp_subsys
))
6723 return nr_swap_pages
;
6724 for (; memcg
!= root_mem_cgroup
; memcg
= parent_mem_cgroup(memcg
))
6725 nr_swap_pages
= min_t(long, nr_swap_pages
,
6726 READ_ONCE(memcg
->swap
.max
) -
6727 page_counter_read(&memcg
->swap
));
6728 return nr_swap_pages
;
6731 bool mem_cgroup_swap_full(struct page
*page
)
6733 struct mem_cgroup
*memcg
;
6735 VM_BUG_ON_PAGE(!PageLocked(page
), page
);
6739 if (!do_swap_account
|| !cgroup_subsys_on_dfl(memory_cgrp_subsys
))
6742 memcg
= page
->mem_cgroup
;
6746 for (; memcg
!= root_mem_cgroup
; memcg
= parent_mem_cgroup(memcg
))
6747 if (page_counter_read(&memcg
->swap
) * 2 >= memcg
->swap
.max
)
6753 /* for remember boot option*/
6754 #ifdef CONFIG_MEMCG_SWAP_ENABLED
6755 static int really_do_swap_account __initdata
= 1;
6757 static int really_do_swap_account __initdata
;
6760 static int __init
enable_swap_account(char *s
)
6762 if (!strcmp(s
, "1"))
6763 really_do_swap_account
= 1;
6764 else if (!strcmp(s
, "0"))
6765 really_do_swap_account
= 0;
6768 __setup("swapaccount=", enable_swap_account
);
6770 static u64
swap_current_read(struct cgroup_subsys_state
*css
,
6773 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
6775 return (u64
)page_counter_read(&memcg
->swap
) * PAGE_SIZE
;
6778 static int swap_max_show(struct seq_file
*m
, void *v
)
6780 return seq_puts_memcg_tunable(m
,
6781 READ_ONCE(mem_cgroup_from_seq(m
)->swap
.max
));
6784 static ssize_t
swap_max_write(struct kernfs_open_file
*of
,
6785 char *buf
, size_t nbytes
, loff_t off
)
6787 struct mem_cgroup
*memcg
= mem_cgroup_from_css(of_css(of
));
6791 buf
= strstrip(buf
);
6792 err
= page_counter_memparse(buf
, "max", &max
);
6796 xchg(&memcg
->swap
.max
, max
);
6801 static int swap_events_show(struct seq_file
*m
, void *v
)
6803 struct mem_cgroup
*memcg
= mem_cgroup_from_seq(m
);
6805 seq_printf(m
, "max %lu\n",
6806 atomic_long_read(&memcg
->memory_events
[MEMCG_SWAP_MAX
]));
6807 seq_printf(m
, "fail %lu\n",
6808 atomic_long_read(&memcg
->memory_events
[MEMCG_SWAP_FAIL
]));
6813 static struct cftype swap_files
[] = {
6815 .name
= "swap.current",
6816 .flags
= CFTYPE_NOT_ON_ROOT
,
6817 .read_u64
= swap_current_read
,
6821 .flags
= CFTYPE_NOT_ON_ROOT
,
6822 .seq_show
= swap_max_show
,
6823 .write
= swap_max_write
,
6826 .name
= "swap.events",
6827 .flags
= CFTYPE_NOT_ON_ROOT
,
6828 .file_offset
= offsetof(struct mem_cgroup
, swap_events_file
),
6829 .seq_show
= swap_events_show
,
6834 static struct cftype memsw_cgroup_files
[] = {
6836 .name
= "memsw.usage_in_bytes",
6837 .private = MEMFILE_PRIVATE(_MEMSWAP
, RES_USAGE
),
6838 .read_u64
= mem_cgroup_read_u64
,
6841 .name
= "memsw.max_usage_in_bytes",
6842 .private = MEMFILE_PRIVATE(_MEMSWAP
, RES_MAX_USAGE
),
6843 .write
= mem_cgroup_reset
,
6844 .read_u64
= mem_cgroup_read_u64
,
6847 .name
= "memsw.limit_in_bytes",
6848 .private = MEMFILE_PRIVATE(_MEMSWAP
, RES_LIMIT
),
6849 .write
= mem_cgroup_write
,
6850 .read_u64
= mem_cgroup_read_u64
,
6853 .name
= "memsw.failcnt",
6854 .private = MEMFILE_PRIVATE(_MEMSWAP
, RES_FAILCNT
),
6855 .write
= mem_cgroup_reset
,
6856 .read_u64
= mem_cgroup_read_u64
,
6858 { }, /* terminate */
6861 static int __init
mem_cgroup_swap_init(void)
6863 if (!mem_cgroup_disabled() && really_do_swap_account
) {
6864 do_swap_account
= 1;
6865 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys
,
6867 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys
,
6868 memsw_cgroup_files
));
6872 subsys_initcall(mem_cgroup_swap_init
);
6874 #endif /* CONFIG_MEMCG_SWAP */