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];
125 * per-zone information in memory controller.
127 struct mem_cgroup_per_zone {
129 * spin_lock to protect the per cgroup LRU
131 struct list_head lists[NR_LRU_LISTS];
132 unsigned long count[NR_LRU_LISTS];
134 struct zone_reclaim_stat reclaim_stat;
135 struct rb_node tree_node; /* RB tree node */
136 unsigned long long usage_in_excess;/* Set to the value by which */
137 /* the soft limit is exceeded*/
139 struct mem_cgroup *mem; /* Back pointer, we cannot */
140 /* use container_of */
142 /* Macro for accessing counter */
143 #define MEM_CGROUP_ZSTAT(mz, idx) ((mz)->count[(idx)])
145 struct mem_cgroup_per_node {
146 struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
149 struct mem_cgroup_lru_info {
150 struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
154 * Cgroups above their limits are maintained in a RB-Tree, independent of
155 * their hierarchy representation
158 struct mem_cgroup_tree_per_zone {
159 struct rb_root rb_root;
163 struct mem_cgroup_tree_per_node {
164 struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
167 struct mem_cgroup_tree {
168 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
171 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
173 struct mem_cgroup_threshold {
174 struct eventfd_ctx *eventfd;
179 struct mem_cgroup_threshold_ary {
180 /* An array index points to threshold just below usage. */
181 int current_threshold;
182 /* Size of entries[] */
184 /* Array of thresholds */
185 struct mem_cgroup_threshold entries[0];
188 struct mem_cgroup_thresholds {
189 /* Primary thresholds array */
190 struct mem_cgroup_threshold_ary *primary;
192 * Spare threshold array.
193 * This is needed to make mem_cgroup_unregister_event() "never fail".
194 * It must be able to store at least primary->size - 1 entries.
196 struct mem_cgroup_threshold_ary *spare;
200 struct mem_cgroup_eventfd_list {
201 struct list_head list;
202 struct eventfd_ctx *eventfd;
205 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
206 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
209 * The memory controller data structure. The memory controller controls both
210 * page cache and RSS per cgroup. We would eventually like to provide
211 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
212 * to help the administrator determine what knobs to tune.
214 * TODO: Add a water mark for the memory controller. Reclaim will begin when
215 * we hit the water mark. May be even add a low water mark, such that
216 * no reclaim occurs from a cgroup at it's low water mark, this is
217 * a feature that will be implemented much later in the future.
220 struct cgroup_subsys_state css;
222 * the counter to account for memory usage
224 struct res_counter res;
226 * the counter to account for mem+swap usage.
228 struct res_counter memsw;
230 * Per cgroup active and inactive list, similar to the
231 * per zone LRU lists.
233 struct mem_cgroup_lru_info info;
235 * While reclaiming in a hierarchy, we cache the last child we
238 int last_scanned_child;
239 int last_scanned_node;
241 nodemask_t scan_nodes;
242 atomic_t numainfo_events;
243 atomic_t numainfo_updating;
246 * Should the accounting and control be hierarchical, per subtree?
256 /* OOM-Killer disable */
257 int oom_kill_disable;
259 /* set when res.limit == memsw.limit */
260 bool memsw_is_minimum;
262 /* protect arrays of thresholds */
263 struct mutex thresholds_lock;
265 /* thresholds for memory usage. RCU-protected */
266 struct mem_cgroup_thresholds thresholds;
268 /* thresholds for mem+swap usage. RCU-protected */
269 struct mem_cgroup_thresholds memsw_thresholds;
271 /* For oom notifier event fd */
272 struct list_head oom_notify;
275 * Should we move charges of a task when a task is moved into this
276 * mem_cgroup ? And what type of charges should we move ?
278 unsigned long move_charge_at_immigrate;
282 struct mem_cgroup_stat_cpu *stat;
284 * used when a cpu is offlined or other synchronizations
285 * See mem_cgroup_read_stat().
287 struct mem_cgroup_stat_cpu nocpu_base;
288 spinlock_t pcp_counter_lock;
291 /* Stuffs for move charges at task migration. */
293 * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a
294 * left-shifted bitmap of these types.
297 MOVE_CHARGE_TYPE_ANON, /* private anonymous page and swap of it */
298 MOVE_CHARGE_TYPE_FILE, /* file page(including tmpfs) and swap of it */
302 /* "mc" and its members are protected by cgroup_mutex */
303 static struct move_charge_struct {
304 spinlock_t lock; /* for from, to */
305 struct mem_cgroup *from;
306 struct mem_cgroup *to;
307 unsigned long precharge;
308 unsigned long moved_charge;
309 unsigned long moved_swap;
310 struct task_struct *moving_task; /* a task moving charges */
311 wait_queue_head_t waitq; /* a waitq for other context */
313 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
314 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
317 static bool move_anon(void)
319 return test_bit(MOVE_CHARGE_TYPE_ANON,
320 &mc.to->move_charge_at_immigrate);
323 static bool move_file(void)
325 return test_bit(MOVE_CHARGE_TYPE_FILE,
326 &mc.to->move_charge_at_immigrate);
330 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
331 * limit reclaim to prevent infinite loops, if they ever occur.
333 #define MEM_CGROUP_MAX_RECLAIM_LOOPS (100)
334 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS (2)
337 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
338 MEM_CGROUP_CHARGE_TYPE_MAPPED,
339 MEM_CGROUP_CHARGE_TYPE_SHMEM, /* used by page migration of shmem */
340 MEM_CGROUP_CHARGE_TYPE_FORCE, /* used by force_empty */
341 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
342 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
346 /* for encoding cft->private value on file */
349 #define _OOM_TYPE (2)
350 #define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val))
351 #define MEMFILE_TYPE(val) (((val) >> 16) & 0xffff)
352 #define MEMFILE_ATTR(val) ((val) & 0xffff)
353 /* Used for OOM nofiier */
354 #define OOM_CONTROL (0)
357 * Reclaim flags for mem_cgroup_hierarchical_reclaim
359 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
360 #define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
361 #define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
362 #define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
363 #define MEM_CGROUP_RECLAIM_SOFT_BIT 0x2
364 #define MEM_CGROUP_RECLAIM_SOFT (1 << MEM_CGROUP_RECLAIM_SOFT_BIT)
366 static void mem_cgroup_get(struct mem_cgroup *memcg);
367 static void mem_cgroup_put(struct mem_cgroup *memcg);
368 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg);
369 static void drain_all_stock_async(struct mem_cgroup *memcg);
371 static struct mem_cgroup_per_zone *
372 mem_cgroup_zoneinfo(struct mem_cgroup *memcg, int nid, int zid)
374 return &memcg->info.nodeinfo[nid]->zoneinfo[zid];
377 struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *memcg)
382 static struct mem_cgroup_per_zone *
383 page_cgroup_zoneinfo(struct mem_cgroup *memcg, struct page *page)
385 int nid = page_to_nid(page);
386 int zid = page_zonenum(page);
388 return mem_cgroup_zoneinfo(memcg, nid, zid);
391 static struct mem_cgroup_tree_per_zone *
392 soft_limit_tree_node_zone(int nid, int zid)
394 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
397 static struct mem_cgroup_tree_per_zone *
398 soft_limit_tree_from_page(struct page *page)
400 int nid = page_to_nid(page);
401 int zid = page_zonenum(page);
403 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
407 __mem_cgroup_insert_exceeded(struct mem_cgroup *memcg,
408 struct mem_cgroup_per_zone *mz,
409 struct mem_cgroup_tree_per_zone *mctz,
410 unsigned long long new_usage_in_excess)
412 struct rb_node **p = &mctz->rb_root.rb_node;
413 struct rb_node *parent = NULL;
414 struct mem_cgroup_per_zone *mz_node;
419 mz->usage_in_excess = new_usage_in_excess;
420 if (!mz->usage_in_excess)
424 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
426 if (mz->usage_in_excess < mz_node->usage_in_excess)
429 * We can't avoid mem cgroups that are over their soft
430 * limit by the same amount
432 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
435 rb_link_node(&mz->tree_node, parent, p);
436 rb_insert_color(&mz->tree_node, &mctz->rb_root);
441 __mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
442 struct mem_cgroup_per_zone *mz,
443 struct mem_cgroup_tree_per_zone *mctz)
447 rb_erase(&mz->tree_node, &mctz->rb_root);
452 mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
453 struct mem_cgroup_per_zone *mz,
454 struct mem_cgroup_tree_per_zone *mctz)
456 spin_lock(&mctz->lock);
457 __mem_cgroup_remove_exceeded(memcg, mz, mctz);
458 spin_unlock(&mctz->lock);
462 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
464 unsigned long long excess;
465 struct mem_cgroup_per_zone *mz;
466 struct mem_cgroup_tree_per_zone *mctz;
467 int nid = page_to_nid(page);
468 int zid = page_zonenum(page);
469 mctz = soft_limit_tree_from_page(page);
472 * Necessary to update all ancestors when hierarchy is used.
473 * because their event counter is not touched.
475 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
476 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
477 excess = res_counter_soft_limit_excess(&memcg->res);
479 * We have to update the tree if mz is on RB-tree or
480 * mem is over its softlimit.
482 if (excess || mz->on_tree) {
483 spin_lock(&mctz->lock);
484 /* if on-tree, remove it */
486 __mem_cgroup_remove_exceeded(memcg, mz, mctz);
488 * Insert again. mz->usage_in_excess will be updated.
489 * If excess is 0, no tree ops.
491 __mem_cgroup_insert_exceeded(memcg, mz, mctz, excess);
492 spin_unlock(&mctz->lock);
497 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
500 struct mem_cgroup_per_zone *mz;
501 struct mem_cgroup_tree_per_zone *mctz;
503 for_each_node_state(node, N_POSSIBLE) {
504 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
505 mz = mem_cgroup_zoneinfo(memcg, node, zone);
506 mctz = soft_limit_tree_node_zone(node, zone);
507 mem_cgroup_remove_exceeded(memcg, mz, mctz);
512 static struct mem_cgroup_per_zone *
513 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
515 struct rb_node *rightmost = NULL;
516 struct mem_cgroup_per_zone *mz;
520 rightmost = rb_last(&mctz->rb_root);
522 goto done; /* Nothing to reclaim from */
524 mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
526 * Remove the node now but someone else can add it back,
527 * we will to add it back at the end of reclaim to its correct
528 * position in the tree.
530 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
531 if (!res_counter_soft_limit_excess(&mz->mem->res) ||
532 !css_tryget(&mz->mem->css))
538 static struct mem_cgroup_per_zone *
539 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
541 struct mem_cgroup_per_zone *mz;
543 spin_lock(&mctz->lock);
544 mz = __mem_cgroup_largest_soft_limit_node(mctz);
545 spin_unlock(&mctz->lock);
550 * Implementation Note: reading percpu statistics for memcg.
552 * Both of vmstat[] and percpu_counter has threshold and do periodic
553 * synchronization to implement "quick" read. There are trade-off between
554 * reading cost and precision of value. Then, we may have a chance to implement
555 * a periodic synchronizion of counter in memcg's counter.
557 * But this _read() function is used for user interface now. The user accounts
558 * memory usage by memory cgroup and he _always_ requires exact value because
559 * he accounts memory. Even if we provide quick-and-fuzzy read, we always
560 * have to visit all online cpus and make sum. So, for now, unnecessary
561 * synchronization is not implemented. (just implemented for cpu hotplug)
563 * If there are kernel internal actions which can make use of some not-exact
564 * value, and reading all cpu value can be performance bottleneck in some
565 * common workload, threashold and synchonization as vmstat[] should be
568 static long mem_cgroup_read_stat(struct mem_cgroup *memcg,
569 enum mem_cgroup_stat_index idx)
575 for_each_online_cpu(cpu)
576 val += per_cpu(memcg->stat->count[idx], cpu);
577 #ifdef CONFIG_HOTPLUG_CPU
578 spin_lock(&memcg->pcp_counter_lock);
579 val += memcg->nocpu_base.count[idx];
580 spin_unlock(&memcg->pcp_counter_lock);
586 static void mem_cgroup_swap_statistics(struct mem_cgroup *memcg,
589 int val = (charge) ? 1 : -1;
590 this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_SWAPOUT], val);
593 void mem_cgroup_pgfault(struct mem_cgroup *memcg, int val)
595 this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_PGFAULT], val);
598 void mem_cgroup_pgmajfault(struct mem_cgroup *memcg, int val)
600 this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_PGMAJFAULT], val);
603 static unsigned long mem_cgroup_read_events(struct mem_cgroup *memcg,
604 enum mem_cgroup_events_index idx)
606 unsigned long val = 0;
609 for_each_online_cpu(cpu)
610 val += per_cpu(memcg->stat->events[idx], cpu);
611 #ifdef CONFIG_HOTPLUG_CPU
612 spin_lock(&memcg->pcp_counter_lock);
613 val += memcg->nocpu_base.events[idx];
614 spin_unlock(&memcg->pcp_counter_lock);
619 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
620 bool file, int nr_pages)
625 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_CACHE],
628 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS],
631 /* pagein of a big page is an event. So, ignore page size */
633 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGIN]);
635 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]);
636 nr_pages = -nr_pages; /* for event */
639 __this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_COUNT], nr_pages);
645 mem_cgroup_zone_nr_lru_pages(struct mem_cgroup *memcg, int nid, int zid,
646 unsigned int lru_mask)
648 struct mem_cgroup_per_zone *mz;
650 unsigned long ret = 0;
652 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
655 if (BIT(l) & lru_mask)
656 ret += MEM_CGROUP_ZSTAT(mz, l);
662 mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
663 int nid, unsigned int lru_mask)
668 for (zid = 0; zid < MAX_NR_ZONES; zid++)
669 total += mem_cgroup_zone_nr_lru_pages(memcg,
675 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
676 unsigned int lru_mask)
681 for_each_node_state(nid, N_HIGH_MEMORY)
682 total += mem_cgroup_node_nr_lru_pages(memcg, nid, lru_mask);
686 static bool __memcg_event_check(struct mem_cgroup *memcg, int 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 return ((long)next - (long)val < 0);
696 static void __mem_cgroup_target_update(struct mem_cgroup *memcg, int target)
698 unsigned long val, next;
700 val = __this_cpu_read(memcg->stat->events[MEM_CGROUP_EVENTS_COUNT]);
703 case MEM_CGROUP_TARGET_THRESH:
704 next = val + THRESHOLDS_EVENTS_TARGET;
706 case MEM_CGROUP_TARGET_SOFTLIMIT:
707 next = val + SOFTLIMIT_EVENTS_TARGET;
709 case MEM_CGROUP_TARGET_NUMAINFO:
710 next = val + NUMAINFO_EVENTS_TARGET;
716 __this_cpu_write(memcg->stat->targets[target], next);
720 * Check events in order.
723 static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
726 /* threshold event is triggered in finer grain than soft limit */
727 if (unlikely(__memcg_event_check(memcg, MEM_CGROUP_TARGET_THRESH))) {
728 mem_cgroup_threshold(memcg);
729 __mem_cgroup_target_update(memcg, MEM_CGROUP_TARGET_THRESH);
730 if (unlikely(__memcg_event_check(memcg,
731 MEM_CGROUP_TARGET_SOFTLIMIT))) {
732 mem_cgroup_update_tree(memcg, page);
733 __mem_cgroup_target_update(memcg,
734 MEM_CGROUP_TARGET_SOFTLIMIT);
737 if (unlikely(__memcg_event_check(memcg,
738 MEM_CGROUP_TARGET_NUMAINFO))) {
739 atomic_inc(&memcg->numainfo_events);
740 __mem_cgroup_target_update(memcg,
741 MEM_CGROUP_TARGET_NUMAINFO);
748 static struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
750 return container_of(cgroup_subsys_state(cont,
751 mem_cgroup_subsys_id), struct mem_cgroup,
755 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
758 * mm_update_next_owner() may clear mm->owner to NULL
759 * if it races with swapoff, page migration, etc.
760 * So this can be called with p == NULL.
765 return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
766 struct mem_cgroup, css);
769 struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
771 struct mem_cgroup *memcg = NULL;
776 * Because we have no locks, mm->owner's may be being moved to other
777 * cgroup. We use css_tryget() here even if this looks
778 * pessimistic (rather than adding locks here).
782 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
783 if (unlikely(!memcg))
785 } while (!css_tryget(&memcg->css));
790 static struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
791 struct mem_cgroup *prev,
794 struct mem_cgroup *memcg = NULL;
798 root = root_mem_cgroup;
800 if (prev && !reclaim)
801 id = css_id(&prev->css);
803 if (prev && prev != root)
806 if (!root->use_hierarchy && root != root_mem_cgroup) {
813 struct cgroup_subsys_state *css;
816 id = root->last_scanned_child;
819 css = css_get_next(&mem_cgroup_subsys, id + 1, &root->css, &id);
821 if (css == &root->css || css_tryget(css))
822 memcg = container_of(css,
823 struct mem_cgroup, css);
829 root->last_scanned_child = id;
837 static void mem_cgroup_iter_break(struct mem_cgroup *root,
838 struct mem_cgroup *prev)
841 root = root_mem_cgroup;
842 if (prev && prev != root)
847 * Iteration constructs for visiting all cgroups (under a tree). If
848 * loops are exited prematurely (break), mem_cgroup_iter_break() must
849 * be used for reference counting.
851 #define for_each_mem_cgroup_tree(iter, root) \
852 for (iter = mem_cgroup_iter(root, NULL, false); \
854 iter = mem_cgroup_iter(root, iter, false))
856 #define for_each_mem_cgroup(iter) \
857 for (iter = mem_cgroup_iter(NULL, NULL, false); \
859 iter = mem_cgroup_iter(NULL, iter, false))
861 static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
863 return (memcg == root_mem_cgroup);
866 void mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx)
868 struct mem_cgroup *memcg;
874 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
875 if (unlikely(!memcg))
880 mem_cgroup_pgmajfault(memcg, 1);
883 mem_cgroup_pgfault(memcg, 1);
891 EXPORT_SYMBOL(mem_cgroup_count_vm_event);
894 * Following LRU functions are allowed to be used without PCG_LOCK.
895 * Operations are called by routine of global LRU independently from memcg.
896 * What we have to take care of here is validness of pc->mem_cgroup.
898 * Changes to pc->mem_cgroup happens when
901 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
902 * It is added to LRU before charge.
903 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
904 * When moving account, the page is not on LRU. It's isolated.
907 void mem_cgroup_del_lru_list(struct page *page, enum lru_list lru)
909 struct page_cgroup *pc;
910 struct mem_cgroup_per_zone *mz;
912 if (mem_cgroup_disabled())
914 pc = lookup_page_cgroup(page);
915 /* can happen while we handle swapcache. */
916 if (!TestClearPageCgroupAcctLRU(pc))
918 VM_BUG_ON(!pc->mem_cgroup);
920 * We don't check PCG_USED bit. It's cleared when the "page" is finally
921 * removed from global LRU.
923 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
924 /* huge page split is done under lru_lock. so, we have no races. */
925 MEM_CGROUP_ZSTAT(mz, lru) -= 1 << compound_order(page);
926 if (mem_cgroup_is_root(pc->mem_cgroup))
928 VM_BUG_ON(list_empty(&pc->lru));
929 list_del_init(&pc->lru);
932 void mem_cgroup_del_lru(struct page *page)
934 mem_cgroup_del_lru_list(page, page_lru(page));
938 * Writeback is about to end against a page which has been marked for immediate
939 * reclaim. If it still appears to be reclaimable, move it to the tail of the
942 void mem_cgroup_rotate_reclaimable_page(struct page *page)
944 struct mem_cgroup_per_zone *mz;
945 struct page_cgroup *pc;
946 enum lru_list lru = page_lru(page);
948 if (mem_cgroup_disabled())
951 pc = lookup_page_cgroup(page);
952 /* unused or root page is not rotated. */
953 if (!PageCgroupUsed(pc))
955 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
957 if (mem_cgroup_is_root(pc->mem_cgroup))
959 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
960 list_move_tail(&pc->lru, &mz->lists[lru]);
963 void mem_cgroup_rotate_lru_list(struct page *page, enum lru_list lru)
965 struct mem_cgroup_per_zone *mz;
966 struct page_cgroup *pc;
968 if (mem_cgroup_disabled())
971 pc = lookup_page_cgroup(page);
972 /* unused or root page is not rotated. */
973 if (!PageCgroupUsed(pc))
975 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
977 if (mem_cgroup_is_root(pc->mem_cgroup))
979 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
980 list_move(&pc->lru, &mz->lists[lru]);
983 void mem_cgroup_add_lru_list(struct page *page, enum lru_list lru)
985 struct page_cgroup *pc;
986 struct mem_cgroup_per_zone *mz;
988 if (mem_cgroup_disabled())
990 pc = lookup_page_cgroup(page);
991 VM_BUG_ON(PageCgroupAcctLRU(pc));
994 * SetPageLRU SetPageCgroupUsed
996 * PageCgroupUsed && add to memcg LRU PageLRU && add to memcg LRU
998 * Ensure that one of the two sides adds the page to the memcg
1002 if (!PageCgroupUsed(pc))
1004 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1006 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1007 /* huge page split is done under lru_lock. so, we have no races. */
1008 MEM_CGROUP_ZSTAT(mz, lru) += 1 << compound_order(page);
1009 SetPageCgroupAcctLRU(pc);
1010 if (mem_cgroup_is_root(pc->mem_cgroup))
1012 list_add(&pc->lru, &mz->lists[lru]);
1016 * At handling SwapCache and other FUSE stuff, pc->mem_cgroup may be changed
1017 * while it's linked to lru because the page may be reused after it's fully
1018 * uncharged. To handle that, unlink page_cgroup from LRU when charge it again.
1019 * It's done under lock_page and expected that zone->lru_lock isnever held.
1021 static void mem_cgroup_lru_del_before_commit(struct page *page)
1023 unsigned long flags;
1024 struct zone *zone = page_zone(page);
1025 struct page_cgroup *pc = lookup_page_cgroup(page);
1028 * Doing this check without taking ->lru_lock seems wrong but this
1029 * is safe. Because if page_cgroup's USED bit is unset, the page
1030 * will not be added to any memcg's LRU. If page_cgroup's USED bit is
1031 * set, the commit after this will fail, anyway.
1032 * This all charge/uncharge is done under some mutual execustion.
1033 * So, we don't need to taking care of changes in USED bit.
1035 if (likely(!PageLRU(page)))
1038 spin_lock_irqsave(&zone->lru_lock, flags);
1040 * Forget old LRU when this page_cgroup is *not* used. This Used bit
1041 * is guarded by lock_page() because the page is SwapCache.
1043 if (!PageCgroupUsed(pc))
1044 mem_cgroup_del_lru_list(page, page_lru(page));
1045 spin_unlock_irqrestore(&zone->lru_lock, flags);
1048 static void mem_cgroup_lru_add_after_commit(struct page *page)
1050 unsigned long flags;
1051 struct zone *zone = page_zone(page);
1052 struct page_cgroup *pc = lookup_page_cgroup(page);
1055 * SetPageLRU SetPageCgroupUsed
1057 * PageCgroupUsed && add to memcg LRU PageLRU && add to memcg LRU
1059 * Ensure that one of the two sides adds the page to the memcg
1060 * LRU during a race.
1063 /* taking care of that the page is added to LRU while we commit it */
1064 if (likely(!PageLRU(page)))
1066 spin_lock_irqsave(&zone->lru_lock, flags);
1067 /* link when the page is linked to LRU but page_cgroup isn't */
1068 if (PageLRU(page) && !PageCgroupAcctLRU(pc))
1069 mem_cgroup_add_lru_list(page, page_lru(page));
1070 spin_unlock_irqrestore(&zone->lru_lock, flags);
1074 void mem_cgroup_move_lists(struct page *page,
1075 enum lru_list from, enum lru_list to)
1077 if (mem_cgroup_disabled())
1079 mem_cgroup_del_lru_list(page, from);
1080 mem_cgroup_add_lru_list(page, to);
1084 * Checks whether given mem is same or in the root_mem_cgroup's
1087 static bool mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1088 struct mem_cgroup *memcg)
1090 if (root_memcg != memcg) {
1091 return (root_memcg->use_hierarchy &&
1092 css_is_ancestor(&memcg->css, &root_memcg->css));
1098 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *memcg)
1101 struct mem_cgroup *curr = NULL;
1102 struct task_struct *p;
1104 p = find_lock_task_mm(task);
1107 curr = try_get_mem_cgroup_from_mm(p->mm);
1112 * We should check use_hierarchy of "memcg" not "curr". Because checking
1113 * use_hierarchy of "curr" here make this function true if hierarchy is
1114 * enabled in "curr" and "curr" is a child of "memcg" in *cgroup*
1115 * hierarchy(even if use_hierarchy is disabled in "memcg").
1117 ret = mem_cgroup_same_or_subtree(memcg, curr);
1118 css_put(&curr->css);
1122 int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg, struct zone *zone)
1124 unsigned long inactive_ratio;
1125 int nid = zone_to_nid(zone);
1126 int zid = zone_idx(zone);
1127 unsigned long inactive;
1128 unsigned long active;
1131 inactive = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1132 BIT(LRU_INACTIVE_ANON));
1133 active = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1134 BIT(LRU_ACTIVE_ANON));
1136 gb = (inactive + active) >> (30 - PAGE_SHIFT);
1138 inactive_ratio = int_sqrt(10 * gb);
1142 return inactive * inactive_ratio < active;
1145 int mem_cgroup_inactive_file_is_low(struct mem_cgroup *memcg, struct zone *zone)
1147 unsigned long active;
1148 unsigned long inactive;
1149 int zid = zone_idx(zone);
1150 int nid = zone_to_nid(zone);
1152 inactive = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1153 BIT(LRU_INACTIVE_FILE));
1154 active = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1155 BIT(LRU_ACTIVE_FILE));
1157 return (active > inactive);
1160 struct zone_reclaim_stat *mem_cgroup_get_reclaim_stat(struct mem_cgroup *memcg,
1163 int nid = zone_to_nid(zone);
1164 int zid = zone_idx(zone);
1165 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
1167 return &mz->reclaim_stat;
1170 struct zone_reclaim_stat *
1171 mem_cgroup_get_reclaim_stat_from_page(struct page *page)
1173 struct page_cgroup *pc;
1174 struct mem_cgroup_per_zone *mz;
1176 if (mem_cgroup_disabled())
1179 pc = lookup_page_cgroup(page);
1180 if (!PageCgroupUsed(pc))
1182 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1184 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1185 return &mz->reclaim_stat;
1188 unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan,
1189 struct list_head *dst,
1190 unsigned long *scanned, int order,
1191 isolate_mode_t mode,
1193 struct mem_cgroup *mem_cont,
1194 int active, int file)
1196 unsigned long nr_taken = 0;
1200 struct list_head *src;
1201 struct page_cgroup *pc, *tmp;
1202 int nid = zone_to_nid(z);
1203 int zid = zone_idx(z);
1204 struct mem_cgroup_per_zone *mz;
1205 int lru = LRU_FILE * file + active;
1209 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
1210 src = &mz->lists[lru];
1213 list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
1214 if (scan >= nr_to_scan)
1217 if (unlikely(!PageCgroupUsed(pc)))
1220 page = lookup_cgroup_page(pc);
1222 if (unlikely(!PageLRU(page)))
1226 ret = __isolate_lru_page(page, mode, file);
1229 list_move(&page->lru, dst);
1230 mem_cgroup_del_lru(page);
1231 nr_taken += hpage_nr_pages(page);
1234 /* we don't affect global LRU but rotate in our LRU */
1235 mem_cgroup_rotate_lru_list(page, page_lru(page));
1244 trace_mm_vmscan_memcg_isolate(0, nr_to_scan, scan, nr_taken,
1250 #define mem_cgroup_from_res_counter(counter, member) \
1251 container_of(counter, struct mem_cgroup, member)
1254 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1255 * @mem: the memory cgroup
1257 * Returns the maximum amount of memory @mem can be charged with, in
1260 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1262 unsigned long long margin;
1264 margin = res_counter_margin(&memcg->res);
1265 if (do_swap_account)
1266 margin = min(margin, res_counter_margin(&memcg->memsw));
1267 return margin >> PAGE_SHIFT;
1270 int mem_cgroup_swappiness(struct mem_cgroup *memcg)
1272 struct cgroup *cgrp = memcg->css.cgroup;
1275 if (cgrp->parent == NULL)
1276 return vm_swappiness;
1278 return memcg->swappiness;
1281 static void mem_cgroup_start_move(struct mem_cgroup *memcg)
1286 spin_lock(&memcg->pcp_counter_lock);
1287 for_each_online_cpu(cpu)
1288 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) += 1;
1289 memcg->nocpu_base.count[MEM_CGROUP_ON_MOVE] += 1;
1290 spin_unlock(&memcg->pcp_counter_lock);
1296 static void mem_cgroup_end_move(struct mem_cgroup *memcg)
1303 spin_lock(&memcg->pcp_counter_lock);
1304 for_each_online_cpu(cpu)
1305 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) -= 1;
1306 memcg->nocpu_base.count[MEM_CGROUP_ON_MOVE] -= 1;
1307 spin_unlock(&memcg->pcp_counter_lock);
1311 * 2 routines for checking "mem" is under move_account() or not.
1313 * mem_cgroup_stealed() - checking a cgroup is mc.from or not. This is used
1314 * for avoiding race in accounting. If true,
1315 * pc->mem_cgroup may be overwritten.
1317 * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
1318 * under hierarchy of moving cgroups. This is for
1319 * waiting at hith-memory prressure caused by "move".
1322 static bool mem_cgroup_stealed(struct mem_cgroup *memcg)
1324 VM_BUG_ON(!rcu_read_lock_held());
1325 return this_cpu_read(memcg->stat->count[MEM_CGROUP_ON_MOVE]) > 0;
1328 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1330 struct mem_cgroup *from;
1331 struct mem_cgroup *to;
1334 * Unlike task_move routines, we access mc.to, mc.from not under
1335 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1337 spin_lock(&mc.lock);
1343 ret = mem_cgroup_same_or_subtree(memcg, from)
1344 || mem_cgroup_same_or_subtree(memcg, to);
1346 spin_unlock(&mc.lock);
1350 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1352 if (mc.moving_task && current != mc.moving_task) {
1353 if (mem_cgroup_under_move(memcg)) {
1355 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1356 /* moving charge context might have finished. */
1359 finish_wait(&mc.waitq, &wait);
1367 * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode.
1368 * @memcg: The memory cgroup that went over limit
1369 * @p: Task that is going to be killed
1371 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1374 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1376 struct cgroup *task_cgrp;
1377 struct cgroup *mem_cgrp;
1379 * Need a buffer in BSS, can't rely on allocations. The code relies
1380 * on the assumption that OOM is serialized for memory controller.
1381 * If this assumption is broken, revisit this code.
1383 static char memcg_name[PATH_MAX];
1392 mem_cgrp = memcg->css.cgroup;
1393 task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1395 ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1398 * Unfortunately, we are unable to convert to a useful name
1399 * But we'll still print out the usage information
1406 printk(KERN_INFO "Task in %s killed", memcg_name);
1409 ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1417 * Continues from above, so we don't need an KERN_ level
1419 printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
1422 printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
1423 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1424 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1425 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1426 printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
1428 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1429 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1430 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1434 * This function returns the number of memcg under hierarchy tree. Returns
1435 * 1(self count) if no children.
1437 static int mem_cgroup_count_children(struct mem_cgroup *memcg)
1440 struct mem_cgroup *iter;
1442 for_each_mem_cgroup_tree(iter, memcg)
1448 * Return the memory (and swap, if configured) limit for a memcg.
1450 u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
1455 limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
1456 limit += total_swap_pages << PAGE_SHIFT;
1458 memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
1460 * If memsw is finite and limits the amount of swap space available
1461 * to this memcg, return that limit.
1463 return min(limit, memsw);
1467 * test_mem_cgroup_node_reclaimable
1468 * @mem: the target memcg
1469 * @nid: the node ID to be checked.
1470 * @noswap : specify true here if the user wants flle only information.
1472 * This function returns whether the specified memcg contains any
1473 * reclaimable pages on a node. Returns true if there are any reclaimable
1474 * pages in the node.
1476 static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
1477 int nid, bool noswap)
1479 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE))
1481 if (noswap || !total_swap_pages)
1483 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON))
1488 #if MAX_NUMNODES > 1
1491 * Always updating the nodemask is not very good - even if we have an empty
1492 * list or the wrong list here, we can start from some node and traverse all
1493 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1496 static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
1500 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1501 * pagein/pageout changes since the last update.
1503 if (!atomic_read(&memcg->numainfo_events))
1505 if (atomic_inc_return(&memcg->numainfo_updating) > 1)
1508 /* make a nodemask where this memcg uses memory from */
1509 memcg->scan_nodes = node_states[N_HIGH_MEMORY];
1511 for_each_node_mask(nid, node_states[N_HIGH_MEMORY]) {
1513 if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
1514 node_clear(nid, memcg->scan_nodes);
1517 atomic_set(&memcg->numainfo_events, 0);
1518 atomic_set(&memcg->numainfo_updating, 0);
1522 * Selecting a node where we start reclaim from. Because what we need is just
1523 * reducing usage counter, start from anywhere is O,K. Considering
1524 * memory reclaim from current node, there are pros. and cons.
1526 * Freeing memory from current node means freeing memory from a node which
1527 * we'll use or we've used. So, it may make LRU bad. And if several threads
1528 * hit limits, it will see a contention on a node. But freeing from remote
1529 * node means more costs for memory reclaim because of memory latency.
1531 * Now, we use round-robin. Better algorithm is welcomed.
1533 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1537 mem_cgroup_may_update_nodemask(memcg);
1538 node = memcg->last_scanned_node;
1540 node = next_node(node, memcg->scan_nodes);
1541 if (node == MAX_NUMNODES)
1542 node = first_node(memcg->scan_nodes);
1544 * We call this when we hit limit, not when pages are added to LRU.
1545 * No LRU may hold pages because all pages are UNEVICTABLE or
1546 * memcg is too small and all pages are not on LRU. In that case,
1547 * we use curret node.
1549 if (unlikely(node == MAX_NUMNODES))
1550 node = numa_node_id();
1552 memcg->last_scanned_node = node;
1557 * Check all nodes whether it contains reclaimable pages or not.
1558 * For quick scan, we make use of scan_nodes. This will allow us to skip
1559 * unused nodes. But scan_nodes is lazily updated and may not cotain
1560 * enough new information. We need to do double check.
1562 bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
1567 * quick check...making use of scan_node.
1568 * We can skip unused nodes.
1570 if (!nodes_empty(memcg->scan_nodes)) {
1571 for (nid = first_node(memcg->scan_nodes);
1573 nid = next_node(nid, memcg->scan_nodes)) {
1575 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
1580 * Check rest of nodes.
1582 for_each_node_state(nid, N_HIGH_MEMORY) {
1583 if (node_isset(nid, memcg->scan_nodes))
1585 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
1592 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1597 bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
1599 return test_mem_cgroup_node_reclaimable(memcg, 0, noswap);
1604 * Scan the hierarchy if needed to reclaim memory. We remember the last child
1605 * we reclaimed from, so that we don't end up penalizing one child extensively
1606 * based on its position in the children list.
1608 * root_memcg is the original ancestor that we've been reclaim from.
1610 * We give up and return to the caller when we visit root_memcg twice.
1611 * (other groups can be removed while we're walking....)
1613 * If shrink==true, for avoiding to free too much, this returns immedieately.
1615 static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup *root_memcg,
1618 unsigned long reclaim_options,
1619 unsigned long *total_scanned)
1621 struct mem_cgroup *victim = NULL;
1624 bool noswap = reclaim_options & MEM_CGROUP_RECLAIM_NOSWAP;
1625 bool shrink = reclaim_options & MEM_CGROUP_RECLAIM_SHRINK;
1626 bool check_soft = reclaim_options & MEM_CGROUP_RECLAIM_SOFT;
1627 unsigned long excess;
1628 unsigned long nr_scanned;
1630 excess = res_counter_soft_limit_excess(&root_memcg->res) >> PAGE_SHIFT;
1632 /* If memsw_is_minimum==1, swap-out is of-no-use. */
1633 if (!check_soft && !shrink && root_memcg->memsw_is_minimum)
1637 victim = mem_cgroup_iter(root_memcg, victim, true);
1641 * We are not draining per cpu cached charges during
1642 * soft limit reclaim because global reclaim doesn't
1643 * care about charges. It tries to free some memory and
1644 * charges will not give any.
1646 if (!check_soft && loop >= 1)
1647 drain_all_stock_async(root_memcg);
1650 * If we have not been able to reclaim
1651 * anything, it might because there are
1652 * no reclaimable pages under this hierarchy
1654 if (!check_soft || !total)
1657 * We want to do more targeted reclaim.
1658 * excess >> 2 is not to excessive so as to
1659 * reclaim too much, nor too less that we keep
1660 * coming back to reclaim from this cgroup
1662 if (total >= (excess >> 2) ||
1663 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1668 if (!mem_cgroup_reclaimable(victim, noswap)) {
1669 /* this cgroup's local usage == 0 */
1672 /* we use swappiness of local cgroup */
1674 ret = mem_cgroup_shrink_node_zone(victim, gfp_mask,
1675 noswap, zone, &nr_scanned);
1676 *total_scanned += nr_scanned;
1678 ret = try_to_free_mem_cgroup_pages(victim, gfp_mask,
1682 * At shrinking usage, we can't check we should stop here or
1683 * reclaim more. It's depends on callers. last_scanned_child
1684 * will work enough for keeping fairness under tree.
1689 if (!res_counter_soft_limit_excess(&root_memcg->res))
1691 } else if (mem_cgroup_margin(root_memcg))
1694 mem_cgroup_iter_break(root_memcg, victim);
1699 * Check OOM-Killer is already running under our hierarchy.
1700 * If someone is running, return false.
1701 * Has to be called with memcg_oom_lock
1703 static bool mem_cgroup_oom_lock(struct mem_cgroup *memcg)
1705 struct mem_cgroup *iter, *failed = NULL;
1707 for_each_mem_cgroup_tree(iter, memcg) {
1708 if (iter->oom_lock) {
1710 * this subtree of our hierarchy is already locked
1711 * so we cannot give a lock.
1714 mem_cgroup_iter_break(memcg, iter);
1717 iter->oom_lock = true;
1724 * OK, we failed to lock the whole subtree so we have to clean up
1725 * what we set up to the failing subtree
1727 for_each_mem_cgroup_tree(iter, memcg) {
1728 if (iter == failed) {
1729 mem_cgroup_iter_break(memcg, iter);
1732 iter->oom_lock = false;
1738 * Has to be called with memcg_oom_lock
1740 static int mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1742 struct mem_cgroup *iter;
1744 for_each_mem_cgroup_tree(iter, memcg)
1745 iter->oom_lock = false;
1749 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1751 struct mem_cgroup *iter;
1753 for_each_mem_cgroup_tree(iter, memcg)
1754 atomic_inc(&iter->under_oom);
1757 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1759 struct mem_cgroup *iter;
1762 * When a new child is created while the hierarchy is under oom,
1763 * mem_cgroup_oom_lock() may not be called. We have to use
1764 * atomic_add_unless() here.
1766 for_each_mem_cgroup_tree(iter, memcg)
1767 atomic_add_unless(&iter->under_oom, -1, 0);
1770 static DEFINE_SPINLOCK(memcg_oom_lock);
1771 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1773 struct oom_wait_info {
1774 struct mem_cgroup *mem;
1778 static int memcg_oom_wake_function(wait_queue_t *wait,
1779 unsigned mode, int sync, void *arg)
1781 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg,
1783 struct oom_wait_info *oom_wait_info;
1785 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1786 oom_wait_memcg = oom_wait_info->mem;
1789 * Both of oom_wait_info->mem and wake_mem are stable under us.
1790 * Then we can use css_is_ancestor without taking care of RCU.
1792 if (!mem_cgroup_same_or_subtree(oom_wait_memcg, wake_memcg)
1793 && !mem_cgroup_same_or_subtree(wake_memcg, oom_wait_memcg))
1795 return autoremove_wake_function(wait, mode, sync, arg);
1798 static void memcg_wakeup_oom(struct mem_cgroup *memcg)
1800 /* for filtering, pass "memcg" as argument. */
1801 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
1804 static void memcg_oom_recover(struct mem_cgroup *memcg)
1806 if (memcg && atomic_read(&memcg->under_oom))
1807 memcg_wakeup_oom(memcg);
1811 * try to call OOM killer. returns false if we should exit memory-reclaim loop.
1813 bool mem_cgroup_handle_oom(struct mem_cgroup *memcg, gfp_t mask)
1815 struct oom_wait_info owait;
1816 bool locked, need_to_kill;
1819 owait.wait.flags = 0;
1820 owait.wait.func = memcg_oom_wake_function;
1821 owait.wait.private = current;
1822 INIT_LIST_HEAD(&owait.wait.task_list);
1823 need_to_kill = true;
1824 mem_cgroup_mark_under_oom(memcg);
1826 /* At first, try to OOM lock hierarchy under memcg.*/
1827 spin_lock(&memcg_oom_lock);
1828 locked = mem_cgroup_oom_lock(memcg);
1830 * Even if signal_pending(), we can't quit charge() loop without
1831 * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
1832 * under OOM is always welcomed, use TASK_KILLABLE here.
1834 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
1835 if (!locked || memcg->oom_kill_disable)
1836 need_to_kill = false;
1838 mem_cgroup_oom_notify(memcg);
1839 spin_unlock(&memcg_oom_lock);
1842 finish_wait(&memcg_oom_waitq, &owait.wait);
1843 mem_cgroup_out_of_memory(memcg, mask);
1846 finish_wait(&memcg_oom_waitq, &owait.wait);
1848 spin_lock(&memcg_oom_lock);
1850 mem_cgroup_oom_unlock(memcg);
1851 memcg_wakeup_oom(memcg);
1852 spin_unlock(&memcg_oom_lock);
1854 mem_cgroup_unmark_under_oom(memcg);
1856 if (test_thread_flag(TIF_MEMDIE) || fatal_signal_pending(current))
1858 /* Give chance to dying process */
1859 schedule_timeout_uninterruptible(1);
1864 * Currently used to update mapped file statistics, but the routine can be
1865 * generalized to update other statistics as well.
1867 * Notes: Race condition
1869 * We usually use page_cgroup_lock() for accessing page_cgroup member but
1870 * it tends to be costly. But considering some conditions, we doesn't need
1871 * to do so _always_.
1873 * Considering "charge", lock_page_cgroup() is not required because all
1874 * file-stat operations happen after a page is attached to radix-tree. There
1875 * are no race with "charge".
1877 * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
1878 * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
1879 * if there are race with "uncharge". Statistics itself is properly handled
1882 * Considering "move", this is an only case we see a race. To make the race
1883 * small, we check MEM_CGROUP_ON_MOVE percpu value and detect there are
1884 * possibility of race condition. If there is, we take a lock.
1887 void mem_cgroup_update_page_stat(struct page *page,
1888 enum mem_cgroup_page_stat_item idx, int val)
1890 struct mem_cgroup *memcg;
1891 struct page_cgroup *pc = lookup_page_cgroup(page);
1892 bool need_unlock = false;
1893 unsigned long uninitialized_var(flags);
1899 memcg = pc->mem_cgroup;
1900 if (unlikely(!memcg || !PageCgroupUsed(pc)))
1902 /* pc->mem_cgroup is unstable ? */
1903 if (unlikely(mem_cgroup_stealed(memcg)) || PageTransHuge(page)) {
1904 /* take a lock against to access pc->mem_cgroup */
1905 move_lock_page_cgroup(pc, &flags);
1907 memcg = pc->mem_cgroup;
1908 if (!memcg || !PageCgroupUsed(pc))
1913 case MEMCG_NR_FILE_MAPPED:
1915 SetPageCgroupFileMapped(pc);
1916 else if (!page_mapped(page))
1917 ClearPageCgroupFileMapped(pc);
1918 idx = MEM_CGROUP_STAT_FILE_MAPPED;
1924 this_cpu_add(memcg->stat->count[idx], val);
1927 if (unlikely(need_unlock))
1928 move_unlock_page_cgroup(pc, &flags);
1932 EXPORT_SYMBOL(mem_cgroup_update_page_stat);
1935 * size of first charge trial. "32" comes from vmscan.c's magic value.
1936 * TODO: maybe necessary to use big numbers in big irons.
1938 #define CHARGE_BATCH 32U
1939 struct memcg_stock_pcp {
1940 struct mem_cgroup *cached; /* this never be root cgroup */
1941 unsigned int nr_pages;
1942 struct work_struct work;
1943 unsigned long flags;
1944 #define FLUSHING_CACHED_CHARGE (0)
1946 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
1947 static DEFINE_MUTEX(percpu_charge_mutex);
1950 * Try to consume stocked charge on this cpu. If success, one page is consumed
1951 * from local stock and true is returned. If the stock is 0 or charges from a
1952 * cgroup which is not current target, returns false. This stock will be
1955 static bool consume_stock(struct mem_cgroup *memcg)
1957 struct memcg_stock_pcp *stock;
1960 stock = &get_cpu_var(memcg_stock);
1961 if (memcg == stock->cached && stock->nr_pages)
1963 else /* need to call res_counter_charge */
1965 put_cpu_var(memcg_stock);
1970 * Returns stocks cached in percpu to res_counter and reset cached information.
1972 static void drain_stock(struct memcg_stock_pcp *stock)
1974 struct mem_cgroup *old = stock->cached;
1976 if (stock->nr_pages) {
1977 unsigned long bytes = stock->nr_pages * PAGE_SIZE;
1979 res_counter_uncharge(&old->res, bytes);
1980 if (do_swap_account)
1981 res_counter_uncharge(&old->memsw, bytes);
1982 stock->nr_pages = 0;
1984 stock->cached = NULL;
1988 * This must be called under preempt disabled or must be called by
1989 * a thread which is pinned to local cpu.
1991 static void drain_local_stock(struct work_struct *dummy)
1993 struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
1995 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
1999 * Cache charges(val) which is from res_counter, to local per_cpu area.
2000 * This will be consumed by consume_stock() function, later.
2002 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2004 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
2006 if (stock->cached != memcg) { /* reset if necessary */
2008 stock->cached = memcg;
2010 stock->nr_pages += nr_pages;
2011 put_cpu_var(memcg_stock);
2015 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2016 * of the hierarchy under it. sync flag says whether we should block
2017 * until the work is done.
2019 static void drain_all_stock(struct mem_cgroup *root_memcg, bool sync)
2023 /* Notify other cpus that system-wide "drain" is running */
2026 for_each_online_cpu(cpu) {
2027 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2028 struct mem_cgroup *memcg;
2030 memcg = stock->cached;
2031 if (!memcg || !stock->nr_pages)
2033 if (!mem_cgroup_same_or_subtree(root_memcg, memcg))
2035 if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2037 drain_local_stock(&stock->work);
2039 schedule_work_on(cpu, &stock->work);
2047 for_each_online_cpu(cpu) {
2048 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2049 if (test_bit(FLUSHING_CACHED_CHARGE, &stock->flags))
2050 flush_work(&stock->work);
2057 * Tries to drain stocked charges in other cpus. This function is asynchronous
2058 * and just put a work per cpu for draining localy on each cpu. Caller can
2059 * expects some charges will be back to res_counter later but cannot wait for
2062 static void drain_all_stock_async(struct mem_cgroup *root_memcg)
2065 * If someone calls draining, avoid adding more kworker runs.
2067 if (!mutex_trylock(&percpu_charge_mutex))
2069 drain_all_stock(root_memcg, false);
2070 mutex_unlock(&percpu_charge_mutex);
2073 /* This is a synchronous drain interface. */
2074 static void drain_all_stock_sync(struct mem_cgroup *root_memcg)
2076 /* called when force_empty is called */
2077 mutex_lock(&percpu_charge_mutex);
2078 drain_all_stock(root_memcg, true);
2079 mutex_unlock(&percpu_charge_mutex);
2083 * This function drains percpu counter value from DEAD cpu and
2084 * move it to local cpu. Note that this function can be preempted.
2086 static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *memcg, int cpu)
2090 spin_lock(&memcg->pcp_counter_lock);
2091 for (i = 0; i < MEM_CGROUP_STAT_DATA; i++) {
2092 long x = per_cpu(memcg->stat->count[i], cpu);
2094 per_cpu(memcg->stat->count[i], cpu) = 0;
2095 memcg->nocpu_base.count[i] += x;
2097 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
2098 unsigned long x = per_cpu(memcg->stat->events[i], cpu);
2100 per_cpu(memcg->stat->events[i], cpu) = 0;
2101 memcg->nocpu_base.events[i] += x;
2103 /* need to clear ON_MOVE value, works as a kind of lock. */
2104 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) = 0;
2105 spin_unlock(&memcg->pcp_counter_lock);
2108 static void synchronize_mem_cgroup_on_move(struct mem_cgroup *memcg, int cpu)
2110 int idx = MEM_CGROUP_ON_MOVE;
2112 spin_lock(&memcg->pcp_counter_lock);
2113 per_cpu(memcg->stat->count[idx], cpu) = memcg->nocpu_base.count[idx];
2114 spin_unlock(&memcg->pcp_counter_lock);
2117 static int __cpuinit memcg_cpu_hotplug_callback(struct notifier_block *nb,
2118 unsigned long action,
2121 int cpu = (unsigned long)hcpu;
2122 struct memcg_stock_pcp *stock;
2123 struct mem_cgroup *iter;
2125 if ((action == CPU_ONLINE)) {
2126 for_each_mem_cgroup(iter)
2127 synchronize_mem_cgroup_on_move(iter, cpu);
2131 if ((action != CPU_DEAD) || action != CPU_DEAD_FROZEN)
2134 for_each_mem_cgroup(iter)
2135 mem_cgroup_drain_pcp_counter(iter, cpu);
2137 stock = &per_cpu(memcg_stock, cpu);
2143 /* See __mem_cgroup_try_charge() for details */
2145 CHARGE_OK, /* success */
2146 CHARGE_RETRY, /* need to retry but retry is not bad */
2147 CHARGE_NOMEM, /* we can't do more. return -ENOMEM */
2148 CHARGE_WOULDBLOCK, /* GFP_WAIT wasn't set and no enough res. */
2149 CHARGE_OOM_DIE, /* the current is killed because of OOM */
2152 static int mem_cgroup_do_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2153 unsigned int nr_pages, bool oom_check)
2155 unsigned long csize = nr_pages * PAGE_SIZE;
2156 struct mem_cgroup *mem_over_limit;
2157 struct res_counter *fail_res;
2158 unsigned long flags = 0;
2161 ret = res_counter_charge(&memcg->res, csize, &fail_res);
2164 if (!do_swap_account)
2166 ret = res_counter_charge(&memcg->memsw, csize, &fail_res);
2170 res_counter_uncharge(&memcg->res, csize);
2171 mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw);
2172 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
2174 mem_over_limit = mem_cgroup_from_res_counter(fail_res, res);
2176 * nr_pages can be either a huge page (HPAGE_PMD_NR), a batch
2177 * of regular pages (CHARGE_BATCH), or a single regular page (1).
2179 * Never reclaim on behalf of optional batching, retry with a
2180 * single page instead.
2182 if (nr_pages == CHARGE_BATCH)
2183 return CHARGE_RETRY;
2185 if (!(gfp_mask & __GFP_WAIT))
2186 return CHARGE_WOULDBLOCK;
2188 ret = mem_cgroup_hierarchical_reclaim(mem_over_limit, NULL,
2189 gfp_mask, flags, NULL);
2190 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2191 return CHARGE_RETRY;
2193 * Even though the limit is exceeded at this point, reclaim
2194 * may have been able to free some pages. Retry the charge
2195 * before killing the task.
2197 * Only for regular pages, though: huge pages are rather
2198 * unlikely to succeed so close to the limit, and we fall back
2199 * to regular pages anyway in case of failure.
2201 if (nr_pages == 1 && ret)
2202 return CHARGE_RETRY;
2205 * At task move, charge accounts can be doubly counted. So, it's
2206 * better to wait until the end of task_move if something is going on.
2208 if (mem_cgroup_wait_acct_move(mem_over_limit))
2209 return CHARGE_RETRY;
2211 /* If we don't need to call oom-killer at el, return immediately */
2213 return CHARGE_NOMEM;
2215 if (!mem_cgroup_handle_oom(mem_over_limit, gfp_mask))
2216 return CHARGE_OOM_DIE;
2218 return CHARGE_RETRY;
2222 * Unlike exported interface, "oom" parameter is added. if oom==true,
2223 * oom-killer can be invoked.
2225 static int __mem_cgroup_try_charge(struct mm_struct *mm,
2227 unsigned int nr_pages,
2228 struct mem_cgroup **ptr,
2231 unsigned int batch = max(CHARGE_BATCH, nr_pages);
2232 int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2233 struct mem_cgroup *memcg = NULL;
2237 * Unlike gloval-vm's OOM-kill, we're not in memory shortage
2238 * in system level. So, allow to go ahead dying process in addition to
2241 if (unlikely(test_thread_flag(TIF_MEMDIE)
2242 || fatal_signal_pending(current)))
2246 * We always charge the cgroup the mm_struct belongs to.
2247 * The mm_struct's mem_cgroup changes on task migration if the
2248 * thread group leader migrates. It's possible that mm is not
2249 * set, if so charge the init_mm (happens for pagecache usage).
2254 if (*ptr) { /* css should be a valid one */
2256 VM_BUG_ON(css_is_removed(&memcg->css));
2257 if (mem_cgroup_is_root(memcg))
2259 if (nr_pages == 1 && consume_stock(memcg))
2261 css_get(&memcg->css);
2263 struct task_struct *p;
2266 p = rcu_dereference(mm->owner);
2268 * Because we don't have task_lock(), "p" can exit.
2269 * In that case, "memcg" can point to root or p can be NULL with
2270 * race with swapoff. Then, we have small risk of mis-accouning.
2271 * But such kind of mis-account by race always happens because
2272 * we don't have cgroup_mutex(). It's overkill and we allo that
2274 * (*) swapoff at el will charge against mm-struct not against
2275 * task-struct. So, mm->owner can be NULL.
2277 memcg = mem_cgroup_from_task(p);
2278 if (!memcg || mem_cgroup_is_root(memcg)) {
2282 if (nr_pages == 1 && consume_stock(memcg)) {
2284 * It seems dagerous to access memcg without css_get().
2285 * But considering how consume_stok works, it's not
2286 * necessary. If consume_stock success, some charges
2287 * from this memcg are cached on this cpu. So, we
2288 * don't need to call css_get()/css_tryget() before
2289 * calling consume_stock().
2294 /* after here, we may be blocked. we need to get refcnt */
2295 if (!css_tryget(&memcg->css)) {
2305 /* If killed, bypass charge */
2306 if (fatal_signal_pending(current)) {
2307 css_put(&memcg->css);
2312 if (oom && !nr_oom_retries) {
2314 nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2317 ret = mem_cgroup_do_charge(memcg, gfp_mask, batch, oom_check);
2321 case CHARGE_RETRY: /* not in OOM situation but retry */
2323 css_put(&memcg->css);
2326 case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
2327 css_put(&memcg->css);
2329 case CHARGE_NOMEM: /* OOM routine works */
2331 css_put(&memcg->css);
2334 /* If oom, we never return -ENOMEM */
2337 case CHARGE_OOM_DIE: /* Killed by OOM Killer */
2338 css_put(&memcg->css);
2341 } while (ret != CHARGE_OK);
2343 if (batch > nr_pages)
2344 refill_stock(memcg, batch - nr_pages);
2345 css_put(&memcg->css);
2358 * Somemtimes we have to undo a charge we got by try_charge().
2359 * This function is for that and do uncharge, put css's refcnt.
2360 * gotten by try_charge().
2362 static void __mem_cgroup_cancel_charge(struct mem_cgroup *memcg,
2363 unsigned int nr_pages)
2365 if (!mem_cgroup_is_root(memcg)) {
2366 unsigned long bytes = nr_pages * PAGE_SIZE;
2368 res_counter_uncharge(&memcg->res, bytes);
2369 if (do_swap_account)
2370 res_counter_uncharge(&memcg->memsw, bytes);
2375 * A helper function to get mem_cgroup from ID. must be called under
2376 * rcu_read_lock(). The caller must check css_is_removed() or some if
2377 * it's concern. (dropping refcnt from swap can be called against removed
2380 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
2382 struct cgroup_subsys_state *css;
2384 /* ID 0 is unused ID */
2387 css = css_lookup(&mem_cgroup_subsys, id);
2390 return container_of(css, struct mem_cgroup, css);
2393 struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
2395 struct mem_cgroup *memcg = NULL;
2396 struct page_cgroup *pc;
2400 VM_BUG_ON(!PageLocked(page));
2402 pc = lookup_page_cgroup(page);
2403 lock_page_cgroup(pc);
2404 if (PageCgroupUsed(pc)) {
2405 memcg = pc->mem_cgroup;
2406 if (memcg && !css_tryget(&memcg->css))
2408 } else if (PageSwapCache(page)) {
2409 ent.val = page_private(page);
2410 id = lookup_swap_cgroup(ent);
2412 memcg = mem_cgroup_lookup(id);
2413 if (memcg && !css_tryget(&memcg->css))
2417 unlock_page_cgroup(pc);
2421 static void __mem_cgroup_commit_charge(struct mem_cgroup *memcg,
2423 unsigned int nr_pages,
2424 struct page_cgroup *pc,
2425 enum charge_type ctype)
2427 lock_page_cgroup(pc);
2428 if (unlikely(PageCgroupUsed(pc))) {
2429 unlock_page_cgroup(pc);
2430 __mem_cgroup_cancel_charge(memcg, nr_pages);
2434 * we don't need page_cgroup_lock about tail pages, becase they are not
2435 * accessed by any other context at this point.
2437 pc->mem_cgroup = memcg;
2439 * We access a page_cgroup asynchronously without lock_page_cgroup().
2440 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
2441 * is accessed after testing USED bit. To make pc->mem_cgroup visible
2442 * before USED bit, we need memory barrier here.
2443 * See mem_cgroup_add_lru_list(), etc.
2447 case MEM_CGROUP_CHARGE_TYPE_CACHE:
2448 case MEM_CGROUP_CHARGE_TYPE_SHMEM:
2449 SetPageCgroupCache(pc);
2450 SetPageCgroupUsed(pc);
2452 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
2453 ClearPageCgroupCache(pc);
2454 SetPageCgroupUsed(pc);
2460 mem_cgroup_charge_statistics(memcg, PageCgroupCache(pc), nr_pages);
2461 unlock_page_cgroup(pc);
2463 * "charge_statistics" updated event counter. Then, check it.
2464 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
2465 * if they exceeds softlimit.
2467 memcg_check_events(memcg, page);
2470 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2472 #define PCGF_NOCOPY_AT_SPLIT ((1 << PCG_LOCK) | (1 << PCG_MOVE_LOCK) |\
2473 (1 << PCG_ACCT_LRU) | (1 << PCG_MIGRATION))
2475 * Because tail pages are not marked as "used", set it. We're under
2476 * zone->lru_lock, 'splitting on pmd' and compund_lock.
2478 void mem_cgroup_split_huge_fixup(struct page *head, struct page *tail)
2480 struct page_cgroup *head_pc = lookup_page_cgroup(head);
2481 struct page_cgroup *tail_pc = lookup_page_cgroup(tail);
2482 unsigned long flags;
2484 if (mem_cgroup_disabled())
2487 * We have no races with charge/uncharge but will have races with
2488 * page state accounting.
2490 move_lock_page_cgroup(head_pc, &flags);
2492 tail_pc->mem_cgroup = head_pc->mem_cgroup;
2493 smp_wmb(); /* see __commit_charge() */
2494 if (PageCgroupAcctLRU(head_pc)) {
2496 struct mem_cgroup_per_zone *mz;
2499 * LRU flags cannot be copied because we need to add tail
2500 *.page to LRU by generic call and our hook will be called.
2501 * We hold lru_lock, then, reduce counter directly.
2503 lru = page_lru(head);
2504 mz = page_cgroup_zoneinfo(head_pc->mem_cgroup, head);
2505 MEM_CGROUP_ZSTAT(mz, lru) -= 1;
2507 tail_pc->flags = head_pc->flags & ~PCGF_NOCOPY_AT_SPLIT;
2508 move_unlock_page_cgroup(head_pc, &flags);
2513 * mem_cgroup_move_account - move account of the page
2515 * @nr_pages: number of regular pages (>1 for huge pages)
2516 * @pc: page_cgroup of the page.
2517 * @from: mem_cgroup which the page is moved from.
2518 * @to: mem_cgroup which the page is moved to. @from != @to.
2519 * @uncharge: whether we should call uncharge and css_put against @from.
2521 * The caller must confirm following.
2522 * - page is not on LRU (isolate_page() is useful.)
2523 * - compound_lock is held when nr_pages > 1
2525 * This function doesn't do "charge" nor css_get to new cgroup. It should be
2526 * done by a caller(__mem_cgroup_try_charge would be useful). If @uncharge is
2527 * true, this function does "uncharge" from old cgroup, but it doesn't if
2528 * @uncharge is false, so a caller should do "uncharge".
2530 static int mem_cgroup_move_account(struct page *page,
2531 unsigned int nr_pages,
2532 struct page_cgroup *pc,
2533 struct mem_cgroup *from,
2534 struct mem_cgroup *to,
2537 unsigned long flags;
2540 VM_BUG_ON(from == to);
2541 VM_BUG_ON(PageLRU(page));
2543 * The page is isolated from LRU. So, collapse function
2544 * will not handle this page. But page splitting can happen.
2545 * Do this check under compound_page_lock(). The caller should
2549 if (nr_pages > 1 && !PageTransHuge(page))
2552 lock_page_cgroup(pc);
2555 if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
2558 move_lock_page_cgroup(pc, &flags);
2560 if (PageCgroupFileMapped(pc)) {
2561 /* Update mapped_file data for mem_cgroup */
2563 __this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2564 __this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2567 mem_cgroup_charge_statistics(from, PageCgroupCache(pc), -nr_pages);
2569 /* This is not "cancel", but cancel_charge does all we need. */
2570 __mem_cgroup_cancel_charge(from, nr_pages);
2572 /* caller should have done css_get */
2573 pc->mem_cgroup = to;
2574 mem_cgroup_charge_statistics(to, PageCgroupCache(pc), nr_pages);
2576 * We charges against "to" which may not have any tasks. Then, "to"
2577 * can be under rmdir(). But in current implementation, caller of
2578 * this function is just force_empty() and move charge, so it's
2579 * guaranteed that "to" is never removed. So, we don't check rmdir
2582 move_unlock_page_cgroup(pc, &flags);
2585 unlock_page_cgroup(pc);
2589 memcg_check_events(to, page);
2590 memcg_check_events(from, page);
2596 * move charges to its parent.
2599 static int mem_cgroup_move_parent(struct page *page,
2600 struct page_cgroup *pc,
2601 struct mem_cgroup *child,
2604 struct cgroup *cg = child->css.cgroup;
2605 struct cgroup *pcg = cg->parent;
2606 struct mem_cgroup *parent;
2607 unsigned int nr_pages;
2608 unsigned long uninitialized_var(flags);
2616 if (!get_page_unless_zero(page))
2618 if (isolate_lru_page(page))
2621 nr_pages = hpage_nr_pages(page);
2623 parent = mem_cgroup_from_cont(pcg);
2624 ret = __mem_cgroup_try_charge(NULL, gfp_mask, nr_pages, &parent, false);
2629 flags = compound_lock_irqsave(page);
2631 ret = mem_cgroup_move_account(page, nr_pages, pc, child, parent, true);
2633 __mem_cgroup_cancel_charge(parent, nr_pages);
2636 compound_unlock_irqrestore(page, flags);
2638 putback_lru_page(page);
2646 * Charge the memory controller for page usage.
2648 * 0 if the charge was successful
2649 * < 0 if the cgroup is over its limit
2651 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
2652 gfp_t gfp_mask, enum charge_type ctype)
2654 struct mem_cgroup *memcg = NULL;
2655 unsigned int nr_pages = 1;
2656 struct page_cgroup *pc;
2660 if (PageTransHuge(page)) {
2661 nr_pages <<= compound_order(page);
2662 VM_BUG_ON(!PageTransHuge(page));
2664 * Never OOM-kill a process for a huge page. The
2665 * fault handler will fall back to regular pages.
2670 pc = lookup_page_cgroup(page);
2671 BUG_ON(!pc); /* XXX: remove this and move pc lookup into commit */
2673 ret = __mem_cgroup_try_charge(mm, gfp_mask, nr_pages, &memcg, oom);
2677 __mem_cgroup_commit_charge(memcg, page, nr_pages, pc, ctype);
2681 int mem_cgroup_newpage_charge(struct page *page,
2682 struct mm_struct *mm, gfp_t gfp_mask)
2684 if (mem_cgroup_disabled())
2687 * If already mapped, we don't have to account.
2688 * If page cache, page->mapping has address_space.
2689 * But page->mapping may have out-of-use anon_vma pointer,
2690 * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
2693 if (page_mapped(page) || (page->mapping && !PageAnon(page)))
2697 return mem_cgroup_charge_common(page, mm, gfp_mask,
2698 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2702 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2703 enum charge_type ctype);
2706 __mem_cgroup_commit_charge_lrucare(struct page *page, struct mem_cgroup *memcg,
2707 enum charge_type ctype)
2709 struct page_cgroup *pc = lookup_page_cgroup(page);
2711 * In some case, SwapCache, FUSE(splice_buf->radixtree), the page
2712 * is already on LRU. It means the page may on some other page_cgroup's
2713 * LRU. Take care of it.
2715 mem_cgroup_lru_del_before_commit(page);
2716 __mem_cgroup_commit_charge(memcg, page, 1, pc, ctype);
2717 mem_cgroup_lru_add_after_commit(page);
2721 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
2724 struct mem_cgroup *memcg = NULL;
2727 if (mem_cgroup_disabled())
2729 if (PageCompound(page))
2735 if (page_is_file_cache(page)) {
2736 ret = __mem_cgroup_try_charge(mm, gfp_mask, 1, &memcg, true);
2741 * FUSE reuses pages without going through the final
2742 * put that would remove them from the LRU list, make
2743 * sure that they get relinked properly.
2745 __mem_cgroup_commit_charge_lrucare(page, memcg,
2746 MEM_CGROUP_CHARGE_TYPE_CACHE);
2750 if (PageSwapCache(page)) {
2751 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &memcg);
2753 __mem_cgroup_commit_charge_swapin(page, memcg,
2754 MEM_CGROUP_CHARGE_TYPE_SHMEM);
2756 ret = mem_cgroup_charge_common(page, mm, gfp_mask,
2757 MEM_CGROUP_CHARGE_TYPE_SHMEM);
2763 * While swap-in, try_charge -> commit or cancel, the page is locked.
2764 * And when try_charge() successfully returns, one refcnt to memcg without
2765 * struct page_cgroup is acquired. This refcnt will be consumed by
2766 * "commit()" or removed by "cancel()"
2768 int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
2770 gfp_t mask, struct mem_cgroup **ptr)
2772 struct mem_cgroup *memcg;
2777 if (mem_cgroup_disabled())
2780 if (!do_swap_account)
2783 * A racing thread's fault, or swapoff, may have already updated
2784 * the pte, and even removed page from swap cache: in those cases
2785 * do_swap_page()'s pte_same() test will fail; but there's also a
2786 * KSM case which does need to charge the page.
2788 if (!PageSwapCache(page))
2790 memcg = try_get_mem_cgroup_from_page(page);
2794 ret = __mem_cgroup_try_charge(NULL, mask, 1, ptr, true);
2795 css_put(&memcg->css);
2800 return __mem_cgroup_try_charge(mm, mask, 1, ptr, true);
2804 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2805 enum charge_type ctype)
2807 if (mem_cgroup_disabled())
2811 cgroup_exclude_rmdir(&ptr->css);
2813 __mem_cgroup_commit_charge_lrucare(page, ptr, ctype);
2815 * Now swap is on-memory. This means this page may be
2816 * counted both as mem and swap....double count.
2817 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
2818 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
2819 * may call delete_from_swap_cache() before reach here.
2821 if (do_swap_account && PageSwapCache(page)) {
2822 swp_entry_t ent = {.val = page_private(page)};
2824 struct mem_cgroup *memcg;
2826 id = swap_cgroup_record(ent, 0);
2828 memcg = mem_cgroup_lookup(id);
2831 * This recorded memcg can be obsolete one. So, avoid
2832 * calling css_tryget
2834 if (!mem_cgroup_is_root(memcg))
2835 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
2836 mem_cgroup_swap_statistics(memcg, false);
2837 mem_cgroup_put(memcg);
2842 * At swapin, we may charge account against cgroup which has no tasks.
2843 * So, rmdir()->pre_destroy() can be called while we do this charge.
2844 * In that case, we need to call pre_destroy() again. check it here.
2846 cgroup_release_and_wakeup_rmdir(&ptr->css);
2849 void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
2851 __mem_cgroup_commit_charge_swapin(page, ptr,
2852 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2855 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *memcg)
2857 if (mem_cgroup_disabled())
2861 __mem_cgroup_cancel_charge(memcg, 1);
2864 static void mem_cgroup_do_uncharge(struct mem_cgroup *memcg,
2865 unsigned int nr_pages,
2866 const enum charge_type ctype)
2868 struct memcg_batch_info *batch = NULL;
2869 bool uncharge_memsw = true;
2871 /* If swapout, usage of swap doesn't decrease */
2872 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2873 uncharge_memsw = false;
2875 batch = ¤t->memcg_batch;
2877 * In usual, we do css_get() when we remember memcg pointer.
2878 * But in this case, we keep res->usage until end of a series of
2879 * uncharges. Then, it's ok to ignore memcg's refcnt.
2882 batch->memcg = memcg;
2884 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
2885 * In those cases, all pages freed continuously can be expected to be in
2886 * the same cgroup and we have chance to coalesce uncharges.
2887 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
2888 * because we want to do uncharge as soon as possible.
2891 if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
2892 goto direct_uncharge;
2895 goto direct_uncharge;
2898 * In typical case, batch->memcg == mem. This means we can
2899 * merge a series of uncharges to an uncharge of res_counter.
2900 * If not, we uncharge res_counter ony by one.
2902 if (batch->memcg != memcg)
2903 goto direct_uncharge;
2904 /* remember freed charge and uncharge it later */
2907 batch->memsw_nr_pages++;
2910 res_counter_uncharge(&memcg->res, nr_pages * PAGE_SIZE);
2912 res_counter_uncharge(&memcg->memsw, nr_pages * PAGE_SIZE);
2913 if (unlikely(batch->memcg != memcg))
2914 memcg_oom_recover(memcg);
2919 * uncharge if !page_mapped(page)
2921 static struct mem_cgroup *
2922 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
2924 struct mem_cgroup *memcg = NULL;
2925 unsigned int nr_pages = 1;
2926 struct page_cgroup *pc;
2928 if (mem_cgroup_disabled())
2931 if (PageSwapCache(page))
2934 if (PageTransHuge(page)) {
2935 nr_pages <<= compound_order(page);
2936 VM_BUG_ON(!PageTransHuge(page));
2939 * Check if our page_cgroup is valid
2941 pc = lookup_page_cgroup(page);
2942 if (unlikely(!pc || !PageCgroupUsed(pc)))
2945 lock_page_cgroup(pc);
2947 memcg = pc->mem_cgroup;
2949 if (!PageCgroupUsed(pc))
2953 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
2954 case MEM_CGROUP_CHARGE_TYPE_DROP:
2955 /* See mem_cgroup_prepare_migration() */
2956 if (page_mapped(page) || PageCgroupMigration(pc))
2959 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
2960 if (!PageAnon(page)) { /* Shared memory */
2961 if (page->mapping && !page_is_file_cache(page))
2963 } else if (page_mapped(page)) /* Anon */
2970 mem_cgroup_charge_statistics(memcg, PageCgroupCache(pc), -nr_pages);
2972 ClearPageCgroupUsed(pc);
2974 * pc->mem_cgroup is not cleared here. It will be accessed when it's
2975 * freed from LRU. This is safe because uncharged page is expected not
2976 * to be reused (freed soon). Exception is SwapCache, it's handled by
2977 * special functions.
2980 unlock_page_cgroup(pc);
2982 * even after unlock, we have memcg->res.usage here and this memcg
2983 * will never be freed.
2985 memcg_check_events(memcg, page);
2986 if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
2987 mem_cgroup_swap_statistics(memcg, true);
2988 mem_cgroup_get(memcg);
2990 if (!mem_cgroup_is_root(memcg))
2991 mem_cgroup_do_uncharge(memcg, nr_pages, ctype);
2996 unlock_page_cgroup(pc);
3000 void mem_cgroup_uncharge_page(struct page *page)
3003 if (page_mapped(page))
3005 if (page->mapping && !PageAnon(page))
3007 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
3010 void mem_cgroup_uncharge_cache_page(struct page *page)
3012 VM_BUG_ON(page_mapped(page));
3013 VM_BUG_ON(page->mapping);
3014 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
3018 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
3019 * In that cases, pages are freed continuously and we can expect pages
3020 * are in the same memcg. All these calls itself limits the number of
3021 * pages freed at once, then uncharge_start/end() is called properly.
3022 * This may be called prural(2) times in a context,
3025 void mem_cgroup_uncharge_start(void)
3027 current->memcg_batch.do_batch++;
3028 /* We can do nest. */
3029 if (current->memcg_batch.do_batch == 1) {
3030 current->memcg_batch.memcg = NULL;
3031 current->memcg_batch.nr_pages = 0;
3032 current->memcg_batch.memsw_nr_pages = 0;
3036 void mem_cgroup_uncharge_end(void)
3038 struct memcg_batch_info *batch = ¤t->memcg_batch;
3040 if (!batch->do_batch)
3044 if (batch->do_batch) /* If stacked, do nothing. */
3050 * This "batch->memcg" is valid without any css_get/put etc...
3051 * bacause we hide charges behind us.
3053 if (batch->nr_pages)
3054 res_counter_uncharge(&batch->memcg->res,
3055 batch->nr_pages * PAGE_SIZE);
3056 if (batch->memsw_nr_pages)
3057 res_counter_uncharge(&batch->memcg->memsw,
3058 batch->memsw_nr_pages * PAGE_SIZE);
3059 memcg_oom_recover(batch->memcg);
3060 /* forget this pointer (for sanity check) */
3061 batch->memcg = NULL;
3066 * called after __delete_from_swap_cache() and drop "page" account.
3067 * memcg information is recorded to swap_cgroup of "ent"
3070 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
3072 struct mem_cgroup *memcg;
3073 int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
3075 if (!swapout) /* this was a swap cache but the swap is unused ! */
3076 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
3078 memcg = __mem_cgroup_uncharge_common(page, ctype);
3081 * record memcg information, if swapout && memcg != NULL,
3082 * mem_cgroup_get() was called in uncharge().
3084 if (do_swap_account && swapout && memcg)
3085 swap_cgroup_record(ent, css_id(&memcg->css));
3089 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3091 * called from swap_entry_free(). remove record in swap_cgroup and
3092 * uncharge "memsw" account.
3094 void mem_cgroup_uncharge_swap(swp_entry_t ent)
3096 struct mem_cgroup *memcg;
3099 if (!do_swap_account)
3102 id = swap_cgroup_record(ent, 0);
3104 memcg = mem_cgroup_lookup(id);
3107 * We uncharge this because swap is freed.
3108 * This memcg can be obsolete one. We avoid calling css_tryget
3110 if (!mem_cgroup_is_root(memcg))
3111 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
3112 mem_cgroup_swap_statistics(memcg, false);
3113 mem_cgroup_put(memcg);
3119 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3120 * @entry: swap entry to be moved
3121 * @from: mem_cgroup which the entry is moved from
3122 * @to: mem_cgroup which the entry is moved to
3123 * @need_fixup: whether we should fixup res_counters and refcounts.
3125 * It succeeds only when the swap_cgroup's record for this entry is the same
3126 * as the mem_cgroup's id of @from.
3128 * Returns 0 on success, -EINVAL on failure.
3130 * The caller must have charged to @to, IOW, called res_counter_charge() about
3131 * both res and memsw, and called css_get().
3133 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3134 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
3136 unsigned short old_id, new_id;
3138 old_id = css_id(&from->css);
3139 new_id = css_id(&to->css);
3141 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3142 mem_cgroup_swap_statistics(from, false);
3143 mem_cgroup_swap_statistics(to, true);
3145 * This function is only called from task migration context now.
3146 * It postpones res_counter and refcount handling till the end
3147 * of task migration(mem_cgroup_clear_mc()) for performance
3148 * improvement. But we cannot postpone mem_cgroup_get(to)
3149 * because if the process that has been moved to @to does
3150 * swap-in, the refcount of @to might be decreased to 0.
3154 if (!mem_cgroup_is_root(from))
3155 res_counter_uncharge(&from->memsw, PAGE_SIZE);
3156 mem_cgroup_put(from);
3158 * we charged both to->res and to->memsw, so we should
3161 if (!mem_cgroup_is_root(to))
3162 res_counter_uncharge(&to->res, PAGE_SIZE);
3169 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3170 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
3177 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
3180 int mem_cgroup_prepare_migration(struct page *page,
3181 struct page *newpage, struct mem_cgroup **ptr, gfp_t gfp_mask)
3183 struct mem_cgroup *memcg = NULL;
3184 struct page_cgroup *pc;
3185 enum charge_type ctype;
3190 VM_BUG_ON(PageTransHuge(page));
3191 if (mem_cgroup_disabled())
3194 pc = lookup_page_cgroup(page);
3195 lock_page_cgroup(pc);
3196 if (PageCgroupUsed(pc)) {
3197 memcg = pc->mem_cgroup;
3198 css_get(&memcg->css);
3200 * At migrating an anonymous page, its mapcount goes down
3201 * to 0 and uncharge() will be called. But, even if it's fully
3202 * unmapped, migration may fail and this page has to be
3203 * charged again. We set MIGRATION flag here and delay uncharge
3204 * until end_migration() is called
3206 * Corner Case Thinking
3208 * When the old page was mapped as Anon and it's unmap-and-freed
3209 * while migration was ongoing.
3210 * If unmap finds the old page, uncharge() of it will be delayed
3211 * until end_migration(). If unmap finds a new page, it's
3212 * uncharged when it make mapcount to be 1->0. If unmap code
3213 * finds swap_migration_entry, the new page will not be mapped
3214 * and end_migration() will find it(mapcount==0).
3217 * When the old page was mapped but migraion fails, the kernel
3218 * remaps it. A charge for it is kept by MIGRATION flag even
3219 * if mapcount goes down to 0. We can do remap successfully
3220 * without charging it again.
3223 * The "old" page is under lock_page() until the end of
3224 * migration, so, the old page itself will not be swapped-out.
3225 * If the new page is swapped out before end_migraton, our
3226 * hook to usual swap-out path will catch the event.
3229 SetPageCgroupMigration(pc);
3231 unlock_page_cgroup(pc);
3233 * If the page is not charged at this point,
3240 ret = __mem_cgroup_try_charge(NULL, gfp_mask, 1, ptr, false);
3241 css_put(&memcg->css);/* drop extra refcnt */
3242 if (ret || *ptr == NULL) {
3243 if (PageAnon(page)) {
3244 lock_page_cgroup(pc);
3245 ClearPageCgroupMigration(pc);
3246 unlock_page_cgroup(pc);
3248 * The old page may be fully unmapped while we kept it.
3250 mem_cgroup_uncharge_page(page);
3255 * We charge new page before it's used/mapped. So, even if unlock_page()
3256 * is called before end_migration, we can catch all events on this new
3257 * page. In the case new page is migrated but not remapped, new page's
3258 * mapcount will be finally 0 and we call uncharge in end_migration().
3260 pc = lookup_page_cgroup(newpage);
3262 ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
3263 else if (page_is_file_cache(page))
3264 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
3266 ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
3267 __mem_cgroup_commit_charge(memcg, page, 1, pc, ctype);
3271 /* remove redundant charge if migration failed*/
3272 void mem_cgroup_end_migration(struct mem_cgroup *memcg,
3273 struct page *oldpage, struct page *newpage, bool migration_ok)
3275 struct page *used, *unused;
3276 struct page_cgroup *pc;
3280 /* blocks rmdir() */
3281 cgroup_exclude_rmdir(&memcg->css);
3282 if (!migration_ok) {
3290 * We disallowed uncharge of pages under migration because mapcount
3291 * of the page goes down to zero, temporarly.
3292 * Clear the flag and check the page should be charged.
3294 pc = lookup_page_cgroup(oldpage);
3295 lock_page_cgroup(pc);
3296 ClearPageCgroupMigration(pc);
3297 unlock_page_cgroup(pc);
3299 __mem_cgroup_uncharge_common(unused, MEM_CGROUP_CHARGE_TYPE_FORCE);
3302 * If a page is a file cache, radix-tree replacement is very atomic
3303 * and we can skip this check. When it was an Anon page, its mapcount
3304 * goes down to 0. But because we added MIGRATION flage, it's not
3305 * uncharged yet. There are several case but page->mapcount check
3306 * and USED bit check in mem_cgroup_uncharge_page() will do enough
3307 * check. (see prepare_charge() also)
3310 mem_cgroup_uncharge_page(used);
3312 * At migration, we may charge account against cgroup which has no
3314 * So, rmdir()->pre_destroy() can be called while we do this charge.
3315 * In that case, we need to call pre_destroy() again. check it here.
3317 cgroup_release_and_wakeup_rmdir(&memcg->css);
3320 #ifdef CONFIG_DEBUG_VM
3321 static struct page_cgroup *lookup_page_cgroup_used(struct page *page)
3323 struct page_cgroup *pc;
3325 pc = lookup_page_cgroup(page);
3326 if (likely(pc) && PageCgroupUsed(pc))
3331 bool mem_cgroup_bad_page_check(struct page *page)
3333 if (mem_cgroup_disabled())
3336 return lookup_page_cgroup_used(page) != NULL;
3339 void mem_cgroup_print_bad_page(struct page *page)
3341 struct page_cgroup *pc;
3343 pc = lookup_page_cgroup_used(page);
3348 printk(KERN_ALERT "pc:%p pc->flags:%lx pc->mem_cgroup:%p",
3349 pc, pc->flags, pc->mem_cgroup);
3351 path = kmalloc(PATH_MAX, GFP_KERNEL);
3354 ret = cgroup_path(pc->mem_cgroup->css.cgroup,
3359 printk(KERN_CONT "(%s)\n",
3360 (ret < 0) ? "cannot get the path" : path);
3366 static DEFINE_MUTEX(set_limit_mutex);
3368 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
3369 unsigned long long val)
3372 u64 memswlimit, memlimit;
3374 int children = mem_cgroup_count_children(memcg);
3375 u64 curusage, oldusage;
3379 * For keeping hierarchical_reclaim simple, how long we should retry
3380 * is depends on callers. We set our retry-count to be function
3381 * of # of children which we should visit in this loop.
3383 retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
3385 oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
3388 while (retry_count) {
3389 if (signal_pending(current)) {
3394 * Rather than hide all in some function, I do this in
3395 * open coded manner. You see what this really does.
3396 * We have to guarantee memcg->res.limit < memcg->memsw.limit.
3398 mutex_lock(&set_limit_mutex);
3399 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3400 if (memswlimit < val) {
3402 mutex_unlock(&set_limit_mutex);
3406 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3410 ret = res_counter_set_limit(&memcg->res, val);
3412 if (memswlimit == val)
3413 memcg->memsw_is_minimum = true;
3415 memcg->memsw_is_minimum = false;
3417 mutex_unlock(&set_limit_mutex);
3422 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
3423 MEM_CGROUP_RECLAIM_SHRINK,
3425 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
3426 /* Usage is reduced ? */
3427 if (curusage >= oldusage)
3430 oldusage = curusage;
3432 if (!ret && enlarge)
3433 memcg_oom_recover(memcg);
3438 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
3439 unsigned long long val)
3442 u64 memlimit, memswlimit, oldusage, curusage;
3443 int children = mem_cgroup_count_children(memcg);
3447 /* see mem_cgroup_resize_res_limit */
3448 retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
3449 oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
3450 while (retry_count) {
3451 if (signal_pending(current)) {
3456 * Rather than hide all in some function, I do this in
3457 * open coded manner. You see what this really does.
3458 * We have to guarantee memcg->res.limit < memcg->memsw.limit.
3460 mutex_lock(&set_limit_mutex);
3461 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3462 if (memlimit > val) {
3464 mutex_unlock(&set_limit_mutex);
3467 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3468 if (memswlimit < val)
3470 ret = res_counter_set_limit(&memcg->memsw, val);
3472 if (memlimit == val)
3473 memcg->memsw_is_minimum = true;
3475 memcg->memsw_is_minimum = false;
3477 mutex_unlock(&set_limit_mutex);
3482 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
3483 MEM_CGROUP_RECLAIM_NOSWAP |
3484 MEM_CGROUP_RECLAIM_SHRINK,
3486 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
3487 /* Usage is reduced ? */
3488 if (curusage >= oldusage)
3491 oldusage = curusage;
3493 if (!ret && enlarge)
3494 memcg_oom_recover(memcg);
3498 unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
3500 unsigned long *total_scanned)
3502 unsigned long nr_reclaimed = 0;
3503 struct mem_cgroup_per_zone *mz, *next_mz = NULL;
3504 unsigned long reclaimed;
3506 struct mem_cgroup_tree_per_zone *mctz;
3507 unsigned long long excess;
3508 unsigned long nr_scanned;
3513 mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
3515 * This loop can run a while, specially if mem_cgroup's continuously
3516 * keep exceeding their soft limit and putting the system under
3523 mz = mem_cgroup_largest_soft_limit_node(mctz);
3528 reclaimed = mem_cgroup_hierarchical_reclaim(mz->mem, zone,
3530 MEM_CGROUP_RECLAIM_SOFT,
3532 nr_reclaimed += reclaimed;
3533 *total_scanned += nr_scanned;
3534 spin_lock(&mctz->lock);
3537 * If we failed to reclaim anything from this memory cgroup
3538 * it is time to move on to the next cgroup
3544 * Loop until we find yet another one.
3546 * By the time we get the soft_limit lock
3547 * again, someone might have aded the
3548 * group back on the RB tree. Iterate to
3549 * make sure we get a different mem.
3550 * mem_cgroup_largest_soft_limit_node returns
3551 * NULL if no other cgroup is present on
3555 __mem_cgroup_largest_soft_limit_node(mctz);
3557 css_put(&next_mz->mem->css);
3558 else /* next_mz == NULL or other memcg */
3562 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
3563 excess = res_counter_soft_limit_excess(&mz->mem->res);
3565 * One school of thought says that we should not add
3566 * back the node to the tree if reclaim returns 0.
3567 * But our reclaim could return 0, simply because due
3568 * to priority we are exposing a smaller subset of
3569 * memory to reclaim from. Consider this as a longer
3572 /* If excess == 0, no tree ops */
3573 __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
3574 spin_unlock(&mctz->lock);
3575 css_put(&mz->mem->css);
3578 * Could not reclaim anything and there are no more
3579 * mem cgroups to try or we seem to be looping without
3580 * reclaiming anything.
3582 if (!nr_reclaimed &&
3584 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3586 } while (!nr_reclaimed);
3588 css_put(&next_mz->mem->css);
3589 return nr_reclaimed;
3593 * This routine traverse page_cgroup in given list and drop them all.
3594 * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
3596 static int mem_cgroup_force_empty_list(struct mem_cgroup *memcg,
3597 int node, int zid, enum lru_list lru)
3600 struct mem_cgroup_per_zone *mz;
3601 struct page_cgroup *pc, *busy;
3602 unsigned long flags, loop;
3603 struct list_head *list;
3606 zone = &NODE_DATA(node)->node_zones[zid];
3607 mz = mem_cgroup_zoneinfo(memcg, node, zid);
3608 list = &mz->lists[lru];
3610 loop = MEM_CGROUP_ZSTAT(mz, lru);
3611 /* give some margin against EBUSY etc...*/
3618 spin_lock_irqsave(&zone->lru_lock, flags);
3619 if (list_empty(list)) {
3620 spin_unlock_irqrestore(&zone->lru_lock, flags);
3623 pc = list_entry(list->prev, struct page_cgroup, lru);
3625 list_move(&pc->lru, list);
3627 spin_unlock_irqrestore(&zone->lru_lock, flags);
3630 spin_unlock_irqrestore(&zone->lru_lock, flags);
3632 page = lookup_cgroup_page(pc);
3634 ret = mem_cgroup_move_parent(page, pc, memcg, GFP_KERNEL);
3638 if (ret == -EBUSY || ret == -EINVAL) {
3639 /* found lock contention or "pc" is obsolete. */
3646 if (!ret && !list_empty(list))
3652 * make mem_cgroup's charge to be 0 if there is no task.
3653 * This enables deleting this mem_cgroup.
3655 static int mem_cgroup_force_empty(struct mem_cgroup *memcg, bool free_all)
3658 int node, zid, shrink;
3659 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
3660 struct cgroup *cgrp = memcg->css.cgroup;
3662 css_get(&memcg->css);
3665 /* should free all ? */
3671 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
3674 if (signal_pending(current))
3676 /* This is for making all *used* pages to be on LRU. */
3677 lru_add_drain_all();
3678 drain_all_stock_sync(memcg);
3680 mem_cgroup_start_move(memcg);
3681 for_each_node_state(node, N_HIGH_MEMORY) {
3682 for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
3685 ret = mem_cgroup_force_empty_list(memcg,
3694 mem_cgroup_end_move(memcg);
3695 memcg_oom_recover(memcg);
3696 /* it seems parent cgroup doesn't have enough mem */
3700 /* "ret" should also be checked to ensure all lists are empty. */
3701 } while (memcg->res.usage > 0 || ret);
3703 css_put(&memcg->css);
3707 /* returns EBUSY if there is a task or if we come here twice. */
3708 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
3712 /* we call try-to-free pages for make this cgroup empty */
3713 lru_add_drain_all();
3714 /* try to free all pages in this cgroup */
3716 while (nr_retries && memcg->res.usage > 0) {
3719 if (signal_pending(current)) {
3723 progress = try_to_free_mem_cgroup_pages(memcg, GFP_KERNEL,
3727 /* maybe some writeback is necessary */
3728 congestion_wait(BLK_RW_ASYNC, HZ/10);
3733 /* try move_account...there may be some *locked* pages. */
3737 int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
3739 return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
3743 static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
3745 return mem_cgroup_from_cont(cont)->use_hierarchy;
3748 static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
3752 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3753 struct cgroup *parent = cont->parent;
3754 struct mem_cgroup *parent_memcg = NULL;
3757 parent_memcg = mem_cgroup_from_cont(parent);
3761 * If parent's use_hierarchy is set, we can't make any modifications
3762 * in the child subtrees. If it is unset, then the change can
3763 * occur, provided the current cgroup has no children.
3765 * For the root cgroup, parent_mem is NULL, we allow value to be
3766 * set if there are no children.
3768 if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
3769 (val == 1 || val == 0)) {
3770 if (list_empty(&cont->children))
3771 memcg->use_hierarchy = val;
3782 static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup *memcg,
3783 enum mem_cgroup_stat_index idx)
3785 struct mem_cgroup *iter;
3788 /* Per-cpu values can be negative, use a signed accumulator */
3789 for_each_mem_cgroup_tree(iter, memcg)
3790 val += mem_cgroup_read_stat(iter, idx);
3792 if (val < 0) /* race ? */
3797 static inline u64 mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3801 if (!mem_cgroup_is_root(memcg)) {
3803 return res_counter_read_u64(&memcg->res, RES_USAGE);
3805 return res_counter_read_u64(&memcg->memsw, RES_USAGE);
3808 val = mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_CACHE);
3809 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_RSS);
3812 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_SWAPOUT);
3814 return val << PAGE_SHIFT;
3817 static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
3819 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3823 type = MEMFILE_TYPE(cft->private);
3824 name = MEMFILE_ATTR(cft->private);
3827 if (name == RES_USAGE)
3828 val = mem_cgroup_usage(memcg, false);
3830 val = res_counter_read_u64(&memcg->res, name);
3833 if (name == RES_USAGE)
3834 val = mem_cgroup_usage(memcg, true);
3836 val = res_counter_read_u64(&memcg->memsw, name);
3845 * The user of this function is...
3848 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
3851 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3853 unsigned long long val;
3856 type = MEMFILE_TYPE(cft->private);
3857 name = MEMFILE_ATTR(cft->private);
3860 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3864 /* This function does all necessary parse...reuse it */
3865 ret = res_counter_memparse_write_strategy(buffer, &val);
3869 ret = mem_cgroup_resize_limit(memcg, val);
3871 ret = mem_cgroup_resize_memsw_limit(memcg, val);
3873 case RES_SOFT_LIMIT:
3874 ret = res_counter_memparse_write_strategy(buffer, &val);
3878 * For memsw, soft limits are hard to implement in terms
3879 * of semantics, for now, we support soft limits for
3880 * control without swap
3883 ret = res_counter_set_soft_limit(&memcg->res, val);
3888 ret = -EINVAL; /* should be BUG() ? */
3894 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
3895 unsigned long long *mem_limit, unsigned long long *memsw_limit)
3897 struct cgroup *cgroup;
3898 unsigned long long min_limit, min_memsw_limit, tmp;
3900 min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3901 min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3902 cgroup = memcg->css.cgroup;
3903 if (!memcg->use_hierarchy)
3906 while (cgroup->parent) {
3907 cgroup = cgroup->parent;
3908 memcg = mem_cgroup_from_cont(cgroup);
3909 if (!memcg->use_hierarchy)
3911 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
3912 min_limit = min(min_limit, tmp);
3913 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3914 min_memsw_limit = min(min_memsw_limit, tmp);
3917 *mem_limit = min_limit;
3918 *memsw_limit = min_memsw_limit;
3922 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
3924 struct mem_cgroup *memcg;
3927 memcg = mem_cgroup_from_cont(cont);
3928 type = MEMFILE_TYPE(event);
3929 name = MEMFILE_ATTR(event);
3933 res_counter_reset_max(&memcg->res);
3935 res_counter_reset_max(&memcg->memsw);
3939 res_counter_reset_failcnt(&memcg->res);
3941 res_counter_reset_failcnt(&memcg->memsw);
3948 static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
3951 return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
3955 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
3956 struct cftype *cft, u64 val)
3958 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3960 if (val >= (1 << NR_MOVE_TYPE))
3963 * We check this value several times in both in can_attach() and
3964 * attach(), so we need cgroup lock to prevent this value from being
3968 memcg->move_charge_at_immigrate = val;
3974 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
3975 struct cftype *cft, u64 val)
3982 /* For read statistics */
4000 struct mcs_total_stat {
4001 s64 stat[NR_MCS_STAT];
4007 } memcg_stat_strings[NR_MCS_STAT] = {
4008 {"cache", "total_cache"},
4009 {"rss", "total_rss"},
4010 {"mapped_file", "total_mapped_file"},
4011 {"pgpgin", "total_pgpgin"},
4012 {"pgpgout", "total_pgpgout"},
4013 {"swap", "total_swap"},
4014 {"pgfault", "total_pgfault"},
4015 {"pgmajfault", "total_pgmajfault"},
4016 {"inactive_anon", "total_inactive_anon"},
4017 {"active_anon", "total_active_anon"},
4018 {"inactive_file", "total_inactive_file"},
4019 {"active_file", "total_active_file"},
4020 {"unevictable", "total_unevictable"}
4025 mem_cgroup_get_local_stat(struct mem_cgroup *memcg, struct mcs_total_stat *s)
4030 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_CACHE);
4031 s->stat[MCS_CACHE] += val * PAGE_SIZE;
4032 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_RSS);
4033 s->stat[MCS_RSS] += val * PAGE_SIZE;
4034 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_FILE_MAPPED);
4035 s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE;
4036 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGPGIN);
4037 s->stat[MCS_PGPGIN] += val;
4038 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGPGOUT);
4039 s->stat[MCS_PGPGOUT] += val;
4040 if (do_swap_account) {
4041 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_SWAPOUT);
4042 s->stat[MCS_SWAP] += val * PAGE_SIZE;
4044 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGFAULT);
4045 s->stat[MCS_PGFAULT] += val;
4046 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGMAJFAULT);
4047 s->stat[MCS_PGMAJFAULT] += val;
4050 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_INACTIVE_ANON));
4051 s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
4052 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_ACTIVE_ANON));
4053 s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
4054 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_INACTIVE_FILE));
4055 s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
4056 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_ACTIVE_FILE));
4057 s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
4058 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_UNEVICTABLE));
4059 s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
4063 mem_cgroup_get_total_stat(struct mem_cgroup *memcg, struct mcs_total_stat *s)
4065 struct mem_cgroup *iter;
4067 for_each_mem_cgroup_tree(iter, memcg)
4068 mem_cgroup_get_local_stat(iter, s);
4072 static int mem_control_numa_stat_show(struct seq_file *m, void *arg)
4075 unsigned long total_nr, file_nr, anon_nr, unevictable_nr;
4076 unsigned long node_nr;
4077 struct cgroup *cont = m->private;
4078 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
4080 total_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL);
4081 seq_printf(m, "total=%lu", total_nr);
4082 for_each_node_state(nid, N_HIGH_MEMORY) {
4083 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid, LRU_ALL);
4084 seq_printf(m, " N%d=%lu", nid, node_nr);
4088 file_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_FILE);
4089 seq_printf(m, "file=%lu", file_nr);
4090 for_each_node_state(nid, N_HIGH_MEMORY) {
4091 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4093 seq_printf(m, " N%d=%lu", nid, node_nr);
4097 anon_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_ANON);
4098 seq_printf(m, "anon=%lu", anon_nr);
4099 for_each_node_state(nid, N_HIGH_MEMORY) {
4100 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4102 seq_printf(m, " N%d=%lu", nid, node_nr);
4106 unevictable_nr = mem_cgroup_nr_lru_pages(mem_cont, BIT(LRU_UNEVICTABLE));
4107 seq_printf(m, "unevictable=%lu", unevictable_nr);
4108 for_each_node_state(nid, N_HIGH_MEMORY) {
4109 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4110 BIT(LRU_UNEVICTABLE));
4111 seq_printf(m, " N%d=%lu", nid, node_nr);
4116 #endif /* CONFIG_NUMA */
4118 static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
4119 struct cgroup_map_cb *cb)
4121 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
4122 struct mcs_total_stat mystat;
4125 memset(&mystat, 0, sizeof(mystat));
4126 mem_cgroup_get_local_stat(mem_cont, &mystat);
4129 for (i = 0; i < NR_MCS_STAT; i++) {
4130 if (i == MCS_SWAP && !do_swap_account)
4132 cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
4135 /* Hierarchical information */
4137 unsigned long long limit, memsw_limit;
4138 memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
4139 cb->fill(cb, "hierarchical_memory_limit", limit);
4140 if (do_swap_account)
4141 cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
4144 memset(&mystat, 0, sizeof(mystat));
4145 mem_cgroup_get_total_stat(mem_cont, &mystat);
4146 for (i = 0; i < NR_MCS_STAT; i++) {
4147 if (i == MCS_SWAP && !do_swap_account)
4149 cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
4152 #ifdef CONFIG_DEBUG_VM
4155 struct mem_cgroup_per_zone *mz;
4156 unsigned long recent_rotated[2] = {0, 0};
4157 unsigned long recent_scanned[2] = {0, 0};
4159 for_each_online_node(nid)
4160 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
4161 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
4163 recent_rotated[0] +=
4164 mz->reclaim_stat.recent_rotated[0];
4165 recent_rotated[1] +=
4166 mz->reclaim_stat.recent_rotated[1];
4167 recent_scanned[0] +=
4168 mz->reclaim_stat.recent_scanned[0];
4169 recent_scanned[1] +=
4170 mz->reclaim_stat.recent_scanned[1];
4172 cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
4173 cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
4174 cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
4175 cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
4182 static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
4184 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4186 return mem_cgroup_swappiness(memcg);
4189 static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
4192 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4193 struct mem_cgroup *parent;
4198 if (cgrp->parent == NULL)
4201 parent = mem_cgroup_from_cont(cgrp->parent);
4205 /* If under hierarchy, only empty-root can set this value */
4206 if ((parent->use_hierarchy) ||
4207 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
4212 memcg->swappiness = val;
4219 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4221 struct mem_cgroup_threshold_ary *t;
4227 t = rcu_dereference(memcg->thresholds.primary);
4229 t = rcu_dereference(memcg->memsw_thresholds.primary);
4234 usage = mem_cgroup_usage(memcg, swap);
4237 * current_threshold points to threshold just below usage.
4238 * If it's not true, a threshold was crossed after last
4239 * call of __mem_cgroup_threshold().
4241 i = t->current_threshold;
4244 * Iterate backward over array of thresholds starting from
4245 * current_threshold and check if a threshold is crossed.
4246 * If none of thresholds below usage is crossed, we read
4247 * only one element of the array here.
4249 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4250 eventfd_signal(t->entries[i].eventfd, 1);
4252 /* i = current_threshold + 1 */
4256 * Iterate forward over array of thresholds starting from
4257 * current_threshold+1 and check if a threshold is crossed.
4258 * If none of thresholds above usage is crossed, we read
4259 * only one element of the array here.
4261 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4262 eventfd_signal(t->entries[i].eventfd, 1);
4264 /* Update current_threshold */
4265 t->current_threshold = i - 1;
4270 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4273 __mem_cgroup_threshold(memcg, false);
4274 if (do_swap_account)
4275 __mem_cgroup_threshold(memcg, true);
4277 memcg = parent_mem_cgroup(memcg);
4281 static int compare_thresholds(const void *a, const void *b)
4283 const struct mem_cgroup_threshold *_a = a;
4284 const struct mem_cgroup_threshold *_b = b;
4286 return _a->threshold - _b->threshold;
4289 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
4291 struct mem_cgroup_eventfd_list *ev;
4293 list_for_each_entry(ev, &memcg->oom_notify, list)
4294 eventfd_signal(ev->eventfd, 1);
4298 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
4300 struct mem_cgroup *iter;
4302 for_each_mem_cgroup_tree(iter, memcg)
4303 mem_cgroup_oom_notify_cb(iter);
4306 static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
4307 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4309 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4310 struct mem_cgroup_thresholds *thresholds;
4311 struct mem_cgroup_threshold_ary *new;
4312 int type = MEMFILE_TYPE(cft->private);
4313 u64 threshold, usage;
4316 ret = res_counter_memparse_write_strategy(args, &threshold);
4320 mutex_lock(&memcg->thresholds_lock);
4323 thresholds = &memcg->thresholds;
4324 else if (type == _MEMSWAP)
4325 thresholds = &memcg->memsw_thresholds;
4329 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4331 /* Check if a threshold crossed before adding a new one */
4332 if (thresholds->primary)
4333 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4335 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4337 /* Allocate memory for new array of thresholds */
4338 new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
4346 /* Copy thresholds (if any) to new array */
4347 if (thresholds->primary) {
4348 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
4349 sizeof(struct mem_cgroup_threshold));
4352 /* Add new threshold */
4353 new->entries[size - 1].eventfd = eventfd;
4354 new->entries[size - 1].threshold = threshold;
4356 /* Sort thresholds. Registering of new threshold isn't time-critical */
4357 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
4358 compare_thresholds, NULL);
4360 /* Find current threshold */
4361 new->current_threshold = -1;
4362 for (i = 0; i < size; i++) {
4363 if (new->entries[i].threshold < usage) {
4365 * new->current_threshold will not be used until
4366 * rcu_assign_pointer(), so it's safe to increment
4369 ++new->current_threshold;
4373 /* Free old spare buffer and save old primary buffer as spare */
4374 kfree(thresholds->spare);
4375 thresholds->spare = thresholds->primary;
4377 rcu_assign_pointer(thresholds->primary, new);
4379 /* To be sure that nobody uses thresholds */
4383 mutex_unlock(&memcg->thresholds_lock);
4388 static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
4389 struct cftype *cft, struct eventfd_ctx *eventfd)
4391 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4392 struct mem_cgroup_thresholds *thresholds;
4393 struct mem_cgroup_threshold_ary *new;
4394 int type = MEMFILE_TYPE(cft->private);
4398 mutex_lock(&memcg->thresholds_lock);
4400 thresholds = &memcg->thresholds;
4401 else if (type == _MEMSWAP)
4402 thresholds = &memcg->memsw_thresholds;
4407 * Something went wrong if we trying to unregister a threshold
4408 * if we don't have thresholds
4410 BUG_ON(!thresholds);
4412 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4414 /* Check if a threshold crossed before removing */
4415 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4417 /* Calculate new number of threshold */
4419 for (i = 0; i < thresholds->primary->size; i++) {
4420 if (thresholds->primary->entries[i].eventfd != eventfd)
4424 new = thresholds->spare;
4426 /* Set thresholds array to NULL if we don't have thresholds */
4435 /* Copy thresholds and find current threshold */
4436 new->current_threshold = -1;
4437 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4438 if (thresholds->primary->entries[i].eventfd == eventfd)
4441 new->entries[j] = thresholds->primary->entries[i];
4442 if (new->entries[j].threshold < usage) {
4444 * new->current_threshold will not be used
4445 * until rcu_assign_pointer(), so it's safe to increment
4448 ++new->current_threshold;
4454 /* Swap primary and spare array */
4455 thresholds->spare = thresholds->primary;
4456 rcu_assign_pointer(thresholds->primary, new);
4458 /* To be sure that nobody uses thresholds */
4461 mutex_unlock(&memcg->thresholds_lock);
4464 static int mem_cgroup_oom_register_event(struct cgroup *cgrp,
4465 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4467 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4468 struct mem_cgroup_eventfd_list *event;
4469 int type = MEMFILE_TYPE(cft->private);
4471 BUG_ON(type != _OOM_TYPE);
4472 event = kmalloc(sizeof(*event), GFP_KERNEL);
4476 spin_lock(&memcg_oom_lock);
4478 event->eventfd = eventfd;
4479 list_add(&event->list, &memcg->oom_notify);
4481 /* already in OOM ? */
4482 if (atomic_read(&memcg->under_oom))
4483 eventfd_signal(eventfd, 1);
4484 spin_unlock(&memcg_oom_lock);
4489 static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
4490 struct cftype *cft, struct eventfd_ctx *eventfd)
4492 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4493 struct mem_cgroup_eventfd_list *ev, *tmp;
4494 int type = MEMFILE_TYPE(cft->private);
4496 BUG_ON(type != _OOM_TYPE);
4498 spin_lock(&memcg_oom_lock);
4500 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
4501 if (ev->eventfd == eventfd) {
4502 list_del(&ev->list);
4507 spin_unlock(&memcg_oom_lock);
4510 static int mem_cgroup_oom_control_read(struct cgroup *cgrp,
4511 struct cftype *cft, struct cgroup_map_cb *cb)
4513 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4515 cb->fill(cb, "oom_kill_disable", memcg->oom_kill_disable);
4517 if (atomic_read(&memcg->under_oom))
4518 cb->fill(cb, "under_oom", 1);
4520 cb->fill(cb, "under_oom", 0);
4524 static int mem_cgroup_oom_control_write(struct cgroup *cgrp,
4525 struct cftype *cft, u64 val)
4527 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4528 struct mem_cgroup *parent;
4530 /* cannot set to root cgroup and only 0 and 1 are allowed */
4531 if (!cgrp->parent || !((val == 0) || (val == 1)))
4534 parent = mem_cgroup_from_cont(cgrp->parent);
4537 /* oom-kill-disable is a flag for subhierarchy. */
4538 if ((parent->use_hierarchy) ||
4539 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
4543 memcg->oom_kill_disable = val;
4545 memcg_oom_recover(memcg);
4551 static const struct file_operations mem_control_numa_stat_file_operations = {
4553 .llseek = seq_lseek,
4554 .release = single_release,
4557 static int mem_control_numa_stat_open(struct inode *unused, struct file *file)
4559 struct cgroup *cont = file->f_dentry->d_parent->d_fsdata;
4561 file->f_op = &mem_control_numa_stat_file_operations;
4562 return single_open(file, mem_control_numa_stat_show, cont);
4564 #endif /* CONFIG_NUMA */
4566 static struct cftype mem_cgroup_files[] = {
4568 .name = "usage_in_bytes",
4569 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
4570 .read_u64 = mem_cgroup_read,
4571 .register_event = mem_cgroup_usage_register_event,
4572 .unregister_event = mem_cgroup_usage_unregister_event,
4575 .name = "max_usage_in_bytes",
4576 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
4577 .trigger = mem_cgroup_reset,
4578 .read_u64 = mem_cgroup_read,
4581 .name = "limit_in_bytes",
4582 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
4583 .write_string = mem_cgroup_write,
4584 .read_u64 = mem_cgroup_read,
4587 .name = "soft_limit_in_bytes",
4588 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
4589 .write_string = mem_cgroup_write,
4590 .read_u64 = mem_cgroup_read,
4594 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
4595 .trigger = mem_cgroup_reset,
4596 .read_u64 = mem_cgroup_read,
4600 .read_map = mem_control_stat_show,
4603 .name = "force_empty",
4604 .trigger = mem_cgroup_force_empty_write,
4607 .name = "use_hierarchy",
4608 .write_u64 = mem_cgroup_hierarchy_write,
4609 .read_u64 = mem_cgroup_hierarchy_read,
4612 .name = "swappiness",
4613 .read_u64 = mem_cgroup_swappiness_read,
4614 .write_u64 = mem_cgroup_swappiness_write,
4617 .name = "move_charge_at_immigrate",
4618 .read_u64 = mem_cgroup_move_charge_read,
4619 .write_u64 = mem_cgroup_move_charge_write,
4622 .name = "oom_control",
4623 .read_map = mem_cgroup_oom_control_read,
4624 .write_u64 = mem_cgroup_oom_control_write,
4625 .register_event = mem_cgroup_oom_register_event,
4626 .unregister_event = mem_cgroup_oom_unregister_event,
4627 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
4631 .name = "numa_stat",
4632 .open = mem_control_numa_stat_open,
4638 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4639 static struct cftype memsw_cgroup_files[] = {
4641 .name = "memsw.usage_in_bytes",
4642 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
4643 .read_u64 = mem_cgroup_read,
4644 .register_event = mem_cgroup_usage_register_event,
4645 .unregister_event = mem_cgroup_usage_unregister_event,
4648 .name = "memsw.max_usage_in_bytes",
4649 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
4650 .trigger = mem_cgroup_reset,
4651 .read_u64 = mem_cgroup_read,
4654 .name = "memsw.limit_in_bytes",
4655 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
4656 .write_string = mem_cgroup_write,
4657 .read_u64 = mem_cgroup_read,
4660 .name = "memsw.failcnt",
4661 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
4662 .trigger = mem_cgroup_reset,
4663 .read_u64 = mem_cgroup_read,
4667 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
4669 if (!do_swap_account)
4671 return cgroup_add_files(cont, ss, memsw_cgroup_files,
4672 ARRAY_SIZE(memsw_cgroup_files));
4675 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
4681 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
4683 struct mem_cgroup_per_node *pn;
4684 struct mem_cgroup_per_zone *mz;
4686 int zone, tmp = node;
4688 * This routine is called against possible nodes.
4689 * But it's BUG to call kmalloc() against offline node.
4691 * TODO: this routine can waste much memory for nodes which will
4692 * never be onlined. It's better to use memory hotplug callback
4695 if (!node_state(node, N_NORMAL_MEMORY))
4697 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
4701 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4702 mz = &pn->zoneinfo[zone];
4704 INIT_LIST_HEAD(&mz->lists[l]);
4705 mz->usage_in_excess = 0;
4706 mz->on_tree = false;
4709 memcg->info.nodeinfo[node] = pn;
4713 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
4715 kfree(memcg->info.nodeinfo[node]);
4718 static struct mem_cgroup *mem_cgroup_alloc(void)
4720 struct mem_cgroup *mem;
4721 int size = sizeof(struct mem_cgroup);
4723 /* Can be very big if MAX_NUMNODES is very big */
4724 if (size < PAGE_SIZE)
4725 mem = kzalloc(size, GFP_KERNEL);
4727 mem = vzalloc(size);
4732 mem->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
4735 spin_lock_init(&mem->pcp_counter_lock);
4739 if (size < PAGE_SIZE)
4747 * At destroying mem_cgroup, references from swap_cgroup can remain.
4748 * (scanning all at force_empty is too costly...)
4750 * Instead of clearing all references at force_empty, we remember
4751 * the number of reference from swap_cgroup and free mem_cgroup when
4752 * it goes down to 0.
4754 * Removal of cgroup itself succeeds regardless of refs from swap.
4757 static void __mem_cgroup_free(struct mem_cgroup *memcg)
4761 mem_cgroup_remove_from_trees(memcg);
4762 free_css_id(&mem_cgroup_subsys, &memcg->css);
4764 for_each_node_state(node, N_POSSIBLE)
4765 free_mem_cgroup_per_zone_info(memcg, node);
4767 free_percpu(memcg->stat);
4768 if (sizeof(struct mem_cgroup) < PAGE_SIZE)
4774 static void mem_cgroup_get(struct mem_cgroup *memcg)
4776 atomic_inc(&memcg->refcnt);
4779 static void __mem_cgroup_put(struct mem_cgroup *memcg, int count)
4781 if (atomic_sub_and_test(count, &memcg->refcnt)) {
4782 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
4783 __mem_cgroup_free(memcg);
4785 mem_cgroup_put(parent);
4789 static void mem_cgroup_put(struct mem_cgroup *memcg)
4791 __mem_cgroup_put(memcg, 1);
4795 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
4797 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg)
4799 if (!memcg->res.parent)
4801 return mem_cgroup_from_res_counter(memcg->res.parent, res);
4804 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4805 static void __init enable_swap_cgroup(void)
4807 if (!mem_cgroup_disabled() && really_do_swap_account)
4808 do_swap_account = 1;
4811 static void __init enable_swap_cgroup(void)
4816 static int mem_cgroup_soft_limit_tree_init(void)
4818 struct mem_cgroup_tree_per_node *rtpn;
4819 struct mem_cgroup_tree_per_zone *rtpz;
4820 int tmp, node, zone;
4822 for_each_node_state(node, N_POSSIBLE) {
4824 if (!node_state(node, N_NORMAL_MEMORY))
4826 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
4830 soft_limit_tree.rb_tree_per_node[node] = rtpn;
4832 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4833 rtpz = &rtpn->rb_tree_per_zone[zone];
4834 rtpz->rb_root = RB_ROOT;
4835 spin_lock_init(&rtpz->lock);
4841 static struct cgroup_subsys_state * __ref
4842 mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
4844 struct mem_cgroup *memcg, *parent;
4845 long error = -ENOMEM;
4848 memcg = mem_cgroup_alloc();
4850 return ERR_PTR(error);
4852 for_each_node_state(node, N_POSSIBLE)
4853 if (alloc_mem_cgroup_per_zone_info(memcg, node))
4857 if (cont->parent == NULL) {
4859 enable_swap_cgroup();
4861 root_mem_cgroup = memcg;
4862 if (mem_cgroup_soft_limit_tree_init())
4864 for_each_possible_cpu(cpu) {
4865 struct memcg_stock_pcp *stock =
4866 &per_cpu(memcg_stock, cpu);
4867 INIT_WORK(&stock->work, drain_local_stock);
4869 hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
4871 parent = mem_cgroup_from_cont(cont->parent);
4872 memcg->use_hierarchy = parent->use_hierarchy;
4873 memcg->oom_kill_disable = parent->oom_kill_disable;
4876 if (parent && parent->use_hierarchy) {
4877 res_counter_init(&memcg->res, &parent->res);
4878 res_counter_init(&memcg->memsw, &parent->memsw);
4880 * We increment refcnt of the parent to ensure that we can
4881 * safely access it on res_counter_charge/uncharge.
4882 * This refcnt will be decremented when freeing this
4883 * mem_cgroup(see mem_cgroup_put).
4885 mem_cgroup_get(parent);
4887 res_counter_init(&memcg->res, NULL);
4888 res_counter_init(&memcg->memsw, NULL);
4890 memcg->last_scanned_child = 0;
4891 memcg->last_scanned_node = MAX_NUMNODES;
4892 INIT_LIST_HEAD(&memcg->oom_notify);
4895 memcg->swappiness = mem_cgroup_swappiness(parent);
4896 atomic_set(&memcg->refcnt, 1);
4897 memcg->move_charge_at_immigrate = 0;
4898 mutex_init(&memcg->thresholds_lock);
4901 __mem_cgroup_free(memcg);
4902 root_mem_cgroup = NULL;
4903 return ERR_PTR(error);
4906 static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
4907 struct cgroup *cont)
4909 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4911 return mem_cgroup_force_empty(memcg, false);
4914 static void mem_cgroup_destroy(struct cgroup_subsys *ss,
4915 struct cgroup *cont)
4917 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4919 mem_cgroup_put(memcg);
4922 static int mem_cgroup_populate(struct cgroup_subsys *ss,
4923 struct cgroup *cont)
4927 ret = cgroup_add_files(cont, ss, mem_cgroup_files,
4928 ARRAY_SIZE(mem_cgroup_files));
4931 ret = register_memsw_files(cont, ss);
4936 /* Handlers for move charge at task migration. */
4937 #define PRECHARGE_COUNT_AT_ONCE 256
4938 static int mem_cgroup_do_precharge(unsigned long count)
4941 int batch_count = PRECHARGE_COUNT_AT_ONCE;
4942 struct mem_cgroup *memcg = mc.to;
4944 if (mem_cgroup_is_root(memcg)) {
4945 mc.precharge += count;
4946 /* we don't need css_get for root */
4949 /* try to charge at once */
4951 struct res_counter *dummy;
4953 * "memcg" cannot be under rmdir() because we've already checked
4954 * by cgroup_lock_live_cgroup() that it is not removed and we
4955 * are still under the same cgroup_mutex. So we can postpone
4958 if (res_counter_charge(&memcg->res, PAGE_SIZE * count, &dummy))
4960 if (do_swap_account && res_counter_charge(&memcg->memsw,
4961 PAGE_SIZE * count, &dummy)) {
4962 res_counter_uncharge(&memcg->res, PAGE_SIZE * count);
4965 mc.precharge += count;
4969 /* fall back to one by one charge */
4971 if (signal_pending(current)) {
4975 if (!batch_count--) {
4976 batch_count = PRECHARGE_COUNT_AT_ONCE;
4979 ret = __mem_cgroup_try_charge(NULL,
4980 GFP_KERNEL, 1, &memcg, false);
4982 /* mem_cgroup_clear_mc() will do uncharge later */
4990 * is_target_pte_for_mc - check a pte whether it is valid for move charge
4991 * @vma: the vma the pte to be checked belongs
4992 * @addr: the address corresponding to the pte to be checked
4993 * @ptent: the pte to be checked
4994 * @target: the pointer the target page or swap ent will be stored(can be NULL)
4997 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
4998 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
4999 * move charge. if @target is not NULL, the page is stored in target->page
5000 * with extra refcnt got(Callers should handle it).
5001 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5002 * target for charge migration. if @target is not NULL, the entry is stored
5005 * Called with pte lock held.
5012 enum mc_target_type {
5013 MC_TARGET_NONE, /* not used */
5018 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5019 unsigned long addr, pte_t ptent)
5021 struct page *page = vm_normal_page(vma, addr, ptent);
5023 if (!page || !page_mapped(page))
5025 if (PageAnon(page)) {
5026 /* we don't move shared anon */
5027 if (!move_anon() || page_mapcount(page) > 2)
5029 } else if (!move_file())
5030 /* we ignore mapcount for file pages */
5032 if (!get_page_unless_zero(page))
5038 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5039 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5042 struct page *page = NULL;
5043 swp_entry_t ent = pte_to_swp_entry(ptent);
5045 if (!move_anon() || non_swap_entry(ent))
5047 usage_count = mem_cgroup_count_swap_user(ent, &page);
5048 if (usage_count > 1) { /* we don't move shared anon */
5053 if (do_swap_account)
5054 entry->val = ent.val;
5059 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5060 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5062 struct page *page = NULL;
5063 struct inode *inode;
5064 struct address_space *mapping;
5067 if (!vma->vm_file) /* anonymous vma */
5072 inode = vma->vm_file->f_path.dentry->d_inode;
5073 mapping = vma->vm_file->f_mapping;
5074 if (pte_none(ptent))
5075 pgoff = linear_page_index(vma, addr);
5076 else /* pte_file(ptent) is true */
5077 pgoff = pte_to_pgoff(ptent);
5079 /* page is moved even if it's not RSS of this task(page-faulted). */
5080 page = find_get_page(mapping, pgoff);
5083 /* shmem/tmpfs may report page out on swap: account for that too. */
5084 if (radix_tree_exceptional_entry(page)) {
5085 swp_entry_t swap = radix_to_swp_entry(page);
5086 if (do_swap_account)
5088 page = find_get_page(&swapper_space, swap.val);
5094 static int is_target_pte_for_mc(struct vm_area_struct *vma,
5095 unsigned long addr, pte_t ptent, union mc_target *target)
5097 struct page *page = NULL;
5098 struct page_cgroup *pc;
5100 swp_entry_t ent = { .val = 0 };
5102 if (pte_present(ptent))
5103 page = mc_handle_present_pte(vma, addr, ptent);
5104 else if (is_swap_pte(ptent))
5105 page = mc_handle_swap_pte(vma, addr, ptent, &ent);
5106 else if (pte_none(ptent) || pte_file(ptent))
5107 page = mc_handle_file_pte(vma, addr, ptent, &ent);
5109 if (!page && !ent.val)
5112 pc = lookup_page_cgroup(page);
5114 * Do only loose check w/o page_cgroup lock.
5115 * mem_cgroup_move_account() checks the pc is valid or not under
5118 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
5119 ret = MC_TARGET_PAGE;
5121 target->page = page;
5123 if (!ret || !target)
5126 /* There is a swap entry and a page doesn't exist or isn't charged */
5127 if (ent.val && !ret &&
5128 css_id(&mc.from->css) == lookup_swap_cgroup(ent)) {
5129 ret = MC_TARGET_SWAP;
5136 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5137 unsigned long addr, unsigned long end,
5138 struct mm_walk *walk)
5140 struct vm_area_struct *vma = walk->private;
5144 split_huge_page_pmd(walk->mm, pmd);
5146 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5147 for (; addr != end; pte++, addr += PAGE_SIZE)
5148 if (is_target_pte_for_mc(vma, addr, *pte, NULL))
5149 mc.precharge++; /* increment precharge temporarily */
5150 pte_unmap_unlock(pte - 1, ptl);
5156 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5158 unsigned long precharge;
5159 struct vm_area_struct *vma;
5161 down_read(&mm->mmap_sem);
5162 for (vma = mm->mmap; vma; vma = vma->vm_next) {
5163 struct mm_walk mem_cgroup_count_precharge_walk = {
5164 .pmd_entry = mem_cgroup_count_precharge_pte_range,
5168 if (is_vm_hugetlb_page(vma))
5170 walk_page_range(vma->vm_start, vma->vm_end,
5171 &mem_cgroup_count_precharge_walk);
5173 up_read(&mm->mmap_sem);
5175 precharge = mc.precharge;
5181 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5183 unsigned long precharge = mem_cgroup_count_precharge(mm);
5185 VM_BUG_ON(mc.moving_task);
5186 mc.moving_task = current;
5187 return mem_cgroup_do_precharge(precharge);
5190 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5191 static void __mem_cgroup_clear_mc(void)
5193 struct mem_cgroup *from = mc.from;
5194 struct mem_cgroup *to = mc.to;
5196 /* we must uncharge all the leftover precharges from mc.to */
5198 __mem_cgroup_cancel_charge(mc.to, mc.precharge);
5202 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5203 * we must uncharge here.
5205 if (mc.moved_charge) {
5206 __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
5207 mc.moved_charge = 0;
5209 /* we must fixup refcnts and charges */
5210 if (mc.moved_swap) {
5211 /* uncharge swap account from the old cgroup */
5212 if (!mem_cgroup_is_root(mc.from))
5213 res_counter_uncharge(&mc.from->memsw,
5214 PAGE_SIZE * mc.moved_swap);
5215 __mem_cgroup_put(mc.from, mc.moved_swap);
5217 if (!mem_cgroup_is_root(mc.to)) {
5219 * we charged both to->res and to->memsw, so we should
5222 res_counter_uncharge(&mc.to->res,
5223 PAGE_SIZE * mc.moved_swap);
5225 /* we've already done mem_cgroup_get(mc.to) */
5228 memcg_oom_recover(from);
5229 memcg_oom_recover(to);
5230 wake_up_all(&mc.waitq);
5233 static void mem_cgroup_clear_mc(void)
5235 struct mem_cgroup *from = mc.from;
5238 * we must clear moving_task before waking up waiters at the end of
5241 mc.moving_task = NULL;
5242 __mem_cgroup_clear_mc();
5243 spin_lock(&mc.lock);
5246 spin_unlock(&mc.lock);
5247 mem_cgroup_end_move(from);
5250 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
5251 struct cgroup *cgroup,
5252 struct task_struct *p)
5255 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgroup);
5257 if (memcg->move_charge_at_immigrate) {
5258 struct mm_struct *mm;
5259 struct mem_cgroup *from = mem_cgroup_from_task(p);
5261 VM_BUG_ON(from == memcg);
5263 mm = get_task_mm(p);
5266 /* We move charges only when we move a owner of the mm */
5267 if (mm->owner == p) {
5270 VM_BUG_ON(mc.precharge);
5271 VM_BUG_ON(mc.moved_charge);
5272 VM_BUG_ON(mc.moved_swap);
5273 mem_cgroup_start_move(from);
5274 spin_lock(&mc.lock);
5277 spin_unlock(&mc.lock);
5278 /* We set mc.moving_task later */
5280 ret = mem_cgroup_precharge_mc(mm);
5282 mem_cgroup_clear_mc();
5289 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
5290 struct cgroup *cgroup,
5291 struct task_struct *p)
5293 mem_cgroup_clear_mc();
5296 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
5297 unsigned long addr, unsigned long end,
5298 struct mm_walk *walk)
5301 struct vm_area_struct *vma = walk->private;
5305 split_huge_page_pmd(walk->mm, pmd);
5307 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5308 for (; addr != end; addr += PAGE_SIZE) {
5309 pte_t ptent = *(pte++);
5310 union mc_target target;
5313 struct page_cgroup *pc;
5319 type = is_target_pte_for_mc(vma, addr, ptent, &target);
5321 case MC_TARGET_PAGE:
5323 if (isolate_lru_page(page))
5325 pc = lookup_page_cgroup(page);
5326 if (!mem_cgroup_move_account(page, 1, pc,
5327 mc.from, mc.to, false)) {
5329 /* we uncharge from mc.from later. */
5332 putback_lru_page(page);
5333 put: /* is_target_pte_for_mc() gets the page */
5336 case MC_TARGET_SWAP:
5338 if (!mem_cgroup_move_swap_account(ent,
5339 mc.from, mc.to, false)) {
5341 /* we fixup refcnts and charges later. */
5349 pte_unmap_unlock(pte - 1, ptl);
5354 * We have consumed all precharges we got in can_attach().
5355 * We try charge one by one, but don't do any additional
5356 * charges to mc.to if we have failed in charge once in attach()
5359 ret = mem_cgroup_do_precharge(1);
5367 static void mem_cgroup_move_charge(struct mm_struct *mm)
5369 struct vm_area_struct *vma;
5371 lru_add_drain_all();
5373 if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
5375 * Someone who are holding the mmap_sem might be waiting in
5376 * waitq. So we cancel all extra charges, wake up all waiters,
5377 * and retry. Because we cancel precharges, we might not be able
5378 * to move enough charges, but moving charge is a best-effort
5379 * feature anyway, so it wouldn't be a big problem.
5381 __mem_cgroup_clear_mc();
5385 for (vma = mm->mmap; vma; vma = vma->vm_next) {
5387 struct mm_walk mem_cgroup_move_charge_walk = {
5388 .pmd_entry = mem_cgroup_move_charge_pte_range,
5392 if (is_vm_hugetlb_page(vma))
5394 ret = walk_page_range(vma->vm_start, vma->vm_end,
5395 &mem_cgroup_move_charge_walk);
5398 * means we have consumed all precharges and failed in
5399 * doing additional charge. Just abandon here.
5403 up_read(&mm->mmap_sem);
5406 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
5407 struct cgroup *cont,
5408 struct cgroup *old_cont,
5409 struct task_struct *p)
5411 struct mm_struct *mm = get_task_mm(p);
5415 mem_cgroup_move_charge(mm);
5420 mem_cgroup_clear_mc();
5422 #else /* !CONFIG_MMU */
5423 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
5424 struct cgroup *cgroup,
5425 struct task_struct *p)
5429 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
5430 struct cgroup *cgroup,
5431 struct task_struct *p)
5434 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
5435 struct cgroup *cont,
5436 struct cgroup *old_cont,
5437 struct task_struct *p)
5442 struct cgroup_subsys mem_cgroup_subsys = {
5444 .subsys_id = mem_cgroup_subsys_id,
5445 .create = mem_cgroup_create,
5446 .pre_destroy = mem_cgroup_pre_destroy,
5447 .destroy = mem_cgroup_destroy,
5448 .populate = mem_cgroup_populate,
5449 .can_attach = mem_cgroup_can_attach,
5450 .cancel_attach = mem_cgroup_cancel_attach,
5451 .attach = mem_cgroup_move_task,
5456 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
5457 static int __init enable_swap_account(char *s)
5459 /* consider enabled if no parameter or 1 is given */
5460 if (!strcmp(s, "1"))
5461 really_do_swap_account = 1;
5462 else if (!strcmp(s, "0"))
5463 really_do_swap_account = 0;
5466 __setup("swapaccount=", enable_swap_account);