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/export.h>
37 #include <linux/mutex.h>
38 #include <linux/rbtree.h>
39 #include <linux/slab.h>
40 #include <linux/swap.h>
41 #include <linux/swapops.h>
42 #include <linux/spinlock.h>
43 #include <linux/eventfd.h>
44 #include <linux/sort.h>
46 #include <linux/seq_file.h>
47 #include <linux/vmalloc.h>
48 #include <linux/mm_inline.h>
49 #include <linux/page_cgroup.h>
50 #include <linux/cpu.h>
51 #include <linux/oom.h>
54 #include <asm/uaccess.h>
56 #include <trace/events/vmscan.h>
58 struct cgroup_subsys mem_cgroup_subsys __read_mostly;
59 #define MEM_CGROUP_RECLAIM_RETRIES 5
60 struct mem_cgroup *root_mem_cgroup __read_mostly;
62 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
63 /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
64 int do_swap_account __read_mostly;
66 /* for remember boot option*/
67 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP_ENABLED
68 static int really_do_swap_account __initdata = 1;
70 static int really_do_swap_account __initdata = 0;
74 #define do_swap_account (0)
79 * Statistics for memory cgroup.
81 enum mem_cgroup_stat_index {
83 * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
85 MEM_CGROUP_STAT_CACHE, /* # of pages charged as cache */
86 MEM_CGROUP_STAT_RSS, /* # of pages charged as anon rss */
87 MEM_CGROUP_STAT_FILE_MAPPED, /* # of pages charged as file rss */
88 MEM_CGROUP_STAT_SWAPOUT, /* # of pages, swapped out */
89 MEM_CGROUP_STAT_DATA, /* end of data requires synchronization */
90 MEM_CGROUP_ON_MOVE, /* someone is moving account between groups */
91 MEM_CGROUP_STAT_NSTATS,
94 enum mem_cgroup_events_index {
95 MEM_CGROUP_EVENTS_PGPGIN, /* # of pages paged in */
96 MEM_CGROUP_EVENTS_PGPGOUT, /* # of pages paged out */
97 MEM_CGROUP_EVENTS_COUNT, /* # of pages paged in/out */
98 MEM_CGROUP_EVENTS_PGFAULT, /* # of page-faults */
99 MEM_CGROUP_EVENTS_PGMAJFAULT, /* # of major page-faults */
100 MEM_CGROUP_EVENTS_NSTATS,
103 * Per memcg event counter is incremented at every pagein/pageout. With THP,
104 * it will be incremated by the number of pages. This counter is used for
105 * for trigger some periodic events. This is straightforward and better
106 * than using jiffies etc. to handle periodic memcg event.
108 enum mem_cgroup_events_target {
109 MEM_CGROUP_TARGET_THRESH,
110 MEM_CGROUP_TARGET_SOFTLIMIT,
111 MEM_CGROUP_TARGET_NUMAINFO,
114 #define THRESHOLDS_EVENTS_TARGET (128)
115 #define SOFTLIMIT_EVENTS_TARGET (1024)
116 #define NUMAINFO_EVENTS_TARGET (1024)
118 struct mem_cgroup_stat_cpu {
119 long count[MEM_CGROUP_STAT_NSTATS];
120 unsigned long events[MEM_CGROUP_EVENTS_NSTATS];
121 unsigned long targets[MEM_CGROUP_NTARGETS];
124 struct mem_cgroup_reclaim_iter {
125 /* css_id of the last scanned hierarchy member */
127 /* scan generation, increased every round-trip */
128 unsigned int generation;
132 * per-zone information in memory controller.
134 struct mem_cgroup_per_zone {
135 struct lruvec lruvec;
136 unsigned long count[NR_LRU_LISTS];
138 struct mem_cgroup_reclaim_iter reclaim_iter[DEF_PRIORITY + 1];
140 struct zone_reclaim_stat reclaim_stat;
141 struct rb_node tree_node; /* RB tree node */
142 unsigned long long usage_in_excess;/* Set to the value by which */
143 /* the soft limit is exceeded*/
145 struct mem_cgroup *mem; /* Back pointer, we cannot */
146 /* use container_of */
148 /* Macro for accessing counter */
149 #define MEM_CGROUP_ZSTAT(mz, idx) ((mz)->count[(idx)])
151 struct mem_cgroup_per_node {
152 struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
155 struct mem_cgroup_lru_info {
156 struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
160 * Cgroups above their limits are maintained in a RB-Tree, independent of
161 * their hierarchy representation
164 struct mem_cgroup_tree_per_zone {
165 struct rb_root rb_root;
169 struct mem_cgroup_tree_per_node {
170 struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
173 struct mem_cgroup_tree {
174 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
177 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
179 struct mem_cgroup_threshold {
180 struct eventfd_ctx *eventfd;
185 struct mem_cgroup_threshold_ary {
186 /* An array index points to threshold just below usage. */
187 int current_threshold;
188 /* Size of entries[] */
190 /* Array of thresholds */
191 struct mem_cgroup_threshold entries[0];
194 struct mem_cgroup_thresholds {
195 /* Primary thresholds array */
196 struct mem_cgroup_threshold_ary *primary;
198 * Spare threshold array.
199 * This is needed to make mem_cgroup_unregister_event() "never fail".
200 * It must be able to store at least primary->size - 1 entries.
202 struct mem_cgroup_threshold_ary *spare;
206 struct mem_cgroup_eventfd_list {
207 struct list_head list;
208 struct eventfd_ctx *eventfd;
211 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
212 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
215 * The memory controller data structure. The memory controller controls both
216 * page cache and RSS per cgroup. We would eventually like to provide
217 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
218 * to help the administrator determine what knobs to tune.
220 * TODO: Add a water mark for the memory controller. Reclaim will begin when
221 * we hit the water mark. May be even add a low water mark, such that
222 * no reclaim occurs from a cgroup at it's low water mark, this is
223 * a feature that will be implemented much later in the future.
226 struct cgroup_subsys_state css;
228 * the counter to account for memory usage
230 struct res_counter res;
232 * the counter to account for mem+swap usage.
234 struct res_counter memsw;
236 * Per cgroup active and inactive list, similar to the
237 * per zone LRU lists.
239 struct mem_cgroup_lru_info info;
240 int last_scanned_node;
242 nodemask_t scan_nodes;
243 atomic_t numainfo_events;
244 atomic_t numainfo_updating;
247 * Should the accounting and control be hierarchical, per subtree?
257 /* OOM-Killer disable */
258 int oom_kill_disable;
260 /* set when res.limit == memsw.limit */
261 bool memsw_is_minimum;
263 /* protect arrays of thresholds */
264 struct mutex thresholds_lock;
266 /* thresholds for memory usage. RCU-protected */
267 struct mem_cgroup_thresholds thresholds;
269 /* thresholds for mem+swap usage. RCU-protected */
270 struct mem_cgroup_thresholds memsw_thresholds;
272 /* For oom notifier event fd */
273 struct list_head oom_notify;
276 * Should we move charges of a task when a task is moved into this
277 * mem_cgroup ? And what type of charges should we move ?
279 unsigned long move_charge_at_immigrate;
283 struct mem_cgroup_stat_cpu *stat;
285 * used when a cpu is offlined or other synchronizations
286 * See mem_cgroup_read_stat().
288 struct mem_cgroup_stat_cpu nocpu_base;
289 spinlock_t pcp_counter_lock;
292 /* Stuffs for move charges at task migration. */
294 * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a
295 * left-shifted bitmap of these types.
298 MOVE_CHARGE_TYPE_ANON, /* private anonymous page and swap of it */
299 MOVE_CHARGE_TYPE_FILE, /* file page(including tmpfs) and swap of it */
303 /* "mc" and its members are protected by cgroup_mutex */
304 static struct move_charge_struct {
305 spinlock_t lock; /* for from, to */
306 struct mem_cgroup *from;
307 struct mem_cgroup *to;
308 unsigned long precharge;
309 unsigned long moved_charge;
310 unsigned long moved_swap;
311 struct task_struct *moving_task; /* a task moving charges */
312 wait_queue_head_t waitq; /* a waitq for other context */
314 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
315 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
318 static bool move_anon(void)
320 return test_bit(MOVE_CHARGE_TYPE_ANON,
321 &mc.to->move_charge_at_immigrate);
324 static bool move_file(void)
326 return test_bit(MOVE_CHARGE_TYPE_FILE,
327 &mc.to->move_charge_at_immigrate);
331 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
332 * limit reclaim to prevent infinite loops, if they ever occur.
334 #define MEM_CGROUP_MAX_RECLAIM_LOOPS (100)
335 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS (2)
338 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
339 MEM_CGROUP_CHARGE_TYPE_MAPPED,
340 MEM_CGROUP_CHARGE_TYPE_SHMEM, /* used by page migration of shmem */
341 MEM_CGROUP_CHARGE_TYPE_FORCE, /* used by force_empty */
342 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
343 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
347 /* for encoding cft->private value on file */
350 #define _OOM_TYPE (2)
351 #define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val))
352 #define MEMFILE_TYPE(val) (((val) >> 16) & 0xffff)
353 #define MEMFILE_ATTR(val) ((val) & 0xffff)
354 /* Used for OOM nofiier */
355 #define OOM_CONTROL (0)
358 * Reclaim flags for mem_cgroup_hierarchical_reclaim
360 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
361 #define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
362 #define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
363 #define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_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)
725 /* threshold event is triggered in finer grain than soft limit */
726 if (unlikely(__memcg_event_check(memcg, MEM_CGROUP_TARGET_THRESH))) {
727 mem_cgroup_threshold(memcg);
728 __mem_cgroup_target_update(memcg, MEM_CGROUP_TARGET_THRESH);
729 if (unlikely(__memcg_event_check(memcg,
730 MEM_CGROUP_TARGET_SOFTLIMIT))) {
731 mem_cgroup_update_tree(memcg, page);
732 __mem_cgroup_target_update(memcg,
733 MEM_CGROUP_TARGET_SOFTLIMIT);
736 if (unlikely(__memcg_event_check(memcg,
737 MEM_CGROUP_TARGET_NUMAINFO))) {
738 atomic_inc(&memcg->numainfo_events);
739 __mem_cgroup_target_update(memcg,
740 MEM_CGROUP_TARGET_NUMAINFO);
747 static struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
749 return container_of(cgroup_subsys_state(cont,
750 mem_cgroup_subsys_id), struct mem_cgroup,
754 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
757 * mm_update_next_owner() may clear mm->owner to NULL
758 * if it races with swapoff, page migration, etc.
759 * So this can be called with p == NULL.
764 return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
765 struct mem_cgroup, css);
768 struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
770 struct mem_cgroup *memcg = NULL;
775 * Because we have no locks, mm->owner's may be being moved to other
776 * cgroup. We use css_tryget() here even if this looks
777 * pessimistic (rather than adding locks here).
781 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
782 if (unlikely(!memcg))
784 } while (!css_tryget(&memcg->css));
790 * mem_cgroup_iter - iterate over memory cgroup hierarchy
791 * @root: hierarchy root
792 * @prev: previously returned memcg, NULL on first invocation
793 * @reclaim: cookie for shared reclaim walks, NULL for full walks
795 * Returns references to children of the hierarchy below @root, or
796 * @root itself, or %NULL after a full round-trip.
798 * Caller must pass the return value in @prev on subsequent
799 * invocations for reference counting, or use mem_cgroup_iter_break()
800 * to cancel a hierarchy walk before the round-trip is complete.
802 * Reclaimers can specify a zone and a priority level in @reclaim to
803 * divide up the memcgs in the hierarchy among all concurrent
804 * reclaimers operating on the same zone and priority.
806 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
807 struct mem_cgroup *prev,
808 struct mem_cgroup_reclaim_cookie *reclaim)
810 struct mem_cgroup *memcg = NULL;
813 if (mem_cgroup_disabled())
817 root = root_mem_cgroup;
819 if (prev && !reclaim)
820 id = css_id(&prev->css);
822 if (prev && prev != root)
825 if (!root->use_hierarchy && root != root_mem_cgroup) {
832 struct mem_cgroup_reclaim_iter *uninitialized_var(iter);
833 struct cgroup_subsys_state *css;
836 int nid = zone_to_nid(reclaim->zone);
837 int zid = zone_idx(reclaim->zone);
838 struct mem_cgroup_per_zone *mz;
840 mz = mem_cgroup_zoneinfo(root, nid, zid);
841 iter = &mz->reclaim_iter[reclaim->priority];
842 if (prev && reclaim->generation != iter->generation)
848 css = css_get_next(&mem_cgroup_subsys, id + 1, &root->css, &id);
850 if (css == &root->css || css_tryget(css))
851 memcg = container_of(css,
852 struct mem_cgroup, css);
861 else if (!prev && memcg)
862 reclaim->generation = iter->generation;
872 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
873 * @root: hierarchy root
874 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
876 void mem_cgroup_iter_break(struct mem_cgroup *root,
877 struct mem_cgroup *prev)
880 root = root_mem_cgroup;
881 if (prev && prev != root)
886 * Iteration constructs for visiting all cgroups (under a tree). If
887 * loops are exited prematurely (break), mem_cgroup_iter_break() must
888 * be used for reference counting.
890 #define for_each_mem_cgroup_tree(iter, root) \
891 for (iter = mem_cgroup_iter(root, NULL, NULL); \
893 iter = mem_cgroup_iter(root, iter, NULL))
895 #define for_each_mem_cgroup(iter) \
896 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
898 iter = mem_cgroup_iter(NULL, iter, NULL))
900 static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
902 return (memcg == root_mem_cgroup);
905 void mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx)
907 struct mem_cgroup *memcg;
913 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
914 if (unlikely(!memcg))
919 mem_cgroup_pgmajfault(memcg, 1);
922 mem_cgroup_pgfault(memcg, 1);
930 EXPORT_SYMBOL(mem_cgroup_count_vm_event);
933 * mem_cgroup_zone_lruvec - get the lru list vector for a zone and memcg
934 * @zone: zone of the wanted lruvec
935 * @mem: memcg of the wanted lruvec
937 * Returns the lru list vector holding pages for the given @zone and
938 * @mem. This can be the global zone lruvec, if the memory controller
941 struct lruvec *mem_cgroup_zone_lruvec(struct zone *zone,
942 struct mem_cgroup *memcg)
944 struct mem_cgroup_per_zone *mz;
946 if (mem_cgroup_disabled())
947 return &zone->lruvec;
949 mz = mem_cgroup_zoneinfo(memcg, zone_to_nid(zone), zone_idx(zone));
954 * Following LRU functions are allowed to be used without PCG_LOCK.
955 * Operations are called by routine of global LRU independently from memcg.
956 * What we have to take care of here is validness of pc->mem_cgroup.
958 * Changes to pc->mem_cgroup happens when
961 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
962 * It is added to LRU before charge.
963 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
964 * When moving account, the page is not on LRU. It's isolated.
968 * mem_cgroup_lru_add_list - account for adding an lru page and return lruvec
969 * @zone: zone of the page
973 * This function accounts for @page being added to @lru, and returns
974 * the lruvec for the given @zone and the memcg @page is charged to.
976 * The callsite is then responsible for physically linking the page to
977 * the returned lruvec->lists[@lru].
979 struct lruvec *mem_cgroup_lru_add_list(struct zone *zone, struct page *page,
982 struct mem_cgroup_per_zone *mz;
983 struct mem_cgroup *memcg;
984 struct page_cgroup *pc;
986 if (mem_cgroup_disabled())
987 return &zone->lruvec;
989 pc = lookup_page_cgroup(page);
990 VM_BUG_ON(PageCgroupAcctLRU(pc));
993 * SetPageLRU SetPageCgroupUsed
995 * PageCgroupUsed && add to memcg LRU PageLRU && add to memcg LRU
997 * Ensure that one of the two sides adds the page to the memcg
1002 * If the page is uncharged, it may be freed soon, but it
1003 * could also be swap cache (readahead, swapoff) that needs to
1004 * be reclaimable in the future. root_mem_cgroup will babysit
1005 * it for the time being.
1007 if (PageCgroupUsed(pc)) {
1008 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1010 memcg = pc->mem_cgroup;
1011 SetPageCgroupAcctLRU(pc);
1013 memcg = root_mem_cgroup;
1014 mz = page_cgroup_zoneinfo(memcg, page);
1015 /* compound_order() is stabilized through lru_lock */
1016 MEM_CGROUP_ZSTAT(mz, lru) += 1 << compound_order(page);
1021 * mem_cgroup_lru_del_list - account for removing an lru page
1025 * This function accounts for @page being removed from @lru.
1027 * The callsite is then responsible for physically unlinking
1030 void mem_cgroup_lru_del_list(struct page *page, enum lru_list lru)
1032 struct mem_cgroup_per_zone *mz;
1033 struct mem_cgroup *memcg;
1034 struct page_cgroup *pc;
1036 if (mem_cgroup_disabled())
1039 pc = lookup_page_cgroup(page);
1041 * root_mem_cgroup babysits uncharged LRU pages, but
1042 * PageCgroupUsed is cleared when the page is about to get
1043 * freed. PageCgroupAcctLRU remembers whether the
1044 * LRU-accounting happened against pc->mem_cgroup or
1047 if (TestClearPageCgroupAcctLRU(pc)) {
1048 VM_BUG_ON(!pc->mem_cgroup);
1049 memcg = pc->mem_cgroup;
1051 memcg = root_mem_cgroup;
1052 mz = page_cgroup_zoneinfo(memcg, page);
1053 /* huge page split is done under lru_lock. so, we have no races. */
1054 MEM_CGROUP_ZSTAT(mz, lru) -= 1 << compound_order(page);
1057 void mem_cgroup_lru_del(struct page *page)
1059 mem_cgroup_lru_del_list(page, page_lru(page));
1063 * mem_cgroup_lru_move_lists - account for moving a page between lrus
1064 * @zone: zone of the page
1066 * @from: current lru
1069 * This function accounts for @page being moved between the lrus @from
1070 * and @to, and returns the lruvec for the given @zone and the memcg
1071 * @page is charged to.
1073 * The callsite is then responsible for physically relinking
1074 * @page->lru to the returned lruvec->lists[@to].
1076 struct lruvec *mem_cgroup_lru_move_lists(struct zone *zone,
1081 /* XXX: Optimize this, especially for @from == @to */
1082 mem_cgroup_lru_del_list(page, from);
1083 return mem_cgroup_lru_add_list(zone, page, to);
1087 * At handling SwapCache and other FUSE stuff, pc->mem_cgroup may be changed
1088 * while it's linked to lru because the page may be reused after it's fully
1089 * uncharged. To handle that, unlink page_cgroup from LRU when charge it again.
1090 * It's done under lock_page and expected that zone->lru_lock isnever held.
1092 static void mem_cgroup_lru_del_before_commit(struct page *page)
1095 unsigned long flags;
1096 struct zone *zone = page_zone(page);
1097 struct page_cgroup *pc = lookup_page_cgroup(page);
1100 * Doing this check without taking ->lru_lock seems wrong but this
1101 * is safe. Because if page_cgroup's USED bit is unset, the page
1102 * will not be added to any memcg's LRU. If page_cgroup's USED bit is
1103 * set, the commit after this will fail, anyway.
1104 * This all charge/uncharge is done under some mutual execustion.
1105 * So, we don't need to taking care of changes in USED bit.
1107 if (likely(!PageLRU(page)))
1110 spin_lock_irqsave(&zone->lru_lock, flags);
1111 lru = page_lru(page);
1113 * The uncharged page could still be registered to the LRU of
1114 * the stale pc->mem_cgroup.
1116 * As pc->mem_cgroup is about to get overwritten, the old LRU
1117 * accounting needs to be taken care of. Let root_mem_cgroup
1118 * babysit the page until the new memcg is responsible for it.
1120 * The PCG_USED bit is guarded by lock_page() as the page is
1121 * swapcache/pagecache.
1123 if (PageLRU(page) && PageCgroupAcctLRU(pc) && !PageCgroupUsed(pc)) {
1124 del_page_from_lru_list(zone, page, lru);
1125 add_page_to_lru_list(zone, page, lru);
1127 spin_unlock_irqrestore(&zone->lru_lock, flags);
1130 static void mem_cgroup_lru_add_after_commit(struct page *page)
1133 unsigned long flags;
1134 struct zone *zone = page_zone(page);
1135 struct page_cgroup *pc = lookup_page_cgroup(page);
1138 * SetPageLRU SetPageCgroupUsed
1140 * PageCgroupUsed && add to memcg LRU PageLRU && add to memcg LRU
1142 * Ensure that one of the two sides adds the page to the memcg
1143 * LRU during a race.
1146 /* taking care of that the page is added to LRU while we commit it */
1147 if (likely(!PageLRU(page)))
1149 spin_lock_irqsave(&zone->lru_lock, flags);
1150 lru = page_lru(page);
1152 * If the page is not on the LRU, someone will soon put it
1153 * there. If it is, and also already accounted for on the
1154 * memcg-side, it must be on the right lruvec as setting
1155 * pc->mem_cgroup and PageCgroupUsed is properly ordered.
1156 * Otherwise, root_mem_cgroup has been babysitting the page
1157 * during the charge. Move it to the new memcg now.
1159 if (PageLRU(page) && !PageCgroupAcctLRU(pc)) {
1160 del_page_from_lru_list(zone, page, lru);
1161 add_page_to_lru_list(zone, page, lru);
1163 spin_unlock_irqrestore(&zone->lru_lock, flags);
1167 * Checks whether given mem is same or in the root_mem_cgroup's
1170 static bool mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1171 struct mem_cgroup *memcg)
1173 if (root_memcg != memcg) {
1174 return (root_memcg->use_hierarchy &&
1175 css_is_ancestor(&memcg->css, &root_memcg->css));
1181 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *memcg)
1184 struct mem_cgroup *curr = NULL;
1185 struct task_struct *p;
1187 p = find_lock_task_mm(task);
1190 curr = try_get_mem_cgroup_from_mm(p->mm);
1195 * We should check use_hierarchy of "memcg" not "curr". Because checking
1196 * use_hierarchy of "curr" here make this function true if hierarchy is
1197 * enabled in "curr" and "curr" is a child of "memcg" in *cgroup*
1198 * hierarchy(even if use_hierarchy is disabled in "memcg").
1200 ret = mem_cgroup_same_or_subtree(memcg, curr);
1201 css_put(&curr->css);
1205 int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg, struct zone *zone)
1207 unsigned long inactive_ratio;
1208 int nid = zone_to_nid(zone);
1209 int zid = zone_idx(zone);
1210 unsigned long inactive;
1211 unsigned long active;
1214 inactive = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1215 BIT(LRU_INACTIVE_ANON));
1216 active = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1217 BIT(LRU_ACTIVE_ANON));
1219 gb = (inactive + active) >> (30 - PAGE_SHIFT);
1221 inactive_ratio = int_sqrt(10 * gb);
1225 return inactive * inactive_ratio < active;
1228 int mem_cgroup_inactive_file_is_low(struct mem_cgroup *memcg, struct zone *zone)
1230 unsigned long active;
1231 unsigned long inactive;
1232 int zid = zone_idx(zone);
1233 int nid = zone_to_nid(zone);
1235 inactive = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1236 BIT(LRU_INACTIVE_FILE));
1237 active = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1238 BIT(LRU_ACTIVE_FILE));
1240 return (active > inactive);
1243 struct zone_reclaim_stat *mem_cgroup_get_reclaim_stat(struct mem_cgroup *memcg,
1246 int nid = zone_to_nid(zone);
1247 int zid = zone_idx(zone);
1248 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
1250 return &mz->reclaim_stat;
1253 struct zone_reclaim_stat *
1254 mem_cgroup_get_reclaim_stat_from_page(struct page *page)
1256 struct page_cgroup *pc;
1257 struct mem_cgroup_per_zone *mz;
1259 if (mem_cgroup_disabled())
1262 pc = lookup_page_cgroup(page);
1263 if (!PageCgroupUsed(pc))
1265 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1267 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1268 return &mz->reclaim_stat;
1271 #define mem_cgroup_from_res_counter(counter, member) \
1272 container_of(counter, struct mem_cgroup, member)
1275 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1276 * @mem: the memory cgroup
1278 * Returns the maximum amount of memory @mem can be charged with, in
1281 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1283 unsigned long long margin;
1285 margin = res_counter_margin(&memcg->res);
1286 if (do_swap_account)
1287 margin = min(margin, res_counter_margin(&memcg->memsw));
1288 return margin >> PAGE_SHIFT;
1291 int mem_cgroup_swappiness(struct mem_cgroup *memcg)
1293 struct cgroup *cgrp = memcg->css.cgroup;
1296 if (cgrp->parent == NULL)
1297 return vm_swappiness;
1299 return memcg->swappiness;
1302 static void mem_cgroup_start_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);
1317 static void mem_cgroup_end_move(struct mem_cgroup *memcg)
1324 spin_lock(&memcg->pcp_counter_lock);
1325 for_each_online_cpu(cpu)
1326 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) -= 1;
1327 memcg->nocpu_base.count[MEM_CGROUP_ON_MOVE] -= 1;
1328 spin_unlock(&memcg->pcp_counter_lock);
1332 * 2 routines for checking "mem" is under move_account() or not.
1334 * mem_cgroup_stealed() - checking a cgroup is mc.from or not. This is used
1335 * for avoiding race in accounting. If true,
1336 * pc->mem_cgroup may be overwritten.
1338 * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
1339 * under hierarchy of moving cgroups. This is for
1340 * waiting at hith-memory prressure caused by "move".
1343 static bool mem_cgroup_stealed(struct mem_cgroup *memcg)
1345 VM_BUG_ON(!rcu_read_lock_held());
1346 return this_cpu_read(memcg->stat->count[MEM_CGROUP_ON_MOVE]) > 0;
1349 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1351 struct mem_cgroup *from;
1352 struct mem_cgroup *to;
1355 * Unlike task_move routines, we access mc.to, mc.from not under
1356 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1358 spin_lock(&mc.lock);
1364 ret = mem_cgroup_same_or_subtree(memcg, from)
1365 || mem_cgroup_same_or_subtree(memcg, to);
1367 spin_unlock(&mc.lock);
1371 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1373 if (mc.moving_task && current != mc.moving_task) {
1374 if (mem_cgroup_under_move(memcg)) {
1376 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1377 /* moving charge context might have finished. */
1380 finish_wait(&mc.waitq, &wait);
1388 * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode.
1389 * @memcg: The memory cgroup that went over limit
1390 * @p: Task that is going to be killed
1392 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1395 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1397 struct cgroup *task_cgrp;
1398 struct cgroup *mem_cgrp;
1400 * Need a buffer in BSS, can't rely on allocations. The code relies
1401 * on the assumption that OOM is serialized for memory controller.
1402 * If this assumption is broken, revisit this code.
1404 static char memcg_name[PATH_MAX];
1413 mem_cgrp = memcg->css.cgroup;
1414 task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1416 ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1419 * Unfortunately, we are unable to convert to a useful name
1420 * But we'll still print out the usage information
1427 printk(KERN_INFO "Task in %s killed", memcg_name);
1430 ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1438 * Continues from above, so we don't need an KERN_ level
1440 printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
1443 printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
1444 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1445 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1446 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1447 printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
1449 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1450 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1451 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1455 * This function returns the number of memcg under hierarchy tree. Returns
1456 * 1(self count) if no children.
1458 static int mem_cgroup_count_children(struct mem_cgroup *memcg)
1461 struct mem_cgroup *iter;
1463 for_each_mem_cgroup_tree(iter, memcg)
1469 * Return the memory (and swap, if configured) limit for a memcg.
1471 u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
1476 limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
1477 limit += total_swap_pages << PAGE_SHIFT;
1479 memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
1481 * If memsw is finite and limits the amount of swap space available
1482 * to this memcg, return that limit.
1484 return min(limit, memsw);
1487 static unsigned long mem_cgroup_reclaim(struct mem_cgroup *memcg,
1489 unsigned long flags)
1491 unsigned long total = 0;
1492 bool noswap = false;
1495 if (flags & MEM_CGROUP_RECLAIM_NOSWAP)
1497 if (!(flags & MEM_CGROUP_RECLAIM_SHRINK) && memcg->memsw_is_minimum)
1500 for (loop = 0; loop < MEM_CGROUP_MAX_RECLAIM_LOOPS; loop++) {
1502 drain_all_stock_async(memcg);
1503 total += try_to_free_mem_cgroup_pages(memcg, gfp_mask, noswap);
1505 * Allow limit shrinkers, which are triggered directly
1506 * by userspace, to catch signals and stop reclaim
1507 * after minimal progress, regardless of the margin.
1509 if (total && (flags & MEM_CGROUP_RECLAIM_SHRINK))
1511 if (mem_cgroup_margin(memcg))
1514 * If nothing was reclaimed after two attempts, there
1515 * may be no reclaimable pages in this hierarchy.
1524 * test_mem_cgroup_node_reclaimable
1525 * @mem: the target memcg
1526 * @nid: the node ID to be checked.
1527 * @noswap : specify true here if the user wants flle only information.
1529 * This function returns whether the specified memcg contains any
1530 * reclaimable pages on a node. Returns true if there are any reclaimable
1531 * pages in the node.
1533 static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
1534 int nid, bool noswap)
1536 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE))
1538 if (noswap || !total_swap_pages)
1540 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON))
1545 #if MAX_NUMNODES > 1
1548 * Always updating the nodemask is not very good - even if we have an empty
1549 * list or the wrong list here, we can start from some node and traverse all
1550 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1553 static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
1557 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1558 * pagein/pageout changes since the last update.
1560 if (!atomic_read(&memcg->numainfo_events))
1562 if (atomic_inc_return(&memcg->numainfo_updating) > 1)
1565 /* make a nodemask where this memcg uses memory from */
1566 memcg->scan_nodes = node_states[N_HIGH_MEMORY];
1568 for_each_node_mask(nid, node_states[N_HIGH_MEMORY]) {
1570 if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
1571 node_clear(nid, memcg->scan_nodes);
1574 atomic_set(&memcg->numainfo_events, 0);
1575 atomic_set(&memcg->numainfo_updating, 0);
1579 * Selecting a node where we start reclaim from. Because what we need is just
1580 * reducing usage counter, start from anywhere is O,K. Considering
1581 * memory reclaim from current node, there are pros. and cons.
1583 * Freeing memory from current node means freeing memory from a node which
1584 * we'll use or we've used. So, it may make LRU bad. And if several threads
1585 * hit limits, it will see a contention on a node. But freeing from remote
1586 * node means more costs for memory reclaim because of memory latency.
1588 * Now, we use round-robin. Better algorithm is welcomed.
1590 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1594 mem_cgroup_may_update_nodemask(memcg);
1595 node = memcg->last_scanned_node;
1597 node = next_node(node, memcg->scan_nodes);
1598 if (node == MAX_NUMNODES)
1599 node = first_node(memcg->scan_nodes);
1601 * We call this when we hit limit, not when pages are added to LRU.
1602 * No LRU may hold pages because all pages are UNEVICTABLE or
1603 * memcg is too small and all pages are not on LRU. In that case,
1604 * we use curret node.
1606 if (unlikely(node == MAX_NUMNODES))
1607 node = numa_node_id();
1609 memcg->last_scanned_node = node;
1614 * Check all nodes whether it contains reclaimable pages or not.
1615 * For quick scan, we make use of scan_nodes. This will allow us to skip
1616 * unused nodes. But scan_nodes is lazily updated and may not cotain
1617 * enough new information. We need to do double check.
1619 bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
1624 * quick check...making use of scan_node.
1625 * We can skip unused nodes.
1627 if (!nodes_empty(memcg->scan_nodes)) {
1628 for (nid = first_node(memcg->scan_nodes);
1630 nid = next_node(nid, memcg->scan_nodes)) {
1632 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
1637 * Check rest of nodes.
1639 for_each_node_state(nid, N_HIGH_MEMORY) {
1640 if (node_isset(nid, memcg->scan_nodes))
1642 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
1649 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1654 bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
1656 return test_mem_cgroup_node_reclaimable(memcg, 0, noswap);
1660 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
1663 unsigned long *total_scanned)
1665 struct mem_cgroup *victim = NULL;
1668 unsigned long excess;
1669 unsigned long nr_scanned;
1670 struct mem_cgroup_reclaim_cookie reclaim = {
1675 excess = res_counter_soft_limit_excess(&root_memcg->res) >> PAGE_SHIFT;
1678 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1683 * If we have not been able to reclaim
1684 * anything, it might because there are
1685 * no reclaimable pages under this hierarchy
1690 * We want to do more targeted reclaim.
1691 * excess >> 2 is not to excessive so as to
1692 * reclaim too much, nor too less that we keep
1693 * coming back to reclaim from this cgroup
1695 if (total >= (excess >> 2) ||
1696 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1701 if (!mem_cgroup_reclaimable(victim, false))
1703 total += mem_cgroup_shrink_node_zone(victim, gfp_mask, false,
1705 *total_scanned += nr_scanned;
1706 if (!res_counter_soft_limit_excess(&root_memcg->res))
1709 mem_cgroup_iter_break(root_memcg, victim);
1714 * Check OOM-Killer is already running under our hierarchy.
1715 * If someone is running, return false.
1716 * Has to be called with memcg_oom_lock
1718 static bool mem_cgroup_oom_lock(struct mem_cgroup *memcg)
1720 struct mem_cgroup *iter, *failed = NULL;
1722 for_each_mem_cgroup_tree(iter, memcg) {
1723 if (iter->oom_lock) {
1725 * this subtree of our hierarchy is already locked
1726 * so we cannot give a lock.
1729 mem_cgroup_iter_break(memcg, iter);
1732 iter->oom_lock = true;
1739 * OK, we failed to lock the whole subtree so we have to clean up
1740 * what we set up to the failing subtree
1742 for_each_mem_cgroup_tree(iter, memcg) {
1743 if (iter == failed) {
1744 mem_cgroup_iter_break(memcg, iter);
1747 iter->oom_lock = false;
1753 * Has to be called with memcg_oom_lock
1755 static int mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1757 struct mem_cgroup *iter;
1759 for_each_mem_cgroup_tree(iter, memcg)
1760 iter->oom_lock = false;
1764 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1766 struct mem_cgroup *iter;
1768 for_each_mem_cgroup_tree(iter, memcg)
1769 atomic_inc(&iter->under_oom);
1772 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1774 struct mem_cgroup *iter;
1777 * When a new child is created while the hierarchy is under oom,
1778 * mem_cgroup_oom_lock() may not be called. We have to use
1779 * atomic_add_unless() here.
1781 for_each_mem_cgroup_tree(iter, memcg)
1782 atomic_add_unless(&iter->under_oom, -1, 0);
1785 static DEFINE_SPINLOCK(memcg_oom_lock);
1786 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1788 struct oom_wait_info {
1789 struct mem_cgroup *mem;
1793 static int memcg_oom_wake_function(wait_queue_t *wait,
1794 unsigned mode, int sync, void *arg)
1796 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg,
1798 struct oom_wait_info *oom_wait_info;
1800 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1801 oom_wait_memcg = oom_wait_info->mem;
1804 * Both of oom_wait_info->mem and wake_mem are stable under us.
1805 * Then we can use css_is_ancestor without taking care of RCU.
1807 if (!mem_cgroup_same_or_subtree(oom_wait_memcg, wake_memcg)
1808 && !mem_cgroup_same_or_subtree(wake_memcg, oom_wait_memcg))
1810 return autoremove_wake_function(wait, mode, sync, arg);
1813 static void memcg_wakeup_oom(struct mem_cgroup *memcg)
1815 /* for filtering, pass "memcg" as argument. */
1816 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
1819 static void memcg_oom_recover(struct mem_cgroup *memcg)
1821 if (memcg && atomic_read(&memcg->under_oom))
1822 memcg_wakeup_oom(memcg);
1826 * try to call OOM killer. returns false if we should exit memory-reclaim loop.
1828 bool mem_cgroup_handle_oom(struct mem_cgroup *memcg, gfp_t mask)
1830 struct oom_wait_info owait;
1831 bool locked, need_to_kill;
1834 owait.wait.flags = 0;
1835 owait.wait.func = memcg_oom_wake_function;
1836 owait.wait.private = current;
1837 INIT_LIST_HEAD(&owait.wait.task_list);
1838 need_to_kill = true;
1839 mem_cgroup_mark_under_oom(memcg);
1841 /* At first, try to OOM lock hierarchy under memcg.*/
1842 spin_lock(&memcg_oom_lock);
1843 locked = mem_cgroup_oom_lock(memcg);
1845 * Even if signal_pending(), we can't quit charge() loop without
1846 * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
1847 * under OOM is always welcomed, use TASK_KILLABLE here.
1849 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
1850 if (!locked || memcg->oom_kill_disable)
1851 need_to_kill = false;
1853 mem_cgroup_oom_notify(memcg);
1854 spin_unlock(&memcg_oom_lock);
1857 finish_wait(&memcg_oom_waitq, &owait.wait);
1858 mem_cgroup_out_of_memory(memcg, mask);
1861 finish_wait(&memcg_oom_waitq, &owait.wait);
1863 spin_lock(&memcg_oom_lock);
1865 mem_cgroup_oom_unlock(memcg);
1866 memcg_wakeup_oom(memcg);
1867 spin_unlock(&memcg_oom_lock);
1869 mem_cgroup_unmark_under_oom(memcg);
1871 if (test_thread_flag(TIF_MEMDIE) || fatal_signal_pending(current))
1873 /* Give chance to dying process */
1874 schedule_timeout_uninterruptible(1);
1879 * Currently used to update mapped file statistics, but the routine can be
1880 * generalized to update other statistics as well.
1882 * Notes: Race condition
1884 * We usually use page_cgroup_lock() for accessing page_cgroup member but
1885 * it tends to be costly. But considering some conditions, we doesn't need
1886 * to do so _always_.
1888 * Considering "charge", lock_page_cgroup() is not required because all
1889 * file-stat operations happen after a page is attached to radix-tree. There
1890 * are no race with "charge".
1892 * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
1893 * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
1894 * if there are race with "uncharge". Statistics itself is properly handled
1897 * Considering "move", this is an only case we see a race. To make the race
1898 * small, we check MEM_CGROUP_ON_MOVE percpu value and detect there are
1899 * possibility of race condition. If there is, we take a lock.
1902 void mem_cgroup_update_page_stat(struct page *page,
1903 enum mem_cgroup_page_stat_item idx, int val)
1905 struct mem_cgroup *memcg;
1906 struct page_cgroup *pc = lookup_page_cgroup(page);
1907 bool need_unlock = false;
1908 unsigned long uninitialized_var(flags);
1914 memcg = pc->mem_cgroup;
1915 if (unlikely(!memcg || !PageCgroupUsed(pc)))
1917 /* pc->mem_cgroup is unstable ? */
1918 if (unlikely(mem_cgroup_stealed(memcg)) || PageTransHuge(page)) {
1919 /* take a lock against to access pc->mem_cgroup */
1920 move_lock_page_cgroup(pc, &flags);
1922 memcg = pc->mem_cgroup;
1923 if (!memcg || !PageCgroupUsed(pc))
1928 case MEMCG_NR_FILE_MAPPED:
1930 SetPageCgroupFileMapped(pc);
1931 else if (!page_mapped(page))
1932 ClearPageCgroupFileMapped(pc);
1933 idx = MEM_CGROUP_STAT_FILE_MAPPED;
1939 this_cpu_add(memcg->stat->count[idx], val);
1942 if (unlikely(need_unlock))
1943 move_unlock_page_cgroup(pc, &flags);
1947 EXPORT_SYMBOL(mem_cgroup_update_page_stat);
1950 * size of first charge trial. "32" comes from vmscan.c's magic value.
1951 * TODO: maybe necessary to use big numbers in big irons.
1953 #define CHARGE_BATCH 32U
1954 struct memcg_stock_pcp {
1955 struct mem_cgroup *cached; /* this never be root cgroup */
1956 unsigned int nr_pages;
1957 struct work_struct work;
1958 unsigned long flags;
1959 #define FLUSHING_CACHED_CHARGE (0)
1961 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
1962 static DEFINE_MUTEX(percpu_charge_mutex);
1965 * Try to consume stocked charge on this cpu. If success, one page is consumed
1966 * from local stock and true is returned. If the stock is 0 or charges from a
1967 * cgroup which is not current target, returns false. This stock will be
1970 static bool consume_stock(struct mem_cgroup *memcg)
1972 struct memcg_stock_pcp *stock;
1975 stock = &get_cpu_var(memcg_stock);
1976 if (memcg == stock->cached && stock->nr_pages)
1978 else /* need to call res_counter_charge */
1980 put_cpu_var(memcg_stock);
1985 * Returns stocks cached in percpu to res_counter and reset cached information.
1987 static void drain_stock(struct memcg_stock_pcp *stock)
1989 struct mem_cgroup *old = stock->cached;
1991 if (stock->nr_pages) {
1992 unsigned long bytes = stock->nr_pages * PAGE_SIZE;
1994 res_counter_uncharge(&old->res, bytes);
1995 if (do_swap_account)
1996 res_counter_uncharge(&old->memsw, bytes);
1997 stock->nr_pages = 0;
1999 stock->cached = NULL;
2003 * This must be called under preempt disabled or must be called by
2004 * a thread which is pinned to local cpu.
2006 static void drain_local_stock(struct work_struct *dummy)
2008 struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
2010 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2014 * Cache charges(val) which is from res_counter, to local per_cpu area.
2015 * This will be consumed by consume_stock() function, later.
2017 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2019 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
2021 if (stock->cached != memcg) { /* reset if necessary */
2023 stock->cached = memcg;
2025 stock->nr_pages += nr_pages;
2026 put_cpu_var(memcg_stock);
2030 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2031 * of the hierarchy under it. sync flag says whether we should block
2032 * until the work is done.
2034 static void drain_all_stock(struct mem_cgroup *root_memcg, bool sync)
2038 /* Notify other cpus that system-wide "drain" is running */
2041 for_each_online_cpu(cpu) {
2042 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2043 struct mem_cgroup *memcg;
2045 memcg = stock->cached;
2046 if (!memcg || !stock->nr_pages)
2048 if (!mem_cgroup_same_or_subtree(root_memcg, memcg))
2050 if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2052 drain_local_stock(&stock->work);
2054 schedule_work_on(cpu, &stock->work);
2062 for_each_online_cpu(cpu) {
2063 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2064 if (test_bit(FLUSHING_CACHED_CHARGE, &stock->flags))
2065 flush_work(&stock->work);
2072 * Tries to drain stocked charges in other cpus. This function is asynchronous
2073 * and just put a work per cpu for draining localy on each cpu. Caller can
2074 * expects some charges will be back to res_counter later but cannot wait for
2077 static void drain_all_stock_async(struct mem_cgroup *root_memcg)
2080 * If someone calls draining, avoid adding more kworker runs.
2082 if (!mutex_trylock(&percpu_charge_mutex))
2084 drain_all_stock(root_memcg, false);
2085 mutex_unlock(&percpu_charge_mutex);
2088 /* This is a synchronous drain interface. */
2089 static void drain_all_stock_sync(struct mem_cgroup *root_memcg)
2091 /* called when force_empty is called */
2092 mutex_lock(&percpu_charge_mutex);
2093 drain_all_stock(root_memcg, true);
2094 mutex_unlock(&percpu_charge_mutex);
2098 * This function drains percpu counter value from DEAD cpu and
2099 * move it to local cpu. Note that this function can be preempted.
2101 static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *memcg, int cpu)
2105 spin_lock(&memcg->pcp_counter_lock);
2106 for (i = 0; i < MEM_CGROUP_STAT_DATA; i++) {
2107 long x = per_cpu(memcg->stat->count[i], cpu);
2109 per_cpu(memcg->stat->count[i], cpu) = 0;
2110 memcg->nocpu_base.count[i] += x;
2112 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
2113 unsigned long x = per_cpu(memcg->stat->events[i], cpu);
2115 per_cpu(memcg->stat->events[i], cpu) = 0;
2116 memcg->nocpu_base.events[i] += x;
2118 /* need to clear ON_MOVE value, works as a kind of lock. */
2119 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) = 0;
2120 spin_unlock(&memcg->pcp_counter_lock);
2123 static void synchronize_mem_cgroup_on_move(struct mem_cgroup *memcg, int cpu)
2125 int idx = MEM_CGROUP_ON_MOVE;
2127 spin_lock(&memcg->pcp_counter_lock);
2128 per_cpu(memcg->stat->count[idx], cpu) = memcg->nocpu_base.count[idx];
2129 spin_unlock(&memcg->pcp_counter_lock);
2132 static int __cpuinit memcg_cpu_hotplug_callback(struct notifier_block *nb,
2133 unsigned long action,
2136 int cpu = (unsigned long)hcpu;
2137 struct memcg_stock_pcp *stock;
2138 struct mem_cgroup *iter;
2140 if ((action == CPU_ONLINE)) {
2141 for_each_mem_cgroup(iter)
2142 synchronize_mem_cgroup_on_move(iter, cpu);
2146 if ((action != CPU_DEAD) || action != CPU_DEAD_FROZEN)
2149 for_each_mem_cgroup(iter)
2150 mem_cgroup_drain_pcp_counter(iter, cpu);
2152 stock = &per_cpu(memcg_stock, cpu);
2158 /* See __mem_cgroup_try_charge() for details */
2160 CHARGE_OK, /* success */
2161 CHARGE_RETRY, /* need to retry but retry is not bad */
2162 CHARGE_NOMEM, /* we can't do more. return -ENOMEM */
2163 CHARGE_WOULDBLOCK, /* GFP_WAIT wasn't set and no enough res. */
2164 CHARGE_OOM_DIE, /* the current is killed because of OOM */
2167 static int mem_cgroup_do_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2168 unsigned int nr_pages, bool oom_check)
2170 unsigned long csize = nr_pages * PAGE_SIZE;
2171 struct mem_cgroup *mem_over_limit;
2172 struct res_counter *fail_res;
2173 unsigned long flags = 0;
2176 ret = res_counter_charge(&memcg->res, csize, &fail_res);
2179 if (!do_swap_account)
2181 ret = res_counter_charge(&memcg->memsw, csize, &fail_res);
2185 res_counter_uncharge(&memcg->res, csize);
2186 mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw);
2187 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
2189 mem_over_limit = mem_cgroup_from_res_counter(fail_res, res);
2191 * nr_pages can be either a huge page (HPAGE_PMD_NR), a batch
2192 * of regular pages (CHARGE_BATCH), or a single regular page (1).
2194 * Never reclaim on behalf of optional batching, retry with a
2195 * single page instead.
2197 if (nr_pages == CHARGE_BATCH)
2198 return CHARGE_RETRY;
2200 if (!(gfp_mask & __GFP_WAIT))
2201 return CHARGE_WOULDBLOCK;
2203 ret = mem_cgroup_reclaim(mem_over_limit, gfp_mask, flags);
2204 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2205 return CHARGE_RETRY;
2207 * Even though the limit is exceeded at this point, reclaim
2208 * may have been able to free some pages. Retry the charge
2209 * before killing the task.
2211 * Only for regular pages, though: huge pages are rather
2212 * unlikely to succeed so close to the limit, and we fall back
2213 * to regular pages anyway in case of failure.
2215 if (nr_pages == 1 && ret)
2216 return CHARGE_RETRY;
2219 * At task move, charge accounts can be doubly counted. So, it's
2220 * better to wait until the end of task_move if something is going on.
2222 if (mem_cgroup_wait_acct_move(mem_over_limit))
2223 return CHARGE_RETRY;
2225 /* If we don't need to call oom-killer at el, return immediately */
2227 return CHARGE_NOMEM;
2229 if (!mem_cgroup_handle_oom(mem_over_limit, gfp_mask))
2230 return CHARGE_OOM_DIE;
2232 return CHARGE_RETRY;
2236 * Unlike exported interface, "oom" parameter is added. if oom==true,
2237 * oom-killer can be invoked.
2239 static int __mem_cgroup_try_charge(struct mm_struct *mm,
2241 unsigned int nr_pages,
2242 struct mem_cgroup **ptr,
2245 unsigned int batch = max(CHARGE_BATCH, nr_pages);
2246 int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2247 struct mem_cgroup *memcg = NULL;
2251 * Unlike gloval-vm's OOM-kill, we're not in memory shortage
2252 * in system level. So, allow to go ahead dying process in addition to
2255 if (unlikely(test_thread_flag(TIF_MEMDIE)
2256 || fatal_signal_pending(current)))
2260 * We always charge the cgroup the mm_struct belongs to.
2261 * The mm_struct's mem_cgroup changes on task migration if the
2262 * thread group leader migrates. It's possible that mm is not
2263 * set, if so charge the init_mm (happens for pagecache usage).
2268 if (*ptr) { /* css should be a valid one */
2270 VM_BUG_ON(css_is_removed(&memcg->css));
2271 if (mem_cgroup_is_root(memcg))
2273 if (nr_pages == 1 && consume_stock(memcg))
2275 css_get(&memcg->css);
2277 struct task_struct *p;
2280 p = rcu_dereference(mm->owner);
2282 * Because we don't have task_lock(), "p" can exit.
2283 * In that case, "memcg" can point to root or p can be NULL with
2284 * race with swapoff. Then, we have small risk of mis-accouning.
2285 * But such kind of mis-account by race always happens because
2286 * we don't have cgroup_mutex(). It's overkill and we allo that
2288 * (*) swapoff at el will charge against mm-struct not against
2289 * task-struct. So, mm->owner can be NULL.
2291 memcg = mem_cgroup_from_task(p);
2292 if (!memcg || mem_cgroup_is_root(memcg)) {
2296 if (nr_pages == 1 && consume_stock(memcg)) {
2298 * It seems dagerous to access memcg without css_get().
2299 * But considering how consume_stok works, it's not
2300 * necessary. If consume_stock success, some charges
2301 * from this memcg are cached on this cpu. So, we
2302 * don't need to call css_get()/css_tryget() before
2303 * calling consume_stock().
2308 /* after here, we may be blocked. we need to get refcnt */
2309 if (!css_tryget(&memcg->css)) {
2319 /* If killed, bypass charge */
2320 if (fatal_signal_pending(current)) {
2321 css_put(&memcg->css);
2326 if (oom && !nr_oom_retries) {
2328 nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2331 ret = mem_cgroup_do_charge(memcg, gfp_mask, batch, oom_check);
2335 case CHARGE_RETRY: /* not in OOM situation but retry */
2337 css_put(&memcg->css);
2340 case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
2341 css_put(&memcg->css);
2343 case CHARGE_NOMEM: /* OOM routine works */
2345 css_put(&memcg->css);
2348 /* If oom, we never return -ENOMEM */
2351 case CHARGE_OOM_DIE: /* Killed by OOM Killer */
2352 css_put(&memcg->css);
2355 } while (ret != CHARGE_OK);
2357 if (batch > nr_pages)
2358 refill_stock(memcg, batch - nr_pages);
2359 css_put(&memcg->css);
2372 * Somemtimes we have to undo a charge we got by try_charge().
2373 * This function is for that and do uncharge, put css's refcnt.
2374 * gotten by try_charge().
2376 static void __mem_cgroup_cancel_charge(struct mem_cgroup *memcg,
2377 unsigned int nr_pages)
2379 if (!mem_cgroup_is_root(memcg)) {
2380 unsigned long bytes = nr_pages * PAGE_SIZE;
2382 res_counter_uncharge(&memcg->res, bytes);
2383 if (do_swap_account)
2384 res_counter_uncharge(&memcg->memsw, bytes);
2389 * A helper function to get mem_cgroup from ID. must be called under
2390 * rcu_read_lock(). The caller must check css_is_removed() or some if
2391 * it's concern. (dropping refcnt from swap can be called against removed
2394 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
2396 struct cgroup_subsys_state *css;
2398 /* ID 0 is unused ID */
2401 css = css_lookup(&mem_cgroup_subsys, id);
2404 return container_of(css, struct mem_cgroup, css);
2407 struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
2409 struct mem_cgroup *memcg = NULL;
2410 struct page_cgroup *pc;
2414 VM_BUG_ON(!PageLocked(page));
2416 pc = lookup_page_cgroup(page);
2417 lock_page_cgroup(pc);
2418 if (PageCgroupUsed(pc)) {
2419 memcg = pc->mem_cgroup;
2420 if (memcg && !css_tryget(&memcg->css))
2422 } else if (PageSwapCache(page)) {
2423 ent.val = page_private(page);
2424 id = lookup_swap_cgroup(ent);
2426 memcg = mem_cgroup_lookup(id);
2427 if (memcg && !css_tryget(&memcg->css))
2431 unlock_page_cgroup(pc);
2435 static void __mem_cgroup_commit_charge(struct mem_cgroup *memcg,
2437 unsigned int nr_pages,
2438 struct page_cgroup *pc,
2439 enum charge_type ctype)
2441 lock_page_cgroup(pc);
2442 if (unlikely(PageCgroupUsed(pc))) {
2443 unlock_page_cgroup(pc);
2444 __mem_cgroup_cancel_charge(memcg, nr_pages);
2448 * we don't need page_cgroup_lock about tail pages, becase they are not
2449 * accessed by any other context at this point.
2451 pc->mem_cgroup = memcg;
2453 * We access a page_cgroup asynchronously without lock_page_cgroup().
2454 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
2455 * is accessed after testing USED bit. To make pc->mem_cgroup visible
2456 * before USED bit, we need memory barrier here.
2457 * See mem_cgroup_add_lru_list(), etc.
2461 case MEM_CGROUP_CHARGE_TYPE_CACHE:
2462 case MEM_CGROUP_CHARGE_TYPE_SHMEM:
2463 SetPageCgroupCache(pc);
2464 SetPageCgroupUsed(pc);
2466 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
2467 ClearPageCgroupCache(pc);
2468 SetPageCgroupUsed(pc);
2474 mem_cgroup_charge_statistics(memcg, PageCgroupCache(pc), nr_pages);
2475 unlock_page_cgroup(pc);
2477 * "charge_statistics" updated event counter. Then, check it.
2478 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
2479 * if they exceeds softlimit.
2481 memcg_check_events(memcg, page);
2484 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2486 #define PCGF_NOCOPY_AT_SPLIT ((1 << PCG_LOCK) | (1 << PCG_MOVE_LOCK) |\
2487 (1 << PCG_ACCT_LRU) | (1 << PCG_MIGRATION))
2489 * Because tail pages are not marked as "used", set it. We're under
2490 * zone->lru_lock, 'splitting on pmd' and compound_lock.
2491 * charge/uncharge will be never happen and move_account() is done under
2492 * compound_lock(), so we don't have to take care of races.
2494 void mem_cgroup_split_huge_fixup(struct page *head)
2496 struct page_cgroup *head_pc = lookup_page_cgroup(head);
2497 struct page_cgroup *pc;
2500 if (mem_cgroup_disabled())
2502 for (i = 1; i < HPAGE_PMD_NR; i++) {
2504 pc->mem_cgroup = head_pc->mem_cgroup;
2505 smp_wmb();/* see __commit_charge() */
2507 * LRU flags cannot be copied because we need to add tail
2508 * page to LRU by generic call and our hooks will be called.
2510 pc->flags = head_pc->flags & ~PCGF_NOCOPY_AT_SPLIT;
2513 if (PageCgroupAcctLRU(head_pc)) {
2515 struct mem_cgroup_per_zone *mz;
2517 * We hold lru_lock, then, reduce counter directly.
2519 lru = page_lru(head);
2520 mz = page_cgroup_zoneinfo(head_pc->mem_cgroup, head);
2521 MEM_CGROUP_ZSTAT(mz, lru) -= HPAGE_PMD_NR - 1;
2527 * mem_cgroup_move_account - move account of the page
2529 * @nr_pages: number of regular pages (>1 for huge pages)
2530 * @pc: page_cgroup of the page.
2531 * @from: mem_cgroup which the page is moved from.
2532 * @to: mem_cgroup which the page is moved to. @from != @to.
2533 * @uncharge: whether we should call uncharge and css_put against @from.
2535 * The caller must confirm following.
2536 * - page is not on LRU (isolate_page() is useful.)
2537 * - compound_lock is held when nr_pages > 1
2539 * This function doesn't do "charge" nor css_get to new cgroup. It should be
2540 * done by a caller(__mem_cgroup_try_charge would be useful). If @uncharge is
2541 * true, this function does "uncharge" from old cgroup, but it doesn't if
2542 * @uncharge is false, so a caller should do "uncharge".
2544 static int mem_cgroup_move_account(struct page *page,
2545 unsigned int nr_pages,
2546 struct page_cgroup *pc,
2547 struct mem_cgroup *from,
2548 struct mem_cgroup *to,
2551 unsigned long flags;
2554 VM_BUG_ON(from == to);
2555 VM_BUG_ON(PageLRU(page));
2557 * The page is isolated from LRU. So, collapse function
2558 * will not handle this page. But page splitting can happen.
2559 * Do this check under compound_page_lock(). The caller should
2563 if (nr_pages > 1 && !PageTransHuge(page))
2566 lock_page_cgroup(pc);
2569 if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
2572 move_lock_page_cgroup(pc, &flags);
2574 if (PageCgroupFileMapped(pc)) {
2575 /* Update mapped_file data for mem_cgroup */
2577 __this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2578 __this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2581 mem_cgroup_charge_statistics(from, PageCgroupCache(pc), -nr_pages);
2583 /* This is not "cancel", but cancel_charge does all we need. */
2584 __mem_cgroup_cancel_charge(from, nr_pages);
2586 /* caller should have done css_get */
2587 pc->mem_cgroup = to;
2588 mem_cgroup_charge_statistics(to, PageCgroupCache(pc), nr_pages);
2590 * We charges against "to" which may not have any tasks. Then, "to"
2591 * can be under rmdir(). But in current implementation, caller of
2592 * this function is just force_empty() and move charge, so it's
2593 * guaranteed that "to" is never removed. So, we don't check rmdir
2596 move_unlock_page_cgroup(pc, &flags);
2599 unlock_page_cgroup(pc);
2603 memcg_check_events(to, page);
2604 memcg_check_events(from, page);
2610 * move charges to its parent.
2613 static int mem_cgroup_move_parent(struct page *page,
2614 struct page_cgroup *pc,
2615 struct mem_cgroup *child,
2618 struct cgroup *cg = child->css.cgroup;
2619 struct cgroup *pcg = cg->parent;
2620 struct mem_cgroup *parent;
2621 unsigned int nr_pages;
2622 unsigned long uninitialized_var(flags);
2630 if (!get_page_unless_zero(page))
2632 if (isolate_lru_page(page))
2635 nr_pages = hpage_nr_pages(page);
2637 parent = mem_cgroup_from_cont(pcg);
2638 ret = __mem_cgroup_try_charge(NULL, gfp_mask, nr_pages, &parent, false);
2643 flags = compound_lock_irqsave(page);
2645 ret = mem_cgroup_move_account(page, nr_pages, pc, child, parent, true);
2647 __mem_cgroup_cancel_charge(parent, nr_pages);
2650 compound_unlock_irqrestore(page, flags);
2652 putback_lru_page(page);
2660 * Charge the memory controller for page usage.
2662 * 0 if the charge was successful
2663 * < 0 if the cgroup is over its limit
2665 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
2666 gfp_t gfp_mask, enum charge_type ctype)
2668 struct mem_cgroup *memcg = NULL;
2669 unsigned int nr_pages = 1;
2670 struct page_cgroup *pc;
2674 if (PageTransHuge(page)) {
2675 nr_pages <<= compound_order(page);
2676 VM_BUG_ON(!PageTransHuge(page));
2678 * Never OOM-kill a process for a huge page. The
2679 * fault handler will fall back to regular pages.
2684 pc = lookup_page_cgroup(page);
2685 BUG_ON(!pc); /* XXX: remove this and move pc lookup into commit */
2687 ret = __mem_cgroup_try_charge(mm, gfp_mask, nr_pages, &memcg, oom);
2691 __mem_cgroup_commit_charge(memcg, page, nr_pages, pc, ctype);
2695 int mem_cgroup_newpage_charge(struct page *page,
2696 struct mm_struct *mm, gfp_t gfp_mask)
2698 if (mem_cgroup_disabled())
2701 * If already mapped, we don't have to account.
2702 * If page cache, page->mapping has address_space.
2703 * But page->mapping may have out-of-use anon_vma pointer,
2704 * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
2707 if (page_mapped(page) || (page->mapping && !PageAnon(page)))
2711 return mem_cgroup_charge_common(page, mm, gfp_mask,
2712 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2716 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2717 enum charge_type ctype);
2720 __mem_cgroup_commit_charge_lrucare(struct page *page, struct mem_cgroup *memcg,
2721 enum charge_type ctype)
2723 struct page_cgroup *pc = lookup_page_cgroup(page);
2725 * In some case, SwapCache, FUSE(splice_buf->radixtree), the page
2726 * is already on LRU. It means the page may on some other page_cgroup's
2727 * LRU. Take care of it.
2729 mem_cgroup_lru_del_before_commit(page);
2730 __mem_cgroup_commit_charge(memcg, page, 1, pc, ctype);
2731 mem_cgroup_lru_add_after_commit(page);
2735 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
2738 struct mem_cgroup *memcg = NULL;
2741 if (mem_cgroup_disabled())
2743 if (PageCompound(page))
2749 if (page_is_file_cache(page)) {
2750 ret = __mem_cgroup_try_charge(mm, gfp_mask, 1, &memcg, true);
2755 * FUSE reuses pages without going through the final
2756 * put that would remove them from the LRU list, make
2757 * sure that they get relinked properly.
2759 __mem_cgroup_commit_charge_lrucare(page, memcg,
2760 MEM_CGROUP_CHARGE_TYPE_CACHE);
2764 if (PageSwapCache(page)) {
2765 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &memcg);
2767 __mem_cgroup_commit_charge_swapin(page, memcg,
2768 MEM_CGROUP_CHARGE_TYPE_SHMEM);
2770 ret = mem_cgroup_charge_common(page, mm, gfp_mask,
2771 MEM_CGROUP_CHARGE_TYPE_SHMEM);
2777 * While swap-in, try_charge -> commit or cancel, the page is locked.
2778 * And when try_charge() successfully returns, one refcnt to memcg without
2779 * struct page_cgroup is acquired. This refcnt will be consumed by
2780 * "commit()" or removed by "cancel()"
2782 int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
2784 gfp_t mask, struct mem_cgroup **ptr)
2786 struct mem_cgroup *memcg;
2791 if (mem_cgroup_disabled())
2794 if (!do_swap_account)
2797 * A racing thread's fault, or swapoff, may have already updated
2798 * the pte, and even removed page from swap cache: in those cases
2799 * do_swap_page()'s pte_same() test will fail; but there's also a
2800 * KSM case which does need to charge the page.
2802 if (!PageSwapCache(page))
2804 memcg = try_get_mem_cgroup_from_page(page);
2808 ret = __mem_cgroup_try_charge(NULL, mask, 1, ptr, true);
2809 css_put(&memcg->css);
2814 return __mem_cgroup_try_charge(mm, mask, 1, ptr, true);
2818 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2819 enum charge_type ctype)
2821 if (mem_cgroup_disabled())
2825 cgroup_exclude_rmdir(&ptr->css);
2827 __mem_cgroup_commit_charge_lrucare(page, ptr, ctype);
2829 * Now swap is on-memory. This means this page may be
2830 * counted both as mem and swap....double count.
2831 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
2832 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
2833 * may call delete_from_swap_cache() before reach here.
2835 if (do_swap_account && PageSwapCache(page)) {
2836 swp_entry_t ent = {.val = page_private(page)};
2838 struct mem_cgroup *memcg;
2840 id = swap_cgroup_record(ent, 0);
2842 memcg = mem_cgroup_lookup(id);
2845 * This recorded memcg can be obsolete one. So, avoid
2846 * calling css_tryget
2848 if (!mem_cgroup_is_root(memcg))
2849 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
2850 mem_cgroup_swap_statistics(memcg, false);
2851 mem_cgroup_put(memcg);
2856 * At swapin, we may charge account against cgroup which has no tasks.
2857 * So, rmdir()->pre_destroy() can be called while we do this charge.
2858 * In that case, we need to call pre_destroy() again. check it here.
2860 cgroup_release_and_wakeup_rmdir(&ptr->css);
2863 void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
2865 __mem_cgroup_commit_charge_swapin(page, ptr,
2866 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2869 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *memcg)
2871 if (mem_cgroup_disabled())
2875 __mem_cgroup_cancel_charge(memcg, 1);
2878 static void mem_cgroup_do_uncharge(struct mem_cgroup *memcg,
2879 unsigned int nr_pages,
2880 const enum charge_type ctype)
2882 struct memcg_batch_info *batch = NULL;
2883 bool uncharge_memsw = true;
2885 /* If swapout, usage of swap doesn't decrease */
2886 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2887 uncharge_memsw = false;
2889 batch = ¤t->memcg_batch;
2891 * In usual, we do css_get() when we remember memcg pointer.
2892 * But in this case, we keep res->usage until end of a series of
2893 * uncharges. Then, it's ok to ignore memcg's refcnt.
2896 batch->memcg = memcg;
2898 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
2899 * In those cases, all pages freed continuously can be expected to be in
2900 * the same cgroup and we have chance to coalesce uncharges.
2901 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
2902 * because we want to do uncharge as soon as possible.
2905 if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
2906 goto direct_uncharge;
2909 goto direct_uncharge;
2912 * In typical case, batch->memcg == mem. This means we can
2913 * merge a series of uncharges to an uncharge of res_counter.
2914 * If not, we uncharge res_counter ony by one.
2916 if (batch->memcg != memcg)
2917 goto direct_uncharge;
2918 /* remember freed charge and uncharge it later */
2921 batch->memsw_nr_pages++;
2924 res_counter_uncharge(&memcg->res, nr_pages * PAGE_SIZE);
2926 res_counter_uncharge(&memcg->memsw, nr_pages * PAGE_SIZE);
2927 if (unlikely(batch->memcg != memcg))
2928 memcg_oom_recover(memcg);
2933 * uncharge if !page_mapped(page)
2935 static struct mem_cgroup *
2936 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
2938 struct mem_cgroup *memcg = NULL;
2939 unsigned int nr_pages = 1;
2940 struct page_cgroup *pc;
2942 if (mem_cgroup_disabled())
2945 if (PageSwapCache(page))
2948 if (PageTransHuge(page)) {
2949 nr_pages <<= compound_order(page);
2950 VM_BUG_ON(!PageTransHuge(page));
2953 * Check if our page_cgroup is valid
2955 pc = lookup_page_cgroup(page);
2956 if (unlikely(!pc || !PageCgroupUsed(pc)))
2959 lock_page_cgroup(pc);
2961 memcg = pc->mem_cgroup;
2963 if (!PageCgroupUsed(pc))
2967 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
2968 case MEM_CGROUP_CHARGE_TYPE_DROP:
2969 /* See mem_cgroup_prepare_migration() */
2970 if (page_mapped(page) || PageCgroupMigration(pc))
2973 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
2974 if (!PageAnon(page)) { /* Shared memory */
2975 if (page->mapping && !page_is_file_cache(page))
2977 } else if (page_mapped(page)) /* Anon */
2984 mem_cgroup_charge_statistics(memcg, PageCgroupCache(pc), -nr_pages);
2986 ClearPageCgroupUsed(pc);
2988 * pc->mem_cgroup is not cleared here. It will be accessed when it's
2989 * freed from LRU. This is safe because uncharged page is expected not
2990 * to be reused (freed soon). Exception is SwapCache, it's handled by
2991 * special functions.
2994 unlock_page_cgroup(pc);
2996 * even after unlock, we have memcg->res.usage here and this memcg
2997 * will never be freed.
2999 memcg_check_events(memcg, page);
3000 if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
3001 mem_cgroup_swap_statistics(memcg, true);
3002 mem_cgroup_get(memcg);
3004 if (!mem_cgroup_is_root(memcg))
3005 mem_cgroup_do_uncharge(memcg, nr_pages, ctype);
3010 unlock_page_cgroup(pc);
3014 void mem_cgroup_uncharge_page(struct page *page)
3017 if (page_mapped(page))
3019 if (page->mapping && !PageAnon(page))
3021 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
3024 void mem_cgroup_uncharge_cache_page(struct page *page)
3026 VM_BUG_ON(page_mapped(page));
3027 VM_BUG_ON(page->mapping);
3028 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
3032 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
3033 * In that cases, pages are freed continuously and we can expect pages
3034 * are in the same memcg. All these calls itself limits the number of
3035 * pages freed at once, then uncharge_start/end() is called properly.
3036 * This may be called prural(2) times in a context,
3039 void mem_cgroup_uncharge_start(void)
3041 current->memcg_batch.do_batch++;
3042 /* We can do nest. */
3043 if (current->memcg_batch.do_batch == 1) {
3044 current->memcg_batch.memcg = NULL;
3045 current->memcg_batch.nr_pages = 0;
3046 current->memcg_batch.memsw_nr_pages = 0;
3050 void mem_cgroup_uncharge_end(void)
3052 struct memcg_batch_info *batch = ¤t->memcg_batch;
3054 if (!batch->do_batch)
3058 if (batch->do_batch) /* If stacked, do nothing. */
3064 * This "batch->memcg" is valid without any css_get/put etc...
3065 * bacause we hide charges behind us.
3067 if (batch->nr_pages)
3068 res_counter_uncharge(&batch->memcg->res,
3069 batch->nr_pages * PAGE_SIZE);
3070 if (batch->memsw_nr_pages)
3071 res_counter_uncharge(&batch->memcg->memsw,
3072 batch->memsw_nr_pages * PAGE_SIZE);
3073 memcg_oom_recover(batch->memcg);
3074 /* forget this pointer (for sanity check) */
3075 batch->memcg = NULL;
3080 * called after __delete_from_swap_cache() and drop "page" account.
3081 * memcg information is recorded to swap_cgroup of "ent"
3084 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
3086 struct mem_cgroup *memcg;
3087 int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
3089 if (!swapout) /* this was a swap cache but the swap is unused ! */
3090 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
3092 memcg = __mem_cgroup_uncharge_common(page, ctype);
3095 * record memcg information, if swapout && memcg != NULL,
3096 * mem_cgroup_get() was called in uncharge().
3098 if (do_swap_account && swapout && memcg)
3099 swap_cgroup_record(ent, css_id(&memcg->css));
3103 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3105 * called from swap_entry_free(). remove record in swap_cgroup and
3106 * uncharge "memsw" account.
3108 void mem_cgroup_uncharge_swap(swp_entry_t ent)
3110 struct mem_cgroup *memcg;
3113 if (!do_swap_account)
3116 id = swap_cgroup_record(ent, 0);
3118 memcg = mem_cgroup_lookup(id);
3121 * We uncharge this because swap is freed.
3122 * This memcg can be obsolete one. We avoid calling css_tryget
3124 if (!mem_cgroup_is_root(memcg))
3125 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
3126 mem_cgroup_swap_statistics(memcg, false);
3127 mem_cgroup_put(memcg);
3133 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3134 * @entry: swap entry to be moved
3135 * @from: mem_cgroup which the entry is moved from
3136 * @to: mem_cgroup which the entry is moved to
3137 * @need_fixup: whether we should fixup res_counters and refcounts.
3139 * It succeeds only when the swap_cgroup's record for this entry is the same
3140 * as the mem_cgroup's id of @from.
3142 * Returns 0 on success, -EINVAL on failure.
3144 * The caller must have charged to @to, IOW, called res_counter_charge() about
3145 * both res and memsw, and called css_get().
3147 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3148 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
3150 unsigned short old_id, new_id;
3152 old_id = css_id(&from->css);
3153 new_id = css_id(&to->css);
3155 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3156 mem_cgroup_swap_statistics(from, false);
3157 mem_cgroup_swap_statistics(to, true);
3159 * This function is only called from task migration context now.
3160 * It postpones res_counter and refcount handling till the end
3161 * of task migration(mem_cgroup_clear_mc()) for performance
3162 * improvement. But we cannot postpone mem_cgroup_get(to)
3163 * because if the process that has been moved to @to does
3164 * swap-in, the refcount of @to might be decreased to 0.
3168 if (!mem_cgroup_is_root(from))
3169 res_counter_uncharge(&from->memsw, PAGE_SIZE);
3170 mem_cgroup_put(from);
3172 * we charged both to->res and to->memsw, so we should
3175 if (!mem_cgroup_is_root(to))
3176 res_counter_uncharge(&to->res, PAGE_SIZE);
3183 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3184 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
3191 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
3194 int mem_cgroup_prepare_migration(struct page *page,
3195 struct page *newpage, struct mem_cgroup **ptr, gfp_t gfp_mask)
3197 struct mem_cgroup *memcg = NULL;
3198 struct page_cgroup *pc;
3199 enum charge_type ctype;
3204 VM_BUG_ON(PageTransHuge(page));
3205 if (mem_cgroup_disabled())
3208 pc = lookup_page_cgroup(page);
3209 lock_page_cgroup(pc);
3210 if (PageCgroupUsed(pc)) {
3211 memcg = pc->mem_cgroup;
3212 css_get(&memcg->css);
3214 * At migrating an anonymous page, its mapcount goes down
3215 * to 0 and uncharge() will be called. But, even if it's fully
3216 * unmapped, migration may fail and this page has to be
3217 * charged again. We set MIGRATION flag here and delay uncharge
3218 * until end_migration() is called
3220 * Corner Case Thinking
3222 * When the old page was mapped as Anon and it's unmap-and-freed
3223 * while migration was ongoing.
3224 * If unmap finds the old page, uncharge() of it will be delayed
3225 * until end_migration(). If unmap finds a new page, it's
3226 * uncharged when it make mapcount to be 1->0. If unmap code
3227 * finds swap_migration_entry, the new page will not be mapped
3228 * and end_migration() will find it(mapcount==0).
3231 * When the old page was mapped but migraion fails, the kernel
3232 * remaps it. A charge for it is kept by MIGRATION flag even
3233 * if mapcount goes down to 0. We can do remap successfully
3234 * without charging it again.
3237 * The "old" page is under lock_page() until the end of
3238 * migration, so, the old page itself will not be swapped-out.
3239 * If the new page is swapped out before end_migraton, our
3240 * hook to usual swap-out path will catch the event.
3243 SetPageCgroupMigration(pc);
3245 unlock_page_cgroup(pc);
3247 * If the page is not charged at this point,
3254 ret = __mem_cgroup_try_charge(NULL, gfp_mask, 1, ptr, false);
3255 css_put(&memcg->css);/* drop extra refcnt */
3256 if (ret || *ptr == NULL) {
3257 if (PageAnon(page)) {
3258 lock_page_cgroup(pc);
3259 ClearPageCgroupMigration(pc);
3260 unlock_page_cgroup(pc);
3262 * The old page may be fully unmapped while we kept it.
3264 mem_cgroup_uncharge_page(page);
3269 * We charge new page before it's used/mapped. So, even if unlock_page()
3270 * is called before end_migration, we can catch all events on this new
3271 * page. In the case new page is migrated but not remapped, new page's
3272 * mapcount will be finally 0 and we call uncharge in end_migration().
3274 pc = lookup_page_cgroup(newpage);
3276 ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
3277 else if (page_is_file_cache(page))
3278 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
3280 ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
3281 __mem_cgroup_commit_charge(memcg, page, 1, pc, ctype);
3285 /* remove redundant charge if migration failed*/
3286 void mem_cgroup_end_migration(struct mem_cgroup *memcg,
3287 struct page *oldpage, struct page *newpage, bool migration_ok)
3289 struct page *used, *unused;
3290 struct page_cgroup *pc;
3294 /* blocks rmdir() */
3295 cgroup_exclude_rmdir(&memcg->css);
3296 if (!migration_ok) {
3304 * We disallowed uncharge of pages under migration because mapcount
3305 * of the page goes down to zero, temporarly.
3306 * Clear the flag and check the page should be charged.
3308 pc = lookup_page_cgroup(oldpage);
3309 lock_page_cgroup(pc);
3310 ClearPageCgroupMigration(pc);
3311 unlock_page_cgroup(pc);
3313 __mem_cgroup_uncharge_common(unused, MEM_CGROUP_CHARGE_TYPE_FORCE);
3316 * If a page is a file cache, radix-tree replacement is very atomic
3317 * and we can skip this check. When it was an Anon page, its mapcount
3318 * goes down to 0. But because we added MIGRATION flage, it's not
3319 * uncharged yet. There are several case but page->mapcount check
3320 * and USED bit check in mem_cgroup_uncharge_page() will do enough
3321 * check. (see prepare_charge() also)
3324 mem_cgroup_uncharge_page(used);
3326 * At migration, we may charge account against cgroup which has no
3328 * So, rmdir()->pre_destroy() can be called while we do this charge.
3329 * In that case, we need to call pre_destroy() again. check it here.
3331 cgroup_release_and_wakeup_rmdir(&memcg->css);
3334 #ifdef CONFIG_DEBUG_VM
3335 static struct page_cgroup *lookup_page_cgroup_used(struct page *page)
3337 struct page_cgroup *pc;
3339 pc = lookup_page_cgroup(page);
3340 if (likely(pc) && PageCgroupUsed(pc))
3345 bool mem_cgroup_bad_page_check(struct page *page)
3347 if (mem_cgroup_disabled())
3350 return lookup_page_cgroup_used(page) != NULL;
3353 void mem_cgroup_print_bad_page(struct page *page)
3355 struct page_cgroup *pc;
3357 pc = lookup_page_cgroup_used(page);
3362 printk(KERN_ALERT "pc:%p pc->flags:%lx pc->mem_cgroup:%p",
3363 pc, pc->flags, pc->mem_cgroup);
3365 path = kmalloc(PATH_MAX, GFP_KERNEL);
3368 ret = cgroup_path(pc->mem_cgroup->css.cgroup,
3373 printk(KERN_CONT "(%s)\n",
3374 (ret < 0) ? "cannot get the path" : path);
3380 static DEFINE_MUTEX(set_limit_mutex);
3382 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
3383 unsigned long long val)
3386 u64 memswlimit, memlimit;
3388 int children = mem_cgroup_count_children(memcg);
3389 u64 curusage, oldusage;
3393 * For keeping hierarchical_reclaim simple, how long we should retry
3394 * is depends on callers. We set our retry-count to be function
3395 * of # of children which we should visit in this loop.
3397 retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
3399 oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
3402 while (retry_count) {
3403 if (signal_pending(current)) {
3408 * Rather than hide all in some function, I do this in
3409 * open coded manner. You see what this really does.
3410 * We have to guarantee memcg->res.limit < memcg->memsw.limit.
3412 mutex_lock(&set_limit_mutex);
3413 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3414 if (memswlimit < val) {
3416 mutex_unlock(&set_limit_mutex);
3420 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3424 ret = res_counter_set_limit(&memcg->res, val);
3426 if (memswlimit == val)
3427 memcg->memsw_is_minimum = true;
3429 memcg->memsw_is_minimum = false;
3431 mutex_unlock(&set_limit_mutex);
3436 mem_cgroup_reclaim(memcg, GFP_KERNEL,
3437 MEM_CGROUP_RECLAIM_SHRINK);
3438 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
3439 /* Usage is reduced ? */
3440 if (curusage >= oldusage)
3443 oldusage = curusage;
3445 if (!ret && enlarge)
3446 memcg_oom_recover(memcg);
3451 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
3452 unsigned long long val)
3455 u64 memlimit, memswlimit, oldusage, curusage;
3456 int children = mem_cgroup_count_children(memcg);
3460 /* see mem_cgroup_resize_res_limit */
3461 retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
3462 oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
3463 while (retry_count) {
3464 if (signal_pending(current)) {
3469 * Rather than hide all in some function, I do this in
3470 * open coded manner. You see what this really does.
3471 * We have to guarantee memcg->res.limit < memcg->memsw.limit.
3473 mutex_lock(&set_limit_mutex);
3474 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3475 if (memlimit > val) {
3477 mutex_unlock(&set_limit_mutex);
3480 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3481 if (memswlimit < val)
3483 ret = res_counter_set_limit(&memcg->memsw, val);
3485 if (memlimit == val)
3486 memcg->memsw_is_minimum = true;
3488 memcg->memsw_is_minimum = false;
3490 mutex_unlock(&set_limit_mutex);
3495 mem_cgroup_reclaim(memcg, GFP_KERNEL,
3496 MEM_CGROUP_RECLAIM_NOSWAP |
3497 MEM_CGROUP_RECLAIM_SHRINK);
3498 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
3499 /* Usage is reduced ? */
3500 if (curusage >= oldusage)
3503 oldusage = curusage;
3505 if (!ret && enlarge)
3506 memcg_oom_recover(memcg);
3510 unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
3512 unsigned long *total_scanned)
3514 unsigned long nr_reclaimed = 0;
3515 struct mem_cgroup_per_zone *mz, *next_mz = NULL;
3516 unsigned long reclaimed;
3518 struct mem_cgroup_tree_per_zone *mctz;
3519 unsigned long long excess;
3520 unsigned long nr_scanned;
3525 mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
3527 * This loop can run a while, specially if mem_cgroup's continuously
3528 * keep exceeding their soft limit and putting the system under
3535 mz = mem_cgroup_largest_soft_limit_node(mctz);
3540 reclaimed = mem_cgroup_soft_reclaim(mz->mem, zone,
3541 gfp_mask, &nr_scanned);
3542 nr_reclaimed += reclaimed;
3543 *total_scanned += nr_scanned;
3544 spin_lock(&mctz->lock);
3547 * If we failed to reclaim anything from this memory cgroup
3548 * it is time to move on to the next cgroup
3554 * Loop until we find yet another one.
3556 * By the time we get the soft_limit lock
3557 * again, someone might have aded the
3558 * group back on the RB tree. Iterate to
3559 * make sure we get a different mem.
3560 * mem_cgroup_largest_soft_limit_node returns
3561 * NULL if no other cgroup is present on
3565 __mem_cgroup_largest_soft_limit_node(mctz);
3567 css_put(&next_mz->mem->css);
3568 else /* next_mz == NULL or other memcg */
3572 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
3573 excess = res_counter_soft_limit_excess(&mz->mem->res);
3575 * One school of thought says that we should not add
3576 * back the node to the tree if reclaim returns 0.
3577 * But our reclaim could return 0, simply because due
3578 * to priority we are exposing a smaller subset of
3579 * memory to reclaim from. Consider this as a longer
3582 /* If excess == 0, no tree ops */
3583 __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
3584 spin_unlock(&mctz->lock);
3585 css_put(&mz->mem->css);
3588 * Could not reclaim anything and there are no more
3589 * mem cgroups to try or we seem to be looping without
3590 * reclaiming anything.
3592 if (!nr_reclaimed &&
3594 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3596 } while (!nr_reclaimed);
3598 css_put(&next_mz->mem->css);
3599 return nr_reclaimed;
3603 * This routine traverse page_cgroup in given list and drop them all.
3604 * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
3606 static int mem_cgroup_force_empty_list(struct mem_cgroup *memcg,
3607 int node, int zid, enum lru_list lru)
3609 struct mem_cgroup_per_zone *mz;
3610 unsigned long flags, loop;
3611 struct list_head *list;
3616 zone = &NODE_DATA(node)->node_zones[zid];
3617 mz = mem_cgroup_zoneinfo(memcg, node, zid);
3618 list = &mz->lruvec.lists[lru];
3620 loop = MEM_CGROUP_ZSTAT(mz, lru);
3621 /* give some margin against EBUSY etc...*/
3625 struct page_cgroup *pc;
3629 spin_lock_irqsave(&zone->lru_lock, flags);
3630 if (list_empty(list)) {
3631 spin_unlock_irqrestore(&zone->lru_lock, flags);
3634 page = list_entry(list->prev, struct page, lru);
3636 list_move(&page->lru, list);
3638 spin_unlock_irqrestore(&zone->lru_lock, flags);
3641 spin_unlock_irqrestore(&zone->lru_lock, flags);
3643 pc = lookup_page_cgroup(page);
3645 ret = mem_cgroup_move_parent(page, pc, memcg, GFP_KERNEL);
3649 if (ret == -EBUSY || ret == -EINVAL) {
3650 /* found lock contention or "pc" is obsolete. */
3657 if (!ret && !list_empty(list))
3663 * make mem_cgroup's charge to be 0 if there is no task.
3664 * This enables deleting this mem_cgroup.
3666 static int mem_cgroup_force_empty(struct mem_cgroup *memcg, bool free_all)
3669 int node, zid, shrink;
3670 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
3671 struct cgroup *cgrp = memcg->css.cgroup;
3673 css_get(&memcg->css);
3676 /* should free all ? */
3682 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
3685 if (signal_pending(current))
3687 /* This is for making all *used* pages to be on LRU. */
3688 lru_add_drain_all();
3689 drain_all_stock_sync(memcg);
3691 mem_cgroup_start_move(memcg);
3692 for_each_node_state(node, N_HIGH_MEMORY) {
3693 for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
3696 ret = mem_cgroup_force_empty_list(memcg,
3705 mem_cgroup_end_move(memcg);
3706 memcg_oom_recover(memcg);
3707 /* it seems parent cgroup doesn't have enough mem */
3711 /* "ret" should also be checked to ensure all lists are empty. */
3712 } while (memcg->res.usage > 0 || ret);
3714 css_put(&memcg->css);
3718 /* returns EBUSY if there is a task or if we come here twice. */
3719 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
3723 /* we call try-to-free pages for make this cgroup empty */
3724 lru_add_drain_all();
3725 /* try to free all pages in this cgroup */
3727 while (nr_retries && memcg->res.usage > 0) {
3730 if (signal_pending(current)) {
3734 progress = try_to_free_mem_cgroup_pages(memcg, GFP_KERNEL,
3738 /* maybe some writeback is necessary */
3739 congestion_wait(BLK_RW_ASYNC, HZ/10);
3744 /* try move_account...there may be some *locked* pages. */
3748 int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
3750 return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
3754 static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
3756 return mem_cgroup_from_cont(cont)->use_hierarchy;
3759 static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
3763 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3764 struct cgroup *parent = cont->parent;
3765 struct mem_cgroup *parent_memcg = NULL;
3768 parent_memcg = mem_cgroup_from_cont(parent);
3772 * If parent's use_hierarchy is set, we can't make any modifications
3773 * in the child subtrees. If it is unset, then the change can
3774 * occur, provided the current cgroup has no children.
3776 * For the root cgroup, parent_mem is NULL, we allow value to be
3777 * set if there are no children.
3779 if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
3780 (val == 1 || val == 0)) {
3781 if (list_empty(&cont->children))
3782 memcg->use_hierarchy = val;
3793 static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup *memcg,
3794 enum mem_cgroup_stat_index idx)
3796 struct mem_cgroup *iter;
3799 /* Per-cpu values can be negative, use a signed accumulator */
3800 for_each_mem_cgroup_tree(iter, memcg)
3801 val += mem_cgroup_read_stat(iter, idx);
3803 if (val < 0) /* race ? */
3808 static inline u64 mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3812 if (!mem_cgroup_is_root(memcg)) {
3814 return res_counter_read_u64(&memcg->res, RES_USAGE);
3816 return res_counter_read_u64(&memcg->memsw, RES_USAGE);
3819 val = mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_CACHE);
3820 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_RSS);
3823 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_SWAPOUT);
3825 return val << PAGE_SHIFT;
3828 static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
3830 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3834 type = MEMFILE_TYPE(cft->private);
3835 name = MEMFILE_ATTR(cft->private);
3838 if (name == RES_USAGE)
3839 val = mem_cgroup_usage(memcg, false);
3841 val = res_counter_read_u64(&memcg->res, name);
3844 if (name == RES_USAGE)
3845 val = mem_cgroup_usage(memcg, true);
3847 val = res_counter_read_u64(&memcg->memsw, name);
3856 * The user of this function is...
3859 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
3862 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3864 unsigned long long val;
3867 type = MEMFILE_TYPE(cft->private);
3868 name = MEMFILE_ATTR(cft->private);
3871 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3875 /* This function does all necessary parse...reuse it */
3876 ret = res_counter_memparse_write_strategy(buffer, &val);
3880 ret = mem_cgroup_resize_limit(memcg, val);
3882 ret = mem_cgroup_resize_memsw_limit(memcg, val);
3884 case RES_SOFT_LIMIT:
3885 ret = res_counter_memparse_write_strategy(buffer, &val);
3889 * For memsw, soft limits are hard to implement in terms
3890 * of semantics, for now, we support soft limits for
3891 * control without swap
3894 ret = res_counter_set_soft_limit(&memcg->res, val);
3899 ret = -EINVAL; /* should be BUG() ? */
3905 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
3906 unsigned long long *mem_limit, unsigned long long *memsw_limit)
3908 struct cgroup *cgroup;
3909 unsigned long long min_limit, min_memsw_limit, tmp;
3911 min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3912 min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3913 cgroup = memcg->css.cgroup;
3914 if (!memcg->use_hierarchy)
3917 while (cgroup->parent) {
3918 cgroup = cgroup->parent;
3919 memcg = mem_cgroup_from_cont(cgroup);
3920 if (!memcg->use_hierarchy)
3922 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
3923 min_limit = min(min_limit, tmp);
3924 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3925 min_memsw_limit = min(min_memsw_limit, tmp);
3928 *mem_limit = min_limit;
3929 *memsw_limit = min_memsw_limit;
3933 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
3935 struct mem_cgroup *memcg;
3938 memcg = mem_cgroup_from_cont(cont);
3939 type = MEMFILE_TYPE(event);
3940 name = MEMFILE_ATTR(event);
3944 res_counter_reset_max(&memcg->res);
3946 res_counter_reset_max(&memcg->memsw);
3950 res_counter_reset_failcnt(&memcg->res);
3952 res_counter_reset_failcnt(&memcg->memsw);
3959 static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
3962 return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
3966 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
3967 struct cftype *cft, u64 val)
3969 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3971 if (val >= (1 << NR_MOVE_TYPE))
3974 * We check this value several times in both in can_attach() and
3975 * attach(), so we need cgroup lock to prevent this value from being
3979 memcg->move_charge_at_immigrate = val;
3985 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
3986 struct cftype *cft, u64 val)
3993 /* For read statistics */
4011 struct mcs_total_stat {
4012 s64 stat[NR_MCS_STAT];
4018 } memcg_stat_strings[NR_MCS_STAT] = {
4019 {"cache", "total_cache"},
4020 {"rss", "total_rss"},
4021 {"mapped_file", "total_mapped_file"},
4022 {"pgpgin", "total_pgpgin"},
4023 {"pgpgout", "total_pgpgout"},
4024 {"swap", "total_swap"},
4025 {"pgfault", "total_pgfault"},
4026 {"pgmajfault", "total_pgmajfault"},
4027 {"inactive_anon", "total_inactive_anon"},
4028 {"active_anon", "total_active_anon"},
4029 {"inactive_file", "total_inactive_file"},
4030 {"active_file", "total_active_file"},
4031 {"unevictable", "total_unevictable"}
4036 mem_cgroup_get_local_stat(struct mem_cgroup *memcg, struct mcs_total_stat *s)
4041 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_CACHE);
4042 s->stat[MCS_CACHE] += val * PAGE_SIZE;
4043 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_RSS);
4044 s->stat[MCS_RSS] += val * PAGE_SIZE;
4045 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_FILE_MAPPED);
4046 s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE;
4047 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGPGIN);
4048 s->stat[MCS_PGPGIN] += val;
4049 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGPGOUT);
4050 s->stat[MCS_PGPGOUT] += val;
4051 if (do_swap_account) {
4052 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_SWAPOUT);
4053 s->stat[MCS_SWAP] += val * PAGE_SIZE;
4055 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGFAULT);
4056 s->stat[MCS_PGFAULT] += val;
4057 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGMAJFAULT);
4058 s->stat[MCS_PGMAJFAULT] += val;
4061 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_INACTIVE_ANON));
4062 s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
4063 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_ACTIVE_ANON));
4064 s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
4065 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_INACTIVE_FILE));
4066 s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
4067 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_ACTIVE_FILE));
4068 s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
4069 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_UNEVICTABLE));
4070 s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
4074 mem_cgroup_get_total_stat(struct mem_cgroup *memcg, struct mcs_total_stat *s)
4076 struct mem_cgroup *iter;
4078 for_each_mem_cgroup_tree(iter, memcg)
4079 mem_cgroup_get_local_stat(iter, s);
4083 static int mem_control_numa_stat_show(struct seq_file *m, void *arg)
4086 unsigned long total_nr, file_nr, anon_nr, unevictable_nr;
4087 unsigned long node_nr;
4088 struct cgroup *cont = m->private;
4089 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
4091 total_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL);
4092 seq_printf(m, "total=%lu", total_nr);
4093 for_each_node_state(nid, N_HIGH_MEMORY) {
4094 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid, LRU_ALL);
4095 seq_printf(m, " N%d=%lu", nid, node_nr);
4099 file_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_FILE);
4100 seq_printf(m, "file=%lu", file_nr);
4101 for_each_node_state(nid, N_HIGH_MEMORY) {
4102 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4104 seq_printf(m, " N%d=%lu", nid, node_nr);
4108 anon_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_ANON);
4109 seq_printf(m, "anon=%lu", anon_nr);
4110 for_each_node_state(nid, N_HIGH_MEMORY) {
4111 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4113 seq_printf(m, " N%d=%lu", nid, node_nr);
4117 unevictable_nr = mem_cgroup_nr_lru_pages(mem_cont, BIT(LRU_UNEVICTABLE));
4118 seq_printf(m, "unevictable=%lu", unevictable_nr);
4119 for_each_node_state(nid, N_HIGH_MEMORY) {
4120 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4121 BIT(LRU_UNEVICTABLE));
4122 seq_printf(m, " N%d=%lu", nid, node_nr);
4127 #endif /* CONFIG_NUMA */
4129 static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
4130 struct cgroup_map_cb *cb)
4132 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
4133 struct mcs_total_stat mystat;
4136 memset(&mystat, 0, sizeof(mystat));
4137 mem_cgroup_get_local_stat(mem_cont, &mystat);
4140 for (i = 0; i < NR_MCS_STAT; i++) {
4141 if (i == MCS_SWAP && !do_swap_account)
4143 cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
4146 /* Hierarchical information */
4148 unsigned long long limit, memsw_limit;
4149 memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
4150 cb->fill(cb, "hierarchical_memory_limit", limit);
4151 if (do_swap_account)
4152 cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
4155 memset(&mystat, 0, sizeof(mystat));
4156 mem_cgroup_get_total_stat(mem_cont, &mystat);
4157 for (i = 0; i < NR_MCS_STAT; i++) {
4158 if (i == MCS_SWAP && !do_swap_account)
4160 cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
4163 #ifdef CONFIG_DEBUG_VM
4166 struct mem_cgroup_per_zone *mz;
4167 unsigned long recent_rotated[2] = {0, 0};
4168 unsigned long recent_scanned[2] = {0, 0};
4170 for_each_online_node(nid)
4171 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
4172 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
4174 recent_rotated[0] +=
4175 mz->reclaim_stat.recent_rotated[0];
4176 recent_rotated[1] +=
4177 mz->reclaim_stat.recent_rotated[1];
4178 recent_scanned[0] +=
4179 mz->reclaim_stat.recent_scanned[0];
4180 recent_scanned[1] +=
4181 mz->reclaim_stat.recent_scanned[1];
4183 cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
4184 cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
4185 cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
4186 cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
4193 static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
4195 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4197 return mem_cgroup_swappiness(memcg);
4200 static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
4203 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4204 struct mem_cgroup *parent;
4209 if (cgrp->parent == NULL)
4212 parent = mem_cgroup_from_cont(cgrp->parent);
4216 /* If under hierarchy, only empty-root can set this value */
4217 if ((parent->use_hierarchy) ||
4218 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
4223 memcg->swappiness = val;
4230 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4232 struct mem_cgroup_threshold_ary *t;
4238 t = rcu_dereference(memcg->thresholds.primary);
4240 t = rcu_dereference(memcg->memsw_thresholds.primary);
4245 usage = mem_cgroup_usage(memcg, swap);
4248 * current_threshold points to threshold just below usage.
4249 * If it's not true, a threshold was crossed after last
4250 * call of __mem_cgroup_threshold().
4252 i = t->current_threshold;
4255 * Iterate backward over array of thresholds starting from
4256 * current_threshold and check if a threshold is crossed.
4257 * If none of thresholds below usage is crossed, we read
4258 * only one element of the array here.
4260 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4261 eventfd_signal(t->entries[i].eventfd, 1);
4263 /* i = current_threshold + 1 */
4267 * Iterate forward over array of thresholds starting from
4268 * current_threshold+1 and check if a threshold is crossed.
4269 * If none of thresholds above usage is crossed, we read
4270 * only one element of the array here.
4272 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4273 eventfd_signal(t->entries[i].eventfd, 1);
4275 /* Update current_threshold */
4276 t->current_threshold = i - 1;
4281 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4284 __mem_cgroup_threshold(memcg, false);
4285 if (do_swap_account)
4286 __mem_cgroup_threshold(memcg, true);
4288 memcg = parent_mem_cgroup(memcg);
4292 static int compare_thresholds(const void *a, const void *b)
4294 const struct mem_cgroup_threshold *_a = a;
4295 const struct mem_cgroup_threshold *_b = b;
4297 return _a->threshold - _b->threshold;
4300 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
4302 struct mem_cgroup_eventfd_list *ev;
4304 list_for_each_entry(ev, &memcg->oom_notify, list)
4305 eventfd_signal(ev->eventfd, 1);
4309 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
4311 struct mem_cgroup *iter;
4313 for_each_mem_cgroup_tree(iter, memcg)
4314 mem_cgroup_oom_notify_cb(iter);
4317 static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
4318 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4320 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4321 struct mem_cgroup_thresholds *thresholds;
4322 struct mem_cgroup_threshold_ary *new;
4323 int type = MEMFILE_TYPE(cft->private);
4324 u64 threshold, usage;
4327 ret = res_counter_memparse_write_strategy(args, &threshold);
4331 mutex_lock(&memcg->thresholds_lock);
4334 thresholds = &memcg->thresholds;
4335 else if (type == _MEMSWAP)
4336 thresholds = &memcg->memsw_thresholds;
4340 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4342 /* Check if a threshold crossed before adding a new one */
4343 if (thresholds->primary)
4344 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4346 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4348 /* Allocate memory for new array of thresholds */
4349 new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
4357 /* Copy thresholds (if any) to new array */
4358 if (thresholds->primary) {
4359 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
4360 sizeof(struct mem_cgroup_threshold));
4363 /* Add new threshold */
4364 new->entries[size - 1].eventfd = eventfd;
4365 new->entries[size - 1].threshold = threshold;
4367 /* Sort thresholds. Registering of new threshold isn't time-critical */
4368 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
4369 compare_thresholds, NULL);
4371 /* Find current threshold */
4372 new->current_threshold = -1;
4373 for (i = 0; i < size; i++) {
4374 if (new->entries[i].threshold < usage) {
4376 * new->current_threshold will not be used until
4377 * rcu_assign_pointer(), so it's safe to increment
4380 ++new->current_threshold;
4384 /* Free old spare buffer and save old primary buffer as spare */
4385 kfree(thresholds->spare);
4386 thresholds->spare = thresholds->primary;
4388 rcu_assign_pointer(thresholds->primary, new);
4390 /* To be sure that nobody uses thresholds */
4394 mutex_unlock(&memcg->thresholds_lock);
4399 static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
4400 struct cftype *cft, struct eventfd_ctx *eventfd)
4402 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4403 struct mem_cgroup_thresholds *thresholds;
4404 struct mem_cgroup_threshold_ary *new;
4405 int type = MEMFILE_TYPE(cft->private);
4409 mutex_lock(&memcg->thresholds_lock);
4411 thresholds = &memcg->thresholds;
4412 else if (type == _MEMSWAP)
4413 thresholds = &memcg->memsw_thresholds;
4418 * Something went wrong if we trying to unregister a threshold
4419 * if we don't have thresholds
4421 BUG_ON(!thresholds);
4423 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4425 /* Check if a threshold crossed before removing */
4426 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4428 /* Calculate new number of threshold */
4430 for (i = 0; i < thresholds->primary->size; i++) {
4431 if (thresholds->primary->entries[i].eventfd != eventfd)
4435 new = thresholds->spare;
4437 /* Set thresholds array to NULL if we don't have thresholds */
4446 /* Copy thresholds and find current threshold */
4447 new->current_threshold = -1;
4448 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4449 if (thresholds->primary->entries[i].eventfd == eventfd)
4452 new->entries[j] = thresholds->primary->entries[i];
4453 if (new->entries[j].threshold < usage) {
4455 * new->current_threshold will not be used
4456 * until rcu_assign_pointer(), so it's safe to increment
4459 ++new->current_threshold;
4465 /* Swap primary and spare array */
4466 thresholds->spare = thresholds->primary;
4467 rcu_assign_pointer(thresholds->primary, new);
4469 /* To be sure that nobody uses thresholds */
4472 mutex_unlock(&memcg->thresholds_lock);
4475 static int mem_cgroup_oom_register_event(struct cgroup *cgrp,
4476 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4478 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4479 struct mem_cgroup_eventfd_list *event;
4480 int type = MEMFILE_TYPE(cft->private);
4482 BUG_ON(type != _OOM_TYPE);
4483 event = kmalloc(sizeof(*event), GFP_KERNEL);
4487 spin_lock(&memcg_oom_lock);
4489 event->eventfd = eventfd;
4490 list_add(&event->list, &memcg->oom_notify);
4492 /* already in OOM ? */
4493 if (atomic_read(&memcg->under_oom))
4494 eventfd_signal(eventfd, 1);
4495 spin_unlock(&memcg_oom_lock);
4500 static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
4501 struct cftype *cft, struct eventfd_ctx *eventfd)
4503 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4504 struct mem_cgroup_eventfd_list *ev, *tmp;
4505 int type = MEMFILE_TYPE(cft->private);
4507 BUG_ON(type != _OOM_TYPE);
4509 spin_lock(&memcg_oom_lock);
4511 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
4512 if (ev->eventfd == eventfd) {
4513 list_del(&ev->list);
4518 spin_unlock(&memcg_oom_lock);
4521 static int mem_cgroup_oom_control_read(struct cgroup *cgrp,
4522 struct cftype *cft, struct cgroup_map_cb *cb)
4524 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4526 cb->fill(cb, "oom_kill_disable", memcg->oom_kill_disable);
4528 if (atomic_read(&memcg->under_oom))
4529 cb->fill(cb, "under_oom", 1);
4531 cb->fill(cb, "under_oom", 0);
4535 static int mem_cgroup_oom_control_write(struct cgroup *cgrp,
4536 struct cftype *cft, u64 val)
4538 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4539 struct mem_cgroup *parent;
4541 /* cannot set to root cgroup and only 0 and 1 are allowed */
4542 if (!cgrp->parent || !((val == 0) || (val == 1)))
4545 parent = mem_cgroup_from_cont(cgrp->parent);
4548 /* oom-kill-disable is a flag for subhierarchy. */
4549 if ((parent->use_hierarchy) ||
4550 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
4554 memcg->oom_kill_disable = val;
4556 memcg_oom_recover(memcg);
4562 static const struct file_operations mem_control_numa_stat_file_operations = {
4564 .llseek = seq_lseek,
4565 .release = single_release,
4568 static int mem_control_numa_stat_open(struct inode *unused, struct file *file)
4570 struct cgroup *cont = file->f_dentry->d_parent->d_fsdata;
4572 file->f_op = &mem_control_numa_stat_file_operations;
4573 return single_open(file, mem_control_numa_stat_show, cont);
4575 #endif /* CONFIG_NUMA */
4577 static struct cftype mem_cgroup_files[] = {
4579 .name = "usage_in_bytes",
4580 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
4581 .read_u64 = mem_cgroup_read,
4582 .register_event = mem_cgroup_usage_register_event,
4583 .unregister_event = mem_cgroup_usage_unregister_event,
4586 .name = "max_usage_in_bytes",
4587 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
4588 .trigger = mem_cgroup_reset,
4589 .read_u64 = mem_cgroup_read,
4592 .name = "limit_in_bytes",
4593 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
4594 .write_string = mem_cgroup_write,
4595 .read_u64 = mem_cgroup_read,
4598 .name = "soft_limit_in_bytes",
4599 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
4600 .write_string = mem_cgroup_write,
4601 .read_u64 = mem_cgroup_read,
4605 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
4606 .trigger = mem_cgroup_reset,
4607 .read_u64 = mem_cgroup_read,
4611 .read_map = mem_control_stat_show,
4614 .name = "force_empty",
4615 .trigger = mem_cgroup_force_empty_write,
4618 .name = "use_hierarchy",
4619 .write_u64 = mem_cgroup_hierarchy_write,
4620 .read_u64 = mem_cgroup_hierarchy_read,
4623 .name = "swappiness",
4624 .read_u64 = mem_cgroup_swappiness_read,
4625 .write_u64 = mem_cgroup_swappiness_write,
4628 .name = "move_charge_at_immigrate",
4629 .read_u64 = mem_cgroup_move_charge_read,
4630 .write_u64 = mem_cgroup_move_charge_write,
4633 .name = "oom_control",
4634 .read_map = mem_cgroup_oom_control_read,
4635 .write_u64 = mem_cgroup_oom_control_write,
4636 .register_event = mem_cgroup_oom_register_event,
4637 .unregister_event = mem_cgroup_oom_unregister_event,
4638 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
4642 .name = "numa_stat",
4643 .open = mem_control_numa_stat_open,
4649 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4650 static struct cftype memsw_cgroup_files[] = {
4652 .name = "memsw.usage_in_bytes",
4653 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
4654 .read_u64 = mem_cgroup_read,
4655 .register_event = mem_cgroup_usage_register_event,
4656 .unregister_event = mem_cgroup_usage_unregister_event,
4659 .name = "memsw.max_usage_in_bytes",
4660 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
4661 .trigger = mem_cgroup_reset,
4662 .read_u64 = mem_cgroup_read,
4665 .name = "memsw.limit_in_bytes",
4666 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
4667 .write_string = mem_cgroup_write,
4668 .read_u64 = mem_cgroup_read,
4671 .name = "memsw.failcnt",
4672 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
4673 .trigger = mem_cgroup_reset,
4674 .read_u64 = mem_cgroup_read,
4678 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
4680 if (!do_swap_account)
4682 return cgroup_add_files(cont, ss, memsw_cgroup_files,
4683 ARRAY_SIZE(memsw_cgroup_files));
4686 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
4692 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
4694 struct mem_cgroup_per_node *pn;
4695 struct mem_cgroup_per_zone *mz;
4697 int zone, tmp = node;
4699 * This routine is called against possible nodes.
4700 * But it's BUG to call kmalloc() against offline node.
4702 * TODO: this routine can waste much memory for nodes which will
4703 * never be onlined. It's better to use memory hotplug callback
4706 if (!node_state(node, N_NORMAL_MEMORY))
4708 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
4712 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4713 mz = &pn->zoneinfo[zone];
4715 INIT_LIST_HEAD(&mz->lruvec.lists[l]);
4716 mz->usage_in_excess = 0;
4717 mz->on_tree = false;
4720 memcg->info.nodeinfo[node] = pn;
4724 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
4726 kfree(memcg->info.nodeinfo[node]);
4729 static struct mem_cgroup *mem_cgroup_alloc(void)
4731 struct mem_cgroup *mem;
4732 int size = sizeof(struct mem_cgroup);
4734 /* Can be very big if MAX_NUMNODES is very big */
4735 if (size < PAGE_SIZE)
4736 mem = kzalloc(size, GFP_KERNEL);
4738 mem = vzalloc(size);
4743 mem->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
4746 spin_lock_init(&mem->pcp_counter_lock);
4750 if (size < PAGE_SIZE)
4758 * At destroying mem_cgroup, references from swap_cgroup can remain.
4759 * (scanning all at force_empty is too costly...)
4761 * Instead of clearing all references at force_empty, we remember
4762 * the number of reference from swap_cgroup and free mem_cgroup when
4763 * it goes down to 0.
4765 * Removal of cgroup itself succeeds regardless of refs from swap.
4768 static void __mem_cgroup_free(struct mem_cgroup *memcg)
4772 mem_cgroup_remove_from_trees(memcg);
4773 free_css_id(&mem_cgroup_subsys, &memcg->css);
4775 for_each_node_state(node, N_POSSIBLE)
4776 free_mem_cgroup_per_zone_info(memcg, node);
4778 free_percpu(memcg->stat);
4779 if (sizeof(struct mem_cgroup) < PAGE_SIZE)
4785 static void mem_cgroup_get(struct mem_cgroup *memcg)
4787 atomic_inc(&memcg->refcnt);
4790 static void __mem_cgroup_put(struct mem_cgroup *memcg, int count)
4792 if (atomic_sub_and_test(count, &memcg->refcnt)) {
4793 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
4794 __mem_cgroup_free(memcg);
4796 mem_cgroup_put(parent);
4800 static void mem_cgroup_put(struct mem_cgroup *memcg)
4802 __mem_cgroup_put(memcg, 1);
4806 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
4808 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg)
4810 if (!memcg->res.parent)
4812 return mem_cgroup_from_res_counter(memcg->res.parent, res);
4815 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4816 static void __init enable_swap_cgroup(void)
4818 if (!mem_cgroup_disabled() && really_do_swap_account)
4819 do_swap_account = 1;
4822 static void __init enable_swap_cgroup(void)
4827 static int mem_cgroup_soft_limit_tree_init(void)
4829 struct mem_cgroup_tree_per_node *rtpn;
4830 struct mem_cgroup_tree_per_zone *rtpz;
4831 int tmp, node, zone;
4833 for_each_node_state(node, N_POSSIBLE) {
4835 if (!node_state(node, N_NORMAL_MEMORY))
4837 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
4841 soft_limit_tree.rb_tree_per_node[node] = rtpn;
4843 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4844 rtpz = &rtpn->rb_tree_per_zone[zone];
4845 rtpz->rb_root = RB_ROOT;
4846 spin_lock_init(&rtpz->lock);
4852 static struct cgroup_subsys_state * __ref
4853 mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
4855 struct mem_cgroup *memcg, *parent;
4856 long error = -ENOMEM;
4859 memcg = mem_cgroup_alloc();
4861 return ERR_PTR(error);
4863 for_each_node_state(node, N_POSSIBLE)
4864 if (alloc_mem_cgroup_per_zone_info(memcg, node))
4868 if (cont->parent == NULL) {
4870 enable_swap_cgroup();
4872 root_mem_cgroup = memcg;
4873 if (mem_cgroup_soft_limit_tree_init())
4875 for_each_possible_cpu(cpu) {
4876 struct memcg_stock_pcp *stock =
4877 &per_cpu(memcg_stock, cpu);
4878 INIT_WORK(&stock->work, drain_local_stock);
4880 hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
4882 parent = mem_cgroup_from_cont(cont->parent);
4883 memcg->use_hierarchy = parent->use_hierarchy;
4884 memcg->oom_kill_disable = parent->oom_kill_disable;
4887 if (parent && parent->use_hierarchy) {
4888 res_counter_init(&memcg->res, &parent->res);
4889 res_counter_init(&memcg->memsw, &parent->memsw);
4891 * We increment refcnt of the parent to ensure that we can
4892 * safely access it on res_counter_charge/uncharge.
4893 * This refcnt will be decremented when freeing this
4894 * mem_cgroup(see mem_cgroup_put).
4896 mem_cgroup_get(parent);
4898 res_counter_init(&memcg->res, NULL);
4899 res_counter_init(&memcg->memsw, NULL);
4901 memcg->last_scanned_node = MAX_NUMNODES;
4902 INIT_LIST_HEAD(&memcg->oom_notify);
4905 memcg->swappiness = mem_cgroup_swappiness(parent);
4906 atomic_set(&memcg->refcnt, 1);
4907 memcg->move_charge_at_immigrate = 0;
4908 mutex_init(&memcg->thresholds_lock);
4911 __mem_cgroup_free(memcg);
4912 root_mem_cgroup = NULL;
4913 return ERR_PTR(error);
4916 static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
4917 struct cgroup *cont)
4919 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4921 return mem_cgroup_force_empty(memcg, false);
4924 static void mem_cgroup_destroy(struct cgroup_subsys *ss,
4925 struct cgroup *cont)
4927 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4929 mem_cgroup_put(memcg);
4932 static int mem_cgroup_populate(struct cgroup_subsys *ss,
4933 struct cgroup *cont)
4937 ret = cgroup_add_files(cont, ss, mem_cgroup_files,
4938 ARRAY_SIZE(mem_cgroup_files));
4941 ret = register_memsw_files(cont, ss);
4946 /* Handlers for move charge at task migration. */
4947 #define PRECHARGE_COUNT_AT_ONCE 256
4948 static int mem_cgroup_do_precharge(unsigned long count)
4951 int batch_count = PRECHARGE_COUNT_AT_ONCE;
4952 struct mem_cgroup *memcg = mc.to;
4954 if (mem_cgroup_is_root(memcg)) {
4955 mc.precharge += count;
4956 /* we don't need css_get for root */
4959 /* try to charge at once */
4961 struct res_counter *dummy;
4963 * "memcg" cannot be under rmdir() because we've already checked
4964 * by cgroup_lock_live_cgroup() that it is not removed and we
4965 * are still under the same cgroup_mutex. So we can postpone
4968 if (res_counter_charge(&memcg->res, PAGE_SIZE * count, &dummy))
4970 if (do_swap_account && res_counter_charge(&memcg->memsw,
4971 PAGE_SIZE * count, &dummy)) {
4972 res_counter_uncharge(&memcg->res, PAGE_SIZE * count);
4975 mc.precharge += count;
4979 /* fall back to one by one charge */
4981 if (signal_pending(current)) {
4985 if (!batch_count--) {
4986 batch_count = PRECHARGE_COUNT_AT_ONCE;
4989 ret = __mem_cgroup_try_charge(NULL,
4990 GFP_KERNEL, 1, &memcg, false);
4992 /* mem_cgroup_clear_mc() will do uncharge later */
5000 * is_target_pte_for_mc - check a pte whether it is valid for move charge
5001 * @vma: the vma the pte to be checked belongs
5002 * @addr: the address corresponding to the pte to be checked
5003 * @ptent: the pte to be checked
5004 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5007 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5008 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5009 * move charge. if @target is not NULL, the page is stored in target->page
5010 * with extra refcnt got(Callers should handle it).
5011 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5012 * target for charge migration. if @target is not NULL, the entry is stored
5015 * Called with pte lock held.
5022 enum mc_target_type {
5023 MC_TARGET_NONE, /* not used */
5028 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5029 unsigned long addr, pte_t ptent)
5031 struct page *page = vm_normal_page(vma, addr, ptent);
5033 if (!page || !page_mapped(page))
5035 if (PageAnon(page)) {
5036 /* we don't move shared anon */
5037 if (!move_anon() || page_mapcount(page) > 2)
5039 } else if (!move_file())
5040 /* we ignore mapcount for file pages */
5042 if (!get_page_unless_zero(page))
5048 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5049 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5052 struct page *page = NULL;
5053 swp_entry_t ent = pte_to_swp_entry(ptent);
5055 if (!move_anon() || non_swap_entry(ent))
5057 usage_count = mem_cgroup_count_swap_user(ent, &page);
5058 if (usage_count > 1) { /* we don't move shared anon */
5063 if (do_swap_account)
5064 entry->val = ent.val;
5069 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5070 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5072 struct page *page = NULL;
5073 struct inode *inode;
5074 struct address_space *mapping;
5077 if (!vma->vm_file) /* anonymous vma */
5082 inode = vma->vm_file->f_path.dentry->d_inode;
5083 mapping = vma->vm_file->f_mapping;
5084 if (pte_none(ptent))
5085 pgoff = linear_page_index(vma, addr);
5086 else /* pte_file(ptent) is true */
5087 pgoff = pte_to_pgoff(ptent);
5089 /* page is moved even if it's not RSS of this task(page-faulted). */
5090 page = find_get_page(mapping, pgoff);
5093 /* shmem/tmpfs may report page out on swap: account for that too. */
5094 if (radix_tree_exceptional_entry(page)) {
5095 swp_entry_t swap = radix_to_swp_entry(page);
5096 if (do_swap_account)
5098 page = find_get_page(&swapper_space, swap.val);
5104 static int is_target_pte_for_mc(struct vm_area_struct *vma,
5105 unsigned long addr, pte_t ptent, union mc_target *target)
5107 struct page *page = NULL;
5108 struct page_cgroup *pc;
5110 swp_entry_t ent = { .val = 0 };
5112 if (pte_present(ptent))
5113 page = mc_handle_present_pte(vma, addr, ptent);
5114 else if (is_swap_pte(ptent))
5115 page = mc_handle_swap_pte(vma, addr, ptent, &ent);
5116 else if (pte_none(ptent) || pte_file(ptent))
5117 page = mc_handle_file_pte(vma, addr, ptent, &ent);
5119 if (!page && !ent.val)
5122 pc = lookup_page_cgroup(page);
5124 * Do only loose check w/o page_cgroup lock.
5125 * mem_cgroup_move_account() checks the pc is valid or not under
5128 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
5129 ret = MC_TARGET_PAGE;
5131 target->page = page;
5133 if (!ret || !target)
5136 /* There is a swap entry and a page doesn't exist or isn't charged */
5137 if (ent.val && !ret &&
5138 css_id(&mc.from->css) == lookup_swap_cgroup(ent)) {
5139 ret = MC_TARGET_SWAP;
5146 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5147 unsigned long addr, unsigned long end,
5148 struct mm_walk *walk)
5150 struct vm_area_struct *vma = walk->private;
5154 split_huge_page_pmd(walk->mm, pmd);
5156 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5157 for (; addr != end; pte++, addr += PAGE_SIZE)
5158 if (is_target_pte_for_mc(vma, addr, *pte, NULL))
5159 mc.precharge++; /* increment precharge temporarily */
5160 pte_unmap_unlock(pte - 1, ptl);
5166 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5168 unsigned long precharge;
5169 struct vm_area_struct *vma;
5171 down_read(&mm->mmap_sem);
5172 for (vma = mm->mmap; vma; vma = vma->vm_next) {
5173 struct mm_walk mem_cgroup_count_precharge_walk = {
5174 .pmd_entry = mem_cgroup_count_precharge_pte_range,
5178 if (is_vm_hugetlb_page(vma))
5180 walk_page_range(vma->vm_start, vma->vm_end,
5181 &mem_cgroup_count_precharge_walk);
5183 up_read(&mm->mmap_sem);
5185 precharge = mc.precharge;
5191 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5193 unsigned long precharge = mem_cgroup_count_precharge(mm);
5195 VM_BUG_ON(mc.moving_task);
5196 mc.moving_task = current;
5197 return mem_cgroup_do_precharge(precharge);
5200 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5201 static void __mem_cgroup_clear_mc(void)
5203 struct mem_cgroup *from = mc.from;
5204 struct mem_cgroup *to = mc.to;
5206 /* we must uncharge all the leftover precharges from mc.to */
5208 __mem_cgroup_cancel_charge(mc.to, mc.precharge);
5212 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5213 * we must uncharge here.
5215 if (mc.moved_charge) {
5216 __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
5217 mc.moved_charge = 0;
5219 /* we must fixup refcnts and charges */
5220 if (mc.moved_swap) {
5221 /* uncharge swap account from the old cgroup */
5222 if (!mem_cgroup_is_root(mc.from))
5223 res_counter_uncharge(&mc.from->memsw,
5224 PAGE_SIZE * mc.moved_swap);
5225 __mem_cgroup_put(mc.from, mc.moved_swap);
5227 if (!mem_cgroup_is_root(mc.to)) {
5229 * we charged both to->res and to->memsw, so we should
5232 res_counter_uncharge(&mc.to->res,
5233 PAGE_SIZE * mc.moved_swap);
5235 /* we've already done mem_cgroup_get(mc.to) */
5238 memcg_oom_recover(from);
5239 memcg_oom_recover(to);
5240 wake_up_all(&mc.waitq);
5243 static void mem_cgroup_clear_mc(void)
5245 struct mem_cgroup *from = mc.from;
5248 * we must clear moving_task before waking up waiters at the end of
5251 mc.moving_task = NULL;
5252 __mem_cgroup_clear_mc();
5253 spin_lock(&mc.lock);
5256 spin_unlock(&mc.lock);
5257 mem_cgroup_end_move(from);
5260 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
5261 struct cgroup *cgroup,
5262 struct task_struct *p)
5265 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgroup);
5267 if (memcg->move_charge_at_immigrate) {
5268 struct mm_struct *mm;
5269 struct mem_cgroup *from = mem_cgroup_from_task(p);
5271 VM_BUG_ON(from == memcg);
5273 mm = get_task_mm(p);
5276 /* We move charges only when we move a owner of the mm */
5277 if (mm->owner == p) {
5280 VM_BUG_ON(mc.precharge);
5281 VM_BUG_ON(mc.moved_charge);
5282 VM_BUG_ON(mc.moved_swap);
5283 mem_cgroup_start_move(from);
5284 spin_lock(&mc.lock);
5287 spin_unlock(&mc.lock);
5288 /* We set mc.moving_task later */
5290 ret = mem_cgroup_precharge_mc(mm);
5292 mem_cgroup_clear_mc();
5299 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
5300 struct cgroup *cgroup,
5301 struct task_struct *p)
5303 mem_cgroup_clear_mc();
5306 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
5307 unsigned long addr, unsigned long end,
5308 struct mm_walk *walk)
5311 struct vm_area_struct *vma = walk->private;
5315 split_huge_page_pmd(walk->mm, pmd);
5317 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5318 for (; addr != end; addr += PAGE_SIZE) {
5319 pte_t ptent = *(pte++);
5320 union mc_target target;
5323 struct page_cgroup *pc;
5329 type = is_target_pte_for_mc(vma, addr, ptent, &target);
5331 case MC_TARGET_PAGE:
5333 if (isolate_lru_page(page))
5335 pc = lookup_page_cgroup(page);
5336 if (!mem_cgroup_move_account(page, 1, pc,
5337 mc.from, mc.to, false)) {
5339 /* we uncharge from mc.from later. */
5342 putback_lru_page(page);
5343 put: /* is_target_pte_for_mc() gets the page */
5346 case MC_TARGET_SWAP:
5348 if (!mem_cgroup_move_swap_account(ent,
5349 mc.from, mc.to, false)) {
5351 /* we fixup refcnts and charges later. */
5359 pte_unmap_unlock(pte - 1, ptl);
5364 * We have consumed all precharges we got in can_attach().
5365 * We try charge one by one, but don't do any additional
5366 * charges to mc.to if we have failed in charge once in attach()
5369 ret = mem_cgroup_do_precharge(1);
5377 static void mem_cgroup_move_charge(struct mm_struct *mm)
5379 struct vm_area_struct *vma;
5381 lru_add_drain_all();
5383 if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
5385 * Someone who are holding the mmap_sem might be waiting in
5386 * waitq. So we cancel all extra charges, wake up all waiters,
5387 * and retry. Because we cancel precharges, we might not be able
5388 * to move enough charges, but moving charge is a best-effort
5389 * feature anyway, so it wouldn't be a big problem.
5391 __mem_cgroup_clear_mc();
5395 for (vma = mm->mmap; vma; vma = vma->vm_next) {
5397 struct mm_walk mem_cgroup_move_charge_walk = {
5398 .pmd_entry = mem_cgroup_move_charge_pte_range,
5402 if (is_vm_hugetlb_page(vma))
5404 ret = walk_page_range(vma->vm_start, vma->vm_end,
5405 &mem_cgroup_move_charge_walk);
5408 * means we have consumed all precharges and failed in
5409 * doing additional charge. Just abandon here.
5413 up_read(&mm->mmap_sem);
5416 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
5417 struct cgroup *cont,
5418 struct cgroup *old_cont,
5419 struct task_struct *p)
5421 struct mm_struct *mm = get_task_mm(p);
5425 mem_cgroup_move_charge(mm);
5430 mem_cgroup_clear_mc();
5432 #else /* !CONFIG_MMU */
5433 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
5434 struct cgroup *cgroup,
5435 struct task_struct *p)
5439 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
5440 struct cgroup *cgroup,
5441 struct task_struct *p)
5444 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
5445 struct cgroup *cont,
5446 struct cgroup *old_cont,
5447 struct task_struct *p)
5452 struct cgroup_subsys mem_cgroup_subsys = {
5454 .subsys_id = mem_cgroup_subsys_id,
5455 .create = mem_cgroup_create,
5456 .pre_destroy = mem_cgroup_pre_destroy,
5457 .destroy = mem_cgroup_destroy,
5458 .populate = mem_cgroup_populate,
5459 .can_attach = mem_cgroup_can_attach,
5460 .cancel_attach = mem_cgroup_cancel_attach,
5461 .attach = mem_cgroup_move_task,
5466 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
5467 static int __init enable_swap_account(char *s)
5469 /* consider enabled if no parameter or 1 is given */
5470 if (!strcmp(s, "1"))
5471 really_do_swap_account = 1;
5472 else if (!strcmp(s, "0"))
5473 really_do_swap_account = 0;
5476 __setup("swapaccount=", enable_swap_account);