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/mm_inline.h>
53 #include <linux/page_cgroup.h>
54 #include <linux/cpu.h>
55 #include <linux/oom.h>
59 #include <net/tcp_memcontrol.h>
61 #include <asm/uaccess.h>
63 #include <trace/events/vmscan.h>
65 struct cgroup_subsys mem_cgroup_subsys __read_mostly;
66 EXPORT_SYMBOL(mem_cgroup_subsys);
68 #define MEM_CGROUP_RECLAIM_RETRIES 5
69 static struct mem_cgroup *root_mem_cgroup __read_mostly;
71 #ifdef CONFIG_MEMCG_SWAP
72 /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
73 int do_swap_account __read_mostly;
75 /* for remember boot option*/
76 #ifdef CONFIG_MEMCG_SWAP_ENABLED
77 static int really_do_swap_account __initdata = 1;
79 static int really_do_swap_account __initdata = 0;
83 #define do_swap_account 0
88 * Statistics for memory cgroup.
90 enum mem_cgroup_stat_index {
92 * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
94 MEM_CGROUP_STAT_CACHE, /* # of pages charged as cache */
95 MEM_CGROUP_STAT_RSS, /* # of pages charged as anon rss */
96 MEM_CGROUP_STAT_FILE_MAPPED, /* # of pages charged as file rss */
97 MEM_CGROUP_STAT_SWAP, /* # of pages, swapped out */
98 MEM_CGROUP_STAT_NSTATS,
101 static const char * const mem_cgroup_stat_names[] = {
108 enum mem_cgroup_events_index {
109 MEM_CGROUP_EVENTS_PGPGIN, /* # of pages paged in */
110 MEM_CGROUP_EVENTS_PGPGOUT, /* # of pages paged out */
111 MEM_CGROUP_EVENTS_PGFAULT, /* # of page-faults */
112 MEM_CGROUP_EVENTS_PGMAJFAULT, /* # of major page-faults */
113 MEM_CGROUP_EVENTS_NSTATS,
116 static const char * const mem_cgroup_events_names[] = {
124 * Per memcg event counter is incremented at every pagein/pageout. With THP,
125 * it will be incremated by the number of pages. This counter is used for
126 * for trigger some periodic events. This is straightforward and better
127 * than using jiffies etc. to handle periodic memcg event.
129 enum mem_cgroup_events_target {
130 MEM_CGROUP_TARGET_THRESH,
131 MEM_CGROUP_TARGET_SOFTLIMIT,
132 MEM_CGROUP_TARGET_NUMAINFO,
135 #define THRESHOLDS_EVENTS_TARGET 128
136 #define SOFTLIMIT_EVENTS_TARGET 1024
137 #define NUMAINFO_EVENTS_TARGET 1024
139 struct mem_cgroup_stat_cpu {
140 long count[MEM_CGROUP_STAT_NSTATS];
141 unsigned long events[MEM_CGROUP_EVENTS_NSTATS];
142 unsigned long nr_page_events;
143 unsigned long targets[MEM_CGROUP_NTARGETS];
146 struct mem_cgroup_reclaim_iter {
147 /* css_id of the last scanned hierarchy member */
149 /* scan generation, increased every round-trip */
150 unsigned int generation;
154 * per-zone information in memory controller.
156 struct mem_cgroup_per_zone {
157 struct lruvec lruvec;
158 unsigned long lru_size[NR_LRU_LISTS];
160 struct mem_cgroup_reclaim_iter reclaim_iter[DEF_PRIORITY + 1];
162 struct rb_node tree_node; /* RB tree node */
163 unsigned long long usage_in_excess;/* Set to the value by which */
164 /* the soft limit is exceeded*/
166 struct mem_cgroup *memcg; /* Back pointer, we cannot */
167 /* use container_of */
170 struct mem_cgroup_per_node {
171 struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
174 struct mem_cgroup_lru_info {
175 struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
179 * Cgroups above their limits are maintained in a RB-Tree, independent of
180 * their hierarchy representation
183 struct mem_cgroup_tree_per_zone {
184 struct rb_root rb_root;
188 struct mem_cgroup_tree_per_node {
189 struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
192 struct mem_cgroup_tree {
193 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
196 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
198 struct mem_cgroup_threshold {
199 struct eventfd_ctx *eventfd;
204 struct mem_cgroup_threshold_ary {
205 /* An array index points to threshold just below or equal to usage. */
206 int current_threshold;
207 /* Size of entries[] */
209 /* Array of thresholds */
210 struct mem_cgroup_threshold entries[0];
213 struct mem_cgroup_thresholds {
214 /* Primary thresholds array */
215 struct mem_cgroup_threshold_ary *primary;
217 * Spare threshold array.
218 * This is needed to make mem_cgroup_unregister_event() "never fail".
219 * It must be able to store at least primary->size - 1 entries.
221 struct mem_cgroup_threshold_ary *spare;
225 struct mem_cgroup_eventfd_list {
226 struct list_head list;
227 struct eventfd_ctx *eventfd;
230 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
231 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
234 * The memory controller data structure. The memory controller controls both
235 * page cache and RSS per cgroup. We would eventually like to provide
236 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
237 * to help the administrator determine what knobs to tune.
239 * TODO: Add a water mark for the memory controller. Reclaim will begin when
240 * we hit the water mark. May be even add a low water mark, such that
241 * no reclaim occurs from a cgroup at it's low water mark, this is
242 * a feature that will be implemented much later in the future.
245 struct cgroup_subsys_state css;
247 * the counter to account for memory usage
249 struct res_counter res;
253 * the counter to account for mem+swap usage.
255 struct res_counter memsw;
258 * rcu_freeing is used only when freeing struct mem_cgroup,
259 * so put it into a union to avoid wasting more memory.
260 * It must be disjoint from the css field. It could be
261 * in a union with the res field, but res plays a much
262 * larger part in mem_cgroup life than memsw, and might
263 * be of interest, even at time of free, when debugging.
264 * So share rcu_head with the less interesting memsw.
266 struct rcu_head rcu_freeing;
268 * We also need some space for a worker in deferred freeing.
269 * By the time we call it, rcu_freeing is no longer in use.
271 struct work_struct work_freeing;
275 * the counter to account for kernel memory usage.
277 struct res_counter kmem;
279 * Per cgroup active and inactive list, similar to the
280 * per zone LRU lists.
282 struct mem_cgroup_lru_info info;
283 int last_scanned_node;
285 nodemask_t scan_nodes;
286 atomic_t numainfo_events;
287 atomic_t numainfo_updating;
290 * Should the accounting and control be hierarchical, per subtree?
293 unsigned long kmem_account_flags; /* See KMEM_ACCOUNTED_*, below */
301 /* OOM-Killer disable */
302 int oom_kill_disable;
304 /* set when res.limit == memsw.limit */
305 bool memsw_is_minimum;
307 /* protect arrays of thresholds */
308 struct mutex thresholds_lock;
310 /* thresholds for memory usage. RCU-protected */
311 struct mem_cgroup_thresholds thresholds;
313 /* thresholds for mem+swap usage. RCU-protected */
314 struct mem_cgroup_thresholds memsw_thresholds;
316 /* For oom notifier event fd */
317 struct list_head oom_notify;
320 * Should we move charges of a task when a task is moved into this
321 * mem_cgroup ? And what type of charges should we move ?
323 unsigned long move_charge_at_immigrate;
325 * set > 0 if pages under this cgroup are moving to other cgroup.
327 atomic_t moving_account;
328 /* taken only while moving_account > 0 */
329 spinlock_t move_lock;
333 struct mem_cgroup_stat_cpu __percpu *stat;
335 * used when a cpu is offlined or other synchronizations
336 * See mem_cgroup_read_stat().
338 struct mem_cgroup_stat_cpu nocpu_base;
339 spinlock_t pcp_counter_lock;
341 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_INET)
342 struct tcp_memcontrol tcp_mem;
344 #if defined(CONFIG_MEMCG_KMEM)
345 /* analogous to slab_common's slab_caches list. per-memcg */
346 struct list_head memcg_slab_caches;
347 /* Not a spinlock, we can take a lot of time walking the list */
348 struct mutex slab_caches_mutex;
349 /* Index in the kmem_cache->memcg_params->memcg_caches array */
354 /* internal only representation about the status of kmem accounting. */
356 KMEM_ACCOUNTED_ACTIVE = 0, /* accounted by this cgroup itself */
357 KMEM_ACCOUNTED_ACTIVATED, /* static key enabled. */
358 KMEM_ACCOUNTED_DEAD, /* dead memcg with pending kmem charges */
361 /* We account when limit is on, but only after call sites are patched */
362 #define KMEM_ACCOUNTED_MASK \
363 ((1 << KMEM_ACCOUNTED_ACTIVE) | (1 << KMEM_ACCOUNTED_ACTIVATED))
365 #ifdef CONFIG_MEMCG_KMEM
366 static inline void memcg_kmem_set_active(struct mem_cgroup *memcg)
368 set_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags);
371 static bool memcg_kmem_is_active(struct mem_cgroup *memcg)
373 return test_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags);
376 static void memcg_kmem_set_activated(struct mem_cgroup *memcg)
378 set_bit(KMEM_ACCOUNTED_ACTIVATED, &memcg->kmem_account_flags);
381 static void memcg_kmem_mark_dead(struct mem_cgroup *memcg)
383 if (test_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags))
384 set_bit(KMEM_ACCOUNTED_DEAD, &memcg->kmem_account_flags);
387 static bool memcg_kmem_test_and_clear_dead(struct mem_cgroup *memcg)
389 return test_and_clear_bit(KMEM_ACCOUNTED_DEAD,
390 &memcg->kmem_account_flags);
394 /* Stuffs for move charges at task migration. */
396 * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a
397 * left-shifted bitmap of these types.
400 MOVE_CHARGE_TYPE_ANON, /* private anonymous page and swap of it */
401 MOVE_CHARGE_TYPE_FILE, /* file page(including tmpfs) and swap of it */
405 /* "mc" and its members are protected by cgroup_mutex */
406 static struct move_charge_struct {
407 spinlock_t lock; /* for from, to */
408 struct mem_cgroup *from;
409 struct mem_cgroup *to;
410 unsigned long precharge;
411 unsigned long moved_charge;
412 unsigned long moved_swap;
413 struct task_struct *moving_task; /* a task moving charges */
414 wait_queue_head_t waitq; /* a waitq for other context */
416 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
417 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
420 static bool move_anon(void)
422 return test_bit(MOVE_CHARGE_TYPE_ANON,
423 &mc.to->move_charge_at_immigrate);
426 static bool move_file(void)
428 return test_bit(MOVE_CHARGE_TYPE_FILE,
429 &mc.to->move_charge_at_immigrate);
433 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
434 * limit reclaim to prevent infinite loops, if they ever occur.
436 #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
437 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
440 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
441 MEM_CGROUP_CHARGE_TYPE_ANON,
442 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
443 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
447 /* for encoding cft->private value on file */
455 #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
456 #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
457 #define MEMFILE_ATTR(val) ((val) & 0xffff)
458 /* Used for OOM nofiier */
459 #define OOM_CONTROL (0)
462 * Reclaim flags for mem_cgroup_hierarchical_reclaim
464 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
465 #define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
466 #define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
467 #define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
469 static void mem_cgroup_get(struct mem_cgroup *memcg);
470 static void mem_cgroup_put(struct mem_cgroup *memcg);
473 struct mem_cgroup *mem_cgroup_from_css(struct cgroup_subsys_state *s)
475 return container_of(s, struct mem_cgroup, css);
478 static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
480 return (memcg == root_mem_cgroup);
483 /* Writing them here to avoid exposing memcg's inner layout */
484 #if defined(CONFIG_INET) && defined(CONFIG_MEMCG_KMEM)
486 void sock_update_memcg(struct sock *sk)
488 if (mem_cgroup_sockets_enabled) {
489 struct mem_cgroup *memcg;
490 struct cg_proto *cg_proto;
492 BUG_ON(!sk->sk_prot->proto_cgroup);
494 /* Socket cloning can throw us here with sk_cgrp already
495 * filled. It won't however, necessarily happen from
496 * process context. So the test for root memcg given
497 * the current task's memcg won't help us in this case.
499 * Respecting the original socket's memcg is a better
500 * decision in this case.
503 BUG_ON(mem_cgroup_is_root(sk->sk_cgrp->memcg));
504 mem_cgroup_get(sk->sk_cgrp->memcg);
509 memcg = mem_cgroup_from_task(current);
510 cg_proto = sk->sk_prot->proto_cgroup(memcg);
511 if (!mem_cgroup_is_root(memcg) && memcg_proto_active(cg_proto)) {
512 mem_cgroup_get(memcg);
513 sk->sk_cgrp = cg_proto;
518 EXPORT_SYMBOL(sock_update_memcg);
520 void sock_release_memcg(struct sock *sk)
522 if (mem_cgroup_sockets_enabled && sk->sk_cgrp) {
523 struct mem_cgroup *memcg;
524 WARN_ON(!sk->sk_cgrp->memcg);
525 memcg = sk->sk_cgrp->memcg;
526 mem_cgroup_put(memcg);
530 struct cg_proto *tcp_proto_cgroup(struct mem_cgroup *memcg)
532 if (!memcg || mem_cgroup_is_root(memcg))
535 return &memcg->tcp_mem.cg_proto;
537 EXPORT_SYMBOL(tcp_proto_cgroup);
539 static void disarm_sock_keys(struct mem_cgroup *memcg)
541 if (!memcg_proto_activated(&memcg->tcp_mem.cg_proto))
543 static_key_slow_dec(&memcg_socket_limit_enabled);
546 static void disarm_sock_keys(struct mem_cgroup *memcg)
551 #ifdef CONFIG_MEMCG_KMEM
552 struct static_key memcg_kmem_enabled_key;
554 static void disarm_kmem_keys(struct mem_cgroup *memcg)
556 if (memcg_kmem_is_active(memcg))
557 static_key_slow_dec(&memcg_kmem_enabled_key);
559 * This check can't live in kmem destruction function,
560 * since the charges will outlive the cgroup
562 WARN_ON(res_counter_read_u64(&memcg->kmem, RES_USAGE) != 0);
565 static void disarm_kmem_keys(struct mem_cgroup *memcg)
568 #endif /* CONFIG_MEMCG_KMEM */
570 static void disarm_static_keys(struct mem_cgroup *memcg)
572 disarm_sock_keys(memcg);
573 disarm_kmem_keys(memcg);
576 static void drain_all_stock_async(struct mem_cgroup *memcg);
578 static struct mem_cgroup_per_zone *
579 mem_cgroup_zoneinfo(struct mem_cgroup *memcg, int nid, int zid)
581 return &memcg->info.nodeinfo[nid]->zoneinfo[zid];
584 struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *memcg)
589 static struct mem_cgroup_per_zone *
590 page_cgroup_zoneinfo(struct mem_cgroup *memcg, struct page *page)
592 int nid = page_to_nid(page);
593 int zid = page_zonenum(page);
595 return mem_cgroup_zoneinfo(memcg, nid, zid);
598 static struct mem_cgroup_tree_per_zone *
599 soft_limit_tree_node_zone(int nid, int zid)
601 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
604 static struct mem_cgroup_tree_per_zone *
605 soft_limit_tree_from_page(struct page *page)
607 int nid = page_to_nid(page);
608 int zid = page_zonenum(page);
610 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
614 __mem_cgroup_insert_exceeded(struct mem_cgroup *memcg,
615 struct mem_cgroup_per_zone *mz,
616 struct mem_cgroup_tree_per_zone *mctz,
617 unsigned long long new_usage_in_excess)
619 struct rb_node **p = &mctz->rb_root.rb_node;
620 struct rb_node *parent = NULL;
621 struct mem_cgroup_per_zone *mz_node;
626 mz->usage_in_excess = new_usage_in_excess;
627 if (!mz->usage_in_excess)
631 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
633 if (mz->usage_in_excess < mz_node->usage_in_excess)
636 * We can't avoid mem cgroups that are over their soft
637 * limit by the same amount
639 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
642 rb_link_node(&mz->tree_node, parent, p);
643 rb_insert_color(&mz->tree_node, &mctz->rb_root);
648 __mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
649 struct mem_cgroup_per_zone *mz,
650 struct mem_cgroup_tree_per_zone *mctz)
654 rb_erase(&mz->tree_node, &mctz->rb_root);
659 mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
660 struct mem_cgroup_per_zone *mz,
661 struct mem_cgroup_tree_per_zone *mctz)
663 spin_lock(&mctz->lock);
664 __mem_cgroup_remove_exceeded(memcg, mz, mctz);
665 spin_unlock(&mctz->lock);
669 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
671 unsigned long long excess;
672 struct mem_cgroup_per_zone *mz;
673 struct mem_cgroup_tree_per_zone *mctz;
674 int nid = page_to_nid(page);
675 int zid = page_zonenum(page);
676 mctz = soft_limit_tree_from_page(page);
679 * Necessary to update all ancestors when hierarchy is used.
680 * because their event counter is not touched.
682 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
683 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
684 excess = res_counter_soft_limit_excess(&memcg->res);
686 * We have to update the tree if mz is on RB-tree or
687 * mem is over its softlimit.
689 if (excess || mz->on_tree) {
690 spin_lock(&mctz->lock);
691 /* if on-tree, remove it */
693 __mem_cgroup_remove_exceeded(memcg, mz, mctz);
695 * Insert again. mz->usage_in_excess will be updated.
696 * If excess is 0, no tree ops.
698 __mem_cgroup_insert_exceeded(memcg, mz, mctz, excess);
699 spin_unlock(&mctz->lock);
704 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
707 struct mem_cgroup_per_zone *mz;
708 struct mem_cgroup_tree_per_zone *mctz;
710 for_each_node(node) {
711 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
712 mz = mem_cgroup_zoneinfo(memcg, node, zone);
713 mctz = soft_limit_tree_node_zone(node, zone);
714 mem_cgroup_remove_exceeded(memcg, mz, mctz);
719 static struct mem_cgroup_per_zone *
720 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
722 struct rb_node *rightmost = NULL;
723 struct mem_cgroup_per_zone *mz;
727 rightmost = rb_last(&mctz->rb_root);
729 goto done; /* Nothing to reclaim from */
731 mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
733 * Remove the node now but someone else can add it back,
734 * we will to add it back at the end of reclaim to its correct
735 * position in the tree.
737 __mem_cgroup_remove_exceeded(mz->memcg, mz, mctz);
738 if (!res_counter_soft_limit_excess(&mz->memcg->res) ||
739 !css_tryget(&mz->memcg->css))
745 static struct mem_cgroup_per_zone *
746 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
748 struct mem_cgroup_per_zone *mz;
750 spin_lock(&mctz->lock);
751 mz = __mem_cgroup_largest_soft_limit_node(mctz);
752 spin_unlock(&mctz->lock);
757 * Implementation Note: reading percpu statistics for memcg.
759 * Both of vmstat[] and percpu_counter has threshold and do periodic
760 * synchronization to implement "quick" read. There are trade-off between
761 * reading cost and precision of value. Then, we may have a chance to implement
762 * a periodic synchronizion of counter in memcg's counter.
764 * But this _read() function is used for user interface now. The user accounts
765 * memory usage by memory cgroup and he _always_ requires exact value because
766 * he accounts memory. Even if we provide quick-and-fuzzy read, we always
767 * have to visit all online cpus and make sum. So, for now, unnecessary
768 * synchronization is not implemented. (just implemented for cpu hotplug)
770 * If there are kernel internal actions which can make use of some not-exact
771 * value, and reading all cpu value can be performance bottleneck in some
772 * common workload, threashold and synchonization as vmstat[] should be
775 static long mem_cgroup_read_stat(struct mem_cgroup *memcg,
776 enum mem_cgroup_stat_index idx)
782 for_each_online_cpu(cpu)
783 val += per_cpu(memcg->stat->count[idx], cpu);
784 #ifdef CONFIG_HOTPLUG_CPU
785 spin_lock(&memcg->pcp_counter_lock);
786 val += memcg->nocpu_base.count[idx];
787 spin_unlock(&memcg->pcp_counter_lock);
793 static void mem_cgroup_swap_statistics(struct mem_cgroup *memcg,
796 int val = (charge) ? 1 : -1;
797 this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_SWAP], val);
800 static unsigned long mem_cgroup_read_events(struct mem_cgroup *memcg,
801 enum mem_cgroup_events_index idx)
803 unsigned long val = 0;
806 for_each_online_cpu(cpu)
807 val += per_cpu(memcg->stat->events[idx], cpu);
808 #ifdef CONFIG_HOTPLUG_CPU
809 spin_lock(&memcg->pcp_counter_lock);
810 val += memcg->nocpu_base.events[idx];
811 spin_unlock(&memcg->pcp_counter_lock);
816 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
817 bool anon, int nr_pages)
822 * Here, RSS means 'mapped anon' and anon's SwapCache. Shmem/tmpfs is
823 * counted as CACHE even if it's on ANON LRU.
826 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS],
829 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_CACHE],
832 /* pagein of a big page is an event. So, ignore page size */
834 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGIN]);
836 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]);
837 nr_pages = -nr_pages; /* for event */
840 __this_cpu_add(memcg->stat->nr_page_events, nr_pages);
846 mem_cgroup_get_lru_size(struct lruvec *lruvec, enum lru_list lru)
848 struct mem_cgroup_per_zone *mz;
850 mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
851 return mz->lru_size[lru];
855 mem_cgroup_zone_nr_lru_pages(struct mem_cgroup *memcg, int nid, int zid,
856 unsigned int lru_mask)
858 struct mem_cgroup_per_zone *mz;
860 unsigned long ret = 0;
862 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
865 if (BIT(lru) & lru_mask)
866 ret += mz->lru_size[lru];
872 mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
873 int nid, unsigned int lru_mask)
878 for (zid = 0; zid < MAX_NR_ZONES; zid++)
879 total += mem_cgroup_zone_nr_lru_pages(memcg,
885 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
886 unsigned int lru_mask)
891 for_each_node_state(nid, N_MEMORY)
892 total += mem_cgroup_node_nr_lru_pages(memcg, nid, lru_mask);
896 static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
897 enum mem_cgroup_events_target target)
899 unsigned long val, next;
901 val = __this_cpu_read(memcg->stat->nr_page_events);
902 next = __this_cpu_read(memcg->stat->targets[target]);
903 /* from time_after() in jiffies.h */
904 if ((long)next - (long)val < 0) {
906 case MEM_CGROUP_TARGET_THRESH:
907 next = val + THRESHOLDS_EVENTS_TARGET;
909 case MEM_CGROUP_TARGET_SOFTLIMIT:
910 next = val + SOFTLIMIT_EVENTS_TARGET;
912 case MEM_CGROUP_TARGET_NUMAINFO:
913 next = val + NUMAINFO_EVENTS_TARGET;
918 __this_cpu_write(memcg->stat->targets[target], next);
925 * Check events in order.
928 static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
931 /* threshold event is triggered in finer grain than soft limit */
932 if (unlikely(mem_cgroup_event_ratelimit(memcg,
933 MEM_CGROUP_TARGET_THRESH))) {
935 bool do_numainfo __maybe_unused;
937 do_softlimit = mem_cgroup_event_ratelimit(memcg,
938 MEM_CGROUP_TARGET_SOFTLIMIT);
940 do_numainfo = mem_cgroup_event_ratelimit(memcg,
941 MEM_CGROUP_TARGET_NUMAINFO);
945 mem_cgroup_threshold(memcg);
946 if (unlikely(do_softlimit))
947 mem_cgroup_update_tree(memcg, page);
949 if (unlikely(do_numainfo))
950 atomic_inc(&memcg->numainfo_events);
956 struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
958 return mem_cgroup_from_css(
959 cgroup_subsys_state(cont, mem_cgroup_subsys_id));
962 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
965 * mm_update_next_owner() may clear mm->owner to NULL
966 * if it races with swapoff, page migration, etc.
967 * So this can be called with p == NULL.
972 return mem_cgroup_from_css(task_subsys_state(p, mem_cgroup_subsys_id));
975 struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
977 struct mem_cgroup *memcg = NULL;
982 * Because we have no locks, mm->owner's may be being moved to other
983 * cgroup. We use css_tryget() here even if this looks
984 * pessimistic (rather than adding locks here).
988 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
989 if (unlikely(!memcg))
991 } while (!css_tryget(&memcg->css));
997 * mem_cgroup_iter - iterate over memory cgroup hierarchy
998 * @root: hierarchy root
999 * @prev: previously returned memcg, NULL on first invocation
1000 * @reclaim: cookie for shared reclaim walks, NULL for full walks
1002 * Returns references to children of the hierarchy below @root, or
1003 * @root itself, or %NULL after a full round-trip.
1005 * Caller must pass the return value in @prev on subsequent
1006 * invocations for reference counting, or use mem_cgroup_iter_break()
1007 * to cancel a hierarchy walk before the round-trip is complete.
1009 * Reclaimers can specify a zone and a priority level in @reclaim to
1010 * divide up the memcgs in the hierarchy among all concurrent
1011 * reclaimers operating on the same zone and priority.
1013 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
1014 struct mem_cgroup *prev,
1015 struct mem_cgroup_reclaim_cookie *reclaim)
1017 struct mem_cgroup *memcg = NULL;
1020 if (mem_cgroup_disabled())
1024 root = root_mem_cgroup;
1026 if (prev && !reclaim)
1027 id = css_id(&prev->css);
1029 if (prev && prev != root)
1030 css_put(&prev->css);
1032 if (!root->use_hierarchy && root != root_mem_cgroup) {
1039 struct mem_cgroup_reclaim_iter *uninitialized_var(iter);
1040 struct cgroup_subsys_state *css;
1043 int nid = zone_to_nid(reclaim->zone);
1044 int zid = zone_idx(reclaim->zone);
1045 struct mem_cgroup_per_zone *mz;
1047 mz = mem_cgroup_zoneinfo(root, nid, zid);
1048 iter = &mz->reclaim_iter[reclaim->priority];
1049 if (prev && reclaim->generation != iter->generation)
1051 id = iter->position;
1055 css = css_get_next(&mem_cgroup_subsys, id + 1, &root->css, &id);
1057 if (css == &root->css || css_tryget(css))
1058 memcg = mem_cgroup_from_css(css);
1064 iter->position = id;
1067 else if (!prev && memcg)
1068 reclaim->generation = iter->generation;
1078 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1079 * @root: hierarchy root
1080 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1082 void mem_cgroup_iter_break(struct mem_cgroup *root,
1083 struct mem_cgroup *prev)
1086 root = root_mem_cgroup;
1087 if (prev && prev != root)
1088 css_put(&prev->css);
1092 * Iteration constructs for visiting all cgroups (under a tree). If
1093 * loops are exited prematurely (break), mem_cgroup_iter_break() must
1094 * be used for reference counting.
1096 #define for_each_mem_cgroup_tree(iter, root) \
1097 for (iter = mem_cgroup_iter(root, NULL, NULL); \
1099 iter = mem_cgroup_iter(root, iter, NULL))
1101 #define for_each_mem_cgroup(iter) \
1102 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
1104 iter = mem_cgroup_iter(NULL, iter, NULL))
1106 void __mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx)
1108 struct mem_cgroup *memcg;
1111 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1112 if (unlikely(!memcg))
1117 this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGFAULT]);
1120 this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGMAJFAULT]);
1128 EXPORT_SYMBOL(__mem_cgroup_count_vm_event);
1131 * mem_cgroup_zone_lruvec - get the lru list vector for a zone and memcg
1132 * @zone: zone of the wanted lruvec
1133 * @memcg: memcg of the wanted lruvec
1135 * Returns the lru list vector holding pages for the given @zone and
1136 * @mem. This can be the global zone lruvec, if the memory controller
1139 struct lruvec *mem_cgroup_zone_lruvec(struct zone *zone,
1140 struct mem_cgroup *memcg)
1142 struct mem_cgroup_per_zone *mz;
1143 struct lruvec *lruvec;
1145 if (mem_cgroup_disabled()) {
1146 lruvec = &zone->lruvec;
1150 mz = mem_cgroup_zoneinfo(memcg, zone_to_nid(zone), zone_idx(zone));
1151 lruvec = &mz->lruvec;
1154 * Since a node can be onlined after the mem_cgroup was created,
1155 * we have to be prepared to initialize lruvec->zone here;
1156 * and if offlined then reonlined, we need to reinitialize it.
1158 if (unlikely(lruvec->zone != zone))
1159 lruvec->zone = zone;
1164 * Following LRU functions are allowed to be used without PCG_LOCK.
1165 * Operations are called by routine of global LRU independently from memcg.
1166 * What we have to take care of here is validness of pc->mem_cgroup.
1168 * Changes to pc->mem_cgroup happens when
1171 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
1172 * It is added to LRU before charge.
1173 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
1174 * When moving account, the page is not on LRU. It's isolated.
1178 * mem_cgroup_page_lruvec - return lruvec for adding an lru page
1180 * @zone: zone of the page
1182 struct lruvec *mem_cgroup_page_lruvec(struct page *page, struct zone *zone)
1184 struct mem_cgroup_per_zone *mz;
1185 struct mem_cgroup *memcg;
1186 struct page_cgroup *pc;
1187 struct lruvec *lruvec;
1189 if (mem_cgroup_disabled()) {
1190 lruvec = &zone->lruvec;
1194 pc = lookup_page_cgroup(page);
1195 memcg = pc->mem_cgroup;
1198 * Surreptitiously switch any uncharged offlist page to root:
1199 * an uncharged page off lru does nothing to secure
1200 * its former mem_cgroup from sudden removal.
1202 * Our caller holds lru_lock, and PageCgroupUsed is updated
1203 * under page_cgroup lock: between them, they make all uses
1204 * of pc->mem_cgroup safe.
1206 if (!PageLRU(page) && !PageCgroupUsed(pc) && memcg != root_mem_cgroup)
1207 pc->mem_cgroup = memcg = root_mem_cgroup;
1209 mz = page_cgroup_zoneinfo(memcg, page);
1210 lruvec = &mz->lruvec;
1213 * Since a node can be onlined after the mem_cgroup was created,
1214 * we have to be prepared to initialize lruvec->zone here;
1215 * and if offlined then reonlined, we need to reinitialize it.
1217 if (unlikely(lruvec->zone != zone))
1218 lruvec->zone = zone;
1223 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1224 * @lruvec: mem_cgroup per zone lru vector
1225 * @lru: index of lru list the page is sitting on
1226 * @nr_pages: positive when adding or negative when removing
1228 * This function must be called when a page is added to or removed from an
1231 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1234 struct mem_cgroup_per_zone *mz;
1235 unsigned long *lru_size;
1237 if (mem_cgroup_disabled())
1240 mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
1241 lru_size = mz->lru_size + lru;
1242 *lru_size += nr_pages;
1243 VM_BUG_ON((long)(*lru_size) < 0);
1247 * Checks whether given mem is same or in the root_mem_cgroup's
1250 bool __mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1251 struct mem_cgroup *memcg)
1253 if (root_memcg == memcg)
1255 if (!root_memcg->use_hierarchy || !memcg)
1257 return css_is_ancestor(&memcg->css, &root_memcg->css);
1260 static bool mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1261 struct mem_cgroup *memcg)
1266 ret = __mem_cgroup_same_or_subtree(root_memcg, memcg);
1271 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *memcg)
1274 struct mem_cgroup *curr = NULL;
1275 struct task_struct *p;
1277 p = find_lock_task_mm(task);
1279 curr = try_get_mem_cgroup_from_mm(p->mm);
1283 * All threads may have already detached their mm's, but the oom
1284 * killer still needs to detect if they have already been oom
1285 * killed to prevent needlessly killing additional tasks.
1288 curr = mem_cgroup_from_task(task);
1290 css_get(&curr->css);
1296 * We should check use_hierarchy of "memcg" not "curr". Because checking
1297 * use_hierarchy of "curr" here make this function true if hierarchy is
1298 * enabled in "curr" and "curr" is a child of "memcg" in *cgroup*
1299 * hierarchy(even if use_hierarchy is disabled in "memcg").
1301 ret = mem_cgroup_same_or_subtree(memcg, curr);
1302 css_put(&curr->css);
1306 int mem_cgroup_inactive_anon_is_low(struct lruvec *lruvec)
1308 unsigned long inactive_ratio;
1309 unsigned long inactive;
1310 unsigned long active;
1313 inactive = mem_cgroup_get_lru_size(lruvec, LRU_INACTIVE_ANON);
1314 active = mem_cgroup_get_lru_size(lruvec, LRU_ACTIVE_ANON);
1316 gb = (inactive + active) >> (30 - PAGE_SHIFT);
1318 inactive_ratio = int_sqrt(10 * gb);
1322 return inactive * inactive_ratio < active;
1325 int mem_cgroup_inactive_file_is_low(struct lruvec *lruvec)
1327 unsigned long active;
1328 unsigned long inactive;
1330 inactive = mem_cgroup_get_lru_size(lruvec, LRU_INACTIVE_FILE);
1331 active = mem_cgroup_get_lru_size(lruvec, LRU_ACTIVE_FILE);
1333 return (active > inactive);
1336 #define mem_cgroup_from_res_counter(counter, member) \
1337 container_of(counter, struct mem_cgroup, member)
1340 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1341 * @memcg: the memory cgroup
1343 * Returns the maximum amount of memory @mem can be charged with, in
1346 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1348 unsigned long long margin;
1350 margin = res_counter_margin(&memcg->res);
1351 if (do_swap_account)
1352 margin = min(margin, res_counter_margin(&memcg->memsw));
1353 return margin >> PAGE_SHIFT;
1356 int mem_cgroup_swappiness(struct mem_cgroup *memcg)
1358 struct cgroup *cgrp = memcg->css.cgroup;
1361 if (cgrp->parent == NULL)
1362 return vm_swappiness;
1364 return memcg->swappiness;
1368 * memcg->moving_account is used for checking possibility that some thread is
1369 * calling move_account(). When a thread on CPU-A starts moving pages under
1370 * a memcg, other threads should check memcg->moving_account under
1371 * rcu_read_lock(), like this:
1375 * memcg->moving_account+1 if (memcg->mocing_account)
1377 * synchronize_rcu() update something.
1382 /* for quick checking without looking up memcg */
1383 atomic_t memcg_moving __read_mostly;
1385 static void mem_cgroup_start_move(struct mem_cgroup *memcg)
1387 atomic_inc(&memcg_moving);
1388 atomic_inc(&memcg->moving_account);
1392 static void mem_cgroup_end_move(struct mem_cgroup *memcg)
1395 * Now, mem_cgroup_clear_mc() may call this function with NULL.
1396 * We check NULL in callee rather than caller.
1399 atomic_dec(&memcg_moving);
1400 atomic_dec(&memcg->moving_account);
1405 * 2 routines for checking "mem" is under move_account() or not.
1407 * mem_cgroup_stolen() - checking whether a cgroup is mc.from or not. This
1408 * is used for avoiding races in accounting. If true,
1409 * pc->mem_cgroup may be overwritten.
1411 * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
1412 * under hierarchy of moving cgroups. This is for
1413 * waiting at hith-memory prressure caused by "move".
1416 static bool mem_cgroup_stolen(struct mem_cgroup *memcg)
1418 VM_BUG_ON(!rcu_read_lock_held());
1419 return atomic_read(&memcg->moving_account) > 0;
1422 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1424 struct mem_cgroup *from;
1425 struct mem_cgroup *to;
1428 * Unlike task_move routines, we access mc.to, mc.from not under
1429 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1431 spin_lock(&mc.lock);
1437 ret = mem_cgroup_same_or_subtree(memcg, from)
1438 || mem_cgroup_same_or_subtree(memcg, to);
1440 spin_unlock(&mc.lock);
1444 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1446 if (mc.moving_task && current != mc.moving_task) {
1447 if (mem_cgroup_under_move(memcg)) {
1449 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1450 /* moving charge context might have finished. */
1453 finish_wait(&mc.waitq, &wait);
1461 * Take this lock when
1462 * - a code tries to modify page's memcg while it's USED.
1463 * - a code tries to modify page state accounting in a memcg.
1464 * see mem_cgroup_stolen(), too.
1466 static void move_lock_mem_cgroup(struct mem_cgroup *memcg,
1467 unsigned long *flags)
1469 spin_lock_irqsave(&memcg->move_lock, *flags);
1472 static void move_unlock_mem_cgroup(struct mem_cgroup *memcg,
1473 unsigned long *flags)
1475 spin_unlock_irqrestore(&memcg->move_lock, *flags);
1479 * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode.
1480 * @memcg: The memory cgroup that went over limit
1481 * @p: Task that is going to be killed
1483 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1486 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1488 struct cgroup *task_cgrp;
1489 struct cgroup *mem_cgrp;
1491 * Need a buffer in BSS, can't rely on allocations. The code relies
1492 * on the assumption that OOM is serialized for memory controller.
1493 * If this assumption is broken, revisit this code.
1495 static char memcg_name[PATH_MAX];
1503 mem_cgrp = memcg->css.cgroup;
1504 task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1506 ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1509 * Unfortunately, we are unable to convert to a useful name
1510 * But we'll still print out the usage information
1517 printk(KERN_INFO "Task in %s killed", memcg_name);
1520 ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1528 * Continues from above, so we don't need an KERN_ level
1530 printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
1533 printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
1534 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1535 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1536 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1537 printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
1539 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1540 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1541 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1542 printk(KERN_INFO "kmem: usage %llukB, limit %llukB, failcnt %llu\n",
1543 res_counter_read_u64(&memcg->kmem, RES_USAGE) >> 10,
1544 res_counter_read_u64(&memcg->kmem, RES_LIMIT) >> 10,
1545 res_counter_read_u64(&memcg->kmem, RES_FAILCNT));
1549 * This function returns the number of memcg under hierarchy tree. Returns
1550 * 1(self count) if no children.
1552 static int mem_cgroup_count_children(struct mem_cgroup *memcg)
1555 struct mem_cgroup *iter;
1557 for_each_mem_cgroup_tree(iter, memcg)
1563 * Return the memory (and swap, if configured) limit for a memcg.
1565 static u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
1569 limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
1572 * Do not consider swap space if we cannot swap due to swappiness
1574 if (mem_cgroup_swappiness(memcg)) {
1577 limit += total_swap_pages << PAGE_SHIFT;
1578 memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
1581 * If memsw is finite and limits the amount of swap space
1582 * available to this memcg, return that limit.
1584 limit = min(limit, memsw);
1590 static void mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1593 struct mem_cgroup *iter;
1594 unsigned long chosen_points = 0;
1595 unsigned long totalpages;
1596 unsigned int points = 0;
1597 struct task_struct *chosen = NULL;
1600 * If current has a pending SIGKILL, then automatically select it. The
1601 * goal is to allow it to allocate so that it may quickly exit and free
1604 if (fatal_signal_pending(current)) {
1605 set_thread_flag(TIF_MEMDIE);
1609 check_panic_on_oom(CONSTRAINT_MEMCG, gfp_mask, order, NULL);
1610 totalpages = mem_cgroup_get_limit(memcg) >> PAGE_SHIFT ? : 1;
1611 for_each_mem_cgroup_tree(iter, memcg) {
1612 struct cgroup *cgroup = iter->css.cgroup;
1613 struct cgroup_iter it;
1614 struct task_struct *task;
1616 cgroup_iter_start(cgroup, &it);
1617 while ((task = cgroup_iter_next(cgroup, &it))) {
1618 switch (oom_scan_process_thread(task, totalpages, NULL,
1620 case OOM_SCAN_SELECT:
1622 put_task_struct(chosen);
1624 chosen_points = ULONG_MAX;
1625 get_task_struct(chosen);
1627 case OOM_SCAN_CONTINUE:
1629 case OOM_SCAN_ABORT:
1630 cgroup_iter_end(cgroup, &it);
1631 mem_cgroup_iter_break(memcg, iter);
1633 put_task_struct(chosen);
1638 points = oom_badness(task, memcg, NULL, totalpages);
1639 if (points > chosen_points) {
1641 put_task_struct(chosen);
1643 chosen_points = points;
1644 get_task_struct(chosen);
1647 cgroup_iter_end(cgroup, &it);
1652 points = chosen_points * 1000 / totalpages;
1653 oom_kill_process(chosen, gfp_mask, order, points, totalpages, memcg,
1654 NULL, "Memory cgroup out of memory");
1657 static unsigned long mem_cgroup_reclaim(struct mem_cgroup *memcg,
1659 unsigned long flags)
1661 unsigned long total = 0;
1662 bool noswap = false;
1665 if (flags & MEM_CGROUP_RECLAIM_NOSWAP)
1667 if (!(flags & MEM_CGROUP_RECLAIM_SHRINK) && memcg->memsw_is_minimum)
1670 for (loop = 0; loop < MEM_CGROUP_MAX_RECLAIM_LOOPS; loop++) {
1672 drain_all_stock_async(memcg);
1673 total += try_to_free_mem_cgroup_pages(memcg, gfp_mask, noswap);
1675 * Allow limit shrinkers, which are triggered directly
1676 * by userspace, to catch signals and stop reclaim
1677 * after minimal progress, regardless of the margin.
1679 if (total && (flags & MEM_CGROUP_RECLAIM_SHRINK))
1681 if (mem_cgroup_margin(memcg))
1684 * If nothing was reclaimed after two attempts, there
1685 * may be no reclaimable pages in this hierarchy.
1694 * test_mem_cgroup_node_reclaimable
1695 * @memcg: the target memcg
1696 * @nid: the node ID to be checked.
1697 * @noswap : specify true here if the user wants flle only information.
1699 * This function returns whether the specified memcg contains any
1700 * reclaimable pages on a node. Returns true if there are any reclaimable
1701 * pages in the node.
1703 static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
1704 int nid, bool noswap)
1706 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE))
1708 if (noswap || !total_swap_pages)
1710 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON))
1715 #if MAX_NUMNODES > 1
1718 * Always updating the nodemask is not very good - even if we have an empty
1719 * list or the wrong list here, we can start from some node and traverse all
1720 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1723 static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
1727 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1728 * pagein/pageout changes since the last update.
1730 if (!atomic_read(&memcg->numainfo_events))
1732 if (atomic_inc_return(&memcg->numainfo_updating) > 1)
1735 /* make a nodemask where this memcg uses memory from */
1736 memcg->scan_nodes = node_states[N_MEMORY];
1738 for_each_node_mask(nid, node_states[N_MEMORY]) {
1740 if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
1741 node_clear(nid, memcg->scan_nodes);
1744 atomic_set(&memcg->numainfo_events, 0);
1745 atomic_set(&memcg->numainfo_updating, 0);
1749 * Selecting a node where we start reclaim from. Because what we need is just
1750 * reducing usage counter, start from anywhere is O,K. Considering
1751 * memory reclaim from current node, there are pros. and cons.
1753 * Freeing memory from current node means freeing memory from a node which
1754 * we'll use or we've used. So, it may make LRU bad. And if several threads
1755 * hit limits, it will see a contention on a node. But freeing from remote
1756 * node means more costs for memory reclaim because of memory latency.
1758 * Now, we use round-robin. Better algorithm is welcomed.
1760 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1764 mem_cgroup_may_update_nodemask(memcg);
1765 node = memcg->last_scanned_node;
1767 node = next_node(node, memcg->scan_nodes);
1768 if (node == MAX_NUMNODES)
1769 node = first_node(memcg->scan_nodes);
1771 * We call this when we hit limit, not when pages are added to LRU.
1772 * No LRU may hold pages because all pages are UNEVICTABLE or
1773 * memcg is too small and all pages are not on LRU. In that case,
1774 * we use curret node.
1776 if (unlikely(node == MAX_NUMNODES))
1777 node = numa_node_id();
1779 memcg->last_scanned_node = node;
1784 * Check all nodes whether it contains reclaimable pages or not.
1785 * For quick scan, we make use of scan_nodes. This will allow us to skip
1786 * unused nodes. But scan_nodes is lazily updated and may not cotain
1787 * enough new information. We need to do double check.
1789 static bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
1794 * quick check...making use of scan_node.
1795 * We can skip unused nodes.
1797 if (!nodes_empty(memcg->scan_nodes)) {
1798 for (nid = first_node(memcg->scan_nodes);
1800 nid = next_node(nid, memcg->scan_nodes)) {
1802 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
1807 * Check rest of nodes.
1809 for_each_node_state(nid, N_MEMORY) {
1810 if (node_isset(nid, memcg->scan_nodes))
1812 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
1819 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1824 static bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
1826 return test_mem_cgroup_node_reclaimable(memcg, 0, noswap);
1830 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
1833 unsigned long *total_scanned)
1835 struct mem_cgroup *victim = NULL;
1838 unsigned long excess;
1839 unsigned long nr_scanned;
1840 struct mem_cgroup_reclaim_cookie reclaim = {
1845 excess = res_counter_soft_limit_excess(&root_memcg->res) >> PAGE_SHIFT;
1848 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1853 * If we have not been able to reclaim
1854 * anything, it might because there are
1855 * no reclaimable pages under this hierarchy
1860 * We want to do more targeted reclaim.
1861 * excess >> 2 is not to excessive so as to
1862 * reclaim too much, nor too less that we keep
1863 * coming back to reclaim from this cgroup
1865 if (total >= (excess >> 2) ||
1866 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1871 if (!mem_cgroup_reclaimable(victim, false))
1873 total += mem_cgroup_shrink_node_zone(victim, gfp_mask, false,
1875 *total_scanned += nr_scanned;
1876 if (!res_counter_soft_limit_excess(&root_memcg->res))
1879 mem_cgroup_iter_break(root_memcg, victim);
1884 * Check OOM-Killer is already running under our hierarchy.
1885 * If someone is running, return false.
1886 * Has to be called with memcg_oom_lock
1888 static bool mem_cgroup_oom_lock(struct mem_cgroup *memcg)
1890 struct mem_cgroup *iter, *failed = NULL;
1892 for_each_mem_cgroup_tree(iter, memcg) {
1893 if (iter->oom_lock) {
1895 * this subtree of our hierarchy is already locked
1896 * so we cannot give a lock.
1899 mem_cgroup_iter_break(memcg, iter);
1902 iter->oom_lock = true;
1909 * OK, we failed to lock the whole subtree so we have to clean up
1910 * what we set up to the failing subtree
1912 for_each_mem_cgroup_tree(iter, memcg) {
1913 if (iter == failed) {
1914 mem_cgroup_iter_break(memcg, iter);
1917 iter->oom_lock = false;
1923 * Has to be called with memcg_oom_lock
1925 static int mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1927 struct mem_cgroup *iter;
1929 for_each_mem_cgroup_tree(iter, memcg)
1930 iter->oom_lock = false;
1934 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1936 struct mem_cgroup *iter;
1938 for_each_mem_cgroup_tree(iter, memcg)
1939 atomic_inc(&iter->under_oom);
1942 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1944 struct mem_cgroup *iter;
1947 * When a new child is created while the hierarchy is under oom,
1948 * mem_cgroup_oom_lock() may not be called. We have to use
1949 * atomic_add_unless() here.
1951 for_each_mem_cgroup_tree(iter, memcg)
1952 atomic_add_unless(&iter->under_oom, -1, 0);
1955 static DEFINE_SPINLOCK(memcg_oom_lock);
1956 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1958 struct oom_wait_info {
1959 struct mem_cgroup *memcg;
1963 static int memcg_oom_wake_function(wait_queue_t *wait,
1964 unsigned mode, int sync, void *arg)
1966 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
1967 struct mem_cgroup *oom_wait_memcg;
1968 struct oom_wait_info *oom_wait_info;
1970 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1971 oom_wait_memcg = oom_wait_info->memcg;
1974 * Both of oom_wait_info->memcg and wake_memcg are stable under us.
1975 * Then we can use css_is_ancestor without taking care of RCU.
1977 if (!mem_cgroup_same_or_subtree(oom_wait_memcg, wake_memcg)
1978 && !mem_cgroup_same_or_subtree(wake_memcg, oom_wait_memcg))
1980 return autoremove_wake_function(wait, mode, sync, arg);
1983 static void memcg_wakeup_oom(struct mem_cgroup *memcg)
1985 /* for filtering, pass "memcg" as argument. */
1986 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
1989 static void memcg_oom_recover(struct mem_cgroup *memcg)
1991 if (memcg && atomic_read(&memcg->under_oom))
1992 memcg_wakeup_oom(memcg);
1996 * try to call OOM killer. returns false if we should exit memory-reclaim loop.
1998 static bool mem_cgroup_handle_oom(struct mem_cgroup *memcg, gfp_t mask,
2001 struct oom_wait_info owait;
2002 bool locked, need_to_kill;
2004 owait.memcg = memcg;
2005 owait.wait.flags = 0;
2006 owait.wait.func = memcg_oom_wake_function;
2007 owait.wait.private = current;
2008 INIT_LIST_HEAD(&owait.wait.task_list);
2009 need_to_kill = true;
2010 mem_cgroup_mark_under_oom(memcg);
2012 /* At first, try to OOM lock hierarchy under memcg.*/
2013 spin_lock(&memcg_oom_lock);
2014 locked = mem_cgroup_oom_lock(memcg);
2016 * Even if signal_pending(), we can't quit charge() loop without
2017 * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
2018 * under OOM is always welcomed, use TASK_KILLABLE here.
2020 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
2021 if (!locked || memcg->oom_kill_disable)
2022 need_to_kill = false;
2024 mem_cgroup_oom_notify(memcg);
2025 spin_unlock(&memcg_oom_lock);
2028 finish_wait(&memcg_oom_waitq, &owait.wait);
2029 mem_cgroup_out_of_memory(memcg, mask, order);
2032 finish_wait(&memcg_oom_waitq, &owait.wait);
2034 spin_lock(&memcg_oom_lock);
2036 mem_cgroup_oom_unlock(memcg);
2037 memcg_wakeup_oom(memcg);
2038 spin_unlock(&memcg_oom_lock);
2040 mem_cgroup_unmark_under_oom(memcg);
2042 if (test_thread_flag(TIF_MEMDIE) || fatal_signal_pending(current))
2044 /* Give chance to dying process */
2045 schedule_timeout_uninterruptible(1);
2050 * Currently used to update mapped file statistics, but the routine can be
2051 * generalized to update other statistics as well.
2053 * Notes: Race condition
2055 * We usually use page_cgroup_lock() for accessing page_cgroup member but
2056 * it tends to be costly. But considering some conditions, we doesn't need
2057 * to do so _always_.
2059 * Considering "charge", lock_page_cgroup() is not required because all
2060 * file-stat operations happen after a page is attached to radix-tree. There
2061 * are no race with "charge".
2063 * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
2064 * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
2065 * if there are race with "uncharge". Statistics itself is properly handled
2068 * Considering "move", this is an only case we see a race. To make the race
2069 * small, we check mm->moving_account and detect there are possibility of race
2070 * If there is, we take a lock.
2073 void __mem_cgroup_begin_update_page_stat(struct page *page,
2074 bool *locked, unsigned long *flags)
2076 struct mem_cgroup *memcg;
2077 struct page_cgroup *pc;
2079 pc = lookup_page_cgroup(page);
2081 memcg = pc->mem_cgroup;
2082 if (unlikely(!memcg || !PageCgroupUsed(pc)))
2085 * If this memory cgroup is not under account moving, we don't
2086 * need to take move_lock_mem_cgroup(). Because we already hold
2087 * rcu_read_lock(), any calls to move_account will be delayed until
2088 * rcu_read_unlock() if mem_cgroup_stolen() == true.
2090 if (!mem_cgroup_stolen(memcg))
2093 move_lock_mem_cgroup(memcg, flags);
2094 if (memcg != pc->mem_cgroup || !PageCgroupUsed(pc)) {
2095 move_unlock_mem_cgroup(memcg, flags);
2101 void __mem_cgroup_end_update_page_stat(struct page *page, unsigned long *flags)
2103 struct page_cgroup *pc = lookup_page_cgroup(page);
2106 * It's guaranteed that pc->mem_cgroup never changes while
2107 * lock is held because a routine modifies pc->mem_cgroup
2108 * should take move_lock_mem_cgroup().
2110 move_unlock_mem_cgroup(pc->mem_cgroup, flags);
2113 void mem_cgroup_update_page_stat(struct page *page,
2114 enum mem_cgroup_page_stat_item idx, int val)
2116 struct mem_cgroup *memcg;
2117 struct page_cgroup *pc = lookup_page_cgroup(page);
2118 unsigned long uninitialized_var(flags);
2120 if (mem_cgroup_disabled())
2123 memcg = pc->mem_cgroup;
2124 if (unlikely(!memcg || !PageCgroupUsed(pc)))
2128 case MEMCG_NR_FILE_MAPPED:
2129 idx = MEM_CGROUP_STAT_FILE_MAPPED;
2135 this_cpu_add(memcg->stat->count[idx], val);
2139 * size of first charge trial. "32" comes from vmscan.c's magic value.
2140 * TODO: maybe necessary to use big numbers in big irons.
2142 #define CHARGE_BATCH 32U
2143 struct memcg_stock_pcp {
2144 struct mem_cgroup *cached; /* this never be root cgroup */
2145 unsigned int nr_pages;
2146 struct work_struct work;
2147 unsigned long flags;
2148 #define FLUSHING_CACHED_CHARGE 0
2150 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
2151 static DEFINE_MUTEX(percpu_charge_mutex);
2154 * consume_stock: Try to consume stocked charge on this cpu.
2155 * @memcg: memcg to consume from.
2156 * @nr_pages: how many pages to charge.
2158 * The charges will only happen if @memcg matches the current cpu's memcg
2159 * stock, and at least @nr_pages are available in that stock. Failure to
2160 * service an allocation will refill the stock.
2162 * returns true if successful, false otherwise.
2164 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2166 struct memcg_stock_pcp *stock;
2169 if (nr_pages > CHARGE_BATCH)
2172 stock = &get_cpu_var(memcg_stock);
2173 if (memcg == stock->cached && stock->nr_pages >= nr_pages)
2174 stock->nr_pages -= nr_pages;
2175 else /* need to call res_counter_charge */
2177 put_cpu_var(memcg_stock);
2182 * Returns stocks cached in percpu to res_counter and reset cached information.
2184 static void drain_stock(struct memcg_stock_pcp *stock)
2186 struct mem_cgroup *old = stock->cached;
2188 if (stock->nr_pages) {
2189 unsigned long bytes = stock->nr_pages * PAGE_SIZE;
2191 res_counter_uncharge(&old->res, bytes);
2192 if (do_swap_account)
2193 res_counter_uncharge(&old->memsw, bytes);
2194 stock->nr_pages = 0;
2196 stock->cached = NULL;
2200 * This must be called under preempt disabled or must be called by
2201 * a thread which is pinned to local cpu.
2203 static void drain_local_stock(struct work_struct *dummy)
2205 struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
2207 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2211 * Cache charges(val) which is from res_counter, to local per_cpu area.
2212 * This will be consumed by consume_stock() function, later.
2214 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2216 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
2218 if (stock->cached != memcg) { /* reset if necessary */
2220 stock->cached = memcg;
2222 stock->nr_pages += nr_pages;
2223 put_cpu_var(memcg_stock);
2227 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2228 * of the hierarchy under it. sync flag says whether we should block
2229 * until the work is done.
2231 static void drain_all_stock(struct mem_cgroup *root_memcg, bool sync)
2235 /* Notify other cpus that system-wide "drain" is running */
2238 for_each_online_cpu(cpu) {
2239 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2240 struct mem_cgroup *memcg;
2242 memcg = stock->cached;
2243 if (!memcg || !stock->nr_pages)
2245 if (!mem_cgroup_same_or_subtree(root_memcg, memcg))
2247 if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2249 drain_local_stock(&stock->work);
2251 schedule_work_on(cpu, &stock->work);
2259 for_each_online_cpu(cpu) {
2260 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2261 if (test_bit(FLUSHING_CACHED_CHARGE, &stock->flags))
2262 flush_work(&stock->work);
2269 * Tries to drain stocked charges in other cpus. This function is asynchronous
2270 * and just put a work per cpu for draining localy on each cpu. Caller can
2271 * expects some charges will be back to res_counter later but cannot wait for
2274 static void drain_all_stock_async(struct mem_cgroup *root_memcg)
2277 * If someone calls draining, avoid adding more kworker runs.
2279 if (!mutex_trylock(&percpu_charge_mutex))
2281 drain_all_stock(root_memcg, false);
2282 mutex_unlock(&percpu_charge_mutex);
2285 /* This is a synchronous drain interface. */
2286 static void drain_all_stock_sync(struct mem_cgroup *root_memcg)
2288 /* called when force_empty is called */
2289 mutex_lock(&percpu_charge_mutex);
2290 drain_all_stock(root_memcg, true);
2291 mutex_unlock(&percpu_charge_mutex);
2295 * This function drains percpu counter value from DEAD cpu and
2296 * move it to local cpu. Note that this function can be preempted.
2298 static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *memcg, int cpu)
2302 spin_lock(&memcg->pcp_counter_lock);
2303 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
2304 long x = per_cpu(memcg->stat->count[i], cpu);
2306 per_cpu(memcg->stat->count[i], cpu) = 0;
2307 memcg->nocpu_base.count[i] += x;
2309 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
2310 unsigned long x = per_cpu(memcg->stat->events[i], cpu);
2312 per_cpu(memcg->stat->events[i], cpu) = 0;
2313 memcg->nocpu_base.events[i] += x;
2315 spin_unlock(&memcg->pcp_counter_lock);
2318 static int __cpuinit memcg_cpu_hotplug_callback(struct notifier_block *nb,
2319 unsigned long action,
2322 int cpu = (unsigned long)hcpu;
2323 struct memcg_stock_pcp *stock;
2324 struct mem_cgroup *iter;
2326 if (action == CPU_ONLINE)
2329 if (action != CPU_DEAD && action != CPU_DEAD_FROZEN)
2332 for_each_mem_cgroup(iter)
2333 mem_cgroup_drain_pcp_counter(iter, cpu);
2335 stock = &per_cpu(memcg_stock, cpu);
2341 /* See __mem_cgroup_try_charge() for details */
2343 CHARGE_OK, /* success */
2344 CHARGE_RETRY, /* need to retry but retry is not bad */
2345 CHARGE_NOMEM, /* we can't do more. return -ENOMEM */
2346 CHARGE_WOULDBLOCK, /* GFP_WAIT wasn't set and no enough res. */
2347 CHARGE_OOM_DIE, /* the current is killed because of OOM */
2350 static int mem_cgroup_do_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2351 unsigned int nr_pages, unsigned int min_pages,
2354 unsigned long csize = nr_pages * PAGE_SIZE;
2355 struct mem_cgroup *mem_over_limit;
2356 struct res_counter *fail_res;
2357 unsigned long flags = 0;
2360 ret = res_counter_charge(&memcg->res, csize, &fail_res);
2363 if (!do_swap_account)
2365 ret = res_counter_charge(&memcg->memsw, csize, &fail_res);
2369 res_counter_uncharge(&memcg->res, csize);
2370 mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw);
2371 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
2373 mem_over_limit = mem_cgroup_from_res_counter(fail_res, res);
2375 * Never reclaim on behalf of optional batching, retry with a
2376 * single page instead.
2378 if (nr_pages > min_pages)
2379 return CHARGE_RETRY;
2381 if (!(gfp_mask & __GFP_WAIT))
2382 return CHARGE_WOULDBLOCK;
2384 if (gfp_mask & __GFP_NORETRY)
2385 return CHARGE_NOMEM;
2387 ret = mem_cgroup_reclaim(mem_over_limit, gfp_mask, flags);
2388 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2389 return CHARGE_RETRY;
2391 * Even though the limit is exceeded at this point, reclaim
2392 * may have been able to free some pages. Retry the charge
2393 * before killing the task.
2395 * Only for regular pages, though: huge pages are rather
2396 * unlikely to succeed so close to the limit, and we fall back
2397 * to regular pages anyway in case of failure.
2399 if (nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER) && ret)
2400 return CHARGE_RETRY;
2403 * At task move, charge accounts can be doubly counted. So, it's
2404 * better to wait until the end of task_move if something is going on.
2406 if (mem_cgroup_wait_acct_move(mem_over_limit))
2407 return CHARGE_RETRY;
2409 /* If we don't need to call oom-killer at el, return immediately */
2411 return CHARGE_NOMEM;
2413 if (!mem_cgroup_handle_oom(mem_over_limit, gfp_mask, get_order(csize)))
2414 return CHARGE_OOM_DIE;
2416 return CHARGE_RETRY;
2420 * __mem_cgroup_try_charge() does
2421 * 1. detect memcg to be charged against from passed *mm and *ptr,
2422 * 2. update res_counter
2423 * 3. call memory reclaim if necessary.
2425 * In some special case, if the task is fatal, fatal_signal_pending() or
2426 * has TIF_MEMDIE, this function returns -EINTR while writing root_mem_cgroup
2427 * to *ptr. There are two reasons for this. 1: fatal threads should quit as soon
2428 * as possible without any hazards. 2: all pages should have a valid
2429 * pc->mem_cgroup. If mm is NULL and the caller doesn't pass a valid memcg
2430 * pointer, that is treated as a charge to root_mem_cgroup.
2432 * So __mem_cgroup_try_charge() will return
2433 * 0 ... on success, filling *ptr with a valid memcg pointer.
2434 * -ENOMEM ... charge failure because of resource limits.
2435 * -EINTR ... if thread is fatal. *ptr is filled with root_mem_cgroup.
2437 * Unlike the exported interface, an "oom" parameter is added. if oom==true,
2438 * the oom-killer can be invoked.
2440 static int __mem_cgroup_try_charge(struct mm_struct *mm,
2442 unsigned int nr_pages,
2443 struct mem_cgroup **ptr,
2446 unsigned int batch = max(CHARGE_BATCH, nr_pages);
2447 int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2448 struct mem_cgroup *memcg = NULL;
2452 * Unlike gloval-vm's OOM-kill, we're not in memory shortage
2453 * in system level. So, allow to go ahead dying process in addition to
2456 if (unlikely(test_thread_flag(TIF_MEMDIE)
2457 || fatal_signal_pending(current)))
2461 * We always charge the cgroup the mm_struct belongs to.
2462 * The mm_struct's mem_cgroup changes on task migration if the
2463 * thread group leader migrates. It's possible that mm is not
2464 * set, if so charge the root memcg (happens for pagecache usage).
2467 *ptr = root_mem_cgroup;
2469 if (*ptr) { /* css should be a valid one */
2471 if (mem_cgroup_is_root(memcg))
2473 if (consume_stock(memcg, nr_pages))
2475 css_get(&memcg->css);
2477 struct task_struct *p;
2480 p = rcu_dereference(mm->owner);
2482 * Because we don't have task_lock(), "p" can exit.
2483 * In that case, "memcg" can point to root or p can be NULL with
2484 * race with swapoff. Then, we have small risk of mis-accouning.
2485 * But such kind of mis-account by race always happens because
2486 * we don't have cgroup_mutex(). It's overkill and we allo that
2488 * (*) swapoff at el will charge against mm-struct not against
2489 * task-struct. So, mm->owner can be NULL.
2491 memcg = mem_cgroup_from_task(p);
2493 memcg = root_mem_cgroup;
2494 if (mem_cgroup_is_root(memcg)) {
2498 if (consume_stock(memcg, nr_pages)) {
2500 * It seems dagerous to access memcg without css_get().
2501 * But considering how consume_stok works, it's not
2502 * necessary. If consume_stock success, some charges
2503 * from this memcg are cached on this cpu. So, we
2504 * don't need to call css_get()/css_tryget() before
2505 * calling consume_stock().
2510 /* after here, we may be blocked. we need to get refcnt */
2511 if (!css_tryget(&memcg->css)) {
2521 /* If killed, bypass charge */
2522 if (fatal_signal_pending(current)) {
2523 css_put(&memcg->css);
2528 if (oom && !nr_oom_retries) {
2530 nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2533 ret = mem_cgroup_do_charge(memcg, gfp_mask, batch, nr_pages,
2538 case CHARGE_RETRY: /* not in OOM situation but retry */
2540 css_put(&memcg->css);
2543 case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
2544 css_put(&memcg->css);
2546 case CHARGE_NOMEM: /* OOM routine works */
2548 css_put(&memcg->css);
2551 /* If oom, we never return -ENOMEM */
2554 case CHARGE_OOM_DIE: /* Killed by OOM Killer */
2555 css_put(&memcg->css);
2558 } while (ret != CHARGE_OK);
2560 if (batch > nr_pages)
2561 refill_stock(memcg, batch - nr_pages);
2562 css_put(&memcg->css);
2570 *ptr = root_mem_cgroup;
2575 * Somemtimes we have to undo a charge we got by try_charge().
2576 * This function is for that and do uncharge, put css's refcnt.
2577 * gotten by try_charge().
2579 static void __mem_cgroup_cancel_charge(struct mem_cgroup *memcg,
2580 unsigned int nr_pages)
2582 if (!mem_cgroup_is_root(memcg)) {
2583 unsigned long bytes = nr_pages * PAGE_SIZE;
2585 res_counter_uncharge(&memcg->res, bytes);
2586 if (do_swap_account)
2587 res_counter_uncharge(&memcg->memsw, bytes);
2592 * Cancel chrages in this cgroup....doesn't propagate to parent cgroup.
2593 * This is useful when moving usage to parent cgroup.
2595 static void __mem_cgroup_cancel_local_charge(struct mem_cgroup *memcg,
2596 unsigned int nr_pages)
2598 unsigned long bytes = nr_pages * PAGE_SIZE;
2600 if (mem_cgroup_is_root(memcg))
2603 res_counter_uncharge_until(&memcg->res, memcg->res.parent, bytes);
2604 if (do_swap_account)
2605 res_counter_uncharge_until(&memcg->memsw,
2606 memcg->memsw.parent, bytes);
2610 * A helper function to get mem_cgroup from ID. must be called under
2611 * rcu_read_lock(). The caller is responsible for calling css_tryget if
2612 * the mem_cgroup is used for charging. (dropping refcnt from swap can be
2613 * called against removed memcg.)
2615 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
2617 struct cgroup_subsys_state *css;
2619 /* ID 0 is unused ID */
2622 css = css_lookup(&mem_cgroup_subsys, id);
2625 return mem_cgroup_from_css(css);
2628 struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
2630 struct mem_cgroup *memcg = NULL;
2631 struct page_cgroup *pc;
2635 VM_BUG_ON(!PageLocked(page));
2637 pc = lookup_page_cgroup(page);
2638 lock_page_cgroup(pc);
2639 if (PageCgroupUsed(pc)) {
2640 memcg = pc->mem_cgroup;
2641 if (memcg && !css_tryget(&memcg->css))
2643 } else if (PageSwapCache(page)) {
2644 ent.val = page_private(page);
2645 id = lookup_swap_cgroup_id(ent);
2647 memcg = mem_cgroup_lookup(id);
2648 if (memcg && !css_tryget(&memcg->css))
2652 unlock_page_cgroup(pc);
2656 static void __mem_cgroup_commit_charge(struct mem_cgroup *memcg,
2658 unsigned int nr_pages,
2659 enum charge_type ctype,
2662 struct page_cgroup *pc = lookup_page_cgroup(page);
2663 struct zone *uninitialized_var(zone);
2664 struct lruvec *lruvec;
2665 bool was_on_lru = false;
2668 lock_page_cgroup(pc);
2669 VM_BUG_ON(PageCgroupUsed(pc));
2671 * we don't need page_cgroup_lock about tail pages, becase they are not
2672 * accessed by any other context at this point.
2676 * In some cases, SwapCache and FUSE(splice_buf->radixtree), the page
2677 * may already be on some other mem_cgroup's LRU. Take care of it.
2680 zone = page_zone(page);
2681 spin_lock_irq(&zone->lru_lock);
2682 if (PageLRU(page)) {
2683 lruvec = mem_cgroup_zone_lruvec(zone, pc->mem_cgroup);
2685 del_page_from_lru_list(page, lruvec, page_lru(page));
2690 pc->mem_cgroup = memcg;
2692 * We access a page_cgroup asynchronously without lock_page_cgroup().
2693 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
2694 * is accessed after testing USED bit. To make pc->mem_cgroup visible
2695 * before USED bit, we need memory barrier here.
2696 * See mem_cgroup_add_lru_list(), etc.
2699 SetPageCgroupUsed(pc);
2703 lruvec = mem_cgroup_zone_lruvec(zone, pc->mem_cgroup);
2704 VM_BUG_ON(PageLRU(page));
2706 add_page_to_lru_list(page, lruvec, page_lru(page));
2708 spin_unlock_irq(&zone->lru_lock);
2711 if (ctype == MEM_CGROUP_CHARGE_TYPE_ANON)
2716 mem_cgroup_charge_statistics(memcg, anon, nr_pages);
2717 unlock_page_cgroup(pc);
2720 * "charge_statistics" updated event counter. Then, check it.
2721 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
2722 * if they exceeds softlimit.
2724 memcg_check_events(memcg, page);
2727 #ifdef CONFIG_MEMCG_KMEM
2728 static inline bool memcg_can_account_kmem(struct mem_cgroup *memcg)
2730 return !mem_cgroup_disabled() && !mem_cgroup_is_root(memcg) &&
2731 (memcg->kmem_account_flags & KMEM_ACCOUNTED_MASK);
2734 static int memcg_charge_kmem(struct mem_cgroup *memcg, gfp_t gfp, u64 size)
2736 struct res_counter *fail_res;
2737 struct mem_cgroup *_memcg;
2741 ret = res_counter_charge(&memcg->kmem, size, &fail_res);
2746 * Conditions under which we can wait for the oom_killer. Those are
2747 * the same conditions tested by the core page allocator
2749 may_oom = (gfp & __GFP_FS) && !(gfp & __GFP_NORETRY);
2752 ret = __mem_cgroup_try_charge(NULL, gfp, size >> PAGE_SHIFT,
2755 if (ret == -EINTR) {
2757 * __mem_cgroup_try_charge() chosed to bypass to root due to
2758 * OOM kill or fatal signal. Since our only options are to
2759 * either fail the allocation or charge it to this cgroup, do
2760 * it as a temporary condition. But we can't fail. From a
2761 * kmem/slab perspective, the cache has already been selected,
2762 * by mem_cgroup_kmem_get_cache(), so it is too late to change
2765 * This condition will only trigger if the task entered
2766 * memcg_charge_kmem in a sane state, but was OOM-killed during
2767 * __mem_cgroup_try_charge() above. Tasks that were already
2768 * dying when the allocation triggers should have been already
2769 * directed to the root cgroup in memcontrol.h
2771 res_counter_charge_nofail(&memcg->res, size, &fail_res);
2772 if (do_swap_account)
2773 res_counter_charge_nofail(&memcg->memsw, size,
2777 res_counter_uncharge(&memcg->kmem, size);
2782 static void memcg_uncharge_kmem(struct mem_cgroup *memcg, u64 size)
2784 res_counter_uncharge(&memcg->res, size);
2785 if (do_swap_account)
2786 res_counter_uncharge(&memcg->memsw, size);
2789 if (res_counter_uncharge(&memcg->kmem, size))
2792 if (memcg_kmem_test_and_clear_dead(memcg))
2793 mem_cgroup_put(memcg);
2796 void memcg_cache_list_add(struct mem_cgroup *memcg, struct kmem_cache *cachep)
2801 mutex_lock(&memcg->slab_caches_mutex);
2802 list_add(&cachep->memcg_params->list, &memcg->memcg_slab_caches);
2803 mutex_unlock(&memcg->slab_caches_mutex);
2807 * helper for acessing a memcg's index. It will be used as an index in the
2808 * child cache array in kmem_cache, and also to derive its name. This function
2809 * will return -1 when this is not a kmem-limited memcg.
2811 int memcg_cache_id(struct mem_cgroup *memcg)
2813 return memcg ? memcg->kmemcg_id : -1;
2816 int memcg_register_cache(struct mem_cgroup *memcg, struct kmem_cache *s)
2818 size_t size = sizeof(struct memcg_cache_params);
2820 if (!memcg_kmem_enabled())
2823 s->memcg_params = kzalloc(size, GFP_KERNEL);
2824 if (!s->memcg_params)
2828 s->memcg_params->memcg = memcg;
2832 void memcg_release_cache(struct kmem_cache *s)
2834 kfree(s->memcg_params);
2838 * We need to verify if the allocation against current->mm->owner's memcg is
2839 * possible for the given order. But the page is not allocated yet, so we'll
2840 * need a further commit step to do the final arrangements.
2842 * It is possible for the task to switch cgroups in this mean time, so at
2843 * commit time, we can't rely on task conversion any longer. We'll then use
2844 * the handle argument to return to the caller which cgroup we should commit
2845 * against. We could also return the memcg directly and avoid the pointer
2846 * passing, but a boolean return value gives better semantics considering
2847 * the compiled-out case as well.
2849 * Returning true means the allocation is possible.
2852 __memcg_kmem_newpage_charge(gfp_t gfp, struct mem_cgroup **_memcg, int order)
2854 struct mem_cgroup *memcg;
2858 memcg = try_get_mem_cgroup_from_mm(current->mm);
2861 * very rare case described in mem_cgroup_from_task. Unfortunately there
2862 * isn't much we can do without complicating this too much, and it would
2863 * be gfp-dependent anyway. Just let it go
2865 if (unlikely(!memcg))
2868 if (!memcg_can_account_kmem(memcg)) {
2869 css_put(&memcg->css);
2873 ret = memcg_charge_kmem(memcg, gfp, PAGE_SIZE << order);
2877 css_put(&memcg->css);
2881 void __memcg_kmem_commit_charge(struct page *page, struct mem_cgroup *memcg,
2884 struct page_cgroup *pc;
2886 VM_BUG_ON(mem_cgroup_is_root(memcg));
2888 /* The page allocation failed. Revert */
2890 memcg_uncharge_kmem(memcg, PAGE_SIZE << order);
2894 pc = lookup_page_cgroup(page);
2895 lock_page_cgroup(pc);
2896 pc->mem_cgroup = memcg;
2897 SetPageCgroupUsed(pc);
2898 unlock_page_cgroup(pc);
2901 void __memcg_kmem_uncharge_pages(struct page *page, int order)
2903 struct mem_cgroup *memcg = NULL;
2904 struct page_cgroup *pc;
2907 pc = lookup_page_cgroup(page);
2909 * Fast unlocked return. Theoretically might have changed, have to
2910 * check again after locking.
2912 if (!PageCgroupUsed(pc))
2915 lock_page_cgroup(pc);
2916 if (PageCgroupUsed(pc)) {
2917 memcg = pc->mem_cgroup;
2918 ClearPageCgroupUsed(pc);
2920 unlock_page_cgroup(pc);
2923 * We trust that only if there is a memcg associated with the page, it
2924 * is a valid allocation
2929 VM_BUG_ON(mem_cgroup_is_root(memcg));
2930 memcg_uncharge_kmem(memcg, PAGE_SIZE << order);
2932 #endif /* CONFIG_MEMCG_KMEM */
2934 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2936 #define PCGF_NOCOPY_AT_SPLIT (1 << PCG_LOCK | 1 << PCG_MIGRATION)
2938 * Because tail pages are not marked as "used", set it. We're under
2939 * zone->lru_lock, 'splitting on pmd' and compound_lock.
2940 * charge/uncharge will be never happen and move_account() is done under
2941 * compound_lock(), so we don't have to take care of races.
2943 void mem_cgroup_split_huge_fixup(struct page *head)
2945 struct page_cgroup *head_pc = lookup_page_cgroup(head);
2946 struct page_cgroup *pc;
2949 if (mem_cgroup_disabled())
2951 for (i = 1; i < HPAGE_PMD_NR; i++) {
2953 pc->mem_cgroup = head_pc->mem_cgroup;
2954 smp_wmb();/* see __commit_charge() */
2955 pc->flags = head_pc->flags & ~PCGF_NOCOPY_AT_SPLIT;
2958 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
2961 * mem_cgroup_move_account - move account of the page
2963 * @nr_pages: number of regular pages (>1 for huge pages)
2964 * @pc: page_cgroup of the page.
2965 * @from: mem_cgroup which the page is moved from.
2966 * @to: mem_cgroup which the page is moved to. @from != @to.
2968 * The caller must confirm following.
2969 * - page is not on LRU (isolate_page() is useful.)
2970 * - compound_lock is held when nr_pages > 1
2972 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
2975 static int mem_cgroup_move_account(struct page *page,
2976 unsigned int nr_pages,
2977 struct page_cgroup *pc,
2978 struct mem_cgroup *from,
2979 struct mem_cgroup *to)
2981 unsigned long flags;
2983 bool anon = PageAnon(page);
2985 VM_BUG_ON(from == to);
2986 VM_BUG_ON(PageLRU(page));
2988 * The page is isolated from LRU. So, collapse function
2989 * will not handle this page. But page splitting can happen.
2990 * Do this check under compound_page_lock(). The caller should
2994 if (nr_pages > 1 && !PageTransHuge(page))
2997 lock_page_cgroup(pc);
3000 if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
3003 move_lock_mem_cgroup(from, &flags);
3005 if (!anon && page_mapped(page)) {
3006 /* Update mapped_file data for mem_cgroup */
3008 __this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
3009 __this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
3012 mem_cgroup_charge_statistics(from, anon, -nr_pages);
3014 /* caller should have done css_get */
3015 pc->mem_cgroup = to;
3016 mem_cgroup_charge_statistics(to, anon, nr_pages);
3017 move_unlock_mem_cgroup(from, &flags);
3020 unlock_page_cgroup(pc);
3024 memcg_check_events(to, page);
3025 memcg_check_events(from, page);
3031 * mem_cgroup_move_parent - moves page to the parent group
3032 * @page: the page to move
3033 * @pc: page_cgroup of the page
3034 * @child: page's cgroup
3036 * move charges to its parent or the root cgroup if the group has no
3037 * parent (aka use_hierarchy==0).
3038 * Although this might fail (get_page_unless_zero, isolate_lru_page or
3039 * mem_cgroup_move_account fails) the failure is always temporary and
3040 * it signals a race with a page removal/uncharge or migration. In the
3041 * first case the page is on the way out and it will vanish from the LRU
3042 * on the next attempt and the call should be retried later.
3043 * Isolation from the LRU fails only if page has been isolated from
3044 * the LRU since we looked at it and that usually means either global
3045 * reclaim or migration going on. The page will either get back to the
3047 * Finaly mem_cgroup_move_account fails only if the page got uncharged
3048 * (!PageCgroupUsed) or moved to a different group. The page will
3049 * disappear in the next attempt.
3051 static int mem_cgroup_move_parent(struct page *page,
3052 struct page_cgroup *pc,
3053 struct mem_cgroup *child)
3055 struct mem_cgroup *parent;
3056 unsigned int nr_pages;
3057 unsigned long uninitialized_var(flags);
3060 VM_BUG_ON(mem_cgroup_is_root(child));
3063 if (!get_page_unless_zero(page))
3065 if (isolate_lru_page(page))
3068 nr_pages = hpage_nr_pages(page);
3070 parent = parent_mem_cgroup(child);
3072 * If no parent, move charges to root cgroup.
3075 parent = root_mem_cgroup;
3078 VM_BUG_ON(!PageTransHuge(page));
3079 flags = compound_lock_irqsave(page);
3082 ret = mem_cgroup_move_account(page, nr_pages,
3085 __mem_cgroup_cancel_local_charge(child, nr_pages);
3088 compound_unlock_irqrestore(page, flags);
3089 putback_lru_page(page);
3097 * Charge the memory controller for page usage.
3099 * 0 if the charge was successful
3100 * < 0 if the cgroup is over its limit
3102 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
3103 gfp_t gfp_mask, enum charge_type ctype)
3105 struct mem_cgroup *memcg = NULL;
3106 unsigned int nr_pages = 1;
3110 if (PageTransHuge(page)) {
3111 nr_pages <<= compound_order(page);
3112 VM_BUG_ON(!PageTransHuge(page));
3114 * Never OOM-kill a process for a huge page. The
3115 * fault handler will fall back to regular pages.
3120 ret = __mem_cgroup_try_charge(mm, gfp_mask, nr_pages, &memcg, oom);
3123 __mem_cgroup_commit_charge(memcg, page, nr_pages, ctype, false);
3127 int mem_cgroup_newpage_charge(struct page *page,
3128 struct mm_struct *mm, gfp_t gfp_mask)
3130 if (mem_cgroup_disabled())
3132 VM_BUG_ON(page_mapped(page));
3133 VM_BUG_ON(page->mapping && !PageAnon(page));
3135 return mem_cgroup_charge_common(page, mm, gfp_mask,
3136 MEM_CGROUP_CHARGE_TYPE_ANON);
3140 * While swap-in, try_charge -> commit or cancel, the page is locked.
3141 * And when try_charge() successfully returns, one refcnt to memcg without
3142 * struct page_cgroup is acquired. This refcnt will be consumed by
3143 * "commit()" or removed by "cancel()"
3145 static int __mem_cgroup_try_charge_swapin(struct mm_struct *mm,
3148 struct mem_cgroup **memcgp)
3150 struct mem_cgroup *memcg;
3151 struct page_cgroup *pc;
3154 pc = lookup_page_cgroup(page);
3156 * Every swap fault against a single page tries to charge the
3157 * page, bail as early as possible. shmem_unuse() encounters
3158 * already charged pages, too. The USED bit is protected by
3159 * the page lock, which serializes swap cache removal, which
3160 * in turn serializes uncharging.
3162 if (PageCgroupUsed(pc))
3164 if (!do_swap_account)
3166 memcg = try_get_mem_cgroup_from_page(page);
3170 ret = __mem_cgroup_try_charge(NULL, mask, 1, memcgp, true);
3171 css_put(&memcg->css);
3176 ret = __mem_cgroup_try_charge(mm, mask, 1, memcgp, true);
3182 int mem_cgroup_try_charge_swapin(struct mm_struct *mm, struct page *page,
3183 gfp_t gfp_mask, struct mem_cgroup **memcgp)
3186 if (mem_cgroup_disabled())
3189 * A racing thread's fault, or swapoff, may have already
3190 * updated the pte, and even removed page from swap cache: in
3191 * those cases unuse_pte()'s pte_same() test will fail; but
3192 * there's also a KSM case which does need to charge the page.
3194 if (!PageSwapCache(page)) {
3197 ret = __mem_cgroup_try_charge(mm, gfp_mask, 1, memcgp, true);
3202 return __mem_cgroup_try_charge_swapin(mm, page, gfp_mask, memcgp);
3205 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *memcg)
3207 if (mem_cgroup_disabled())
3211 __mem_cgroup_cancel_charge(memcg, 1);
3215 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *memcg,
3216 enum charge_type ctype)
3218 if (mem_cgroup_disabled())
3223 __mem_cgroup_commit_charge(memcg, page, 1, ctype, true);
3225 * Now swap is on-memory. This means this page may be
3226 * counted both as mem and swap....double count.
3227 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
3228 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
3229 * may call delete_from_swap_cache() before reach here.
3231 if (do_swap_account && PageSwapCache(page)) {
3232 swp_entry_t ent = {.val = page_private(page)};
3233 mem_cgroup_uncharge_swap(ent);
3237 void mem_cgroup_commit_charge_swapin(struct page *page,
3238 struct mem_cgroup *memcg)
3240 __mem_cgroup_commit_charge_swapin(page, memcg,
3241 MEM_CGROUP_CHARGE_TYPE_ANON);
3244 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
3247 struct mem_cgroup *memcg = NULL;
3248 enum charge_type type = MEM_CGROUP_CHARGE_TYPE_CACHE;
3251 if (mem_cgroup_disabled())
3253 if (PageCompound(page))
3256 if (!PageSwapCache(page))
3257 ret = mem_cgroup_charge_common(page, mm, gfp_mask, type);
3258 else { /* page is swapcache/shmem */
3259 ret = __mem_cgroup_try_charge_swapin(mm, page,
3262 __mem_cgroup_commit_charge_swapin(page, memcg, type);
3267 static void mem_cgroup_do_uncharge(struct mem_cgroup *memcg,
3268 unsigned int nr_pages,
3269 const enum charge_type ctype)
3271 struct memcg_batch_info *batch = NULL;
3272 bool uncharge_memsw = true;
3274 /* If swapout, usage of swap doesn't decrease */
3275 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
3276 uncharge_memsw = false;
3278 batch = ¤t->memcg_batch;
3280 * In usual, we do css_get() when we remember memcg pointer.
3281 * But in this case, we keep res->usage until end of a series of
3282 * uncharges. Then, it's ok to ignore memcg's refcnt.
3285 batch->memcg = memcg;
3287 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
3288 * In those cases, all pages freed continuously can be expected to be in
3289 * the same cgroup and we have chance to coalesce uncharges.
3290 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
3291 * because we want to do uncharge as soon as possible.
3294 if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
3295 goto direct_uncharge;
3298 goto direct_uncharge;
3301 * In typical case, batch->memcg == mem. This means we can
3302 * merge a series of uncharges to an uncharge of res_counter.
3303 * If not, we uncharge res_counter ony by one.
3305 if (batch->memcg != memcg)
3306 goto direct_uncharge;
3307 /* remember freed charge and uncharge it later */
3310 batch->memsw_nr_pages++;
3313 res_counter_uncharge(&memcg->res, nr_pages * PAGE_SIZE);
3315 res_counter_uncharge(&memcg->memsw, nr_pages * PAGE_SIZE);
3316 if (unlikely(batch->memcg != memcg))
3317 memcg_oom_recover(memcg);
3321 * uncharge if !page_mapped(page)
3323 static struct mem_cgroup *
3324 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype,
3327 struct mem_cgroup *memcg = NULL;
3328 unsigned int nr_pages = 1;
3329 struct page_cgroup *pc;
3332 if (mem_cgroup_disabled())
3335 VM_BUG_ON(PageSwapCache(page));
3337 if (PageTransHuge(page)) {
3338 nr_pages <<= compound_order(page);
3339 VM_BUG_ON(!PageTransHuge(page));
3342 * Check if our page_cgroup is valid
3344 pc = lookup_page_cgroup(page);
3345 if (unlikely(!PageCgroupUsed(pc)))
3348 lock_page_cgroup(pc);
3350 memcg = pc->mem_cgroup;
3352 if (!PageCgroupUsed(pc))
3355 anon = PageAnon(page);
3358 case MEM_CGROUP_CHARGE_TYPE_ANON:
3360 * Generally PageAnon tells if it's the anon statistics to be
3361 * updated; but sometimes e.g. mem_cgroup_uncharge_page() is
3362 * used before page reached the stage of being marked PageAnon.
3366 case MEM_CGROUP_CHARGE_TYPE_DROP:
3367 /* See mem_cgroup_prepare_migration() */
3368 if (page_mapped(page))
3371 * Pages under migration may not be uncharged. But
3372 * end_migration() /must/ be the one uncharging the
3373 * unused post-migration page and so it has to call
3374 * here with the migration bit still set. See the
3375 * res_counter handling below.
3377 if (!end_migration && PageCgroupMigration(pc))
3380 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
3381 if (!PageAnon(page)) { /* Shared memory */
3382 if (page->mapping && !page_is_file_cache(page))
3384 } else if (page_mapped(page)) /* Anon */
3391 mem_cgroup_charge_statistics(memcg, anon, -nr_pages);
3393 ClearPageCgroupUsed(pc);
3395 * pc->mem_cgroup is not cleared here. It will be accessed when it's
3396 * freed from LRU. This is safe because uncharged page is expected not
3397 * to be reused (freed soon). Exception is SwapCache, it's handled by
3398 * special functions.
3401 unlock_page_cgroup(pc);
3403 * even after unlock, we have memcg->res.usage here and this memcg
3404 * will never be freed.
3406 memcg_check_events(memcg, page);
3407 if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
3408 mem_cgroup_swap_statistics(memcg, true);
3409 mem_cgroup_get(memcg);
3412 * Migration does not charge the res_counter for the
3413 * replacement page, so leave it alone when phasing out the
3414 * page that is unused after the migration.
3416 if (!end_migration && !mem_cgroup_is_root(memcg))
3417 mem_cgroup_do_uncharge(memcg, nr_pages, ctype);
3422 unlock_page_cgroup(pc);
3426 void mem_cgroup_uncharge_page(struct page *page)
3429 if (page_mapped(page))
3431 VM_BUG_ON(page->mapping && !PageAnon(page));
3432 if (PageSwapCache(page))
3434 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_ANON, false);
3437 void mem_cgroup_uncharge_cache_page(struct page *page)
3439 VM_BUG_ON(page_mapped(page));
3440 VM_BUG_ON(page->mapping);
3441 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE, false);
3445 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
3446 * In that cases, pages are freed continuously and we can expect pages
3447 * are in the same memcg. All these calls itself limits the number of
3448 * pages freed at once, then uncharge_start/end() is called properly.
3449 * This may be called prural(2) times in a context,
3452 void mem_cgroup_uncharge_start(void)
3454 current->memcg_batch.do_batch++;
3455 /* We can do nest. */
3456 if (current->memcg_batch.do_batch == 1) {
3457 current->memcg_batch.memcg = NULL;
3458 current->memcg_batch.nr_pages = 0;
3459 current->memcg_batch.memsw_nr_pages = 0;
3463 void mem_cgroup_uncharge_end(void)
3465 struct memcg_batch_info *batch = ¤t->memcg_batch;
3467 if (!batch->do_batch)
3471 if (batch->do_batch) /* If stacked, do nothing. */
3477 * This "batch->memcg" is valid without any css_get/put etc...
3478 * bacause we hide charges behind us.
3480 if (batch->nr_pages)
3481 res_counter_uncharge(&batch->memcg->res,
3482 batch->nr_pages * PAGE_SIZE);
3483 if (batch->memsw_nr_pages)
3484 res_counter_uncharge(&batch->memcg->memsw,
3485 batch->memsw_nr_pages * PAGE_SIZE);
3486 memcg_oom_recover(batch->memcg);
3487 /* forget this pointer (for sanity check) */
3488 batch->memcg = NULL;
3493 * called after __delete_from_swap_cache() and drop "page" account.
3494 * memcg information is recorded to swap_cgroup of "ent"
3497 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
3499 struct mem_cgroup *memcg;
3500 int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
3502 if (!swapout) /* this was a swap cache but the swap is unused ! */
3503 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
3505 memcg = __mem_cgroup_uncharge_common(page, ctype, false);
3508 * record memcg information, if swapout && memcg != NULL,
3509 * mem_cgroup_get() was called in uncharge().
3511 if (do_swap_account && swapout && memcg)
3512 swap_cgroup_record(ent, css_id(&memcg->css));
3516 #ifdef CONFIG_MEMCG_SWAP
3518 * called from swap_entry_free(). remove record in swap_cgroup and
3519 * uncharge "memsw" account.
3521 void mem_cgroup_uncharge_swap(swp_entry_t ent)
3523 struct mem_cgroup *memcg;
3526 if (!do_swap_account)
3529 id = swap_cgroup_record(ent, 0);
3531 memcg = mem_cgroup_lookup(id);
3534 * We uncharge this because swap is freed.
3535 * This memcg can be obsolete one. We avoid calling css_tryget
3537 if (!mem_cgroup_is_root(memcg))
3538 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
3539 mem_cgroup_swap_statistics(memcg, false);
3540 mem_cgroup_put(memcg);
3546 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3547 * @entry: swap entry to be moved
3548 * @from: mem_cgroup which the entry is moved from
3549 * @to: mem_cgroup which the entry is moved to
3551 * It succeeds only when the swap_cgroup's record for this entry is the same
3552 * as the mem_cgroup's id of @from.
3554 * Returns 0 on success, -EINVAL on failure.
3556 * The caller must have charged to @to, IOW, called res_counter_charge() about
3557 * both res and memsw, and called css_get().
3559 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3560 struct mem_cgroup *from, struct mem_cgroup *to)
3562 unsigned short old_id, new_id;
3564 old_id = css_id(&from->css);
3565 new_id = css_id(&to->css);
3567 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3568 mem_cgroup_swap_statistics(from, false);
3569 mem_cgroup_swap_statistics(to, true);
3571 * This function is only called from task migration context now.
3572 * It postpones res_counter and refcount handling till the end
3573 * of task migration(mem_cgroup_clear_mc()) for performance
3574 * improvement. But we cannot postpone mem_cgroup_get(to)
3575 * because if the process that has been moved to @to does
3576 * swap-in, the refcount of @to might be decreased to 0.
3584 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3585 struct mem_cgroup *from, struct mem_cgroup *to)
3592 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
3595 void mem_cgroup_prepare_migration(struct page *page, struct page *newpage,
3596 struct mem_cgroup **memcgp)
3598 struct mem_cgroup *memcg = NULL;
3599 unsigned int nr_pages = 1;
3600 struct page_cgroup *pc;
3601 enum charge_type ctype;
3605 if (mem_cgroup_disabled())
3608 if (PageTransHuge(page))
3609 nr_pages <<= compound_order(page);
3611 pc = lookup_page_cgroup(page);
3612 lock_page_cgroup(pc);
3613 if (PageCgroupUsed(pc)) {
3614 memcg = pc->mem_cgroup;
3615 css_get(&memcg->css);
3617 * At migrating an anonymous page, its mapcount goes down
3618 * to 0 and uncharge() will be called. But, even if it's fully
3619 * unmapped, migration may fail and this page has to be
3620 * charged again. We set MIGRATION flag here and delay uncharge
3621 * until end_migration() is called
3623 * Corner Case Thinking
3625 * When the old page was mapped as Anon and it's unmap-and-freed
3626 * while migration was ongoing.
3627 * If unmap finds the old page, uncharge() of it will be delayed
3628 * until end_migration(). If unmap finds a new page, it's
3629 * uncharged when it make mapcount to be 1->0. If unmap code
3630 * finds swap_migration_entry, the new page will not be mapped
3631 * and end_migration() will find it(mapcount==0).
3634 * When the old page was mapped but migraion fails, the kernel
3635 * remaps it. A charge for it is kept by MIGRATION flag even
3636 * if mapcount goes down to 0. We can do remap successfully
3637 * without charging it again.
3640 * The "old" page is under lock_page() until the end of
3641 * migration, so, the old page itself will not be swapped-out.
3642 * If the new page is swapped out before end_migraton, our
3643 * hook to usual swap-out path will catch the event.
3646 SetPageCgroupMigration(pc);
3648 unlock_page_cgroup(pc);
3650 * If the page is not charged at this point,
3658 * We charge new page before it's used/mapped. So, even if unlock_page()
3659 * is called before end_migration, we can catch all events on this new
3660 * page. In the case new page is migrated but not remapped, new page's
3661 * mapcount will be finally 0 and we call uncharge in end_migration().
3664 ctype = MEM_CGROUP_CHARGE_TYPE_ANON;
3666 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
3668 * The page is committed to the memcg, but it's not actually
3669 * charged to the res_counter since we plan on replacing the
3670 * old one and only one page is going to be left afterwards.
3672 __mem_cgroup_commit_charge(memcg, newpage, nr_pages, ctype, false);
3675 /* remove redundant charge if migration failed*/
3676 void mem_cgroup_end_migration(struct mem_cgroup *memcg,
3677 struct page *oldpage, struct page *newpage, bool migration_ok)
3679 struct page *used, *unused;
3680 struct page_cgroup *pc;
3686 if (!migration_ok) {
3693 anon = PageAnon(used);
3694 __mem_cgroup_uncharge_common(unused,
3695 anon ? MEM_CGROUP_CHARGE_TYPE_ANON
3696 : MEM_CGROUP_CHARGE_TYPE_CACHE,
3698 css_put(&memcg->css);
3700 * We disallowed uncharge of pages under migration because mapcount
3701 * of the page goes down to zero, temporarly.
3702 * Clear the flag and check the page should be charged.
3704 pc = lookup_page_cgroup(oldpage);
3705 lock_page_cgroup(pc);
3706 ClearPageCgroupMigration(pc);
3707 unlock_page_cgroup(pc);
3710 * If a page is a file cache, radix-tree replacement is very atomic
3711 * and we can skip this check. When it was an Anon page, its mapcount
3712 * goes down to 0. But because we added MIGRATION flage, it's not
3713 * uncharged yet. There are several case but page->mapcount check
3714 * and USED bit check in mem_cgroup_uncharge_page() will do enough
3715 * check. (see prepare_charge() also)
3718 mem_cgroup_uncharge_page(used);
3722 * At replace page cache, newpage is not under any memcg but it's on
3723 * LRU. So, this function doesn't touch res_counter but handles LRU
3724 * in correct way. Both pages are locked so we cannot race with uncharge.
3726 void mem_cgroup_replace_page_cache(struct page *oldpage,
3727 struct page *newpage)
3729 struct mem_cgroup *memcg = NULL;
3730 struct page_cgroup *pc;
3731 enum charge_type type = MEM_CGROUP_CHARGE_TYPE_CACHE;
3733 if (mem_cgroup_disabled())
3736 pc = lookup_page_cgroup(oldpage);
3737 /* fix accounting on old pages */
3738 lock_page_cgroup(pc);
3739 if (PageCgroupUsed(pc)) {
3740 memcg = pc->mem_cgroup;
3741 mem_cgroup_charge_statistics(memcg, false, -1);
3742 ClearPageCgroupUsed(pc);
3744 unlock_page_cgroup(pc);
3747 * When called from shmem_replace_page(), in some cases the
3748 * oldpage has already been charged, and in some cases not.
3753 * Even if newpage->mapping was NULL before starting replacement,
3754 * the newpage may be on LRU(or pagevec for LRU) already. We lock
3755 * LRU while we overwrite pc->mem_cgroup.
3757 __mem_cgroup_commit_charge(memcg, newpage, 1, type, true);
3760 #ifdef CONFIG_DEBUG_VM
3761 static struct page_cgroup *lookup_page_cgroup_used(struct page *page)
3763 struct page_cgroup *pc;
3765 pc = lookup_page_cgroup(page);
3767 * Can be NULL while feeding pages into the page allocator for
3768 * the first time, i.e. during boot or memory hotplug;
3769 * or when mem_cgroup_disabled().
3771 if (likely(pc) && PageCgroupUsed(pc))
3776 bool mem_cgroup_bad_page_check(struct page *page)
3778 if (mem_cgroup_disabled())
3781 return lookup_page_cgroup_used(page) != NULL;
3784 void mem_cgroup_print_bad_page(struct page *page)
3786 struct page_cgroup *pc;
3788 pc = lookup_page_cgroup_used(page);
3790 printk(KERN_ALERT "pc:%p pc->flags:%lx pc->mem_cgroup:%p\n",
3791 pc, pc->flags, pc->mem_cgroup);
3796 static DEFINE_MUTEX(set_limit_mutex);
3798 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
3799 unsigned long long val)
3802 u64 memswlimit, memlimit;
3804 int children = mem_cgroup_count_children(memcg);
3805 u64 curusage, oldusage;
3809 * For keeping hierarchical_reclaim simple, how long we should retry
3810 * is depends on callers. We set our retry-count to be function
3811 * of # of children which we should visit in this loop.
3813 retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
3815 oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
3818 while (retry_count) {
3819 if (signal_pending(current)) {
3824 * Rather than hide all in some function, I do this in
3825 * open coded manner. You see what this really does.
3826 * We have to guarantee memcg->res.limit <= memcg->memsw.limit.
3828 mutex_lock(&set_limit_mutex);
3829 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3830 if (memswlimit < val) {
3832 mutex_unlock(&set_limit_mutex);
3836 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3840 ret = res_counter_set_limit(&memcg->res, val);
3842 if (memswlimit == val)
3843 memcg->memsw_is_minimum = true;
3845 memcg->memsw_is_minimum = false;
3847 mutex_unlock(&set_limit_mutex);
3852 mem_cgroup_reclaim(memcg, GFP_KERNEL,
3853 MEM_CGROUP_RECLAIM_SHRINK);
3854 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
3855 /* Usage is reduced ? */
3856 if (curusage >= oldusage)
3859 oldusage = curusage;
3861 if (!ret && enlarge)
3862 memcg_oom_recover(memcg);
3867 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
3868 unsigned long long val)
3871 u64 memlimit, memswlimit, oldusage, curusage;
3872 int children = mem_cgroup_count_children(memcg);
3876 /* see mem_cgroup_resize_res_limit */
3877 retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
3878 oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
3879 while (retry_count) {
3880 if (signal_pending(current)) {
3885 * Rather than hide all in some function, I do this in
3886 * open coded manner. You see what this really does.
3887 * We have to guarantee memcg->res.limit <= memcg->memsw.limit.
3889 mutex_lock(&set_limit_mutex);
3890 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3891 if (memlimit > val) {
3893 mutex_unlock(&set_limit_mutex);
3896 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3897 if (memswlimit < val)
3899 ret = res_counter_set_limit(&memcg->memsw, val);
3901 if (memlimit == val)
3902 memcg->memsw_is_minimum = true;
3904 memcg->memsw_is_minimum = false;
3906 mutex_unlock(&set_limit_mutex);
3911 mem_cgroup_reclaim(memcg, GFP_KERNEL,
3912 MEM_CGROUP_RECLAIM_NOSWAP |
3913 MEM_CGROUP_RECLAIM_SHRINK);
3914 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
3915 /* Usage is reduced ? */
3916 if (curusage >= oldusage)
3919 oldusage = curusage;
3921 if (!ret && enlarge)
3922 memcg_oom_recover(memcg);
3926 unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
3928 unsigned long *total_scanned)
3930 unsigned long nr_reclaimed = 0;
3931 struct mem_cgroup_per_zone *mz, *next_mz = NULL;
3932 unsigned long reclaimed;
3934 struct mem_cgroup_tree_per_zone *mctz;
3935 unsigned long long excess;
3936 unsigned long nr_scanned;
3941 mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
3943 * This loop can run a while, specially if mem_cgroup's continuously
3944 * keep exceeding their soft limit and putting the system under
3951 mz = mem_cgroup_largest_soft_limit_node(mctz);
3956 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, zone,
3957 gfp_mask, &nr_scanned);
3958 nr_reclaimed += reclaimed;
3959 *total_scanned += nr_scanned;
3960 spin_lock(&mctz->lock);
3963 * If we failed to reclaim anything from this memory cgroup
3964 * it is time to move on to the next cgroup
3970 * Loop until we find yet another one.
3972 * By the time we get the soft_limit lock
3973 * again, someone might have aded the
3974 * group back on the RB tree. Iterate to
3975 * make sure we get a different mem.
3976 * mem_cgroup_largest_soft_limit_node returns
3977 * NULL if no other cgroup is present on
3981 __mem_cgroup_largest_soft_limit_node(mctz);
3983 css_put(&next_mz->memcg->css);
3984 else /* next_mz == NULL or other memcg */
3988 __mem_cgroup_remove_exceeded(mz->memcg, mz, mctz);
3989 excess = res_counter_soft_limit_excess(&mz->memcg->res);
3991 * One school of thought says that we should not add
3992 * back the node to the tree if reclaim returns 0.
3993 * But our reclaim could return 0, simply because due
3994 * to priority we are exposing a smaller subset of
3995 * memory to reclaim from. Consider this as a longer
3998 /* If excess == 0, no tree ops */
3999 __mem_cgroup_insert_exceeded(mz->memcg, mz, mctz, excess);
4000 spin_unlock(&mctz->lock);
4001 css_put(&mz->memcg->css);
4004 * Could not reclaim anything and there are no more
4005 * mem cgroups to try or we seem to be looping without
4006 * reclaiming anything.
4008 if (!nr_reclaimed &&
4010 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
4012 } while (!nr_reclaimed);
4014 css_put(&next_mz->memcg->css);
4015 return nr_reclaimed;
4019 * mem_cgroup_force_empty_list - clears LRU of a group
4020 * @memcg: group to clear
4023 * @lru: lru to to clear
4025 * Traverse a specified page_cgroup list and try to drop them all. This doesn't
4026 * reclaim the pages page themselves - pages are moved to the parent (or root)
4029 static void mem_cgroup_force_empty_list(struct mem_cgroup *memcg,
4030 int node, int zid, enum lru_list lru)
4032 struct lruvec *lruvec;
4033 unsigned long flags;
4034 struct list_head *list;
4038 zone = &NODE_DATA(node)->node_zones[zid];
4039 lruvec = mem_cgroup_zone_lruvec(zone, memcg);
4040 list = &lruvec->lists[lru];
4044 struct page_cgroup *pc;
4047 spin_lock_irqsave(&zone->lru_lock, flags);
4048 if (list_empty(list)) {
4049 spin_unlock_irqrestore(&zone->lru_lock, flags);
4052 page = list_entry(list->prev, struct page, lru);
4054 list_move(&page->lru, list);
4056 spin_unlock_irqrestore(&zone->lru_lock, flags);
4059 spin_unlock_irqrestore(&zone->lru_lock, flags);
4061 pc = lookup_page_cgroup(page);
4063 if (mem_cgroup_move_parent(page, pc, memcg)) {
4064 /* found lock contention or "pc" is obsolete. */
4069 } while (!list_empty(list));
4073 * make mem_cgroup's charge to be 0 if there is no task by moving
4074 * all the charges and pages to the parent.
4075 * This enables deleting this mem_cgroup.
4077 * Caller is responsible for holding css reference on the memcg.
4079 static void mem_cgroup_reparent_charges(struct mem_cgroup *memcg)
4085 /* This is for making all *used* pages to be on LRU. */
4086 lru_add_drain_all();
4087 drain_all_stock_sync(memcg);
4088 mem_cgroup_start_move(memcg);
4089 for_each_node_state(node, N_MEMORY) {
4090 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
4093 mem_cgroup_force_empty_list(memcg,
4098 mem_cgroup_end_move(memcg);
4099 memcg_oom_recover(memcg);
4103 * Kernel memory may not necessarily be trackable to a specific
4104 * process. So they are not migrated, and therefore we can't
4105 * expect their value to drop to 0 here.
4106 * Having res filled up with kmem only is enough.
4108 * This is a safety check because mem_cgroup_force_empty_list
4109 * could have raced with mem_cgroup_replace_page_cache callers
4110 * so the lru seemed empty but the page could have been added
4111 * right after the check. RES_USAGE should be safe as we always
4112 * charge before adding to the LRU.
4114 usage = res_counter_read_u64(&memcg->res, RES_USAGE) -
4115 res_counter_read_u64(&memcg->kmem, RES_USAGE);
4116 } while (usage > 0);
4120 * Reclaims as many pages from the given memcg as possible and moves
4121 * the rest to the parent.
4123 * Caller is responsible for holding css reference for memcg.
4125 static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
4127 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
4128 struct cgroup *cgrp = memcg->css.cgroup;
4130 /* returns EBUSY if there is a task or if we come here twice. */
4131 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
4134 /* we call try-to-free pages for make this cgroup empty */
4135 lru_add_drain_all();
4136 /* try to free all pages in this cgroup */
4137 while (nr_retries && res_counter_read_u64(&memcg->res, RES_USAGE) > 0) {
4140 if (signal_pending(current))
4143 progress = try_to_free_mem_cgroup_pages(memcg, GFP_KERNEL,
4147 /* maybe some writeback is necessary */
4148 congestion_wait(BLK_RW_ASYNC, HZ/10);
4153 mem_cgroup_reparent_charges(memcg);
4158 static int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
4160 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4163 if (mem_cgroup_is_root(memcg))
4165 css_get(&memcg->css);
4166 ret = mem_cgroup_force_empty(memcg);
4167 css_put(&memcg->css);
4173 static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
4175 return mem_cgroup_from_cont(cont)->use_hierarchy;
4178 static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
4182 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4183 struct cgroup *parent = cont->parent;
4184 struct mem_cgroup *parent_memcg = NULL;
4187 parent_memcg = mem_cgroup_from_cont(parent);
4191 if (memcg->use_hierarchy == val)
4195 * If parent's use_hierarchy is set, we can't make any modifications
4196 * in the child subtrees. If it is unset, then the change can
4197 * occur, provided the current cgroup has no children.
4199 * For the root cgroup, parent_mem is NULL, we allow value to be
4200 * set if there are no children.
4202 if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
4203 (val == 1 || val == 0)) {
4204 if (list_empty(&cont->children))
4205 memcg->use_hierarchy = val;
4218 static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup *memcg,
4219 enum mem_cgroup_stat_index idx)
4221 struct mem_cgroup *iter;
4224 /* Per-cpu values can be negative, use a signed accumulator */
4225 for_each_mem_cgroup_tree(iter, memcg)
4226 val += mem_cgroup_read_stat(iter, idx);
4228 if (val < 0) /* race ? */
4233 static inline u64 mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
4237 if (!mem_cgroup_is_root(memcg)) {
4239 return res_counter_read_u64(&memcg->res, RES_USAGE);
4241 return res_counter_read_u64(&memcg->memsw, RES_USAGE);
4244 val = mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_CACHE);
4245 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_RSS);
4248 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_SWAP);
4250 return val << PAGE_SHIFT;
4253 static ssize_t mem_cgroup_read(struct cgroup *cont, struct cftype *cft,
4254 struct file *file, char __user *buf,
4255 size_t nbytes, loff_t *ppos)
4257 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4263 type = MEMFILE_TYPE(cft->private);
4264 name = MEMFILE_ATTR(cft->private);
4266 if (!do_swap_account && type == _MEMSWAP)
4271 if (name == RES_USAGE)
4272 val = mem_cgroup_usage(memcg, false);
4274 val = res_counter_read_u64(&memcg->res, name);
4277 if (name == RES_USAGE)
4278 val = mem_cgroup_usage(memcg, true);
4280 val = res_counter_read_u64(&memcg->memsw, name);
4283 val = res_counter_read_u64(&memcg->kmem, name);
4289 len = scnprintf(str, sizeof(str), "%llu\n", (unsigned long long)val);
4290 return simple_read_from_buffer(buf, nbytes, ppos, str, len);
4293 static int memcg_update_kmem_limit(struct cgroup *cont, u64 val)
4296 #ifdef CONFIG_MEMCG_KMEM
4297 bool must_inc_static_branch = false;
4299 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4301 * For simplicity, we won't allow this to be disabled. It also can't
4302 * be changed if the cgroup has children already, or if tasks had
4305 * If tasks join before we set the limit, a person looking at
4306 * kmem.usage_in_bytes will have no way to determine when it took
4307 * place, which makes the value quite meaningless.
4309 * After it first became limited, changes in the value of the limit are
4310 * of course permitted.
4312 * Taking the cgroup_lock is really offensive, but it is so far the only
4313 * way to guarantee that no children will appear. There are plenty of
4314 * other offenders, and they should all go away. Fine grained locking
4315 * is probably the way to go here. When we are fully hierarchical, we
4316 * can also get rid of the use_hierarchy check.
4319 mutex_lock(&set_limit_mutex);
4320 if (!memcg->kmem_account_flags && val != RESOURCE_MAX) {
4321 if (cgroup_task_count(cont) || (memcg->use_hierarchy &&
4322 !list_empty(&cont->children))) {
4326 ret = res_counter_set_limit(&memcg->kmem, val);
4330 * After this point, kmem_accounted (that we test atomically in
4331 * the beginning of this conditional), is no longer 0. This
4332 * guarantees only one process will set the following boolean
4333 * to true. We don't need test_and_set because we're protected
4334 * by the set_limit_mutex anyway.
4336 memcg_kmem_set_activated(memcg);
4337 must_inc_static_branch = true;
4339 * kmem charges can outlive the cgroup. In the case of slab
4340 * pages, for instance, a page contain objects from various
4341 * processes, so it is unfeasible to migrate them away. We
4342 * need to reference count the memcg because of that.
4344 mem_cgroup_get(memcg);
4346 ret = res_counter_set_limit(&memcg->kmem, val);
4348 mutex_unlock(&set_limit_mutex);
4352 * We are by now familiar with the fact that we can't inc the static
4353 * branch inside cgroup_lock. See disarm functions for details. A
4354 * worker here is overkill, but also wrong: After the limit is set, we
4355 * must start accounting right away. Since this operation can't fail,
4356 * we can safely defer it to here - no rollback will be needed.
4358 * The boolean used to control this is also safe, because
4359 * KMEM_ACCOUNTED_ACTIVATED guarantees that only one process will be
4360 * able to set it to true;
4362 if (must_inc_static_branch) {
4363 static_key_slow_inc(&memcg_kmem_enabled_key);
4365 * setting the active bit after the inc will guarantee no one
4366 * starts accounting before all call sites are patched
4368 memcg_kmem_set_active(memcg);
4375 static void memcg_propagate_kmem(struct mem_cgroup *memcg)
4377 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
4380 memcg->kmem_account_flags = parent->kmem_account_flags;
4381 #ifdef CONFIG_MEMCG_KMEM
4383 * When that happen, we need to disable the static branch only on those
4384 * memcgs that enabled it. To achieve this, we would be forced to
4385 * complicate the code by keeping track of which memcgs were the ones
4386 * that actually enabled limits, and which ones got it from its
4389 * It is a lot simpler just to do static_key_slow_inc() on every child
4390 * that is accounted.
4392 if (memcg_kmem_is_active(memcg)) {
4393 mem_cgroup_get(memcg);
4394 static_key_slow_inc(&memcg_kmem_enabled_key);
4400 * The user of this function is...
4403 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
4406 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4409 unsigned long long val;
4412 type = MEMFILE_TYPE(cft->private);
4413 name = MEMFILE_ATTR(cft->private);
4415 if (!do_swap_account && type == _MEMSWAP)
4420 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
4424 /* This function does all necessary parse...reuse it */
4425 ret = res_counter_memparse_write_strategy(buffer, &val);
4429 ret = mem_cgroup_resize_limit(memcg, val);
4430 else if (type == _MEMSWAP)
4431 ret = mem_cgroup_resize_memsw_limit(memcg, val);
4432 else if (type == _KMEM)
4433 ret = memcg_update_kmem_limit(cont, val);
4437 case RES_SOFT_LIMIT:
4438 ret = res_counter_memparse_write_strategy(buffer, &val);
4442 * For memsw, soft limits are hard to implement in terms
4443 * of semantics, for now, we support soft limits for
4444 * control without swap
4447 ret = res_counter_set_soft_limit(&memcg->res, val);
4452 ret = -EINVAL; /* should be BUG() ? */
4458 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
4459 unsigned long long *mem_limit, unsigned long long *memsw_limit)
4461 struct cgroup *cgroup;
4462 unsigned long long min_limit, min_memsw_limit, tmp;
4464 min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
4465 min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
4466 cgroup = memcg->css.cgroup;
4467 if (!memcg->use_hierarchy)
4470 while (cgroup->parent) {
4471 cgroup = cgroup->parent;
4472 memcg = mem_cgroup_from_cont(cgroup);
4473 if (!memcg->use_hierarchy)
4475 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
4476 min_limit = min(min_limit, tmp);
4477 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
4478 min_memsw_limit = min(min_memsw_limit, tmp);
4481 *mem_limit = min_limit;
4482 *memsw_limit = min_memsw_limit;
4485 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
4487 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4491 type = MEMFILE_TYPE(event);
4492 name = MEMFILE_ATTR(event);
4494 if (!do_swap_account && type == _MEMSWAP)
4500 res_counter_reset_max(&memcg->res);
4501 else if (type == _MEMSWAP)
4502 res_counter_reset_max(&memcg->memsw);
4503 else if (type == _KMEM)
4504 res_counter_reset_max(&memcg->kmem);
4510 res_counter_reset_failcnt(&memcg->res);
4511 else if (type == _MEMSWAP)
4512 res_counter_reset_failcnt(&memcg->memsw);
4513 else if (type == _KMEM)
4514 res_counter_reset_failcnt(&memcg->kmem);
4523 static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
4526 return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
4530 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
4531 struct cftype *cft, u64 val)
4533 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4535 if (val >= (1 << NR_MOVE_TYPE))
4538 * We check this value several times in both in can_attach() and
4539 * attach(), so we need cgroup lock to prevent this value from being
4543 memcg->move_charge_at_immigrate = val;
4549 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
4550 struct cftype *cft, u64 val)
4557 static int memcg_numa_stat_show(struct cgroup *cont, struct cftype *cft,
4561 unsigned long total_nr, file_nr, anon_nr, unevictable_nr;
4562 unsigned long node_nr;
4563 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4565 total_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL);
4566 seq_printf(m, "total=%lu", total_nr);
4567 for_each_node_state(nid, N_MEMORY) {
4568 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL);
4569 seq_printf(m, " N%d=%lu", nid, node_nr);
4573 file_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL_FILE);
4574 seq_printf(m, "file=%lu", file_nr);
4575 for_each_node_state(nid, N_MEMORY) {
4576 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
4578 seq_printf(m, " N%d=%lu", nid, node_nr);
4582 anon_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL_ANON);
4583 seq_printf(m, "anon=%lu", anon_nr);
4584 for_each_node_state(nid, N_MEMORY) {
4585 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
4587 seq_printf(m, " N%d=%lu", nid, node_nr);
4591 unevictable_nr = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_UNEVICTABLE));
4592 seq_printf(m, "unevictable=%lu", unevictable_nr);
4593 for_each_node_state(nid, N_MEMORY) {
4594 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
4595 BIT(LRU_UNEVICTABLE));
4596 seq_printf(m, " N%d=%lu", nid, node_nr);
4601 #endif /* CONFIG_NUMA */
4603 static const char * const mem_cgroup_lru_names[] = {
4611 static inline void mem_cgroup_lru_names_not_uptodate(void)
4613 BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_lru_names) != NR_LRU_LISTS);
4616 static int memcg_stat_show(struct cgroup *cont, struct cftype *cft,
4619 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4620 struct mem_cgroup *mi;
4623 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
4624 if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
4626 seq_printf(m, "%s %ld\n", mem_cgroup_stat_names[i],
4627 mem_cgroup_read_stat(memcg, i) * PAGE_SIZE);
4630 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++)
4631 seq_printf(m, "%s %lu\n", mem_cgroup_events_names[i],
4632 mem_cgroup_read_events(memcg, i));
4634 for (i = 0; i < NR_LRU_LISTS; i++)
4635 seq_printf(m, "%s %lu\n", mem_cgroup_lru_names[i],
4636 mem_cgroup_nr_lru_pages(memcg, BIT(i)) * PAGE_SIZE);
4638 /* Hierarchical information */
4640 unsigned long long limit, memsw_limit;
4641 memcg_get_hierarchical_limit(memcg, &limit, &memsw_limit);
4642 seq_printf(m, "hierarchical_memory_limit %llu\n", limit);
4643 if (do_swap_account)
4644 seq_printf(m, "hierarchical_memsw_limit %llu\n",
4648 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
4651 if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
4653 for_each_mem_cgroup_tree(mi, memcg)
4654 val += mem_cgroup_read_stat(mi, i) * PAGE_SIZE;
4655 seq_printf(m, "total_%s %lld\n", mem_cgroup_stat_names[i], val);
4658 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
4659 unsigned long long val = 0;
4661 for_each_mem_cgroup_tree(mi, memcg)
4662 val += mem_cgroup_read_events(mi, i);
4663 seq_printf(m, "total_%s %llu\n",
4664 mem_cgroup_events_names[i], val);
4667 for (i = 0; i < NR_LRU_LISTS; i++) {
4668 unsigned long long val = 0;
4670 for_each_mem_cgroup_tree(mi, memcg)
4671 val += mem_cgroup_nr_lru_pages(mi, BIT(i)) * PAGE_SIZE;
4672 seq_printf(m, "total_%s %llu\n", mem_cgroup_lru_names[i], val);
4675 #ifdef CONFIG_DEBUG_VM
4678 struct mem_cgroup_per_zone *mz;
4679 struct zone_reclaim_stat *rstat;
4680 unsigned long recent_rotated[2] = {0, 0};
4681 unsigned long recent_scanned[2] = {0, 0};
4683 for_each_online_node(nid)
4684 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
4685 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
4686 rstat = &mz->lruvec.reclaim_stat;
4688 recent_rotated[0] += rstat->recent_rotated[0];
4689 recent_rotated[1] += rstat->recent_rotated[1];
4690 recent_scanned[0] += rstat->recent_scanned[0];
4691 recent_scanned[1] += rstat->recent_scanned[1];
4693 seq_printf(m, "recent_rotated_anon %lu\n", recent_rotated[0]);
4694 seq_printf(m, "recent_rotated_file %lu\n", recent_rotated[1]);
4695 seq_printf(m, "recent_scanned_anon %lu\n", recent_scanned[0]);
4696 seq_printf(m, "recent_scanned_file %lu\n", recent_scanned[1]);
4703 static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
4705 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4707 return mem_cgroup_swappiness(memcg);
4710 static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
4713 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4714 struct mem_cgroup *parent;
4719 if (cgrp->parent == NULL)
4722 parent = mem_cgroup_from_cont(cgrp->parent);
4726 /* If under hierarchy, only empty-root can set this value */
4727 if ((parent->use_hierarchy) ||
4728 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
4733 memcg->swappiness = val;
4740 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4742 struct mem_cgroup_threshold_ary *t;
4748 t = rcu_dereference(memcg->thresholds.primary);
4750 t = rcu_dereference(memcg->memsw_thresholds.primary);
4755 usage = mem_cgroup_usage(memcg, swap);
4758 * current_threshold points to threshold just below or equal to usage.
4759 * If it's not true, a threshold was crossed after last
4760 * call of __mem_cgroup_threshold().
4762 i = t->current_threshold;
4765 * Iterate backward over array of thresholds starting from
4766 * current_threshold and check if a threshold is crossed.
4767 * If none of thresholds below usage is crossed, we read
4768 * only one element of the array here.
4770 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4771 eventfd_signal(t->entries[i].eventfd, 1);
4773 /* i = current_threshold + 1 */
4777 * Iterate forward over array of thresholds starting from
4778 * current_threshold+1 and check if a threshold is crossed.
4779 * If none of thresholds above usage is crossed, we read
4780 * only one element of the array here.
4782 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4783 eventfd_signal(t->entries[i].eventfd, 1);
4785 /* Update current_threshold */
4786 t->current_threshold = i - 1;
4791 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4794 __mem_cgroup_threshold(memcg, false);
4795 if (do_swap_account)
4796 __mem_cgroup_threshold(memcg, true);
4798 memcg = parent_mem_cgroup(memcg);
4802 static int compare_thresholds(const void *a, const void *b)
4804 const struct mem_cgroup_threshold *_a = a;
4805 const struct mem_cgroup_threshold *_b = b;
4807 return _a->threshold - _b->threshold;
4810 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
4812 struct mem_cgroup_eventfd_list *ev;
4814 list_for_each_entry(ev, &memcg->oom_notify, list)
4815 eventfd_signal(ev->eventfd, 1);
4819 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
4821 struct mem_cgroup *iter;
4823 for_each_mem_cgroup_tree(iter, memcg)
4824 mem_cgroup_oom_notify_cb(iter);
4827 static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
4828 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4830 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4831 struct mem_cgroup_thresholds *thresholds;
4832 struct mem_cgroup_threshold_ary *new;
4833 enum res_type type = MEMFILE_TYPE(cft->private);
4834 u64 threshold, usage;
4837 ret = res_counter_memparse_write_strategy(args, &threshold);
4841 mutex_lock(&memcg->thresholds_lock);
4844 thresholds = &memcg->thresholds;
4845 else if (type == _MEMSWAP)
4846 thresholds = &memcg->memsw_thresholds;
4850 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4852 /* Check if a threshold crossed before adding a new one */
4853 if (thresholds->primary)
4854 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4856 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4858 /* Allocate memory for new array of thresholds */
4859 new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
4867 /* Copy thresholds (if any) to new array */
4868 if (thresholds->primary) {
4869 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
4870 sizeof(struct mem_cgroup_threshold));
4873 /* Add new threshold */
4874 new->entries[size - 1].eventfd = eventfd;
4875 new->entries[size - 1].threshold = threshold;
4877 /* Sort thresholds. Registering of new threshold isn't time-critical */
4878 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
4879 compare_thresholds, NULL);
4881 /* Find current threshold */
4882 new->current_threshold = -1;
4883 for (i = 0; i < size; i++) {
4884 if (new->entries[i].threshold <= usage) {
4886 * new->current_threshold will not be used until
4887 * rcu_assign_pointer(), so it's safe to increment
4890 ++new->current_threshold;
4895 /* Free old spare buffer and save old primary buffer as spare */
4896 kfree(thresholds->spare);
4897 thresholds->spare = thresholds->primary;
4899 rcu_assign_pointer(thresholds->primary, new);
4901 /* To be sure that nobody uses thresholds */
4905 mutex_unlock(&memcg->thresholds_lock);
4910 static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
4911 struct cftype *cft, struct eventfd_ctx *eventfd)
4913 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4914 struct mem_cgroup_thresholds *thresholds;
4915 struct mem_cgroup_threshold_ary *new;
4916 enum res_type type = MEMFILE_TYPE(cft->private);
4920 mutex_lock(&memcg->thresholds_lock);
4922 thresholds = &memcg->thresholds;
4923 else if (type == _MEMSWAP)
4924 thresholds = &memcg->memsw_thresholds;
4928 if (!thresholds->primary)
4931 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4933 /* Check if a threshold crossed before removing */
4934 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4936 /* Calculate new number of threshold */
4938 for (i = 0; i < thresholds->primary->size; i++) {
4939 if (thresholds->primary->entries[i].eventfd != eventfd)
4943 new = thresholds->spare;
4945 /* Set thresholds array to NULL if we don't have thresholds */
4954 /* Copy thresholds and find current threshold */
4955 new->current_threshold = -1;
4956 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4957 if (thresholds->primary->entries[i].eventfd == eventfd)
4960 new->entries[j] = thresholds->primary->entries[i];
4961 if (new->entries[j].threshold <= usage) {
4963 * new->current_threshold will not be used
4964 * until rcu_assign_pointer(), so it's safe to increment
4967 ++new->current_threshold;
4973 /* Swap primary and spare array */
4974 thresholds->spare = thresholds->primary;
4975 /* If all events are unregistered, free the spare array */
4977 kfree(thresholds->spare);
4978 thresholds->spare = NULL;
4981 rcu_assign_pointer(thresholds->primary, new);
4983 /* To be sure that nobody uses thresholds */
4986 mutex_unlock(&memcg->thresholds_lock);
4989 static int mem_cgroup_oom_register_event(struct cgroup *cgrp,
4990 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4992 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4993 struct mem_cgroup_eventfd_list *event;
4994 enum res_type type = MEMFILE_TYPE(cft->private);
4996 BUG_ON(type != _OOM_TYPE);
4997 event = kmalloc(sizeof(*event), GFP_KERNEL);
5001 spin_lock(&memcg_oom_lock);
5003 event->eventfd = eventfd;
5004 list_add(&event->list, &memcg->oom_notify);
5006 /* already in OOM ? */
5007 if (atomic_read(&memcg->under_oom))
5008 eventfd_signal(eventfd, 1);
5009 spin_unlock(&memcg_oom_lock);
5014 static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
5015 struct cftype *cft, struct eventfd_ctx *eventfd)
5017 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5018 struct mem_cgroup_eventfd_list *ev, *tmp;
5019 enum res_type type = MEMFILE_TYPE(cft->private);
5021 BUG_ON(type != _OOM_TYPE);
5023 spin_lock(&memcg_oom_lock);
5025 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
5026 if (ev->eventfd == eventfd) {
5027 list_del(&ev->list);
5032 spin_unlock(&memcg_oom_lock);
5035 static int mem_cgroup_oom_control_read(struct cgroup *cgrp,
5036 struct cftype *cft, struct cgroup_map_cb *cb)
5038 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5040 cb->fill(cb, "oom_kill_disable", memcg->oom_kill_disable);
5042 if (atomic_read(&memcg->under_oom))
5043 cb->fill(cb, "under_oom", 1);
5045 cb->fill(cb, "under_oom", 0);
5049 static int mem_cgroup_oom_control_write(struct cgroup *cgrp,
5050 struct cftype *cft, u64 val)
5052 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5053 struct mem_cgroup *parent;
5055 /* cannot set to root cgroup and only 0 and 1 are allowed */
5056 if (!cgrp->parent || !((val == 0) || (val == 1)))
5059 parent = mem_cgroup_from_cont(cgrp->parent);
5062 /* oom-kill-disable is a flag for subhierarchy. */
5063 if ((parent->use_hierarchy) ||
5064 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
5068 memcg->oom_kill_disable = val;
5070 memcg_oom_recover(memcg);
5075 #ifdef CONFIG_MEMCG_KMEM
5076 static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
5078 memcg->kmemcg_id = -1;
5079 memcg_propagate_kmem(memcg);
5081 return mem_cgroup_sockets_init(memcg, ss);
5084 static void kmem_cgroup_destroy(struct mem_cgroup *memcg)
5086 mem_cgroup_sockets_destroy(memcg);
5088 memcg_kmem_mark_dead(memcg);
5090 if (res_counter_read_u64(&memcg->kmem, RES_USAGE) != 0)
5094 * Charges already down to 0, undo mem_cgroup_get() done in the charge
5095 * path here, being careful not to race with memcg_uncharge_kmem: it is
5096 * possible that the charges went down to 0 between mark_dead and the
5097 * res_counter read, so in that case, we don't need the put
5099 if (memcg_kmem_test_and_clear_dead(memcg))
5100 mem_cgroup_put(memcg);
5103 static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
5108 static void kmem_cgroup_destroy(struct mem_cgroup *memcg)
5113 static struct cftype mem_cgroup_files[] = {
5115 .name = "usage_in_bytes",
5116 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
5117 .read = mem_cgroup_read,
5118 .register_event = mem_cgroup_usage_register_event,
5119 .unregister_event = mem_cgroup_usage_unregister_event,
5122 .name = "max_usage_in_bytes",
5123 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
5124 .trigger = mem_cgroup_reset,
5125 .read = mem_cgroup_read,
5128 .name = "limit_in_bytes",
5129 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
5130 .write_string = mem_cgroup_write,
5131 .read = mem_cgroup_read,
5134 .name = "soft_limit_in_bytes",
5135 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
5136 .write_string = mem_cgroup_write,
5137 .read = mem_cgroup_read,
5141 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
5142 .trigger = mem_cgroup_reset,
5143 .read = mem_cgroup_read,
5147 .read_seq_string = memcg_stat_show,
5150 .name = "force_empty",
5151 .trigger = mem_cgroup_force_empty_write,
5154 .name = "use_hierarchy",
5155 .write_u64 = mem_cgroup_hierarchy_write,
5156 .read_u64 = mem_cgroup_hierarchy_read,
5159 .name = "swappiness",
5160 .read_u64 = mem_cgroup_swappiness_read,
5161 .write_u64 = mem_cgroup_swappiness_write,
5164 .name = "move_charge_at_immigrate",
5165 .read_u64 = mem_cgroup_move_charge_read,
5166 .write_u64 = mem_cgroup_move_charge_write,
5169 .name = "oom_control",
5170 .read_map = mem_cgroup_oom_control_read,
5171 .write_u64 = mem_cgroup_oom_control_write,
5172 .register_event = mem_cgroup_oom_register_event,
5173 .unregister_event = mem_cgroup_oom_unregister_event,
5174 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
5178 .name = "numa_stat",
5179 .read_seq_string = memcg_numa_stat_show,
5182 #ifdef CONFIG_MEMCG_SWAP
5184 .name = "memsw.usage_in_bytes",
5185 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
5186 .read = mem_cgroup_read,
5187 .register_event = mem_cgroup_usage_register_event,
5188 .unregister_event = mem_cgroup_usage_unregister_event,
5191 .name = "memsw.max_usage_in_bytes",
5192 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
5193 .trigger = mem_cgroup_reset,
5194 .read = mem_cgroup_read,
5197 .name = "memsw.limit_in_bytes",
5198 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
5199 .write_string = mem_cgroup_write,
5200 .read = mem_cgroup_read,
5203 .name = "memsw.failcnt",
5204 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
5205 .trigger = mem_cgroup_reset,
5206 .read = mem_cgroup_read,
5209 #ifdef CONFIG_MEMCG_KMEM
5211 .name = "kmem.limit_in_bytes",
5212 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
5213 .write_string = mem_cgroup_write,
5214 .read = mem_cgroup_read,
5217 .name = "kmem.usage_in_bytes",
5218 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
5219 .read = mem_cgroup_read,
5222 .name = "kmem.failcnt",
5223 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
5224 .trigger = mem_cgroup_reset,
5225 .read = mem_cgroup_read,
5228 .name = "kmem.max_usage_in_bytes",
5229 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
5230 .trigger = mem_cgroup_reset,
5231 .read = mem_cgroup_read,
5234 { }, /* terminate */
5237 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
5239 struct mem_cgroup_per_node *pn;
5240 struct mem_cgroup_per_zone *mz;
5241 int zone, tmp = node;
5243 * This routine is called against possible nodes.
5244 * But it's BUG to call kmalloc() against offline node.
5246 * TODO: this routine can waste much memory for nodes which will
5247 * never be onlined. It's better to use memory hotplug callback
5250 if (!node_state(node, N_NORMAL_MEMORY))
5252 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
5256 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
5257 mz = &pn->zoneinfo[zone];
5258 lruvec_init(&mz->lruvec);
5259 mz->usage_in_excess = 0;
5260 mz->on_tree = false;
5263 memcg->info.nodeinfo[node] = pn;
5267 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
5269 kfree(memcg->info.nodeinfo[node]);
5272 static struct mem_cgroup *mem_cgroup_alloc(void)
5274 struct mem_cgroup *memcg;
5275 int size = sizeof(struct mem_cgroup);
5277 /* Can be very big if MAX_NUMNODES is very big */
5278 if (size < PAGE_SIZE)
5279 memcg = kzalloc(size, GFP_KERNEL);
5281 memcg = vzalloc(size);
5286 memcg->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
5289 spin_lock_init(&memcg->pcp_counter_lock);
5293 if (size < PAGE_SIZE)
5301 * At destroying mem_cgroup, references from swap_cgroup can remain.
5302 * (scanning all at force_empty is too costly...)
5304 * Instead of clearing all references at force_empty, we remember
5305 * the number of reference from swap_cgroup and free mem_cgroup when
5306 * it goes down to 0.
5308 * Removal of cgroup itself succeeds regardless of refs from swap.
5311 static void __mem_cgroup_free(struct mem_cgroup *memcg)
5314 int size = sizeof(struct mem_cgroup);
5316 mem_cgroup_remove_from_trees(memcg);
5317 free_css_id(&mem_cgroup_subsys, &memcg->css);
5320 free_mem_cgroup_per_zone_info(memcg, node);
5322 free_percpu(memcg->stat);
5325 * We need to make sure that (at least for now), the jump label
5326 * destruction code runs outside of the cgroup lock. This is because
5327 * get_online_cpus(), which is called from the static_branch update,
5328 * can't be called inside the cgroup_lock. cpusets are the ones
5329 * enforcing this dependency, so if they ever change, we might as well.
5331 * schedule_work() will guarantee this happens. Be careful if you need
5332 * to move this code around, and make sure it is outside
5335 disarm_static_keys(memcg);
5336 if (size < PAGE_SIZE)
5344 * Helpers for freeing a kmalloc()ed/vzalloc()ed mem_cgroup by RCU,
5345 * but in process context. The work_freeing structure is overlaid
5346 * on the rcu_freeing structure, which itself is overlaid on memsw.
5348 static void free_work(struct work_struct *work)
5350 struct mem_cgroup *memcg;
5352 memcg = container_of(work, struct mem_cgroup, work_freeing);
5353 __mem_cgroup_free(memcg);
5356 static void free_rcu(struct rcu_head *rcu_head)
5358 struct mem_cgroup *memcg;
5360 memcg = container_of(rcu_head, struct mem_cgroup, rcu_freeing);
5361 INIT_WORK(&memcg->work_freeing, free_work);
5362 schedule_work(&memcg->work_freeing);
5365 static void mem_cgroup_get(struct mem_cgroup *memcg)
5367 atomic_inc(&memcg->refcnt);
5370 static void __mem_cgroup_put(struct mem_cgroup *memcg, int count)
5372 if (atomic_sub_and_test(count, &memcg->refcnt)) {
5373 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
5374 call_rcu(&memcg->rcu_freeing, free_rcu);
5376 mem_cgroup_put(parent);
5380 static void mem_cgroup_put(struct mem_cgroup *memcg)
5382 __mem_cgroup_put(memcg, 1);
5386 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
5388 struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg)
5390 if (!memcg->res.parent)
5392 return mem_cgroup_from_res_counter(memcg->res.parent, res);
5394 EXPORT_SYMBOL(parent_mem_cgroup);
5396 #ifdef CONFIG_MEMCG_SWAP
5397 static void __init enable_swap_cgroup(void)
5399 if (!mem_cgroup_disabled() && really_do_swap_account)
5400 do_swap_account = 1;
5403 static void __init enable_swap_cgroup(void)
5408 static int mem_cgroup_soft_limit_tree_init(void)
5410 struct mem_cgroup_tree_per_node *rtpn;
5411 struct mem_cgroup_tree_per_zone *rtpz;
5412 int tmp, node, zone;
5414 for_each_node(node) {
5416 if (!node_state(node, N_NORMAL_MEMORY))
5418 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
5422 soft_limit_tree.rb_tree_per_node[node] = rtpn;
5424 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
5425 rtpz = &rtpn->rb_tree_per_zone[zone];
5426 rtpz->rb_root = RB_ROOT;
5427 spin_lock_init(&rtpz->lock);
5433 for_each_node(node) {
5434 if (!soft_limit_tree.rb_tree_per_node[node])
5436 kfree(soft_limit_tree.rb_tree_per_node[node]);
5437 soft_limit_tree.rb_tree_per_node[node] = NULL;
5443 static struct cgroup_subsys_state * __ref
5444 mem_cgroup_css_alloc(struct cgroup *cont)
5446 struct mem_cgroup *memcg, *parent;
5447 long error = -ENOMEM;
5450 memcg = mem_cgroup_alloc();
5452 return ERR_PTR(error);
5455 if (alloc_mem_cgroup_per_zone_info(memcg, node))
5459 if (cont->parent == NULL) {
5461 enable_swap_cgroup();
5463 if (mem_cgroup_soft_limit_tree_init())
5465 root_mem_cgroup = memcg;
5466 for_each_possible_cpu(cpu) {
5467 struct memcg_stock_pcp *stock =
5468 &per_cpu(memcg_stock, cpu);
5469 INIT_WORK(&stock->work, drain_local_stock);
5471 hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
5473 parent = mem_cgroup_from_cont(cont->parent);
5474 memcg->use_hierarchy = parent->use_hierarchy;
5475 memcg->oom_kill_disable = parent->oom_kill_disable;
5478 if (parent && parent->use_hierarchy) {
5479 res_counter_init(&memcg->res, &parent->res);
5480 res_counter_init(&memcg->memsw, &parent->memsw);
5481 res_counter_init(&memcg->kmem, &parent->kmem);
5483 * We increment refcnt of the parent to ensure that we can
5484 * safely access it on res_counter_charge/uncharge.
5485 * This refcnt will be decremented when freeing this
5486 * mem_cgroup(see mem_cgroup_put).
5488 mem_cgroup_get(parent);
5490 res_counter_init(&memcg->res, NULL);
5491 res_counter_init(&memcg->memsw, NULL);
5492 res_counter_init(&memcg->kmem, NULL);
5494 * Deeper hierachy with use_hierarchy == false doesn't make
5495 * much sense so let cgroup subsystem know about this
5496 * unfortunate state in our controller.
5498 if (parent && parent != root_mem_cgroup)
5499 mem_cgroup_subsys.broken_hierarchy = true;
5501 memcg->last_scanned_node = MAX_NUMNODES;
5502 INIT_LIST_HEAD(&memcg->oom_notify);
5505 memcg->swappiness = mem_cgroup_swappiness(parent);
5506 atomic_set(&memcg->refcnt, 1);
5507 memcg->move_charge_at_immigrate = 0;
5508 mutex_init(&memcg->thresholds_lock);
5509 spin_lock_init(&memcg->move_lock);
5511 error = memcg_init_kmem(memcg, &mem_cgroup_subsys);
5514 * We call put now because our (and parent's) refcnts
5515 * are already in place. mem_cgroup_put() will internally
5516 * call __mem_cgroup_free, so return directly
5518 mem_cgroup_put(memcg);
5519 return ERR_PTR(error);
5523 __mem_cgroup_free(memcg);
5524 return ERR_PTR(error);
5527 static void mem_cgroup_css_offline(struct cgroup *cont)
5529 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5531 mem_cgroup_reparent_charges(memcg);
5534 static void mem_cgroup_css_free(struct cgroup *cont)
5536 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5538 kmem_cgroup_destroy(memcg);
5540 mem_cgroup_put(memcg);
5544 /* Handlers for move charge at task migration. */
5545 #define PRECHARGE_COUNT_AT_ONCE 256
5546 static int mem_cgroup_do_precharge(unsigned long count)
5549 int batch_count = PRECHARGE_COUNT_AT_ONCE;
5550 struct mem_cgroup *memcg = mc.to;
5552 if (mem_cgroup_is_root(memcg)) {
5553 mc.precharge += count;
5554 /* we don't need css_get for root */
5557 /* try to charge at once */
5559 struct res_counter *dummy;
5561 * "memcg" cannot be under rmdir() because we've already checked
5562 * by cgroup_lock_live_cgroup() that it is not removed and we
5563 * are still under the same cgroup_mutex. So we can postpone
5566 if (res_counter_charge(&memcg->res, PAGE_SIZE * count, &dummy))
5568 if (do_swap_account && res_counter_charge(&memcg->memsw,
5569 PAGE_SIZE * count, &dummy)) {
5570 res_counter_uncharge(&memcg->res, PAGE_SIZE * count);
5573 mc.precharge += count;
5577 /* fall back to one by one charge */
5579 if (signal_pending(current)) {
5583 if (!batch_count--) {
5584 batch_count = PRECHARGE_COUNT_AT_ONCE;
5587 ret = __mem_cgroup_try_charge(NULL,
5588 GFP_KERNEL, 1, &memcg, false);
5590 /* mem_cgroup_clear_mc() will do uncharge later */
5598 * get_mctgt_type - get target type of moving charge
5599 * @vma: the vma the pte to be checked belongs
5600 * @addr: the address corresponding to the pte to be checked
5601 * @ptent: the pte to be checked
5602 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5605 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5606 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5607 * move charge. if @target is not NULL, the page is stored in target->page
5608 * with extra refcnt got(Callers should handle it).
5609 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5610 * target for charge migration. if @target is not NULL, the entry is stored
5613 * Called with pte lock held.
5620 enum mc_target_type {
5626 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5627 unsigned long addr, pte_t ptent)
5629 struct page *page = vm_normal_page(vma, addr, ptent);
5631 if (!page || !page_mapped(page))
5633 if (PageAnon(page)) {
5634 /* we don't move shared anon */
5637 } else if (!move_file())
5638 /* we ignore mapcount for file pages */
5640 if (!get_page_unless_zero(page))
5647 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5648 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5650 struct page *page = NULL;
5651 swp_entry_t ent = pte_to_swp_entry(ptent);
5653 if (!move_anon() || non_swap_entry(ent))
5656 * Because lookup_swap_cache() updates some statistics counter,
5657 * we call find_get_page() with swapper_space directly.
5659 page = find_get_page(&swapper_space, ent.val);
5660 if (do_swap_account)
5661 entry->val = ent.val;
5666 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5667 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5673 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5674 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5676 struct page *page = NULL;
5677 struct address_space *mapping;
5680 if (!vma->vm_file) /* anonymous vma */
5685 mapping = vma->vm_file->f_mapping;
5686 if (pte_none(ptent))
5687 pgoff = linear_page_index(vma, addr);
5688 else /* pte_file(ptent) is true */
5689 pgoff = pte_to_pgoff(ptent);
5691 /* page is moved even if it's not RSS of this task(page-faulted). */
5692 page = find_get_page(mapping, pgoff);
5695 /* shmem/tmpfs may report page out on swap: account for that too. */
5696 if (radix_tree_exceptional_entry(page)) {
5697 swp_entry_t swap = radix_to_swp_entry(page);
5698 if (do_swap_account)
5700 page = find_get_page(&swapper_space, swap.val);
5706 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
5707 unsigned long addr, pte_t ptent, union mc_target *target)
5709 struct page *page = NULL;
5710 struct page_cgroup *pc;
5711 enum mc_target_type ret = MC_TARGET_NONE;
5712 swp_entry_t ent = { .val = 0 };
5714 if (pte_present(ptent))
5715 page = mc_handle_present_pte(vma, addr, ptent);
5716 else if (is_swap_pte(ptent))
5717 page = mc_handle_swap_pte(vma, addr, ptent, &ent);
5718 else if (pte_none(ptent) || pte_file(ptent))
5719 page = mc_handle_file_pte(vma, addr, ptent, &ent);
5721 if (!page && !ent.val)
5724 pc = lookup_page_cgroup(page);
5726 * Do only loose check w/o page_cgroup lock.
5727 * mem_cgroup_move_account() checks the pc is valid or not under
5730 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
5731 ret = MC_TARGET_PAGE;
5733 target->page = page;
5735 if (!ret || !target)
5738 /* There is a swap entry and a page doesn't exist or isn't charged */
5739 if (ent.val && !ret &&
5740 css_id(&mc.from->css) == lookup_swap_cgroup_id(ent)) {
5741 ret = MC_TARGET_SWAP;
5748 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5750 * We don't consider swapping or file mapped pages because THP does not
5751 * support them for now.
5752 * Caller should make sure that pmd_trans_huge(pmd) is true.
5754 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5755 unsigned long addr, pmd_t pmd, union mc_target *target)
5757 struct page *page = NULL;
5758 struct page_cgroup *pc;
5759 enum mc_target_type ret = MC_TARGET_NONE;
5761 page = pmd_page(pmd);
5762 VM_BUG_ON(!page || !PageHead(page));
5765 pc = lookup_page_cgroup(page);
5766 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
5767 ret = MC_TARGET_PAGE;
5770 target->page = page;
5776 static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5777 unsigned long addr, pmd_t pmd, union mc_target *target)
5779 return MC_TARGET_NONE;
5783 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5784 unsigned long addr, unsigned long end,
5785 struct mm_walk *walk)
5787 struct vm_area_struct *vma = walk->private;
5791 if (pmd_trans_huge_lock(pmd, vma) == 1) {
5792 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
5793 mc.precharge += HPAGE_PMD_NR;
5794 spin_unlock(&vma->vm_mm->page_table_lock);
5798 if (pmd_trans_unstable(pmd))
5800 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5801 for (; addr != end; pte++, addr += PAGE_SIZE)
5802 if (get_mctgt_type(vma, addr, *pte, NULL))
5803 mc.precharge++; /* increment precharge temporarily */
5804 pte_unmap_unlock(pte - 1, ptl);
5810 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5812 unsigned long precharge;
5813 struct vm_area_struct *vma;
5815 down_read(&mm->mmap_sem);
5816 for (vma = mm->mmap; vma; vma = vma->vm_next) {
5817 struct mm_walk mem_cgroup_count_precharge_walk = {
5818 .pmd_entry = mem_cgroup_count_precharge_pte_range,
5822 if (is_vm_hugetlb_page(vma))
5824 walk_page_range(vma->vm_start, vma->vm_end,
5825 &mem_cgroup_count_precharge_walk);
5827 up_read(&mm->mmap_sem);
5829 precharge = mc.precharge;
5835 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5837 unsigned long precharge = mem_cgroup_count_precharge(mm);
5839 VM_BUG_ON(mc.moving_task);
5840 mc.moving_task = current;
5841 return mem_cgroup_do_precharge(precharge);
5844 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5845 static void __mem_cgroup_clear_mc(void)
5847 struct mem_cgroup *from = mc.from;
5848 struct mem_cgroup *to = mc.to;
5850 /* we must uncharge all the leftover precharges from mc.to */
5852 __mem_cgroup_cancel_charge(mc.to, mc.precharge);
5856 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5857 * we must uncharge here.
5859 if (mc.moved_charge) {
5860 __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
5861 mc.moved_charge = 0;
5863 /* we must fixup refcnts and charges */
5864 if (mc.moved_swap) {
5865 /* uncharge swap account from the old cgroup */
5866 if (!mem_cgroup_is_root(mc.from))
5867 res_counter_uncharge(&mc.from->memsw,
5868 PAGE_SIZE * mc.moved_swap);
5869 __mem_cgroup_put(mc.from, mc.moved_swap);
5871 if (!mem_cgroup_is_root(mc.to)) {
5873 * we charged both to->res and to->memsw, so we should
5876 res_counter_uncharge(&mc.to->res,
5877 PAGE_SIZE * mc.moved_swap);
5879 /* we've already done mem_cgroup_get(mc.to) */
5882 memcg_oom_recover(from);
5883 memcg_oom_recover(to);
5884 wake_up_all(&mc.waitq);
5887 static void mem_cgroup_clear_mc(void)
5889 struct mem_cgroup *from = mc.from;
5892 * we must clear moving_task before waking up waiters at the end of
5895 mc.moving_task = NULL;
5896 __mem_cgroup_clear_mc();
5897 spin_lock(&mc.lock);
5900 spin_unlock(&mc.lock);
5901 mem_cgroup_end_move(from);
5904 static int mem_cgroup_can_attach(struct cgroup *cgroup,
5905 struct cgroup_taskset *tset)
5907 struct task_struct *p = cgroup_taskset_first(tset);
5909 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgroup);
5911 if (memcg->move_charge_at_immigrate) {
5912 struct mm_struct *mm;
5913 struct mem_cgroup *from = mem_cgroup_from_task(p);
5915 VM_BUG_ON(from == memcg);
5917 mm = get_task_mm(p);
5920 /* We move charges only when we move a owner of the mm */
5921 if (mm->owner == p) {
5924 VM_BUG_ON(mc.precharge);
5925 VM_BUG_ON(mc.moved_charge);
5926 VM_BUG_ON(mc.moved_swap);
5927 mem_cgroup_start_move(from);
5928 spin_lock(&mc.lock);
5931 spin_unlock(&mc.lock);
5932 /* We set mc.moving_task later */
5934 ret = mem_cgroup_precharge_mc(mm);
5936 mem_cgroup_clear_mc();
5943 static void mem_cgroup_cancel_attach(struct cgroup *cgroup,
5944 struct cgroup_taskset *tset)
5946 mem_cgroup_clear_mc();
5949 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
5950 unsigned long addr, unsigned long end,
5951 struct mm_walk *walk)
5954 struct vm_area_struct *vma = walk->private;
5957 enum mc_target_type target_type;
5958 union mc_target target;
5960 struct page_cgroup *pc;
5963 * We don't take compound_lock() here but no race with splitting thp
5965 * - if pmd_trans_huge_lock() returns 1, the relevant thp is not
5966 * under splitting, which means there's no concurrent thp split,
5967 * - if another thread runs into split_huge_page() just after we
5968 * entered this if-block, the thread must wait for page table lock
5969 * to be unlocked in __split_huge_page_splitting(), where the main
5970 * part of thp split is not executed yet.
5972 if (pmd_trans_huge_lock(pmd, vma) == 1) {
5973 if (mc.precharge < HPAGE_PMD_NR) {
5974 spin_unlock(&vma->vm_mm->page_table_lock);
5977 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
5978 if (target_type == MC_TARGET_PAGE) {
5980 if (!isolate_lru_page(page)) {
5981 pc = lookup_page_cgroup(page);
5982 if (!mem_cgroup_move_account(page, HPAGE_PMD_NR,
5983 pc, mc.from, mc.to)) {
5984 mc.precharge -= HPAGE_PMD_NR;
5985 mc.moved_charge += HPAGE_PMD_NR;
5987 putback_lru_page(page);
5991 spin_unlock(&vma->vm_mm->page_table_lock);
5995 if (pmd_trans_unstable(pmd))
5998 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5999 for (; addr != end; addr += PAGE_SIZE) {
6000 pte_t ptent = *(pte++);
6006 switch (get_mctgt_type(vma, addr, ptent, &target)) {
6007 case MC_TARGET_PAGE:
6009 if (isolate_lru_page(page))
6011 pc = lookup_page_cgroup(page);
6012 if (!mem_cgroup_move_account(page, 1, pc,
6015 /* we uncharge from mc.from later. */
6018 putback_lru_page(page);
6019 put: /* get_mctgt_type() gets the page */
6022 case MC_TARGET_SWAP:
6024 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
6026 /* we fixup refcnts and charges later. */
6034 pte_unmap_unlock(pte - 1, ptl);
6039 * We have consumed all precharges we got in can_attach().
6040 * We try charge one by one, but don't do any additional
6041 * charges to mc.to if we have failed in charge once in attach()
6044 ret = mem_cgroup_do_precharge(1);
6052 static void mem_cgroup_move_charge(struct mm_struct *mm)
6054 struct vm_area_struct *vma;
6056 lru_add_drain_all();
6058 if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
6060 * Someone who are holding the mmap_sem might be waiting in
6061 * waitq. So we cancel all extra charges, wake up all waiters,
6062 * and retry. Because we cancel precharges, we might not be able
6063 * to move enough charges, but moving charge is a best-effort
6064 * feature anyway, so it wouldn't be a big problem.
6066 __mem_cgroup_clear_mc();
6070 for (vma = mm->mmap; vma; vma = vma->vm_next) {
6072 struct mm_walk mem_cgroup_move_charge_walk = {
6073 .pmd_entry = mem_cgroup_move_charge_pte_range,
6077 if (is_vm_hugetlb_page(vma))
6079 ret = walk_page_range(vma->vm_start, vma->vm_end,
6080 &mem_cgroup_move_charge_walk);
6083 * means we have consumed all precharges and failed in
6084 * doing additional charge. Just abandon here.
6088 up_read(&mm->mmap_sem);
6091 static void mem_cgroup_move_task(struct cgroup *cont,
6092 struct cgroup_taskset *tset)
6094 struct task_struct *p = cgroup_taskset_first(tset);
6095 struct mm_struct *mm = get_task_mm(p);
6099 mem_cgroup_move_charge(mm);
6103 mem_cgroup_clear_mc();
6105 #else /* !CONFIG_MMU */
6106 static int mem_cgroup_can_attach(struct cgroup *cgroup,
6107 struct cgroup_taskset *tset)
6111 static void mem_cgroup_cancel_attach(struct cgroup *cgroup,
6112 struct cgroup_taskset *tset)
6115 static void mem_cgroup_move_task(struct cgroup *cont,
6116 struct cgroup_taskset *tset)
6121 struct cgroup_subsys mem_cgroup_subsys = {
6123 .subsys_id = mem_cgroup_subsys_id,
6124 .css_alloc = mem_cgroup_css_alloc,
6125 .css_offline = mem_cgroup_css_offline,
6126 .css_free = mem_cgroup_css_free,
6127 .can_attach = mem_cgroup_can_attach,
6128 .cancel_attach = mem_cgroup_cancel_attach,
6129 .attach = mem_cgroup_move_task,
6130 .base_cftypes = mem_cgroup_files,
6135 #ifdef CONFIG_MEMCG_SWAP
6136 static int __init enable_swap_account(char *s)
6138 /* consider enabled if no parameter or 1 is given */
6139 if (!strcmp(s, "1"))
6140 really_do_swap_account = 1;
6141 else if (!strcmp(s, "0"))
6142 really_do_swap_account = 0;
6145 __setup("swapaccount=", enable_swap_account);