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 mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
686 enum mem_cgroup_events_target target)
688 unsigned long val, next;
690 val = __this_cpu_read(memcg->stat->events[MEM_CGROUP_EVENTS_COUNT]);
691 next = __this_cpu_read(memcg->stat->targets[target]);
692 /* from time_after() in jiffies.h */
693 if ((long)next - (long)val < 0) {
695 case MEM_CGROUP_TARGET_THRESH:
696 next = val + THRESHOLDS_EVENTS_TARGET;
698 case MEM_CGROUP_TARGET_SOFTLIMIT:
699 next = val + SOFTLIMIT_EVENTS_TARGET;
701 case MEM_CGROUP_TARGET_NUMAINFO:
702 next = val + NUMAINFO_EVENTS_TARGET;
707 __this_cpu_write(memcg->stat->targets[target], next);
714 * Check events in order.
717 static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
720 /* threshold event is triggered in finer grain than soft limit */
721 if (unlikely(mem_cgroup_event_ratelimit(memcg,
722 MEM_CGROUP_TARGET_THRESH))) {
723 bool do_softlimit, do_numainfo;
725 do_softlimit = mem_cgroup_event_ratelimit(memcg,
726 MEM_CGROUP_TARGET_SOFTLIMIT);
728 do_numainfo = mem_cgroup_event_ratelimit(memcg,
729 MEM_CGROUP_TARGET_NUMAINFO);
733 mem_cgroup_threshold(memcg);
734 if (unlikely(do_softlimit))
735 mem_cgroup_update_tree(memcg, page);
737 if (unlikely(do_numainfo))
738 atomic_inc(&memcg->numainfo_events);
744 static struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
746 return container_of(cgroup_subsys_state(cont,
747 mem_cgroup_subsys_id), struct mem_cgroup,
751 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
754 * mm_update_next_owner() may clear mm->owner to NULL
755 * if it races with swapoff, page migration, etc.
756 * So this can be called with p == NULL.
761 return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
762 struct mem_cgroup, css);
765 struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
767 struct mem_cgroup *memcg = NULL;
772 * Because we have no locks, mm->owner's may be being moved to other
773 * cgroup. We use css_tryget() here even if this looks
774 * pessimistic (rather than adding locks here).
778 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
779 if (unlikely(!memcg))
781 } while (!css_tryget(&memcg->css));
787 * mem_cgroup_iter - iterate over memory cgroup hierarchy
788 * @root: hierarchy root
789 * @prev: previously returned memcg, NULL on first invocation
790 * @reclaim: cookie for shared reclaim walks, NULL for full walks
792 * Returns references to children of the hierarchy below @root, or
793 * @root itself, or %NULL after a full round-trip.
795 * Caller must pass the return value in @prev on subsequent
796 * invocations for reference counting, or use mem_cgroup_iter_break()
797 * to cancel a hierarchy walk before the round-trip is complete.
799 * Reclaimers can specify a zone and a priority level in @reclaim to
800 * divide up the memcgs in the hierarchy among all concurrent
801 * reclaimers operating on the same zone and priority.
803 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
804 struct mem_cgroup *prev,
805 struct mem_cgroup_reclaim_cookie *reclaim)
807 struct mem_cgroup *memcg = NULL;
810 if (mem_cgroup_disabled())
814 root = root_mem_cgroup;
816 if (prev && !reclaim)
817 id = css_id(&prev->css);
819 if (prev && prev != root)
822 if (!root->use_hierarchy && root != root_mem_cgroup) {
829 struct mem_cgroup_reclaim_iter *uninitialized_var(iter);
830 struct cgroup_subsys_state *css;
833 int nid = zone_to_nid(reclaim->zone);
834 int zid = zone_idx(reclaim->zone);
835 struct mem_cgroup_per_zone *mz;
837 mz = mem_cgroup_zoneinfo(root, nid, zid);
838 iter = &mz->reclaim_iter[reclaim->priority];
839 if (prev && reclaim->generation != iter->generation)
845 css = css_get_next(&mem_cgroup_subsys, id + 1, &root->css, &id);
847 if (css == &root->css || css_tryget(css))
848 memcg = container_of(css,
849 struct mem_cgroup, css);
858 else if (!prev && memcg)
859 reclaim->generation = iter->generation;
869 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
870 * @root: hierarchy root
871 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
873 void mem_cgroup_iter_break(struct mem_cgroup *root,
874 struct mem_cgroup *prev)
877 root = root_mem_cgroup;
878 if (prev && prev != root)
883 * Iteration constructs for visiting all cgroups (under a tree). If
884 * loops are exited prematurely (break), mem_cgroup_iter_break() must
885 * be used for reference counting.
887 #define for_each_mem_cgroup_tree(iter, root) \
888 for (iter = mem_cgroup_iter(root, NULL, NULL); \
890 iter = mem_cgroup_iter(root, iter, NULL))
892 #define for_each_mem_cgroup(iter) \
893 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
895 iter = mem_cgroup_iter(NULL, iter, NULL))
897 static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
899 return (memcg == root_mem_cgroup);
902 void mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx)
904 struct mem_cgroup *memcg;
910 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
911 if (unlikely(!memcg))
916 mem_cgroup_pgmajfault(memcg, 1);
919 mem_cgroup_pgfault(memcg, 1);
927 EXPORT_SYMBOL(mem_cgroup_count_vm_event);
930 * mem_cgroup_zone_lruvec - get the lru list vector for a zone and memcg
931 * @zone: zone of the wanted lruvec
932 * @mem: memcg of the wanted lruvec
934 * Returns the lru list vector holding pages for the given @zone and
935 * @mem. This can be the global zone lruvec, if the memory controller
938 struct lruvec *mem_cgroup_zone_lruvec(struct zone *zone,
939 struct mem_cgroup *memcg)
941 struct mem_cgroup_per_zone *mz;
943 if (mem_cgroup_disabled())
944 return &zone->lruvec;
946 mz = mem_cgroup_zoneinfo(memcg, zone_to_nid(zone), zone_idx(zone));
951 * Following LRU functions are allowed to be used without PCG_LOCK.
952 * Operations are called by routine of global LRU independently from memcg.
953 * What we have to take care of here is validness of pc->mem_cgroup.
955 * Changes to pc->mem_cgroup happens when
958 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
959 * It is added to LRU before charge.
960 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
961 * When moving account, the page is not on LRU. It's isolated.
965 * mem_cgroup_lru_add_list - account for adding an lru page and return lruvec
966 * @zone: zone of the page
970 * This function accounts for @page being added to @lru, and returns
971 * the lruvec for the given @zone and the memcg @page is charged to.
973 * The callsite is then responsible for physically linking the page to
974 * the returned lruvec->lists[@lru].
976 struct lruvec *mem_cgroup_lru_add_list(struct zone *zone, struct page *page,
979 struct mem_cgroup_per_zone *mz;
980 struct mem_cgroup *memcg;
981 struct page_cgroup *pc;
983 if (mem_cgroup_disabled())
984 return &zone->lruvec;
986 pc = lookup_page_cgroup(page);
987 VM_BUG_ON(PageCgroupAcctLRU(pc));
990 * SetPageLRU SetPageCgroupUsed
992 * PageCgroupUsed && add to memcg LRU PageLRU && add to memcg LRU
994 * Ensure that one of the two sides adds the page to the memcg
999 * If the page is uncharged, it may be freed soon, but it
1000 * could also be swap cache (readahead, swapoff) that needs to
1001 * be reclaimable in the future. root_mem_cgroup will babysit
1002 * it for the time being.
1004 if (PageCgroupUsed(pc)) {
1005 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1007 memcg = pc->mem_cgroup;
1008 SetPageCgroupAcctLRU(pc);
1010 memcg = root_mem_cgroup;
1011 mz = page_cgroup_zoneinfo(memcg, page);
1012 /* compound_order() is stabilized through lru_lock */
1013 MEM_CGROUP_ZSTAT(mz, lru) += 1 << compound_order(page);
1018 * mem_cgroup_lru_del_list - account for removing an lru page
1022 * This function accounts for @page being removed from @lru.
1024 * The callsite is then responsible for physically unlinking
1027 void mem_cgroup_lru_del_list(struct page *page, enum lru_list lru)
1029 struct mem_cgroup_per_zone *mz;
1030 struct mem_cgroup *memcg;
1031 struct page_cgroup *pc;
1033 if (mem_cgroup_disabled())
1036 pc = lookup_page_cgroup(page);
1038 * root_mem_cgroup babysits uncharged LRU pages, but
1039 * PageCgroupUsed is cleared when the page is about to get
1040 * freed. PageCgroupAcctLRU remembers whether the
1041 * LRU-accounting happened against pc->mem_cgroup or
1044 if (TestClearPageCgroupAcctLRU(pc)) {
1045 VM_BUG_ON(!pc->mem_cgroup);
1046 memcg = pc->mem_cgroup;
1048 memcg = root_mem_cgroup;
1049 mz = page_cgroup_zoneinfo(memcg, page);
1050 /* huge page split is done under lru_lock. so, we have no races. */
1051 MEM_CGROUP_ZSTAT(mz, lru) -= 1 << compound_order(page);
1054 void mem_cgroup_lru_del(struct page *page)
1056 mem_cgroup_lru_del_list(page, page_lru(page));
1060 * mem_cgroup_lru_move_lists - account for moving a page between lrus
1061 * @zone: zone of the page
1063 * @from: current lru
1066 * This function accounts for @page being moved between the lrus @from
1067 * and @to, and returns the lruvec for the given @zone and the memcg
1068 * @page is charged to.
1070 * The callsite is then responsible for physically relinking
1071 * @page->lru to the returned lruvec->lists[@to].
1073 struct lruvec *mem_cgroup_lru_move_lists(struct zone *zone,
1078 /* XXX: Optimize this, especially for @from == @to */
1079 mem_cgroup_lru_del_list(page, from);
1080 return mem_cgroup_lru_add_list(zone, page, to);
1084 * At handling SwapCache and other FUSE stuff, pc->mem_cgroup may be changed
1085 * while it's linked to lru because the page may be reused after it's fully
1086 * uncharged. To handle that, unlink page_cgroup from LRU when charge it again.
1087 * It's done under lock_page and expected that zone->lru_lock isnever held.
1089 static void mem_cgroup_lru_del_before_commit(struct page *page)
1092 unsigned long flags;
1093 struct zone *zone = page_zone(page);
1094 struct page_cgroup *pc = lookup_page_cgroup(page);
1097 * Doing this check without taking ->lru_lock seems wrong but this
1098 * is safe. Because if page_cgroup's USED bit is unset, the page
1099 * will not be added to any memcg's LRU. If page_cgroup's USED bit is
1100 * set, the commit after this will fail, anyway.
1101 * This all charge/uncharge is done under some mutual execustion.
1102 * So, we don't need to taking care of changes in USED bit.
1104 if (likely(!PageLRU(page)))
1107 spin_lock_irqsave(&zone->lru_lock, flags);
1108 lru = page_lru(page);
1110 * The uncharged page could still be registered to the LRU of
1111 * the stale pc->mem_cgroup.
1113 * As pc->mem_cgroup is about to get overwritten, the old LRU
1114 * accounting needs to be taken care of. Let root_mem_cgroup
1115 * babysit the page until the new memcg is responsible for it.
1117 * The PCG_USED bit is guarded by lock_page() as the page is
1118 * swapcache/pagecache.
1120 if (PageLRU(page) && PageCgroupAcctLRU(pc) && !PageCgroupUsed(pc)) {
1121 del_page_from_lru_list(zone, page, lru);
1122 add_page_to_lru_list(zone, page, lru);
1124 spin_unlock_irqrestore(&zone->lru_lock, flags);
1127 static void mem_cgroup_lru_add_after_commit(struct page *page)
1130 unsigned long flags;
1131 struct zone *zone = page_zone(page);
1132 struct page_cgroup *pc = lookup_page_cgroup(page);
1135 * SetPageLRU SetPageCgroupUsed
1137 * PageCgroupUsed && add to memcg LRU PageLRU && add to memcg LRU
1139 * Ensure that one of the two sides adds the page to the memcg
1140 * LRU during a race.
1143 /* taking care of that the page is added to LRU while we commit it */
1144 if (likely(!PageLRU(page)))
1146 spin_lock_irqsave(&zone->lru_lock, flags);
1147 lru = page_lru(page);
1149 * If the page is not on the LRU, someone will soon put it
1150 * there. If it is, and also already accounted for on the
1151 * memcg-side, it must be on the right lruvec as setting
1152 * pc->mem_cgroup and PageCgroupUsed is properly ordered.
1153 * Otherwise, root_mem_cgroup has been babysitting the page
1154 * during the charge. Move it to the new memcg now.
1156 if (PageLRU(page) && !PageCgroupAcctLRU(pc)) {
1157 del_page_from_lru_list(zone, page, lru);
1158 add_page_to_lru_list(zone, page, lru);
1160 spin_unlock_irqrestore(&zone->lru_lock, flags);
1164 * Checks whether given mem is same or in the root_mem_cgroup's
1167 static bool mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1168 struct mem_cgroup *memcg)
1170 if (root_memcg != memcg) {
1171 return (root_memcg->use_hierarchy &&
1172 css_is_ancestor(&memcg->css, &root_memcg->css));
1178 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *memcg)
1181 struct mem_cgroup *curr = NULL;
1182 struct task_struct *p;
1184 p = find_lock_task_mm(task);
1187 curr = try_get_mem_cgroup_from_mm(p->mm);
1192 * We should check use_hierarchy of "memcg" not "curr". Because checking
1193 * use_hierarchy of "curr" here make this function true if hierarchy is
1194 * enabled in "curr" and "curr" is a child of "memcg" in *cgroup*
1195 * hierarchy(even if use_hierarchy is disabled in "memcg").
1197 ret = mem_cgroup_same_or_subtree(memcg, curr);
1198 css_put(&curr->css);
1202 int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg, struct zone *zone)
1204 unsigned long inactive_ratio;
1205 int nid = zone_to_nid(zone);
1206 int zid = zone_idx(zone);
1207 unsigned long inactive;
1208 unsigned long active;
1211 inactive = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1212 BIT(LRU_INACTIVE_ANON));
1213 active = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1214 BIT(LRU_ACTIVE_ANON));
1216 gb = (inactive + active) >> (30 - PAGE_SHIFT);
1218 inactive_ratio = int_sqrt(10 * gb);
1222 return inactive * inactive_ratio < active;
1225 int mem_cgroup_inactive_file_is_low(struct mem_cgroup *memcg, struct zone *zone)
1227 unsigned long active;
1228 unsigned long inactive;
1229 int zid = zone_idx(zone);
1230 int nid = zone_to_nid(zone);
1232 inactive = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1233 BIT(LRU_INACTIVE_FILE));
1234 active = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1235 BIT(LRU_ACTIVE_FILE));
1237 return (active > inactive);
1240 struct zone_reclaim_stat *mem_cgroup_get_reclaim_stat(struct mem_cgroup *memcg,
1243 int nid = zone_to_nid(zone);
1244 int zid = zone_idx(zone);
1245 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
1247 return &mz->reclaim_stat;
1250 struct zone_reclaim_stat *
1251 mem_cgroup_get_reclaim_stat_from_page(struct page *page)
1253 struct page_cgroup *pc;
1254 struct mem_cgroup_per_zone *mz;
1256 if (mem_cgroup_disabled())
1259 pc = lookup_page_cgroup(page);
1260 if (!PageCgroupUsed(pc))
1262 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1264 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1265 return &mz->reclaim_stat;
1268 #define mem_cgroup_from_res_counter(counter, member) \
1269 container_of(counter, struct mem_cgroup, member)
1272 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1273 * @mem: the memory cgroup
1275 * Returns the maximum amount of memory @mem can be charged with, in
1278 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1280 unsigned long long margin;
1282 margin = res_counter_margin(&memcg->res);
1283 if (do_swap_account)
1284 margin = min(margin, res_counter_margin(&memcg->memsw));
1285 return margin >> PAGE_SHIFT;
1288 int mem_cgroup_swappiness(struct mem_cgroup *memcg)
1290 struct cgroup *cgrp = memcg->css.cgroup;
1293 if (cgrp->parent == NULL)
1294 return vm_swappiness;
1296 return memcg->swappiness;
1299 static void mem_cgroup_start_move(struct mem_cgroup *memcg)
1304 spin_lock(&memcg->pcp_counter_lock);
1305 for_each_online_cpu(cpu)
1306 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) += 1;
1307 memcg->nocpu_base.count[MEM_CGROUP_ON_MOVE] += 1;
1308 spin_unlock(&memcg->pcp_counter_lock);
1314 static void mem_cgroup_end_move(struct mem_cgroup *memcg)
1321 spin_lock(&memcg->pcp_counter_lock);
1322 for_each_online_cpu(cpu)
1323 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) -= 1;
1324 memcg->nocpu_base.count[MEM_CGROUP_ON_MOVE] -= 1;
1325 spin_unlock(&memcg->pcp_counter_lock);
1329 * 2 routines for checking "mem" is under move_account() or not.
1331 * mem_cgroup_stealed() - checking a cgroup is mc.from or not. This is used
1332 * for avoiding race in accounting. If true,
1333 * pc->mem_cgroup may be overwritten.
1335 * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
1336 * under hierarchy of moving cgroups. This is for
1337 * waiting at hith-memory prressure caused by "move".
1340 static bool mem_cgroup_stealed(struct mem_cgroup *memcg)
1342 VM_BUG_ON(!rcu_read_lock_held());
1343 return this_cpu_read(memcg->stat->count[MEM_CGROUP_ON_MOVE]) > 0;
1346 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1348 struct mem_cgroup *from;
1349 struct mem_cgroup *to;
1352 * Unlike task_move routines, we access mc.to, mc.from not under
1353 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1355 spin_lock(&mc.lock);
1361 ret = mem_cgroup_same_or_subtree(memcg, from)
1362 || mem_cgroup_same_or_subtree(memcg, to);
1364 spin_unlock(&mc.lock);
1368 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1370 if (mc.moving_task && current != mc.moving_task) {
1371 if (mem_cgroup_under_move(memcg)) {
1373 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1374 /* moving charge context might have finished. */
1377 finish_wait(&mc.waitq, &wait);
1385 * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode.
1386 * @memcg: The memory cgroup that went over limit
1387 * @p: Task that is going to be killed
1389 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1392 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1394 struct cgroup *task_cgrp;
1395 struct cgroup *mem_cgrp;
1397 * Need a buffer in BSS, can't rely on allocations. The code relies
1398 * on the assumption that OOM is serialized for memory controller.
1399 * If this assumption is broken, revisit this code.
1401 static char memcg_name[PATH_MAX];
1410 mem_cgrp = memcg->css.cgroup;
1411 task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1413 ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1416 * Unfortunately, we are unable to convert to a useful name
1417 * But we'll still print out the usage information
1424 printk(KERN_INFO "Task in %s killed", memcg_name);
1427 ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1435 * Continues from above, so we don't need an KERN_ level
1437 printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
1440 printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
1441 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1442 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1443 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1444 printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
1446 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1447 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1448 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1452 * This function returns the number of memcg under hierarchy tree. Returns
1453 * 1(self count) if no children.
1455 static int mem_cgroup_count_children(struct mem_cgroup *memcg)
1458 struct mem_cgroup *iter;
1460 for_each_mem_cgroup_tree(iter, memcg)
1466 * Return the memory (and swap, if configured) limit for a memcg.
1468 u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
1473 limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
1474 limit += total_swap_pages << PAGE_SHIFT;
1476 memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
1478 * If memsw is finite and limits the amount of swap space available
1479 * to this memcg, return that limit.
1481 return min(limit, memsw);
1484 static unsigned long mem_cgroup_reclaim(struct mem_cgroup *memcg,
1486 unsigned long flags)
1488 unsigned long total = 0;
1489 bool noswap = false;
1492 if (flags & MEM_CGROUP_RECLAIM_NOSWAP)
1494 if (!(flags & MEM_CGROUP_RECLAIM_SHRINK) && memcg->memsw_is_minimum)
1497 for (loop = 0; loop < MEM_CGROUP_MAX_RECLAIM_LOOPS; loop++) {
1499 drain_all_stock_async(memcg);
1500 total += try_to_free_mem_cgroup_pages(memcg, gfp_mask, noswap);
1502 * Allow limit shrinkers, which are triggered directly
1503 * by userspace, to catch signals and stop reclaim
1504 * after minimal progress, regardless of the margin.
1506 if (total && (flags & MEM_CGROUP_RECLAIM_SHRINK))
1508 if (mem_cgroup_margin(memcg))
1511 * If nothing was reclaimed after two attempts, there
1512 * may be no reclaimable pages in this hierarchy.
1521 * test_mem_cgroup_node_reclaimable
1522 * @mem: the target memcg
1523 * @nid: the node ID to be checked.
1524 * @noswap : specify true here if the user wants flle only information.
1526 * This function returns whether the specified memcg contains any
1527 * reclaimable pages on a node. Returns true if there are any reclaimable
1528 * pages in the node.
1530 static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
1531 int nid, bool noswap)
1533 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE))
1535 if (noswap || !total_swap_pages)
1537 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON))
1542 #if MAX_NUMNODES > 1
1545 * Always updating the nodemask is not very good - even if we have an empty
1546 * list or the wrong list here, we can start from some node and traverse all
1547 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1550 static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
1554 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1555 * pagein/pageout changes since the last update.
1557 if (!atomic_read(&memcg->numainfo_events))
1559 if (atomic_inc_return(&memcg->numainfo_updating) > 1)
1562 /* make a nodemask where this memcg uses memory from */
1563 memcg->scan_nodes = node_states[N_HIGH_MEMORY];
1565 for_each_node_mask(nid, node_states[N_HIGH_MEMORY]) {
1567 if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
1568 node_clear(nid, memcg->scan_nodes);
1571 atomic_set(&memcg->numainfo_events, 0);
1572 atomic_set(&memcg->numainfo_updating, 0);
1576 * Selecting a node where we start reclaim from. Because what we need is just
1577 * reducing usage counter, start from anywhere is O,K. Considering
1578 * memory reclaim from current node, there are pros. and cons.
1580 * Freeing memory from current node means freeing memory from a node which
1581 * we'll use or we've used. So, it may make LRU bad. And if several threads
1582 * hit limits, it will see a contention on a node. But freeing from remote
1583 * node means more costs for memory reclaim because of memory latency.
1585 * Now, we use round-robin. Better algorithm is welcomed.
1587 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1591 mem_cgroup_may_update_nodemask(memcg);
1592 node = memcg->last_scanned_node;
1594 node = next_node(node, memcg->scan_nodes);
1595 if (node == MAX_NUMNODES)
1596 node = first_node(memcg->scan_nodes);
1598 * We call this when we hit limit, not when pages are added to LRU.
1599 * No LRU may hold pages because all pages are UNEVICTABLE or
1600 * memcg is too small and all pages are not on LRU. In that case,
1601 * we use curret node.
1603 if (unlikely(node == MAX_NUMNODES))
1604 node = numa_node_id();
1606 memcg->last_scanned_node = node;
1611 * Check all nodes whether it contains reclaimable pages or not.
1612 * For quick scan, we make use of scan_nodes. This will allow us to skip
1613 * unused nodes. But scan_nodes is lazily updated and may not cotain
1614 * enough new information. We need to do double check.
1616 bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
1621 * quick check...making use of scan_node.
1622 * We can skip unused nodes.
1624 if (!nodes_empty(memcg->scan_nodes)) {
1625 for (nid = first_node(memcg->scan_nodes);
1627 nid = next_node(nid, memcg->scan_nodes)) {
1629 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
1634 * Check rest of nodes.
1636 for_each_node_state(nid, N_HIGH_MEMORY) {
1637 if (node_isset(nid, memcg->scan_nodes))
1639 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
1646 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1651 bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
1653 return test_mem_cgroup_node_reclaimable(memcg, 0, noswap);
1657 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
1660 unsigned long *total_scanned)
1662 struct mem_cgroup *victim = NULL;
1665 unsigned long excess;
1666 unsigned long nr_scanned;
1667 struct mem_cgroup_reclaim_cookie reclaim = {
1672 excess = res_counter_soft_limit_excess(&root_memcg->res) >> PAGE_SHIFT;
1675 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1680 * If we have not been able to reclaim
1681 * anything, it might because there are
1682 * no reclaimable pages under this hierarchy
1687 * We want to do more targeted reclaim.
1688 * excess >> 2 is not to excessive so as to
1689 * reclaim too much, nor too less that we keep
1690 * coming back to reclaim from this cgroup
1692 if (total >= (excess >> 2) ||
1693 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1698 if (!mem_cgroup_reclaimable(victim, false))
1700 total += mem_cgroup_shrink_node_zone(victim, gfp_mask, false,
1702 *total_scanned += nr_scanned;
1703 if (!res_counter_soft_limit_excess(&root_memcg->res))
1706 mem_cgroup_iter_break(root_memcg, victim);
1711 * Check OOM-Killer is already running under our hierarchy.
1712 * If someone is running, return false.
1713 * Has to be called with memcg_oom_lock
1715 static bool mem_cgroup_oom_lock(struct mem_cgroup *memcg)
1717 struct mem_cgroup *iter, *failed = NULL;
1719 for_each_mem_cgroup_tree(iter, memcg) {
1720 if (iter->oom_lock) {
1722 * this subtree of our hierarchy is already locked
1723 * so we cannot give a lock.
1726 mem_cgroup_iter_break(memcg, iter);
1729 iter->oom_lock = true;
1736 * OK, we failed to lock the whole subtree so we have to clean up
1737 * what we set up to the failing subtree
1739 for_each_mem_cgroup_tree(iter, memcg) {
1740 if (iter == failed) {
1741 mem_cgroup_iter_break(memcg, iter);
1744 iter->oom_lock = false;
1750 * Has to be called with memcg_oom_lock
1752 static int mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1754 struct mem_cgroup *iter;
1756 for_each_mem_cgroup_tree(iter, memcg)
1757 iter->oom_lock = false;
1761 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1763 struct mem_cgroup *iter;
1765 for_each_mem_cgroup_tree(iter, memcg)
1766 atomic_inc(&iter->under_oom);
1769 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1771 struct mem_cgroup *iter;
1774 * When a new child is created while the hierarchy is under oom,
1775 * mem_cgroup_oom_lock() may not be called. We have to use
1776 * atomic_add_unless() here.
1778 for_each_mem_cgroup_tree(iter, memcg)
1779 atomic_add_unless(&iter->under_oom, -1, 0);
1782 static DEFINE_SPINLOCK(memcg_oom_lock);
1783 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1785 struct oom_wait_info {
1786 struct mem_cgroup *mem;
1790 static int memcg_oom_wake_function(wait_queue_t *wait,
1791 unsigned mode, int sync, void *arg)
1793 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg,
1795 struct oom_wait_info *oom_wait_info;
1797 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1798 oom_wait_memcg = oom_wait_info->mem;
1801 * Both of oom_wait_info->mem and wake_mem are stable under us.
1802 * Then we can use css_is_ancestor without taking care of RCU.
1804 if (!mem_cgroup_same_or_subtree(oom_wait_memcg, wake_memcg)
1805 && !mem_cgroup_same_or_subtree(wake_memcg, oom_wait_memcg))
1807 return autoremove_wake_function(wait, mode, sync, arg);
1810 static void memcg_wakeup_oom(struct mem_cgroup *memcg)
1812 /* for filtering, pass "memcg" as argument. */
1813 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
1816 static void memcg_oom_recover(struct mem_cgroup *memcg)
1818 if (memcg && atomic_read(&memcg->under_oom))
1819 memcg_wakeup_oom(memcg);
1823 * try to call OOM killer. returns false if we should exit memory-reclaim loop.
1825 bool mem_cgroup_handle_oom(struct mem_cgroup *memcg, gfp_t mask)
1827 struct oom_wait_info owait;
1828 bool locked, need_to_kill;
1831 owait.wait.flags = 0;
1832 owait.wait.func = memcg_oom_wake_function;
1833 owait.wait.private = current;
1834 INIT_LIST_HEAD(&owait.wait.task_list);
1835 need_to_kill = true;
1836 mem_cgroup_mark_under_oom(memcg);
1838 /* At first, try to OOM lock hierarchy under memcg.*/
1839 spin_lock(&memcg_oom_lock);
1840 locked = mem_cgroup_oom_lock(memcg);
1842 * Even if signal_pending(), we can't quit charge() loop without
1843 * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
1844 * under OOM is always welcomed, use TASK_KILLABLE here.
1846 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
1847 if (!locked || memcg->oom_kill_disable)
1848 need_to_kill = false;
1850 mem_cgroup_oom_notify(memcg);
1851 spin_unlock(&memcg_oom_lock);
1854 finish_wait(&memcg_oom_waitq, &owait.wait);
1855 mem_cgroup_out_of_memory(memcg, mask);
1858 finish_wait(&memcg_oom_waitq, &owait.wait);
1860 spin_lock(&memcg_oom_lock);
1862 mem_cgroup_oom_unlock(memcg);
1863 memcg_wakeup_oom(memcg);
1864 spin_unlock(&memcg_oom_lock);
1866 mem_cgroup_unmark_under_oom(memcg);
1868 if (test_thread_flag(TIF_MEMDIE) || fatal_signal_pending(current))
1870 /* Give chance to dying process */
1871 schedule_timeout_uninterruptible(1);
1876 * Currently used to update mapped file statistics, but the routine can be
1877 * generalized to update other statistics as well.
1879 * Notes: Race condition
1881 * We usually use page_cgroup_lock() for accessing page_cgroup member but
1882 * it tends to be costly. But considering some conditions, we doesn't need
1883 * to do so _always_.
1885 * Considering "charge", lock_page_cgroup() is not required because all
1886 * file-stat operations happen after a page is attached to radix-tree. There
1887 * are no race with "charge".
1889 * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
1890 * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
1891 * if there are race with "uncharge". Statistics itself is properly handled
1894 * Considering "move", this is an only case we see a race. To make the race
1895 * small, we check MEM_CGROUP_ON_MOVE percpu value and detect there are
1896 * possibility of race condition. If there is, we take a lock.
1899 void mem_cgroup_update_page_stat(struct page *page,
1900 enum mem_cgroup_page_stat_item idx, int val)
1902 struct mem_cgroup *memcg;
1903 struct page_cgroup *pc = lookup_page_cgroup(page);
1904 bool need_unlock = false;
1905 unsigned long uninitialized_var(flags);
1911 memcg = pc->mem_cgroup;
1912 if (unlikely(!memcg || !PageCgroupUsed(pc)))
1914 /* pc->mem_cgroup is unstable ? */
1915 if (unlikely(mem_cgroup_stealed(memcg)) || PageTransHuge(page)) {
1916 /* take a lock against to access pc->mem_cgroup */
1917 move_lock_page_cgroup(pc, &flags);
1919 memcg = pc->mem_cgroup;
1920 if (!memcg || !PageCgroupUsed(pc))
1925 case MEMCG_NR_FILE_MAPPED:
1927 SetPageCgroupFileMapped(pc);
1928 else if (!page_mapped(page))
1929 ClearPageCgroupFileMapped(pc);
1930 idx = MEM_CGROUP_STAT_FILE_MAPPED;
1936 this_cpu_add(memcg->stat->count[idx], val);
1939 if (unlikely(need_unlock))
1940 move_unlock_page_cgroup(pc, &flags);
1944 EXPORT_SYMBOL(mem_cgroup_update_page_stat);
1947 * size of first charge trial. "32" comes from vmscan.c's magic value.
1948 * TODO: maybe necessary to use big numbers in big irons.
1950 #define CHARGE_BATCH 32U
1951 struct memcg_stock_pcp {
1952 struct mem_cgroup *cached; /* this never be root cgroup */
1953 unsigned int nr_pages;
1954 struct work_struct work;
1955 unsigned long flags;
1956 #define FLUSHING_CACHED_CHARGE (0)
1958 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
1959 static DEFINE_MUTEX(percpu_charge_mutex);
1962 * Try to consume stocked charge on this cpu. If success, one page is consumed
1963 * from local stock and true is returned. If the stock is 0 or charges from a
1964 * cgroup which is not current target, returns false. This stock will be
1967 static bool consume_stock(struct mem_cgroup *memcg)
1969 struct memcg_stock_pcp *stock;
1972 stock = &get_cpu_var(memcg_stock);
1973 if (memcg == stock->cached && stock->nr_pages)
1975 else /* need to call res_counter_charge */
1977 put_cpu_var(memcg_stock);
1982 * Returns stocks cached in percpu to res_counter and reset cached information.
1984 static void drain_stock(struct memcg_stock_pcp *stock)
1986 struct mem_cgroup *old = stock->cached;
1988 if (stock->nr_pages) {
1989 unsigned long bytes = stock->nr_pages * PAGE_SIZE;
1991 res_counter_uncharge(&old->res, bytes);
1992 if (do_swap_account)
1993 res_counter_uncharge(&old->memsw, bytes);
1994 stock->nr_pages = 0;
1996 stock->cached = NULL;
2000 * This must be called under preempt disabled or must be called by
2001 * a thread which is pinned to local cpu.
2003 static void drain_local_stock(struct work_struct *dummy)
2005 struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
2007 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2011 * Cache charges(val) which is from res_counter, to local per_cpu area.
2012 * This will be consumed by consume_stock() function, later.
2014 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2016 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
2018 if (stock->cached != memcg) { /* reset if necessary */
2020 stock->cached = memcg;
2022 stock->nr_pages += nr_pages;
2023 put_cpu_var(memcg_stock);
2027 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2028 * of the hierarchy under it. sync flag says whether we should block
2029 * until the work is done.
2031 static void drain_all_stock(struct mem_cgroup *root_memcg, bool sync)
2035 /* Notify other cpus that system-wide "drain" is running */
2038 for_each_online_cpu(cpu) {
2039 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2040 struct mem_cgroup *memcg;
2042 memcg = stock->cached;
2043 if (!memcg || !stock->nr_pages)
2045 if (!mem_cgroup_same_or_subtree(root_memcg, memcg))
2047 if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2049 drain_local_stock(&stock->work);
2051 schedule_work_on(cpu, &stock->work);
2059 for_each_online_cpu(cpu) {
2060 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2061 if (test_bit(FLUSHING_CACHED_CHARGE, &stock->flags))
2062 flush_work(&stock->work);
2069 * Tries to drain stocked charges in other cpus. This function is asynchronous
2070 * and just put a work per cpu for draining localy on each cpu. Caller can
2071 * expects some charges will be back to res_counter later but cannot wait for
2074 static void drain_all_stock_async(struct mem_cgroup *root_memcg)
2077 * If someone calls draining, avoid adding more kworker runs.
2079 if (!mutex_trylock(&percpu_charge_mutex))
2081 drain_all_stock(root_memcg, false);
2082 mutex_unlock(&percpu_charge_mutex);
2085 /* This is a synchronous drain interface. */
2086 static void drain_all_stock_sync(struct mem_cgroup *root_memcg)
2088 /* called when force_empty is called */
2089 mutex_lock(&percpu_charge_mutex);
2090 drain_all_stock(root_memcg, true);
2091 mutex_unlock(&percpu_charge_mutex);
2095 * This function drains percpu counter value from DEAD cpu and
2096 * move it to local cpu. Note that this function can be preempted.
2098 static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *memcg, int cpu)
2102 spin_lock(&memcg->pcp_counter_lock);
2103 for (i = 0; i < MEM_CGROUP_STAT_DATA; i++) {
2104 long x = per_cpu(memcg->stat->count[i], cpu);
2106 per_cpu(memcg->stat->count[i], cpu) = 0;
2107 memcg->nocpu_base.count[i] += x;
2109 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
2110 unsigned long x = per_cpu(memcg->stat->events[i], cpu);
2112 per_cpu(memcg->stat->events[i], cpu) = 0;
2113 memcg->nocpu_base.events[i] += x;
2115 /* need to clear ON_MOVE value, works as a kind of lock. */
2116 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) = 0;
2117 spin_unlock(&memcg->pcp_counter_lock);
2120 static void synchronize_mem_cgroup_on_move(struct mem_cgroup *memcg, int cpu)
2122 int idx = MEM_CGROUP_ON_MOVE;
2124 spin_lock(&memcg->pcp_counter_lock);
2125 per_cpu(memcg->stat->count[idx], cpu) = memcg->nocpu_base.count[idx];
2126 spin_unlock(&memcg->pcp_counter_lock);
2129 static int __cpuinit memcg_cpu_hotplug_callback(struct notifier_block *nb,
2130 unsigned long action,
2133 int cpu = (unsigned long)hcpu;
2134 struct memcg_stock_pcp *stock;
2135 struct mem_cgroup *iter;
2137 if ((action == CPU_ONLINE)) {
2138 for_each_mem_cgroup(iter)
2139 synchronize_mem_cgroup_on_move(iter, cpu);
2143 if ((action != CPU_DEAD) || action != CPU_DEAD_FROZEN)
2146 for_each_mem_cgroup(iter)
2147 mem_cgroup_drain_pcp_counter(iter, cpu);
2149 stock = &per_cpu(memcg_stock, cpu);
2155 /* See __mem_cgroup_try_charge() for details */
2157 CHARGE_OK, /* success */
2158 CHARGE_RETRY, /* need to retry but retry is not bad */
2159 CHARGE_NOMEM, /* we can't do more. return -ENOMEM */
2160 CHARGE_WOULDBLOCK, /* GFP_WAIT wasn't set and no enough res. */
2161 CHARGE_OOM_DIE, /* the current is killed because of OOM */
2164 static int mem_cgroup_do_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2165 unsigned int nr_pages, bool oom_check)
2167 unsigned long csize = nr_pages * PAGE_SIZE;
2168 struct mem_cgroup *mem_over_limit;
2169 struct res_counter *fail_res;
2170 unsigned long flags = 0;
2173 ret = res_counter_charge(&memcg->res, csize, &fail_res);
2176 if (!do_swap_account)
2178 ret = res_counter_charge(&memcg->memsw, csize, &fail_res);
2182 res_counter_uncharge(&memcg->res, csize);
2183 mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw);
2184 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
2186 mem_over_limit = mem_cgroup_from_res_counter(fail_res, res);
2188 * nr_pages can be either a huge page (HPAGE_PMD_NR), a batch
2189 * of regular pages (CHARGE_BATCH), or a single regular page (1).
2191 * Never reclaim on behalf of optional batching, retry with a
2192 * single page instead.
2194 if (nr_pages == CHARGE_BATCH)
2195 return CHARGE_RETRY;
2197 if (!(gfp_mask & __GFP_WAIT))
2198 return CHARGE_WOULDBLOCK;
2200 ret = mem_cgroup_reclaim(mem_over_limit, gfp_mask, flags);
2201 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2202 return CHARGE_RETRY;
2204 * Even though the limit is exceeded at this point, reclaim
2205 * may have been able to free some pages. Retry the charge
2206 * before killing the task.
2208 * Only for regular pages, though: huge pages are rather
2209 * unlikely to succeed so close to the limit, and we fall back
2210 * to regular pages anyway in case of failure.
2212 if (nr_pages == 1 && ret)
2213 return CHARGE_RETRY;
2216 * At task move, charge accounts can be doubly counted. So, it's
2217 * better to wait until the end of task_move if something is going on.
2219 if (mem_cgroup_wait_acct_move(mem_over_limit))
2220 return CHARGE_RETRY;
2222 /* If we don't need to call oom-killer at el, return immediately */
2224 return CHARGE_NOMEM;
2226 if (!mem_cgroup_handle_oom(mem_over_limit, gfp_mask))
2227 return CHARGE_OOM_DIE;
2229 return CHARGE_RETRY;
2233 * Unlike exported interface, "oom" parameter is added. if oom==true,
2234 * oom-killer can be invoked.
2236 static int __mem_cgroup_try_charge(struct mm_struct *mm,
2238 unsigned int nr_pages,
2239 struct mem_cgroup **ptr,
2242 unsigned int batch = max(CHARGE_BATCH, nr_pages);
2243 int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2244 struct mem_cgroup *memcg = NULL;
2248 * Unlike gloval-vm's OOM-kill, we're not in memory shortage
2249 * in system level. So, allow to go ahead dying process in addition to
2252 if (unlikely(test_thread_flag(TIF_MEMDIE)
2253 || fatal_signal_pending(current)))
2257 * We always charge the cgroup the mm_struct belongs to.
2258 * The mm_struct's mem_cgroup changes on task migration if the
2259 * thread group leader migrates. It's possible that mm is not
2260 * set, if so charge the init_mm (happens for pagecache usage).
2265 if (*ptr) { /* css should be a valid one */
2267 VM_BUG_ON(css_is_removed(&memcg->css));
2268 if (mem_cgroup_is_root(memcg))
2270 if (nr_pages == 1 && consume_stock(memcg))
2272 css_get(&memcg->css);
2274 struct task_struct *p;
2277 p = rcu_dereference(mm->owner);
2279 * Because we don't have task_lock(), "p" can exit.
2280 * In that case, "memcg" can point to root or p can be NULL with
2281 * race with swapoff. Then, we have small risk of mis-accouning.
2282 * But such kind of mis-account by race always happens because
2283 * we don't have cgroup_mutex(). It's overkill and we allo that
2285 * (*) swapoff at el will charge against mm-struct not against
2286 * task-struct. So, mm->owner can be NULL.
2288 memcg = mem_cgroup_from_task(p);
2289 if (!memcg || mem_cgroup_is_root(memcg)) {
2293 if (nr_pages == 1 && consume_stock(memcg)) {
2295 * It seems dagerous to access memcg without css_get().
2296 * But considering how consume_stok works, it's not
2297 * necessary. If consume_stock success, some charges
2298 * from this memcg are cached on this cpu. So, we
2299 * don't need to call css_get()/css_tryget() before
2300 * calling consume_stock().
2305 /* after here, we may be blocked. we need to get refcnt */
2306 if (!css_tryget(&memcg->css)) {
2316 /* If killed, bypass charge */
2317 if (fatal_signal_pending(current)) {
2318 css_put(&memcg->css);
2323 if (oom && !nr_oom_retries) {
2325 nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2328 ret = mem_cgroup_do_charge(memcg, gfp_mask, batch, oom_check);
2332 case CHARGE_RETRY: /* not in OOM situation but retry */
2334 css_put(&memcg->css);
2337 case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
2338 css_put(&memcg->css);
2340 case CHARGE_NOMEM: /* OOM routine works */
2342 css_put(&memcg->css);
2345 /* If oom, we never return -ENOMEM */
2348 case CHARGE_OOM_DIE: /* Killed by OOM Killer */
2349 css_put(&memcg->css);
2352 } while (ret != CHARGE_OK);
2354 if (batch > nr_pages)
2355 refill_stock(memcg, batch - nr_pages);
2356 css_put(&memcg->css);
2369 * Somemtimes we have to undo a charge we got by try_charge().
2370 * This function is for that and do uncharge, put css's refcnt.
2371 * gotten by try_charge().
2373 static void __mem_cgroup_cancel_charge(struct mem_cgroup *memcg,
2374 unsigned int nr_pages)
2376 if (!mem_cgroup_is_root(memcg)) {
2377 unsigned long bytes = nr_pages * PAGE_SIZE;
2379 res_counter_uncharge(&memcg->res, bytes);
2380 if (do_swap_account)
2381 res_counter_uncharge(&memcg->memsw, bytes);
2386 * A helper function to get mem_cgroup from ID. must be called under
2387 * rcu_read_lock(). The caller must check css_is_removed() or some if
2388 * it's concern. (dropping refcnt from swap can be called against removed
2391 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
2393 struct cgroup_subsys_state *css;
2395 /* ID 0 is unused ID */
2398 css = css_lookup(&mem_cgroup_subsys, id);
2401 return container_of(css, struct mem_cgroup, css);
2404 struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
2406 struct mem_cgroup *memcg = NULL;
2407 struct page_cgroup *pc;
2411 VM_BUG_ON(!PageLocked(page));
2413 pc = lookup_page_cgroup(page);
2414 lock_page_cgroup(pc);
2415 if (PageCgroupUsed(pc)) {
2416 memcg = pc->mem_cgroup;
2417 if (memcg && !css_tryget(&memcg->css))
2419 } else if (PageSwapCache(page)) {
2420 ent.val = page_private(page);
2421 id = lookup_swap_cgroup(ent);
2423 memcg = mem_cgroup_lookup(id);
2424 if (memcg && !css_tryget(&memcg->css))
2428 unlock_page_cgroup(pc);
2432 static void __mem_cgroup_commit_charge(struct mem_cgroup *memcg,
2434 unsigned int nr_pages,
2435 struct page_cgroup *pc,
2436 enum charge_type ctype)
2438 lock_page_cgroup(pc);
2439 if (unlikely(PageCgroupUsed(pc))) {
2440 unlock_page_cgroup(pc);
2441 __mem_cgroup_cancel_charge(memcg, nr_pages);
2445 * we don't need page_cgroup_lock about tail pages, becase they are not
2446 * accessed by any other context at this point.
2448 pc->mem_cgroup = memcg;
2450 * We access a page_cgroup asynchronously without lock_page_cgroup().
2451 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
2452 * is accessed after testing USED bit. To make pc->mem_cgroup visible
2453 * before USED bit, we need memory barrier here.
2454 * See mem_cgroup_add_lru_list(), etc.
2458 case MEM_CGROUP_CHARGE_TYPE_CACHE:
2459 case MEM_CGROUP_CHARGE_TYPE_SHMEM:
2460 SetPageCgroupCache(pc);
2461 SetPageCgroupUsed(pc);
2463 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
2464 ClearPageCgroupCache(pc);
2465 SetPageCgroupUsed(pc);
2471 mem_cgroup_charge_statistics(memcg, PageCgroupCache(pc), nr_pages);
2472 unlock_page_cgroup(pc);
2474 * "charge_statistics" updated event counter. Then, check it.
2475 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
2476 * if they exceeds softlimit.
2478 memcg_check_events(memcg, page);
2481 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2483 #define PCGF_NOCOPY_AT_SPLIT ((1 << PCG_LOCK) | (1 << PCG_MOVE_LOCK) |\
2484 (1 << PCG_ACCT_LRU) | (1 << PCG_MIGRATION))
2486 * Because tail pages are not marked as "used", set it. We're under
2487 * zone->lru_lock, 'splitting on pmd' and compound_lock.
2488 * charge/uncharge will be never happen and move_account() is done under
2489 * compound_lock(), so we don't have to take care of races.
2491 void mem_cgroup_split_huge_fixup(struct page *head)
2493 struct page_cgroup *head_pc = lookup_page_cgroup(head);
2494 struct page_cgroup *pc;
2497 if (mem_cgroup_disabled())
2499 for (i = 1; i < HPAGE_PMD_NR; i++) {
2501 pc->mem_cgroup = head_pc->mem_cgroup;
2502 smp_wmb();/* see __commit_charge() */
2504 * LRU flags cannot be copied because we need to add tail
2505 * page to LRU by generic call and our hooks will be called.
2507 pc->flags = head_pc->flags & ~PCGF_NOCOPY_AT_SPLIT;
2510 if (PageCgroupAcctLRU(head_pc)) {
2512 struct mem_cgroup_per_zone *mz;
2514 * We hold lru_lock, then, reduce counter directly.
2516 lru = page_lru(head);
2517 mz = page_cgroup_zoneinfo(head_pc->mem_cgroup, head);
2518 MEM_CGROUP_ZSTAT(mz, lru) -= HPAGE_PMD_NR - 1;
2524 * mem_cgroup_move_account - move account of the page
2526 * @nr_pages: number of regular pages (>1 for huge pages)
2527 * @pc: page_cgroup of the page.
2528 * @from: mem_cgroup which the page is moved from.
2529 * @to: mem_cgroup which the page is moved to. @from != @to.
2530 * @uncharge: whether we should call uncharge and css_put against @from.
2532 * The caller must confirm following.
2533 * - page is not on LRU (isolate_page() is useful.)
2534 * - compound_lock is held when nr_pages > 1
2536 * This function doesn't do "charge" nor css_get to new cgroup. It should be
2537 * done by a caller(__mem_cgroup_try_charge would be useful). If @uncharge is
2538 * true, this function does "uncharge" from old cgroup, but it doesn't if
2539 * @uncharge is false, so a caller should do "uncharge".
2541 static int mem_cgroup_move_account(struct page *page,
2542 unsigned int nr_pages,
2543 struct page_cgroup *pc,
2544 struct mem_cgroup *from,
2545 struct mem_cgroup *to,
2548 unsigned long flags;
2551 VM_BUG_ON(from == to);
2552 VM_BUG_ON(PageLRU(page));
2554 * The page is isolated from LRU. So, collapse function
2555 * will not handle this page. But page splitting can happen.
2556 * Do this check under compound_page_lock(). The caller should
2560 if (nr_pages > 1 && !PageTransHuge(page))
2563 lock_page_cgroup(pc);
2566 if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
2569 move_lock_page_cgroup(pc, &flags);
2571 if (PageCgroupFileMapped(pc)) {
2572 /* Update mapped_file data for mem_cgroup */
2574 __this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2575 __this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2578 mem_cgroup_charge_statistics(from, PageCgroupCache(pc), -nr_pages);
2580 /* This is not "cancel", but cancel_charge does all we need. */
2581 __mem_cgroup_cancel_charge(from, nr_pages);
2583 /* caller should have done css_get */
2584 pc->mem_cgroup = to;
2585 mem_cgroup_charge_statistics(to, PageCgroupCache(pc), nr_pages);
2587 * We charges against "to" which may not have any tasks. Then, "to"
2588 * can be under rmdir(). But in current implementation, caller of
2589 * this function is just force_empty() and move charge, so it's
2590 * guaranteed that "to" is never removed. So, we don't check rmdir
2593 move_unlock_page_cgroup(pc, &flags);
2596 unlock_page_cgroup(pc);
2600 memcg_check_events(to, page);
2601 memcg_check_events(from, page);
2607 * move charges to its parent.
2610 static int mem_cgroup_move_parent(struct page *page,
2611 struct page_cgroup *pc,
2612 struct mem_cgroup *child,
2615 struct cgroup *cg = child->css.cgroup;
2616 struct cgroup *pcg = cg->parent;
2617 struct mem_cgroup *parent;
2618 unsigned int nr_pages;
2619 unsigned long uninitialized_var(flags);
2627 if (!get_page_unless_zero(page))
2629 if (isolate_lru_page(page))
2632 nr_pages = hpage_nr_pages(page);
2634 parent = mem_cgroup_from_cont(pcg);
2635 ret = __mem_cgroup_try_charge(NULL, gfp_mask, nr_pages, &parent, false);
2640 flags = compound_lock_irqsave(page);
2642 ret = mem_cgroup_move_account(page, nr_pages, pc, child, parent, true);
2644 __mem_cgroup_cancel_charge(parent, nr_pages);
2647 compound_unlock_irqrestore(page, flags);
2649 putback_lru_page(page);
2657 * Charge the memory controller for page usage.
2659 * 0 if the charge was successful
2660 * < 0 if the cgroup is over its limit
2662 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
2663 gfp_t gfp_mask, enum charge_type ctype)
2665 struct mem_cgroup *memcg = NULL;
2666 unsigned int nr_pages = 1;
2667 struct page_cgroup *pc;
2671 if (PageTransHuge(page)) {
2672 nr_pages <<= compound_order(page);
2673 VM_BUG_ON(!PageTransHuge(page));
2675 * Never OOM-kill a process for a huge page. The
2676 * fault handler will fall back to regular pages.
2681 pc = lookup_page_cgroup(page);
2682 BUG_ON(!pc); /* XXX: remove this and move pc lookup into commit */
2684 ret = __mem_cgroup_try_charge(mm, gfp_mask, nr_pages, &memcg, oom);
2688 __mem_cgroup_commit_charge(memcg, page, nr_pages, pc, ctype);
2692 int mem_cgroup_newpage_charge(struct page *page,
2693 struct mm_struct *mm, gfp_t gfp_mask)
2695 if (mem_cgroup_disabled())
2698 * If already mapped, we don't have to account.
2699 * If page cache, page->mapping has address_space.
2700 * But page->mapping may have out-of-use anon_vma pointer,
2701 * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
2704 if (page_mapped(page) || (page->mapping && !PageAnon(page)))
2708 return mem_cgroup_charge_common(page, mm, gfp_mask,
2709 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2713 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2714 enum charge_type ctype);
2717 __mem_cgroup_commit_charge_lrucare(struct page *page, struct mem_cgroup *memcg,
2718 enum charge_type ctype)
2720 struct page_cgroup *pc = lookup_page_cgroup(page);
2722 * In some case, SwapCache, FUSE(splice_buf->radixtree), the page
2723 * is already on LRU. It means the page may on some other page_cgroup's
2724 * LRU. Take care of it.
2726 mem_cgroup_lru_del_before_commit(page);
2727 __mem_cgroup_commit_charge(memcg, page, 1, pc, ctype);
2728 mem_cgroup_lru_add_after_commit(page);
2732 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
2735 struct mem_cgroup *memcg = NULL;
2738 if (mem_cgroup_disabled())
2740 if (PageCompound(page))
2746 if (page_is_file_cache(page)) {
2747 ret = __mem_cgroup_try_charge(mm, gfp_mask, 1, &memcg, true);
2752 * FUSE reuses pages without going through the final
2753 * put that would remove them from the LRU list, make
2754 * sure that they get relinked properly.
2756 __mem_cgroup_commit_charge_lrucare(page, memcg,
2757 MEM_CGROUP_CHARGE_TYPE_CACHE);
2761 if (PageSwapCache(page)) {
2762 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &memcg);
2764 __mem_cgroup_commit_charge_swapin(page, memcg,
2765 MEM_CGROUP_CHARGE_TYPE_SHMEM);
2767 ret = mem_cgroup_charge_common(page, mm, gfp_mask,
2768 MEM_CGROUP_CHARGE_TYPE_SHMEM);
2774 * While swap-in, try_charge -> commit or cancel, the page is locked.
2775 * And when try_charge() successfully returns, one refcnt to memcg without
2776 * struct page_cgroup is acquired. This refcnt will be consumed by
2777 * "commit()" or removed by "cancel()"
2779 int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
2781 gfp_t mask, struct mem_cgroup **memcgp)
2783 struct mem_cgroup *memcg;
2788 if (mem_cgroup_disabled())
2791 if (!do_swap_account)
2794 * A racing thread's fault, or swapoff, may have already updated
2795 * the pte, and even removed page from swap cache: in those cases
2796 * do_swap_page()'s pte_same() test will fail; but there's also a
2797 * KSM case which does need to charge the page.
2799 if (!PageSwapCache(page))
2801 memcg = try_get_mem_cgroup_from_page(page);
2805 ret = __mem_cgroup_try_charge(NULL, mask, 1, memcgp, true);
2806 css_put(&memcg->css);
2811 return __mem_cgroup_try_charge(mm, mask, 1, memcgp, true);
2815 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *memcg,
2816 enum charge_type ctype)
2818 if (mem_cgroup_disabled())
2822 cgroup_exclude_rmdir(&memcg->css);
2824 __mem_cgroup_commit_charge_lrucare(page, memcg, ctype);
2826 * Now swap is on-memory. This means this page may be
2827 * counted both as mem and swap....double count.
2828 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
2829 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
2830 * may call delete_from_swap_cache() before reach here.
2832 if (do_swap_account && PageSwapCache(page)) {
2833 swp_entry_t ent = {.val = page_private(page)};
2834 struct mem_cgroup *swap_memcg;
2837 id = swap_cgroup_record(ent, 0);
2839 swap_memcg = mem_cgroup_lookup(id);
2842 * This recorded memcg can be obsolete one. So, avoid
2843 * calling css_tryget
2845 if (!mem_cgroup_is_root(swap_memcg))
2846 res_counter_uncharge(&swap_memcg->memsw,
2848 mem_cgroup_swap_statistics(swap_memcg, false);
2849 mem_cgroup_put(swap_memcg);
2854 * At swapin, we may charge account against cgroup which has no tasks.
2855 * So, rmdir()->pre_destroy() can be called while we do this charge.
2856 * In that case, we need to call pre_destroy() again. check it here.
2858 cgroup_release_and_wakeup_rmdir(&memcg->css);
2861 void mem_cgroup_commit_charge_swapin(struct page *page,
2862 struct mem_cgroup *memcg)
2864 __mem_cgroup_commit_charge_swapin(page, memcg,
2865 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2868 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *memcg)
2870 if (mem_cgroup_disabled())
2874 __mem_cgroup_cancel_charge(memcg, 1);
2877 static void mem_cgroup_do_uncharge(struct mem_cgroup *memcg,
2878 unsigned int nr_pages,
2879 const enum charge_type ctype)
2881 struct memcg_batch_info *batch = NULL;
2882 bool uncharge_memsw = true;
2884 /* If swapout, usage of swap doesn't decrease */
2885 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2886 uncharge_memsw = false;
2888 batch = ¤t->memcg_batch;
2890 * In usual, we do css_get() when we remember memcg pointer.
2891 * But in this case, we keep res->usage until end of a series of
2892 * uncharges. Then, it's ok to ignore memcg's refcnt.
2895 batch->memcg = memcg;
2897 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
2898 * In those cases, all pages freed continuously can be expected to be in
2899 * the same cgroup and we have chance to coalesce uncharges.
2900 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
2901 * because we want to do uncharge as soon as possible.
2904 if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
2905 goto direct_uncharge;
2908 goto direct_uncharge;
2911 * In typical case, batch->memcg == mem. This means we can
2912 * merge a series of uncharges to an uncharge of res_counter.
2913 * If not, we uncharge res_counter ony by one.
2915 if (batch->memcg != memcg)
2916 goto direct_uncharge;
2917 /* remember freed charge and uncharge it later */
2920 batch->memsw_nr_pages++;
2923 res_counter_uncharge(&memcg->res, nr_pages * PAGE_SIZE);
2925 res_counter_uncharge(&memcg->memsw, nr_pages * PAGE_SIZE);
2926 if (unlikely(batch->memcg != memcg))
2927 memcg_oom_recover(memcg);
2932 * uncharge if !page_mapped(page)
2934 static struct mem_cgroup *
2935 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
2937 struct mem_cgroup *memcg = NULL;
2938 unsigned int nr_pages = 1;
2939 struct page_cgroup *pc;
2941 if (mem_cgroup_disabled())
2944 if (PageSwapCache(page))
2947 if (PageTransHuge(page)) {
2948 nr_pages <<= compound_order(page);
2949 VM_BUG_ON(!PageTransHuge(page));
2952 * Check if our page_cgroup is valid
2954 pc = lookup_page_cgroup(page);
2955 if (unlikely(!pc || !PageCgroupUsed(pc)))
2958 lock_page_cgroup(pc);
2960 memcg = pc->mem_cgroup;
2962 if (!PageCgroupUsed(pc))
2966 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
2967 case MEM_CGROUP_CHARGE_TYPE_DROP:
2968 /* See mem_cgroup_prepare_migration() */
2969 if (page_mapped(page) || PageCgroupMigration(pc))
2972 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
2973 if (!PageAnon(page)) { /* Shared memory */
2974 if (page->mapping && !page_is_file_cache(page))
2976 } else if (page_mapped(page)) /* Anon */
2983 mem_cgroup_charge_statistics(memcg, PageCgroupCache(pc), -nr_pages);
2985 ClearPageCgroupUsed(pc);
2987 * pc->mem_cgroup is not cleared here. It will be accessed when it's
2988 * freed from LRU. This is safe because uncharged page is expected not
2989 * to be reused (freed soon). Exception is SwapCache, it's handled by
2990 * special functions.
2993 unlock_page_cgroup(pc);
2995 * even after unlock, we have memcg->res.usage here and this memcg
2996 * will never be freed.
2998 memcg_check_events(memcg, page);
2999 if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
3000 mem_cgroup_swap_statistics(memcg, true);
3001 mem_cgroup_get(memcg);
3003 if (!mem_cgroup_is_root(memcg))
3004 mem_cgroup_do_uncharge(memcg, nr_pages, ctype);
3009 unlock_page_cgroup(pc);
3013 void mem_cgroup_uncharge_page(struct page *page)
3016 if (page_mapped(page))
3018 if (page->mapping && !PageAnon(page))
3020 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
3023 void mem_cgroup_uncharge_cache_page(struct page *page)
3025 VM_BUG_ON(page_mapped(page));
3026 VM_BUG_ON(page->mapping);
3027 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
3031 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
3032 * In that cases, pages are freed continuously and we can expect pages
3033 * are in the same memcg. All these calls itself limits the number of
3034 * pages freed at once, then uncharge_start/end() is called properly.
3035 * This may be called prural(2) times in a context,
3038 void mem_cgroup_uncharge_start(void)
3040 current->memcg_batch.do_batch++;
3041 /* We can do nest. */
3042 if (current->memcg_batch.do_batch == 1) {
3043 current->memcg_batch.memcg = NULL;
3044 current->memcg_batch.nr_pages = 0;
3045 current->memcg_batch.memsw_nr_pages = 0;
3049 void mem_cgroup_uncharge_end(void)
3051 struct memcg_batch_info *batch = ¤t->memcg_batch;
3053 if (!batch->do_batch)
3057 if (batch->do_batch) /* If stacked, do nothing. */
3063 * This "batch->memcg" is valid without any css_get/put etc...
3064 * bacause we hide charges behind us.
3066 if (batch->nr_pages)
3067 res_counter_uncharge(&batch->memcg->res,
3068 batch->nr_pages * PAGE_SIZE);
3069 if (batch->memsw_nr_pages)
3070 res_counter_uncharge(&batch->memcg->memsw,
3071 batch->memsw_nr_pages * PAGE_SIZE);
3072 memcg_oom_recover(batch->memcg);
3073 /* forget this pointer (for sanity check) */
3074 batch->memcg = NULL;
3079 * called after __delete_from_swap_cache() and drop "page" account.
3080 * memcg information is recorded to swap_cgroup of "ent"
3083 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
3085 struct mem_cgroup *memcg;
3086 int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
3088 if (!swapout) /* this was a swap cache but the swap is unused ! */
3089 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
3091 memcg = __mem_cgroup_uncharge_common(page, ctype);
3094 * record memcg information, if swapout && memcg != NULL,
3095 * mem_cgroup_get() was called in uncharge().
3097 if (do_swap_account && swapout && memcg)
3098 swap_cgroup_record(ent, css_id(&memcg->css));
3102 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3104 * called from swap_entry_free(). remove record in swap_cgroup and
3105 * uncharge "memsw" account.
3107 void mem_cgroup_uncharge_swap(swp_entry_t ent)
3109 struct mem_cgroup *memcg;
3112 if (!do_swap_account)
3115 id = swap_cgroup_record(ent, 0);
3117 memcg = mem_cgroup_lookup(id);
3120 * We uncharge this because swap is freed.
3121 * This memcg can be obsolete one. We avoid calling css_tryget
3123 if (!mem_cgroup_is_root(memcg))
3124 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
3125 mem_cgroup_swap_statistics(memcg, false);
3126 mem_cgroup_put(memcg);
3132 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3133 * @entry: swap entry to be moved
3134 * @from: mem_cgroup which the entry is moved from
3135 * @to: mem_cgroup which the entry is moved to
3136 * @need_fixup: whether we should fixup res_counters and refcounts.
3138 * It succeeds only when the swap_cgroup's record for this entry is the same
3139 * as the mem_cgroup's id of @from.
3141 * Returns 0 on success, -EINVAL on failure.
3143 * The caller must have charged to @to, IOW, called res_counter_charge() about
3144 * both res and memsw, and called css_get().
3146 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3147 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
3149 unsigned short old_id, new_id;
3151 old_id = css_id(&from->css);
3152 new_id = css_id(&to->css);
3154 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3155 mem_cgroup_swap_statistics(from, false);
3156 mem_cgroup_swap_statistics(to, true);
3158 * This function is only called from task migration context now.
3159 * It postpones res_counter and refcount handling till the end
3160 * of task migration(mem_cgroup_clear_mc()) for performance
3161 * improvement. But we cannot postpone mem_cgroup_get(to)
3162 * because if the process that has been moved to @to does
3163 * swap-in, the refcount of @to might be decreased to 0.
3167 if (!mem_cgroup_is_root(from))
3168 res_counter_uncharge(&from->memsw, PAGE_SIZE);
3169 mem_cgroup_put(from);
3171 * we charged both to->res and to->memsw, so we should
3174 if (!mem_cgroup_is_root(to))
3175 res_counter_uncharge(&to->res, PAGE_SIZE);
3182 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3183 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
3190 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
3193 int mem_cgroup_prepare_migration(struct page *page,
3194 struct page *newpage, struct mem_cgroup **memcgp, gfp_t gfp_mask)
3196 struct mem_cgroup *memcg = NULL;
3197 struct page_cgroup *pc;
3198 enum charge_type ctype;
3203 VM_BUG_ON(PageTransHuge(page));
3204 if (mem_cgroup_disabled())
3207 pc = lookup_page_cgroup(page);
3208 lock_page_cgroup(pc);
3209 if (PageCgroupUsed(pc)) {
3210 memcg = pc->mem_cgroup;
3211 css_get(&memcg->css);
3213 * At migrating an anonymous page, its mapcount goes down
3214 * to 0 and uncharge() will be called. But, even if it's fully
3215 * unmapped, migration may fail and this page has to be
3216 * charged again. We set MIGRATION flag here and delay uncharge
3217 * until end_migration() is called
3219 * Corner Case Thinking
3221 * When the old page was mapped as Anon and it's unmap-and-freed
3222 * while migration was ongoing.
3223 * If unmap finds the old page, uncharge() of it will be delayed
3224 * until end_migration(). If unmap finds a new page, it's
3225 * uncharged when it make mapcount to be 1->0. If unmap code
3226 * finds swap_migration_entry, the new page will not be mapped
3227 * and end_migration() will find it(mapcount==0).
3230 * When the old page was mapped but migraion fails, the kernel
3231 * remaps it. A charge for it is kept by MIGRATION flag even
3232 * if mapcount goes down to 0. We can do remap successfully
3233 * without charging it again.
3236 * The "old" page is under lock_page() until the end of
3237 * migration, so, the old page itself will not be swapped-out.
3238 * If the new page is swapped out before end_migraton, our
3239 * hook to usual swap-out path will catch the event.
3242 SetPageCgroupMigration(pc);
3244 unlock_page_cgroup(pc);
3246 * If the page is not charged at this point,
3253 ret = __mem_cgroup_try_charge(NULL, gfp_mask, 1, memcgp, false);
3254 css_put(&memcg->css);/* drop extra refcnt */
3255 if (ret || *memcgp == NULL) {
3256 if (PageAnon(page)) {
3257 lock_page_cgroup(pc);
3258 ClearPageCgroupMigration(pc);
3259 unlock_page_cgroup(pc);
3261 * The old page may be fully unmapped while we kept it.
3263 mem_cgroup_uncharge_page(page);
3268 * We charge new page before it's used/mapped. So, even if unlock_page()
3269 * is called before end_migration, we can catch all events on this new
3270 * page. In the case new page is migrated but not remapped, new page's
3271 * mapcount will be finally 0 and we call uncharge in end_migration().
3273 pc = lookup_page_cgroup(newpage);
3275 ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
3276 else if (page_is_file_cache(page))
3277 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
3279 ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
3280 __mem_cgroup_commit_charge(memcg, page, 1, pc, ctype);
3284 /* remove redundant charge if migration failed*/
3285 void mem_cgroup_end_migration(struct mem_cgroup *memcg,
3286 struct page *oldpage, struct page *newpage, bool migration_ok)
3288 struct page *used, *unused;
3289 struct page_cgroup *pc;
3293 /* blocks rmdir() */
3294 cgroup_exclude_rmdir(&memcg->css);
3295 if (!migration_ok) {
3303 * We disallowed uncharge of pages under migration because mapcount
3304 * of the page goes down to zero, temporarly.
3305 * Clear the flag and check the page should be charged.
3307 pc = lookup_page_cgroup(oldpage);
3308 lock_page_cgroup(pc);
3309 ClearPageCgroupMigration(pc);
3310 unlock_page_cgroup(pc);
3312 __mem_cgroup_uncharge_common(unused, MEM_CGROUP_CHARGE_TYPE_FORCE);
3315 * If a page is a file cache, radix-tree replacement is very atomic
3316 * and we can skip this check. When it was an Anon page, its mapcount
3317 * goes down to 0. But because we added MIGRATION flage, it's not
3318 * uncharged yet. There are several case but page->mapcount check
3319 * and USED bit check in mem_cgroup_uncharge_page() will do enough
3320 * check. (see prepare_charge() also)
3323 mem_cgroup_uncharge_page(used);
3325 * At migration, we may charge account against cgroup which has no
3327 * So, rmdir()->pre_destroy() can be called while we do this charge.
3328 * In that case, we need to call pre_destroy() again. check it here.
3330 cgroup_release_and_wakeup_rmdir(&memcg->css);
3333 #ifdef CONFIG_DEBUG_VM
3334 static struct page_cgroup *lookup_page_cgroup_used(struct page *page)
3336 struct page_cgroup *pc;
3338 pc = lookup_page_cgroup(page);
3339 if (likely(pc) && PageCgroupUsed(pc))
3344 bool mem_cgroup_bad_page_check(struct page *page)
3346 if (mem_cgroup_disabled())
3349 return lookup_page_cgroup_used(page) != NULL;
3352 void mem_cgroup_print_bad_page(struct page *page)
3354 struct page_cgroup *pc;
3356 pc = lookup_page_cgroup_used(page);
3361 printk(KERN_ALERT "pc:%p pc->flags:%lx pc->mem_cgroup:%p",
3362 pc, pc->flags, pc->mem_cgroup);
3364 path = kmalloc(PATH_MAX, GFP_KERNEL);
3367 ret = cgroup_path(pc->mem_cgroup->css.cgroup,
3372 printk(KERN_CONT "(%s)\n",
3373 (ret < 0) ? "cannot get the path" : path);
3379 static DEFINE_MUTEX(set_limit_mutex);
3381 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
3382 unsigned long long val)
3385 u64 memswlimit, memlimit;
3387 int children = mem_cgroup_count_children(memcg);
3388 u64 curusage, oldusage;
3392 * For keeping hierarchical_reclaim simple, how long we should retry
3393 * is depends on callers. We set our retry-count to be function
3394 * of # of children which we should visit in this loop.
3396 retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
3398 oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
3401 while (retry_count) {
3402 if (signal_pending(current)) {
3407 * Rather than hide all in some function, I do this in
3408 * open coded manner. You see what this really does.
3409 * We have to guarantee memcg->res.limit < memcg->memsw.limit.
3411 mutex_lock(&set_limit_mutex);
3412 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3413 if (memswlimit < val) {
3415 mutex_unlock(&set_limit_mutex);
3419 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3423 ret = res_counter_set_limit(&memcg->res, val);
3425 if (memswlimit == val)
3426 memcg->memsw_is_minimum = true;
3428 memcg->memsw_is_minimum = false;
3430 mutex_unlock(&set_limit_mutex);
3435 mem_cgroup_reclaim(memcg, GFP_KERNEL,
3436 MEM_CGROUP_RECLAIM_SHRINK);
3437 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
3438 /* Usage is reduced ? */
3439 if (curusage >= oldusage)
3442 oldusage = curusage;
3444 if (!ret && enlarge)
3445 memcg_oom_recover(memcg);
3450 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
3451 unsigned long long val)
3454 u64 memlimit, memswlimit, oldusage, curusage;
3455 int children = mem_cgroup_count_children(memcg);
3459 /* see mem_cgroup_resize_res_limit */
3460 retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
3461 oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
3462 while (retry_count) {
3463 if (signal_pending(current)) {
3468 * Rather than hide all in some function, I do this in
3469 * open coded manner. You see what this really does.
3470 * We have to guarantee memcg->res.limit < memcg->memsw.limit.
3472 mutex_lock(&set_limit_mutex);
3473 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3474 if (memlimit > val) {
3476 mutex_unlock(&set_limit_mutex);
3479 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3480 if (memswlimit < val)
3482 ret = res_counter_set_limit(&memcg->memsw, val);
3484 if (memlimit == val)
3485 memcg->memsw_is_minimum = true;
3487 memcg->memsw_is_minimum = false;
3489 mutex_unlock(&set_limit_mutex);
3494 mem_cgroup_reclaim(memcg, GFP_KERNEL,
3495 MEM_CGROUP_RECLAIM_NOSWAP |
3496 MEM_CGROUP_RECLAIM_SHRINK);
3497 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
3498 /* Usage is reduced ? */
3499 if (curusage >= oldusage)
3502 oldusage = curusage;
3504 if (!ret && enlarge)
3505 memcg_oom_recover(memcg);
3509 unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
3511 unsigned long *total_scanned)
3513 unsigned long nr_reclaimed = 0;
3514 struct mem_cgroup_per_zone *mz, *next_mz = NULL;
3515 unsigned long reclaimed;
3517 struct mem_cgroup_tree_per_zone *mctz;
3518 unsigned long long excess;
3519 unsigned long nr_scanned;
3524 mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
3526 * This loop can run a while, specially if mem_cgroup's continuously
3527 * keep exceeding their soft limit and putting the system under
3534 mz = mem_cgroup_largest_soft_limit_node(mctz);
3539 reclaimed = mem_cgroup_soft_reclaim(mz->mem, zone,
3540 gfp_mask, &nr_scanned);
3541 nr_reclaimed += reclaimed;
3542 *total_scanned += nr_scanned;
3543 spin_lock(&mctz->lock);
3546 * If we failed to reclaim anything from this memory cgroup
3547 * it is time to move on to the next cgroup
3553 * Loop until we find yet another one.
3555 * By the time we get the soft_limit lock
3556 * again, someone might have aded the
3557 * group back on the RB tree. Iterate to
3558 * make sure we get a different mem.
3559 * mem_cgroup_largest_soft_limit_node returns
3560 * NULL if no other cgroup is present on
3564 __mem_cgroup_largest_soft_limit_node(mctz);
3566 css_put(&next_mz->mem->css);
3567 else /* next_mz == NULL or other memcg */
3571 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
3572 excess = res_counter_soft_limit_excess(&mz->mem->res);
3574 * One school of thought says that we should not add
3575 * back the node to the tree if reclaim returns 0.
3576 * But our reclaim could return 0, simply because due
3577 * to priority we are exposing a smaller subset of
3578 * memory to reclaim from. Consider this as a longer
3581 /* If excess == 0, no tree ops */
3582 __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
3583 spin_unlock(&mctz->lock);
3584 css_put(&mz->mem->css);
3587 * Could not reclaim anything and there are no more
3588 * mem cgroups to try or we seem to be looping without
3589 * reclaiming anything.
3591 if (!nr_reclaimed &&
3593 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3595 } while (!nr_reclaimed);
3597 css_put(&next_mz->mem->css);
3598 return nr_reclaimed;
3602 * This routine traverse page_cgroup in given list and drop them all.
3603 * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
3605 static int mem_cgroup_force_empty_list(struct mem_cgroup *memcg,
3606 int node, int zid, enum lru_list lru)
3608 struct mem_cgroup_per_zone *mz;
3609 unsigned long flags, loop;
3610 struct list_head *list;
3615 zone = &NODE_DATA(node)->node_zones[zid];
3616 mz = mem_cgroup_zoneinfo(memcg, node, zid);
3617 list = &mz->lruvec.lists[lru];
3619 loop = MEM_CGROUP_ZSTAT(mz, lru);
3620 /* give some margin against EBUSY etc...*/
3624 struct page_cgroup *pc;
3628 spin_lock_irqsave(&zone->lru_lock, flags);
3629 if (list_empty(list)) {
3630 spin_unlock_irqrestore(&zone->lru_lock, flags);
3633 page = list_entry(list->prev, struct page, lru);
3635 list_move(&page->lru, list);
3637 spin_unlock_irqrestore(&zone->lru_lock, flags);
3640 spin_unlock_irqrestore(&zone->lru_lock, flags);
3642 pc = lookup_page_cgroup(page);
3644 ret = mem_cgroup_move_parent(page, pc, memcg, GFP_KERNEL);
3648 if (ret == -EBUSY || ret == -EINVAL) {
3649 /* found lock contention or "pc" is obsolete. */
3656 if (!ret && !list_empty(list))
3662 * make mem_cgroup's charge to be 0 if there is no task.
3663 * This enables deleting this mem_cgroup.
3665 static int mem_cgroup_force_empty(struct mem_cgroup *memcg, bool free_all)
3668 int node, zid, shrink;
3669 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
3670 struct cgroup *cgrp = memcg->css.cgroup;
3672 css_get(&memcg->css);
3675 /* should free all ? */
3681 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
3684 if (signal_pending(current))
3686 /* This is for making all *used* pages to be on LRU. */
3687 lru_add_drain_all();
3688 drain_all_stock_sync(memcg);
3690 mem_cgroup_start_move(memcg);
3691 for_each_node_state(node, N_HIGH_MEMORY) {
3692 for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
3695 ret = mem_cgroup_force_empty_list(memcg,
3704 mem_cgroup_end_move(memcg);
3705 memcg_oom_recover(memcg);
3706 /* it seems parent cgroup doesn't have enough mem */
3710 /* "ret" should also be checked to ensure all lists are empty. */
3711 } while (memcg->res.usage > 0 || ret);
3713 css_put(&memcg->css);
3717 /* returns EBUSY if there is a task or if we come here twice. */
3718 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
3722 /* we call try-to-free pages for make this cgroup empty */
3723 lru_add_drain_all();
3724 /* try to free all pages in this cgroup */
3726 while (nr_retries && memcg->res.usage > 0) {
3729 if (signal_pending(current)) {
3733 progress = try_to_free_mem_cgroup_pages(memcg, GFP_KERNEL,
3737 /* maybe some writeback is necessary */
3738 congestion_wait(BLK_RW_ASYNC, HZ/10);
3743 /* try move_account...there may be some *locked* pages. */
3747 int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
3749 return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
3753 static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
3755 return mem_cgroup_from_cont(cont)->use_hierarchy;
3758 static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
3762 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3763 struct cgroup *parent = cont->parent;
3764 struct mem_cgroup *parent_memcg = NULL;
3767 parent_memcg = mem_cgroup_from_cont(parent);
3771 * If parent's use_hierarchy is set, we can't make any modifications
3772 * in the child subtrees. If it is unset, then the change can
3773 * occur, provided the current cgroup has no children.
3775 * For the root cgroup, parent_mem is NULL, we allow value to be
3776 * set if there are no children.
3778 if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
3779 (val == 1 || val == 0)) {
3780 if (list_empty(&cont->children))
3781 memcg->use_hierarchy = val;
3792 static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup *memcg,
3793 enum mem_cgroup_stat_index idx)
3795 struct mem_cgroup *iter;
3798 /* Per-cpu values can be negative, use a signed accumulator */
3799 for_each_mem_cgroup_tree(iter, memcg)
3800 val += mem_cgroup_read_stat(iter, idx);
3802 if (val < 0) /* race ? */
3807 static inline u64 mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3811 if (!mem_cgroup_is_root(memcg)) {
3813 return res_counter_read_u64(&memcg->res, RES_USAGE);
3815 return res_counter_read_u64(&memcg->memsw, RES_USAGE);
3818 val = mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_CACHE);
3819 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_RSS);
3822 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_SWAPOUT);
3824 return val << PAGE_SHIFT;
3827 static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
3829 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3833 type = MEMFILE_TYPE(cft->private);
3834 name = MEMFILE_ATTR(cft->private);
3837 if (name == RES_USAGE)
3838 val = mem_cgroup_usage(memcg, false);
3840 val = res_counter_read_u64(&memcg->res, name);
3843 if (name == RES_USAGE)
3844 val = mem_cgroup_usage(memcg, true);
3846 val = res_counter_read_u64(&memcg->memsw, name);
3855 * The user of this function is...
3858 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
3861 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3863 unsigned long long val;
3866 type = MEMFILE_TYPE(cft->private);
3867 name = MEMFILE_ATTR(cft->private);
3870 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3874 /* This function does all necessary parse...reuse it */
3875 ret = res_counter_memparse_write_strategy(buffer, &val);
3879 ret = mem_cgroup_resize_limit(memcg, val);
3881 ret = mem_cgroup_resize_memsw_limit(memcg, val);
3883 case RES_SOFT_LIMIT:
3884 ret = res_counter_memparse_write_strategy(buffer, &val);
3888 * For memsw, soft limits are hard to implement in terms
3889 * of semantics, for now, we support soft limits for
3890 * control without swap
3893 ret = res_counter_set_soft_limit(&memcg->res, val);
3898 ret = -EINVAL; /* should be BUG() ? */
3904 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
3905 unsigned long long *mem_limit, unsigned long long *memsw_limit)
3907 struct cgroup *cgroup;
3908 unsigned long long min_limit, min_memsw_limit, tmp;
3910 min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3911 min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3912 cgroup = memcg->css.cgroup;
3913 if (!memcg->use_hierarchy)
3916 while (cgroup->parent) {
3917 cgroup = cgroup->parent;
3918 memcg = mem_cgroup_from_cont(cgroup);
3919 if (!memcg->use_hierarchy)
3921 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
3922 min_limit = min(min_limit, tmp);
3923 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3924 min_memsw_limit = min(min_memsw_limit, tmp);
3927 *mem_limit = min_limit;
3928 *memsw_limit = min_memsw_limit;
3932 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
3934 struct mem_cgroup *memcg;
3937 memcg = mem_cgroup_from_cont(cont);
3938 type = MEMFILE_TYPE(event);
3939 name = MEMFILE_ATTR(event);
3943 res_counter_reset_max(&memcg->res);
3945 res_counter_reset_max(&memcg->memsw);
3949 res_counter_reset_failcnt(&memcg->res);
3951 res_counter_reset_failcnt(&memcg->memsw);
3958 static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
3961 return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
3965 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
3966 struct cftype *cft, u64 val)
3968 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3970 if (val >= (1 << NR_MOVE_TYPE))
3973 * We check this value several times in both in can_attach() and
3974 * attach(), so we need cgroup lock to prevent this value from being
3978 memcg->move_charge_at_immigrate = val;
3984 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
3985 struct cftype *cft, u64 val)
3992 /* For read statistics */
4010 struct mcs_total_stat {
4011 s64 stat[NR_MCS_STAT];
4017 } memcg_stat_strings[NR_MCS_STAT] = {
4018 {"cache", "total_cache"},
4019 {"rss", "total_rss"},
4020 {"mapped_file", "total_mapped_file"},
4021 {"pgpgin", "total_pgpgin"},
4022 {"pgpgout", "total_pgpgout"},
4023 {"swap", "total_swap"},
4024 {"pgfault", "total_pgfault"},
4025 {"pgmajfault", "total_pgmajfault"},
4026 {"inactive_anon", "total_inactive_anon"},
4027 {"active_anon", "total_active_anon"},
4028 {"inactive_file", "total_inactive_file"},
4029 {"active_file", "total_active_file"},
4030 {"unevictable", "total_unevictable"}
4035 mem_cgroup_get_local_stat(struct mem_cgroup *memcg, struct mcs_total_stat *s)
4040 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_CACHE);
4041 s->stat[MCS_CACHE] += val * PAGE_SIZE;
4042 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_RSS);
4043 s->stat[MCS_RSS] += val * PAGE_SIZE;
4044 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_FILE_MAPPED);
4045 s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE;
4046 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGPGIN);
4047 s->stat[MCS_PGPGIN] += val;
4048 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGPGOUT);
4049 s->stat[MCS_PGPGOUT] += val;
4050 if (do_swap_account) {
4051 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_SWAPOUT);
4052 s->stat[MCS_SWAP] += val * PAGE_SIZE;
4054 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGFAULT);
4055 s->stat[MCS_PGFAULT] += val;
4056 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGMAJFAULT);
4057 s->stat[MCS_PGMAJFAULT] += val;
4060 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_INACTIVE_ANON));
4061 s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
4062 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_ACTIVE_ANON));
4063 s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
4064 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_INACTIVE_FILE));
4065 s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
4066 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_ACTIVE_FILE));
4067 s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
4068 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_UNEVICTABLE));
4069 s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
4073 mem_cgroup_get_total_stat(struct mem_cgroup *memcg, struct mcs_total_stat *s)
4075 struct mem_cgroup *iter;
4077 for_each_mem_cgroup_tree(iter, memcg)
4078 mem_cgroup_get_local_stat(iter, s);
4082 static int mem_control_numa_stat_show(struct seq_file *m, void *arg)
4085 unsigned long total_nr, file_nr, anon_nr, unevictable_nr;
4086 unsigned long node_nr;
4087 struct cgroup *cont = m->private;
4088 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
4090 total_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL);
4091 seq_printf(m, "total=%lu", total_nr);
4092 for_each_node_state(nid, N_HIGH_MEMORY) {
4093 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid, LRU_ALL);
4094 seq_printf(m, " N%d=%lu", nid, node_nr);
4098 file_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_FILE);
4099 seq_printf(m, "file=%lu", file_nr);
4100 for_each_node_state(nid, N_HIGH_MEMORY) {
4101 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4103 seq_printf(m, " N%d=%lu", nid, node_nr);
4107 anon_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_ANON);
4108 seq_printf(m, "anon=%lu", anon_nr);
4109 for_each_node_state(nid, N_HIGH_MEMORY) {
4110 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4112 seq_printf(m, " N%d=%lu", nid, node_nr);
4116 unevictable_nr = mem_cgroup_nr_lru_pages(mem_cont, BIT(LRU_UNEVICTABLE));
4117 seq_printf(m, "unevictable=%lu", unevictable_nr);
4118 for_each_node_state(nid, N_HIGH_MEMORY) {
4119 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4120 BIT(LRU_UNEVICTABLE));
4121 seq_printf(m, " N%d=%lu", nid, node_nr);
4126 #endif /* CONFIG_NUMA */
4128 static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
4129 struct cgroup_map_cb *cb)
4131 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
4132 struct mcs_total_stat mystat;
4135 memset(&mystat, 0, sizeof(mystat));
4136 mem_cgroup_get_local_stat(mem_cont, &mystat);
4139 for (i = 0; i < NR_MCS_STAT; i++) {
4140 if (i == MCS_SWAP && !do_swap_account)
4142 cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
4145 /* Hierarchical information */
4147 unsigned long long limit, memsw_limit;
4148 memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
4149 cb->fill(cb, "hierarchical_memory_limit", limit);
4150 if (do_swap_account)
4151 cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
4154 memset(&mystat, 0, sizeof(mystat));
4155 mem_cgroup_get_total_stat(mem_cont, &mystat);
4156 for (i = 0; i < NR_MCS_STAT; i++) {
4157 if (i == MCS_SWAP && !do_swap_account)
4159 cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
4162 #ifdef CONFIG_DEBUG_VM
4165 struct mem_cgroup_per_zone *mz;
4166 unsigned long recent_rotated[2] = {0, 0};
4167 unsigned long recent_scanned[2] = {0, 0};
4169 for_each_online_node(nid)
4170 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
4171 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
4173 recent_rotated[0] +=
4174 mz->reclaim_stat.recent_rotated[0];
4175 recent_rotated[1] +=
4176 mz->reclaim_stat.recent_rotated[1];
4177 recent_scanned[0] +=
4178 mz->reclaim_stat.recent_scanned[0];
4179 recent_scanned[1] +=
4180 mz->reclaim_stat.recent_scanned[1];
4182 cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
4183 cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
4184 cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
4185 cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
4192 static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
4194 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4196 return mem_cgroup_swappiness(memcg);
4199 static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
4202 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4203 struct mem_cgroup *parent;
4208 if (cgrp->parent == NULL)
4211 parent = mem_cgroup_from_cont(cgrp->parent);
4215 /* If under hierarchy, only empty-root can set this value */
4216 if ((parent->use_hierarchy) ||
4217 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
4222 memcg->swappiness = val;
4229 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4231 struct mem_cgroup_threshold_ary *t;
4237 t = rcu_dereference(memcg->thresholds.primary);
4239 t = rcu_dereference(memcg->memsw_thresholds.primary);
4244 usage = mem_cgroup_usage(memcg, swap);
4247 * current_threshold points to threshold just below usage.
4248 * If it's not true, a threshold was crossed after last
4249 * call of __mem_cgroup_threshold().
4251 i = t->current_threshold;
4254 * Iterate backward over array of thresholds starting from
4255 * current_threshold and check if a threshold is crossed.
4256 * If none of thresholds below usage is crossed, we read
4257 * only one element of the array here.
4259 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4260 eventfd_signal(t->entries[i].eventfd, 1);
4262 /* i = current_threshold + 1 */
4266 * Iterate forward over array of thresholds starting from
4267 * current_threshold+1 and check if a threshold is crossed.
4268 * If none of thresholds above usage is crossed, we read
4269 * only one element of the array here.
4271 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4272 eventfd_signal(t->entries[i].eventfd, 1);
4274 /* Update current_threshold */
4275 t->current_threshold = i - 1;
4280 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4283 __mem_cgroup_threshold(memcg, false);
4284 if (do_swap_account)
4285 __mem_cgroup_threshold(memcg, true);
4287 memcg = parent_mem_cgroup(memcg);
4291 static int compare_thresholds(const void *a, const void *b)
4293 const struct mem_cgroup_threshold *_a = a;
4294 const struct mem_cgroup_threshold *_b = b;
4296 return _a->threshold - _b->threshold;
4299 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
4301 struct mem_cgroup_eventfd_list *ev;
4303 list_for_each_entry(ev, &memcg->oom_notify, list)
4304 eventfd_signal(ev->eventfd, 1);
4308 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
4310 struct mem_cgroup *iter;
4312 for_each_mem_cgroup_tree(iter, memcg)
4313 mem_cgroup_oom_notify_cb(iter);
4316 static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
4317 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4319 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4320 struct mem_cgroup_thresholds *thresholds;
4321 struct mem_cgroup_threshold_ary *new;
4322 int type = MEMFILE_TYPE(cft->private);
4323 u64 threshold, usage;
4326 ret = res_counter_memparse_write_strategy(args, &threshold);
4330 mutex_lock(&memcg->thresholds_lock);
4333 thresholds = &memcg->thresholds;
4334 else if (type == _MEMSWAP)
4335 thresholds = &memcg->memsw_thresholds;
4339 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4341 /* Check if a threshold crossed before adding a new one */
4342 if (thresholds->primary)
4343 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4345 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4347 /* Allocate memory for new array of thresholds */
4348 new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
4356 /* Copy thresholds (if any) to new array */
4357 if (thresholds->primary) {
4358 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
4359 sizeof(struct mem_cgroup_threshold));
4362 /* Add new threshold */
4363 new->entries[size - 1].eventfd = eventfd;
4364 new->entries[size - 1].threshold = threshold;
4366 /* Sort thresholds. Registering of new threshold isn't time-critical */
4367 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
4368 compare_thresholds, NULL);
4370 /* Find current threshold */
4371 new->current_threshold = -1;
4372 for (i = 0; i < size; i++) {
4373 if (new->entries[i].threshold < usage) {
4375 * new->current_threshold will not be used until
4376 * rcu_assign_pointer(), so it's safe to increment
4379 ++new->current_threshold;
4383 /* Free old spare buffer and save old primary buffer as spare */
4384 kfree(thresholds->spare);
4385 thresholds->spare = thresholds->primary;
4387 rcu_assign_pointer(thresholds->primary, new);
4389 /* To be sure that nobody uses thresholds */
4393 mutex_unlock(&memcg->thresholds_lock);
4398 static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
4399 struct cftype *cft, struct eventfd_ctx *eventfd)
4401 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4402 struct mem_cgroup_thresholds *thresholds;
4403 struct mem_cgroup_threshold_ary *new;
4404 int type = MEMFILE_TYPE(cft->private);
4408 mutex_lock(&memcg->thresholds_lock);
4410 thresholds = &memcg->thresholds;
4411 else if (type == _MEMSWAP)
4412 thresholds = &memcg->memsw_thresholds;
4417 * Something went wrong if we trying to unregister a threshold
4418 * if we don't have thresholds
4420 BUG_ON(!thresholds);
4422 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4424 /* Check if a threshold crossed before removing */
4425 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4427 /* Calculate new number of threshold */
4429 for (i = 0; i < thresholds->primary->size; i++) {
4430 if (thresholds->primary->entries[i].eventfd != eventfd)
4434 new = thresholds->spare;
4436 /* Set thresholds array to NULL if we don't have thresholds */
4445 /* Copy thresholds and find current threshold */
4446 new->current_threshold = -1;
4447 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4448 if (thresholds->primary->entries[i].eventfd == eventfd)
4451 new->entries[j] = thresholds->primary->entries[i];
4452 if (new->entries[j].threshold < usage) {
4454 * new->current_threshold will not be used
4455 * until rcu_assign_pointer(), so it's safe to increment
4458 ++new->current_threshold;
4464 /* Swap primary and spare array */
4465 thresholds->spare = thresholds->primary;
4466 rcu_assign_pointer(thresholds->primary, new);
4468 /* To be sure that nobody uses thresholds */
4471 mutex_unlock(&memcg->thresholds_lock);
4474 static int mem_cgroup_oom_register_event(struct cgroup *cgrp,
4475 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4477 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4478 struct mem_cgroup_eventfd_list *event;
4479 int type = MEMFILE_TYPE(cft->private);
4481 BUG_ON(type != _OOM_TYPE);
4482 event = kmalloc(sizeof(*event), GFP_KERNEL);
4486 spin_lock(&memcg_oom_lock);
4488 event->eventfd = eventfd;
4489 list_add(&event->list, &memcg->oom_notify);
4491 /* already in OOM ? */
4492 if (atomic_read(&memcg->under_oom))
4493 eventfd_signal(eventfd, 1);
4494 spin_unlock(&memcg_oom_lock);
4499 static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
4500 struct cftype *cft, struct eventfd_ctx *eventfd)
4502 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4503 struct mem_cgroup_eventfd_list *ev, *tmp;
4504 int type = MEMFILE_TYPE(cft->private);
4506 BUG_ON(type != _OOM_TYPE);
4508 spin_lock(&memcg_oom_lock);
4510 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
4511 if (ev->eventfd == eventfd) {
4512 list_del(&ev->list);
4517 spin_unlock(&memcg_oom_lock);
4520 static int mem_cgroup_oom_control_read(struct cgroup *cgrp,
4521 struct cftype *cft, struct cgroup_map_cb *cb)
4523 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4525 cb->fill(cb, "oom_kill_disable", memcg->oom_kill_disable);
4527 if (atomic_read(&memcg->under_oom))
4528 cb->fill(cb, "under_oom", 1);
4530 cb->fill(cb, "under_oom", 0);
4534 static int mem_cgroup_oom_control_write(struct cgroup *cgrp,
4535 struct cftype *cft, u64 val)
4537 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4538 struct mem_cgroup *parent;
4540 /* cannot set to root cgroup and only 0 and 1 are allowed */
4541 if (!cgrp->parent || !((val == 0) || (val == 1)))
4544 parent = mem_cgroup_from_cont(cgrp->parent);
4547 /* oom-kill-disable is a flag for subhierarchy. */
4548 if ((parent->use_hierarchy) ||
4549 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
4553 memcg->oom_kill_disable = val;
4555 memcg_oom_recover(memcg);
4561 static const struct file_operations mem_control_numa_stat_file_operations = {
4563 .llseek = seq_lseek,
4564 .release = single_release,
4567 static int mem_control_numa_stat_open(struct inode *unused, struct file *file)
4569 struct cgroup *cont = file->f_dentry->d_parent->d_fsdata;
4571 file->f_op = &mem_control_numa_stat_file_operations;
4572 return single_open(file, mem_control_numa_stat_show, cont);
4574 #endif /* CONFIG_NUMA */
4576 static struct cftype mem_cgroup_files[] = {
4578 .name = "usage_in_bytes",
4579 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
4580 .read_u64 = mem_cgroup_read,
4581 .register_event = mem_cgroup_usage_register_event,
4582 .unregister_event = mem_cgroup_usage_unregister_event,
4585 .name = "max_usage_in_bytes",
4586 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
4587 .trigger = mem_cgroup_reset,
4588 .read_u64 = mem_cgroup_read,
4591 .name = "limit_in_bytes",
4592 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
4593 .write_string = mem_cgroup_write,
4594 .read_u64 = mem_cgroup_read,
4597 .name = "soft_limit_in_bytes",
4598 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
4599 .write_string = mem_cgroup_write,
4600 .read_u64 = mem_cgroup_read,
4604 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
4605 .trigger = mem_cgroup_reset,
4606 .read_u64 = mem_cgroup_read,
4610 .read_map = mem_control_stat_show,
4613 .name = "force_empty",
4614 .trigger = mem_cgroup_force_empty_write,
4617 .name = "use_hierarchy",
4618 .write_u64 = mem_cgroup_hierarchy_write,
4619 .read_u64 = mem_cgroup_hierarchy_read,
4622 .name = "swappiness",
4623 .read_u64 = mem_cgroup_swappiness_read,
4624 .write_u64 = mem_cgroup_swappiness_write,
4627 .name = "move_charge_at_immigrate",
4628 .read_u64 = mem_cgroup_move_charge_read,
4629 .write_u64 = mem_cgroup_move_charge_write,
4632 .name = "oom_control",
4633 .read_map = mem_cgroup_oom_control_read,
4634 .write_u64 = mem_cgroup_oom_control_write,
4635 .register_event = mem_cgroup_oom_register_event,
4636 .unregister_event = mem_cgroup_oom_unregister_event,
4637 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
4641 .name = "numa_stat",
4642 .open = mem_control_numa_stat_open,
4648 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4649 static struct cftype memsw_cgroup_files[] = {
4651 .name = "memsw.usage_in_bytes",
4652 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
4653 .read_u64 = mem_cgroup_read,
4654 .register_event = mem_cgroup_usage_register_event,
4655 .unregister_event = mem_cgroup_usage_unregister_event,
4658 .name = "memsw.max_usage_in_bytes",
4659 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
4660 .trigger = mem_cgroup_reset,
4661 .read_u64 = mem_cgroup_read,
4664 .name = "memsw.limit_in_bytes",
4665 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
4666 .write_string = mem_cgroup_write,
4667 .read_u64 = mem_cgroup_read,
4670 .name = "memsw.failcnt",
4671 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
4672 .trigger = mem_cgroup_reset,
4673 .read_u64 = mem_cgroup_read,
4677 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
4679 if (!do_swap_account)
4681 return cgroup_add_files(cont, ss, memsw_cgroup_files,
4682 ARRAY_SIZE(memsw_cgroup_files));
4685 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
4691 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
4693 struct mem_cgroup_per_node *pn;
4694 struct mem_cgroup_per_zone *mz;
4696 int zone, tmp = node;
4698 * This routine is called against possible nodes.
4699 * But it's BUG to call kmalloc() against offline node.
4701 * TODO: this routine can waste much memory for nodes which will
4702 * never be onlined. It's better to use memory hotplug callback
4705 if (!node_state(node, N_NORMAL_MEMORY))
4707 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
4711 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4712 mz = &pn->zoneinfo[zone];
4714 INIT_LIST_HEAD(&mz->lruvec.lists[l]);
4715 mz->usage_in_excess = 0;
4716 mz->on_tree = false;
4719 memcg->info.nodeinfo[node] = pn;
4723 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
4725 kfree(memcg->info.nodeinfo[node]);
4728 static struct mem_cgroup *mem_cgroup_alloc(void)
4730 struct mem_cgroup *mem;
4731 int size = sizeof(struct mem_cgroup);
4733 /* Can be very big if MAX_NUMNODES is very big */
4734 if (size < PAGE_SIZE)
4735 mem = kzalloc(size, GFP_KERNEL);
4737 mem = vzalloc(size);
4742 mem->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
4745 spin_lock_init(&mem->pcp_counter_lock);
4749 if (size < PAGE_SIZE)
4757 * At destroying mem_cgroup, references from swap_cgroup can remain.
4758 * (scanning all at force_empty is too costly...)
4760 * Instead of clearing all references at force_empty, we remember
4761 * the number of reference from swap_cgroup and free mem_cgroup when
4762 * it goes down to 0.
4764 * Removal of cgroup itself succeeds regardless of refs from swap.
4767 static void __mem_cgroup_free(struct mem_cgroup *memcg)
4771 mem_cgroup_remove_from_trees(memcg);
4772 free_css_id(&mem_cgroup_subsys, &memcg->css);
4774 for_each_node_state(node, N_POSSIBLE)
4775 free_mem_cgroup_per_zone_info(memcg, node);
4777 free_percpu(memcg->stat);
4778 if (sizeof(struct mem_cgroup) < PAGE_SIZE)
4784 static void mem_cgroup_get(struct mem_cgroup *memcg)
4786 atomic_inc(&memcg->refcnt);
4789 static void __mem_cgroup_put(struct mem_cgroup *memcg, int count)
4791 if (atomic_sub_and_test(count, &memcg->refcnt)) {
4792 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
4793 __mem_cgroup_free(memcg);
4795 mem_cgroup_put(parent);
4799 static void mem_cgroup_put(struct mem_cgroup *memcg)
4801 __mem_cgroup_put(memcg, 1);
4805 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
4807 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg)
4809 if (!memcg->res.parent)
4811 return mem_cgroup_from_res_counter(memcg->res.parent, res);
4814 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4815 static void __init enable_swap_cgroup(void)
4817 if (!mem_cgroup_disabled() && really_do_swap_account)
4818 do_swap_account = 1;
4821 static void __init enable_swap_cgroup(void)
4826 static int mem_cgroup_soft_limit_tree_init(void)
4828 struct mem_cgroup_tree_per_node *rtpn;
4829 struct mem_cgroup_tree_per_zone *rtpz;
4830 int tmp, node, zone;
4832 for_each_node_state(node, N_POSSIBLE) {
4834 if (!node_state(node, N_NORMAL_MEMORY))
4836 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
4840 soft_limit_tree.rb_tree_per_node[node] = rtpn;
4842 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4843 rtpz = &rtpn->rb_tree_per_zone[zone];
4844 rtpz->rb_root = RB_ROOT;
4845 spin_lock_init(&rtpz->lock);
4851 static struct cgroup_subsys_state * __ref
4852 mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
4854 struct mem_cgroup *memcg, *parent;
4855 long error = -ENOMEM;
4858 memcg = mem_cgroup_alloc();
4860 return ERR_PTR(error);
4862 for_each_node_state(node, N_POSSIBLE)
4863 if (alloc_mem_cgroup_per_zone_info(memcg, node))
4867 if (cont->parent == NULL) {
4869 enable_swap_cgroup();
4871 root_mem_cgroup = memcg;
4872 if (mem_cgroup_soft_limit_tree_init())
4874 for_each_possible_cpu(cpu) {
4875 struct memcg_stock_pcp *stock =
4876 &per_cpu(memcg_stock, cpu);
4877 INIT_WORK(&stock->work, drain_local_stock);
4879 hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
4881 parent = mem_cgroup_from_cont(cont->parent);
4882 memcg->use_hierarchy = parent->use_hierarchy;
4883 memcg->oom_kill_disable = parent->oom_kill_disable;
4886 if (parent && parent->use_hierarchy) {
4887 res_counter_init(&memcg->res, &parent->res);
4888 res_counter_init(&memcg->memsw, &parent->memsw);
4890 * We increment refcnt of the parent to ensure that we can
4891 * safely access it on res_counter_charge/uncharge.
4892 * This refcnt will be decremented when freeing this
4893 * mem_cgroup(see mem_cgroup_put).
4895 mem_cgroup_get(parent);
4897 res_counter_init(&memcg->res, NULL);
4898 res_counter_init(&memcg->memsw, NULL);
4900 memcg->last_scanned_node = MAX_NUMNODES;
4901 INIT_LIST_HEAD(&memcg->oom_notify);
4904 memcg->swappiness = mem_cgroup_swappiness(parent);
4905 atomic_set(&memcg->refcnt, 1);
4906 memcg->move_charge_at_immigrate = 0;
4907 mutex_init(&memcg->thresholds_lock);
4910 __mem_cgroup_free(memcg);
4911 root_mem_cgroup = NULL;
4912 return ERR_PTR(error);
4915 static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
4916 struct cgroup *cont)
4918 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4920 return mem_cgroup_force_empty(memcg, false);
4923 static void mem_cgroup_destroy(struct cgroup_subsys *ss,
4924 struct cgroup *cont)
4926 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4928 mem_cgroup_put(memcg);
4931 static int mem_cgroup_populate(struct cgroup_subsys *ss,
4932 struct cgroup *cont)
4936 ret = cgroup_add_files(cont, ss, mem_cgroup_files,
4937 ARRAY_SIZE(mem_cgroup_files));
4940 ret = register_memsw_files(cont, ss);
4945 /* Handlers for move charge at task migration. */
4946 #define PRECHARGE_COUNT_AT_ONCE 256
4947 static int mem_cgroup_do_precharge(unsigned long count)
4950 int batch_count = PRECHARGE_COUNT_AT_ONCE;
4951 struct mem_cgroup *memcg = mc.to;
4953 if (mem_cgroup_is_root(memcg)) {
4954 mc.precharge += count;
4955 /* we don't need css_get for root */
4958 /* try to charge at once */
4960 struct res_counter *dummy;
4962 * "memcg" cannot be under rmdir() because we've already checked
4963 * by cgroup_lock_live_cgroup() that it is not removed and we
4964 * are still under the same cgroup_mutex. So we can postpone
4967 if (res_counter_charge(&memcg->res, PAGE_SIZE * count, &dummy))
4969 if (do_swap_account && res_counter_charge(&memcg->memsw,
4970 PAGE_SIZE * count, &dummy)) {
4971 res_counter_uncharge(&memcg->res, PAGE_SIZE * count);
4974 mc.precharge += count;
4978 /* fall back to one by one charge */
4980 if (signal_pending(current)) {
4984 if (!batch_count--) {
4985 batch_count = PRECHARGE_COUNT_AT_ONCE;
4988 ret = __mem_cgroup_try_charge(NULL,
4989 GFP_KERNEL, 1, &memcg, false);
4991 /* mem_cgroup_clear_mc() will do uncharge later */
4999 * is_target_pte_for_mc - check a pte whether it is valid for move charge
5000 * @vma: the vma the pte to be checked belongs
5001 * @addr: the address corresponding to the pte to be checked
5002 * @ptent: the pte to be checked
5003 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5006 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5007 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5008 * move charge. if @target is not NULL, the page is stored in target->page
5009 * with extra refcnt got(Callers should handle it).
5010 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5011 * target for charge migration. if @target is not NULL, the entry is stored
5014 * Called with pte lock held.
5021 enum mc_target_type {
5022 MC_TARGET_NONE, /* not used */
5027 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5028 unsigned long addr, pte_t ptent)
5030 struct page *page = vm_normal_page(vma, addr, ptent);
5032 if (!page || !page_mapped(page))
5034 if (PageAnon(page)) {
5035 /* we don't move shared anon */
5036 if (!move_anon() || page_mapcount(page) > 2)
5038 } else if (!move_file())
5039 /* we ignore mapcount for file pages */
5041 if (!get_page_unless_zero(page))
5047 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5048 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5051 struct page *page = NULL;
5052 swp_entry_t ent = pte_to_swp_entry(ptent);
5054 if (!move_anon() || non_swap_entry(ent))
5056 usage_count = mem_cgroup_count_swap_user(ent, &page);
5057 if (usage_count > 1) { /* we don't move shared anon */
5062 if (do_swap_account)
5063 entry->val = ent.val;
5068 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5069 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5071 struct page *page = NULL;
5072 struct inode *inode;
5073 struct address_space *mapping;
5076 if (!vma->vm_file) /* anonymous vma */
5081 inode = vma->vm_file->f_path.dentry->d_inode;
5082 mapping = vma->vm_file->f_mapping;
5083 if (pte_none(ptent))
5084 pgoff = linear_page_index(vma, addr);
5085 else /* pte_file(ptent) is true */
5086 pgoff = pte_to_pgoff(ptent);
5088 /* page is moved even if it's not RSS of this task(page-faulted). */
5089 page = find_get_page(mapping, pgoff);
5092 /* shmem/tmpfs may report page out on swap: account for that too. */
5093 if (radix_tree_exceptional_entry(page)) {
5094 swp_entry_t swap = radix_to_swp_entry(page);
5095 if (do_swap_account)
5097 page = find_get_page(&swapper_space, swap.val);
5103 static int is_target_pte_for_mc(struct vm_area_struct *vma,
5104 unsigned long addr, pte_t ptent, union mc_target *target)
5106 struct page *page = NULL;
5107 struct page_cgroup *pc;
5109 swp_entry_t ent = { .val = 0 };
5111 if (pte_present(ptent))
5112 page = mc_handle_present_pte(vma, addr, ptent);
5113 else if (is_swap_pte(ptent))
5114 page = mc_handle_swap_pte(vma, addr, ptent, &ent);
5115 else if (pte_none(ptent) || pte_file(ptent))
5116 page = mc_handle_file_pte(vma, addr, ptent, &ent);
5118 if (!page && !ent.val)
5121 pc = lookup_page_cgroup(page);
5123 * Do only loose check w/o page_cgroup lock.
5124 * mem_cgroup_move_account() checks the pc is valid or not under
5127 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
5128 ret = MC_TARGET_PAGE;
5130 target->page = page;
5132 if (!ret || !target)
5135 /* There is a swap entry and a page doesn't exist or isn't charged */
5136 if (ent.val && !ret &&
5137 css_id(&mc.from->css) == lookup_swap_cgroup(ent)) {
5138 ret = MC_TARGET_SWAP;
5145 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5146 unsigned long addr, unsigned long end,
5147 struct mm_walk *walk)
5149 struct vm_area_struct *vma = walk->private;
5153 split_huge_page_pmd(walk->mm, pmd);
5155 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5156 for (; addr != end; pte++, addr += PAGE_SIZE)
5157 if (is_target_pte_for_mc(vma, addr, *pte, NULL))
5158 mc.precharge++; /* increment precharge temporarily */
5159 pte_unmap_unlock(pte - 1, ptl);
5165 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5167 unsigned long precharge;
5168 struct vm_area_struct *vma;
5170 down_read(&mm->mmap_sem);
5171 for (vma = mm->mmap; vma; vma = vma->vm_next) {
5172 struct mm_walk mem_cgroup_count_precharge_walk = {
5173 .pmd_entry = mem_cgroup_count_precharge_pte_range,
5177 if (is_vm_hugetlb_page(vma))
5179 walk_page_range(vma->vm_start, vma->vm_end,
5180 &mem_cgroup_count_precharge_walk);
5182 up_read(&mm->mmap_sem);
5184 precharge = mc.precharge;
5190 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5192 unsigned long precharge = mem_cgroup_count_precharge(mm);
5194 VM_BUG_ON(mc.moving_task);
5195 mc.moving_task = current;
5196 return mem_cgroup_do_precharge(precharge);
5199 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5200 static void __mem_cgroup_clear_mc(void)
5202 struct mem_cgroup *from = mc.from;
5203 struct mem_cgroup *to = mc.to;
5205 /* we must uncharge all the leftover precharges from mc.to */
5207 __mem_cgroup_cancel_charge(mc.to, mc.precharge);
5211 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5212 * we must uncharge here.
5214 if (mc.moved_charge) {
5215 __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
5216 mc.moved_charge = 0;
5218 /* we must fixup refcnts and charges */
5219 if (mc.moved_swap) {
5220 /* uncharge swap account from the old cgroup */
5221 if (!mem_cgroup_is_root(mc.from))
5222 res_counter_uncharge(&mc.from->memsw,
5223 PAGE_SIZE * mc.moved_swap);
5224 __mem_cgroup_put(mc.from, mc.moved_swap);
5226 if (!mem_cgroup_is_root(mc.to)) {
5228 * we charged both to->res and to->memsw, so we should
5231 res_counter_uncharge(&mc.to->res,
5232 PAGE_SIZE * mc.moved_swap);
5234 /* we've already done mem_cgroup_get(mc.to) */
5237 memcg_oom_recover(from);
5238 memcg_oom_recover(to);
5239 wake_up_all(&mc.waitq);
5242 static void mem_cgroup_clear_mc(void)
5244 struct mem_cgroup *from = mc.from;
5247 * we must clear moving_task before waking up waiters at the end of
5250 mc.moving_task = NULL;
5251 __mem_cgroup_clear_mc();
5252 spin_lock(&mc.lock);
5255 spin_unlock(&mc.lock);
5256 mem_cgroup_end_move(from);
5259 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
5260 struct cgroup *cgroup,
5261 struct task_struct *p)
5264 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgroup);
5266 if (memcg->move_charge_at_immigrate) {
5267 struct mm_struct *mm;
5268 struct mem_cgroup *from = mem_cgroup_from_task(p);
5270 VM_BUG_ON(from == memcg);
5272 mm = get_task_mm(p);
5275 /* We move charges only when we move a owner of the mm */
5276 if (mm->owner == p) {
5279 VM_BUG_ON(mc.precharge);
5280 VM_BUG_ON(mc.moved_charge);
5281 VM_BUG_ON(mc.moved_swap);
5282 mem_cgroup_start_move(from);
5283 spin_lock(&mc.lock);
5286 spin_unlock(&mc.lock);
5287 /* We set mc.moving_task later */
5289 ret = mem_cgroup_precharge_mc(mm);
5291 mem_cgroup_clear_mc();
5298 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
5299 struct cgroup *cgroup,
5300 struct task_struct *p)
5302 mem_cgroup_clear_mc();
5305 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
5306 unsigned long addr, unsigned long end,
5307 struct mm_walk *walk)
5310 struct vm_area_struct *vma = walk->private;
5314 split_huge_page_pmd(walk->mm, pmd);
5316 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5317 for (; addr != end; addr += PAGE_SIZE) {
5318 pte_t ptent = *(pte++);
5319 union mc_target target;
5322 struct page_cgroup *pc;
5328 type = is_target_pte_for_mc(vma, addr, ptent, &target);
5330 case MC_TARGET_PAGE:
5332 if (isolate_lru_page(page))
5334 pc = lookup_page_cgroup(page);
5335 if (!mem_cgroup_move_account(page, 1, pc,
5336 mc.from, mc.to, false)) {
5338 /* we uncharge from mc.from later. */
5341 putback_lru_page(page);
5342 put: /* is_target_pte_for_mc() gets the page */
5345 case MC_TARGET_SWAP:
5347 if (!mem_cgroup_move_swap_account(ent,
5348 mc.from, mc.to, false)) {
5350 /* we fixup refcnts and charges later. */
5358 pte_unmap_unlock(pte - 1, ptl);
5363 * We have consumed all precharges we got in can_attach().
5364 * We try charge one by one, but don't do any additional
5365 * charges to mc.to if we have failed in charge once in attach()
5368 ret = mem_cgroup_do_precharge(1);
5376 static void mem_cgroup_move_charge(struct mm_struct *mm)
5378 struct vm_area_struct *vma;
5380 lru_add_drain_all();
5382 if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
5384 * Someone who are holding the mmap_sem might be waiting in
5385 * waitq. So we cancel all extra charges, wake up all waiters,
5386 * and retry. Because we cancel precharges, we might not be able
5387 * to move enough charges, but moving charge is a best-effort
5388 * feature anyway, so it wouldn't be a big problem.
5390 __mem_cgroup_clear_mc();
5394 for (vma = mm->mmap; vma; vma = vma->vm_next) {
5396 struct mm_walk mem_cgroup_move_charge_walk = {
5397 .pmd_entry = mem_cgroup_move_charge_pte_range,
5401 if (is_vm_hugetlb_page(vma))
5403 ret = walk_page_range(vma->vm_start, vma->vm_end,
5404 &mem_cgroup_move_charge_walk);
5407 * means we have consumed all precharges and failed in
5408 * doing additional charge. Just abandon here.
5412 up_read(&mm->mmap_sem);
5415 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
5416 struct cgroup *cont,
5417 struct cgroup *old_cont,
5418 struct task_struct *p)
5420 struct mm_struct *mm = get_task_mm(p);
5424 mem_cgroup_move_charge(mm);
5429 mem_cgroup_clear_mc();
5431 #else /* !CONFIG_MMU */
5432 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
5433 struct cgroup *cgroup,
5434 struct task_struct *p)
5438 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
5439 struct cgroup *cgroup,
5440 struct task_struct *p)
5443 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
5444 struct cgroup *cont,
5445 struct cgroup *old_cont,
5446 struct task_struct *p)
5451 struct cgroup_subsys mem_cgroup_subsys = {
5453 .subsys_id = mem_cgroup_subsys_id,
5454 .create = mem_cgroup_create,
5455 .pre_destroy = mem_cgroup_pre_destroy,
5456 .destroy = mem_cgroup_destroy,
5457 .populate = mem_cgroup_populate,
5458 .can_attach = mem_cgroup_can_attach,
5459 .cancel_attach = mem_cgroup_cancel_attach,
5460 .attach = mem_cgroup_move_task,
5465 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
5466 static int __init enable_swap_account(char *s)
5468 /* consider enabled if no parameter or 1 is given */
5469 if (!strcmp(s, "1"))
5470 really_do_swap_account = 1;
5471 else if (!strcmp(s, "0"))
5472 really_do_swap_account = 0;
5475 __setup("swapaccount=", enable_swap_account);