1 /* memcontrol.c - Memory Controller
3 * Copyright IBM Corporation, 2007
4 * Author Balbir Singh <balbir@linux.vnet.ibm.com>
6 * Copyright 2007 OpenVZ SWsoft Inc
7 * Author: Pavel Emelianov <xemul@openvz.org>
10 * Copyright (C) 2009 Nokia Corporation
11 * Author: Kirill A. Shutemov
13 * Kernel Memory Controller
14 * Copyright (C) 2012 Parallels Inc. and Google Inc.
15 * Authors: Glauber Costa and Suleiman Souhlal
17 * This program is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation; either version 2 of the License, or
20 * (at your option) any later version.
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
28 #include <linux/res_counter.h>
29 #include <linux/memcontrol.h>
30 #include <linux/cgroup.h>
32 #include <linux/hugetlb.h>
33 #include <linux/pagemap.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/sort.h>
50 #include <linux/seq_file.h>
51 #include <linux/vmalloc.h>
52 #include <linux/vmpressure.h>
53 #include <linux/mm_inline.h>
54 #include <linux/page_cgroup.h>
55 #include <linux/cpu.h>
56 #include <linux/oom.h>
60 #include <net/tcp_memcontrol.h>
62 #ifdef CONFIG_SHRINK_MEMORY
63 #ifdef CONFIG_COMPACTION
64 #include <linux/compaction.h>
66 #include <linux/vmstat.h>
67 #define MIN_SHRINK_THRESHOLD 25000
70 #include <asm/uaccess.h>
72 #include <trace/events/vmscan.h>
74 struct cgroup_subsys mem_cgroup_subsys __read_mostly;
75 EXPORT_SYMBOL(mem_cgroup_subsys);
77 #define MEM_CGROUP_RECLAIM_RETRIES 5
78 static struct mem_cgroup *root_mem_cgroup __read_mostly;
80 #ifdef CONFIG_MEMCG_SWAP
81 /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
82 int do_swap_account __read_mostly;
84 /* for remember boot option*/
85 #ifdef CONFIG_MEMCG_SWAP_ENABLED
86 static int really_do_swap_account __initdata = 1;
88 static int really_do_swap_account __initdata = 0;
92 #define do_swap_account 0
97 * Statistics for memory cgroup.
99 enum mem_cgroup_stat_index {
101 * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
103 MEM_CGROUP_STAT_CACHE, /* # of pages charged as cache */
104 MEM_CGROUP_STAT_RSS, /* # of pages charged as anon rss */
105 MEM_CGROUP_STAT_RSS_HUGE, /* # of pages charged as anon huge */
106 MEM_CGROUP_STAT_FILE_MAPPED, /* # of pages charged as file rss */
107 MEM_CGROUP_STAT_SWAP, /* # of pages, swapped out */
108 MEM_CGROUP_STAT_NSTATS,
111 static const char * const mem_cgroup_stat_names[] = {
119 enum mem_cgroup_events_index {
120 MEM_CGROUP_EVENTS_PGPGIN, /* # of pages paged in */
121 MEM_CGROUP_EVENTS_PGPGOUT, /* # of pages paged out */
122 MEM_CGROUP_EVENTS_PGFAULT, /* # of page-faults */
123 MEM_CGROUP_EVENTS_PGMAJFAULT, /* # of major page-faults */
124 MEM_CGROUP_EVENTS_NSTATS,
127 static const char * const mem_cgroup_events_names[] = {
134 static const char * const mem_cgroup_lru_names[] = {
143 * Per memcg event counter is incremented at every pagein/pageout. With THP,
144 * it will be incremated by the number of pages. This counter is used for
145 * for trigger some periodic events. This is straightforward and better
146 * than using jiffies etc. to handle periodic memcg event.
148 enum mem_cgroup_events_target {
149 MEM_CGROUP_TARGET_THRESH,
150 MEM_CGROUP_TARGET_SOFTLIMIT,
151 MEM_CGROUP_TARGET_NUMAINFO,
154 #define THRESHOLDS_EVENTS_TARGET 128
155 #define SOFTLIMIT_EVENTS_TARGET 1024
156 #define NUMAINFO_EVENTS_TARGET 1024
158 struct mem_cgroup_stat_cpu {
159 long count[MEM_CGROUP_STAT_NSTATS];
160 unsigned long events[MEM_CGROUP_EVENTS_NSTATS];
161 unsigned long nr_page_events;
162 unsigned long targets[MEM_CGROUP_NTARGETS];
165 struct mem_cgroup_reclaim_iter {
167 * last scanned hierarchy member. Valid only if last_dead_count
168 * matches memcg->dead_count of the hierarchy root group.
170 struct mem_cgroup *last_visited;
171 unsigned long last_dead_count;
173 /* scan generation, increased every round-trip */
174 unsigned int generation;
178 * per-zone information in memory controller.
180 struct mem_cgroup_per_zone {
181 struct lruvec lruvec;
182 unsigned long lru_size[NR_LRU_LISTS];
184 struct mem_cgroup_reclaim_iter reclaim_iter[DEF_PRIORITY + 1];
186 struct rb_node tree_node; /* RB tree node */
187 unsigned long long usage_in_excess;/* Set to the value by which */
188 /* the soft limit is exceeded*/
190 struct mem_cgroup *memcg; /* Back pointer, we cannot */
191 /* use container_of */
194 struct mem_cgroup_per_node {
195 struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
198 struct mem_cgroup_lru_info {
199 struct mem_cgroup_per_node *nodeinfo[0];
203 * Cgroups above their limits are maintained in a RB-Tree, independent of
204 * their hierarchy representation
207 struct mem_cgroup_tree_per_zone {
208 struct rb_root rb_root;
212 struct mem_cgroup_tree_per_node {
213 struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
216 struct mem_cgroup_tree {
217 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
220 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
222 struct mem_cgroup_threshold {
223 struct eventfd_ctx *eventfd;
228 struct mem_cgroup_threshold_ary {
229 /* An array index points to threshold just below or equal to usage. */
230 int current_threshold;
231 /* Size of entries[] */
233 /* Array of thresholds */
234 struct mem_cgroup_threshold entries[0];
237 struct mem_cgroup_thresholds {
238 /* Primary thresholds array */
239 struct mem_cgroup_threshold_ary *primary;
241 * Spare threshold array.
242 * This is needed to make mem_cgroup_unregister_event() "never fail".
243 * It must be able to store at least primary->size - 1 entries.
245 struct mem_cgroup_threshold_ary *spare;
249 struct mem_cgroup_eventfd_list {
250 struct list_head list;
251 struct eventfd_ctx *eventfd;
254 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
255 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
258 * The memory controller data structure. The memory controller controls both
259 * page cache and RSS per cgroup. We would eventually like to provide
260 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
261 * to help the administrator determine what knobs to tune.
263 * TODO: Add a water mark for the memory controller. Reclaim will begin when
264 * we hit the water mark. May be even add a low water mark, such that
265 * no reclaim occurs from a cgroup at it's low water mark, this is
266 * a feature that will be implemented much later in the future.
269 struct cgroup_subsys_state css;
271 * the counter to account for memory usage
273 struct res_counter res;
275 /* vmpressure notifications */
276 struct vmpressure vmpressure;
280 * the counter to account for mem+swap usage.
282 struct res_counter memsw;
285 * rcu_freeing is used only when freeing struct mem_cgroup,
286 * so put it into a union to avoid wasting more memory.
287 * It must be disjoint from the css field. It could be
288 * in a union with the res field, but res plays a much
289 * larger part in mem_cgroup life than memsw, and might
290 * be of interest, even at time of free, when debugging.
291 * So share rcu_head with the less interesting memsw.
293 struct rcu_head rcu_freeing;
295 * We also need some space for a worker in deferred freeing.
296 * By the time we call it, rcu_freeing is no longer in use.
298 struct work_struct work_freeing;
302 * the counter to account for kernel memory usage.
304 struct res_counter kmem;
306 * Should the accounting and control be hierarchical, per subtree?
309 unsigned long kmem_account_flags; /* See KMEM_ACCOUNTED_*, below */
313 atomic_t oom_wakeups;
318 /* OOM-Killer disable */
319 int oom_kill_disable;
321 /* set when res.limit == memsw.limit */
322 bool memsw_is_minimum;
324 /* protect arrays of thresholds */
325 struct mutex thresholds_lock;
327 /* thresholds for memory usage. RCU-protected */
328 struct mem_cgroup_thresholds thresholds;
330 /* thresholds for mem+swap usage. RCU-protected */
331 struct mem_cgroup_thresholds memsw_thresholds;
333 /* For oom notifier event fd */
334 struct list_head oom_notify;
337 * Should we move charges of a task when a task is moved into this
338 * mem_cgroup ? And what type of charges should we move ?
340 unsigned long move_charge_at_immigrate;
342 * set > 0 if pages under this cgroup are moving to other cgroup.
344 atomic_t moving_account;
345 /* taken only while moving_account > 0 */
346 spinlock_t move_lock;
350 struct mem_cgroup_stat_cpu __percpu *stat;
352 * used when a cpu is offlined or other synchronizations
353 * See mem_cgroup_read_stat().
355 struct mem_cgroup_stat_cpu nocpu_base;
356 spinlock_t pcp_counter_lock;
359 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_INET)
360 struct tcp_memcontrol tcp_mem;
362 #if defined(CONFIG_MEMCG_KMEM)
363 /* analogous to slab_common's slab_caches list. per-memcg */
364 struct list_head memcg_slab_caches;
365 /* Not a spinlock, we can take a lot of time walking the list */
366 struct mutex slab_caches_mutex;
367 /* Index in the kmem_cache->memcg_params->memcg_caches array */
371 int last_scanned_node;
373 nodemask_t scan_nodes;
374 atomic_t numainfo_events;
375 atomic_t numainfo_updating;
379 * Per cgroup active and inactive list, similar to the
380 * per zone LRU lists.
382 * WARNING: This has to be the last element of the struct. Don't
383 * add new fields after this point.
385 struct mem_cgroup_lru_info info;
388 static size_t memcg_size(void)
390 return sizeof(struct mem_cgroup) +
391 nr_node_ids * sizeof(struct mem_cgroup_per_node *);
394 /* internal only representation about the status of kmem accounting. */
396 KMEM_ACCOUNTED_ACTIVE = 0, /* accounted by this cgroup itself */
397 KMEM_ACCOUNTED_ACTIVATED, /* static key enabled. */
398 KMEM_ACCOUNTED_DEAD, /* dead memcg with pending kmem charges */
401 /* We account when limit is on, but only after call sites are patched */
402 #define KMEM_ACCOUNTED_MASK \
403 ((1 << KMEM_ACCOUNTED_ACTIVE) | (1 << KMEM_ACCOUNTED_ACTIVATED))
405 #ifdef CONFIG_MEMCG_KMEM
406 static inline void memcg_kmem_set_active(struct mem_cgroup *memcg)
408 set_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags);
411 static bool memcg_kmem_is_active(struct mem_cgroup *memcg)
413 return test_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags);
416 static void memcg_kmem_set_activated(struct mem_cgroup *memcg)
418 set_bit(KMEM_ACCOUNTED_ACTIVATED, &memcg->kmem_account_flags);
421 static void memcg_kmem_clear_activated(struct mem_cgroup *memcg)
423 clear_bit(KMEM_ACCOUNTED_ACTIVATED, &memcg->kmem_account_flags);
426 static void memcg_kmem_mark_dead(struct mem_cgroup *memcg)
428 if (test_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags))
429 set_bit(KMEM_ACCOUNTED_DEAD, &memcg->kmem_account_flags);
432 static bool memcg_kmem_test_and_clear_dead(struct mem_cgroup *memcg)
434 return test_and_clear_bit(KMEM_ACCOUNTED_DEAD,
435 &memcg->kmem_account_flags);
439 /* Stuffs for move charges at task migration. */
441 * Types of charges to be moved. "move_charge_at_immitgrate" and
442 * "immigrate_flags" are treated as a left-shifted bitmap of these types.
445 MOVE_CHARGE_TYPE_ANON, /* private anonymous page and swap of it */
446 MOVE_CHARGE_TYPE_FILE, /* file page(including tmpfs) and swap of it */
450 /* "mc" and its members are protected by cgroup_mutex */
451 static struct move_charge_struct {
452 spinlock_t lock; /* for from, to */
453 struct mem_cgroup *from;
454 struct mem_cgroup *to;
455 unsigned long immigrate_flags;
456 unsigned long precharge;
457 unsigned long moved_charge;
458 unsigned long moved_swap;
459 struct task_struct *moving_task; /* a task moving charges */
460 wait_queue_head_t waitq; /* a waitq for other context */
462 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
463 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
466 static bool move_anon(void)
468 return test_bit(MOVE_CHARGE_TYPE_ANON, &mc.immigrate_flags);
471 static bool move_file(void)
473 return test_bit(MOVE_CHARGE_TYPE_FILE, &mc.immigrate_flags);
477 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
478 * limit reclaim to prevent infinite loops, if they ever occur.
480 #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
481 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
484 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
485 MEM_CGROUP_CHARGE_TYPE_ANON,
486 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
487 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
491 /* for encoding cft->private value on file */
499 #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
500 #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
501 #define MEMFILE_ATTR(val) ((val) & 0xffff)
502 /* Used for OOM nofiier */
503 #define OOM_CONTROL (0)
506 * Reclaim flags for mem_cgroup_hierarchical_reclaim
508 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
509 #define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
510 #define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
511 #define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
514 * The memcg_create_mutex will be held whenever a new cgroup is created.
515 * As a consequence, any change that needs to protect against new child cgroups
516 * appearing has to hold it as well.
518 static DEFINE_MUTEX(memcg_create_mutex);
520 static void mem_cgroup_get(struct mem_cgroup *memcg);
521 static void mem_cgroup_put(struct mem_cgroup *memcg);
524 struct mem_cgroup *mem_cgroup_from_css(struct cgroup_subsys_state *s)
526 return container_of(s, struct mem_cgroup, css);
529 /* Some nice accessors for the vmpressure. */
530 struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
533 memcg = root_mem_cgroup;
534 return &memcg->vmpressure;
537 struct cgroup_subsys_state *vmpressure_to_css(struct vmpressure *vmpr)
539 return &container_of(vmpr, struct mem_cgroup, vmpressure)->css;
542 struct vmpressure *css_to_vmpressure(struct cgroup_subsys_state *css)
544 return &mem_cgroup_from_css(css)->vmpressure;
547 static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
549 return (memcg == root_mem_cgroup);
552 /* Writing them here to avoid exposing memcg's inner layout */
553 #if defined(CONFIG_INET) && defined(CONFIG_MEMCG_KMEM)
555 void sock_update_memcg(struct sock *sk)
557 if (mem_cgroup_sockets_enabled) {
558 struct mem_cgroup *memcg;
559 struct cg_proto *cg_proto;
561 BUG_ON(!sk->sk_prot->proto_cgroup);
563 /* Socket cloning can throw us here with sk_cgrp already
564 * filled. It won't however, necessarily happen from
565 * process context. So the test for root memcg given
566 * the current task's memcg won't help us in this case.
568 * Respecting the original socket's memcg is a better
569 * decision in this case.
572 BUG_ON(mem_cgroup_is_root(sk->sk_cgrp->memcg));
573 mem_cgroup_get(sk->sk_cgrp->memcg);
578 memcg = mem_cgroup_from_task(current);
579 cg_proto = sk->sk_prot->proto_cgroup(memcg);
580 if (!mem_cgroup_is_root(memcg) && memcg_proto_active(cg_proto)) {
581 mem_cgroup_get(memcg);
582 sk->sk_cgrp = cg_proto;
587 EXPORT_SYMBOL(sock_update_memcg);
589 void sock_release_memcg(struct sock *sk)
591 if (mem_cgroup_sockets_enabled && sk->sk_cgrp) {
592 struct mem_cgroup *memcg;
593 WARN_ON(!sk->sk_cgrp->memcg);
594 memcg = sk->sk_cgrp->memcg;
595 mem_cgroup_put(memcg);
599 struct cg_proto *tcp_proto_cgroup(struct mem_cgroup *memcg)
601 if (!memcg || mem_cgroup_is_root(memcg))
604 return &memcg->tcp_mem.cg_proto;
606 EXPORT_SYMBOL(tcp_proto_cgroup);
608 static void disarm_sock_keys(struct mem_cgroup *memcg)
610 if (!memcg_proto_activated(&memcg->tcp_mem.cg_proto))
612 static_key_slow_dec(&memcg_socket_limit_enabled);
615 static void disarm_sock_keys(struct mem_cgroup *memcg)
620 #ifdef CONFIG_MEMCG_KMEM
622 * This will be the memcg's index in each cache's ->memcg_params->memcg_caches.
623 * There are two main reasons for not using the css_id for this:
624 * 1) this works better in sparse environments, where we have a lot of memcgs,
625 * but only a few kmem-limited. Or also, if we have, for instance, 200
626 * memcgs, and none but the 200th is kmem-limited, we'd have to have a
627 * 200 entry array for that.
629 * 2) In order not to violate the cgroup API, we would like to do all memory
630 * allocation in ->create(). At that point, we haven't yet allocated the
631 * css_id. Having a separate index prevents us from messing with the cgroup
634 * The current size of the caches array is stored in
635 * memcg_limited_groups_array_size. It will double each time we have to
638 static DEFINE_IDA(kmem_limited_groups);
639 int memcg_limited_groups_array_size;
642 * MIN_SIZE is different than 1, because we would like to avoid going through
643 * the alloc/free process all the time. In a small machine, 4 kmem-limited
644 * cgroups is a reasonable guess. In the future, it could be a parameter or
645 * tunable, but that is strictly not necessary.
647 * MAX_SIZE should be as large as the number of css_ids. Ideally, we could get
648 * this constant directly from cgroup, but it is understandable that this is
649 * better kept as an internal representation in cgroup.c. In any case, the
650 * css_id space is not getting any smaller, and we don't have to necessarily
651 * increase ours as well if it increases.
653 #define MEMCG_CACHES_MIN_SIZE 4
654 #define MEMCG_CACHES_MAX_SIZE 65535
657 * A lot of the calls to the cache allocation functions are expected to be
658 * inlined by the compiler. Since the calls to memcg_kmem_get_cache are
659 * conditional to this static branch, we'll have to allow modules that does
660 * kmem_cache_alloc and the such to see this symbol as well
662 struct static_key memcg_kmem_enabled_key;
663 EXPORT_SYMBOL(memcg_kmem_enabled_key);
665 static void disarm_kmem_keys(struct mem_cgroup *memcg)
667 if (memcg_kmem_is_active(memcg)) {
668 static_key_slow_dec(&memcg_kmem_enabled_key);
669 ida_simple_remove(&kmem_limited_groups, memcg->kmemcg_id);
672 * This check can't live in kmem destruction function,
673 * since the charges will outlive the cgroup
675 WARN_ON(res_counter_read_u64(&memcg->kmem, RES_USAGE) != 0);
678 static void disarm_kmem_keys(struct mem_cgroup *memcg)
681 #endif /* CONFIG_MEMCG_KMEM */
683 static void disarm_static_keys(struct mem_cgroup *memcg)
685 disarm_sock_keys(memcg);
686 disarm_kmem_keys(memcg);
689 static void drain_all_stock_async(struct mem_cgroup *memcg);
691 static struct mem_cgroup_per_zone *
692 mem_cgroup_zoneinfo(struct mem_cgroup *memcg, int nid, int zid)
694 VM_BUG_ON((unsigned)nid >= nr_node_ids);
695 return &memcg->info.nodeinfo[nid]->zoneinfo[zid];
698 struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *memcg)
703 static struct mem_cgroup_per_zone *
704 page_cgroup_zoneinfo(struct mem_cgroup *memcg, struct page *page)
706 int nid = page_to_nid(page);
707 int zid = page_zonenum(page);
709 return mem_cgroup_zoneinfo(memcg, nid, zid);
712 static struct mem_cgroup_tree_per_zone *
713 soft_limit_tree_node_zone(int nid, int zid)
715 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
718 static struct mem_cgroup_tree_per_zone *
719 soft_limit_tree_from_page(struct page *page)
721 int nid = page_to_nid(page);
722 int zid = page_zonenum(page);
724 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
728 __mem_cgroup_insert_exceeded(struct mem_cgroup *memcg,
729 struct mem_cgroup_per_zone *mz,
730 struct mem_cgroup_tree_per_zone *mctz,
731 unsigned long long new_usage_in_excess)
733 struct rb_node **p = &mctz->rb_root.rb_node;
734 struct rb_node *parent = NULL;
735 struct mem_cgroup_per_zone *mz_node;
740 mz->usage_in_excess = new_usage_in_excess;
741 if (!mz->usage_in_excess)
745 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
747 if (mz->usage_in_excess < mz_node->usage_in_excess)
750 * We can't avoid mem cgroups that are over their soft
751 * limit by the same amount
753 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
756 rb_link_node(&mz->tree_node, parent, p);
757 rb_insert_color(&mz->tree_node, &mctz->rb_root);
762 __mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
763 struct mem_cgroup_per_zone *mz,
764 struct mem_cgroup_tree_per_zone *mctz)
768 rb_erase(&mz->tree_node, &mctz->rb_root);
773 mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
774 struct mem_cgroup_per_zone *mz,
775 struct mem_cgroup_tree_per_zone *mctz)
777 spin_lock(&mctz->lock);
778 __mem_cgroup_remove_exceeded(memcg, mz, mctz);
779 spin_unlock(&mctz->lock);
783 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
785 unsigned long long excess;
786 struct mem_cgroup_per_zone *mz;
787 struct mem_cgroup_tree_per_zone *mctz;
788 int nid = page_to_nid(page);
789 int zid = page_zonenum(page);
790 mctz = soft_limit_tree_from_page(page);
793 * Necessary to update all ancestors when hierarchy is used.
794 * because their event counter is not touched.
796 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
797 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
798 excess = res_counter_soft_limit_excess(&memcg->res);
800 * We have to update the tree if mz is on RB-tree or
801 * mem is over its softlimit.
803 if (excess || mz->on_tree) {
804 spin_lock(&mctz->lock);
805 /* if on-tree, remove it */
807 __mem_cgroup_remove_exceeded(memcg, mz, mctz);
809 * Insert again. mz->usage_in_excess will be updated.
810 * If excess is 0, no tree ops.
812 __mem_cgroup_insert_exceeded(memcg, mz, mctz, excess);
813 spin_unlock(&mctz->lock);
818 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
821 struct mem_cgroup_per_zone *mz;
822 struct mem_cgroup_tree_per_zone *mctz;
824 for_each_node(node) {
825 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
826 mz = mem_cgroup_zoneinfo(memcg, node, zone);
827 mctz = soft_limit_tree_node_zone(node, zone);
828 mem_cgroup_remove_exceeded(memcg, mz, mctz);
833 static struct mem_cgroup_per_zone *
834 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
836 struct rb_node *rightmost = NULL;
837 struct mem_cgroup_per_zone *mz;
841 rightmost = rb_last(&mctz->rb_root);
843 goto done; /* Nothing to reclaim from */
845 mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
847 * Remove the node now but someone else can add it back,
848 * we will to add it back at the end of reclaim to its correct
849 * position in the tree.
851 __mem_cgroup_remove_exceeded(mz->memcg, mz, mctz);
852 if (!res_counter_soft_limit_excess(&mz->memcg->res) ||
853 !css_tryget(&mz->memcg->css))
859 static struct mem_cgroup_per_zone *
860 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
862 struct mem_cgroup_per_zone *mz;
864 spin_lock(&mctz->lock);
865 mz = __mem_cgroup_largest_soft_limit_node(mctz);
866 spin_unlock(&mctz->lock);
871 * Implementation Note: reading percpu statistics for memcg.
873 * Both of vmstat[] and percpu_counter has threshold and do periodic
874 * synchronization to implement "quick" read. There are trade-off between
875 * reading cost and precision of value. Then, we may have a chance to implement
876 * a periodic synchronizion of counter in memcg's counter.
878 * But this _read() function is used for user interface now. The user accounts
879 * memory usage by memory cgroup and he _always_ requires exact value because
880 * he accounts memory. Even if we provide quick-and-fuzzy read, we always
881 * have to visit all online cpus and make sum. So, for now, unnecessary
882 * synchronization is not implemented. (just implemented for cpu hotplug)
884 * If there are kernel internal actions which can make use of some not-exact
885 * value, and reading all cpu value can be performance bottleneck in some
886 * common workload, threashold and synchonization as vmstat[] should be
889 static long mem_cgroup_read_stat(struct mem_cgroup *memcg,
890 enum mem_cgroup_stat_index idx)
896 for_each_online_cpu(cpu)
897 val += per_cpu(memcg->stat->count[idx], cpu);
898 #ifdef CONFIG_HOTPLUG_CPU
899 spin_lock(&memcg->pcp_counter_lock);
900 val += memcg->nocpu_base.count[idx];
901 spin_unlock(&memcg->pcp_counter_lock);
907 static void mem_cgroup_swap_statistics(struct mem_cgroup *memcg,
910 int val = (charge) ? 1 : -1;
911 this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_SWAP], val);
914 static unsigned long mem_cgroup_read_events(struct mem_cgroup *memcg,
915 enum mem_cgroup_events_index idx)
917 unsigned long val = 0;
920 for_each_online_cpu(cpu)
921 val += per_cpu(memcg->stat->events[idx], cpu);
922 #ifdef CONFIG_HOTPLUG_CPU
923 spin_lock(&memcg->pcp_counter_lock);
924 val += memcg->nocpu_base.events[idx];
925 spin_unlock(&memcg->pcp_counter_lock);
930 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
932 bool anon, int nr_pages)
937 * Here, RSS means 'mapped anon' and anon's SwapCache. Shmem/tmpfs is
938 * counted as CACHE even if it's on ANON LRU.
941 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS],
944 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_CACHE],
947 if (PageTransHuge(page))
948 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS_HUGE],
951 /* pagein of a big page is an event. So, ignore page size */
953 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGIN]);
955 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]);
956 nr_pages = -nr_pages; /* for event */
959 __this_cpu_add(memcg->stat->nr_page_events, nr_pages);
965 mem_cgroup_get_lru_size(struct lruvec *lruvec, enum lru_list lru)
967 struct mem_cgroup_per_zone *mz;
969 mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
970 return mz->lru_size[lru];
974 mem_cgroup_zone_nr_lru_pages(struct mem_cgroup *memcg, int nid, int zid,
975 unsigned int lru_mask)
977 struct mem_cgroup_per_zone *mz;
979 unsigned long ret = 0;
981 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
984 if (BIT(lru) & lru_mask)
985 ret += mz->lru_size[lru];
991 mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
992 int nid, unsigned int lru_mask)
997 for (zid = 0; zid < MAX_NR_ZONES; zid++)
998 total += mem_cgroup_zone_nr_lru_pages(memcg,
1004 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
1005 unsigned int lru_mask)
1010 for_each_node_state(nid, N_MEMORY)
1011 total += mem_cgroup_node_nr_lru_pages(memcg, nid, lru_mask);
1015 static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
1016 enum mem_cgroup_events_target target)
1018 unsigned long val, next;
1020 val = __this_cpu_read(memcg->stat->nr_page_events);
1021 next = __this_cpu_read(memcg->stat->targets[target]);
1022 /* from time_after() in jiffies.h */
1023 if ((long)next - (long)val < 0) {
1025 case MEM_CGROUP_TARGET_THRESH:
1026 next = val + THRESHOLDS_EVENTS_TARGET;
1028 case MEM_CGROUP_TARGET_SOFTLIMIT:
1029 next = val + SOFTLIMIT_EVENTS_TARGET;
1031 case MEM_CGROUP_TARGET_NUMAINFO:
1032 next = val + NUMAINFO_EVENTS_TARGET;
1037 __this_cpu_write(memcg->stat->targets[target], next);
1044 * Check events in order.
1047 static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
1050 /* threshold event is triggered in finer grain than soft limit */
1051 if (unlikely(mem_cgroup_event_ratelimit(memcg,
1052 MEM_CGROUP_TARGET_THRESH))) {
1054 bool do_numainfo __maybe_unused;
1056 do_softlimit = mem_cgroup_event_ratelimit(memcg,
1057 MEM_CGROUP_TARGET_SOFTLIMIT);
1058 #if MAX_NUMNODES > 1
1059 do_numainfo = mem_cgroup_event_ratelimit(memcg,
1060 MEM_CGROUP_TARGET_NUMAINFO);
1064 mem_cgroup_threshold(memcg);
1065 if (unlikely(do_softlimit))
1066 mem_cgroup_update_tree(memcg, page);
1067 #if MAX_NUMNODES > 1
1068 if (unlikely(do_numainfo))
1069 atomic_inc(&memcg->numainfo_events);
1075 struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
1077 return mem_cgroup_from_css(
1078 cgroup_subsys_state(cont, mem_cgroup_subsys_id));
1081 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
1084 * mm_update_next_owner() may clear mm->owner to NULL
1085 * if it races with swapoff, page migration, etc.
1086 * So this can be called with p == NULL.
1091 return mem_cgroup_from_css(task_subsys_state(p, mem_cgroup_subsys_id));
1094 struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
1096 struct mem_cgroup *memcg = NULL;
1101 * Because we have no locks, mm->owner's may be being moved to other
1102 * cgroup. We use css_tryget() here even if this looks
1103 * pessimistic (rather than adding locks here).
1107 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1108 if (unlikely(!memcg))
1110 } while (!css_tryget(&memcg->css));
1116 * Returns a next (in a pre-order walk) alive memcg (with elevated css
1117 * ref. count) or NULL if the whole root's subtree has been visited.
1119 * helper function to be used by mem_cgroup_iter
1121 static struct mem_cgroup *__mem_cgroup_iter_next(struct mem_cgroup *root,
1122 struct mem_cgroup *last_visited)
1124 struct cgroup *prev_cgroup, *next_cgroup;
1127 * Root is not visited by cgroup iterators so it needs an
1133 prev_cgroup = (last_visited == root) ? NULL
1134 : last_visited->css.cgroup;
1136 next_cgroup = cgroup_next_descendant_pre(
1137 prev_cgroup, root->css.cgroup);
1140 * Even if we found a group we have to make sure it is
1141 * alive. css && !memcg means that the groups should be
1142 * skipped and we should continue the tree walk.
1143 * last_visited css is safe to use because it is
1144 * protected by css_get and the tree walk is rcu safe.
1147 struct mem_cgroup *mem = mem_cgroup_from_cont(
1149 if (css_tryget(&mem->css))
1152 prev_cgroup = next_cgroup;
1161 * mem_cgroup_iter - iterate over memory cgroup hierarchy
1162 * @root: hierarchy root
1163 * @prev: previously returned memcg, NULL on first invocation
1164 * @reclaim: cookie for shared reclaim walks, NULL for full walks
1166 * Returns references to children of the hierarchy below @root, or
1167 * @root itself, or %NULL after a full round-trip.
1169 * Caller must pass the return value in @prev on subsequent
1170 * invocations for reference counting, or use mem_cgroup_iter_break()
1171 * to cancel a hierarchy walk before the round-trip is complete.
1173 * Reclaimers can specify a zone and a priority level in @reclaim to
1174 * divide up the memcgs in the hierarchy among all concurrent
1175 * reclaimers operating on the same zone and priority.
1177 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
1178 struct mem_cgroup *prev,
1179 struct mem_cgroup_reclaim_cookie *reclaim)
1181 struct mem_cgroup *memcg = NULL;
1182 struct mem_cgroup *last_visited = NULL;
1183 unsigned long uninitialized_var(dead_count);
1185 if (mem_cgroup_disabled())
1189 root = root_mem_cgroup;
1191 if (prev && !reclaim)
1192 last_visited = prev;
1194 if (!root->use_hierarchy && root != root_mem_cgroup) {
1202 struct mem_cgroup_reclaim_iter *uninitialized_var(iter);
1205 int nid = zone_to_nid(reclaim->zone);
1206 int zid = zone_idx(reclaim->zone);
1207 struct mem_cgroup_per_zone *mz;
1209 mz = mem_cgroup_zoneinfo(root, nid, zid);
1210 iter = &mz->reclaim_iter[reclaim->priority];
1211 if (prev && reclaim->generation != iter->generation) {
1212 iter->last_visited = NULL;
1217 * If the dead_count mismatches, a destruction
1218 * has happened or is happening concurrently.
1219 * If the dead_count matches, a destruction
1220 * might still happen concurrently, but since
1221 * we checked under RCU, that destruction
1222 * won't free the object until we release the
1223 * RCU reader lock. Thus, the dead_count
1224 * check verifies the pointer is still valid,
1225 * css_tryget() verifies the cgroup pointed to
1228 dead_count = atomic_read(&root->dead_count);
1229 if (dead_count == iter->last_dead_count) {
1231 last_visited = iter->last_visited;
1232 if (last_visited && last_visited != root &&
1233 !css_tryget(&last_visited->css))
1234 last_visited = NULL;
1238 memcg = __mem_cgroup_iter_next(root, last_visited);
1241 if (last_visited && last_visited != root)
1242 css_put(&last_visited->css);
1244 iter->last_visited = memcg;
1246 iter->last_dead_count = dead_count;
1250 else if (!prev && memcg)
1251 reclaim->generation = iter->generation;
1260 if (prev && prev != root)
1261 css_put(&prev->css);
1267 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1268 * @root: hierarchy root
1269 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1271 void mem_cgroup_iter_break(struct mem_cgroup *root,
1272 struct mem_cgroup *prev)
1275 root = root_mem_cgroup;
1276 if (prev && prev != root)
1277 css_put(&prev->css);
1281 * Iteration constructs for visiting all cgroups (under a tree). If
1282 * loops are exited prematurely (break), mem_cgroup_iter_break() must
1283 * be used for reference counting.
1285 #define for_each_mem_cgroup_tree(iter, root) \
1286 for (iter = mem_cgroup_iter(root, NULL, NULL); \
1288 iter = mem_cgroup_iter(root, iter, NULL))
1290 #define for_each_mem_cgroup(iter) \
1291 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
1293 iter = mem_cgroup_iter(NULL, iter, NULL))
1295 void __mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx)
1297 struct mem_cgroup *memcg;
1300 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1301 if (unlikely(!memcg))
1306 this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGFAULT]);
1309 this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGMAJFAULT]);
1317 EXPORT_SYMBOL(__mem_cgroup_count_vm_event);
1320 * mem_cgroup_zone_lruvec - get the lru list vector for a zone and memcg
1321 * @zone: zone of the wanted lruvec
1322 * @memcg: memcg of the wanted lruvec
1324 * Returns the lru list vector holding pages for the given @zone and
1325 * @mem. This can be the global zone lruvec, if the memory controller
1328 struct lruvec *mem_cgroup_zone_lruvec(struct zone *zone,
1329 struct mem_cgroup *memcg)
1331 struct mem_cgroup_per_zone *mz;
1332 struct lruvec *lruvec;
1334 if (mem_cgroup_disabled()) {
1335 lruvec = &zone->lruvec;
1339 mz = mem_cgroup_zoneinfo(memcg, zone_to_nid(zone), zone_idx(zone));
1340 lruvec = &mz->lruvec;
1343 * Since a node can be onlined after the mem_cgroup was created,
1344 * we have to be prepared to initialize lruvec->zone here;
1345 * and if offlined then reonlined, we need to reinitialize it.
1347 if (unlikely(lruvec->zone != zone))
1348 lruvec->zone = zone;
1353 * Following LRU functions are allowed to be used without PCG_LOCK.
1354 * Operations are called by routine of global LRU independently from memcg.
1355 * What we have to take care of here is validness of pc->mem_cgroup.
1357 * Changes to pc->mem_cgroup happens when
1360 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
1361 * It is added to LRU before charge.
1362 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
1363 * When moving account, the page is not on LRU. It's isolated.
1367 * mem_cgroup_page_lruvec - return lruvec for adding an lru page
1369 * @zone: zone of the page
1371 struct lruvec *mem_cgroup_page_lruvec(struct page *page, struct zone *zone)
1373 struct mem_cgroup_per_zone *mz;
1374 struct mem_cgroup *memcg;
1375 struct page_cgroup *pc;
1376 struct lruvec *lruvec;
1378 if (mem_cgroup_disabled()) {
1379 lruvec = &zone->lruvec;
1383 pc = lookup_page_cgroup(page);
1384 memcg = pc->mem_cgroup;
1387 * Surreptitiously switch any uncharged offlist page to root:
1388 * an uncharged page off lru does nothing to secure
1389 * its former mem_cgroup from sudden removal.
1391 * Our caller holds lru_lock, and PageCgroupUsed is updated
1392 * under page_cgroup lock: between them, they make all uses
1393 * of pc->mem_cgroup safe.
1395 if (!PageLRU(page) && !PageCgroupUsed(pc) && memcg != root_mem_cgroup)
1396 pc->mem_cgroup = memcg = root_mem_cgroup;
1398 mz = page_cgroup_zoneinfo(memcg, page);
1399 lruvec = &mz->lruvec;
1402 * Since a node can be onlined after the mem_cgroup was created,
1403 * we have to be prepared to initialize lruvec->zone here;
1404 * and if offlined then reonlined, we need to reinitialize it.
1406 if (unlikely(lruvec->zone != zone))
1407 lruvec->zone = zone;
1412 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1413 * @lruvec: mem_cgroup per zone lru vector
1414 * @lru: index of lru list the page is sitting on
1415 * @nr_pages: positive when adding or negative when removing
1417 * This function must be called when a page is added to or removed from an
1420 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1423 struct mem_cgroup_per_zone *mz;
1424 unsigned long *lru_size;
1426 if (mem_cgroup_disabled())
1429 mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
1430 lru_size = mz->lru_size + lru;
1431 *lru_size += nr_pages;
1432 VM_BUG_ON((long)(*lru_size) < 0);
1436 * Checks whether given mem is same or in the root_mem_cgroup's
1439 bool __mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1440 struct mem_cgroup *memcg)
1442 if (root_memcg == memcg)
1444 if (!root_memcg->use_hierarchy || !memcg)
1446 return css_is_ancestor(&memcg->css, &root_memcg->css);
1449 static bool mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1450 struct mem_cgroup *memcg)
1455 ret = __mem_cgroup_same_or_subtree(root_memcg, memcg);
1460 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *memcg)
1463 struct mem_cgroup *curr = NULL;
1464 struct task_struct *p;
1466 p = find_lock_task_mm(task);
1468 curr = try_get_mem_cgroup_from_mm(p->mm);
1472 * All threads may have already detached their mm's, but the oom
1473 * killer still needs to detect if they have already been oom
1474 * killed to prevent needlessly killing additional tasks.
1477 curr = mem_cgroup_from_task(task);
1479 css_get(&curr->css);
1485 * We should check use_hierarchy of "memcg" not "curr". Because checking
1486 * use_hierarchy of "curr" here make this function true if hierarchy is
1487 * enabled in "curr" and "curr" is a child of "memcg" in *cgroup*
1488 * hierarchy(even if use_hierarchy is disabled in "memcg").
1490 ret = mem_cgroup_same_or_subtree(memcg, curr);
1491 css_put(&curr->css);
1495 int mem_cgroup_inactive_anon_is_low(struct lruvec *lruvec)
1497 unsigned long inactive_ratio;
1498 unsigned long inactive;
1499 unsigned long active;
1502 inactive = mem_cgroup_get_lru_size(lruvec, LRU_INACTIVE_ANON);
1503 active = mem_cgroup_get_lru_size(lruvec, LRU_ACTIVE_ANON);
1505 gb = (inactive + active) >> (30 - PAGE_SHIFT);
1507 inactive_ratio = int_sqrt(10 * gb);
1511 return inactive * inactive_ratio < active;
1514 #define mem_cgroup_from_res_counter(counter, member) \
1515 container_of(counter, struct mem_cgroup, member)
1518 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1519 * @memcg: the memory cgroup
1521 * Returns the maximum amount of memory @mem can be charged with, in
1524 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1526 unsigned long long margin;
1528 margin = res_counter_margin(&memcg->res);
1529 if (do_swap_account)
1530 margin = min(margin, res_counter_margin(&memcg->memsw));
1531 return margin >> PAGE_SHIFT;
1534 int mem_cgroup_swappiness(struct mem_cgroup *memcg)
1536 struct cgroup *cgrp = memcg->css.cgroup;
1539 if (cgrp->parent == NULL)
1540 return vm_swappiness;
1542 return memcg->swappiness;
1546 * memcg->moving_account is used for checking possibility that some thread is
1547 * calling move_account(). When a thread on CPU-A starts moving pages under
1548 * a memcg, other threads should check memcg->moving_account under
1549 * rcu_read_lock(), like this:
1553 * memcg->moving_account+1 if (memcg->mocing_account)
1555 * synchronize_rcu() update something.
1560 /* for quick checking without looking up memcg */
1561 atomic_t memcg_moving __read_mostly;
1563 static void mem_cgroup_start_move(struct mem_cgroup *memcg)
1565 atomic_inc(&memcg_moving);
1566 atomic_inc(&memcg->moving_account);
1570 static void mem_cgroup_end_move(struct mem_cgroup *memcg)
1573 * Now, mem_cgroup_clear_mc() may call this function with NULL.
1574 * We check NULL in callee rather than caller.
1577 atomic_dec(&memcg_moving);
1578 atomic_dec(&memcg->moving_account);
1583 * 2 routines for checking "mem" is under move_account() or not.
1585 * mem_cgroup_stolen() - checking whether a cgroup is mc.from or not. This
1586 * is used for avoiding races in accounting. If true,
1587 * pc->mem_cgroup may be overwritten.
1589 * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
1590 * under hierarchy of moving cgroups. This is for
1591 * waiting at hith-memory prressure caused by "move".
1594 static bool mem_cgroup_stolen(struct mem_cgroup *memcg)
1596 VM_BUG_ON(!rcu_read_lock_held());
1597 return atomic_read(&memcg->moving_account) > 0;
1600 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1602 struct mem_cgroup *from;
1603 struct mem_cgroup *to;
1606 * Unlike task_move routines, we access mc.to, mc.from not under
1607 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1609 spin_lock(&mc.lock);
1615 ret = mem_cgroup_same_or_subtree(memcg, from)
1616 || mem_cgroup_same_or_subtree(memcg, to);
1618 spin_unlock(&mc.lock);
1622 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1624 if (mc.moving_task && current != mc.moving_task) {
1625 if (mem_cgroup_under_move(memcg)) {
1627 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1628 /* moving charge context might have finished. */
1631 finish_wait(&mc.waitq, &wait);
1639 * Take this lock when
1640 * - a code tries to modify page's memcg while it's USED.
1641 * - a code tries to modify page state accounting in a memcg.
1642 * see mem_cgroup_stolen(), too.
1644 static void move_lock_mem_cgroup(struct mem_cgroup *memcg,
1645 unsigned long *flags)
1647 spin_lock_irqsave(&memcg->move_lock, *flags);
1650 static void move_unlock_mem_cgroup(struct mem_cgroup *memcg,
1651 unsigned long *flags)
1653 spin_unlock_irqrestore(&memcg->move_lock, *flags);
1656 #define K(x) ((x) << (PAGE_SHIFT-10))
1658 * mem_cgroup_print_oom_info: Print OOM information relevant to memory controller.
1659 * @memcg: The memory cgroup that went over limit
1660 * @p: Task that is going to be killed
1662 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1665 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1667 struct cgroup *task_cgrp;
1668 struct cgroup *mem_cgrp;
1670 * Need a buffer in BSS, can't rely on allocations. The code relies
1671 * on the assumption that OOM is serialized for memory controller.
1672 * If this assumption is broken, revisit this code.
1674 static char memcg_name[PATH_MAX];
1676 struct mem_cgroup *iter;
1684 mem_cgrp = memcg->css.cgroup;
1685 task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1687 ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1690 * Unfortunately, we are unable to convert to a useful name
1691 * But we'll still print out the usage information
1698 pr_info("Task in %s killed", memcg_name);
1701 ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1709 * Continues from above, so we don't need an KERN_ level
1711 pr_cont(" as a result of limit of %s\n", memcg_name);
1714 pr_info("memory: usage %llukB, limit %llukB, failcnt %llu\n",
1715 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1716 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1717 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1718 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %llu\n",
1719 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1720 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1721 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1722 pr_info("kmem: usage %llukB, limit %llukB, failcnt %llu\n",
1723 res_counter_read_u64(&memcg->kmem, RES_USAGE) >> 10,
1724 res_counter_read_u64(&memcg->kmem, RES_LIMIT) >> 10,
1725 res_counter_read_u64(&memcg->kmem, RES_FAILCNT));
1727 for_each_mem_cgroup_tree(iter, memcg) {
1728 pr_info("Memory cgroup stats");
1731 ret = cgroup_path(iter->css.cgroup, memcg_name, PATH_MAX);
1733 pr_cont(" for %s", memcg_name);
1737 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
1738 if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
1740 pr_cont(" %s:%ldKB", mem_cgroup_stat_names[i],
1741 K(mem_cgroup_read_stat(iter, i)));
1744 for (i = 0; i < NR_LRU_LISTS; i++)
1745 pr_cont(" %s:%luKB", mem_cgroup_lru_names[i],
1746 K(mem_cgroup_nr_lru_pages(iter, BIT(i))));
1753 * This function returns the number of memcg under hierarchy tree. Returns
1754 * 1(self count) if no children.
1756 static int mem_cgroup_count_children(struct mem_cgroup *memcg)
1759 struct mem_cgroup *iter;
1761 for_each_mem_cgroup_tree(iter, memcg)
1767 * Return the memory (and swap, if configured) limit for a memcg.
1769 static u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
1773 limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
1776 * Do not consider swap space if we cannot swap due to swappiness
1778 if (mem_cgroup_swappiness(memcg)) {
1781 limit += total_swap_pages << PAGE_SHIFT;
1782 memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
1785 * If memsw is finite and limits the amount of swap space
1786 * available to this memcg, return that limit.
1788 limit = min(limit, memsw);
1794 static void mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1797 struct mem_cgroup *iter;
1798 unsigned long chosen_points = 0;
1799 unsigned long totalpages;
1800 unsigned int points = 0;
1801 struct task_struct *chosen = NULL;
1804 * If current has a pending SIGKILL or is exiting, then automatically
1805 * select it. The goal is to allow it to allocate so that it may
1806 * quickly exit and free its memory.
1808 if (fatal_signal_pending(current) || current->flags & PF_EXITING) {
1809 set_thread_flag(TIF_MEMDIE);
1813 check_panic_on_oom(CONSTRAINT_MEMCG, gfp_mask, order, NULL);
1814 totalpages = mem_cgroup_get_limit(memcg) >> PAGE_SHIFT ? : 1;
1815 for_each_mem_cgroup_tree(iter, memcg) {
1816 struct cgroup *cgroup = iter->css.cgroup;
1817 struct cgroup_iter it;
1818 struct task_struct *task;
1820 cgroup_iter_start(cgroup, &it);
1821 while ((task = cgroup_iter_next(cgroup, &it))) {
1822 switch (oom_scan_process_thread(task, totalpages, NULL,
1824 case OOM_SCAN_SELECT:
1826 put_task_struct(chosen);
1828 chosen_points = ULONG_MAX;
1829 get_task_struct(chosen);
1831 case OOM_SCAN_CONTINUE:
1833 case OOM_SCAN_ABORT:
1834 cgroup_iter_end(cgroup, &it);
1835 mem_cgroup_iter_break(memcg, iter);
1837 put_task_struct(chosen);
1842 points = oom_badness(task, memcg, NULL, totalpages);
1843 if (points > chosen_points) {
1845 put_task_struct(chosen);
1847 chosen_points = points;
1848 get_task_struct(chosen);
1851 cgroup_iter_end(cgroup, &it);
1856 points = chosen_points * 1000 / totalpages;
1857 oom_kill_process(chosen, gfp_mask, order, points, totalpages, memcg,
1858 NULL, "Memory cgroup out of memory");
1861 static unsigned long mem_cgroup_reclaim(struct mem_cgroup *memcg,
1863 unsigned long flags)
1865 unsigned long total = 0;
1866 bool noswap = false;
1869 if (flags & MEM_CGROUP_RECLAIM_NOSWAP)
1871 if (!(flags & MEM_CGROUP_RECLAIM_SHRINK) && memcg->memsw_is_minimum)
1874 for (loop = 0; loop < MEM_CGROUP_MAX_RECLAIM_LOOPS; loop++) {
1876 drain_all_stock_async(memcg);
1877 total += try_to_free_mem_cgroup_pages(memcg, gfp_mask, noswap);
1879 * Allow limit shrinkers, which are triggered directly
1880 * by userspace, to catch signals and stop reclaim
1881 * after minimal progress, regardless of the margin.
1883 if (total && (flags & MEM_CGROUP_RECLAIM_SHRINK))
1885 if (mem_cgroup_margin(memcg))
1888 * If nothing was reclaimed after two attempts, there
1889 * may be no reclaimable pages in this hierarchy.
1898 * test_mem_cgroup_node_reclaimable
1899 * @memcg: the target memcg
1900 * @nid: the node ID to be checked.
1901 * @noswap : specify true here if the user wants flle only information.
1903 * This function returns whether the specified memcg contains any
1904 * reclaimable pages on a node. Returns true if there are any reclaimable
1905 * pages in the node.
1907 static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
1908 int nid, bool noswap)
1910 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE))
1912 if (noswap || !total_swap_pages)
1914 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON))
1919 #if MAX_NUMNODES > 1
1922 * Always updating the nodemask is not very good - even if we have an empty
1923 * list or the wrong list here, we can start from some node and traverse all
1924 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1927 static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
1931 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1932 * pagein/pageout changes since the last update.
1934 if (!atomic_read(&memcg->numainfo_events))
1936 if (atomic_inc_return(&memcg->numainfo_updating) > 1)
1939 /* make a nodemask where this memcg uses memory from */
1940 memcg->scan_nodes = node_states[N_MEMORY];
1942 for_each_node_mask(nid, node_states[N_MEMORY]) {
1944 if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
1945 node_clear(nid, memcg->scan_nodes);
1948 atomic_set(&memcg->numainfo_events, 0);
1949 atomic_set(&memcg->numainfo_updating, 0);
1953 * Selecting a node where we start reclaim from. Because what we need is just
1954 * reducing usage counter, start from anywhere is O,K. Considering
1955 * memory reclaim from current node, there are pros. and cons.
1957 * Freeing memory from current node means freeing memory from a node which
1958 * we'll use or we've used. So, it may make LRU bad. And if several threads
1959 * hit limits, it will see a contention on a node. But freeing from remote
1960 * node means more costs for memory reclaim because of memory latency.
1962 * Now, we use round-robin. Better algorithm is welcomed.
1964 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1968 mem_cgroup_may_update_nodemask(memcg);
1969 node = memcg->last_scanned_node;
1971 node = next_node(node, memcg->scan_nodes);
1972 if (node == MAX_NUMNODES)
1973 node = first_node(memcg->scan_nodes);
1975 * We call this when we hit limit, not when pages are added to LRU.
1976 * No LRU may hold pages because all pages are UNEVICTABLE or
1977 * memcg is too small and all pages are not on LRU. In that case,
1978 * we use curret node.
1980 if (unlikely(node == MAX_NUMNODES))
1981 node = numa_node_id();
1983 memcg->last_scanned_node = node;
1988 * Check all nodes whether it contains reclaimable pages or not.
1989 * For quick scan, we make use of scan_nodes. This will allow us to skip
1990 * unused nodes. But scan_nodes is lazily updated and may not cotain
1991 * enough new information. We need to do double check.
1993 static bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
1998 * quick check...making use of scan_node.
1999 * We can skip unused nodes.
2001 if (!nodes_empty(memcg->scan_nodes)) {
2002 for (nid = first_node(memcg->scan_nodes);
2004 nid = next_node(nid, memcg->scan_nodes)) {
2006 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
2011 * Check rest of nodes.
2013 for_each_node_state(nid, N_MEMORY) {
2014 if (node_isset(nid, memcg->scan_nodes))
2016 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
2023 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
2028 static bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
2030 return test_mem_cgroup_node_reclaimable(memcg, 0, noswap);
2034 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
2037 unsigned long *total_scanned)
2039 struct mem_cgroup *victim = NULL;
2042 unsigned long excess;
2043 unsigned long nr_scanned;
2044 struct mem_cgroup_reclaim_cookie reclaim = {
2049 excess = res_counter_soft_limit_excess(&root_memcg->res) >> PAGE_SHIFT;
2052 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
2057 * If we have not been able to reclaim
2058 * anything, it might because there are
2059 * no reclaimable pages under this hierarchy
2064 * We want to do more targeted reclaim.
2065 * excess >> 2 is not to excessive so as to
2066 * reclaim too much, nor too less that we keep
2067 * coming back to reclaim from this cgroup
2069 if (total >= (excess >> 2) ||
2070 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
2075 if (!mem_cgroup_reclaimable(victim, false))
2077 total += mem_cgroup_shrink_node_zone(victim, gfp_mask, false,
2079 *total_scanned += nr_scanned;
2080 if (!res_counter_soft_limit_excess(&root_memcg->res))
2083 mem_cgroup_iter_break(root_memcg, victim);
2087 static DEFINE_SPINLOCK(memcg_oom_lock);
2090 * Check OOM-Killer is already running under our hierarchy.
2091 * If someone is running, return false.
2093 static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
2095 struct mem_cgroup *iter, *failed = NULL;
2097 spin_lock(&memcg_oom_lock);
2099 for_each_mem_cgroup_tree(iter, memcg) {
2100 if (iter->oom_lock) {
2102 * this subtree of our hierarchy is already locked
2103 * so we cannot give a lock.
2106 mem_cgroup_iter_break(memcg, iter);
2109 iter->oom_lock = true;
2114 * OK, we failed to lock the whole subtree so we have
2115 * to clean up what we set up to the failing subtree
2117 for_each_mem_cgroup_tree(iter, memcg) {
2118 if (iter == failed) {
2119 mem_cgroup_iter_break(memcg, iter);
2122 iter->oom_lock = false;
2126 spin_unlock(&memcg_oom_lock);
2131 static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
2133 struct mem_cgroup *iter;
2135 spin_lock(&memcg_oom_lock);
2136 for_each_mem_cgroup_tree(iter, memcg)
2137 iter->oom_lock = false;
2138 spin_unlock(&memcg_oom_lock);
2141 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
2143 struct mem_cgroup *iter;
2145 for_each_mem_cgroup_tree(iter, memcg)
2146 atomic_inc(&iter->under_oom);
2149 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
2151 struct mem_cgroup *iter;
2154 * When a new child is created while the hierarchy is under oom,
2155 * mem_cgroup_oom_lock() may not be called. We have to use
2156 * atomic_add_unless() here.
2158 for_each_mem_cgroup_tree(iter, memcg)
2159 atomic_add_unless(&iter->under_oom, -1, 0);
2162 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
2164 struct oom_wait_info {
2165 struct mem_cgroup *memcg;
2169 static int memcg_oom_wake_function(wait_queue_t *wait,
2170 unsigned mode, int sync, void *arg)
2172 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
2173 struct mem_cgroup *oom_wait_memcg;
2174 struct oom_wait_info *oom_wait_info;
2176 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
2177 oom_wait_memcg = oom_wait_info->memcg;
2180 * Both of oom_wait_info->memcg and wake_memcg are stable under us.
2181 * Then we can use css_is_ancestor without taking care of RCU.
2183 if (!mem_cgroup_same_or_subtree(oom_wait_memcg, wake_memcg)
2184 && !mem_cgroup_same_or_subtree(wake_memcg, oom_wait_memcg))
2186 return autoremove_wake_function(wait, mode, sync, arg);
2189 static void memcg_wakeup_oom(struct mem_cgroup *memcg)
2191 atomic_inc(&memcg->oom_wakeups);
2192 /* for filtering, pass "memcg" as argument. */
2193 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
2196 static void memcg_oom_recover(struct mem_cgroup *memcg)
2198 if (memcg && atomic_read(&memcg->under_oom))
2199 memcg_wakeup_oom(memcg);
2202 static void mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
2204 if (!current->memcg_oom.may_oom)
2207 * We are in the middle of the charge context here, so we
2208 * don't want to block when potentially sitting on a callstack
2209 * that holds all kinds of filesystem and mm locks.
2211 * Also, the caller may handle a failed allocation gracefully
2212 * (like optional page cache readahead) and so an OOM killer
2213 * invocation might not even be necessary.
2215 * That's why we don't do anything here except remember the
2216 * OOM context and then deal with it at the end of the page
2217 * fault when the stack is unwound, the locks are released,
2218 * and when we know whether the fault was overall successful.
2220 css_get(&memcg->css);
2221 current->memcg_oom.memcg = memcg;
2222 current->memcg_oom.gfp_mask = mask;
2223 current->memcg_oom.order = order;
2227 * mem_cgroup_oom_synchronize - complete memcg OOM handling
2228 * @handle: actually kill/wait or just clean up the OOM state
2230 * This has to be called at the end of a page fault if the memcg OOM
2231 * handler was enabled.
2233 * Memcg supports userspace OOM handling where failed allocations must
2234 * sleep on a waitqueue until the userspace task resolves the
2235 * situation. Sleeping directly in the charge context with all kinds
2236 * of locks held is not a good idea, instead we remember an OOM state
2237 * in the task and mem_cgroup_oom_synchronize() has to be called at
2238 * the end of the page fault to complete the OOM handling.
2240 * Returns %true if an ongoing memcg OOM situation was detected and
2241 * completed, %false otherwise.
2243 bool mem_cgroup_oom_synchronize(bool handle)
2245 struct mem_cgroup *memcg = current->memcg_oom.memcg;
2246 struct oom_wait_info owait;
2249 /* OOM is global, do not handle */
2256 owait.memcg = memcg;
2257 owait.wait.flags = 0;
2258 owait.wait.func = memcg_oom_wake_function;
2259 owait.wait.private = current;
2260 INIT_LIST_HEAD(&owait.wait.task_list);
2262 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
2263 mem_cgroup_mark_under_oom(memcg);
2265 locked = mem_cgroup_oom_trylock(memcg);
2268 mem_cgroup_oom_notify(memcg);
2270 if (locked && !memcg->oom_kill_disable) {
2271 mem_cgroup_unmark_under_oom(memcg);
2272 finish_wait(&memcg_oom_waitq, &owait.wait);
2273 mem_cgroup_out_of_memory(memcg, current->memcg_oom.gfp_mask,
2274 current->memcg_oom.order);
2277 mem_cgroup_unmark_under_oom(memcg);
2278 finish_wait(&memcg_oom_waitq, &owait.wait);
2282 mem_cgroup_oom_unlock(memcg);
2284 * There is no guarantee that an OOM-lock contender
2285 * sees the wakeups triggered by the OOM kill
2286 * uncharges. Wake any sleepers explicitely.
2288 memcg_oom_recover(memcg);
2291 current->memcg_oom.memcg = NULL;
2292 css_put(&memcg->css);
2297 * Currently used to update mapped file statistics, but the routine can be
2298 * generalized to update other statistics as well.
2300 * Notes: Race condition
2302 * We usually use page_cgroup_lock() for accessing page_cgroup member but
2303 * it tends to be costly. But considering some conditions, we doesn't need
2304 * to do so _always_.
2306 * Considering "charge", lock_page_cgroup() is not required because all
2307 * file-stat operations happen after a page is attached to radix-tree. There
2308 * are no race with "charge".
2310 * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
2311 * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
2312 * if there are race with "uncharge". Statistics itself is properly handled
2315 * Considering "move", this is an only case we see a race. To make the race
2316 * small, we check mm->moving_account and detect there are possibility of race
2317 * If there is, we take a lock.
2320 void __mem_cgroup_begin_update_page_stat(struct page *page,
2321 bool *locked, unsigned long *flags)
2323 struct mem_cgroup *memcg;
2324 struct page_cgroup *pc;
2326 pc = lookup_page_cgroup(page);
2328 memcg = pc->mem_cgroup;
2329 if (unlikely(!memcg || !PageCgroupUsed(pc)))
2332 * If this memory cgroup is not under account moving, we don't
2333 * need to take move_lock_mem_cgroup(). Because we already hold
2334 * rcu_read_lock(), any calls to move_account will be delayed until
2335 * rcu_read_unlock() if mem_cgroup_stolen() == true.
2337 if (!mem_cgroup_stolen(memcg))
2340 move_lock_mem_cgroup(memcg, flags);
2341 if (memcg != pc->mem_cgroup || !PageCgroupUsed(pc)) {
2342 move_unlock_mem_cgroup(memcg, flags);
2348 void __mem_cgroup_end_update_page_stat(struct page *page, unsigned long *flags)
2350 struct page_cgroup *pc = lookup_page_cgroup(page);
2353 * It's guaranteed that pc->mem_cgroup never changes while
2354 * lock is held because a routine modifies pc->mem_cgroup
2355 * should take move_lock_mem_cgroup().
2357 move_unlock_mem_cgroup(pc->mem_cgroup, flags);
2360 void mem_cgroup_update_page_stat(struct page *page,
2361 enum mem_cgroup_page_stat_item idx, int val)
2363 struct mem_cgroup *memcg;
2364 struct page_cgroup *pc = lookup_page_cgroup(page);
2365 unsigned long uninitialized_var(flags);
2367 if (mem_cgroup_disabled())
2370 memcg = pc->mem_cgroup;
2371 if (unlikely(!memcg || !PageCgroupUsed(pc)))
2375 case MEMCG_NR_FILE_MAPPED:
2376 idx = MEM_CGROUP_STAT_FILE_MAPPED;
2382 this_cpu_add(memcg->stat->count[idx], val);
2386 * size of first charge trial. "32" comes from vmscan.c's magic value.
2387 * TODO: maybe necessary to use big numbers in big irons.
2389 #define CHARGE_BATCH 32U
2390 struct memcg_stock_pcp {
2391 struct mem_cgroup *cached; /* this never be root cgroup */
2392 unsigned int nr_pages;
2393 struct work_struct work;
2394 unsigned long flags;
2395 #define FLUSHING_CACHED_CHARGE 0
2397 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
2398 static DEFINE_MUTEX(percpu_charge_mutex);
2401 * consume_stock: Try to consume stocked charge on this cpu.
2402 * @memcg: memcg to consume from.
2403 * @nr_pages: how many pages to charge.
2405 * The charges will only happen if @memcg matches the current cpu's memcg
2406 * stock, and at least @nr_pages are available in that stock. Failure to
2407 * service an allocation will refill the stock.
2409 * returns true if successful, false otherwise.
2411 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2413 struct memcg_stock_pcp *stock;
2416 if (nr_pages > CHARGE_BATCH)
2419 stock = &get_cpu_var(memcg_stock);
2420 if (memcg == stock->cached && stock->nr_pages >= nr_pages)
2421 stock->nr_pages -= nr_pages;
2422 else /* need to call res_counter_charge */
2424 put_cpu_var(memcg_stock);
2429 * Returns stocks cached in percpu to res_counter and reset cached information.
2431 static void drain_stock(struct memcg_stock_pcp *stock)
2433 struct mem_cgroup *old = stock->cached;
2435 if (stock->nr_pages) {
2436 unsigned long bytes = stock->nr_pages * PAGE_SIZE;
2438 res_counter_uncharge(&old->res, bytes);
2439 if (do_swap_account)
2440 res_counter_uncharge(&old->memsw, bytes);
2441 stock->nr_pages = 0;
2443 stock->cached = NULL;
2447 * This must be called under preempt disabled or must be called by
2448 * a thread which is pinned to local cpu.
2450 static void drain_local_stock(struct work_struct *dummy)
2452 struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
2454 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2457 static void __init memcg_stock_init(void)
2461 for_each_possible_cpu(cpu) {
2462 struct memcg_stock_pcp *stock =
2463 &per_cpu(memcg_stock, cpu);
2464 INIT_WORK(&stock->work, drain_local_stock);
2469 * Cache charges(val) which is from res_counter, to local per_cpu area.
2470 * This will be consumed by consume_stock() function, later.
2472 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2474 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
2476 if (stock->cached != memcg) { /* reset if necessary */
2478 stock->cached = memcg;
2480 stock->nr_pages += nr_pages;
2481 put_cpu_var(memcg_stock);
2485 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2486 * of the hierarchy under it. sync flag says whether we should block
2487 * until the work is done.
2489 static void drain_all_stock(struct mem_cgroup *root_memcg, bool sync)
2493 /* Notify other cpus that system-wide "drain" is running */
2496 for_each_online_cpu(cpu) {
2497 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2498 struct mem_cgroup *memcg;
2500 memcg = stock->cached;
2501 if (!memcg || !stock->nr_pages)
2503 if (!mem_cgroup_same_or_subtree(root_memcg, memcg))
2505 if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2507 drain_local_stock(&stock->work);
2509 schedule_work_on(cpu, &stock->work);
2517 for_each_online_cpu(cpu) {
2518 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2519 if (test_bit(FLUSHING_CACHED_CHARGE, &stock->flags))
2520 flush_work(&stock->work);
2527 * Tries to drain stocked charges in other cpus. This function is asynchronous
2528 * and just put a work per cpu for draining localy on each cpu. Caller can
2529 * expects some charges will be back to res_counter later but cannot wait for
2532 static void drain_all_stock_async(struct mem_cgroup *root_memcg)
2535 * If someone calls draining, avoid adding more kworker runs.
2537 if (!mutex_trylock(&percpu_charge_mutex))
2539 drain_all_stock(root_memcg, false);
2540 mutex_unlock(&percpu_charge_mutex);
2543 /* This is a synchronous drain interface. */
2544 static void drain_all_stock_sync(struct mem_cgroup *root_memcg)
2546 /* called when force_empty is called */
2547 mutex_lock(&percpu_charge_mutex);
2548 drain_all_stock(root_memcg, true);
2549 mutex_unlock(&percpu_charge_mutex);
2553 * This function drains percpu counter value from DEAD cpu and
2554 * move it to local cpu. Note that this function can be preempted.
2556 static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *memcg, int cpu)
2560 spin_lock(&memcg->pcp_counter_lock);
2561 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
2562 long x = per_cpu(memcg->stat->count[i], cpu);
2564 per_cpu(memcg->stat->count[i], cpu) = 0;
2565 memcg->nocpu_base.count[i] += x;
2567 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
2568 unsigned long x = per_cpu(memcg->stat->events[i], cpu);
2570 per_cpu(memcg->stat->events[i], cpu) = 0;
2571 memcg->nocpu_base.events[i] += x;
2573 spin_unlock(&memcg->pcp_counter_lock);
2576 static int __cpuinit memcg_cpu_hotplug_callback(struct notifier_block *nb,
2577 unsigned long action,
2580 int cpu = (unsigned long)hcpu;
2581 struct memcg_stock_pcp *stock;
2582 struct mem_cgroup *iter;
2584 if (action == CPU_ONLINE)
2587 if (action != CPU_DEAD && action != CPU_DEAD_FROZEN)
2590 for_each_mem_cgroup(iter)
2591 mem_cgroup_drain_pcp_counter(iter, cpu);
2593 stock = &per_cpu(memcg_stock, cpu);
2599 /* See __mem_cgroup_try_charge() for details */
2601 CHARGE_OK, /* success */
2602 CHARGE_RETRY, /* need to retry but retry is not bad */
2603 CHARGE_NOMEM, /* we can't do more. return -ENOMEM */
2604 CHARGE_WOULDBLOCK, /* GFP_WAIT wasn't set and no enough res. */
2607 static int mem_cgroup_do_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2608 unsigned int nr_pages, unsigned int min_pages,
2611 unsigned long csize = nr_pages * PAGE_SIZE;
2612 struct mem_cgroup *mem_over_limit;
2613 struct res_counter *fail_res;
2614 unsigned long flags = 0;
2617 ret = res_counter_charge(&memcg->res, csize, &fail_res);
2620 if (!do_swap_account)
2622 ret = res_counter_charge(&memcg->memsw, csize, &fail_res);
2626 res_counter_uncharge(&memcg->res, csize);
2627 mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw);
2628 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
2630 mem_over_limit = mem_cgroup_from_res_counter(fail_res, res);
2632 * Never reclaim on behalf of optional batching, retry with a
2633 * single page instead.
2635 if (nr_pages > min_pages)
2636 return CHARGE_RETRY;
2638 if (!(gfp_mask & __GFP_WAIT))
2639 return CHARGE_WOULDBLOCK;
2641 if (gfp_mask & __GFP_NORETRY)
2642 return CHARGE_NOMEM;
2644 ret = mem_cgroup_reclaim(mem_over_limit, gfp_mask, flags);
2645 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2646 return CHARGE_RETRY;
2648 * Even though the limit is exceeded at this point, reclaim
2649 * may have been able to free some pages. Retry the charge
2650 * before killing the task.
2652 * Only for regular pages, though: huge pages are rather
2653 * unlikely to succeed so close to the limit, and we fall back
2654 * to regular pages anyway in case of failure.
2656 if (nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER) && ret)
2657 return CHARGE_RETRY;
2660 * At task move, charge accounts can be doubly counted. So, it's
2661 * better to wait until the end of task_move if something is going on.
2663 if (mem_cgroup_wait_acct_move(mem_over_limit))
2664 return CHARGE_RETRY;
2667 mem_cgroup_oom(mem_over_limit, gfp_mask, get_order(csize));
2669 return CHARGE_NOMEM;
2673 * __mem_cgroup_try_charge() does
2674 * 1. detect memcg to be charged against from passed *mm and *ptr,
2675 * 2. update res_counter
2676 * 3. call memory reclaim if necessary.
2678 * In some special case, if the task is fatal, fatal_signal_pending() or
2679 * has TIF_MEMDIE, this function returns -EINTR while writing root_mem_cgroup
2680 * to *ptr. There are two reasons for this. 1: fatal threads should quit as soon
2681 * as possible without any hazards. 2: all pages should have a valid
2682 * pc->mem_cgroup. If mm is NULL and the caller doesn't pass a valid memcg
2683 * pointer, that is treated as a charge to root_mem_cgroup.
2685 * So __mem_cgroup_try_charge() will return
2686 * 0 ... on success, filling *ptr with a valid memcg pointer.
2687 * -ENOMEM ... charge failure because of resource limits.
2688 * -EINTR ... if thread is fatal. *ptr is filled with root_mem_cgroup.
2690 * Unlike the exported interface, an "oom" parameter is added. if oom==true,
2691 * the oom-killer can be invoked.
2693 static int __mem_cgroup_try_charge(struct mm_struct *mm,
2695 unsigned int nr_pages,
2696 struct mem_cgroup **ptr,
2699 unsigned int batch = max(CHARGE_BATCH, nr_pages);
2700 int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2701 struct mem_cgroup *memcg = NULL;
2705 * Unlike gloval-vm's OOM-kill, we're not in memory shortage
2706 * in system level. So, allow to go ahead dying process in addition to
2709 if (unlikely(test_thread_flag(TIF_MEMDIE)
2710 || fatal_signal_pending(current)))
2713 if (unlikely(task_in_memcg_oom(current)))
2717 * We always charge the cgroup the mm_struct belongs to.
2718 * The mm_struct's mem_cgroup changes on task migration if the
2719 * thread group leader migrates. It's possible that mm is not
2720 * set, if so charge the root memcg (happens for pagecache usage).
2723 *ptr = root_mem_cgroup;
2725 if (*ptr) { /* css should be a valid one */
2727 if (mem_cgroup_is_root(memcg))
2729 if (consume_stock(memcg, nr_pages))
2731 css_get(&memcg->css);
2733 struct task_struct *p;
2736 p = rcu_dereference(mm->owner);
2738 * Because we don't have task_lock(), "p" can exit.
2739 * In that case, "memcg" can point to root or p can be NULL with
2740 * race with swapoff. Then, we have small risk of mis-accouning.
2741 * But such kind of mis-account by race always happens because
2742 * we don't have cgroup_mutex(). It's overkill and we allo that
2744 * (*) swapoff at el will charge against mm-struct not against
2745 * task-struct. So, mm->owner can be NULL.
2747 memcg = mem_cgroup_from_task(p);
2749 memcg = root_mem_cgroup;
2750 if (mem_cgroup_is_root(memcg)) {
2754 if (consume_stock(memcg, nr_pages)) {
2756 * It seems dagerous to access memcg without css_get().
2757 * But considering how consume_stok works, it's not
2758 * necessary. If consume_stock success, some charges
2759 * from this memcg are cached on this cpu. So, we
2760 * don't need to call css_get()/css_tryget() before
2761 * calling consume_stock().
2766 /* after here, we may be blocked. we need to get refcnt */
2767 if (!css_tryget(&memcg->css)) {
2775 bool invoke_oom = oom && !nr_oom_retries;
2777 /* If killed, bypass charge */
2778 if (fatal_signal_pending(current)) {
2779 css_put(&memcg->css);
2783 ret = mem_cgroup_do_charge(memcg, gfp_mask, batch,
2784 nr_pages, invoke_oom);
2788 case CHARGE_RETRY: /* not in OOM situation but retry */
2790 css_put(&memcg->css);
2793 case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
2794 css_put(&memcg->css);
2796 case CHARGE_NOMEM: /* OOM routine works */
2797 if (!oom || invoke_oom) {
2798 css_put(&memcg->css);
2804 } while (ret != CHARGE_OK);
2806 if (batch > nr_pages)
2807 refill_stock(memcg, batch - nr_pages);
2808 css_put(&memcg->css);
2816 *ptr = root_mem_cgroup;
2821 * Somemtimes we have to undo a charge we got by try_charge().
2822 * This function is for that and do uncharge, put css's refcnt.
2823 * gotten by try_charge().
2825 static void __mem_cgroup_cancel_charge(struct mem_cgroup *memcg,
2826 unsigned int nr_pages)
2828 if (!mem_cgroup_is_root(memcg)) {
2829 unsigned long bytes = nr_pages * PAGE_SIZE;
2831 res_counter_uncharge(&memcg->res, bytes);
2832 if (do_swap_account)
2833 res_counter_uncharge(&memcg->memsw, bytes);
2838 * Cancel chrages in this cgroup....doesn't propagate to parent cgroup.
2839 * This is useful when moving usage to parent cgroup.
2841 static void __mem_cgroup_cancel_local_charge(struct mem_cgroup *memcg,
2842 unsigned int nr_pages)
2844 unsigned long bytes = nr_pages * PAGE_SIZE;
2846 if (mem_cgroup_is_root(memcg))
2849 res_counter_uncharge_until(&memcg->res, memcg->res.parent, bytes);
2850 if (do_swap_account)
2851 res_counter_uncharge_until(&memcg->memsw,
2852 memcg->memsw.parent, bytes);
2856 * A helper function to get mem_cgroup from ID. must be called under
2857 * rcu_read_lock(). The caller is responsible for calling css_tryget if
2858 * the mem_cgroup is used for charging. (dropping refcnt from swap can be
2859 * called against removed memcg.)
2861 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
2863 struct cgroup_subsys_state *css;
2865 /* ID 0 is unused ID */
2868 css = css_lookup(&mem_cgroup_subsys, id);
2871 return mem_cgroup_from_css(css);
2874 struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
2876 struct mem_cgroup *memcg = NULL;
2877 struct page_cgroup *pc;
2881 VM_BUG_ON(!PageLocked(page));
2883 pc = lookup_page_cgroup(page);
2884 lock_page_cgroup(pc);
2885 if (PageCgroupUsed(pc)) {
2886 memcg = pc->mem_cgroup;
2887 if (memcg && !css_tryget(&memcg->css))
2889 } else if (PageSwapCache(page)) {
2890 ent.val = page_private(page);
2891 id = lookup_swap_cgroup_id(ent);
2893 memcg = mem_cgroup_lookup(id);
2894 if (memcg && !css_tryget(&memcg->css))
2898 unlock_page_cgroup(pc);
2902 static void __mem_cgroup_commit_charge(struct mem_cgroup *memcg,
2904 unsigned int nr_pages,
2905 enum charge_type ctype,
2908 struct page_cgroup *pc = lookup_page_cgroup(page);
2909 struct zone *uninitialized_var(zone);
2910 struct lruvec *lruvec;
2911 bool was_on_lru = false;
2914 lock_page_cgroup(pc);
2915 VM_BUG_ON(PageCgroupUsed(pc));
2917 * we don't need page_cgroup_lock about tail pages, becase they are not
2918 * accessed by any other context at this point.
2922 * In some cases, SwapCache and FUSE(splice_buf->radixtree), the page
2923 * may already be on some other mem_cgroup's LRU. Take care of it.
2926 zone = page_zone(page);
2927 spin_lock_irq(&zone->lru_lock);
2928 if (PageLRU(page)) {
2929 lruvec = mem_cgroup_zone_lruvec(zone, pc->mem_cgroup);
2931 del_page_from_lru_list(page, lruvec, page_lru(page));
2936 pc->mem_cgroup = memcg;
2938 * We access a page_cgroup asynchronously without lock_page_cgroup().
2939 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
2940 * is accessed after testing USED bit. To make pc->mem_cgroup visible
2941 * before USED bit, we need memory barrier here.
2942 * See mem_cgroup_add_lru_list(), etc.
2945 SetPageCgroupUsed(pc);
2949 lruvec = mem_cgroup_zone_lruvec(zone, pc->mem_cgroup);
2950 VM_BUG_ON(PageLRU(page));
2952 add_page_to_lru_list(page, lruvec, page_lru(page));
2954 spin_unlock_irq(&zone->lru_lock);
2957 if (ctype == MEM_CGROUP_CHARGE_TYPE_ANON)
2962 mem_cgroup_charge_statistics(memcg, page, anon, nr_pages);
2963 unlock_page_cgroup(pc);
2966 * "charge_statistics" updated event counter. Then, check it.
2967 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
2968 * if they exceeds softlimit.
2970 memcg_check_events(memcg, page);
2973 static DEFINE_MUTEX(set_limit_mutex);
2975 #ifdef CONFIG_MEMCG_KMEM
2976 static inline bool memcg_can_account_kmem(struct mem_cgroup *memcg)
2978 return !mem_cgroup_disabled() && !mem_cgroup_is_root(memcg) &&
2979 (memcg->kmem_account_flags & KMEM_ACCOUNTED_MASK);
2983 * This is a bit cumbersome, but it is rarely used and avoids a backpointer
2984 * in the memcg_cache_params struct.
2986 static struct kmem_cache *memcg_params_to_cache(struct memcg_cache_params *p)
2988 struct kmem_cache *cachep;
2990 VM_BUG_ON(p->is_root_cache);
2991 cachep = p->root_cache;
2992 return cachep->memcg_params->memcg_caches[memcg_cache_id(p->memcg)];
2995 #ifdef CONFIG_SLABINFO
2996 static int mem_cgroup_slabinfo_read(struct cgroup *cont, struct cftype *cft,
2999 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3000 struct memcg_cache_params *params;
3002 if (!memcg_can_account_kmem(memcg))
3005 print_slabinfo_header(m);
3007 mutex_lock(&memcg->slab_caches_mutex);
3008 list_for_each_entry(params, &memcg->memcg_slab_caches, list)
3009 cache_show(memcg_params_to_cache(params), m);
3010 mutex_unlock(&memcg->slab_caches_mutex);
3016 static int memcg_charge_kmem(struct mem_cgroup *memcg, gfp_t gfp, u64 size)
3018 struct res_counter *fail_res;
3019 struct mem_cgroup *_memcg;
3023 ret = res_counter_charge(&memcg->kmem, size, &fail_res);
3028 * Conditions under which we can wait for the oom_killer. Those are
3029 * the same conditions tested by the core page allocator
3031 may_oom = (gfp & __GFP_FS) && !(gfp & __GFP_NORETRY);
3034 ret = __mem_cgroup_try_charge(NULL, gfp, size >> PAGE_SHIFT,
3037 if (ret == -EINTR) {
3039 * __mem_cgroup_try_charge() chosed to bypass to root due to
3040 * OOM kill or fatal signal. Since our only options are to
3041 * either fail the allocation or charge it to this cgroup, do
3042 * it as a temporary condition. But we can't fail. From a
3043 * kmem/slab perspective, the cache has already been selected,
3044 * by mem_cgroup_kmem_get_cache(), so it is too late to change
3047 * This condition will only trigger if the task entered
3048 * memcg_charge_kmem in a sane state, but was OOM-killed during
3049 * __mem_cgroup_try_charge() above. Tasks that were already
3050 * dying when the allocation triggers should have been already
3051 * directed to the root cgroup in memcontrol.h
3053 res_counter_charge_nofail(&memcg->res, size, &fail_res);
3054 if (do_swap_account)
3055 res_counter_charge_nofail(&memcg->memsw, size,
3059 res_counter_uncharge(&memcg->kmem, size);
3064 static void memcg_uncharge_kmem(struct mem_cgroup *memcg, u64 size)
3066 res_counter_uncharge(&memcg->res, size);
3067 if (do_swap_account)
3068 res_counter_uncharge(&memcg->memsw, size);
3071 if (res_counter_uncharge(&memcg->kmem, size))
3074 if (memcg_kmem_test_and_clear_dead(memcg))
3075 mem_cgroup_put(memcg);
3078 void memcg_cache_list_add(struct mem_cgroup *memcg, struct kmem_cache *cachep)
3083 mutex_lock(&memcg->slab_caches_mutex);
3084 list_add(&cachep->memcg_params->list, &memcg->memcg_slab_caches);
3085 mutex_unlock(&memcg->slab_caches_mutex);
3089 * helper for acessing a memcg's index. It will be used as an index in the
3090 * child cache array in kmem_cache, and also to derive its name. This function
3091 * will return -1 when this is not a kmem-limited memcg.
3093 int memcg_cache_id(struct mem_cgroup *memcg)
3095 return memcg ? memcg->kmemcg_id : -1;
3099 * This ends up being protected by the set_limit mutex, during normal
3100 * operation, because that is its main call site.
3102 * But when we create a new cache, we can call this as well if its parent
3103 * is kmem-limited. That will have to hold set_limit_mutex as well.
3105 int memcg_update_cache_sizes(struct mem_cgroup *memcg)
3109 num = ida_simple_get(&kmem_limited_groups,
3110 0, MEMCG_CACHES_MAX_SIZE, GFP_KERNEL);
3114 * After this point, kmem_accounted (that we test atomically in
3115 * the beginning of this conditional), is no longer 0. This
3116 * guarantees only one process will set the following boolean
3117 * to true. We don't need test_and_set because we're protected
3118 * by the set_limit_mutex anyway.
3120 memcg_kmem_set_activated(memcg);
3122 ret = memcg_update_all_caches(num+1);
3124 ida_simple_remove(&kmem_limited_groups, num);
3125 memcg_kmem_clear_activated(memcg);
3129 memcg->kmemcg_id = num;
3130 INIT_LIST_HEAD(&memcg->memcg_slab_caches);
3131 mutex_init(&memcg->slab_caches_mutex);
3135 static size_t memcg_caches_array_size(int num_groups)
3138 if (num_groups <= 0)
3141 size = 2 * num_groups;
3142 if (size < MEMCG_CACHES_MIN_SIZE)
3143 size = MEMCG_CACHES_MIN_SIZE;
3144 else if (size > MEMCG_CACHES_MAX_SIZE)
3145 size = MEMCG_CACHES_MAX_SIZE;
3151 * We should update the current array size iff all caches updates succeed. This
3152 * can only be done from the slab side. The slab mutex needs to be held when
3155 void memcg_update_array_size(int num)
3157 if (num > memcg_limited_groups_array_size)
3158 memcg_limited_groups_array_size = memcg_caches_array_size(num);
3161 static void kmem_cache_destroy_work_func(struct work_struct *w);
3163 int memcg_update_cache_size(struct kmem_cache *s, int num_groups)
3165 struct memcg_cache_params *cur_params = s->memcg_params;
3167 VM_BUG_ON(s->memcg_params && !s->memcg_params->is_root_cache);
3169 if (num_groups > memcg_limited_groups_array_size) {
3171 ssize_t size = memcg_caches_array_size(num_groups);
3173 size *= sizeof(void *);
3174 size += sizeof(struct memcg_cache_params);
3176 s->memcg_params = kzalloc(size, GFP_KERNEL);
3177 if (!s->memcg_params) {
3178 s->memcg_params = cur_params;
3182 s->memcg_params->is_root_cache = true;
3185 * There is the chance it will be bigger than
3186 * memcg_limited_groups_array_size, if we failed an allocation
3187 * in a cache, in which case all caches updated before it, will
3188 * have a bigger array.
3190 * But if that is the case, the data after
3191 * memcg_limited_groups_array_size is certainly unused
3193 for (i = 0; i < memcg_limited_groups_array_size; i++) {
3194 if (!cur_params->memcg_caches[i])
3196 s->memcg_params->memcg_caches[i] =
3197 cur_params->memcg_caches[i];
3201 * Ideally, we would wait until all caches succeed, and only
3202 * then free the old one. But this is not worth the extra
3203 * pointer per-cache we'd have to have for this.
3205 * It is not a big deal if some caches are left with a size
3206 * bigger than the others. And all updates will reset this
3214 int memcg_register_cache(struct mem_cgroup *memcg, struct kmem_cache *s,
3215 struct kmem_cache *root_cache)
3217 size_t size = sizeof(struct memcg_cache_params);
3219 if (!memcg_kmem_enabled())
3223 size += memcg_limited_groups_array_size * sizeof(void *);
3225 s->memcg_params = kzalloc(size, GFP_KERNEL);
3226 if (!s->memcg_params)
3230 s->memcg_params->memcg = memcg;
3231 s->memcg_params->root_cache = root_cache;
3232 INIT_WORK(&s->memcg_params->destroy,
3233 kmem_cache_destroy_work_func);
3235 s->memcg_params->is_root_cache = true;
3240 void memcg_release_cache(struct kmem_cache *s)
3242 struct kmem_cache *root;
3243 struct mem_cgroup *memcg;
3247 * This happens, for instance, when a root cache goes away before we
3250 if (!s->memcg_params)
3253 if (s->memcg_params->is_root_cache)
3256 memcg = s->memcg_params->memcg;
3257 id = memcg_cache_id(memcg);
3259 root = s->memcg_params->root_cache;
3260 root->memcg_params->memcg_caches[id] = NULL;
3262 mutex_lock(&memcg->slab_caches_mutex);
3263 list_del(&s->memcg_params->list);
3264 mutex_unlock(&memcg->slab_caches_mutex);
3266 mem_cgroup_put(memcg);
3268 kfree(s->memcg_params);
3272 * During the creation a new cache, we need to disable our accounting mechanism
3273 * altogether. This is true even if we are not creating, but rather just
3274 * enqueing new caches to be created.
3276 * This is because that process will trigger allocations; some visible, like
3277 * explicit kmallocs to auxiliary data structures, name strings and internal
3278 * cache structures; some well concealed, like INIT_WORK() that can allocate
3279 * objects during debug.
3281 * If any allocation happens during memcg_kmem_get_cache, we will recurse back
3282 * to it. This may not be a bounded recursion: since the first cache creation
3283 * failed to complete (waiting on the allocation), we'll just try to create the
3284 * cache again, failing at the same point.
3286 * memcg_kmem_get_cache is prepared to abort after seeing a positive count of
3287 * memcg_kmem_skip_account. So we enclose anything that might allocate memory
3288 * inside the following two functions.
3290 static inline void memcg_stop_kmem_account(void)
3292 VM_BUG_ON(!current->mm);
3293 current->memcg_kmem_skip_account++;
3296 static inline void memcg_resume_kmem_account(void)
3298 VM_BUG_ON(!current->mm);
3299 current->memcg_kmem_skip_account--;
3302 static void kmem_cache_destroy_work_func(struct work_struct *w)
3304 struct kmem_cache *cachep;
3305 struct memcg_cache_params *p;
3307 p = container_of(w, struct memcg_cache_params, destroy);
3309 cachep = memcg_params_to_cache(p);
3312 * If we get down to 0 after shrink, we could delete right away.
3313 * However, memcg_release_pages() already puts us back in the workqueue
3314 * in that case. If we proceed deleting, we'll get a dangling
3315 * reference, and removing the object from the workqueue in that case
3316 * is unnecessary complication. We are not a fast path.
3318 * Note that this case is fundamentally different from racing with
3319 * shrink_slab(): if memcg_cgroup_destroy_cache() is called in
3320 * kmem_cache_shrink, not only we would be reinserting a dead cache
3321 * into the queue, but doing so from inside the worker racing to
3324 * So if we aren't down to zero, we'll just schedule a worker and try
3327 if (atomic_read(&cachep->memcg_params->nr_pages) != 0) {
3328 kmem_cache_shrink(cachep);
3329 if (atomic_read(&cachep->memcg_params->nr_pages) == 0)
3332 kmem_cache_destroy(cachep);
3335 void mem_cgroup_destroy_cache(struct kmem_cache *cachep)
3337 if (!cachep->memcg_params->dead)
3341 * There are many ways in which we can get here.
3343 * We can get to a memory-pressure situation while the delayed work is
3344 * still pending to run. The vmscan shrinkers can then release all
3345 * cache memory and get us to destruction. If this is the case, we'll
3346 * be executed twice, which is a bug (the second time will execute over
3347 * bogus data). In this case, cancelling the work should be fine.
3349 * But we can also get here from the worker itself, if
3350 * kmem_cache_shrink is enough to shake all the remaining objects and
3351 * get the page count to 0. In this case, we'll deadlock if we try to
3352 * cancel the work (the worker runs with an internal lock held, which
3353 * is the same lock we would hold for cancel_work_sync().)
3355 * Since we can't possibly know who got us here, just refrain from
3356 * running if there is already work pending
3358 if (work_pending(&cachep->memcg_params->destroy))
3361 * We have to defer the actual destroying to a workqueue, because
3362 * we might currently be in a context that cannot sleep.
3364 schedule_work(&cachep->memcg_params->destroy);
3368 * This lock protects updaters, not readers. We want readers to be as fast as
3369 * they can, and they will either see NULL or a valid cache value. Our model
3370 * allow them to see NULL, in which case the root memcg will be selected.
3372 * We need this lock because multiple allocations to the same cache from a non
3373 * will span more than one worker. Only one of them can create the cache.
3375 static DEFINE_MUTEX(memcg_cache_mutex);
3378 * Called with memcg_cache_mutex held
3380 static struct kmem_cache *kmem_cache_dup(struct mem_cgroup *memcg,
3381 struct kmem_cache *s)
3383 struct kmem_cache *new;
3384 static char *tmp_name = NULL;
3386 lockdep_assert_held(&memcg_cache_mutex);
3389 * kmem_cache_create_memcg duplicates the given name and
3390 * cgroup_name for this name requires RCU context.
3391 * This static temporary buffer is used to prevent from
3392 * pointless shortliving allocation.
3395 tmp_name = kmalloc(PATH_MAX, GFP_KERNEL);
3401 snprintf(tmp_name, PATH_MAX, "%s(%d:%s)", s->name,
3402 memcg_cache_id(memcg), cgroup_name(memcg->css.cgroup));
3405 new = kmem_cache_create_memcg(memcg, tmp_name, s->object_size, s->align,
3406 (s->flags & ~SLAB_PANIC), s->ctor, s);
3409 new->allocflags |= __GFP_KMEMCG;
3414 static struct kmem_cache *memcg_create_kmem_cache(struct mem_cgroup *memcg,
3415 struct kmem_cache *cachep)
3417 struct kmem_cache *new_cachep;
3420 BUG_ON(!memcg_can_account_kmem(memcg));
3422 idx = memcg_cache_id(memcg);
3424 mutex_lock(&memcg_cache_mutex);
3425 new_cachep = cachep->memcg_params->memcg_caches[idx];
3429 new_cachep = kmem_cache_dup(memcg, cachep);
3430 if (new_cachep == NULL) {
3431 new_cachep = cachep;
3435 mem_cgroup_get(memcg);
3436 atomic_set(&new_cachep->memcg_params->nr_pages , 0);
3438 cachep->memcg_params->memcg_caches[idx] = new_cachep;
3440 * the readers won't lock, make sure everybody sees the updated value,
3441 * so they won't put stuff in the queue again for no reason
3445 mutex_unlock(&memcg_cache_mutex);
3449 void kmem_cache_destroy_memcg_children(struct kmem_cache *s)
3451 struct kmem_cache *c;
3454 if (!s->memcg_params)
3456 if (!s->memcg_params->is_root_cache)
3460 * If the cache is being destroyed, we trust that there is no one else
3461 * requesting objects from it. Even if there are, the sanity checks in
3462 * kmem_cache_destroy should caught this ill-case.
3464 * Still, we don't want anyone else freeing memcg_caches under our
3465 * noses, which can happen if a new memcg comes to life. As usual,
3466 * we'll take the set_limit_mutex to protect ourselves against this.
3468 mutex_lock(&set_limit_mutex);
3469 for (i = 0; i < memcg_limited_groups_array_size; i++) {
3470 c = s->memcg_params->memcg_caches[i];
3475 * We will now manually delete the caches, so to avoid races
3476 * we need to cancel all pending destruction workers and
3477 * proceed with destruction ourselves.
3479 * kmem_cache_destroy() will call kmem_cache_shrink internally,
3480 * and that could spawn the workers again: it is likely that
3481 * the cache still have active pages until this very moment.
3482 * This would lead us back to mem_cgroup_destroy_cache.
3484 * But that will not execute at all if the "dead" flag is not
3485 * set, so flip it down to guarantee we are in control.
3487 c->memcg_params->dead = false;
3488 cancel_work_sync(&c->memcg_params->destroy);
3489 kmem_cache_destroy(c);
3491 mutex_unlock(&set_limit_mutex);
3494 struct create_work {
3495 struct mem_cgroup *memcg;
3496 struct kmem_cache *cachep;
3497 struct work_struct work;
3500 static void mem_cgroup_destroy_all_caches(struct mem_cgroup *memcg)
3502 struct kmem_cache *cachep;
3503 struct memcg_cache_params *params;
3505 if (!memcg_kmem_is_active(memcg))
3508 mutex_lock(&memcg->slab_caches_mutex);
3509 list_for_each_entry(params, &memcg->memcg_slab_caches, list) {
3510 cachep = memcg_params_to_cache(params);
3511 cachep->memcg_params->dead = true;
3512 schedule_work(&cachep->memcg_params->destroy);
3514 mutex_unlock(&memcg->slab_caches_mutex);
3517 static void memcg_create_cache_work_func(struct work_struct *w)
3519 struct create_work *cw;
3521 cw = container_of(w, struct create_work, work);
3522 memcg_create_kmem_cache(cw->memcg, cw->cachep);
3523 /* Drop the reference gotten when we enqueued. */
3524 css_put(&cw->memcg->css);
3529 * Enqueue the creation of a per-memcg kmem_cache.
3531 static void __memcg_create_cache_enqueue(struct mem_cgroup *memcg,
3532 struct kmem_cache *cachep)
3534 struct create_work *cw;
3536 cw = kmalloc(sizeof(struct create_work), GFP_NOWAIT);
3538 css_put(&memcg->css);
3543 cw->cachep = cachep;
3545 INIT_WORK(&cw->work, memcg_create_cache_work_func);
3546 schedule_work(&cw->work);
3549 static void memcg_create_cache_enqueue(struct mem_cgroup *memcg,
3550 struct kmem_cache *cachep)
3553 * We need to stop accounting when we kmalloc, because if the
3554 * corresponding kmalloc cache is not yet created, the first allocation
3555 * in __memcg_create_cache_enqueue will recurse.
3557 * However, it is better to enclose the whole function. Depending on
3558 * the debugging options enabled, INIT_WORK(), for instance, can
3559 * trigger an allocation. This too, will make us recurse. Because at
3560 * this point we can't allow ourselves back into memcg_kmem_get_cache,
3561 * the safest choice is to do it like this, wrapping the whole function.
3563 memcg_stop_kmem_account();
3564 __memcg_create_cache_enqueue(memcg, cachep);
3565 memcg_resume_kmem_account();
3568 * Return the kmem_cache we're supposed to use for a slab allocation.
3569 * We try to use the current memcg's version of the cache.
3571 * If the cache does not exist yet, if we are the first user of it,
3572 * we either create it immediately, if possible, or create it asynchronously
3574 * In the latter case, we will let the current allocation go through with
3575 * the original cache.
3577 * Can't be called in interrupt context or from kernel threads.
3578 * This function needs to be called with rcu_read_lock() held.
3580 struct kmem_cache *__memcg_kmem_get_cache(struct kmem_cache *cachep,
3583 struct mem_cgroup *memcg;
3586 VM_BUG_ON(!cachep->memcg_params);
3587 VM_BUG_ON(!cachep->memcg_params->is_root_cache);
3589 if (!current->mm || current->memcg_kmem_skip_account)
3593 memcg = mem_cgroup_from_task(rcu_dereference(current->mm->owner));
3595 if (!memcg_can_account_kmem(memcg))
3598 idx = memcg_cache_id(memcg);
3601 * barrier to mare sure we're always seeing the up to date value. The
3602 * code updating memcg_caches will issue a write barrier to match this.
3604 read_barrier_depends();
3605 if (likely(cachep->memcg_params->memcg_caches[idx])) {
3606 cachep = cachep->memcg_params->memcg_caches[idx];
3610 /* The corresponding put will be done in the workqueue. */
3611 if (!css_tryget(&memcg->css))
3616 * If we are in a safe context (can wait, and not in interrupt
3617 * context), we could be be predictable and return right away.
3618 * This would guarantee that the allocation being performed
3619 * already belongs in the new cache.
3621 * However, there are some clashes that can arrive from locking.
3622 * For instance, because we acquire the slab_mutex while doing
3623 * kmem_cache_dup, this means no further allocation could happen
3624 * with the slab_mutex held.
3626 * Also, because cache creation issue get_online_cpus(), this
3627 * creates a lock chain: memcg_slab_mutex -> cpu_hotplug_mutex,
3628 * that ends up reversed during cpu hotplug. (cpuset allocates
3629 * a bunch of GFP_KERNEL memory during cpuup). Due to all that,
3630 * better to defer everything.
3632 memcg_create_cache_enqueue(memcg, cachep);
3638 EXPORT_SYMBOL(__memcg_kmem_get_cache);
3641 * We need to verify if the allocation against current->mm->owner's memcg is
3642 * possible for the given order. But the page is not allocated yet, so we'll
3643 * need a further commit step to do the final arrangements.
3645 * It is possible for the task to switch cgroups in this mean time, so at
3646 * commit time, we can't rely on task conversion any longer. We'll then use
3647 * the handle argument to return to the caller which cgroup we should commit
3648 * against. We could also return the memcg directly and avoid the pointer
3649 * passing, but a boolean return value gives better semantics considering
3650 * the compiled-out case as well.
3652 * Returning true means the allocation is possible.
3655 __memcg_kmem_newpage_charge(gfp_t gfp, struct mem_cgroup **_memcg, int order)
3657 struct mem_cgroup *memcg;
3661 memcg = try_get_mem_cgroup_from_mm(current->mm);
3664 * very rare case described in mem_cgroup_from_task. Unfortunately there
3665 * isn't much we can do without complicating this too much, and it would
3666 * be gfp-dependent anyway. Just let it go
3668 if (unlikely(!memcg))
3671 if (!memcg_can_account_kmem(memcg)) {
3672 css_put(&memcg->css);
3676 ret = memcg_charge_kmem(memcg, gfp, PAGE_SIZE << order);
3680 css_put(&memcg->css);
3684 void __memcg_kmem_commit_charge(struct page *page, struct mem_cgroup *memcg,
3687 struct page_cgroup *pc;
3689 VM_BUG_ON(mem_cgroup_is_root(memcg));
3691 /* The page allocation failed. Revert */
3693 memcg_uncharge_kmem(memcg, PAGE_SIZE << order);
3697 pc = lookup_page_cgroup(page);
3698 lock_page_cgroup(pc);
3699 pc->mem_cgroup = memcg;
3700 SetPageCgroupUsed(pc);
3701 unlock_page_cgroup(pc);
3704 void __memcg_kmem_uncharge_pages(struct page *page, int order)
3706 struct mem_cgroup *memcg = NULL;
3707 struct page_cgroup *pc;
3710 pc = lookup_page_cgroup(page);
3712 * Fast unlocked return. Theoretically might have changed, have to
3713 * check again after locking.
3715 if (!PageCgroupUsed(pc))
3718 lock_page_cgroup(pc);
3719 if (PageCgroupUsed(pc)) {
3720 memcg = pc->mem_cgroup;
3721 ClearPageCgroupUsed(pc);
3723 unlock_page_cgroup(pc);
3726 * We trust that only if there is a memcg associated with the page, it
3727 * is a valid allocation
3732 VM_BUG_ON(mem_cgroup_is_root(memcg));
3733 memcg_uncharge_kmem(memcg, PAGE_SIZE << order);
3736 static inline void mem_cgroup_destroy_all_caches(struct mem_cgroup *memcg)
3739 #endif /* CONFIG_MEMCG_KMEM */
3741 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3743 #define PCGF_NOCOPY_AT_SPLIT (1 << PCG_LOCK | 1 << PCG_MIGRATION)
3745 * Because tail pages are not marked as "used", set it. We're under
3746 * zone->lru_lock, 'splitting on pmd' and compound_lock.
3747 * charge/uncharge will be never happen and move_account() is done under
3748 * compound_lock(), so we don't have to take care of races.
3750 void mem_cgroup_split_huge_fixup(struct page *head)
3752 struct page_cgroup *head_pc = lookup_page_cgroup(head);
3753 struct page_cgroup *pc;
3754 struct mem_cgroup *memcg;
3757 if (mem_cgroup_disabled())
3760 memcg = head_pc->mem_cgroup;
3761 for (i = 1; i < HPAGE_PMD_NR; i++) {
3763 pc->mem_cgroup = memcg;
3764 smp_wmb();/* see __commit_charge() */
3765 pc->flags = head_pc->flags & ~PCGF_NOCOPY_AT_SPLIT;
3767 __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_RSS_HUGE],
3770 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
3773 * mem_cgroup_move_account - move account of the page
3775 * @nr_pages: number of regular pages (>1 for huge pages)
3776 * @pc: page_cgroup of the page.
3777 * @from: mem_cgroup which the page is moved from.
3778 * @to: mem_cgroup which the page is moved to. @from != @to.
3780 * The caller must confirm following.
3781 * - page is not on LRU (isolate_page() is useful.)
3782 * - compound_lock is held when nr_pages > 1
3784 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
3787 static int mem_cgroup_move_account(struct page *page,
3788 unsigned int nr_pages,
3789 struct page_cgroup *pc,
3790 struct mem_cgroup *from,
3791 struct mem_cgroup *to)
3793 unsigned long flags;
3795 bool anon = PageAnon(page);
3797 VM_BUG_ON(from == to);
3798 VM_BUG_ON(PageLRU(page));
3800 * The page is isolated from LRU. So, collapse function
3801 * will not handle this page. But page splitting can happen.
3802 * Do this check under compound_page_lock(). The caller should
3806 if (nr_pages > 1 && !PageTransHuge(page))
3809 lock_page_cgroup(pc);
3812 if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
3815 move_lock_mem_cgroup(from, &flags);
3817 if (!anon && page_mapped(page)) {
3818 /* Update mapped_file data for mem_cgroup */
3820 __this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
3821 __this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
3824 mem_cgroup_charge_statistics(from, page, anon, -nr_pages);
3826 /* caller should have done css_get */
3827 pc->mem_cgroup = to;
3828 mem_cgroup_charge_statistics(to, page, anon, nr_pages);
3829 move_unlock_mem_cgroup(from, &flags);
3832 unlock_page_cgroup(pc);
3836 memcg_check_events(to, page);
3837 memcg_check_events(from, page);
3843 * mem_cgroup_move_parent - moves page to the parent group
3844 * @page: the page to move
3845 * @pc: page_cgroup of the page
3846 * @child: page's cgroup
3848 * move charges to its parent or the root cgroup if the group has no
3849 * parent (aka use_hierarchy==0).
3850 * Although this might fail (get_page_unless_zero, isolate_lru_page or
3851 * mem_cgroup_move_account fails) the failure is always temporary and
3852 * it signals a race with a page removal/uncharge or migration. In the
3853 * first case the page is on the way out and it will vanish from the LRU
3854 * on the next attempt and the call should be retried later.
3855 * Isolation from the LRU fails only if page has been isolated from
3856 * the LRU since we looked at it and that usually means either global
3857 * reclaim or migration going on. The page will either get back to the
3859 * Finaly mem_cgroup_move_account fails only if the page got uncharged
3860 * (!PageCgroupUsed) or moved to a different group. The page will
3861 * disappear in the next attempt.
3863 static int mem_cgroup_move_parent(struct page *page,
3864 struct page_cgroup *pc,
3865 struct mem_cgroup *child)
3867 struct mem_cgroup *parent;
3868 unsigned int nr_pages;
3869 unsigned long uninitialized_var(flags);
3872 VM_BUG_ON(mem_cgroup_is_root(child));
3875 if (!get_page_unless_zero(page))
3877 if (isolate_lru_page(page))
3880 nr_pages = hpage_nr_pages(page);
3882 parent = parent_mem_cgroup(child);
3884 * If no parent, move charges to root cgroup.
3887 parent = root_mem_cgroup;
3890 VM_BUG_ON(!PageTransHuge(page));
3891 flags = compound_lock_irqsave(page);
3894 ret = mem_cgroup_move_account(page, nr_pages,
3897 __mem_cgroup_cancel_local_charge(child, nr_pages);
3900 compound_unlock_irqrestore(page, flags);
3901 putback_lru_page(page);
3909 * Charge the memory controller for page usage.
3911 * 0 if the charge was successful
3912 * < 0 if the cgroup is over its limit
3914 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
3915 gfp_t gfp_mask, enum charge_type ctype)
3917 struct mem_cgroup *memcg = NULL;
3918 unsigned int nr_pages = 1;
3922 if (PageTransHuge(page)) {
3923 nr_pages <<= compound_order(page);
3924 VM_BUG_ON(!PageTransHuge(page));
3926 * Never OOM-kill a process for a huge page. The
3927 * fault handler will fall back to regular pages.
3932 ret = __mem_cgroup_try_charge(mm, gfp_mask, nr_pages, &memcg, oom);
3935 __mem_cgroup_commit_charge(memcg, page, nr_pages, ctype, false);
3939 int mem_cgroup_newpage_charge(struct page *page,
3940 struct mm_struct *mm, gfp_t gfp_mask)
3942 if (mem_cgroup_disabled())
3944 VM_BUG_ON(page_mapped(page));
3945 VM_BUG_ON(page->mapping && !PageAnon(page));
3947 return mem_cgroup_charge_common(page, mm, gfp_mask,
3948 MEM_CGROUP_CHARGE_TYPE_ANON);
3952 * While swap-in, try_charge -> commit or cancel, the page is locked.
3953 * And when try_charge() successfully returns, one refcnt to memcg without
3954 * struct page_cgroup is acquired. This refcnt will be consumed by
3955 * "commit()" or removed by "cancel()"
3957 static int __mem_cgroup_try_charge_swapin(struct mm_struct *mm,
3960 struct mem_cgroup **memcgp)
3962 struct mem_cgroup *memcg;
3963 struct page_cgroup *pc;
3966 pc = lookup_page_cgroup(page);
3968 * Every swap fault against a single page tries to charge the
3969 * page, bail as early as possible. shmem_unuse() encounters
3970 * already charged pages, too. The USED bit is protected by
3971 * the page lock, which serializes swap cache removal, which
3972 * in turn serializes uncharging.
3974 if (PageCgroupUsed(pc))
3976 if (!do_swap_account)
3978 memcg = try_get_mem_cgroup_from_page(page);
3982 ret = __mem_cgroup_try_charge(NULL, mask, 1, memcgp, true);
3983 css_put(&memcg->css);
3988 ret = __mem_cgroup_try_charge(mm, mask, 1, memcgp, true);
3994 int mem_cgroup_try_charge_swapin(struct mm_struct *mm, struct page *page,
3995 gfp_t gfp_mask, struct mem_cgroup **memcgp)
3998 if (mem_cgroup_disabled())
4001 * A racing thread's fault, or swapoff, may have already
4002 * updated the pte, and even removed page from swap cache: in
4003 * those cases unuse_pte()'s pte_same() test will fail; but
4004 * there's also a KSM case which does need to charge the page.
4006 if (!PageSwapCache(page)) {
4009 ret = __mem_cgroup_try_charge(mm, gfp_mask, 1, memcgp, true);
4014 return __mem_cgroup_try_charge_swapin(mm, page, gfp_mask, memcgp);
4017 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *memcg)
4019 if (mem_cgroup_disabled())
4023 __mem_cgroup_cancel_charge(memcg, 1);
4027 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *memcg,
4028 enum charge_type ctype)
4030 if (mem_cgroup_disabled())
4035 __mem_cgroup_commit_charge(memcg, page, 1, ctype, true);
4037 * Now swap is on-memory. This means this page may be
4038 * counted both as mem and swap....double count.
4039 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
4040 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
4041 * may call delete_from_swap_cache() before reach here.
4043 if (do_swap_account && PageSwapCache(page)) {
4044 swp_entry_t ent = {.val = page_private(page)};
4045 mem_cgroup_uncharge_swap(ent);
4049 void mem_cgroup_commit_charge_swapin(struct page *page,
4050 struct mem_cgroup *memcg)
4052 __mem_cgroup_commit_charge_swapin(page, memcg,
4053 MEM_CGROUP_CHARGE_TYPE_ANON);
4056 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
4059 struct mem_cgroup *memcg = NULL;
4060 enum charge_type type = MEM_CGROUP_CHARGE_TYPE_CACHE;
4063 if (mem_cgroup_disabled())
4065 if (PageCompound(page))
4068 if (!PageSwapCache(page))
4069 ret = mem_cgroup_charge_common(page, mm, gfp_mask, type);
4070 else { /* page is swapcache/shmem */
4071 ret = __mem_cgroup_try_charge_swapin(mm, page,
4074 __mem_cgroup_commit_charge_swapin(page, memcg, type);
4079 static void mem_cgroup_do_uncharge(struct mem_cgroup *memcg,
4080 unsigned int nr_pages,
4081 const enum charge_type ctype)
4083 struct memcg_batch_info *batch = NULL;
4084 bool uncharge_memsw = true;
4086 /* If swapout, usage of swap doesn't decrease */
4087 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
4088 uncharge_memsw = false;
4090 batch = ¤t->memcg_batch;
4092 * In usual, we do css_get() when we remember memcg pointer.
4093 * But in this case, we keep res->usage until end of a series of
4094 * uncharges. Then, it's ok to ignore memcg's refcnt.
4097 batch->memcg = memcg;
4099 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
4100 * In those cases, all pages freed continuously can be expected to be in
4101 * the same cgroup and we have chance to coalesce uncharges.
4102 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
4103 * because we want to do uncharge as soon as possible.
4106 if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
4107 goto direct_uncharge;
4110 goto direct_uncharge;
4113 * In typical case, batch->memcg == mem. This means we can
4114 * merge a series of uncharges to an uncharge of res_counter.
4115 * If not, we uncharge res_counter ony by one.
4117 if (batch->memcg != memcg)
4118 goto direct_uncharge;
4119 /* remember freed charge and uncharge it later */
4122 batch->memsw_nr_pages++;
4125 res_counter_uncharge(&memcg->res, nr_pages * PAGE_SIZE);
4127 res_counter_uncharge(&memcg->memsw, nr_pages * PAGE_SIZE);
4128 if (unlikely(batch->memcg != memcg))
4129 memcg_oom_recover(memcg);
4133 * uncharge if !page_mapped(page)
4135 static struct mem_cgroup *
4136 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype,
4139 struct mem_cgroup *memcg = NULL;
4140 unsigned int nr_pages = 1;
4141 struct page_cgroup *pc;
4144 if (mem_cgroup_disabled())
4147 if (PageTransHuge(page)) {
4148 nr_pages <<= compound_order(page);
4149 VM_BUG_ON(!PageTransHuge(page));
4152 * Check if our page_cgroup is valid
4154 pc = lookup_page_cgroup(page);
4155 if (unlikely(!PageCgroupUsed(pc)))
4158 lock_page_cgroup(pc);
4160 memcg = pc->mem_cgroup;
4162 if (!PageCgroupUsed(pc))
4165 anon = PageAnon(page);
4168 case MEM_CGROUP_CHARGE_TYPE_ANON:
4170 * Generally PageAnon tells if it's the anon statistics to be
4171 * updated; but sometimes e.g. mem_cgroup_uncharge_page() is
4172 * used before page reached the stage of being marked PageAnon.
4176 case MEM_CGROUP_CHARGE_TYPE_DROP:
4177 /* See mem_cgroup_prepare_migration() */
4178 if (page_mapped(page))
4181 * Pages under migration may not be uncharged. But
4182 * end_migration() /must/ be the one uncharging the
4183 * unused post-migration page and so it has to call
4184 * here with the migration bit still set. See the
4185 * res_counter handling below.
4187 if (!end_migration && PageCgroupMigration(pc))
4190 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
4191 if (!PageAnon(page)) { /* Shared memory */
4192 if (page->mapping && !page_is_file_cache(page))
4194 } else if (page_mapped(page)) /* Anon */
4201 mem_cgroup_charge_statistics(memcg, page, anon, -nr_pages);
4203 ClearPageCgroupUsed(pc);
4205 * pc->mem_cgroup is not cleared here. It will be accessed when it's
4206 * freed from LRU. This is safe because uncharged page is expected not
4207 * to be reused (freed soon). Exception is SwapCache, it's handled by
4208 * special functions.
4211 unlock_page_cgroup(pc);
4213 * even after unlock, we have memcg->res.usage here and this memcg
4214 * will never be freed.
4216 memcg_check_events(memcg, page);
4217 if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
4218 mem_cgroup_swap_statistics(memcg, true);
4219 mem_cgroup_get(memcg);
4222 * Migration does not charge the res_counter for the
4223 * replacement page, so leave it alone when phasing out the
4224 * page that is unused after the migration.
4226 if (!end_migration && !mem_cgroup_is_root(memcg))
4227 mem_cgroup_do_uncharge(memcg, nr_pages, ctype);
4232 unlock_page_cgroup(pc);
4236 void mem_cgroup_uncharge_page(struct page *page)
4239 if (page_mapped(page))
4241 VM_BUG_ON(page->mapping && !PageAnon(page));
4243 * If the page is in swap cache, uncharge should be deferred
4244 * to the swap path, which also properly accounts swap usage
4245 * and handles memcg lifetime.
4247 * Note that this check is not stable and reclaim may add the
4248 * page to swap cache at any time after this. However, if the
4249 * page is not in swap cache by the time page->mapcount hits
4250 * 0, there won't be any page table references to the swap
4251 * slot, and reclaim will free it and not actually write the
4254 if (PageSwapCache(page))
4256 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_ANON, false);
4259 void mem_cgroup_uncharge_cache_page(struct page *page)
4261 VM_BUG_ON(page_mapped(page));
4262 VM_BUG_ON(page->mapping);
4263 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE, false);
4267 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
4268 * In that cases, pages are freed continuously and we can expect pages
4269 * are in the same memcg. All these calls itself limits the number of
4270 * pages freed at once, then uncharge_start/end() is called properly.
4271 * This may be called prural(2) times in a context,
4274 void mem_cgroup_uncharge_start(void)
4276 current->memcg_batch.do_batch++;
4277 /* We can do nest. */
4278 if (current->memcg_batch.do_batch == 1) {
4279 current->memcg_batch.memcg = NULL;
4280 current->memcg_batch.nr_pages = 0;
4281 current->memcg_batch.memsw_nr_pages = 0;
4285 void mem_cgroup_uncharge_end(void)
4287 struct memcg_batch_info *batch = ¤t->memcg_batch;
4289 if (!batch->do_batch)
4293 if (batch->do_batch) /* If stacked, do nothing. */
4299 * This "batch->memcg" is valid without any css_get/put etc...
4300 * bacause we hide charges behind us.
4302 if (batch->nr_pages)
4303 res_counter_uncharge(&batch->memcg->res,
4304 batch->nr_pages * PAGE_SIZE);
4305 if (batch->memsw_nr_pages)
4306 res_counter_uncharge(&batch->memcg->memsw,
4307 batch->memsw_nr_pages * PAGE_SIZE);
4308 memcg_oom_recover(batch->memcg);
4309 /* forget this pointer (for sanity check) */
4310 batch->memcg = NULL;
4315 * called after __delete_from_swap_cache() and drop "page" account.
4316 * memcg information is recorded to swap_cgroup of "ent"
4319 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
4321 struct mem_cgroup *memcg;
4322 int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
4324 if (!swapout) /* this was a swap cache but the swap is unused ! */
4325 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
4327 memcg = __mem_cgroup_uncharge_common(page, ctype, false);
4330 * record memcg information, if swapout && memcg != NULL,
4331 * mem_cgroup_get() was called in uncharge().
4333 if (do_swap_account && swapout && memcg)
4334 swap_cgroup_record(ent, css_id(&memcg->css));
4338 #ifdef CONFIG_MEMCG_SWAP
4340 * called from swap_entry_free(). remove record in swap_cgroup and
4341 * uncharge "memsw" account.
4343 void mem_cgroup_uncharge_swap(swp_entry_t ent)
4345 struct mem_cgroup *memcg;
4348 if (!do_swap_account)
4351 id = swap_cgroup_record(ent, 0);
4353 memcg = mem_cgroup_lookup(id);
4356 * We uncharge this because swap is freed.
4357 * This memcg can be obsolete one. We avoid calling css_tryget
4359 if (!mem_cgroup_is_root(memcg))
4360 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
4361 mem_cgroup_swap_statistics(memcg, false);
4362 mem_cgroup_put(memcg);
4368 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
4369 * @entry: swap entry to be moved
4370 * @from: mem_cgroup which the entry is moved from
4371 * @to: mem_cgroup which the entry is moved to
4373 * It succeeds only when the swap_cgroup's record for this entry is the same
4374 * as the mem_cgroup's id of @from.
4376 * Returns 0 on success, -EINVAL on failure.
4378 * The caller must have charged to @to, IOW, called res_counter_charge() about
4379 * both res and memsw, and called css_get().
4381 static int mem_cgroup_move_swap_account(swp_entry_t entry,
4382 struct mem_cgroup *from, struct mem_cgroup *to)
4384 unsigned short old_id, new_id;
4386 old_id = css_id(&from->css);
4387 new_id = css_id(&to->css);
4389 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
4390 mem_cgroup_swap_statistics(from, false);
4391 mem_cgroup_swap_statistics(to, true);
4393 * This function is only called from task migration context now.
4394 * It postpones res_counter and refcount handling till the end
4395 * of task migration(mem_cgroup_clear_mc()) for performance
4396 * improvement. But we cannot postpone mem_cgroup_get(to)
4397 * because if the process that has been moved to @to does
4398 * swap-in, the refcount of @to might be decreased to 0.
4406 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
4407 struct mem_cgroup *from, struct mem_cgroup *to)
4414 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
4417 void mem_cgroup_prepare_migration(struct page *page, struct page *newpage,
4418 struct mem_cgroup **memcgp)
4420 struct mem_cgroup *memcg = NULL;
4421 unsigned int nr_pages = 1;
4422 struct page_cgroup *pc;
4423 enum charge_type ctype;
4427 if (mem_cgroup_disabled())
4430 if (PageTransHuge(page))
4431 nr_pages <<= compound_order(page);
4433 pc = lookup_page_cgroup(page);
4434 lock_page_cgroup(pc);
4435 if (PageCgroupUsed(pc)) {
4436 memcg = pc->mem_cgroup;
4437 css_get(&memcg->css);
4439 * At migrating an anonymous page, its mapcount goes down
4440 * to 0 and uncharge() will be called. But, even if it's fully
4441 * unmapped, migration may fail and this page has to be
4442 * charged again. We set MIGRATION flag here and delay uncharge
4443 * until end_migration() is called
4445 * Corner Case Thinking
4447 * When the old page was mapped as Anon and it's unmap-and-freed
4448 * while migration was ongoing.
4449 * If unmap finds the old page, uncharge() of it will be delayed
4450 * until end_migration(). If unmap finds a new page, it's
4451 * uncharged when it make mapcount to be 1->0. If unmap code
4452 * finds swap_migration_entry, the new page will not be mapped
4453 * and end_migration() will find it(mapcount==0).
4456 * When the old page was mapped but migraion fails, the kernel
4457 * remaps it. A charge for it is kept by MIGRATION flag even
4458 * if mapcount goes down to 0. We can do remap successfully
4459 * without charging it again.
4462 * The "old" page is under lock_page() until the end of
4463 * migration, so, the old page itself will not be swapped-out.
4464 * If the new page is swapped out before end_migraton, our
4465 * hook to usual swap-out path will catch the event.
4468 SetPageCgroupMigration(pc);
4470 unlock_page_cgroup(pc);
4472 * If the page is not charged at this point,
4480 * We charge new page before it's used/mapped. So, even if unlock_page()
4481 * is called before end_migration, we can catch all events on this new
4482 * page. In the case new page is migrated but not remapped, new page's
4483 * mapcount will be finally 0 and we call uncharge in end_migration().
4486 ctype = MEM_CGROUP_CHARGE_TYPE_ANON;
4488 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
4490 * The page is committed to the memcg, but it's not actually
4491 * charged to the res_counter since we plan on replacing the
4492 * old one and only one page is going to be left afterwards.
4494 __mem_cgroup_commit_charge(memcg, newpage, nr_pages, ctype, false);
4497 /* remove redundant charge if migration failed*/
4498 void mem_cgroup_end_migration(struct mem_cgroup *memcg,
4499 struct page *oldpage, struct page *newpage, bool migration_ok)
4501 struct page *used, *unused;
4502 struct page_cgroup *pc;
4508 if (!migration_ok) {
4515 anon = PageAnon(used);
4516 __mem_cgroup_uncharge_common(unused,
4517 anon ? MEM_CGROUP_CHARGE_TYPE_ANON
4518 : MEM_CGROUP_CHARGE_TYPE_CACHE,
4520 css_put(&memcg->css);
4522 * We disallowed uncharge of pages under migration because mapcount
4523 * of the page goes down to zero, temporarly.
4524 * Clear the flag and check the page should be charged.
4526 pc = lookup_page_cgroup(oldpage);
4527 lock_page_cgroup(pc);
4528 ClearPageCgroupMigration(pc);
4529 unlock_page_cgroup(pc);
4532 * If a page is a file cache, radix-tree replacement is very atomic
4533 * and we can skip this check. When it was an Anon page, its mapcount
4534 * goes down to 0. But because we added MIGRATION flage, it's not
4535 * uncharged yet. There are several case but page->mapcount check
4536 * and USED bit check in mem_cgroup_uncharge_page() will do enough
4537 * check. (see prepare_charge() also)
4540 mem_cgroup_uncharge_page(used);
4544 * At replace page cache, newpage is not under any memcg but it's on
4545 * LRU. So, this function doesn't touch res_counter but handles LRU
4546 * in correct way. Both pages are locked so we cannot race with uncharge.
4548 void mem_cgroup_replace_page_cache(struct page *oldpage,
4549 struct page *newpage)
4551 struct mem_cgroup *memcg = NULL;
4552 struct page_cgroup *pc;
4553 enum charge_type type = MEM_CGROUP_CHARGE_TYPE_CACHE;
4555 if (mem_cgroup_disabled())
4558 pc = lookup_page_cgroup(oldpage);
4559 /* fix accounting on old pages */
4560 lock_page_cgroup(pc);
4561 if (PageCgroupUsed(pc)) {
4562 memcg = pc->mem_cgroup;
4563 mem_cgroup_charge_statistics(memcg, oldpage, false, -1);
4564 ClearPageCgroupUsed(pc);
4566 unlock_page_cgroup(pc);
4569 * When called from shmem_replace_page(), in some cases the
4570 * oldpage has already been charged, and in some cases not.
4575 * Even if newpage->mapping was NULL before starting replacement,
4576 * the newpage may be on LRU(or pagevec for LRU) already. We lock
4577 * LRU while we overwrite pc->mem_cgroup.
4579 __mem_cgroup_commit_charge(memcg, newpage, 1, type, true);
4582 #ifdef CONFIG_DEBUG_VM
4583 static struct page_cgroup *lookup_page_cgroup_used(struct page *page)
4585 struct page_cgroup *pc;
4587 pc = lookup_page_cgroup(page);
4589 * Can be NULL while feeding pages into the page allocator for
4590 * the first time, i.e. during boot or memory hotplug;
4591 * or when mem_cgroup_disabled().
4593 if (likely(pc) && PageCgroupUsed(pc))
4598 bool mem_cgroup_bad_page_check(struct page *page)
4600 if (mem_cgroup_disabled())
4603 return lookup_page_cgroup_used(page) != NULL;
4606 void mem_cgroup_print_bad_page(struct page *page)
4608 struct page_cgroup *pc;
4610 pc = lookup_page_cgroup_used(page);
4612 pr_alert("pc:%p pc->flags:%lx pc->mem_cgroup:%p\n",
4613 pc, pc->flags, pc->mem_cgroup);
4618 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
4619 unsigned long long val)
4622 u64 memswlimit, memlimit;
4624 int children = mem_cgroup_count_children(memcg);
4625 u64 curusage, oldusage;
4629 * For keeping hierarchical_reclaim simple, how long we should retry
4630 * is depends on callers. We set our retry-count to be function
4631 * of # of children which we should visit in this loop.
4633 retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
4635 oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
4638 while (retry_count) {
4639 if (signal_pending(current)) {
4644 * Rather than hide all in some function, I do this in
4645 * open coded manner. You see what this really does.
4646 * We have to guarantee memcg->res.limit <= memcg->memsw.limit.
4648 mutex_lock(&set_limit_mutex);
4649 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
4650 if (memswlimit < val) {
4652 mutex_unlock(&set_limit_mutex);
4656 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
4660 ret = res_counter_set_limit(&memcg->res, val);
4662 if (memswlimit == val)
4663 memcg->memsw_is_minimum = true;
4665 memcg->memsw_is_minimum = false;
4667 mutex_unlock(&set_limit_mutex);
4672 mem_cgroup_reclaim(memcg, GFP_KERNEL,
4673 MEM_CGROUP_RECLAIM_SHRINK);
4674 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
4675 /* Usage is reduced ? */
4676 if (curusage >= oldusage)
4679 oldusage = curusage;
4681 if (!ret && enlarge)
4682 memcg_oom_recover(memcg);
4687 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
4688 unsigned long long val)
4691 u64 memlimit, memswlimit, oldusage, curusage;
4692 int children = mem_cgroup_count_children(memcg);
4696 /* see mem_cgroup_resize_res_limit */
4697 retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
4698 oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
4699 while (retry_count) {
4700 if (signal_pending(current)) {
4705 * Rather than hide all in some function, I do this in
4706 * open coded manner. You see what this really does.
4707 * We have to guarantee memcg->res.limit <= memcg->memsw.limit.
4709 mutex_lock(&set_limit_mutex);
4710 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
4711 if (memlimit > val) {
4713 mutex_unlock(&set_limit_mutex);
4716 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
4717 if (memswlimit < val)
4719 ret = res_counter_set_limit(&memcg->memsw, val);
4721 if (memlimit == val)
4722 memcg->memsw_is_minimum = true;
4724 memcg->memsw_is_minimum = false;
4726 mutex_unlock(&set_limit_mutex);
4731 mem_cgroup_reclaim(memcg, GFP_KERNEL,
4732 MEM_CGROUP_RECLAIM_NOSWAP |
4733 MEM_CGROUP_RECLAIM_SHRINK);
4734 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
4735 /* Usage is reduced ? */
4736 if (curusage >= oldusage)
4739 oldusage = curusage;
4741 if (!ret && enlarge)
4742 memcg_oom_recover(memcg);
4746 unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
4748 unsigned long *total_scanned)
4750 unsigned long nr_reclaimed = 0;
4751 struct mem_cgroup_per_zone *mz, *next_mz = NULL;
4752 unsigned long reclaimed;
4754 struct mem_cgroup_tree_per_zone *mctz;
4755 unsigned long long excess;
4756 unsigned long nr_scanned;
4761 mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
4763 * This loop can run a while, specially if mem_cgroup's continuously
4764 * keep exceeding their soft limit and putting the system under
4771 mz = mem_cgroup_largest_soft_limit_node(mctz);
4776 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, zone,
4777 gfp_mask, &nr_scanned);
4778 nr_reclaimed += reclaimed;
4779 *total_scanned += nr_scanned;
4780 spin_lock(&mctz->lock);
4783 * If we failed to reclaim anything from this memory cgroup
4784 * it is time to move on to the next cgroup
4790 * Loop until we find yet another one.
4792 * By the time we get the soft_limit lock
4793 * again, someone might have aded the
4794 * group back on the RB tree. Iterate to
4795 * make sure we get a different mem.
4796 * mem_cgroup_largest_soft_limit_node returns
4797 * NULL if no other cgroup is present on
4801 __mem_cgroup_largest_soft_limit_node(mctz);
4803 css_put(&next_mz->memcg->css);
4804 else /* next_mz == NULL or other memcg */
4808 __mem_cgroup_remove_exceeded(mz->memcg, mz, mctz);
4809 excess = res_counter_soft_limit_excess(&mz->memcg->res);
4811 * One school of thought says that we should not add
4812 * back the node to the tree if reclaim returns 0.
4813 * But our reclaim could return 0, simply because due
4814 * to priority we are exposing a smaller subset of
4815 * memory to reclaim from. Consider this as a longer
4818 /* If excess == 0, no tree ops */
4819 __mem_cgroup_insert_exceeded(mz->memcg, mz, mctz, excess);
4820 spin_unlock(&mctz->lock);
4821 css_put(&mz->memcg->css);
4824 * Could not reclaim anything and there are no more
4825 * mem cgroups to try or we seem to be looping without
4826 * reclaiming anything.
4828 if (!nr_reclaimed &&
4830 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
4832 } while (!nr_reclaimed);
4834 css_put(&next_mz->memcg->css);
4835 return nr_reclaimed;
4839 * mem_cgroup_force_empty_list - clears LRU of a group
4840 * @memcg: group to clear
4843 * @lru: lru to to clear
4845 * Traverse a specified page_cgroup list and try to drop them all. This doesn't
4846 * reclaim the pages page themselves - pages are moved to the parent (or root)
4849 static void mem_cgroup_force_empty_list(struct mem_cgroup *memcg,
4850 int node, int zid, enum lru_list lru)
4852 struct lruvec *lruvec;
4853 unsigned long flags;
4854 struct list_head *list;
4858 zone = &NODE_DATA(node)->node_zones[zid];
4859 lruvec = mem_cgroup_zone_lruvec(zone, memcg);
4860 list = &lruvec->lists[lru];
4864 struct page_cgroup *pc;
4867 spin_lock_irqsave(&zone->lru_lock, flags);
4868 if (list_empty(list)) {
4869 spin_unlock_irqrestore(&zone->lru_lock, flags);
4872 page = list_entry(list->prev, struct page, lru);
4874 list_move(&page->lru, list);
4876 spin_unlock_irqrestore(&zone->lru_lock, flags);
4879 spin_unlock_irqrestore(&zone->lru_lock, flags);
4881 pc = lookup_page_cgroup(page);
4883 if (mem_cgroup_move_parent(page, pc, memcg)) {
4884 /* found lock contention or "pc" is obsolete. */
4889 } while (!list_empty(list));
4893 * make mem_cgroup's charge to be 0 if there is no task by moving
4894 * all the charges and pages to the parent.
4895 * This enables deleting this mem_cgroup.
4897 * Caller is responsible for holding css reference on the memcg.
4899 static void mem_cgroup_reparent_charges(struct mem_cgroup *memcg)
4905 /* This is for making all *used* pages to be on LRU. */
4906 lru_add_drain_all();
4907 drain_all_stock_sync(memcg);
4908 mem_cgroup_start_move(memcg);
4909 for_each_node_state(node, N_MEMORY) {
4910 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
4913 mem_cgroup_force_empty_list(memcg,
4918 mem_cgroup_end_move(memcg);
4919 memcg_oom_recover(memcg);
4923 * Kernel memory may not necessarily be trackable to a specific
4924 * process. So they are not migrated, and therefore we can't
4925 * expect their value to drop to 0 here.
4926 * Having res filled up with kmem only is enough.
4928 * This is a safety check because mem_cgroup_force_empty_list
4929 * could have raced with mem_cgroup_replace_page_cache callers
4930 * so the lru seemed empty but the page could have been added
4931 * right after the check. RES_USAGE should be safe as we always
4932 * charge before adding to the LRU.
4934 usage = res_counter_read_u64(&memcg->res, RES_USAGE) -
4935 res_counter_read_u64(&memcg->kmem, RES_USAGE);
4936 } while (usage > 0);
4940 * This mainly exists for tests during the setting of set of use_hierarchy.
4941 * Since this is the very setting we are changing, the current hierarchy value
4944 static inline bool __memcg_has_children(struct mem_cgroup *memcg)
4948 /* bounce at first found */
4949 cgroup_for_each_child(pos, memcg->css.cgroup)
4955 * Must be called with memcg_create_mutex held, unless the cgroup is guaranteed
4956 * to be already dead (as in mem_cgroup_force_empty, for instance). This is
4957 * from mem_cgroup_count_children(), in the sense that we don't really care how
4958 * many children we have; we only need to know if we have any. It also counts
4959 * any memcg without hierarchy as infertile.
4961 static inline bool memcg_has_children(struct mem_cgroup *memcg)
4963 return memcg->use_hierarchy && __memcg_has_children(memcg);
4967 * Reclaims as many pages from the given memcg as possible and moves
4968 * the rest to the parent.
4970 * Caller is responsible for holding css reference for memcg.
4972 static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
4974 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
4975 struct cgroup *cgrp = memcg->css.cgroup;
4977 /* returns EBUSY if there is a task or if we come here twice. */
4978 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
4981 /* we call try-to-free pages for make this cgroup empty */
4982 lru_add_drain_all();
4983 /* try to free all pages in this cgroup */
4984 while (nr_retries && res_counter_read_u64(&memcg->res, RES_USAGE) > 0) {
4987 if (signal_pending(current))
4990 progress = try_to_free_mem_cgroup_pages(memcg, GFP_KERNEL,
4994 /* maybe some writeback is necessary */
4995 congestion_wait(BLK_RW_ASYNC, HZ/10);
5000 mem_cgroup_reparent_charges(memcg);
5005 static int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
5007 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5010 if (mem_cgroup_is_root(memcg))
5012 css_get(&memcg->css);
5013 ret = mem_cgroup_force_empty(memcg);
5014 css_put(&memcg->css);
5019 #ifdef CONFIG_MEMCG_SWAP
5020 static int mem_cgroup_force_reclaim(struct cgroup *cont, struct cftype *cft, u64 val)
5023 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5024 unsigned long nr_to_reclaim = val;
5025 unsigned long total = 0;
5028 for (loop = 0; loop < MEM_CGROUP_MAX_RECLAIM_LOOPS; loop++) {
5029 total += try_to_free_mem_cgroup_pages(memcg, GFP_KERNEL, false);
5032 * If nothing was reclaimed after two attempts, there
5033 * may be no reclaimable pages in this hierarchy.
5034 * If more than nr_to_reclaim pages were already reclaimed,
5035 * finish force reclaim.
5037 if (loop && (!total || total > nr_to_reclaim))
5041 if (IS_ENABLED(CONFIG_SHRINK_MEMORY)) {
5042 /* if reclaim failed from cgroup and if number of
5043 * global reclaimable pages is less than 100MB, then
5044 * do not call memory shrinker.
5046 if ((total < nr_to_reclaim) &&
5047 (global_reclaimable_pages() > MIN_SHRINK_THRESHOLD)) {
5048 unsigned long nr_shrink;
5049 nr_shrink = shrink_all_memory(totalram_pages/2);
5050 pr_info("%s: Total pages shrinked: %lu\n",
5051 __func__, nr_shrink);
5056 /* Calling compaction immediately after reclaim give good benefits.
5057 * So, if either cgroup_reclaim or shrinker could make some progress,
5058 * we trigger compaction.
5060 if (IS_ENABLED(CONFIG_COMPACTION) && (total > 0))
5067 static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
5069 return mem_cgroup_from_cont(cont)->use_hierarchy;
5072 static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
5076 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5077 struct cgroup *parent = cont->parent;
5078 struct mem_cgroup *parent_memcg = NULL;
5081 parent_memcg = mem_cgroup_from_cont(parent);
5083 mutex_lock(&memcg_create_mutex);
5085 if (memcg->use_hierarchy == val)
5089 * If parent's use_hierarchy is set, we can't make any modifications
5090 * in the child subtrees. If it is unset, then the change can
5091 * occur, provided the current cgroup has no children.
5093 * For the root cgroup, parent_mem is NULL, we allow value to be
5094 * set if there are no children.
5096 if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
5097 (val == 1 || val == 0)) {
5098 if (!__memcg_has_children(memcg))
5099 memcg->use_hierarchy = val;
5106 mutex_unlock(&memcg_create_mutex);
5112 static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup *memcg,
5113 enum mem_cgroup_stat_index idx)
5115 struct mem_cgroup *iter;
5118 /* Per-cpu values can be negative, use a signed accumulator */
5119 for_each_mem_cgroup_tree(iter, memcg)
5120 val += mem_cgroup_read_stat(iter, idx);
5122 if (val < 0) /* race ? */
5127 static inline u64 mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
5131 if (!mem_cgroup_is_root(memcg)) {
5133 return res_counter_read_u64(&memcg->res, RES_USAGE);
5135 return res_counter_read_u64(&memcg->memsw, RES_USAGE);
5139 * Transparent hugepages are still accounted for in MEM_CGROUP_STAT_RSS
5140 * as well as in MEM_CGROUP_STAT_RSS_HUGE.
5142 val = mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_CACHE);
5143 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_RSS);
5146 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_SWAP);
5148 return val << PAGE_SHIFT;
5151 static ssize_t mem_cgroup_read(struct cgroup *cont, struct cftype *cft,
5152 struct file *file, char __user *buf,
5153 size_t nbytes, loff_t *ppos)
5155 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5161 type = MEMFILE_TYPE(cft->private);
5162 name = MEMFILE_ATTR(cft->private);
5166 if (name == RES_USAGE)
5167 val = mem_cgroup_usage(memcg, false);
5169 val = res_counter_read_u64(&memcg->res, name);
5172 if (name == RES_USAGE)
5173 val = mem_cgroup_usage(memcg, true);
5175 val = res_counter_read_u64(&memcg->memsw, name);
5178 val = res_counter_read_u64(&memcg->kmem, name);
5184 len = scnprintf(str, sizeof(str), "%llu\n", (unsigned long long)val);
5185 return simple_read_from_buffer(buf, nbytes, ppos, str, len);
5188 static int memcg_update_kmem_limit(struct cgroup *cont, u64 val)
5191 #ifdef CONFIG_MEMCG_KMEM
5192 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5194 * For simplicity, we won't allow this to be disabled. It also can't
5195 * be changed if the cgroup has children already, or if tasks had
5198 * If tasks join before we set the limit, a person looking at
5199 * kmem.usage_in_bytes will have no way to determine when it took
5200 * place, which makes the value quite meaningless.
5202 * After it first became limited, changes in the value of the limit are
5203 * of course permitted.
5205 mutex_lock(&memcg_create_mutex);
5206 mutex_lock(&set_limit_mutex);
5207 if (!memcg->kmem_account_flags && val != RESOURCE_MAX) {
5208 if (cgroup_task_count(cont) || memcg_has_children(memcg)) {
5212 ret = res_counter_set_limit(&memcg->kmem, val);
5215 ret = memcg_update_cache_sizes(memcg);
5217 res_counter_set_limit(&memcg->kmem, RESOURCE_MAX);
5220 static_key_slow_inc(&memcg_kmem_enabled_key);
5222 * setting the active bit after the inc will guarantee no one
5223 * starts accounting before all call sites are patched
5225 memcg_kmem_set_active(memcg);
5228 * kmem charges can outlive the cgroup. In the case of slab
5229 * pages, for instance, a page contain objects from various
5230 * processes, so it is unfeasible to migrate them away. We
5231 * need to reference count the memcg because of that.
5233 mem_cgroup_get(memcg);
5235 ret = res_counter_set_limit(&memcg->kmem, val);
5237 mutex_unlock(&set_limit_mutex);
5238 mutex_unlock(&memcg_create_mutex);
5243 #ifdef CONFIG_MEMCG_KMEM
5244 static int memcg_propagate_kmem(struct mem_cgroup *memcg)
5247 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
5251 memcg->kmem_account_flags = parent->kmem_account_flags;
5253 * When that happen, we need to disable the static branch only on those
5254 * memcgs that enabled it. To achieve this, we would be forced to
5255 * complicate the code by keeping track of which memcgs were the ones
5256 * that actually enabled limits, and which ones got it from its
5259 * It is a lot simpler just to do static_key_slow_inc() on every child
5260 * that is accounted.
5262 if (!memcg_kmem_is_active(memcg))
5266 * destroy(), called if we fail, will issue static_key_slow_inc() and
5267 * mem_cgroup_put() if kmem is enabled. We have to either call them
5268 * unconditionally, or clear the KMEM_ACTIVE flag. I personally find
5269 * this more consistent, since it always leads to the same destroy path
5271 mem_cgroup_get(memcg);
5272 static_key_slow_inc(&memcg_kmem_enabled_key);
5274 mutex_lock(&set_limit_mutex);
5275 ret = memcg_update_cache_sizes(memcg);
5276 mutex_unlock(&set_limit_mutex);
5280 #endif /* CONFIG_MEMCG_KMEM */
5283 * The user of this function is...
5286 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
5289 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5292 unsigned long long val;
5295 type = MEMFILE_TYPE(cft->private);
5296 name = MEMFILE_ATTR(cft->private);
5300 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
5304 /* This function does all necessary parse...reuse it */
5305 ret = res_counter_memparse_write_strategy(buffer, &val);
5309 ret = mem_cgroup_resize_limit(memcg, val);
5310 else if (type == _MEMSWAP)
5311 ret = mem_cgroup_resize_memsw_limit(memcg, val);
5312 else if (type == _KMEM)
5313 ret = memcg_update_kmem_limit(cont, val);
5317 case RES_SOFT_LIMIT:
5318 ret = res_counter_memparse_write_strategy(buffer, &val);
5322 * For memsw, soft limits are hard to implement in terms
5323 * of semantics, for now, we support soft limits for
5324 * control without swap
5327 ret = res_counter_set_soft_limit(&memcg->res, val);
5332 ret = -EINVAL; /* should be BUG() ? */
5338 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
5339 unsigned long long *mem_limit, unsigned long long *memsw_limit)
5341 struct cgroup *cgroup;
5342 unsigned long long min_limit, min_memsw_limit, tmp;
5344 min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
5345 min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
5346 cgroup = memcg->css.cgroup;
5347 if (!memcg->use_hierarchy)
5350 while (cgroup->parent) {
5351 cgroup = cgroup->parent;
5352 memcg = mem_cgroup_from_cont(cgroup);
5353 if (!memcg->use_hierarchy)
5355 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
5356 min_limit = min(min_limit, tmp);
5357 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
5358 min_memsw_limit = min(min_memsw_limit, tmp);
5361 *mem_limit = min_limit;
5362 *memsw_limit = min_memsw_limit;
5365 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
5367 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5371 type = MEMFILE_TYPE(event);
5372 name = MEMFILE_ATTR(event);
5377 res_counter_reset_max(&memcg->res);
5378 else if (type == _MEMSWAP)
5379 res_counter_reset_max(&memcg->memsw);
5380 else if (type == _KMEM)
5381 res_counter_reset_max(&memcg->kmem);
5387 res_counter_reset_failcnt(&memcg->res);
5388 else if (type == _MEMSWAP)
5389 res_counter_reset_failcnt(&memcg->memsw);
5390 else if (type == _KMEM)
5391 res_counter_reset_failcnt(&memcg->kmem);
5400 static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
5403 return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
5407 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
5408 struct cftype *cft, u64 val)
5410 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5412 if (val >= (1 << NR_MOVE_TYPE))
5416 * No kind of locking is needed in here, because ->can_attach() will
5417 * check this value once in the beginning of the process, and then carry
5418 * on with stale data. This means that changes to this value will only
5419 * affect task migrations starting after the change.
5421 memcg->move_charge_at_immigrate = val;
5425 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
5426 struct cftype *cft, u64 val)
5433 static int memcg_numa_stat_show(struct cgroup *cont, struct cftype *cft,
5437 unsigned long total_nr, file_nr, anon_nr, unevictable_nr;
5438 unsigned long node_nr;
5439 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5441 total_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL);
5442 seq_printf(m, "total=%lu", total_nr);
5443 for_each_node_state(nid, N_MEMORY) {
5444 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL);
5445 seq_printf(m, " N%d=%lu", nid, node_nr);
5449 file_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL_FILE);
5450 seq_printf(m, "file=%lu", file_nr);
5451 for_each_node_state(nid, N_MEMORY) {
5452 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
5454 seq_printf(m, " N%d=%lu", nid, node_nr);
5458 anon_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL_ANON);
5459 seq_printf(m, "anon=%lu", anon_nr);
5460 for_each_node_state(nid, N_MEMORY) {
5461 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
5463 seq_printf(m, " N%d=%lu", nid, node_nr);
5467 unevictable_nr = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_UNEVICTABLE));
5468 seq_printf(m, "unevictable=%lu", unevictable_nr);
5469 for_each_node_state(nid, N_MEMORY) {
5470 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
5471 BIT(LRU_UNEVICTABLE));
5472 seq_printf(m, " N%d=%lu", nid, node_nr);
5477 #endif /* CONFIG_NUMA */
5479 static inline void mem_cgroup_lru_names_not_uptodate(void)
5481 BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_lru_names) != NR_LRU_LISTS);
5484 static int memcg_stat_show(struct cgroup *cont, struct cftype *cft,
5487 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5488 struct mem_cgroup *mi;
5491 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
5492 if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
5494 seq_printf(m, "%s %ld\n", mem_cgroup_stat_names[i],
5495 mem_cgroup_read_stat(memcg, i) * PAGE_SIZE);
5498 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++)
5499 seq_printf(m, "%s %lu\n", mem_cgroup_events_names[i],
5500 mem_cgroup_read_events(memcg, i));
5502 for (i = 0; i < NR_LRU_LISTS; i++)
5503 seq_printf(m, "%s %lu\n", mem_cgroup_lru_names[i],
5504 mem_cgroup_nr_lru_pages(memcg, BIT(i)) * PAGE_SIZE);
5506 /* Hierarchical information */
5508 unsigned long long limit, memsw_limit;
5509 memcg_get_hierarchical_limit(memcg, &limit, &memsw_limit);
5510 seq_printf(m, "hierarchical_memory_limit %llu\n", limit);
5511 if (do_swap_account)
5512 seq_printf(m, "hierarchical_memsw_limit %llu\n",
5516 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
5519 if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
5521 for_each_mem_cgroup_tree(mi, memcg)
5522 val += mem_cgroup_read_stat(mi, i) * PAGE_SIZE;
5523 seq_printf(m, "total_%s %lld\n", mem_cgroup_stat_names[i], val);
5526 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
5527 unsigned long long val = 0;
5529 for_each_mem_cgroup_tree(mi, memcg)
5530 val += mem_cgroup_read_events(mi, i);
5531 seq_printf(m, "total_%s %llu\n",
5532 mem_cgroup_events_names[i], val);
5535 for (i = 0; i < NR_LRU_LISTS; i++) {
5536 unsigned long long val = 0;
5538 for_each_mem_cgroup_tree(mi, memcg)
5539 val += mem_cgroup_nr_lru_pages(mi, BIT(i)) * PAGE_SIZE;
5540 seq_printf(m, "total_%s %llu\n", mem_cgroup_lru_names[i], val);
5543 #ifdef CONFIG_DEBUG_VM
5546 struct mem_cgroup_per_zone *mz;
5547 struct zone_reclaim_stat *rstat;
5548 unsigned long recent_rotated[2] = {0, 0};
5549 unsigned long recent_scanned[2] = {0, 0};
5551 for_each_online_node(nid)
5552 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
5553 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
5554 rstat = &mz->lruvec.reclaim_stat;
5556 recent_rotated[0] += rstat->recent_rotated[0];
5557 recent_rotated[1] += rstat->recent_rotated[1];
5558 recent_scanned[0] += rstat->recent_scanned[0];
5559 recent_scanned[1] += rstat->recent_scanned[1];
5561 seq_printf(m, "recent_rotated_anon %lu\n", recent_rotated[0]);
5562 seq_printf(m, "recent_rotated_file %lu\n", recent_rotated[1]);
5563 seq_printf(m, "recent_scanned_anon %lu\n", recent_scanned[0]);
5564 seq_printf(m, "recent_scanned_file %lu\n", recent_scanned[1]);
5571 static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
5573 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5575 return mem_cgroup_swappiness(memcg);
5578 static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
5581 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5582 struct mem_cgroup *parent;
5587 if (cgrp->parent == NULL)
5590 parent = mem_cgroup_from_cont(cgrp->parent);
5592 mutex_lock(&memcg_create_mutex);
5594 /* If under hierarchy, only empty-root can set this value */
5595 if ((parent->use_hierarchy) || memcg_has_children(memcg)) {
5596 mutex_unlock(&memcg_create_mutex);
5600 memcg->swappiness = val;
5602 mutex_unlock(&memcg_create_mutex);
5607 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
5609 struct mem_cgroup_threshold_ary *t;
5615 t = rcu_dereference(memcg->thresholds.primary);
5617 t = rcu_dereference(memcg->memsw_thresholds.primary);
5622 usage = mem_cgroup_usage(memcg, swap);
5625 * current_threshold points to threshold just below or equal to usage.
5626 * If it's not true, a threshold was crossed after last
5627 * call of __mem_cgroup_threshold().
5629 i = t->current_threshold;
5632 * Iterate backward over array of thresholds starting from
5633 * current_threshold and check if a threshold is crossed.
5634 * If none of thresholds below usage is crossed, we read
5635 * only one element of the array here.
5637 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
5638 eventfd_signal(t->entries[i].eventfd, 1);
5640 /* i = current_threshold + 1 */
5644 * Iterate forward over array of thresholds starting from
5645 * current_threshold+1 and check if a threshold is crossed.
5646 * If none of thresholds above usage is crossed, we read
5647 * only one element of the array here.
5649 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
5650 eventfd_signal(t->entries[i].eventfd, 1);
5652 /* Update current_threshold */
5653 t->current_threshold = i - 1;
5658 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
5661 __mem_cgroup_threshold(memcg, false);
5662 if (do_swap_account)
5663 __mem_cgroup_threshold(memcg, true);
5665 memcg = parent_mem_cgroup(memcg);
5669 static int compare_thresholds(const void *a, const void *b)
5671 const struct mem_cgroup_threshold *_a = a;
5672 const struct mem_cgroup_threshold *_b = b;
5674 if (_a->threshold > _b->threshold)
5677 if (_a->threshold < _b->threshold)
5683 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
5685 struct mem_cgroup_eventfd_list *ev;
5687 list_for_each_entry(ev, &memcg->oom_notify, list)
5688 eventfd_signal(ev->eventfd, 1);
5692 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
5694 struct mem_cgroup *iter;
5696 for_each_mem_cgroup_tree(iter, memcg)
5697 mem_cgroup_oom_notify_cb(iter);
5700 static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
5701 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
5703 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5704 struct mem_cgroup_thresholds *thresholds;
5705 struct mem_cgroup_threshold_ary *new;
5706 enum res_type type = MEMFILE_TYPE(cft->private);
5707 u64 threshold, usage;
5710 ret = res_counter_memparse_write_strategy(args, &threshold);
5714 mutex_lock(&memcg->thresholds_lock);
5717 thresholds = &memcg->thresholds;
5718 else if (type == _MEMSWAP)
5719 thresholds = &memcg->memsw_thresholds;
5723 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
5725 /* Check if a threshold crossed before adding a new one */
5726 if (thresholds->primary)
5727 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
5729 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
5731 /* Allocate memory for new array of thresholds */
5732 new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
5740 /* Copy thresholds (if any) to new array */
5741 if (thresholds->primary) {
5742 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
5743 sizeof(struct mem_cgroup_threshold));
5746 /* Add new threshold */
5747 new->entries[size - 1].eventfd = eventfd;
5748 new->entries[size - 1].threshold = threshold;
5750 /* Sort thresholds. Registering of new threshold isn't time-critical */
5751 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
5752 compare_thresholds, NULL);
5754 /* Find current threshold */
5755 new->current_threshold = -1;
5756 for (i = 0; i < size; i++) {
5757 if (new->entries[i].threshold <= usage) {
5759 * new->current_threshold will not be used until
5760 * rcu_assign_pointer(), so it's safe to increment
5763 ++new->current_threshold;
5768 /* Free old spare buffer and save old primary buffer as spare */
5769 kfree(thresholds->spare);
5770 thresholds->spare = thresholds->primary;
5772 rcu_assign_pointer(thresholds->primary, new);
5774 /* To be sure that nobody uses thresholds */
5778 mutex_unlock(&memcg->thresholds_lock);
5783 static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
5784 struct cftype *cft, struct eventfd_ctx *eventfd)
5786 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5787 struct mem_cgroup_thresholds *thresholds;
5788 struct mem_cgroup_threshold_ary *new;
5789 enum res_type type = MEMFILE_TYPE(cft->private);
5793 mutex_lock(&memcg->thresholds_lock);
5795 thresholds = &memcg->thresholds;
5796 else if (type == _MEMSWAP)
5797 thresholds = &memcg->memsw_thresholds;
5801 if (!thresholds->primary)
5804 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
5806 /* Check if a threshold crossed before removing */
5807 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
5809 /* Calculate new number of threshold */
5811 for (i = 0; i < thresholds->primary->size; i++) {
5812 if (thresholds->primary->entries[i].eventfd != eventfd)
5816 new = thresholds->spare;
5818 /* Set thresholds array to NULL if we don't have thresholds */
5827 /* Copy thresholds and find current threshold */
5828 new->current_threshold = -1;
5829 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
5830 if (thresholds->primary->entries[i].eventfd == eventfd)
5833 new->entries[j] = thresholds->primary->entries[i];
5834 if (new->entries[j].threshold <= usage) {
5836 * new->current_threshold will not be used
5837 * until rcu_assign_pointer(), so it's safe to increment
5840 ++new->current_threshold;
5846 /* Swap primary and spare array */
5847 thresholds->spare = thresholds->primary;
5848 /* If all events are unregistered, free the spare array */
5850 kfree(thresholds->spare);
5851 thresholds->spare = NULL;
5854 rcu_assign_pointer(thresholds->primary, new);
5856 /* To be sure that nobody uses thresholds */
5859 mutex_unlock(&memcg->thresholds_lock);
5862 static int mem_cgroup_oom_register_event(struct cgroup *cgrp,
5863 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
5865 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5866 struct mem_cgroup_eventfd_list *event;
5867 enum res_type type = MEMFILE_TYPE(cft->private);
5869 BUG_ON(type != _OOM_TYPE);
5870 event = kmalloc(sizeof(*event), GFP_KERNEL);
5874 spin_lock(&memcg_oom_lock);
5876 event->eventfd = eventfd;
5877 list_add(&event->list, &memcg->oom_notify);
5879 /* already in OOM ? */
5880 if (atomic_read(&memcg->under_oom))
5881 eventfd_signal(eventfd, 1);
5882 spin_unlock(&memcg_oom_lock);
5887 static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
5888 struct cftype *cft, struct eventfd_ctx *eventfd)
5890 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5891 struct mem_cgroup_eventfd_list *ev, *tmp;
5892 enum res_type type = MEMFILE_TYPE(cft->private);
5894 BUG_ON(type != _OOM_TYPE);
5896 spin_lock(&memcg_oom_lock);
5898 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
5899 if (ev->eventfd == eventfd) {
5900 list_del(&ev->list);
5905 spin_unlock(&memcg_oom_lock);
5908 static int mem_cgroup_oom_control_read(struct cgroup *cgrp,
5909 struct cftype *cft, struct cgroup_map_cb *cb)
5911 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5913 cb->fill(cb, "oom_kill_disable", memcg->oom_kill_disable);
5915 if (atomic_read(&memcg->under_oom))
5916 cb->fill(cb, "under_oom", 1);
5918 cb->fill(cb, "under_oom", 0);
5922 static int mem_cgroup_oom_control_write(struct cgroup *cgrp,
5923 struct cftype *cft, u64 val)
5925 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5926 struct mem_cgroup *parent;
5928 /* cannot set to root cgroup and only 0 and 1 are allowed */
5929 if (!cgrp->parent || !((val == 0) || (val == 1)))
5932 parent = mem_cgroup_from_cont(cgrp->parent);
5934 mutex_lock(&memcg_create_mutex);
5935 /* oom-kill-disable is a flag for subhierarchy. */
5936 if ((parent->use_hierarchy) || memcg_has_children(memcg)) {
5937 mutex_unlock(&memcg_create_mutex);
5940 memcg->oom_kill_disable = val;
5942 memcg_oom_recover(memcg);
5943 mutex_unlock(&memcg_create_mutex);
5947 #ifdef CONFIG_MEMCG_KMEM
5948 static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
5952 memcg->kmemcg_id = -1;
5953 ret = memcg_propagate_kmem(memcg);
5957 return mem_cgroup_sockets_init(memcg, ss);
5960 static void kmem_cgroup_destroy(struct mem_cgroup *memcg)
5962 mem_cgroup_sockets_destroy(memcg);
5964 memcg_kmem_mark_dead(memcg);
5966 if (res_counter_read_u64(&memcg->kmem, RES_USAGE) != 0)
5970 * Charges already down to 0, undo mem_cgroup_get() done in the charge
5971 * path here, being careful not to race with memcg_uncharge_kmem: it is
5972 * possible that the charges went down to 0 between mark_dead and the
5973 * res_counter read, so in that case, we don't need the put
5975 if (memcg_kmem_test_and_clear_dead(memcg))
5976 mem_cgroup_put(memcg);
5979 static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
5984 static void kmem_cgroup_destroy(struct mem_cgroup *memcg)
5989 static struct cftype mem_cgroup_files[] = {
5991 .name = "usage_in_bytes",
5992 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
5993 .read = mem_cgroup_read,
5994 .register_event = mem_cgroup_usage_register_event,
5995 .unregister_event = mem_cgroup_usage_unregister_event,
5998 .name = "max_usage_in_bytes",
5999 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
6000 .trigger = mem_cgroup_reset,
6001 .read = mem_cgroup_read,
6004 .name = "limit_in_bytes",
6005 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
6006 .write_string = mem_cgroup_write,
6007 .read = mem_cgroup_read,
6010 .name = "soft_limit_in_bytes",
6011 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
6012 .write_string = mem_cgroup_write,
6013 .read = mem_cgroup_read,
6017 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
6018 .trigger = mem_cgroup_reset,
6019 .read = mem_cgroup_read,
6023 .read_seq_string = memcg_stat_show,
6026 .name = "force_empty",
6027 .trigger = mem_cgroup_force_empty_write,
6029 #ifdef CONFIG_MEMCG_SWAP
6031 .name = "force_reclaim",
6032 .write_u64 = mem_cgroup_force_reclaim,
6036 .name = "use_hierarchy",
6037 .flags = CFTYPE_INSANE,
6038 .write_u64 = mem_cgroup_hierarchy_write,
6039 .read_u64 = mem_cgroup_hierarchy_read,
6042 .name = "swappiness",
6043 .read_u64 = mem_cgroup_swappiness_read,
6044 .write_u64 = mem_cgroup_swappiness_write,
6047 .name = "move_charge_at_immigrate",
6048 .read_u64 = mem_cgroup_move_charge_read,
6049 .write_u64 = mem_cgroup_move_charge_write,
6052 .name = "oom_control",
6053 .read_map = mem_cgroup_oom_control_read,
6054 .write_u64 = mem_cgroup_oom_control_write,
6055 .register_event = mem_cgroup_oom_register_event,
6056 .unregister_event = mem_cgroup_oom_unregister_event,
6057 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
6060 .name = "pressure_level",
6061 .register_event = vmpressure_register_event,
6062 .unregister_event = vmpressure_unregister_event,
6066 .name = "numa_stat",
6067 .read_seq_string = memcg_numa_stat_show,
6070 #ifdef CONFIG_MEMCG_KMEM
6072 .name = "kmem.limit_in_bytes",
6073 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
6074 .write_string = mem_cgroup_write,
6075 .read = mem_cgroup_read,
6078 .name = "kmem.usage_in_bytes",
6079 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
6080 .read = mem_cgroup_read,
6083 .name = "kmem.failcnt",
6084 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
6085 .trigger = mem_cgroup_reset,
6086 .read = mem_cgroup_read,
6089 .name = "kmem.max_usage_in_bytes",
6090 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
6091 .trigger = mem_cgroup_reset,
6092 .read = mem_cgroup_read,
6094 #ifdef CONFIG_SLABINFO
6096 .name = "kmem.slabinfo",
6097 .read_seq_string = mem_cgroup_slabinfo_read,
6101 { }, /* terminate */
6104 #ifdef CONFIG_MEMCG_SWAP
6105 static struct cftype memsw_cgroup_files[] = {
6107 .name = "memsw.usage_in_bytes",
6108 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
6109 .read = mem_cgroup_read,
6110 .register_event = mem_cgroup_usage_register_event,
6111 .unregister_event = mem_cgroup_usage_unregister_event,
6114 .name = "memsw.max_usage_in_bytes",
6115 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
6116 .trigger = mem_cgroup_reset,
6117 .read = mem_cgroup_read,
6120 .name = "memsw.limit_in_bytes",
6121 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
6122 .write_string = mem_cgroup_write,
6123 .read = mem_cgroup_read,
6126 .name = "memsw.failcnt",
6127 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
6128 .trigger = mem_cgroup_reset,
6129 .read = mem_cgroup_read,
6131 { }, /* terminate */
6134 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
6136 struct mem_cgroup_per_node *pn;
6137 struct mem_cgroup_per_zone *mz;
6138 int zone, tmp = node;
6140 * This routine is called against possible nodes.
6141 * But it's BUG to call kmalloc() against offline node.
6143 * TODO: this routine can waste much memory for nodes which will
6144 * never be onlined. It's better to use memory hotplug callback
6147 if (!node_state(node, N_NORMAL_MEMORY))
6149 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
6153 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
6154 mz = &pn->zoneinfo[zone];
6155 lruvec_init(&mz->lruvec);
6156 mz->usage_in_excess = 0;
6157 mz->on_tree = false;
6160 memcg->info.nodeinfo[node] = pn;
6164 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
6166 kfree(memcg->info.nodeinfo[node]);
6169 static struct mem_cgroup *mem_cgroup_alloc(void)
6171 struct mem_cgroup *memcg;
6172 size_t size = memcg_size();
6174 /* Can be very big if nr_node_ids is very big */
6175 if (size < PAGE_SIZE)
6176 memcg = kzalloc(size, GFP_KERNEL);
6178 memcg = vzalloc(size);
6183 memcg->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
6186 spin_lock_init(&memcg->pcp_counter_lock);
6190 if (size < PAGE_SIZE)
6198 * At destroying mem_cgroup, references from swap_cgroup can remain.
6199 * (scanning all at force_empty is too costly...)
6201 * Instead of clearing all references at force_empty, we remember
6202 * the number of reference from swap_cgroup and free mem_cgroup when
6203 * it goes down to 0.
6205 * Removal of cgroup itself succeeds regardless of refs from swap.
6208 static void __mem_cgroup_free(struct mem_cgroup *memcg)
6211 size_t size = memcg_size();
6213 mem_cgroup_remove_from_trees(memcg);
6214 free_css_id(&mem_cgroup_subsys, &memcg->css);
6217 free_mem_cgroup_per_zone_info(memcg, node);
6219 free_percpu(memcg->stat);
6222 * We need to make sure that (at least for now), the jump label
6223 * destruction code runs outside of the cgroup lock. This is because
6224 * get_online_cpus(), which is called from the static_branch update,
6225 * can't be called inside the cgroup_lock. cpusets are the ones
6226 * enforcing this dependency, so if they ever change, we might as well.
6228 * schedule_work() will guarantee this happens. Be careful if you need
6229 * to move this code around, and make sure it is outside
6232 disarm_static_keys(memcg);
6233 if (size < PAGE_SIZE)
6241 * Helpers for freeing a kmalloc()ed/vzalloc()ed mem_cgroup by RCU,
6242 * but in process context. The work_freeing structure is overlaid
6243 * on the rcu_freeing structure, which itself is overlaid on memsw.
6245 static void free_work(struct work_struct *work)
6247 struct mem_cgroup *memcg;
6249 memcg = container_of(work, struct mem_cgroup, work_freeing);
6250 __mem_cgroup_free(memcg);
6253 static void free_rcu(struct rcu_head *rcu_head)
6255 struct mem_cgroup *memcg;
6257 memcg = container_of(rcu_head, struct mem_cgroup, rcu_freeing);
6258 INIT_WORK(&memcg->work_freeing, free_work);
6259 schedule_work(&memcg->work_freeing);
6262 static void mem_cgroup_get(struct mem_cgroup *memcg)
6264 atomic_inc(&memcg->refcnt);
6267 static void __mem_cgroup_put(struct mem_cgroup *memcg, int count)
6269 if (atomic_sub_and_test(count, &memcg->refcnt)) {
6270 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
6271 call_rcu(&memcg->rcu_freeing, free_rcu);
6273 mem_cgroup_put(parent);
6277 static void mem_cgroup_put(struct mem_cgroup *memcg)
6279 __mem_cgroup_put(memcg, 1);
6283 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
6285 struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg)
6287 if (!memcg->res.parent)
6289 return mem_cgroup_from_res_counter(memcg->res.parent, res);
6291 EXPORT_SYMBOL(parent_mem_cgroup);
6293 static void __init mem_cgroup_soft_limit_tree_init(void)
6295 struct mem_cgroup_tree_per_node *rtpn;
6296 struct mem_cgroup_tree_per_zone *rtpz;
6297 int tmp, node, zone;
6299 for_each_node(node) {
6301 if (!node_state(node, N_NORMAL_MEMORY))
6303 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
6306 soft_limit_tree.rb_tree_per_node[node] = rtpn;
6308 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
6309 rtpz = &rtpn->rb_tree_per_zone[zone];
6310 rtpz->rb_root = RB_ROOT;
6311 spin_lock_init(&rtpz->lock);
6316 static struct cgroup_subsys_state * __ref
6317 mem_cgroup_css_alloc(struct cgroup *cont)
6319 struct mem_cgroup *memcg;
6320 long error = -ENOMEM;
6323 memcg = mem_cgroup_alloc();
6325 return ERR_PTR(error);
6328 if (alloc_mem_cgroup_per_zone_info(memcg, node))
6332 if (cont->parent == NULL) {
6333 root_mem_cgroup = memcg;
6334 res_counter_init(&memcg->res, NULL);
6335 res_counter_init(&memcg->memsw, NULL);
6336 res_counter_init(&memcg->kmem, NULL);
6339 memcg->last_scanned_node = MAX_NUMNODES;
6340 INIT_LIST_HEAD(&memcg->oom_notify);
6341 atomic_set(&memcg->refcnt, 1);
6342 memcg->move_charge_at_immigrate = 0;
6343 mutex_init(&memcg->thresholds_lock);
6344 spin_lock_init(&memcg->move_lock);
6345 vmpressure_init(&memcg->vmpressure);
6350 __mem_cgroup_free(memcg);
6351 return ERR_PTR(error);
6355 mem_cgroup_css_online(struct cgroup *cont)
6357 struct mem_cgroup *memcg, *parent;
6363 mutex_lock(&memcg_create_mutex);
6364 memcg = mem_cgroup_from_cont(cont);
6365 parent = mem_cgroup_from_cont(cont->parent);
6367 memcg->use_hierarchy = parent->use_hierarchy;
6368 memcg->oom_kill_disable = parent->oom_kill_disable;
6369 memcg->swappiness = mem_cgroup_swappiness(parent);
6371 if (parent->use_hierarchy) {
6372 res_counter_init(&memcg->res, &parent->res);
6373 res_counter_init(&memcg->memsw, &parent->memsw);
6374 res_counter_init(&memcg->kmem, &parent->kmem);
6377 * We increment refcnt of the parent to ensure that we can
6378 * safely access it on res_counter_charge/uncharge.
6379 * This refcnt will be decremented when freeing this
6380 * mem_cgroup(see mem_cgroup_put).
6382 mem_cgroup_get(parent);
6384 res_counter_init(&memcg->res, NULL);
6385 res_counter_init(&memcg->memsw, NULL);
6386 res_counter_init(&memcg->kmem, NULL);
6388 * Deeper hierachy with use_hierarchy == false doesn't make
6389 * much sense so let cgroup subsystem know about this
6390 * unfortunate state in our controller.
6392 if (parent != root_mem_cgroup)
6393 mem_cgroup_subsys.broken_hierarchy = true;
6396 error = memcg_init_kmem(memcg, &mem_cgroup_subsys);
6397 mutex_unlock(&memcg_create_mutex);
6402 * Announce all parents that a group from their hierarchy is gone.
6404 static void mem_cgroup_invalidate_reclaim_iterators(struct mem_cgroup *memcg)
6406 struct mem_cgroup *parent = memcg;
6408 while ((parent = parent_mem_cgroup(parent)))
6409 atomic_inc(&parent->dead_count);
6412 * if the root memcg is not hierarchical we have to check it
6415 if (!root_mem_cgroup->use_hierarchy)
6416 atomic_inc(&root_mem_cgroup->dead_count);
6419 static void mem_cgroup_css_offline(struct cgroup *cont)
6421 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
6422 struct cgroup *iter;
6424 mem_cgroup_invalidate_reclaim_iterators(memcg);
6427 * This requires that offlining is serialized. Right now that is
6428 * guaranteed because css_killed_work_fn() holds the cgroup_mutex.
6431 cgroup_for_each_descendant_post(iter, cont) {
6433 mem_cgroup_reparent_charges(mem_cgroup_from_cont(iter));
6437 mem_cgroup_reparent_charges(memcg);
6439 mem_cgroup_destroy_all_caches(memcg);
6442 static void mem_cgroup_css_free(struct cgroup *cont)
6444 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
6446 kmem_cgroup_destroy(memcg);
6448 mem_cgroup_put(memcg);
6452 /* Handlers for move charge at task migration. */
6453 #define PRECHARGE_COUNT_AT_ONCE 256
6454 static int mem_cgroup_do_precharge(unsigned long count)
6457 int batch_count = PRECHARGE_COUNT_AT_ONCE;
6458 struct mem_cgroup *memcg = mc.to;
6460 if (mem_cgroup_is_root(memcg)) {
6461 mc.precharge += count;
6462 /* we don't need css_get for root */
6465 /* try to charge at once */
6467 struct res_counter *dummy;
6469 * "memcg" cannot be under rmdir() because we've already checked
6470 * by cgroup_lock_live_cgroup() that it is not removed and we
6471 * are still under the same cgroup_mutex. So we can postpone
6474 if (res_counter_charge(&memcg->res, PAGE_SIZE * count, &dummy))
6476 if (do_swap_account && res_counter_charge(&memcg->memsw,
6477 PAGE_SIZE * count, &dummy)) {
6478 res_counter_uncharge(&memcg->res, PAGE_SIZE * count);
6481 mc.precharge += count;
6485 /* fall back to one by one charge */
6487 if (signal_pending(current)) {
6491 if (!batch_count--) {
6492 batch_count = PRECHARGE_COUNT_AT_ONCE;
6495 ret = __mem_cgroup_try_charge(NULL,
6496 GFP_KERNEL, 1, &memcg, false);
6498 /* mem_cgroup_clear_mc() will do uncharge later */
6506 * get_mctgt_type - get target type of moving charge
6507 * @vma: the vma the pte to be checked belongs
6508 * @addr: the address corresponding to the pte to be checked
6509 * @ptent: the pte to be checked
6510 * @target: the pointer the target page or swap ent will be stored(can be NULL)
6513 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
6514 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
6515 * move charge. if @target is not NULL, the page is stored in target->page
6516 * with extra refcnt got(Callers should handle it).
6517 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
6518 * target for charge migration. if @target is not NULL, the entry is stored
6521 * Called with pte lock held.
6528 enum mc_target_type {
6534 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
6535 unsigned long addr, pte_t ptent)
6537 struct page *page = vm_normal_page(vma, addr, ptent);
6539 if (!page || !page_mapped(page))
6541 if (PageAnon(page)) {
6542 /* we don't move shared anon */
6545 } else if (!move_file())
6546 /* we ignore mapcount for file pages */
6548 if (!get_page_unless_zero(page))
6555 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
6556 unsigned long addr, pte_t ptent, swp_entry_t *entry)
6558 struct page *page = NULL;
6559 swp_entry_t ent = pte_to_swp_entry(ptent);
6561 if (!move_anon() || non_swap_entry(ent))
6564 * Because lookup_swap_cache() updates some statistics counter,
6565 * we call find_get_page() with swapper_space directly.
6567 page = find_get_page(swap_address_space(ent), ent.val);
6568 if (do_swap_account)
6569 entry->val = ent.val;
6574 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
6575 unsigned long addr, pte_t ptent, swp_entry_t *entry)
6581 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
6582 unsigned long addr, pte_t ptent, swp_entry_t *entry)
6584 struct page *page = NULL;
6585 struct address_space *mapping;
6588 if (!vma->vm_file) /* anonymous vma */
6593 mapping = vma->vm_file->f_mapping;
6594 if (pte_none(ptent))
6595 pgoff = linear_page_index(vma, addr);
6596 else /* pte_file(ptent) is true */
6597 pgoff = pte_to_pgoff(ptent);
6599 /* page is moved even if it's not RSS of this task(page-faulted). */
6600 page = find_get_page(mapping, pgoff);
6603 /* shmem/tmpfs may report page out on swap: account for that too. */
6604 if (radix_tree_exceptional_entry(page)) {
6605 swp_entry_t swap = radix_to_swp_entry(page);
6606 if (do_swap_account)
6608 page = find_get_page(swap_address_space(swap), swap.val);
6614 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
6615 unsigned long addr, pte_t ptent, union mc_target *target)
6617 struct page *page = NULL;
6618 struct page_cgroup *pc;
6619 enum mc_target_type ret = MC_TARGET_NONE;
6620 swp_entry_t ent = { .val = 0 };
6622 if (pte_present(ptent))
6623 page = mc_handle_present_pte(vma, addr, ptent);
6624 else if (is_swap_pte(ptent))
6625 page = mc_handle_swap_pte(vma, addr, ptent, &ent);
6626 else if (pte_none(ptent) || pte_file(ptent))
6627 page = mc_handle_file_pte(vma, addr, ptent, &ent);
6629 if (!page && !ent.val)
6632 pc = lookup_page_cgroup(page);
6634 * Do only loose check w/o page_cgroup lock.
6635 * mem_cgroup_move_account() checks the pc is valid or not under
6638 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
6639 ret = MC_TARGET_PAGE;
6641 target->page = page;
6643 if (!ret || !target)
6646 /* There is a swap entry and a page doesn't exist or isn't charged */
6647 if (ent.val && !ret &&
6648 css_id(&mc.from->css) == lookup_swap_cgroup_id(ent)) {
6649 ret = MC_TARGET_SWAP;
6656 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
6658 * We don't consider swapping or file mapped pages because THP does not
6659 * support them for now.
6660 * Caller should make sure that pmd_trans_huge(pmd) is true.
6662 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
6663 unsigned long addr, pmd_t pmd, union mc_target *target)
6665 struct page *page = NULL;
6666 struct page_cgroup *pc;
6667 enum mc_target_type ret = MC_TARGET_NONE;
6669 page = pmd_page(pmd);
6670 VM_BUG_ON(!page || !PageHead(page));
6673 pc = lookup_page_cgroup(page);
6674 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
6675 ret = MC_TARGET_PAGE;
6678 target->page = page;
6684 static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
6685 unsigned long addr, pmd_t pmd, union mc_target *target)
6687 return MC_TARGET_NONE;
6691 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
6692 unsigned long addr, unsigned long end,
6693 struct mm_walk *walk)
6695 struct vm_area_struct *vma = walk->private;
6699 if (pmd_trans_huge_lock(pmd, vma) == 1) {
6700 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
6701 mc.precharge += HPAGE_PMD_NR;
6702 spin_unlock(&vma->vm_mm->page_table_lock);
6706 if (pmd_trans_unstable(pmd))
6708 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6709 for (; addr != end; pte++, addr += PAGE_SIZE)
6710 if (get_mctgt_type(vma, addr, *pte, NULL))
6711 mc.precharge++; /* increment precharge temporarily */
6712 pte_unmap_unlock(pte - 1, ptl);
6718 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
6720 unsigned long precharge;
6721 struct vm_area_struct *vma;
6723 down_read(&mm->mmap_sem);
6724 for (vma = mm->mmap; vma; vma = vma->vm_next) {
6725 struct mm_walk mem_cgroup_count_precharge_walk = {
6726 .pmd_entry = mem_cgroup_count_precharge_pte_range,
6730 if (is_vm_hugetlb_page(vma))
6732 walk_page_range(vma->vm_start, vma->vm_end,
6733 &mem_cgroup_count_precharge_walk);
6735 up_read(&mm->mmap_sem);
6737 precharge = mc.precharge;
6743 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
6745 unsigned long precharge = mem_cgroup_count_precharge(mm);
6747 VM_BUG_ON(mc.moving_task);
6748 mc.moving_task = current;
6749 return mem_cgroup_do_precharge(precharge);
6752 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
6753 static void __mem_cgroup_clear_mc(void)
6755 struct mem_cgroup *from = mc.from;
6756 struct mem_cgroup *to = mc.to;
6758 /* we must uncharge all the leftover precharges from mc.to */
6760 __mem_cgroup_cancel_charge(mc.to, mc.precharge);
6764 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
6765 * we must uncharge here.
6767 if (mc.moved_charge) {
6768 __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
6769 mc.moved_charge = 0;
6771 /* we must fixup refcnts and charges */
6772 if (mc.moved_swap) {
6773 /* uncharge swap account from the old cgroup */
6774 if (!mem_cgroup_is_root(mc.from))
6775 res_counter_uncharge(&mc.from->memsw,
6776 PAGE_SIZE * mc.moved_swap);
6777 __mem_cgroup_put(mc.from, mc.moved_swap);
6779 if (!mem_cgroup_is_root(mc.to)) {
6781 * we charged both to->res and to->memsw, so we should
6784 res_counter_uncharge(&mc.to->res,
6785 PAGE_SIZE * mc.moved_swap);
6787 /* we've already done mem_cgroup_get(mc.to) */
6790 memcg_oom_recover(from);
6791 memcg_oom_recover(to);
6792 wake_up_all(&mc.waitq);
6795 static void mem_cgroup_clear_mc(void)
6797 struct mem_cgroup *from = mc.from;
6800 * we must clear moving_task before waking up waiters at the end of
6803 mc.moving_task = NULL;
6804 __mem_cgroup_clear_mc();
6805 spin_lock(&mc.lock);
6808 spin_unlock(&mc.lock);
6809 mem_cgroup_end_move(from);
6812 static int mem_cgroup_can_attach(struct cgroup *cgroup,
6813 struct cgroup_taskset *tset)
6815 struct task_struct *p = cgroup_taskset_first(tset);
6817 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgroup);
6818 unsigned long move_charge_at_immigrate;
6821 * We are now commited to this value whatever it is. Changes in this
6822 * tunable will only affect upcoming migrations, not the current one.
6823 * So we need to save it, and keep it going.
6825 move_charge_at_immigrate = memcg->move_charge_at_immigrate;
6826 if (move_charge_at_immigrate) {
6827 struct mm_struct *mm;
6828 struct mem_cgroup *from = mem_cgroup_from_task(p);
6830 VM_BUG_ON(from == memcg);
6832 mm = get_task_mm(p);
6835 /* We move charges only when we move a owner of the mm */
6836 if (mm->owner == p) {
6839 VM_BUG_ON(mc.precharge);
6840 VM_BUG_ON(mc.moved_charge);
6841 VM_BUG_ON(mc.moved_swap);
6842 mem_cgroup_start_move(from);
6843 spin_lock(&mc.lock);
6846 mc.immigrate_flags = move_charge_at_immigrate;
6847 spin_unlock(&mc.lock);
6848 /* We set mc.moving_task later */
6850 ret = mem_cgroup_precharge_mc(mm);
6852 mem_cgroup_clear_mc();
6859 static int mem_cgroup_allow_attach(struct cgroup *cgroup,
6860 struct cgroup_taskset *tset)
6862 return subsys_cgroup_allow_attach(cgroup, tset);
6865 static void mem_cgroup_cancel_attach(struct cgroup *cgroup,
6866 struct cgroup_taskset *tset)
6868 mem_cgroup_clear_mc();
6871 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
6872 unsigned long addr, unsigned long end,
6873 struct mm_walk *walk)
6876 struct vm_area_struct *vma = walk->private;
6879 enum mc_target_type target_type;
6880 union mc_target target;
6882 struct page_cgroup *pc;
6885 * We don't take compound_lock() here but no race with splitting thp
6887 * - if pmd_trans_huge_lock() returns 1, the relevant thp is not
6888 * under splitting, which means there's no concurrent thp split,
6889 * - if another thread runs into split_huge_page() just after we
6890 * entered this if-block, the thread must wait for page table lock
6891 * to be unlocked in __split_huge_page_splitting(), where the main
6892 * part of thp split is not executed yet.
6894 if (pmd_trans_huge_lock(pmd, vma) == 1) {
6895 if (mc.precharge < HPAGE_PMD_NR) {
6896 spin_unlock(&vma->vm_mm->page_table_lock);
6899 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
6900 if (target_type == MC_TARGET_PAGE) {
6902 if (!isolate_lru_page(page)) {
6903 pc = lookup_page_cgroup(page);
6904 if (!mem_cgroup_move_account(page, HPAGE_PMD_NR,
6905 pc, mc.from, mc.to)) {
6906 mc.precharge -= HPAGE_PMD_NR;
6907 mc.moved_charge += HPAGE_PMD_NR;
6909 putback_lru_page(page);
6913 spin_unlock(&vma->vm_mm->page_table_lock);
6917 if (pmd_trans_unstable(pmd))
6920 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6921 for (; addr != end; addr += PAGE_SIZE) {
6922 pte_t ptent = *(pte++);
6928 switch (get_mctgt_type(vma, addr, ptent, &target)) {
6929 case MC_TARGET_PAGE:
6931 if (isolate_lru_page(page))
6933 pc = lookup_page_cgroup(page);
6934 if (!mem_cgroup_move_account(page, 1, pc,
6937 /* we uncharge from mc.from later. */
6940 putback_lru_page(page);
6941 put: /* get_mctgt_type() gets the page */
6944 case MC_TARGET_SWAP:
6946 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
6948 /* we fixup refcnts and charges later. */
6956 pte_unmap_unlock(pte - 1, ptl);
6961 * We have consumed all precharges we got in can_attach().
6962 * We try charge one by one, but don't do any additional
6963 * charges to mc.to if we have failed in charge once in attach()
6966 ret = mem_cgroup_do_precharge(1);
6974 static void mem_cgroup_move_charge(struct mm_struct *mm)
6976 struct vm_area_struct *vma;
6978 lru_add_drain_all();
6980 if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
6982 * Someone who are holding the mmap_sem might be waiting in
6983 * waitq. So we cancel all extra charges, wake up all waiters,
6984 * and retry. Because we cancel precharges, we might not be able
6985 * to move enough charges, but moving charge is a best-effort
6986 * feature anyway, so it wouldn't be a big problem.
6988 __mem_cgroup_clear_mc();
6992 for (vma = mm->mmap; vma; vma = vma->vm_next) {
6994 struct mm_walk mem_cgroup_move_charge_walk = {
6995 .pmd_entry = mem_cgroup_move_charge_pte_range,
6999 if (is_vm_hugetlb_page(vma))
7001 ret = walk_page_range(vma->vm_start, vma->vm_end,
7002 &mem_cgroup_move_charge_walk);
7005 * means we have consumed all precharges and failed in
7006 * doing additional charge. Just abandon here.
7010 up_read(&mm->mmap_sem);
7013 static void mem_cgroup_move_task(struct cgroup *cont,
7014 struct cgroup_taskset *tset)
7016 struct task_struct *p = cgroup_taskset_first(tset);
7017 struct mm_struct *mm = get_task_mm(p);
7021 mem_cgroup_move_charge(mm);
7025 mem_cgroup_clear_mc();
7027 #else /* !CONFIG_MMU */
7028 static int mem_cgroup_can_attach(struct cgroup *cgroup,
7029 struct cgroup_taskset *tset)
7033 static int mem_cgroup_allow_attach(struct cgroup *cgroup,
7034 struct cgroup_taskset *tset)
7038 static void mem_cgroup_cancel_attach(struct cgroup *cgroup,
7039 struct cgroup_taskset *tset)
7042 static void mem_cgroup_move_task(struct cgroup *cont,
7043 struct cgroup_taskset *tset)
7049 * Cgroup retains root cgroups across [un]mount cycles making it necessary
7050 * to verify sane_behavior flag on each mount attempt.
7052 static void mem_cgroup_bind(struct cgroup *root)
7055 * use_hierarchy is forced with sane_behavior. cgroup core
7056 * guarantees that @root doesn't have any children, so turning it
7057 * on for the root memcg is enough.
7059 if (cgroup_sane_behavior(root))
7060 mem_cgroup_from_cont(root)->use_hierarchy = true;
7063 struct cgroup_subsys mem_cgroup_subsys = {
7065 .subsys_id = mem_cgroup_subsys_id,
7066 .css_alloc = mem_cgroup_css_alloc,
7067 .css_online = mem_cgroup_css_online,
7068 .css_offline = mem_cgroup_css_offline,
7069 .css_free = mem_cgroup_css_free,
7070 .can_attach = mem_cgroup_can_attach,
7071 .cancel_attach = mem_cgroup_cancel_attach,
7072 .attach = mem_cgroup_move_task,
7073 .allow_attach = mem_cgroup_allow_attach,
7074 .bind = mem_cgroup_bind,
7075 .base_cftypes = mem_cgroup_files,
7080 #ifdef CONFIG_MEMCG_SWAP
7081 static int __init enable_swap_account(char *s)
7083 /* consider enabled if no parameter or 1 is given */
7084 if (!strcmp(s, "1"))
7085 really_do_swap_account = 1;
7086 else if (!strcmp(s, "0"))
7087 really_do_swap_account = 0;
7090 __setup("swapaccount=", enable_swap_account);
7092 static void __init memsw_file_init(void)
7094 WARN_ON(cgroup_add_cftypes(&mem_cgroup_subsys, memsw_cgroup_files));
7097 static void __init enable_swap_cgroup(void)
7099 if (!mem_cgroup_disabled() && really_do_swap_account) {
7100 do_swap_account = 1;
7106 static void __init enable_swap_cgroup(void)
7112 * subsys_initcall() for memory controller.
7114 * Some parts like hotcpu_notifier() have to be initialized from this context
7115 * because of lock dependencies (cgroup_lock -> cpu hotplug) but basically
7116 * everything that doesn't depend on a specific mem_cgroup structure should
7117 * be initialized from here.
7119 static int __init mem_cgroup_init(void)
7121 hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
7122 enable_swap_cgroup();
7123 mem_cgroup_soft_limit_tree_init();
7127 subsys_initcall(mem_cgroup_init);