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 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
24 #include <linux/res_counter.h>
25 #include <linux/memcontrol.h>
26 #include <linux/cgroup.h>
28 #include <linux/hugetlb.h>
29 #include <linux/pagemap.h>
30 #include <linux/smp.h>
31 #include <linux/page-flags.h>
32 #include <linux/backing-dev.h>
33 #include <linux/bit_spinlock.h>
34 #include <linux/rcupdate.h>
35 #include <linux/limits.h>
36 #include <linux/mutex.h>
37 #include <linux/rbtree.h>
38 #include <linux/slab.h>
39 #include <linux/swap.h>
40 #include <linux/swapops.h>
41 #include <linux/spinlock.h>
42 #include <linux/eventfd.h>
43 #include <linux/sort.h>
45 #include <linux/seq_file.h>
46 #include <linux/vmalloc.h>
47 #include <linux/mm_inline.h>
48 #include <linux/page_cgroup.h>
49 #include <linux/cpu.h>
50 #include <linux/oom.h>
53 #include <asm/uaccess.h>
55 #include <trace/events/vmscan.h>
57 struct cgroup_subsys mem_cgroup_subsys __read_mostly;
58 #define MEM_CGROUP_RECLAIM_RETRIES 5
59 struct mem_cgroup *root_mem_cgroup __read_mostly;
61 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
62 /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
63 int do_swap_account __read_mostly;
65 /* for remember boot option*/
66 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP_ENABLED
67 static int really_do_swap_account __initdata = 1;
69 static int really_do_swap_account __initdata = 0;
73 #define do_swap_account (0)
78 * Statistics for memory cgroup.
80 enum mem_cgroup_stat_index {
82 * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
84 MEM_CGROUP_STAT_CACHE, /* # of pages charged as cache */
85 MEM_CGROUP_STAT_RSS, /* # of pages charged as anon rss */
86 MEM_CGROUP_STAT_FILE_MAPPED, /* # of pages charged as file rss */
87 MEM_CGROUP_STAT_SWAPOUT, /* # of pages, swapped out */
88 MEM_CGROUP_STAT_DATA, /* end of data requires synchronization */
89 MEM_CGROUP_ON_MOVE, /* someone is moving account between groups */
90 MEM_CGROUP_STAT_NSTATS,
93 enum mem_cgroup_events_index {
94 MEM_CGROUP_EVENTS_PGPGIN, /* # of pages paged in */
95 MEM_CGROUP_EVENTS_PGPGOUT, /* # of pages paged out */
96 MEM_CGROUP_EVENTS_COUNT, /* # of pages paged in/out */
97 MEM_CGROUP_EVENTS_PGFAULT, /* # of page-faults */
98 MEM_CGROUP_EVENTS_PGMAJFAULT, /* # of major page-faults */
99 MEM_CGROUP_EVENTS_NSTATS,
102 * Per memcg event counter is incremented at every pagein/pageout. With THP,
103 * it will be incremated by the number of pages. This counter is used for
104 * for trigger some periodic events. This is straightforward and better
105 * than using jiffies etc. to handle periodic memcg event.
107 enum mem_cgroup_events_target {
108 MEM_CGROUP_TARGET_THRESH,
109 MEM_CGROUP_TARGET_SOFTLIMIT,
110 MEM_CGROUP_TARGET_NUMAINFO,
113 #define THRESHOLDS_EVENTS_TARGET (128)
114 #define SOFTLIMIT_EVENTS_TARGET (1024)
115 #define NUMAINFO_EVENTS_TARGET (1024)
117 struct mem_cgroup_stat_cpu {
118 long count[MEM_CGROUP_STAT_NSTATS];
119 unsigned long events[MEM_CGROUP_EVENTS_NSTATS];
120 unsigned long targets[MEM_CGROUP_NTARGETS];
124 * per-zone information in memory controller.
126 struct mem_cgroup_per_zone {
128 * spin_lock to protect the per cgroup LRU
130 struct list_head lists[NR_LRU_LISTS];
131 unsigned long count[NR_LRU_LISTS];
133 struct zone_reclaim_stat reclaim_stat;
134 struct rb_node tree_node; /* RB tree node */
135 unsigned long long usage_in_excess;/* Set to the value by which */
136 /* the soft limit is exceeded*/
138 struct mem_cgroup *mem; /* Back pointer, we cannot */
139 /* use container_of */
141 /* Macro for accessing counter */
142 #define MEM_CGROUP_ZSTAT(mz, idx) ((mz)->count[(idx)])
144 struct mem_cgroup_per_node {
145 struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
148 struct mem_cgroup_lru_info {
149 struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
153 * Cgroups above their limits are maintained in a RB-Tree, independent of
154 * their hierarchy representation
157 struct mem_cgroup_tree_per_zone {
158 struct rb_root rb_root;
162 struct mem_cgroup_tree_per_node {
163 struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
166 struct mem_cgroup_tree {
167 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
170 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
172 struct mem_cgroup_threshold {
173 struct eventfd_ctx *eventfd;
178 struct mem_cgroup_threshold_ary {
179 /* An array index points to threshold just below usage. */
180 int current_threshold;
181 /* Size of entries[] */
183 /* Array of thresholds */
184 struct mem_cgroup_threshold entries[0];
187 struct mem_cgroup_thresholds {
188 /* Primary thresholds array */
189 struct mem_cgroup_threshold_ary *primary;
191 * Spare threshold array.
192 * This is needed to make mem_cgroup_unregister_event() "never fail".
193 * It must be able to store at least primary->size - 1 entries.
195 struct mem_cgroup_threshold_ary *spare;
199 struct mem_cgroup_eventfd_list {
200 struct list_head list;
201 struct eventfd_ctx *eventfd;
204 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
205 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
208 * The memory controller data structure. The memory controller controls both
209 * page cache and RSS per cgroup. We would eventually like to provide
210 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
211 * to help the administrator determine what knobs to tune.
213 * TODO: Add a water mark for the memory controller. Reclaim will begin when
214 * we hit the water mark. May be even add a low water mark, such that
215 * no reclaim occurs from a cgroup at it's low water mark, this is
216 * a feature that will be implemented much later in the future.
219 struct cgroup_subsys_state css;
221 * the counter to account for memory usage
223 struct res_counter res;
225 * the counter to account for mem+swap usage.
227 struct res_counter memsw;
229 * Per cgroup active and inactive list, similar to the
230 * per zone LRU lists.
232 struct mem_cgroup_lru_info info;
234 * While reclaiming in a hierarchy, we cache the last child we
237 int last_scanned_child;
238 int last_scanned_node;
240 nodemask_t scan_nodes;
241 atomic_t numainfo_events;
242 atomic_t numainfo_updating;
245 * Should the accounting and control be hierarchical, per subtree?
255 /* OOM-Killer disable */
256 int oom_kill_disable;
258 /* set when res.limit == memsw.limit */
259 bool memsw_is_minimum;
261 /* protect arrays of thresholds */
262 struct mutex thresholds_lock;
264 /* thresholds for memory usage. RCU-protected */
265 struct mem_cgroup_thresholds thresholds;
267 /* thresholds for mem+swap usage. RCU-protected */
268 struct mem_cgroup_thresholds memsw_thresholds;
270 /* For oom notifier event fd */
271 struct list_head oom_notify;
274 * Should we move charges of a task when a task is moved into this
275 * mem_cgroup ? And what type of charges should we move ?
277 unsigned long move_charge_at_immigrate;
281 struct mem_cgroup_stat_cpu *stat;
283 * used when a cpu is offlined or other synchronizations
284 * See mem_cgroup_read_stat().
286 struct mem_cgroup_stat_cpu nocpu_base;
287 spinlock_t pcp_counter_lock;
290 /* Stuffs for move charges at task migration. */
292 * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a
293 * left-shifted bitmap of these types.
296 MOVE_CHARGE_TYPE_ANON, /* private anonymous page and swap of it */
297 MOVE_CHARGE_TYPE_FILE, /* file page(including tmpfs) and swap of it */
301 /* "mc" and its members are protected by cgroup_mutex */
302 static struct move_charge_struct {
303 spinlock_t lock; /* for from, to */
304 struct mem_cgroup *from;
305 struct mem_cgroup *to;
306 unsigned long precharge;
307 unsigned long moved_charge;
308 unsigned long moved_swap;
309 struct task_struct *moving_task; /* a task moving charges */
310 wait_queue_head_t waitq; /* a waitq for other context */
312 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
313 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
316 static bool move_anon(void)
318 return test_bit(MOVE_CHARGE_TYPE_ANON,
319 &mc.to->move_charge_at_immigrate);
322 static bool move_file(void)
324 return test_bit(MOVE_CHARGE_TYPE_FILE,
325 &mc.to->move_charge_at_immigrate);
329 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
330 * limit reclaim to prevent infinite loops, if they ever occur.
332 #define MEM_CGROUP_MAX_RECLAIM_LOOPS (100)
333 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS (2)
336 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
337 MEM_CGROUP_CHARGE_TYPE_MAPPED,
338 MEM_CGROUP_CHARGE_TYPE_SHMEM, /* used by page migration of shmem */
339 MEM_CGROUP_CHARGE_TYPE_FORCE, /* used by force_empty */
340 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
341 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
345 /* for encoding cft->private value on file */
348 #define _OOM_TYPE (2)
349 #define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val))
350 #define MEMFILE_TYPE(val) (((val) >> 16) & 0xffff)
351 #define MEMFILE_ATTR(val) ((val) & 0xffff)
352 /* Used for OOM nofiier */
353 #define OOM_CONTROL (0)
356 * Reclaim flags for mem_cgroup_hierarchical_reclaim
358 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
359 #define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
360 #define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
361 #define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
362 #define MEM_CGROUP_RECLAIM_SOFT_BIT 0x2
363 #define MEM_CGROUP_RECLAIM_SOFT (1 << MEM_CGROUP_RECLAIM_SOFT_BIT)
365 static void mem_cgroup_get(struct mem_cgroup *memcg);
366 static void mem_cgroup_put(struct mem_cgroup *memcg);
367 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg);
368 static void drain_all_stock_async(struct mem_cgroup *memcg);
370 static struct mem_cgroup_per_zone *
371 mem_cgroup_zoneinfo(struct mem_cgroup *memcg, int nid, int zid)
373 return &memcg->info.nodeinfo[nid]->zoneinfo[zid];
376 struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *memcg)
381 static struct mem_cgroup_per_zone *
382 page_cgroup_zoneinfo(struct mem_cgroup *memcg, struct page *page)
384 int nid = page_to_nid(page);
385 int zid = page_zonenum(page);
387 return mem_cgroup_zoneinfo(memcg, nid, zid);
390 static struct mem_cgroup_tree_per_zone *
391 soft_limit_tree_node_zone(int nid, int zid)
393 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
396 static struct mem_cgroup_tree_per_zone *
397 soft_limit_tree_from_page(struct page *page)
399 int nid = page_to_nid(page);
400 int zid = page_zonenum(page);
402 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
406 __mem_cgroup_insert_exceeded(struct mem_cgroup *memcg,
407 struct mem_cgroup_per_zone *mz,
408 struct mem_cgroup_tree_per_zone *mctz,
409 unsigned long long new_usage_in_excess)
411 struct rb_node **p = &mctz->rb_root.rb_node;
412 struct rb_node *parent = NULL;
413 struct mem_cgroup_per_zone *mz_node;
418 mz->usage_in_excess = new_usage_in_excess;
419 if (!mz->usage_in_excess)
423 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
425 if (mz->usage_in_excess < mz_node->usage_in_excess)
428 * We can't avoid mem cgroups that are over their soft
429 * limit by the same amount
431 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
434 rb_link_node(&mz->tree_node, parent, p);
435 rb_insert_color(&mz->tree_node, &mctz->rb_root);
440 __mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
441 struct mem_cgroup_per_zone *mz,
442 struct mem_cgroup_tree_per_zone *mctz)
446 rb_erase(&mz->tree_node, &mctz->rb_root);
451 mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
452 struct mem_cgroup_per_zone *mz,
453 struct mem_cgroup_tree_per_zone *mctz)
455 spin_lock(&mctz->lock);
456 __mem_cgroup_remove_exceeded(memcg, mz, mctz);
457 spin_unlock(&mctz->lock);
461 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
463 unsigned long long excess;
464 struct mem_cgroup_per_zone *mz;
465 struct mem_cgroup_tree_per_zone *mctz;
466 int nid = page_to_nid(page);
467 int zid = page_zonenum(page);
468 mctz = soft_limit_tree_from_page(page);
471 * Necessary to update all ancestors when hierarchy is used.
472 * because their event counter is not touched.
474 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
475 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
476 excess = res_counter_soft_limit_excess(&memcg->res);
478 * We have to update the tree if mz is on RB-tree or
479 * mem is over its softlimit.
481 if (excess || mz->on_tree) {
482 spin_lock(&mctz->lock);
483 /* if on-tree, remove it */
485 __mem_cgroup_remove_exceeded(memcg, mz, mctz);
487 * Insert again. mz->usage_in_excess will be updated.
488 * If excess is 0, no tree ops.
490 __mem_cgroup_insert_exceeded(memcg, mz, mctz, excess);
491 spin_unlock(&mctz->lock);
496 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
499 struct mem_cgroup_per_zone *mz;
500 struct mem_cgroup_tree_per_zone *mctz;
502 for_each_node_state(node, N_POSSIBLE) {
503 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
504 mz = mem_cgroup_zoneinfo(memcg, node, zone);
505 mctz = soft_limit_tree_node_zone(node, zone);
506 mem_cgroup_remove_exceeded(memcg, mz, mctz);
511 static struct mem_cgroup_per_zone *
512 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
514 struct rb_node *rightmost = NULL;
515 struct mem_cgroup_per_zone *mz;
519 rightmost = rb_last(&mctz->rb_root);
521 goto done; /* Nothing to reclaim from */
523 mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
525 * Remove the node now but someone else can add it back,
526 * we will to add it back at the end of reclaim to its correct
527 * position in the tree.
529 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
530 if (!res_counter_soft_limit_excess(&mz->mem->res) ||
531 !css_tryget(&mz->mem->css))
537 static struct mem_cgroup_per_zone *
538 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
540 struct mem_cgroup_per_zone *mz;
542 spin_lock(&mctz->lock);
543 mz = __mem_cgroup_largest_soft_limit_node(mctz);
544 spin_unlock(&mctz->lock);
549 * Implementation Note: reading percpu statistics for memcg.
551 * Both of vmstat[] and percpu_counter has threshold and do periodic
552 * synchronization to implement "quick" read. There are trade-off between
553 * reading cost and precision of value. Then, we may have a chance to implement
554 * a periodic synchronizion of counter in memcg's counter.
556 * But this _read() function is used for user interface now. The user accounts
557 * memory usage by memory cgroup and he _always_ requires exact value because
558 * he accounts memory. Even if we provide quick-and-fuzzy read, we always
559 * have to visit all online cpus and make sum. So, for now, unnecessary
560 * synchronization is not implemented. (just implemented for cpu hotplug)
562 * If there are kernel internal actions which can make use of some not-exact
563 * value, and reading all cpu value can be performance bottleneck in some
564 * common workload, threashold and synchonization as vmstat[] should be
567 static long mem_cgroup_read_stat(struct mem_cgroup *memcg,
568 enum mem_cgroup_stat_index idx)
574 for_each_online_cpu(cpu)
575 val += per_cpu(memcg->stat->count[idx], cpu);
576 #ifdef CONFIG_HOTPLUG_CPU
577 spin_lock(&memcg->pcp_counter_lock);
578 val += memcg->nocpu_base.count[idx];
579 spin_unlock(&memcg->pcp_counter_lock);
585 static void mem_cgroup_swap_statistics(struct mem_cgroup *memcg,
588 int val = (charge) ? 1 : -1;
589 this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_SWAPOUT], val);
592 void mem_cgroup_pgfault(struct mem_cgroup *memcg, int val)
594 this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_PGFAULT], val);
597 void mem_cgroup_pgmajfault(struct mem_cgroup *memcg, int val)
599 this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_PGMAJFAULT], val);
602 static unsigned long mem_cgroup_read_events(struct mem_cgroup *memcg,
603 enum mem_cgroup_events_index idx)
605 unsigned long val = 0;
608 for_each_online_cpu(cpu)
609 val += per_cpu(memcg->stat->events[idx], cpu);
610 #ifdef CONFIG_HOTPLUG_CPU
611 spin_lock(&memcg->pcp_counter_lock);
612 val += memcg->nocpu_base.events[idx];
613 spin_unlock(&memcg->pcp_counter_lock);
618 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
619 bool file, int nr_pages)
624 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_CACHE],
627 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS],
630 /* pagein of a big page is an event. So, ignore page size */
632 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGIN]);
634 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]);
635 nr_pages = -nr_pages; /* for event */
638 __this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_COUNT], nr_pages);
644 mem_cgroup_zone_nr_lru_pages(struct mem_cgroup *memcg, int nid, int zid,
645 unsigned int lru_mask)
647 struct mem_cgroup_per_zone *mz;
649 unsigned long ret = 0;
651 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
654 if (BIT(l) & lru_mask)
655 ret += MEM_CGROUP_ZSTAT(mz, l);
661 mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
662 int nid, unsigned int lru_mask)
667 for (zid = 0; zid < MAX_NR_ZONES; zid++)
668 total += mem_cgroup_zone_nr_lru_pages(memcg,
674 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
675 unsigned int lru_mask)
680 for_each_node_state(nid, N_HIGH_MEMORY)
681 total += mem_cgroup_node_nr_lru_pages(memcg, nid, lru_mask);
685 static bool __memcg_event_check(struct mem_cgroup *memcg, int target)
687 unsigned long val, next;
689 val = this_cpu_read(memcg->stat->events[MEM_CGROUP_EVENTS_COUNT]);
690 next = this_cpu_read(memcg->stat->targets[target]);
691 /* from time_after() in jiffies.h */
692 return ((long)next - (long)val < 0);
695 static void __mem_cgroup_target_update(struct mem_cgroup *memcg, int target)
697 unsigned long val, next;
699 val = this_cpu_read(memcg->stat->events[MEM_CGROUP_EVENTS_COUNT]);
702 case MEM_CGROUP_TARGET_THRESH:
703 next = val + THRESHOLDS_EVENTS_TARGET;
705 case MEM_CGROUP_TARGET_SOFTLIMIT:
706 next = val + SOFTLIMIT_EVENTS_TARGET;
708 case MEM_CGROUP_TARGET_NUMAINFO:
709 next = val + NUMAINFO_EVENTS_TARGET;
715 this_cpu_write(memcg->stat->targets[target], next);
719 * Check events in order.
722 static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
724 /* threshold event is triggered in finer grain than soft limit */
725 if (unlikely(__memcg_event_check(memcg, MEM_CGROUP_TARGET_THRESH))) {
726 mem_cgroup_threshold(memcg);
727 __mem_cgroup_target_update(memcg, MEM_CGROUP_TARGET_THRESH);
728 if (unlikely(__memcg_event_check(memcg,
729 MEM_CGROUP_TARGET_SOFTLIMIT))) {
730 mem_cgroup_update_tree(memcg, page);
731 __mem_cgroup_target_update(memcg,
732 MEM_CGROUP_TARGET_SOFTLIMIT);
735 if (unlikely(__memcg_event_check(memcg,
736 MEM_CGROUP_TARGET_NUMAINFO))) {
737 atomic_inc(&memcg->numainfo_events);
738 __mem_cgroup_target_update(memcg,
739 MEM_CGROUP_TARGET_NUMAINFO);
745 static struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
747 return container_of(cgroup_subsys_state(cont,
748 mem_cgroup_subsys_id), struct mem_cgroup,
752 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
755 * mm_update_next_owner() may clear mm->owner to NULL
756 * if it races with swapoff, page migration, etc.
757 * So this can be called with p == NULL.
762 return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
763 struct mem_cgroup, css);
766 struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
768 struct mem_cgroup *memcg = NULL;
773 * Because we have no locks, mm->owner's may be being moved to other
774 * cgroup. We use css_tryget() here even if this looks
775 * pessimistic (rather than adding locks here).
779 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
780 if (unlikely(!memcg))
782 } while (!css_tryget(&memcg->css));
787 /* The caller has to guarantee "mem" exists before calling this */
788 static struct mem_cgroup *mem_cgroup_start_loop(struct mem_cgroup *memcg)
790 struct cgroup_subsys_state *css;
793 if (!memcg) /* ROOT cgroup has the smallest ID */
794 return root_mem_cgroup; /*css_put/get against root is ignored*/
795 if (!memcg->use_hierarchy) {
796 if (css_tryget(&memcg->css))
802 * searching a memory cgroup which has the smallest ID under given
803 * ROOT cgroup. (ID >= 1)
805 css = css_get_next(&mem_cgroup_subsys, 1, &memcg->css, &found);
806 if (css && css_tryget(css))
807 memcg = container_of(css, struct mem_cgroup, css);
814 static struct mem_cgroup *mem_cgroup_get_next(struct mem_cgroup *iter,
815 struct mem_cgroup *root,
818 int nextid = css_id(&iter->css) + 1;
821 struct cgroup_subsys_state *css;
823 hierarchy_used = iter->use_hierarchy;
826 /* If no ROOT, walk all, ignore hierarchy */
827 if (!cond || (root && !hierarchy_used))
831 root = root_mem_cgroup;
837 css = css_get_next(&mem_cgroup_subsys, nextid,
839 if (css && css_tryget(css))
840 iter = container_of(css, struct mem_cgroup, css);
842 /* If css is NULL, no more cgroups will be found */
844 } while (css && !iter);
849 * for_eacn_mem_cgroup_tree() for visiting all cgroup under tree. Please
850 * be careful that "break" loop is not allowed. We have reference count.
851 * Instead of that modify "cond" to be false and "continue" to exit the loop.
853 #define for_each_mem_cgroup_tree_cond(iter, root, cond) \
854 for (iter = mem_cgroup_start_loop(root);\
856 iter = mem_cgroup_get_next(iter, root, cond))
858 #define for_each_mem_cgroup_tree(iter, root) \
859 for_each_mem_cgroup_tree_cond(iter, root, true)
861 #define for_each_mem_cgroup_all(iter) \
862 for_each_mem_cgroup_tree_cond(iter, NULL, true)
865 static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
867 return (memcg == root_mem_cgroup);
870 void mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx)
872 struct mem_cgroup *memcg;
878 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
879 if (unlikely(!memcg))
884 mem_cgroup_pgmajfault(memcg, 1);
887 mem_cgroup_pgfault(memcg, 1);
895 EXPORT_SYMBOL(mem_cgroup_count_vm_event);
898 * Following LRU functions are allowed to be used without PCG_LOCK.
899 * Operations are called by routine of global LRU independently from memcg.
900 * What we have to take care of here is validness of pc->mem_cgroup.
902 * Changes to pc->mem_cgroup happens when
905 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
906 * It is added to LRU before charge.
907 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
908 * When moving account, the page is not on LRU. It's isolated.
911 void mem_cgroup_del_lru_list(struct page *page, enum lru_list lru)
913 struct page_cgroup *pc;
914 struct mem_cgroup_per_zone *mz;
916 if (mem_cgroup_disabled())
918 pc = lookup_page_cgroup(page);
919 /* can happen while we handle swapcache. */
920 if (!TestClearPageCgroupAcctLRU(pc))
922 VM_BUG_ON(!pc->mem_cgroup);
924 * We don't check PCG_USED bit. It's cleared when the "page" is finally
925 * removed from global LRU.
927 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
928 /* huge page split is done under lru_lock. so, we have no races. */
929 MEM_CGROUP_ZSTAT(mz, lru) -= 1 << compound_order(page);
930 if (mem_cgroup_is_root(pc->mem_cgroup))
932 VM_BUG_ON(list_empty(&pc->lru));
933 list_del_init(&pc->lru);
936 void mem_cgroup_del_lru(struct page *page)
938 mem_cgroup_del_lru_list(page, page_lru(page));
942 * Writeback is about to end against a page which has been marked for immediate
943 * reclaim. If it still appears to be reclaimable, move it to the tail of the
946 void mem_cgroup_rotate_reclaimable_page(struct page *page)
948 struct mem_cgroup_per_zone *mz;
949 struct page_cgroup *pc;
950 enum lru_list lru = page_lru(page);
952 if (mem_cgroup_disabled())
955 pc = lookup_page_cgroup(page);
956 /* unused or root page is not rotated. */
957 if (!PageCgroupUsed(pc))
959 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
961 if (mem_cgroup_is_root(pc->mem_cgroup))
963 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
964 list_move_tail(&pc->lru, &mz->lists[lru]);
967 void mem_cgroup_rotate_lru_list(struct page *page, enum lru_list lru)
969 struct mem_cgroup_per_zone *mz;
970 struct page_cgroup *pc;
972 if (mem_cgroup_disabled())
975 pc = lookup_page_cgroup(page);
976 /* unused or root page is not rotated. */
977 if (!PageCgroupUsed(pc))
979 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
981 if (mem_cgroup_is_root(pc->mem_cgroup))
983 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
984 list_move(&pc->lru, &mz->lists[lru]);
987 void mem_cgroup_add_lru_list(struct page *page, enum lru_list lru)
989 struct page_cgroup *pc;
990 struct mem_cgroup_per_zone *mz;
992 if (mem_cgroup_disabled())
994 pc = lookup_page_cgroup(page);
995 VM_BUG_ON(PageCgroupAcctLRU(pc));
998 * SetPageLRU SetPageCgroupUsed
1000 * PageCgroupUsed && add to memcg LRU PageLRU && add to memcg LRU
1002 * Ensure that one of the two sides adds the page to the memcg
1003 * LRU during a race.
1006 if (!PageCgroupUsed(pc))
1008 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1010 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1011 /* huge page split is done under lru_lock. so, we have no races. */
1012 MEM_CGROUP_ZSTAT(mz, lru) += 1 << compound_order(page);
1013 SetPageCgroupAcctLRU(pc);
1014 if (mem_cgroup_is_root(pc->mem_cgroup))
1016 list_add(&pc->lru, &mz->lists[lru]);
1020 * At handling SwapCache and other FUSE stuff, pc->mem_cgroup may be changed
1021 * while it's linked to lru because the page may be reused after it's fully
1022 * uncharged. To handle that, unlink page_cgroup from LRU when charge it again.
1023 * It's done under lock_page and expected that zone->lru_lock isnever held.
1025 static void mem_cgroup_lru_del_before_commit(struct page *page)
1027 unsigned long flags;
1028 struct zone *zone = page_zone(page);
1029 struct page_cgroup *pc = lookup_page_cgroup(page);
1032 * Doing this check without taking ->lru_lock seems wrong but this
1033 * is safe. Because if page_cgroup's USED bit is unset, the page
1034 * will not be added to any memcg's LRU. If page_cgroup's USED bit is
1035 * set, the commit after this will fail, anyway.
1036 * This all charge/uncharge is done under some mutual execustion.
1037 * So, we don't need to taking care of changes in USED bit.
1039 if (likely(!PageLRU(page)))
1042 spin_lock_irqsave(&zone->lru_lock, flags);
1044 * Forget old LRU when this page_cgroup is *not* used. This Used bit
1045 * is guarded by lock_page() because the page is SwapCache.
1047 if (!PageCgroupUsed(pc))
1048 mem_cgroup_del_lru_list(page, page_lru(page));
1049 spin_unlock_irqrestore(&zone->lru_lock, flags);
1052 static void mem_cgroup_lru_add_after_commit(struct page *page)
1054 unsigned long flags;
1055 struct zone *zone = page_zone(page);
1056 struct page_cgroup *pc = lookup_page_cgroup(page);
1059 * SetPageLRU SetPageCgroupUsed
1061 * PageCgroupUsed && add to memcg LRU PageLRU && add to memcg LRU
1063 * Ensure that one of the two sides adds the page to the memcg
1064 * LRU during a race.
1067 /* taking care of that the page is added to LRU while we commit it */
1068 if (likely(!PageLRU(page)))
1070 spin_lock_irqsave(&zone->lru_lock, flags);
1071 /* link when the page is linked to LRU but page_cgroup isn't */
1072 if (PageLRU(page) && !PageCgroupAcctLRU(pc))
1073 mem_cgroup_add_lru_list(page, page_lru(page));
1074 spin_unlock_irqrestore(&zone->lru_lock, flags);
1078 void mem_cgroup_move_lists(struct page *page,
1079 enum lru_list from, enum lru_list to)
1081 if (mem_cgroup_disabled())
1083 mem_cgroup_del_lru_list(page, from);
1084 mem_cgroup_add_lru_list(page, to);
1088 * Checks whether given mem is same or in the root_mem_cgroup's
1091 static bool mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1092 struct mem_cgroup *memcg)
1094 if (root_memcg != memcg) {
1095 return (root_memcg->use_hierarchy &&
1096 css_is_ancestor(&memcg->css, &root_memcg->css));
1102 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *memcg)
1105 struct mem_cgroup *curr = NULL;
1106 struct task_struct *p;
1108 p = find_lock_task_mm(task);
1111 curr = try_get_mem_cgroup_from_mm(p->mm);
1116 * We should check use_hierarchy of "memcg" not "curr". Because checking
1117 * use_hierarchy of "curr" here make this function true if hierarchy is
1118 * enabled in "curr" and "curr" is a child of "memcg" in *cgroup*
1119 * hierarchy(even if use_hierarchy is disabled in "memcg").
1121 ret = mem_cgroup_same_or_subtree(memcg, curr);
1122 css_put(&curr->css);
1126 int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg, struct zone *zone)
1128 unsigned long inactive_ratio;
1129 int nid = zone_to_nid(zone);
1130 int zid = zone_idx(zone);
1131 unsigned long inactive;
1132 unsigned long active;
1135 inactive = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1136 BIT(LRU_INACTIVE_ANON));
1137 active = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1138 BIT(LRU_ACTIVE_ANON));
1140 gb = (inactive + active) >> (30 - PAGE_SHIFT);
1142 inactive_ratio = int_sqrt(10 * gb);
1146 return inactive * inactive_ratio < active;
1149 int mem_cgroup_inactive_file_is_low(struct mem_cgroup *memcg, struct zone *zone)
1151 unsigned long active;
1152 unsigned long inactive;
1153 int zid = zone_idx(zone);
1154 int nid = zone_to_nid(zone);
1156 inactive = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1157 BIT(LRU_INACTIVE_FILE));
1158 active = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1159 BIT(LRU_ACTIVE_FILE));
1161 return (active > inactive);
1164 struct zone_reclaim_stat *mem_cgroup_get_reclaim_stat(struct mem_cgroup *memcg,
1167 int nid = zone_to_nid(zone);
1168 int zid = zone_idx(zone);
1169 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
1171 return &mz->reclaim_stat;
1174 struct zone_reclaim_stat *
1175 mem_cgroup_get_reclaim_stat_from_page(struct page *page)
1177 struct page_cgroup *pc;
1178 struct mem_cgroup_per_zone *mz;
1180 if (mem_cgroup_disabled())
1183 pc = lookup_page_cgroup(page);
1184 if (!PageCgroupUsed(pc))
1186 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1188 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1189 return &mz->reclaim_stat;
1192 unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan,
1193 struct list_head *dst,
1194 unsigned long *scanned, int order,
1195 isolate_mode_t mode,
1197 struct mem_cgroup *mem_cont,
1198 int active, int file)
1200 unsigned long nr_taken = 0;
1204 struct list_head *src;
1205 struct page_cgroup *pc, *tmp;
1206 int nid = zone_to_nid(z);
1207 int zid = zone_idx(z);
1208 struct mem_cgroup_per_zone *mz;
1209 int lru = LRU_FILE * file + active;
1213 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
1214 src = &mz->lists[lru];
1217 list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
1218 if (scan >= nr_to_scan)
1221 if (unlikely(!PageCgroupUsed(pc)))
1224 page = lookup_cgroup_page(pc);
1226 if (unlikely(!PageLRU(page)))
1230 ret = __isolate_lru_page(page, mode, file);
1233 list_move(&page->lru, dst);
1234 mem_cgroup_del_lru(page);
1235 nr_taken += hpage_nr_pages(page);
1238 /* we don't affect global LRU but rotate in our LRU */
1239 mem_cgroup_rotate_lru_list(page, page_lru(page));
1248 trace_mm_vmscan_memcg_isolate(0, nr_to_scan, scan, nr_taken,
1254 #define mem_cgroup_from_res_counter(counter, member) \
1255 container_of(counter, struct mem_cgroup, member)
1258 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1259 * @mem: the memory cgroup
1261 * Returns the maximum amount of memory @mem can be charged with, in
1264 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1266 unsigned long long margin;
1268 margin = res_counter_margin(&memcg->res);
1269 if (do_swap_account)
1270 margin = min(margin, res_counter_margin(&memcg->memsw));
1271 return margin >> PAGE_SHIFT;
1274 int mem_cgroup_swappiness(struct mem_cgroup *memcg)
1276 struct cgroup *cgrp = memcg->css.cgroup;
1279 if (cgrp->parent == NULL)
1280 return vm_swappiness;
1282 return memcg->swappiness;
1285 static void mem_cgroup_start_move(struct mem_cgroup *memcg)
1290 spin_lock(&memcg->pcp_counter_lock);
1291 for_each_online_cpu(cpu)
1292 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) += 1;
1293 memcg->nocpu_base.count[MEM_CGROUP_ON_MOVE] += 1;
1294 spin_unlock(&memcg->pcp_counter_lock);
1300 static void mem_cgroup_end_move(struct mem_cgroup *memcg)
1307 spin_lock(&memcg->pcp_counter_lock);
1308 for_each_online_cpu(cpu)
1309 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) -= 1;
1310 memcg->nocpu_base.count[MEM_CGROUP_ON_MOVE] -= 1;
1311 spin_unlock(&memcg->pcp_counter_lock);
1315 * 2 routines for checking "mem" is under move_account() or not.
1317 * mem_cgroup_stealed() - checking a cgroup is mc.from or not. This is used
1318 * for avoiding race in accounting. If true,
1319 * pc->mem_cgroup may be overwritten.
1321 * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
1322 * under hierarchy of moving cgroups. This is for
1323 * waiting at hith-memory prressure caused by "move".
1326 static bool mem_cgroup_stealed(struct mem_cgroup *memcg)
1328 VM_BUG_ON(!rcu_read_lock_held());
1329 return this_cpu_read(memcg->stat->count[MEM_CGROUP_ON_MOVE]) > 0;
1332 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1334 struct mem_cgroup *from;
1335 struct mem_cgroup *to;
1338 * Unlike task_move routines, we access mc.to, mc.from not under
1339 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1341 spin_lock(&mc.lock);
1347 ret = mem_cgroup_same_or_subtree(memcg, from)
1348 || mem_cgroup_same_or_subtree(memcg, to);
1350 spin_unlock(&mc.lock);
1354 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1356 if (mc.moving_task && current != mc.moving_task) {
1357 if (mem_cgroup_under_move(memcg)) {
1359 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1360 /* moving charge context might have finished. */
1363 finish_wait(&mc.waitq, &wait);
1371 * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode.
1372 * @memcg: The memory cgroup that went over limit
1373 * @p: Task that is going to be killed
1375 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1378 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1380 struct cgroup *task_cgrp;
1381 struct cgroup *mem_cgrp;
1383 * Need a buffer in BSS, can't rely on allocations. The code relies
1384 * on the assumption that OOM is serialized for memory controller.
1385 * If this assumption is broken, revisit this code.
1387 static char memcg_name[PATH_MAX];
1396 mem_cgrp = memcg->css.cgroup;
1397 task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1399 ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1402 * Unfortunately, we are unable to convert to a useful name
1403 * But we'll still print out the usage information
1410 printk(KERN_INFO "Task in %s killed", memcg_name);
1413 ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1421 * Continues from above, so we don't need an KERN_ level
1423 printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
1426 printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
1427 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1428 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1429 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1430 printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
1432 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1433 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1434 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1438 * This function returns the number of memcg under hierarchy tree. Returns
1439 * 1(self count) if no children.
1441 static int mem_cgroup_count_children(struct mem_cgroup *memcg)
1444 struct mem_cgroup *iter;
1446 for_each_mem_cgroup_tree(iter, memcg)
1452 * Return the memory (and swap, if configured) limit for a memcg.
1454 u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
1459 limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
1460 limit += total_swap_pages << PAGE_SHIFT;
1462 memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
1464 * If memsw is finite and limits the amount of swap space available
1465 * to this memcg, return that limit.
1467 return min(limit, memsw);
1471 * Visit the first child (need not be the first child as per the ordering
1472 * of the cgroup list, since we track last_scanned_child) of @mem and use
1473 * that to reclaim free pages from.
1475 static struct mem_cgroup *
1476 mem_cgroup_select_victim(struct mem_cgroup *root_memcg)
1478 struct mem_cgroup *ret = NULL;
1479 struct cgroup_subsys_state *css;
1482 if (!root_memcg->use_hierarchy) {
1483 css_get(&root_memcg->css);
1489 nextid = root_memcg->last_scanned_child + 1;
1490 css = css_get_next(&mem_cgroup_subsys, nextid, &root_memcg->css,
1492 if (css && css_tryget(css))
1493 ret = container_of(css, struct mem_cgroup, css);
1496 /* Updates scanning parameter */
1498 /* this means start scan from ID:1 */
1499 root_memcg->last_scanned_child = 0;
1501 root_memcg->last_scanned_child = found;
1508 * test_mem_cgroup_node_reclaimable
1509 * @mem: the target memcg
1510 * @nid: the node ID to be checked.
1511 * @noswap : specify true here if the user wants flle only information.
1513 * This function returns whether the specified memcg contains any
1514 * reclaimable pages on a node. Returns true if there are any reclaimable
1515 * pages in the node.
1517 static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
1518 int nid, bool noswap)
1520 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE))
1522 if (noswap || !total_swap_pages)
1524 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON))
1529 #if MAX_NUMNODES > 1
1532 * Always updating the nodemask is not very good - even if we have an empty
1533 * list or the wrong list here, we can start from some node and traverse all
1534 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1537 static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
1541 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1542 * pagein/pageout changes since the last update.
1544 if (!atomic_read(&memcg->numainfo_events))
1546 if (atomic_inc_return(&memcg->numainfo_updating) > 1)
1549 /* make a nodemask where this memcg uses memory from */
1550 memcg->scan_nodes = node_states[N_HIGH_MEMORY];
1552 for_each_node_mask(nid, node_states[N_HIGH_MEMORY]) {
1554 if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
1555 node_clear(nid, memcg->scan_nodes);
1558 atomic_set(&memcg->numainfo_events, 0);
1559 atomic_set(&memcg->numainfo_updating, 0);
1563 * Selecting a node where we start reclaim from. Because what we need is just
1564 * reducing usage counter, start from anywhere is O,K. Considering
1565 * memory reclaim from current node, there are pros. and cons.
1567 * Freeing memory from current node means freeing memory from a node which
1568 * we'll use or we've used. So, it may make LRU bad. And if several threads
1569 * hit limits, it will see a contention on a node. But freeing from remote
1570 * node means more costs for memory reclaim because of memory latency.
1572 * Now, we use round-robin. Better algorithm is welcomed.
1574 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1578 mem_cgroup_may_update_nodemask(memcg);
1579 node = memcg->last_scanned_node;
1581 node = next_node(node, memcg->scan_nodes);
1582 if (node == MAX_NUMNODES)
1583 node = first_node(memcg->scan_nodes);
1585 * We call this when we hit limit, not when pages are added to LRU.
1586 * No LRU may hold pages because all pages are UNEVICTABLE or
1587 * memcg is too small and all pages are not on LRU. In that case,
1588 * we use curret node.
1590 if (unlikely(node == MAX_NUMNODES))
1591 node = numa_node_id();
1593 memcg->last_scanned_node = node;
1598 * Check all nodes whether it contains reclaimable pages or not.
1599 * For quick scan, we make use of scan_nodes. This will allow us to skip
1600 * unused nodes. But scan_nodes is lazily updated and may not cotain
1601 * enough new information. We need to do double check.
1603 bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
1608 * quick check...making use of scan_node.
1609 * We can skip unused nodes.
1611 if (!nodes_empty(memcg->scan_nodes)) {
1612 for (nid = first_node(memcg->scan_nodes);
1614 nid = next_node(nid, memcg->scan_nodes)) {
1616 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
1621 * Check rest of nodes.
1623 for_each_node_state(nid, N_HIGH_MEMORY) {
1624 if (node_isset(nid, memcg->scan_nodes))
1626 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
1633 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1638 bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
1640 return test_mem_cgroup_node_reclaimable(memcg, 0, noswap);
1645 * Scan the hierarchy if needed to reclaim memory. We remember the last child
1646 * we reclaimed from, so that we don't end up penalizing one child extensively
1647 * based on its position in the children list.
1649 * root_memcg is the original ancestor that we've been reclaim from.
1651 * We give up and return to the caller when we visit root_memcg twice.
1652 * (other groups can be removed while we're walking....)
1654 * If shrink==true, for avoiding to free too much, this returns immedieately.
1656 static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup *root_memcg,
1659 unsigned long reclaim_options,
1660 unsigned long *total_scanned)
1662 struct mem_cgroup *victim;
1665 bool noswap = reclaim_options & MEM_CGROUP_RECLAIM_NOSWAP;
1666 bool shrink = reclaim_options & MEM_CGROUP_RECLAIM_SHRINK;
1667 bool check_soft = reclaim_options & MEM_CGROUP_RECLAIM_SOFT;
1668 unsigned long excess;
1669 unsigned long nr_scanned;
1671 excess = res_counter_soft_limit_excess(&root_memcg->res) >> PAGE_SHIFT;
1673 /* If memsw_is_minimum==1, swap-out is of-no-use. */
1674 if (!check_soft && !shrink && root_memcg->memsw_is_minimum)
1678 victim = mem_cgroup_select_victim(root_memcg);
1679 if (victim == root_memcg) {
1682 * We are not draining per cpu cached charges during
1683 * soft limit reclaim because global reclaim doesn't
1684 * care about charges. It tries to free some memory and
1685 * charges will not give any.
1687 if (!check_soft && loop >= 1)
1688 drain_all_stock_async(root_memcg);
1691 * If we have not been able to reclaim
1692 * anything, it might because there are
1693 * no reclaimable pages under this hierarchy
1695 if (!check_soft || !total) {
1696 css_put(&victim->css);
1700 * We want to do more targeted reclaim.
1701 * excess >> 2 is not to excessive so as to
1702 * reclaim too much, nor too less that we keep
1703 * coming back to reclaim from this cgroup
1705 if (total >= (excess >> 2) ||
1706 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS)) {
1707 css_put(&victim->css);
1712 if (!mem_cgroup_reclaimable(victim, noswap)) {
1713 /* this cgroup's local usage == 0 */
1714 css_put(&victim->css);
1717 /* we use swappiness of local cgroup */
1719 ret = mem_cgroup_shrink_node_zone(victim, gfp_mask,
1720 noswap, zone, &nr_scanned);
1721 *total_scanned += nr_scanned;
1723 ret = try_to_free_mem_cgroup_pages(victim, gfp_mask,
1725 css_put(&victim->css);
1727 * At shrinking usage, we can't check we should stop here or
1728 * reclaim more. It's depends on callers. last_scanned_child
1729 * will work enough for keeping fairness under tree.
1735 if (!res_counter_soft_limit_excess(&root_memcg->res))
1737 } else if (mem_cgroup_margin(root_memcg))
1744 * Check OOM-Killer is already running under our hierarchy.
1745 * If someone is running, return false.
1746 * Has to be called with memcg_oom_lock
1748 static bool mem_cgroup_oom_lock(struct mem_cgroup *memcg)
1750 struct mem_cgroup *iter, *failed = NULL;
1753 for_each_mem_cgroup_tree_cond(iter, memcg, cond) {
1754 if (iter->oom_lock) {
1756 * this subtree of our hierarchy is already locked
1757 * so we cannot give a lock.
1762 iter->oom_lock = true;
1769 * OK, we failed to lock the whole subtree so we have to clean up
1770 * what we set up to the failing subtree
1773 for_each_mem_cgroup_tree_cond(iter, memcg, cond) {
1774 if (iter == failed) {
1778 iter->oom_lock = false;
1784 * Has to be called with memcg_oom_lock
1786 static int mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1788 struct mem_cgroup *iter;
1790 for_each_mem_cgroup_tree(iter, memcg)
1791 iter->oom_lock = false;
1795 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1797 struct mem_cgroup *iter;
1799 for_each_mem_cgroup_tree(iter, memcg)
1800 atomic_inc(&iter->under_oom);
1803 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1805 struct mem_cgroup *iter;
1808 * When a new child is created while the hierarchy is under oom,
1809 * mem_cgroup_oom_lock() may not be called. We have to use
1810 * atomic_add_unless() here.
1812 for_each_mem_cgroup_tree(iter, memcg)
1813 atomic_add_unless(&iter->under_oom, -1, 0);
1816 static DEFINE_SPINLOCK(memcg_oom_lock);
1817 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1819 struct oom_wait_info {
1820 struct mem_cgroup *mem;
1824 static int memcg_oom_wake_function(wait_queue_t *wait,
1825 unsigned mode, int sync, void *arg)
1827 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg,
1829 struct oom_wait_info *oom_wait_info;
1831 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1832 oom_wait_memcg = oom_wait_info->mem;
1835 * Both of oom_wait_info->mem and wake_mem are stable under us.
1836 * Then we can use css_is_ancestor without taking care of RCU.
1838 if (!mem_cgroup_same_or_subtree(oom_wait_memcg, wake_memcg)
1839 && !mem_cgroup_same_or_subtree(wake_memcg, oom_wait_memcg))
1841 return autoremove_wake_function(wait, mode, sync, arg);
1844 static void memcg_wakeup_oom(struct mem_cgroup *memcg)
1846 /* for filtering, pass "memcg" as argument. */
1847 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
1850 static void memcg_oom_recover(struct mem_cgroup *memcg)
1852 if (memcg && atomic_read(&memcg->under_oom))
1853 memcg_wakeup_oom(memcg);
1857 * try to call OOM killer. returns false if we should exit memory-reclaim loop.
1859 bool mem_cgroup_handle_oom(struct mem_cgroup *memcg, gfp_t mask)
1861 struct oom_wait_info owait;
1862 bool locked, need_to_kill;
1865 owait.wait.flags = 0;
1866 owait.wait.func = memcg_oom_wake_function;
1867 owait.wait.private = current;
1868 INIT_LIST_HEAD(&owait.wait.task_list);
1869 need_to_kill = true;
1870 mem_cgroup_mark_under_oom(memcg);
1872 /* At first, try to OOM lock hierarchy under memcg.*/
1873 spin_lock(&memcg_oom_lock);
1874 locked = mem_cgroup_oom_lock(memcg);
1876 * Even if signal_pending(), we can't quit charge() loop without
1877 * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
1878 * under OOM is always welcomed, use TASK_KILLABLE here.
1880 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
1881 if (!locked || memcg->oom_kill_disable)
1882 need_to_kill = false;
1884 mem_cgroup_oom_notify(memcg);
1885 spin_unlock(&memcg_oom_lock);
1888 finish_wait(&memcg_oom_waitq, &owait.wait);
1889 mem_cgroup_out_of_memory(memcg, mask);
1892 finish_wait(&memcg_oom_waitq, &owait.wait);
1894 spin_lock(&memcg_oom_lock);
1896 mem_cgroup_oom_unlock(memcg);
1897 memcg_wakeup_oom(memcg);
1898 spin_unlock(&memcg_oom_lock);
1900 mem_cgroup_unmark_under_oom(memcg);
1902 if (test_thread_flag(TIF_MEMDIE) || fatal_signal_pending(current))
1904 /* Give chance to dying process */
1905 schedule_timeout_uninterruptible(1);
1910 * Currently used to update mapped file statistics, but the routine can be
1911 * generalized to update other statistics as well.
1913 * Notes: Race condition
1915 * We usually use page_cgroup_lock() for accessing page_cgroup member but
1916 * it tends to be costly. But considering some conditions, we doesn't need
1917 * to do so _always_.
1919 * Considering "charge", lock_page_cgroup() is not required because all
1920 * file-stat operations happen after a page is attached to radix-tree. There
1921 * are no race with "charge".
1923 * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
1924 * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
1925 * if there are race with "uncharge". Statistics itself is properly handled
1928 * Considering "move", this is an only case we see a race. To make the race
1929 * small, we check MEM_CGROUP_ON_MOVE percpu value and detect there are
1930 * possibility of race condition. If there is, we take a lock.
1933 void mem_cgroup_update_page_stat(struct page *page,
1934 enum mem_cgroup_page_stat_item idx, int val)
1936 struct mem_cgroup *memcg;
1937 struct page_cgroup *pc = lookup_page_cgroup(page);
1938 bool need_unlock = false;
1939 unsigned long uninitialized_var(flags);
1945 memcg = pc->mem_cgroup;
1946 if (unlikely(!memcg || !PageCgroupUsed(pc)))
1948 /* pc->mem_cgroup is unstable ? */
1949 if (unlikely(mem_cgroup_stealed(memcg)) || PageTransHuge(page)) {
1950 /* take a lock against to access pc->mem_cgroup */
1951 move_lock_page_cgroup(pc, &flags);
1953 memcg = pc->mem_cgroup;
1954 if (!memcg || !PageCgroupUsed(pc))
1959 case MEMCG_NR_FILE_MAPPED:
1961 SetPageCgroupFileMapped(pc);
1962 else if (!page_mapped(page))
1963 ClearPageCgroupFileMapped(pc);
1964 idx = MEM_CGROUP_STAT_FILE_MAPPED;
1970 this_cpu_add(memcg->stat->count[idx], val);
1973 if (unlikely(need_unlock))
1974 move_unlock_page_cgroup(pc, &flags);
1978 EXPORT_SYMBOL(mem_cgroup_update_page_stat);
1981 * size of first charge trial. "32" comes from vmscan.c's magic value.
1982 * TODO: maybe necessary to use big numbers in big irons.
1984 #define CHARGE_BATCH 32U
1985 struct memcg_stock_pcp {
1986 struct mem_cgroup *cached; /* this never be root cgroup */
1987 unsigned int nr_pages;
1988 struct work_struct work;
1989 unsigned long flags;
1990 #define FLUSHING_CACHED_CHARGE (0)
1992 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
1993 static DEFINE_MUTEX(percpu_charge_mutex);
1996 * Try to consume stocked charge on this cpu. If success, one page is consumed
1997 * from local stock and true is returned. If the stock is 0 or charges from a
1998 * cgroup which is not current target, returns false. This stock will be
2001 static bool consume_stock(struct mem_cgroup *memcg)
2003 struct memcg_stock_pcp *stock;
2006 stock = &get_cpu_var(memcg_stock);
2007 if (memcg == stock->cached && stock->nr_pages)
2009 else /* need to call res_counter_charge */
2011 put_cpu_var(memcg_stock);
2016 * Returns stocks cached in percpu to res_counter and reset cached information.
2018 static void drain_stock(struct memcg_stock_pcp *stock)
2020 struct mem_cgroup *old = stock->cached;
2022 if (stock->nr_pages) {
2023 unsigned long bytes = stock->nr_pages * PAGE_SIZE;
2025 res_counter_uncharge(&old->res, bytes);
2026 if (do_swap_account)
2027 res_counter_uncharge(&old->memsw, bytes);
2028 stock->nr_pages = 0;
2030 stock->cached = NULL;
2034 * This must be called under preempt disabled or must be called by
2035 * a thread which is pinned to local cpu.
2037 static void drain_local_stock(struct work_struct *dummy)
2039 struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
2041 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2045 * Cache charges(val) which is from res_counter, to local per_cpu area.
2046 * This will be consumed by consume_stock() function, later.
2048 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2050 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
2052 if (stock->cached != memcg) { /* reset if necessary */
2054 stock->cached = memcg;
2056 stock->nr_pages += nr_pages;
2057 put_cpu_var(memcg_stock);
2061 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2062 * of the hierarchy under it. sync flag says whether we should block
2063 * until the work is done.
2065 static void drain_all_stock(struct mem_cgroup *root_memcg, bool sync)
2069 /* Notify other cpus that system-wide "drain" is running */
2072 for_each_online_cpu(cpu) {
2073 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2074 struct mem_cgroup *memcg;
2076 memcg = stock->cached;
2077 if (!memcg || !stock->nr_pages)
2079 if (!mem_cgroup_same_or_subtree(root_memcg, memcg))
2081 if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2083 drain_local_stock(&stock->work);
2085 schedule_work_on(cpu, &stock->work);
2093 for_each_online_cpu(cpu) {
2094 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2095 if (test_bit(FLUSHING_CACHED_CHARGE, &stock->flags))
2096 flush_work(&stock->work);
2103 * Tries to drain stocked charges in other cpus. This function is asynchronous
2104 * and just put a work per cpu for draining localy on each cpu. Caller can
2105 * expects some charges will be back to res_counter later but cannot wait for
2108 static void drain_all_stock_async(struct mem_cgroup *root_memcg)
2111 * If someone calls draining, avoid adding more kworker runs.
2113 if (!mutex_trylock(&percpu_charge_mutex))
2115 drain_all_stock(root_memcg, false);
2116 mutex_unlock(&percpu_charge_mutex);
2119 /* This is a synchronous drain interface. */
2120 static void drain_all_stock_sync(struct mem_cgroup *root_memcg)
2122 /* called when force_empty is called */
2123 mutex_lock(&percpu_charge_mutex);
2124 drain_all_stock(root_memcg, true);
2125 mutex_unlock(&percpu_charge_mutex);
2129 * This function drains percpu counter value from DEAD cpu and
2130 * move it to local cpu. Note that this function can be preempted.
2132 static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *memcg, int cpu)
2136 spin_lock(&memcg->pcp_counter_lock);
2137 for (i = 0; i < MEM_CGROUP_STAT_DATA; i++) {
2138 long x = per_cpu(memcg->stat->count[i], cpu);
2140 per_cpu(memcg->stat->count[i], cpu) = 0;
2141 memcg->nocpu_base.count[i] += x;
2143 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
2144 unsigned long x = per_cpu(memcg->stat->events[i], cpu);
2146 per_cpu(memcg->stat->events[i], cpu) = 0;
2147 memcg->nocpu_base.events[i] += x;
2149 /* need to clear ON_MOVE value, works as a kind of lock. */
2150 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) = 0;
2151 spin_unlock(&memcg->pcp_counter_lock);
2154 static void synchronize_mem_cgroup_on_move(struct mem_cgroup *memcg, int cpu)
2156 int idx = MEM_CGROUP_ON_MOVE;
2158 spin_lock(&memcg->pcp_counter_lock);
2159 per_cpu(memcg->stat->count[idx], cpu) = memcg->nocpu_base.count[idx];
2160 spin_unlock(&memcg->pcp_counter_lock);
2163 static int __cpuinit memcg_cpu_hotplug_callback(struct notifier_block *nb,
2164 unsigned long action,
2167 int cpu = (unsigned long)hcpu;
2168 struct memcg_stock_pcp *stock;
2169 struct mem_cgroup *iter;
2171 if ((action == CPU_ONLINE)) {
2172 for_each_mem_cgroup_all(iter)
2173 synchronize_mem_cgroup_on_move(iter, cpu);
2177 if ((action != CPU_DEAD) || action != CPU_DEAD_FROZEN)
2180 for_each_mem_cgroup_all(iter)
2181 mem_cgroup_drain_pcp_counter(iter, cpu);
2183 stock = &per_cpu(memcg_stock, cpu);
2189 /* See __mem_cgroup_try_charge() for details */
2191 CHARGE_OK, /* success */
2192 CHARGE_RETRY, /* need to retry but retry is not bad */
2193 CHARGE_NOMEM, /* we can't do more. return -ENOMEM */
2194 CHARGE_WOULDBLOCK, /* GFP_WAIT wasn't set and no enough res. */
2195 CHARGE_OOM_DIE, /* the current is killed because of OOM */
2198 static int mem_cgroup_do_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2199 unsigned int nr_pages, bool oom_check)
2201 unsigned long csize = nr_pages * PAGE_SIZE;
2202 struct mem_cgroup *mem_over_limit;
2203 struct res_counter *fail_res;
2204 unsigned long flags = 0;
2207 ret = res_counter_charge(&memcg->res, csize, &fail_res);
2210 if (!do_swap_account)
2212 ret = res_counter_charge(&memcg->memsw, csize, &fail_res);
2216 res_counter_uncharge(&memcg->res, csize);
2217 mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw);
2218 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
2220 mem_over_limit = mem_cgroup_from_res_counter(fail_res, res);
2222 * nr_pages can be either a huge page (HPAGE_PMD_NR), a batch
2223 * of regular pages (CHARGE_BATCH), or a single regular page (1).
2225 * Never reclaim on behalf of optional batching, retry with a
2226 * single page instead.
2228 if (nr_pages == CHARGE_BATCH)
2229 return CHARGE_RETRY;
2231 if (!(gfp_mask & __GFP_WAIT))
2232 return CHARGE_WOULDBLOCK;
2234 ret = mem_cgroup_hierarchical_reclaim(mem_over_limit, NULL,
2235 gfp_mask, flags, NULL);
2236 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2237 return CHARGE_RETRY;
2239 * Even though the limit is exceeded at this point, reclaim
2240 * may have been able to free some pages. Retry the charge
2241 * before killing the task.
2243 * Only for regular pages, though: huge pages are rather
2244 * unlikely to succeed so close to the limit, and we fall back
2245 * to regular pages anyway in case of failure.
2247 if (nr_pages == 1 && ret)
2248 return CHARGE_RETRY;
2251 * At task move, charge accounts can be doubly counted. So, it's
2252 * better to wait until the end of task_move if something is going on.
2254 if (mem_cgroup_wait_acct_move(mem_over_limit))
2255 return CHARGE_RETRY;
2257 /* If we don't need to call oom-killer at el, return immediately */
2259 return CHARGE_NOMEM;
2261 if (!mem_cgroup_handle_oom(mem_over_limit, gfp_mask))
2262 return CHARGE_OOM_DIE;
2264 return CHARGE_RETRY;
2268 * Unlike exported interface, "oom" parameter is added. if oom==true,
2269 * oom-killer can be invoked.
2271 static int __mem_cgroup_try_charge(struct mm_struct *mm,
2273 unsigned int nr_pages,
2274 struct mem_cgroup **ptr,
2277 unsigned int batch = max(CHARGE_BATCH, nr_pages);
2278 int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2279 struct mem_cgroup *memcg = NULL;
2283 * Unlike gloval-vm's OOM-kill, we're not in memory shortage
2284 * in system level. So, allow to go ahead dying process in addition to
2287 if (unlikely(test_thread_flag(TIF_MEMDIE)
2288 || fatal_signal_pending(current)))
2292 * We always charge the cgroup the mm_struct belongs to.
2293 * The mm_struct's mem_cgroup changes on task migration if the
2294 * thread group leader migrates. It's possible that mm is not
2295 * set, if so charge the init_mm (happens for pagecache usage).
2300 if (*ptr) { /* css should be a valid one */
2302 VM_BUG_ON(css_is_removed(&memcg->css));
2303 if (mem_cgroup_is_root(memcg))
2305 if (nr_pages == 1 && consume_stock(memcg))
2307 css_get(&memcg->css);
2309 struct task_struct *p;
2312 p = rcu_dereference(mm->owner);
2314 * Because we don't have task_lock(), "p" can exit.
2315 * In that case, "memcg" can point to root or p can be NULL with
2316 * race with swapoff. Then, we have small risk of mis-accouning.
2317 * But such kind of mis-account by race always happens because
2318 * we don't have cgroup_mutex(). It's overkill and we allo that
2320 * (*) swapoff at el will charge against mm-struct not against
2321 * task-struct. So, mm->owner can be NULL.
2323 memcg = mem_cgroup_from_task(p);
2324 if (!memcg || mem_cgroup_is_root(memcg)) {
2328 if (nr_pages == 1 && consume_stock(memcg)) {
2330 * It seems dagerous to access memcg without css_get().
2331 * But considering how consume_stok works, it's not
2332 * necessary. If consume_stock success, some charges
2333 * from this memcg are cached on this cpu. So, we
2334 * don't need to call css_get()/css_tryget() before
2335 * calling consume_stock().
2340 /* after here, we may be blocked. we need to get refcnt */
2341 if (!css_tryget(&memcg->css)) {
2351 /* If killed, bypass charge */
2352 if (fatal_signal_pending(current)) {
2353 css_put(&memcg->css);
2358 if (oom && !nr_oom_retries) {
2360 nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2363 ret = mem_cgroup_do_charge(memcg, gfp_mask, batch, oom_check);
2367 case CHARGE_RETRY: /* not in OOM situation but retry */
2369 css_put(&memcg->css);
2372 case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
2373 css_put(&memcg->css);
2375 case CHARGE_NOMEM: /* OOM routine works */
2377 css_put(&memcg->css);
2380 /* If oom, we never return -ENOMEM */
2383 case CHARGE_OOM_DIE: /* Killed by OOM Killer */
2384 css_put(&memcg->css);
2387 } while (ret != CHARGE_OK);
2389 if (batch > nr_pages)
2390 refill_stock(memcg, batch - nr_pages);
2391 css_put(&memcg->css);
2404 * Somemtimes we have to undo a charge we got by try_charge().
2405 * This function is for that and do uncharge, put css's refcnt.
2406 * gotten by try_charge().
2408 static void __mem_cgroup_cancel_charge(struct mem_cgroup *memcg,
2409 unsigned int nr_pages)
2411 if (!mem_cgroup_is_root(memcg)) {
2412 unsigned long bytes = nr_pages * PAGE_SIZE;
2414 res_counter_uncharge(&memcg->res, bytes);
2415 if (do_swap_account)
2416 res_counter_uncharge(&memcg->memsw, bytes);
2421 * A helper function to get mem_cgroup from ID. must be called under
2422 * rcu_read_lock(). The caller must check css_is_removed() or some if
2423 * it's concern. (dropping refcnt from swap can be called against removed
2426 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
2428 struct cgroup_subsys_state *css;
2430 /* ID 0 is unused ID */
2433 css = css_lookup(&mem_cgroup_subsys, id);
2436 return container_of(css, struct mem_cgroup, css);
2439 struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
2441 struct mem_cgroup *memcg = NULL;
2442 struct page_cgroup *pc;
2446 VM_BUG_ON(!PageLocked(page));
2448 pc = lookup_page_cgroup(page);
2449 lock_page_cgroup(pc);
2450 if (PageCgroupUsed(pc)) {
2451 memcg = pc->mem_cgroup;
2452 if (memcg && !css_tryget(&memcg->css))
2454 } else if (PageSwapCache(page)) {
2455 ent.val = page_private(page);
2456 id = lookup_swap_cgroup(ent);
2458 memcg = mem_cgroup_lookup(id);
2459 if (memcg && !css_tryget(&memcg->css))
2463 unlock_page_cgroup(pc);
2467 static void __mem_cgroup_commit_charge(struct mem_cgroup *memcg,
2469 unsigned int nr_pages,
2470 struct page_cgroup *pc,
2471 enum charge_type ctype)
2473 lock_page_cgroup(pc);
2474 if (unlikely(PageCgroupUsed(pc))) {
2475 unlock_page_cgroup(pc);
2476 __mem_cgroup_cancel_charge(memcg, nr_pages);
2480 * we don't need page_cgroup_lock about tail pages, becase they are not
2481 * accessed by any other context at this point.
2483 pc->mem_cgroup = memcg;
2485 * We access a page_cgroup asynchronously without lock_page_cgroup().
2486 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
2487 * is accessed after testing USED bit. To make pc->mem_cgroup visible
2488 * before USED bit, we need memory barrier here.
2489 * See mem_cgroup_add_lru_list(), etc.
2493 case MEM_CGROUP_CHARGE_TYPE_CACHE:
2494 case MEM_CGROUP_CHARGE_TYPE_SHMEM:
2495 SetPageCgroupCache(pc);
2496 SetPageCgroupUsed(pc);
2498 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
2499 ClearPageCgroupCache(pc);
2500 SetPageCgroupUsed(pc);
2506 mem_cgroup_charge_statistics(memcg, PageCgroupCache(pc), nr_pages);
2507 unlock_page_cgroup(pc);
2509 * "charge_statistics" updated event counter. Then, check it.
2510 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
2511 * if they exceeds softlimit.
2513 memcg_check_events(memcg, page);
2516 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2518 #define PCGF_NOCOPY_AT_SPLIT ((1 << PCG_LOCK) | (1 << PCG_MOVE_LOCK) |\
2519 (1 << PCG_ACCT_LRU) | (1 << PCG_MIGRATION))
2521 * Because tail pages are not marked as "used", set it. We're under
2522 * zone->lru_lock, 'splitting on pmd' and compund_lock.
2524 void mem_cgroup_split_huge_fixup(struct page *head, struct page *tail)
2526 struct page_cgroup *head_pc = lookup_page_cgroup(head);
2527 struct page_cgroup *tail_pc = lookup_page_cgroup(tail);
2528 unsigned long flags;
2530 if (mem_cgroup_disabled())
2533 * We have no races with charge/uncharge but will have races with
2534 * page state accounting.
2536 move_lock_page_cgroup(head_pc, &flags);
2538 tail_pc->mem_cgroup = head_pc->mem_cgroup;
2539 smp_wmb(); /* see __commit_charge() */
2540 if (PageCgroupAcctLRU(head_pc)) {
2542 struct mem_cgroup_per_zone *mz;
2545 * LRU flags cannot be copied because we need to add tail
2546 *.page to LRU by generic call and our hook will be called.
2547 * We hold lru_lock, then, reduce counter directly.
2549 lru = page_lru(head);
2550 mz = page_cgroup_zoneinfo(head_pc->mem_cgroup, head);
2551 MEM_CGROUP_ZSTAT(mz, lru) -= 1;
2553 tail_pc->flags = head_pc->flags & ~PCGF_NOCOPY_AT_SPLIT;
2554 move_unlock_page_cgroup(head_pc, &flags);
2559 * mem_cgroup_move_account - move account of the page
2561 * @nr_pages: number of regular pages (>1 for huge pages)
2562 * @pc: page_cgroup of the page.
2563 * @from: mem_cgroup which the page is moved from.
2564 * @to: mem_cgroup which the page is moved to. @from != @to.
2565 * @uncharge: whether we should call uncharge and css_put against @from.
2567 * The caller must confirm following.
2568 * - page is not on LRU (isolate_page() is useful.)
2569 * - compound_lock is held when nr_pages > 1
2571 * This function doesn't do "charge" nor css_get to new cgroup. It should be
2572 * done by a caller(__mem_cgroup_try_charge would be useful). If @uncharge is
2573 * true, this function does "uncharge" from old cgroup, but it doesn't if
2574 * @uncharge is false, so a caller should do "uncharge".
2576 static int mem_cgroup_move_account(struct page *page,
2577 unsigned int nr_pages,
2578 struct page_cgroup *pc,
2579 struct mem_cgroup *from,
2580 struct mem_cgroup *to,
2583 unsigned long flags;
2586 VM_BUG_ON(from == to);
2587 VM_BUG_ON(PageLRU(page));
2589 * The page is isolated from LRU. So, collapse function
2590 * will not handle this page. But page splitting can happen.
2591 * Do this check under compound_page_lock(). The caller should
2595 if (nr_pages > 1 && !PageTransHuge(page))
2598 lock_page_cgroup(pc);
2601 if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
2604 move_lock_page_cgroup(pc, &flags);
2606 if (PageCgroupFileMapped(pc)) {
2607 /* Update mapped_file data for mem_cgroup */
2609 __this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2610 __this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2613 mem_cgroup_charge_statistics(from, PageCgroupCache(pc), -nr_pages);
2615 /* This is not "cancel", but cancel_charge does all we need. */
2616 __mem_cgroup_cancel_charge(from, nr_pages);
2618 /* caller should have done css_get */
2619 pc->mem_cgroup = to;
2620 mem_cgroup_charge_statistics(to, PageCgroupCache(pc), nr_pages);
2622 * We charges against "to" which may not have any tasks. Then, "to"
2623 * can be under rmdir(). But in current implementation, caller of
2624 * this function is just force_empty() and move charge, so it's
2625 * guaranteed that "to" is never removed. So, we don't check rmdir
2628 move_unlock_page_cgroup(pc, &flags);
2631 unlock_page_cgroup(pc);
2635 memcg_check_events(to, page);
2636 memcg_check_events(from, page);
2642 * move charges to its parent.
2645 static int mem_cgroup_move_parent(struct page *page,
2646 struct page_cgroup *pc,
2647 struct mem_cgroup *child,
2650 struct cgroup *cg = child->css.cgroup;
2651 struct cgroup *pcg = cg->parent;
2652 struct mem_cgroup *parent;
2653 unsigned int nr_pages;
2654 unsigned long uninitialized_var(flags);
2662 if (!get_page_unless_zero(page))
2664 if (isolate_lru_page(page))
2667 nr_pages = hpage_nr_pages(page);
2669 parent = mem_cgroup_from_cont(pcg);
2670 ret = __mem_cgroup_try_charge(NULL, gfp_mask, nr_pages, &parent, false);
2675 flags = compound_lock_irqsave(page);
2677 ret = mem_cgroup_move_account(page, nr_pages, pc, child, parent, true);
2679 __mem_cgroup_cancel_charge(parent, nr_pages);
2682 compound_unlock_irqrestore(page, flags);
2684 putback_lru_page(page);
2692 * Charge the memory controller for page usage.
2694 * 0 if the charge was successful
2695 * < 0 if the cgroup is over its limit
2697 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
2698 gfp_t gfp_mask, enum charge_type ctype)
2700 struct mem_cgroup *memcg = NULL;
2701 unsigned int nr_pages = 1;
2702 struct page_cgroup *pc;
2706 if (PageTransHuge(page)) {
2707 nr_pages <<= compound_order(page);
2708 VM_BUG_ON(!PageTransHuge(page));
2710 * Never OOM-kill a process for a huge page. The
2711 * fault handler will fall back to regular pages.
2716 pc = lookup_page_cgroup(page);
2717 BUG_ON(!pc); /* XXX: remove this and move pc lookup into commit */
2719 ret = __mem_cgroup_try_charge(mm, gfp_mask, nr_pages, &memcg, oom);
2723 __mem_cgroup_commit_charge(memcg, page, nr_pages, pc, ctype);
2727 int mem_cgroup_newpage_charge(struct page *page,
2728 struct mm_struct *mm, gfp_t gfp_mask)
2730 if (mem_cgroup_disabled())
2733 * If already mapped, we don't have to account.
2734 * If page cache, page->mapping has address_space.
2735 * But page->mapping may have out-of-use anon_vma pointer,
2736 * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
2739 if (page_mapped(page) || (page->mapping && !PageAnon(page)))
2743 return mem_cgroup_charge_common(page, mm, gfp_mask,
2744 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2748 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2749 enum charge_type ctype);
2752 __mem_cgroup_commit_charge_lrucare(struct page *page, struct mem_cgroup *memcg,
2753 enum charge_type ctype)
2755 struct page_cgroup *pc = lookup_page_cgroup(page);
2757 * In some case, SwapCache, FUSE(splice_buf->radixtree), the page
2758 * is already on LRU. It means the page may on some other page_cgroup's
2759 * LRU. Take care of it.
2761 mem_cgroup_lru_del_before_commit(page);
2762 __mem_cgroup_commit_charge(memcg, page, 1, pc, ctype);
2763 mem_cgroup_lru_add_after_commit(page);
2767 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
2770 struct mem_cgroup *memcg = NULL;
2773 if (mem_cgroup_disabled())
2775 if (PageCompound(page))
2781 if (page_is_file_cache(page)) {
2782 ret = __mem_cgroup_try_charge(mm, gfp_mask, 1, &memcg, true);
2787 * FUSE reuses pages without going through the final
2788 * put that would remove them from the LRU list, make
2789 * sure that they get relinked properly.
2791 __mem_cgroup_commit_charge_lrucare(page, memcg,
2792 MEM_CGROUP_CHARGE_TYPE_CACHE);
2796 if (PageSwapCache(page)) {
2797 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &memcg);
2799 __mem_cgroup_commit_charge_swapin(page, memcg,
2800 MEM_CGROUP_CHARGE_TYPE_SHMEM);
2802 ret = mem_cgroup_charge_common(page, mm, gfp_mask,
2803 MEM_CGROUP_CHARGE_TYPE_SHMEM);
2809 * While swap-in, try_charge -> commit or cancel, the page is locked.
2810 * And when try_charge() successfully returns, one refcnt to memcg without
2811 * struct page_cgroup is acquired. This refcnt will be consumed by
2812 * "commit()" or removed by "cancel()"
2814 int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
2816 gfp_t mask, struct mem_cgroup **ptr)
2818 struct mem_cgroup *memcg;
2823 if (mem_cgroup_disabled())
2826 if (!do_swap_account)
2829 * A racing thread's fault, or swapoff, may have already updated
2830 * the pte, and even removed page from swap cache: in those cases
2831 * do_swap_page()'s pte_same() test will fail; but there's also a
2832 * KSM case which does need to charge the page.
2834 if (!PageSwapCache(page))
2836 memcg = try_get_mem_cgroup_from_page(page);
2840 ret = __mem_cgroup_try_charge(NULL, mask, 1, ptr, true);
2841 css_put(&memcg->css);
2846 return __mem_cgroup_try_charge(mm, mask, 1, ptr, true);
2850 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2851 enum charge_type ctype)
2853 if (mem_cgroup_disabled())
2857 cgroup_exclude_rmdir(&ptr->css);
2859 __mem_cgroup_commit_charge_lrucare(page, ptr, ctype);
2861 * Now swap is on-memory. This means this page may be
2862 * counted both as mem and swap....double count.
2863 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
2864 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
2865 * may call delete_from_swap_cache() before reach here.
2867 if (do_swap_account && PageSwapCache(page)) {
2868 swp_entry_t ent = {.val = page_private(page)};
2870 struct mem_cgroup *memcg;
2872 id = swap_cgroup_record(ent, 0);
2874 memcg = mem_cgroup_lookup(id);
2877 * This recorded memcg can be obsolete one. So, avoid
2878 * calling css_tryget
2880 if (!mem_cgroup_is_root(memcg))
2881 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
2882 mem_cgroup_swap_statistics(memcg, false);
2883 mem_cgroup_put(memcg);
2888 * At swapin, we may charge account against cgroup which has no tasks.
2889 * So, rmdir()->pre_destroy() can be called while we do this charge.
2890 * In that case, we need to call pre_destroy() again. check it here.
2892 cgroup_release_and_wakeup_rmdir(&ptr->css);
2895 void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
2897 __mem_cgroup_commit_charge_swapin(page, ptr,
2898 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2901 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *memcg)
2903 if (mem_cgroup_disabled())
2907 __mem_cgroup_cancel_charge(memcg, 1);
2910 static void mem_cgroup_do_uncharge(struct mem_cgroup *memcg,
2911 unsigned int nr_pages,
2912 const enum charge_type ctype)
2914 struct memcg_batch_info *batch = NULL;
2915 bool uncharge_memsw = true;
2917 /* If swapout, usage of swap doesn't decrease */
2918 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2919 uncharge_memsw = false;
2921 batch = ¤t->memcg_batch;
2923 * In usual, we do css_get() when we remember memcg pointer.
2924 * But in this case, we keep res->usage until end of a series of
2925 * uncharges. Then, it's ok to ignore memcg's refcnt.
2928 batch->memcg = memcg;
2930 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
2931 * In those cases, all pages freed continuously can be expected to be in
2932 * the same cgroup and we have chance to coalesce uncharges.
2933 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
2934 * because we want to do uncharge as soon as possible.
2937 if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
2938 goto direct_uncharge;
2941 goto direct_uncharge;
2944 * In typical case, batch->memcg == mem. This means we can
2945 * merge a series of uncharges to an uncharge of res_counter.
2946 * If not, we uncharge res_counter ony by one.
2948 if (batch->memcg != memcg)
2949 goto direct_uncharge;
2950 /* remember freed charge and uncharge it later */
2953 batch->memsw_nr_pages++;
2956 res_counter_uncharge(&memcg->res, nr_pages * PAGE_SIZE);
2958 res_counter_uncharge(&memcg->memsw, nr_pages * PAGE_SIZE);
2959 if (unlikely(batch->memcg != memcg))
2960 memcg_oom_recover(memcg);
2965 * uncharge if !page_mapped(page)
2967 static struct mem_cgroup *
2968 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
2970 struct mem_cgroup *memcg = NULL;
2971 unsigned int nr_pages = 1;
2972 struct page_cgroup *pc;
2974 if (mem_cgroup_disabled())
2977 if (PageSwapCache(page))
2980 if (PageTransHuge(page)) {
2981 nr_pages <<= compound_order(page);
2982 VM_BUG_ON(!PageTransHuge(page));
2985 * Check if our page_cgroup is valid
2987 pc = lookup_page_cgroup(page);
2988 if (unlikely(!pc || !PageCgroupUsed(pc)))
2991 lock_page_cgroup(pc);
2993 memcg = pc->mem_cgroup;
2995 if (!PageCgroupUsed(pc))
2999 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
3000 case MEM_CGROUP_CHARGE_TYPE_DROP:
3001 /* See mem_cgroup_prepare_migration() */
3002 if (page_mapped(page) || PageCgroupMigration(pc))
3005 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
3006 if (!PageAnon(page)) { /* Shared memory */
3007 if (page->mapping && !page_is_file_cache(page))
3009 } else if (page_mapped(page)) /* Anon */
3016 mem_cgroup_charge_statistics(memcg, PageCgroupCache(pc), -nr_pages);
3018 ClearPageCgroupUsed(pc);
3020 * pc->mem_cgroup is not cleared here. It will be accessed when it's
3021 * freed from LRU. This is safe because uncharged page is expected not
3022 * to be reused (freed soon). Exception is SwapCache, it's handled by
3023 * special functions.
3026 unlock_page_cgroup(pc);
3028 * even after unlock, we have memcg->res.usage here and this memcg
3029 * will never be freed.
3031 memcg_check_events(memcg, page);
3032 if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
3033 mem_cgroup_swap_statistics(memcg, true);
3034 mem_cgroup_get(memcg);
3036 if (!mem_cgroup_is_root(memcg))
3037 mem_cgroup_do_uncharge(memcg, nr_pages, ctype);
3042 unlock_page_cgroup(pc);
3046 void mem_cgroup_uncharge_page(struct page *page)
3049 if (page_mapped(page))
3051 if (page->mapping && !PageAnon(page))
3053 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
3056 void mem_cgroup_uncharge_cache_page(struct page *page)
3058 VM_BUG_ON(page_mapped(page));
3059 VM_BUG_ON(page->mapping);
3060 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
3064 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
3065 * In that cases, pages are freed continuously and we can expect pages
3066 * are in the same memcg. All these calls itself limits the number of
3067 * pages freed at once, then uncharge_start/end() is called properly.
3068 * This may be called prural(2) times in a context,
3071 void mem_cgroup_uncharge_start(void)
3073 current->memcg_batch.do_batch++;
3074 /* We can do nest. */
3075 if (current->memcg_batch.do_batch == 1) {
3076 current->memcg_batch.memcg = NULL;
3077 current->memcg_batch.nr_pages = 0;
3078 current->memcg_batch.memsw_nr_pages = 0;
3082 void mem_cgroup_uncharge_end(void)
3084 struct memcg_batch_info *batch = ¤t->memcg_batch;
3086 if (!batch->do_batch)
3090 if (batch->do_batch) /* If stacked, do nothing. */
3096 * This "batch->memcg" is valid without any css_get/put etc...
3097 * bacause we hide charges behind us.
3099 if (batch->nr_pages)
3100 res_counter_uncharge(&batch->memcg->res,
3101 batch->nr_pages * PAGE_SIZE);
3102 if (batch->memsw_nr_pages)
3103 res_counter_uncharge(&batch->memcg->memsw,
3104 batch->memsw_nr_pages * PAGE_SIZE);
3105 memcg_oom_recover(batch->memcg);
3106 /* forget this pointer (for sanity check) */
3107 batch->memcg = NULL;
3112 * called after __delete_from_swap_cache() and drop "page" account.
3113 * memcg information is recorded to swap_cgroup of "ent"
3116 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
3118 struct mem_cgroup *memcg;
3119 int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
3121 if (!swapout) /* this was a swap cache but the swap is unused ! */
3122 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
3124 memcg = __mem_cgroup_uncharge_common(page, ctype);
3127 * record memcg information, if swapout && memcg != NULL,
3128 * mem_cgroup_get() was called in uncharge().
3130 if (do_swap_account && swapout && memcg)
3131 swap_cgroup_record(ent, css_id(&memcg->css));
3135 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3137 * called from swap_entry_free(). remove record in swap_cgroup and
3138 * uncharge "memsw" account.
3140 void mem_cgroup_uncharge_swap(swp_entry_t ent)
3142 struct mem_cgroup *memcg;
3145 if (!do_swap_account)
3148 id = swap_cgroup_record(ent, 0);
3150 memcg = mem_cgroup_lookup(id);
3153 * We uncharge this because swap is freed.
3154 * This memcg can be obsolete one. We avoid calling css_tryget
3156 if (!mem_cgroup_is_root(memcg))
3157 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
3158 mem_cgroup_swap_statistics(memcg, false);
3159 mem_cgroup_put(memcg);
3165 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3166 * @entry: swap entry to be moved
3167 * @from: mem_cgroup which the entry is moved from
3168 * @to: mem_cgroup which the entry is moved to
3169 * @need_fixup: whether we should fixup res_counters and refcounts.
3171 * It succeeds only when the swap_cgroup's record for this entry is the same
3172 * as the mem_cgroup's id of @from.
3174 * Returns 0 on success, -EINVAL on failure.
3176 * The caller must have charged to @to, IOW, called res_counter_charge() about
3177 * both res and memsw, and called css_get().
3179 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3180 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
3182 unsigned short old_id, new_id;
3184 old_id = css_id(&from->css);
3185 new_id = css_id(&to->css);
3187 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3188 mem_cgroup_swap_statistics(from, false);
3189 mem_cgroup_swap_statistics(to, true);
3191 * This function is only called from task migration context now.
3192 * It postpones res_counter and refcount handling till the end
3193 * of task migration(mem_cgroup_clear_mc()) for performance
3194 * improvement. But we cannot postpone mem_cgroup_get(to)
3195 * because if the process that has been moved to @to does
3196 * swap-in, the refcount of @to might be decreased to 0.
3200 if (!mem_cgroup_is_root(from))
3201 res_counter_uncharge(&from->memsw, PAGE_SIZE);
3202 mem_cgroup_put(from);
3204 * we charged both to->res and to->memsw, so we should
3207 if (!mem_cgroup_is_root(to))
3208 res_counter_uncharge(&to->res, PAGE_SIZE);
3215 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3216 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
3223 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
3226 int mem_cgroup_prepare_migration(struct page *page,
3227 struct page *newpage, struct mem_cgroup **ptr, gfp_t gfp_mask)
3229 struct mem_cgroup *memcg = NULL;
3230 struct page_cgroup *pc;
3231 enum charge_type ctype;
3236 VM_BUG_ON(PageTransHuge(page));
3237 if (mem_cgroup_disabled())
3240 pc = lookup_page_cgroup(page);
3241 lock_page_cgroup(pc);
3242 if (PageCgroupUsed(pc)) {
3243 memcg = pc->mem_cgroup;
3244 css_get(&memcg->css);
3246 * At migrating an anonymous page, its mapcount goes down
3247 * to 0 and uncharge() will be called. But, even if it's fully
3248 * unmapped, migration may fail and this page has to be
3249 * charged again. We set MIGRATION flag here and delay uncharge
3250 * until end_migration() is called
3252 * Corner Case Thinking
3254 * When the old page was mapped as Anon and it's unmap-and-freed
3255 * while migration was ongoing.
3256 * If unmap finds the old page, uncharge() of it will be delayed
3257 * until end_migration(). If unmap finds a new page, it's
3258 * uncharged when it make mapcount to be 1->0. If unmap code
3259 * finds swap_migration_entry, the new page will not be mapped
3260 * and end_migration() will find it(mapcount==0).
3263 * When the old page was mapped but migraion fails, the kernel
3264 * remaps it. A charge for it is kept by MIGRATION flag even
3265 * if mapcount goes down to 0. We can do remap successfully
3266 * without charging it again.
3269 * The "old" page is under lock_page() until the end of
3270 * migration, so, the old page itself will not be swapped-out.
3271 * If the new page is swapped out before end_migraton, our
3272 * hook to usual swap-out path will catch the event.
3275 SetPageCgroupMigration(pc);
3277 unlock_page_cgroup(pc);
3279 * If the page is not charged at this point,
3286 ret = __mem_cgroup_try_charge(NULL, gfp_mask, 1, ptr, false);
3287 css_put(&memcg->css);/* drop extra refcnt */
3288 if (ret || *ptr == NULL) {
3289 if (PageAnon(page)) {
3290 lock_page_cgroup(pc);
3291 ClearPageCgroupMigration(pc);
3292 unlock_page_cgroup(pc);
3294 * The old page may be fully unmapped while we kept it.
3296 mem_cgroup_uncharge_page(page);
3301 * We charge new page before it's used/mapped. So, even if unlock_page()
3302 * is called before end_migration, we can catch all events on this new
3303 * page. In the case new page is migrated but not remapped, new page's
3304 * mapcount will be finally 0 and we call uncharge in end_migration().
3306 pc = lookup_page_cgroup(newpage);
3308 ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
3309 else if (page_is_file_cache(page))
3310 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
3312 ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
3313 __mem_cgroup_commit_charge(memcg, page, 1, pc, ctype);
3317 /* remove redundant charge if migration failed*/
3318 void mem_cgroup_end_migration(struct mem_cgroup *memcg,
3319 struct page *oldpage, struct page *newpage, bool migration_ok)
3321 struct page *used, *unused;
3322 struct page_cgroup *pc;
3326 /* blocks rmdir() */
3327 cgroup_exclude_rmdir(&memcg->css);
3328 if (!migration_ok) {
3336 * We disallowed uncharge of pages under migration because mapcount
3337 * of the page goes down to zero, temporarly.
3338 * Clear the flag and check the page should be charged.
3340 pc = lookup_page_cgroup(oldpage);
3341 lock_page_cgroup(pc);
3342 ClearPageCgroupMigration(pc);
3343 unlock_page_cgroup(pc);
3345 __mem_cgroup_uncharge_common(unused, MEM_CGROUP_CHARGE_TYPE_FORCE);
3348 * If a page is a file cache, radix-tree replacement is very atomic
3349 * and we can skip this check. When it was an Anon page, its mapcount
3350 * goes down to 0. But because we added MIGRATION flage, it's not
3351 * uncharged yet. There are several case but page->mapcount check
3352 * and USED bit check in mem_cgroup_uncharge_page() will do enough
3353 * check. (see prepare_charge() also)
3356 mem_cgroup_uncharge_page(used);
3358 * At migration, we may charge account against cgroup which has no
3360 * So, rmdir()->pre_destroy() can be called while we do this charge.
3361 * In that case, we need to call pre_destroy() again. check it here.
3363 cgroup_release_and_wakeup_rmdir(&memcg->css);
3366 #ifdef CONFIG_DEBUG_VM
3367 static struct page_cgroup *lookup_page_cgroup_used(struct page *page)
3369 struct page_cgroup *pc;
3371 pc = lookup_page_cgroup(page);
3372 if (likely(pc) && PageCgroupUsed(pc))
3377 bool mem_cgroup_bad_page_check(struct page *page)
3379 if (mem_cgroup_disabled())
3382 return lookup_page_cgroup_used(page) != NULL;
3385 void mem_cgroup_print_bad_page(struct page *page)
3387 struct page_cgroup *pc;
3389 pc = lookup_page_cgroup_used(page);
3394 printk(KERN_ALERT "pc:%p pc->flags:%lx pc->mem_cgroup:%p",
3395 pc, pc->flags, pc->mem_cgroup);
3397 path = kmalloc(PATH_MAX, GFP_KERNEL);
3400 ret = cgroup_path(pc->mem_cgroup->css.cgroup,
3405 printk(KERN_CONT "(%s)\n",
3406 (ret < 0) ? "cannot get the path" : path);
3412 static DEFINE_MUTEX(set_limit_mutex);
3414 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
3415 unsigned long long val)
3418 u64 memswlimit, memlimit;
3420 int children = mem_cgroup_count_children(memcg);
3421 u64 curusage, oldusage;
3425 * For keeping hierarchical_reclaim simple, how long we should retry
3426 * is depends on callers. We set our retry-count to be function
3427 * of # of children which we should visit in this loop.
3429 retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
3431 oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
3434 while (retry_count) {
3435 if (signal_pending(current)) {
3440 * Rather than hide all in some function, I do this in
3441 * open coded manner. You see what this really does.
3442 * We have to guarantee memcg->res.limit < memcg->memsw.limit.
3444 mutex_lock(&set_limit_mutex);
3445 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3446 if (memswlimit < val) {
3448 mutex_unlock(&set_limit_mutex);
3452 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3456 ret = res_counter_set_limit(&memcg->res, val);
3458 if (memswlimit == val)
3459 memcg->memsw_is_minimum = true;
3461 memcg->memsw_is_minimum = false;
3463 mutex_unlock(&set_limit_mutex);
3468 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
3469 MEM_CGROUP_RECLAIM_SHRINK,
3471 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
3472 /* Usage is reduced ? */
3473 if (curusage >= oldusage)
3476 oldusage = curusage;
3478 if (!ret && enlarge)
3479 memcg_oom_recover(memcg);
3484 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
3485 unsigned long long val)
3488 u64 memlimit, memswlimit, oldusage, curusage;
3489 int children = mem_cgroup_count_children(memcg);
3493 /* see mem_cgroup_resize_res_limit */
3494 retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
3495 oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
3496 while (retry_count) {
3497 if (signal_pending(current)) {
3502 * Rather than hide all in some function, I do this in
3503 * open coded manner. You see what this really does.
3504 * We have to guarantee memcg->res.limit < memcg->memsw.limit.
3506 mutex_lock(&set_limit_mutex);
3507 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3508 if (memlimit > val) {
3510 mutex_unlock(&set_limit_mutex);
3513 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3514 if (memswlimit < val)
3516 ret = res_counter_set_limit(&memcg->memsw, val);
3518 if (memlimit == val)
3519 memcg->memsw_is_minimum = true;
3521 memcg->memsw_is_minimum = false;
3523 mutex_unlock(&set_limit_mutex);
3528 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
3529 MEM_CGROUP_RECLAIM_NOSWAP |
3530 MEM_CGROUP_RECLAIM_SHRINK,
3532 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
3533 /* Usage is reduced ? */
3534 if (curusage >= oldusage)
3537 oldusage = curusage;
3539 if (!ret && enlarge)
3540 memcg_oom_recover(memcg);
3544 unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
3546 unsigned long *total_scanned)
3548 unsigned long nr_reclaimed = 0;
3549 struct mem_cgroup_per_zone *mz, *next_mz = NULL;
3550 unsigned long reclaimed;
3552 struct mem_cgroup_tree_per_zone *mctz;
3553 unsigned long long excess;
3554 unsigned long nr_scanned;
3559 mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
3561 * This loop can run a while, specially if mem_cgroup's continuously
3562 * keep exceeding their soft limit and putting the system under
3569 mz = mem_cgroup_largest_soft_limit_node(mctz);
3574 reclaimed = mem_cgroup_hierarchical_reclaim(mz->mem, zone,
3576 MEM_CGROUP_RECLAIM_SOFT,
3578 nr_reclaimed += reclaimed;
3579 *total_scanned += nr_scanned;
3580 spin_lock(&mctz->lock);
3583 * If we failed to reclaim anything from this memory cgroup
3584 * it is time to move on to the next cgroup
3590 * Loop until we find yet another one.
3592 * By the time we get the soft_limit lock
3593 * again, someone might have aded the
3594 * group back on the RB tree. Iterate to
3595 * make sure we get a different mem.
3596 * mem_cgroup_largest_soft_limit_node returns
3597 * NULL if no other cgroup is present on
3601 __mem_cgroup_largest_soft_limit_node(mctz);
3603 css_put(&next_mz->mem->css);
3604 else /* next_mz == NULL or other memcg */
3608 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
3609 excess = res_counter_soft_limit_excess(&mz->mem->res);
3611 * One school of thought says that we should not add
3612 * back the node to the tree if reclaim returns 0.
3613 * But our reclaim could return 0, simply because due
3614 * to priority we are exposing a smaller subset of
3615 * memory to reclaim from. Consider this as a longer
3618 /* If excess == 0, no tree ops */
3619 __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
3620 spin_unlock(&mctz->lock);
3621 css_put(&mz->mem->css);
3624 * Could not reclaim anything and there are no more
3625 * mem cgroups to try or we seem to be looping without
3626 * reclaiming anything.
3628 if (!nr_reclaimed &&
3630 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3632 } while (!nr_reclaimed);
3634 css_put(&next_mz->mem->css);
3635 return nr_reclaimed;
3639 * This routine traverse page_cgroup in given list and drop them all.
3640 * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
3642 static int mem_cgroup_force_empty_list(struct mem_cgroup *memcg,
3643 int node, int zid, enum lru_list lru)
3646 struct mem_cgroup_per_zone *mz;
3647 struct page_cgroup *pc, *busy;
3648 unsigned long flags, loop;
3649 struct list_head *list;
3652 zone = &NODE_DATA(node)->node_zones[zid];
3653 mz = mem_cgroup_zoneinfo(memcg, node, zid);
3654 list = &mz->lists[lru];
3656 loop = MEM_CGROUP_ZSTAT(mz, lru);
3657 /* give some margin against EBUSY etc...*/
3664 spin_lock_irqsave(&zone->lru_lock, flags);
3665 if (list_empty(list)) {
3666 spin_unlock_irqrestore(&zone->lru_lock, flags);
3669 pc = list_entry(list->prev, struct page_cgroup, lru);
3671 list_move(&pc->lru, list);
3673 spin_unlock_irqrestore(&zone->lru_lock, flags);
3676 spin_unlock_irqrestore(&zone->lru_lock, flags);
3678 page = lookup_cgroup_page(pc);
3680 ret = mem_cgroup_move_parent(page, pc, memcg, GFP_KERNEL);
3684 if (ret == -EBUSY || ret == -EINVAL) {
3685 /* found lock contention or "pc" is obsolete. */
3692 if (!ret && !list_empty(list))
3698 * make mem_cgroup's charge to be 0 if there is no task.
3699 * This enables deleting this mem_cgroup.
3701 static int mem_cgroup_force_empty(struct mem_cgroup *memcg, bool free_all)
3704 int node, zid, shrink;
3705 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
3706 struct cgroup *cgrp = memcg->css.cgroup;
3708 css_get(&memcg->css);
3711 /* should free all ? */
3717 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
3720 if (signal_pending(current))
3722 /* This is for making all *used* pages to be on LRU. */
3723 lru_add_drain_all();
3724 drain_all_stock_sync(memcg);
3726 mem_cgroup_start_move(memcg);
3727 for_each_node_state(node, N_HIGH_MEMORY) {
3728 for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
3731 ret = mem_cgroup_force_empty_list(memcg,
3740 mem_cgroup_end_move(memcg);
3741 memcg_oom_recover(memcg);
3742 /* it seems parent cgroup doesn't have enough mem */
3746 /* "ret" should also be checked to ensure all lists are empty. */
3747 } while (memcg->res.usage > 0 || ret);
3749 css_put(&memcg->css);
3753 /* returns EBUSY if there is a task or if we come here twice. */
3754 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
3758 /* we call try-to-free pages for make this cgroup empty */
3759 lru_add_drain_all();
3760 /* try to free all pages in this cgroup */
3762 while (nr_retries && memcg->res.usage > 0) {
3765 if (signal_pending(current)) {
3769 progress = try_to_free_mem_cgroup_pages(memcg, GFP_KERNEL,
3773 /* maybe some writeback is necessary */
3774 congestion_wait(BLK_RW_ASYNC, HZ/10);
3779 /* try move_account...there may be some *locked* pages. */
3783 int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
3785 return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
3789 static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
3791 return mem_cgroup_from_cont(cont)->use_hierarchy;
3794 static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
3798 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3799 struct cgroup *parent = cont->parent;
3800 struct mem_cgroup *parent_memcg = NULL;
3803 parent_memcg = mem_cgroup_from_cont(parent);
3807 * If parent's use_hierarchy is set, we can't make any modifications
3808 * in the child subtrees. If it is unset, then the change can
3809 * occur, provided the current cgroup has no children.
3811 * For the root cgroup, parent_mem is NULL, we allow value to be
3812 * set if there are no children.
3814 if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
3815 (val == 1 || val == 0)) {
3816 if (list_empty(&cont->children))
3817 memcg->use_hierarchy = val;
3828 static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup *memcg,
3829 enum mem_cgroup_stat_index idx)
3831 struct mem_cgroup *iter;
3834 /* Per-cpu values can be negative, use a signed accumulator */
3835 for_each_mem_cgroup_tree(iter, memcg)
3836 val += mem_cgroup_read_stat(iter, idx);
3838 if (val < 0) /* race ? */
3843 static inline u64 mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3847 if (!mem_cgroup_is_root(memcg)) {
3849 return res_counter_read_u64(&memcg->res, RES_USAGE);
3851 return res_counter_read_u64(&memcg->memsw, RES_USAGE);
3854 val = mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_CACHE);
3855 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_RSS);
3858 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_SWAPOUT);
3860 return val << PAGE_SHIFT;
3863 static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
3865 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3869 type = MEMFILE_TYPE(cft->private);
3870 name = MEMFILE_ATTR(cft->private);
3873 if (name == RES_USAGE)
3874 val = mem_cgroup_usage(memcg, false);
3876 val = res_counter_read_u64(&memcg->res, name);
3879 if (name == RES_USAGE)
3880 val = mem_cgroup_usage(memcg, true);
3882 val = res_counter_read_u64(&memcg->memsw, name);
3891 * The user of this function is...
3894 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
3897 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3899 unsigned long long val;
3902 type = MEMFILE_TYPE(cft->private);
3903 name = MEMFILE_ATTR(cft->private);
3906 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3910 /* This function does all necessary parse...reuse it */
3911 ret = res_counter_memparse_write_strategy(buffer, &val);
3915 ret = mem_cgroup_resize_limit(memcg, val);
3917 ret = mem_cgroup_resize_memsw_limit(memcg, val);
3919 case RES_SOFT_LIMIT:
3920 ret = res_counter_memparse_write_strategy(buffer, &val);
3924 * For memsw, soft limits are hard to implement in terms
3925 * of semantics, for now, we support soft limits for
3926 * control without swap
3929 ret = res_counter_set_soft_limit(&memcg->res, val);
3934 ret = -EINVAL; /* should be BUG() ? */
3940 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
3941 unsigned long long *mem_limit, unsigned long long *memsw_limit)
3943 struct cgroup *cgroup;
3944 unsigned long long min_limit, min_memsw_limit, tmp;
3946 min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3947 min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3948 cgroup = memcg->css.cgroup;
3949 if (!memcg->use_hierarchy)
3952 while (cgroup->parent) {
3953 cgroup = cgroup->parent;
3954 memcg = mem_cgroup_from_cont(cgroup);
3955 if (!memcg->use_hierarchy)
3957 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
3958 min_limit = min(min_limit, tmp);
3959 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3960 min_memsw_limit = min(min_memsw_limit, tmp);
3963 *mem_limit = min_limit;
3964 *memsw_limit = min_memsw_limit;
3968 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
3970 struct mem_cgroup *memcg;
3973 memcg = mem_cgroup_from_cont(cont);
3974 type = MEMFILE_TYPE(event);
3975 name = MEMFILE_ATTR(event);
3979 res_counter_reset_max(&memcg->res);
3981 res_counter_reset_max(&memcg->memsw);
3985 res_counter_reset_failcnt(&memcg->res);
3987 res_counter_reset_failcnt(&memcg->memsw);
3994 static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
3997 return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
4001 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
4002 struct cftype *cft, u64 val)
4004 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4006 if (val >= (1 << NR_MOVE_TYPE))
4009 * We check this value several times in both in can_attach() and
4010 * attach(), so we need cgroup lock to prevent this value from being
4014 memcg->move_charge_at_immigrate = val;
4020 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
4021 struct cftype *cft, u64 val)
4028 /* For read statistics */
4046 struct mcs_total_stat {
4047 s64 stat[NR_MCS_STAT];
4053 } memcg_stat_strings[NR_MCS_STAT] = {
4054 {"cache", "total_cache"},
4055 {"rss", "total_rss"},
4056 {"mapped_file", "total_mapped_file"},
4057 {"pgpgin", "total_pgpgin"},
4058 {"pgpgout", "total_pgpgout"},
4059 {"swap", "total_swap"},
4060 {"pgfault", "total_pgfault"},
4061 {"pgmajfault", "total_pgmajfault"},
4062 {"inactive_anon", "total_inactive_anon"},
4063 {"active_anon", "total_active_anon"},
4064 {"inactive_file", "total_inactive_file"},
4065 {"active_file", "total_active_file"},
4066 {"unevictable", "total_unevictable"}
4071 mem_cgroup_get_local_stat(struct mem_cgroup *memcg, struct mcs_total_stat *s)
4076 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_CACHE);
4077 s->stat[MCS_CACHE] += val * PAGE_SIZE;
4078 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_RSS);
4079 s->stat[MCS_RSS] += val * PAGE_SIZE;
4080 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_FILE_MAPPED);
4081 s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE;
4082 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGPGIN);
4083 s->stat[MCS_PGPGIN] += val;
4084 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGPGOUT);
4085 s->stat[MCS_PGPGOUT] += val;
4086 if (do_swap_account) {
4087 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_SWAPOUT);
4088 s->stat[MCS_SWAP] += val * PAGE_SIZE;
4090 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGFAULT);
4091 s->stat[MCS_PGFAULT] += val;
4092 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGMAJFAULT);
4093 s->stat[MCS_PGMAJFAULT] += val;
4096 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_INACTIVE_ANON));
4097 s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
4098 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_ACTIVE_ANON));
4099 s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
4100 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_INACTIVE_FILE));
4101 s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
4102 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_ACTIVE_FILE));
4103 s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
4104 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_UNEVICTABLE));
4105 s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
4109 mem_cgroup_get_total_stat(struct mem_cgroup *memcg, struct mcs_total_stat *s)
4111 struct mem_cgroup *iter;
4113 for_each_mem_cgroup_tree(iter, memcg)
4114 mem_cgroup_get_local_stat(iter, s);
4118 static int mem_control_numa_stat_show(struct seq_file *m, void *arg)
4121 unsigned long total_nr, file_nr, anon_nr, unevictable_nr;
4122 unsigned long node_nr;
4123 struct cgroup *cont = m->private;
4124 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
4126 total_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL);
4127 seq_printf(m, "total=%lu", total_nr);
4128 for_each_node_state(nid, N_HIGH_MEMORY) {
4129 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid, LRU_ALL);
4130 seq_printf(m, " N%d=%lu", nid, node_nr);
4134 file_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_FILE);
4135 seq_printf(m, "file=%lu", file_nr);
4136 for_each_node_state(nid, N_HIGH_MEMORY) {
4137 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4139 seq_printf(m, " N%d=%lu", nid, node_nr);
4143 anon_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_ANON);
4144 seq_printf(m, "anon=%lu", anon_nr);
4145 for_each_node_state(nid, N_HIGH_MEMORY) {
4146 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4148 seq_printf(m, " N%d=%lu", nid, node_nr);
4152 unevictable_nr = mem_cgroup_nr_lru_pages(mem_cont, BIT(LRU_UNEVICTABLE));
4153 seq_printf(m, "unevictable=%lu", unevictable_nr);
4154 for_each_node_state(nid, N_HIGH_MEMORY) {
4155 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4156 BIT(LRU_UNEVICTABLE));
4157 seq_printf(m, " N%d=%lu", nid, node_nr);
4162 #endif /* CONFIG_NUMA */
4164 static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
4165 struct cgroup_map_cb *cb)
4167 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
4168 struct mcs_total_stat mystat;
4171 memset(&mystat, 0, sizeof(mystat));
4172 mem_cgroup_get_local_stat(mem_cont, &mystat);
4175 for (i = 0; i < NR_MCS_STAT; i++) {
4176 if (i == MCS_SWAP && !do_swap_account)
4178 cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
4181 /* Hierarchical information */
4183 unsigned long long limit, memsw_limit;
4184 memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
4185 cb->fill(cb, "hierarchical_memory_limit", limit);
4186 if (do_swap_account)
4187 cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
4190 memset(&mystat, 0, sizeof(mystat));
4191 mem_cgroup_get_total_stat(mem_cont, &mystat);
4192 for (i = 0; i < NR_MCS_STAT; i++) {
4193 if (i == MCS_SWAP && !do_swap_account)
4195 cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
4198 #ifdef CONFIG_DEBUG_VM
4201 struct mem_cgroup_per_zone *mz;
4202 unsigned long recent_rotated[2] = {0, 0};
4203 unsigned long recent_scanned[2] = {0, 0};
4205 for_each_online_node(nid)
4206 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
4207 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
4209 recent_rotated[0] +=
4210 mz->reclaim_stat.recent_rotated[0];
4211 recent_rotated[1] +=
4212 mz->reclaim_stat.recent_rotated[1];
4213 recent_scanned[0] +=
4214 mz->reclaim_stat.recent_scanned[0];
4215 recent_scanned[1] +=
4216 mz->reclaim_stat.recent_scanned[1];
4218 cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
4219 cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
4220 cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
4221 cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
4228 static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
4230 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4232 return mem_cgroup_swappiness(memcg);
4235 static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
4238 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4239 struct mem_cgroup *parent;
4244 if (cgrp->parent == NULL)
4247 parent = mem_cgroup_from_cont(cgrp->parent);
4251 /* If under hierarchy, only empty-root can set this value */
4252 if ((parent->use_hierarchy) ||
4253 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
4258 memcg->swappiness = val;
4265 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4267 struct mem_cgroup_threshold_ary *t;
4273 t = rcu_dereference(memcg->thresholds.primary);
4275 t = rcu_dereference(memcg->memsw_thresholds.primary);
4280 usage = mem_cgroup_usage(memcg, swap);
4283 * current_threshold points to threshold just below usage.
4284 * If it's not true, a threshold was crossed after last
4285 * call of __mem_cgroup_threshold().
4287 i = t->current_threshold;
4290 * Iterate backward over array of thresholds starting from
4291 * current_threshold and check if a threshold is crossed.
4292 * If none of thresholds below usage is crossed, we read
4293 * only one element of the array here.
4295 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4296 eventfd_signal(t->entries[i].eventfd, 1);
4298 /* i = current_threshold + 1 */
4302 * Iterate forward over array of thresholds starting from
4303 * current_threshold+1 and check if a threshold is crossed.
4304 * If none of thresholds above usage is crossed, we read
4305 * only one element of the array here.
4307 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4308 eventfd_signal(t->entries[i].eventfd, 1);
4310 /* Update current_threshold */
4311 t->current_threshold = i - 1;
4316 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4319 __mem_cgroup_threshold(memcg, false);
4320 if (do_swap_account)
4321 __mem_cgroup_threshold(memcg, true);
4323 memcg = parent_mem_cgroup(memcg);
4327 static int compare_thresholds(const void *a, const void *b)
4329 const struct mem_cgroup_threshold *_a = a;
4330 const struct mem_cgroup_threshold *_b = b;
4332 return _a->threshold - _b->threshold;
4335 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
4337 struct mem_cgroup_eventfd_list *ev;
4339 list_for_each_entry(ev, &memcg->oom_notify, list)
4340 eventfd_signal(ev->eventfd, 1);
4344 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
4346 struct mem_cgroup *iter;
4348 for_each_mem_cgroup_tree(iter, memcg)
4349 mem_cgroup_oom_notify_cb(iter);
4352 static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
4353 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4355 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4356 struct mem_cgroup_thresholds *thresholds;
4357 struct mem_cgroup_threshold_ary *new;
4358 int type = MEMFILE_TYPE(cft->private);
4359 u64 threshold, usage;
4362 ret = res_counter_memparse_write_strategy(args, &threshold);
4366 mutex_lock(&memcg->thresholds_lock);
4369 thresholds = &memcg->thresholds;
4370 else if (type == _MEMSWAP)
4371 thresholds = &memcg->memsw_thresholds;
4375 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4377 /* Check if a threshold crossed before adding a new one */
4378 if (thresholds->primary)
4379 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4381 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4383 /* Allocate memory for new array of thresholds */
4384 new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
4392 /* Copy thresholds (if any) to new array */
4393 if (thresholds->primary) {
4394 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
4395 sizeof(struct mem_cgroup_threshold));
4398 /* Add new threshold */
4399 new->entries[size - 1].eventfd = eventfd;
4400 new->entries[size - 1].threshold = threshold;
4402 /* Sort thresholds. Registering of new threshold isn't time-critical */
4403 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
4404 compare_thresholds, NULL);
4406 /* Find current threshold */
4407 new->current_threshold = -1;
4408 for (i = 0; i < size; i++) {
4409 if (new->entries[i].threshold < usage) {
4411 * new->current_threshold will not be used until
4412 * rcu_assign_pointer(), so it's safe to increment
4415 ++new->current_threshold;
4419 /* Free old spare buffer and save old primary buffer as spare */
4420 kfree(thresholds->spare);
4421 thresholds->spare = thresholds->primary;
4423 rcu_assign_pointer(thresholds->primary, new);
4425 /* To be sure that nobody uses thresholds */
4429 mutex_unlock(&memcg->thresholds_lock);
4434 static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
4435 struct cftype *cft, struct eventfd_ctx *eventfd)
4437 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4438 struct mem_cgroup_thresholds *thresholds;
4439 struct mem_cgroup_threshold_ary *new;
4440 int type = MEMFILE_TYPE(cft->private);
4444 mutex_lock(&memcg->thresholds_lock);
4446 thresholds = &memcg->thresholds;
4447 else if (type == _MEMSWAP)
4448 thresholds = &memcg->memsw_thresholds;
4453 * Something went wrong if we trying to unregister a threshold
4454 * if we don't have thresholds
4456 BUG_ON(!thresholds);
4458 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4460 /* Check if a threshold crossed before removing */
4461 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4463 /* Calculate new number of threshold */
4465 for (i = 0; i < thresholds->primary->size; i++) {
4466 if (thresholds->primary->entries[i].eventfd != eventfd)
4470 new = thresholds->spare;
4472 /* Set thresholds array to NULL if we don't have thresholds */
4481 /* Copy thresholds and find current threshold */
4482 new->current_threshold = -1;
4483 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4484 if (thresholds->primary->entries[i].eventfd == eventfd)
4487 new->entries[j] = thresholds->primary->entries[i];
4488 if (new->entries[j].threshold < usage) {
4490 * new->current_threshold will not be used
4491 * until rcu_assign_pointer(), so it's safe to increment
4494 ++new->current_threshold;
4500 /* Swap primary and spare array */
4501 thresholds->spare = thresholds->primary;
4502 rcu_assign_pointer(thresholds->primary, new);
4504 /* To be sure that nobody uses thresholds */
4507 mutex_unlock(&memcg->thresholds_lock);
4510 static int mem_cgroup_oom_register_event(struct cgroup *cgrp,
4511 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4513 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4514 struct mem_cgroup_eventfd_list *event;
4515 int type = MEMFILE_TYPE(cft->private);
4517 BUG_ON(type != _OOM_TYPE);
4518 event = kmalloc(sizeof(*event), GFP_KERNEL);
4522 spin_lock(&memcg_oom_lock);
4524 event->eventfd = eventfd;
4525 list_add(&event->list, &memcg->oom_notify);
4527 /* already in OOM ? */
4528 if (atomic_read(&memcg->under_oom))
4529 eventfd_signal(eventfd, 1);
4530 spin_unlock(&memcg_oom_lock);
4535 static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
4536 struct cftype *cft, struct eventfd_ctx *eventfd)
4538 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4539 struct mem_cgroup_eventfd_list *ev, *tmp;
4540 int type = MEMFILE_TYPE(cft->private);
4542 BUG_ON(type != _OOM_TYPE);
4544 spin_lock(&memcg_oom_lock);
4546 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
4547 if (ev->eventfd == eventfd) {
4548 list_del(&ev->list);
4553 spin_unlock(&memcg_oom_lock);
4556 static int mem_cgroup_oom_control_read(struct cgroup *cgrp,
4557 struct cftype *cft, struct cgroup_map_cb *cb)
4559 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4561 cb->fill(cb, "oom_kill_disable", memcg->oom_kill_disable);
4563 if (atomic_read(&memcg->under_oom))
4564 cb->fill(cb, "under_oom", 1);
4566 cb->fill(cb, "under_oom", 0);
4570 static int mem_cgroup_oom_control_write(struct cgroup *cgrp,
4571 struct cftype *cft, u64 val)
4573 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4574 struct mem_cgroup *parent;
4576 /* cannot set to root cgroup and only 0 and 1 are allowed */
4577 if (!cgrp->parent || !((val == 0) || (val == 1)))
4580 parent = mem_cgroup_from_cont(cgrp->parent);
4583 /* oom-kill-disable is a flag for subhierarchy. */
4584 if ((parent->use_hierarchy) ||
4585 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
4589 memcg->oom_kill_disable = val;
4591 memcg_oom_recover(memcg);
4597 static const struct file_operations mem_control_numa_stat_file_operations = {
4599 .llseek = seq_lseek,
4600 .release = single_release,
4603 static int mem_control_numa_stat_open(struct inode *unused, struct file *file)
4605 struct cgroup *cont = file->f_dentry->d_parent->d_fsdata;
4607 file->f_op = &mem_control_numa_stat_file_operations;
4608 return single_open(file, mem_control_numa_stat_show, cont);
4610 #endif /* CONFIG_NUMA */
4612 static struct cftype mem_cgroup_files[] = {
4614 .name = "usage_in_bytes",
4615 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
4616 .read_u64 = mem_cgroup_read,
4617 .register_event = mem_cgroup_usage_register_event,
4618 .unregister_event = mem_cgroup_usage_unregister_event,
4621 .name = "max_usage_in_bytes",
4622 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
4623 .trigger = mem_cgroup_reset,
4624 .read_u64 = mem_cgroup_read,
4627 .name = "limit_in_bytes",
4628 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
4629 .write_string = mem_cgroup_write,
4630 .read_u64 = mem_cgroup_read,
4633 .name = "soft_limit_in_bytes",
4634 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
4635 .write_string = mem_cgroup_write,
4636 .read_u64 = mem_cgroup_read,
4640 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
4641 .trigger = mem_cgroup_reset,
4642 .read_u64 = mem_cgroup_read,
4646 .read_map = mem_control_stat_show,
4649 .name = "force_empty",
4650 .trigger = mem_cgroup_force_empty_write,
4653 .name = "use_hierarchy",
4654 .write_u64 = mem_cgroup_hierarchy_write,
4655 .read_u64 = mem_cgroup_hierarchy_read,
4658 .name = "swappiness",
4659 .read_u64 = mem_cgroup_swappiness_read,
4660 .write_u64 = mem_cgroup_swappiness_write,
4663 .name = "move_charge_at_immigrate",
4664 .read_u64 = mem_cgroup_move_charge_read,
4665 .write_u64 = mem_cgroup_move_charge_write,
4668 .name = "oom_control",
4669 .read_map = mem_cgroup_oom_control_read,
4670 .write_u64 = mem_cgroup_oom_control_write,
4671 .register_event = mem_cgroup_oom_register_event,
4672 .unregister_event = mem_cgroup_oom_unregister_event,
4673 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
4677 .name = "numa_stat",
4678 .open = mem_control_numa_stat_open,
4684 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4685 static struct cftype memsw_cgroup_files[] = {
4687 .name = "memsw.usage_in_bytes",
4688 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
4689 .read_u64 = mem_cgroup_read,
4690 .register_event = mem_cgroup_usage_register_event,
4691 .unregister_event = mem_cgroup_usage_unregister_event,
4694 .name = "memsw.max_usage_in_bytes",
4695 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
4696 .trigger = mem_cgroup_reset,
4697 .read_u64 = mem_cgroup_read,
4700 .name = "memsw.limit_in_bytes",
4701 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
4702 .write_string = mem_cgroup_write,
4703 .read_u64 = mem_cgroup_read,
4706 .name = "memsw.failcnt",
4707 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
4708 .trigger = mem_cgroup_reset,
4709 .read_u64 = mem_cgroup_read,
4713 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
4715 if (!do_swap_account)
4717 return cgroup_add_files(cont, ss, memsw_cgroup_files,
4718 ARRAY_SIZE(memsw_cgroup_files));
4721 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
4727 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
4729 struct mem_cgroup_per_node *pn;
4730 struct mem_cgroup_per_zone *mz;
4732 int zone, tmp = node;
4734 * This routine is called against possible nodes.
4735 * But it's BUG to call kmalloc() against offline node.
4737 * TODO: this routine can waste much memory for nodes which will
4738 * never be onlined. It's better to use memory hotplug callback
4741 if (!node_state(node, N_NORMAL_MEMORY))
4743 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
4747 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4748 mz = &pn->zoneinfo[zone];
4750 INIT_LIST_HEAD(&mz->lists[l]);
4751 mz->usage_in_excess = 0;
4752 mz->on_tree = false;
4755 memcg->info.nodeinfo[node] = pn;
4759 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
4761 kfree(memcg->info.nodeinfo[node]);
4764 static struct mem_cgroup *mem_cgroup_alloc(void)
4766 struct mem_cgroup *mem;
4767 int size = sizeof(struct mem_cgroup);
4769 /* Can be very big if MAX_NUMNODES is very big */
4770 if (size < PAGE_SIZE)
4771 mem = kzalloc(size, GFP_KERNEL);
4773 mem = vzalloc(size);
4778 mem->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
4781 spin_lock_init(&mem->pcp_counter_lock);
4785 if (size < PAGE_SIZE)
4793 * At destroying mem_cgroup, references from swap_cgroup can remain.
4794 * (scanning all at force_empty is too costly...)
4796 * Instead of clearing all references at force_empty, we remember
4797 * the number of reference from swap_cgroup and free mem_cgroup when
4798 * it goes down to 0.
4800 * Removal of cgroup itself succeeds regardless of refs from swap.
4803 static void __mem_cgroup_free(struct mem_cgroup *memcg)
4807 mem_cgroup_remove_from_trees(memcg);
4808 free_css_id(&mem_cgroup_subsys, &memcg->css);
4810 for_each_node_state(node, N_POSSIBLE)
4811 free_mem_cgroup_per_zone_info(memcg, node);
4813 free_percpu(memcg->stat);
4814 if (sizeof(struct mem_cgroup) < PAGE_SIZE)
4820 static void mem_cgroup_get(struct mem_cgroup *memcg)
4822 atomic_inc(&memcg->refcnt);
4825 static void __mem_cgroup_put(struct mem_cgroup *memcg, int count)
4827 if (atomic_sub_and_test(count, &memcg->refcnt)) {
4828 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
4829 __mem_cgroup_free(memcg);
4831 mem_cgroup_put(parent);
4835 static void mem_cgroup_put(struct mem_cgroup *memcg)
4837 __mem_cgroup_put(memcg, 1);
4841 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
4843 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg)
4845 if (!memcg->res.parent)
4847 return mem_cgroup_from_res_counter(memcg->res.parent, res);
4850 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4851 static void __init enable_swap_cgroup(void)
4853 if (!mem_cgroup_disabled() && really_do_swap_account)
4854 do_swap_account = 1;
4857 static void __init enable_swap_cgroup(void)
4862 static int mem_cgroup_soft_limit_tree_init(void)
4864 struct mem_cgroup_tree_per_node *rtpn;
4865 struct mem_cgroup_tree_per_zone *rtpz;
4866 int tmp, node, zone;
4868 for_each_node_state(node, N_POSSIBLE) {
4870 if (!node_state(node, N_NORMAL_MEMORY))
4872 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
4876 soft_limit_tree.rb_tree_per_node[node] = rtpn;
4878 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4879 rtpz = &rtpn->rb_tree_per_zone[zone];
4880 rtpz->rb_root = RB_ROOT;
4881 spin_lock_init(&rtpz->lock);
4887 static struct cgroup_subsys_state * __ref
4888 mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
4890 struct mem_cgroup *memcg, *parent;
4891 long error = -ENOMEM;
4894 memcg = mem_cgroup_alloc();
4896 return ERR_PTR(error);
4898 for_each_node_state(node, N_POSSIBLE)
4899 if (alloc_mem_cgroup_per_zone_info(memcg, node))
4903 if (cont->parent == NULL) {
4905 enable_swap_cgroup();
4907 root_mem_cgroup = memcg;
4908 if (mem_cgroup_soft_limit_tree_init())
4910 for_each_possible_cpu(cpu) {
4911 struct memcg_stock_pcp *stock =
4912 &per_cpu(memcg_stock, cpu);
4913 INIT_WORK(&stock->work, drain_local_stock);
4915 hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
4917 parent = mem_cgroup_from_cont(cont->parent);
4918 memcg->use_hierarchy = parent->use_hierarchy;
4919 memcg->oom_kill_disable = parent->oom_kill_disable;
4922 if (parent && parent->use_hierarchy) {
4923 res_counter_init(&memcg->res, &parent->res);
4924 res_counter_init(&memcg->memsw, &parent->memsw);
4926 * We increment refcnt of the parent to ensure that we can
4927 * safely access it on res_counter_charge/uncharge.
4928 * This refcnt will be decremented when freeing this
4929 * mem_cgroup(see mem_cgroup_put).
4931 mem_cgroup_get(parent);
4933 res_counter_init(&memcg->res, NULL);
4934 res_counter_init(&memcg->memsw, NULL);
4936 memcg->last_scanned_child = 0;
4937 memcg->last_scanned_node = MAX_NUMNODES;
4938 INIT_LIST_HEAD(&memcg->oom_notify);
4941 memcg->swappiness = mem_cgroup_swappiness(parent);
4942 atomic_set(&memcg->refcnt, 1);
4943 memcg->move_charge_at_immigrate = 0;
4944 mutex_init(&memcg->thresholds_lock);
4947 __mem_cgroup_free(memcg);
4948 root_mem_cgroup = NULL;
4949 return ERR_PTR(error);
4952 static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
4953 struct cgroup *cont)
4955 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4957 return mem_cgroup_force_empty(memcg, false);
4960 static void mem_cgroup_destroy(struct cgroup_subsys *ss,
4961 struct cgroup *cont)
4963 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4965 mem_cgroup_put(memcg);
4968 static int mem_cgroup_populate(struct cgroup_subsys *ss,
4969 struct cgroup *cont)
4973 ret = cgroup_add_files(cont, ss, mem_cgroup_files,
4974 ARRAY_SIZE(mem_cgroup_files));
4977 ret = register_memsw_files(cont, ss);
4982 /* Handlers for move charge at task migration. */
4983 #define PRECHARGE_COUNT_AT_ONCE 256
4984 static int mem_cgroup_do_precharge(unsigned long count)
4987 int batch_count = PRECHARGE_COUNT_AT_ONCE;
4988 struct mem_cgroup *memcg = mc.to;
4990 if (mem_cgroup_is_root(memcg)) {
4991 mc.precharge += count;
4992 /* we don't need css_get for root */
4995 /* try to charge at once */
4997 struct res_counter *dummy;
4999 * "memcg" cannot be under rmdir() because we've already checked
5000 * by cgroup_lock_live_cgroup() that it is not removed and we
5001 * are still under the same cgroup_mutex. So we can postpone
5004 if (res_counter_charge(&memcg->res, PAGE_SIZE * count, &dummy))
5006 if (do_swap_account && res_counter_charge(&memcg->memsw,
5007 PAGE_SIZE * count, &dummy)) {
5008 res_counter_uncharge(&memcg->res, PAGE_SIZE * count);
5011 mc.precharge += count;
5015 /* fall back to one by one charge */
5017 if (signal_pending(current)) {
5021 if (!batch_count--) {
5022 batch_count = PRECHARGE_COUNT_AT_ONCE;
5025 ret = __mem_cgroup_try_charge(NULL,
5026 GFP_KERNEL, 1, &memcg, false);
5028 /* mem_cgroup_clear_mc() will do uncharge later */
5036 * is_target_pte_for_mc - check a pte whether it is valid for move charge
5037 * @vma: the vma the pte to be checked belongs
5038 * @addr: the address corresponding to the pte to be checked
5039 * @ptent: the pte to be checked
5040 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5043 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5044 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5045 * move charge. if @target is not NULL, the page is stored in target->page
5046 * with extra refcnt got(Callers should handle it).
5047 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5048 * target for charge migration. if @target is not NULL, the entry is stored
5051 * Called with pte lock held.
5058 enum mc_target_type {
5059 MC_TARGET_NONE, /* not used */
5064 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5065 unsigned long addr, pte_t ptent)
5067 struct page *page = vm_normal_page(vma, addr, ptent);
5069 if (!page || !page_mapped(page))
5071 if (PageAnon(page)) {
5072 /* we don't move shared anon */
5073 if (!move_anon() || page_mapcount(page) > 2)
5075 } else if (!move_file())
5076 /* we ignore mapcount for file pages */
5078 if (!get_page_unless_zero(page))
5084 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5085 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5088 struct page *page = NULL;
5089 swp_entry_t ent = pte_to_swp_entry(ptent);
5091 if (!move_anon() || non_swap_entry(ent))
5093 usage_count = mem_cgroup_count_swap_user(ent, &page);
5094 if (usage_count > 1) { /* we don't move shared anon */
5099 if (do_swap_account)
5100 entry->val = ent.val;
5105 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5106 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5108 struct page *page = NULL;
5109 struct inode *inode;
5110 struct address_space *mapping;
5113 if (!vma->vm_file) /* anonymous vma */
5118 inode = vma->vm_file->f_path.dentry->d_inode;
5119 mapping = vma->vm_file->f_mapping;
5120 if (pte_none(ptent))
5121 pgoff = linear_page_index(vma, addr);
5122 else /* pte_file(ptent) is true */
5123 pgoff = pte_to_pgoff(ptent);
5125 /* page is moved even if it's not RSS of this task(page-faulted). */
5126 page = find_get_page(mapping, pgoff);
5129 /* shmem/tmpfs may report page out on swap: account for that too. */
5130 if (radix_tree_exceptional_entry(page)) {
5131 swp_entry_t swap = radix_to_swp_entry(page);
5132 if (do_swap_account)
5134 page = find_get_page(&swapper_space, swap.val);
5140 static int is_target_pte_for_mc(struct vm_area_struct *vma,
5141 unsigned long addr, pte_t ptent, union mc_target *target)
5143 struct page *page = NULL;
5144 struct page_cgroup *pc;
5146 swp_entry_t ent = { .val = 0 };
5148 if (pte_present(ptent))
5149 page = mc_handle_present_pte(vma, addr, ptent);
5150 else if (is_swap_pte(ptent))
5151 page = mc_handle_swap_pte(vma, addr, ptent, &ent);
5152 else if (pte_none(ptent) || pte_file(ptent))
5153 page = mc_handle_file_pte(vma, addr, ptent, &ent);
5155 if (!page && !ent.val)
5158 pc = lookup_page_cgroup(page);
5160 * Do only loose check w/o page_cgroup lock.
5161 * mem_cgroup_move_account() checks the pc is valid or not under
5164 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
5165 ret = MC_TARGET_PAGE;
5167 target->page = page;
5169 if (!ret || !target)
5172 /* There is a swap entry and a page doesn't exist or isn't charged */
5173 if (ent.val && !ret &&
5174 css_id(&mc.from->css) == lookup_swap_cgroup(ent)) {
5175 ret = MC_TARGET_SWAP;
5182 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5183 unsigned long addr, unsigned long end,
5184 struct mm_walk *walk)
5186 struct vm_area_struct *vma = walk->private;
5190 split_huge_page_pmd(walk->mm, pmd);
5192 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5193 for (; addr != end; pte++, addr += PAGE_SIZE)
5194 if (is_target_pte_for_mc(vma, addr, *pte, NULL))
5195 mc.precharge++; /* increment precharge temporarily */
5196 pte_unmap_unlock(pte - 1, ptl);
5202 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5204 unsigned long precharge;
5205 struct vm_area_struct *vma;
5207 down_read(&mm->mmap_sem);
5208 for (vma = mm->mmap; vma; vma = vma->vm_next) {
5209 struct mm_walk mem_cgroup_count_precharge_walk = {
5210 .pmd_entry = mem_cgroup_count_precharge_pte_range,
5214 if (is_vm_hugetlb_page(vma))
5216 walk_page_range(vma->vm_start, vma->vm_end,
5217 &mem_cgroup_count_precharge_walk);
5219 up_read(&mm->mmap_sem);
5221 precharge = mc.precharge;
5227 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5229 unsigned long precharge = mem_cgroup_count_precharge(mm);
5231 VM_BUG_ON(mc.moving_task);
5232 mc.moving_task = current;
5233 return mem_cgroup_do_precharge(precharge);
5236 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5237 static void __mem_cgroup_clear_mc(void)
5239 struct mem_cgroup *from = mc.from;
5240 struct mem_cgroup *to = mc.to;
5242 /* we must uncharge all the leftover precharges from mc.to */
5244 __mem_cgroup_cancel_charge(mc.to, mc.precharge);
5248 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5249 * we must uncharge here.
5251 if (mc.moved_charge) {
5252 __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
5253 mc.moved_charge = 0;
5255 /* we must fixup refcnts and charges */
5256 if (mc.moved_swap) {
5257 /* uncharge swap account from the old cgroup */
5258 if (!mem_cgroup_is_root(mc.from))
5259 res_counter_uncharge(&mc.from->memsw,
5260 PAGE_SIZE * mc.moved_swap);
5261 __mem_cgroup_put(mc.from, mc.moved_swap);
5263 if (!mem_cgroup_is_root(mc.to)) {
5265 * we charged both to->res and to->memsw, so we should
5268 res_counter_uncharge(&mc.to->res,
5269 PAGE_SIZE * mc.moved_swap);
5271 /* we've already done mem_cgroup_get(mc.to) */
5274 memcg_oom_recover(from);
5275 memcg_oom_recover(to);
5276 wake_up_all(&mc.waitq);
5279 static void mem_cgroup_clear_mc(void)
5281 struct mem_cgroup *from = mc.from;
5284 * we must clear moving_task before waking up waiters at the end of
5287 mc.moving_task = NULL;
5288 __mem_cgroup_clear_mc();
5289 spin_lock(&mc.lock);
5292 spin_unlock(&mc.lock);
5293 mem_cgroup_end_move(from);
5296 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
5297 struct cgroup *cgroup,
5298 struct task_struct *p)
5301 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgroup);
5303 if (memcg->move_charge_at_immigrate) {
5304 struct mm_struct *mm;
5305 struct mem_cgroup *from = mem_cgroup_from_task(p);
5307 VM_BUG_ON(from == memcg);
5309 mm = get_task_mm(p);
5312 /* We move charges only when we move a owner of the mm */
5313 if (mm->owner == p) {
5316 VM_BUG_ON(mc.precharge);
5317 VM_BUG_ON(mc.moved_charge);
5318 VM_BUG_ON(mc.moved_swap);
5319 mem_cgroup_start_move(from);
5320 spin_lock(&mc.lock);
5323 spin_unlock(&mc.lock);
5324 /* We set mc.moving_task later */
5326 ret = mem_cgroup_precharge_mc(mm);
5328 mem_cgroup_clear_mc();
5335 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
5336 struct cgroup *cgroup,
5337 struct task_struct *p)
5339 mem_cgroup_clear_mc();
5342 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
5343 unsigned long addr, unsigned long end,
5344 struct mm_walk *walk)
5347 struct vm_area_struct *vma = walk->private;
5351 split_huge_page_pmd(walk->mm, pmd);
5353 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5354 for (; addr != end; addr += PAGE_SIZE) {
5355 pte_t ptent = *(pte++);
5356 union mc_target target;
5359 struct page_cgroup *pc;
5365 type = is_target_pte_for_mc(vma, addr, ptent, &target);
5367 case MC_TARGET_PAGE:
5369 if (isolate_lru_page(page))
5371 pc = lookup_page_cgroup(page);
5372 if (!mem_cgroup_move_account(page, 1, pc,
5373 mc.from, mc.to, false)) {
5375 /* we uncharge from mc.from later. */
5378 putback_lru_page(page);
5379 put: /* is_target_pte_for_mc() gets the page */
5382 case MC_TARGET_SWAP:
5384 if (!mem_cgroup_move_swap_account(ent,
5385 mc.from, mc.to, false)) {
5387 /* we fixup refcnts and charges later. */
5395 pte_unmap_unlock(pte - 1, ptl);
5400 * We have consumed all precharges we got in can_attach().
5401 * We try charge one by one, but don't do any additional
5402 * charges to mc.to if we have failed in charge once in attach()
5405 ret = mem_cgroup_do_precharge(1);
5413 static void mem_cgroup_move_charge(struct mm_struct *mm)
5415 struct vm_area_struct *vma;
5417 lru_add_drain_all();
5419 if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
5421 * Someone who are holding the mmap_sem might be waiting in
5422 * waitq. So we cancel all extra charges, wake up all waiters,
5423 * and retry. Because we cancel precharges, we might not be able
5424 * to move enough charges, but moving charge is a best-effort
5425 * feature anyway, so it wouldn't be a big problem.
5427 __mem_cgroup_clear_mc();
5431 for (vma = mm->mmap; vma; vma = vma->vm_next) {
5433 struct mm_walk mem_cgroup_move_charge_walk = {
5434 .pmd_entry = mem_cgroup_move_charge_pte_range,
5438 if (is_vm_hugetlb_page(vma))
5440 ret = walk_page_range(vma->vm_start, vma->vm_end,
5441 &mem_cgroup_move_charge_walk);
5444 * means we have consumed all precharges and failed in
5445 * doing additional charge. Just abandon here.
5449 up_read(&mm->mmap_sem);
5452 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
5453 struct cgroup *cont,
5454 struct cgroup *old_cont,
5455 struct task_struct *p)
5457 struct mm_struct *mm = get_task_mm(p);
5461 mem_cgroup_move_charge(mm);
5466 mem_cgroup_clear_mc();
5468 #else /* !CONFIG_MMU */
5469 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
5470 struct cgroup *cgroup,
5471 struct task_struct *p)
5475 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
5476 struct cgroup *cgroup,
5477 struct task_struct *p)
5480 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
5481 struct cgroup *cont,
5482 struct cgroup *old_cont,
5483 struct task_struct *p)
5488 struct cgroup_subsys mem_cgroup_subsys = {
5490 .subsys_id = mem_cgroup_subsys_id,
5491 .create = mem_cgroup_create,
5492 .pre_destroy = mem_cgroup_pre_destroy,
5493 .destroy = mem_cgroup_destroy,
5494 .populate = mem_cgroup_populate,
5495 .can_attach = mem_cgroup_can_attach,
5496 .cancel_attach = mem_cgroup_cancel_attach,
5497 .attach = mem_cgroup_move_task,
5502 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
5503 static int __init enable_swap_account(char *s)
5505 /* consider enabled if no parameter or 1 is given */
5506 if (!strcmp(s, "1"))
5507 really_do_swap_account = 1;
5508 else if (!strcmp(s, "0"))
5509 really_do_swap_account = 0;
5512 __setup("swapaccount=", enable_swap_account);