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>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
20 #include <linux/res_counter.h>
21 #include <linux/memcontrol.h>
22 #include <linux/cgroup.h>
24 #include <linux/hugetlb.h>
25 #include <linux/pagemap.h>
26 #include <linux/smp.h>
27 #include <linux/page-flags.h>
28 #include <linux/backing-dev.h>
29 #include <linux/bit_spinlock.h>
30 #include <linux/rcupdate.h>
31 #include <linux/limits.h>
32 #include <linux/mutex.h>
33 #include <linux/rbtree.h>
34 #include <linux/slab.h>
35 #include <linux/swap.h>
36 #include <linux/spinlock.h>
38 #include <linux/seq_file.h>
39 #include <linux/vmalloc.h>
40 #include <linux/mm_inline.h>
41 #include <linux/page_cgroup.h>
42 #include <linux/cpu.h>
45 #include <asm/uaccess.h>
47 struct cgroup_subsys mem_cgroup_subsys __read_mostly;
48 #define MEM_CGROUP_RECLAIM_RETRIES 5
49 struct mem_cgroup *root_mem_cgroup __read_mostly;
51 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
52 /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
53 int do_swap_account __read_mostly;
54 static int really_do_swap_account __initdata = 1; /* for remember boot option*/
56 #define do_swap_account (0)
59 #define SOFTLIMIT_EVENTS_THRESH (1000)
62 * Statistics for memory cgroup.
64 enum mem_cgroup_stat_index {
66 * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
68 MEM_CGROUP_STAT_CACHE, /* # of pages charged as cache */
69 MEM_CGROUP_STAT_RSS, /* # of pages charged as anon rss */
70 MEM_CGROUP_STAT_FILE_MAPPED, /* # of pages charged as file rss */
71 MEM_CGROUP_STAT_PGPGIN_COUNT, /* # of pages paged in */
72 MEM_CGROUP_STAT_PGPGOUT_COUNT, /* # of pages paged out */
73 MEM_CGROUP_STAT_EVENTS, /* sum of pagein + pageout for internal use */
74 MEM_CGROUP_STAT_SWAPOUT, /* # of pages, swapped out */
76 MEM_CGROUP_STAT_NSTATS,
79 struct mem_cgroup_stat_cpu {
80 s64 count[MEM_CGROUP_STAT_NSTATS];
81 } ____cacheline_aligned_in_smp;
83 struct mem_cgroup_stat {
84 struct mem_cgroup_stat_cpu cpustat[0];
88 __mem_cgroup_stat_reset_safe(struct mem_cgroup_stat_cpu *stat,
89 enum mem_cgroup_stat_index idx)
95 __mem_cgroup_stat_read_local(struct mem_cgroup_stat_cpu *stat,
96 enum mem_cgroup_stat_index idx)
98 return stat->count[idx];
102 * For accounting under irq disable, no need for increment preempt count.
104 static inline void __mem_cgroup_stat_add_safe(struct mem_cgroup_stat_cpu *stat,
105 enum mem_cgroup_stat_index idx, int val)
107 stat->count[idx] += val;
110 static s64 mem_cgroup_read_stat(struct mem_cgroup_stat *stat,
111 enum mem_cgroup_stat_index idx)
115 for_each_possible_cpu(cpu)
116 ret += stat->cpustat[cpu].count[idx];
120 static s64 mem_cgroup_local_usage(struct mem_cgroup_stat *stat)
124 ret = mem_cgroup_read_stat(stat, MEM_CGROUP_STAT_CACHE);
125 ret += mem_cgroup_read_stat(stat, MEM_CGROUP_STAT_RSS);
130 * per-zone information in memory controller.
132 struct mem_cgroup_per_zone {
134 * spin_lock to protect the per cgroup LRU
136 struct list_head lists[NR_LRU_LISTS];
137 unsigned long count[NR_LRU_LISTS];
139 struct zone_reclaim_stat reclaim_stat;
140 struct rb_node tree_node; /* RB tree node */
141 unsigned long long usage_in_excess;/* Set to the value by which */
142 /* the soft limit is exceeded*/
144 struct mem_cgroup *mem; /* Back pointer, we cannot */
145 /* use container_of */
147 /* Macro for accessing counter */
148 #define MEM_CGROUP_ZSTAT(mz, idx) ((mz)->count[(idx)])
150 struct mem_cgroup_per_node {
151 struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
154 struct mem_cgroup_lru_info {
155 struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
159 * Cgroups above their limits are maintained in a RB-Tree, independent of
160 * their hierarchy representation
163 struct mem_cgroup_tree_per_zone {
164 struct rb_root rb_root;
168 struct mem_cgroup_tree_per_node {
169 struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
172 struct mem_cgroup_tree {
173 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
176 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
179 * The memory controller data structure. The memory controller controls both
180 * page cache and RSS per cgroup. We would eventually like to provide
181 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
182 * to help the administrator determine what knobs to tune.
184 * TODO: Add a water mark for the memory controller. Reclaim will begin when
185 * we hit the water mark. May be even add a low water mark, such that
186 * no reclaim occurs from a cgroup at it's low water mark, this is
187 * a feature that will be implemented much later in the future.
190 struct cgroup_subsys_state css;
192 * the counter to account for memory usage
194 struct res_counter res;
196 * the counter to account for mem+swap usage.
198 struct res_counter memsw;
200 * Per cgroup active and inactive list, similar to the
201 * per zone LRU lists.
203 struct mem_cgroup_lru_info info;
206 protect against reclaim related member.
208 spinlock_t reclaim_param_lock;
210 int prev_priority; /* for recording reclaim priority */
213 * While reclaiming in a hierarchy, we cache the last child we
216 int last_scanned_child;
218 * Should the accounting and control be hierarchical, per subtree?
221 unsigned long last_oom_jiffies;
224 unsigned int swappiness;
226 /* set when res.limit == memsw.limit */
227 bool memsw_is_minimum;
230 * Should we move charges of a task when a task is moved into this
231 * mem_cgroup ? And what type of charges should we move ?
233 unsigned long move_charge_at_immigrate;
236 * statistics. This must be placed at the end of memcg.
238 struct mem_cgroup_stat stat;
241 /* Stuffs for move charges at task migration. */
243 * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a
244 * left-shifted bitmap of these types.
247 MOVE_CHARGE_TYPE_ANON, /* private anonymous page and swap of it */
251 /* "mc" and its members are protected by cgroup_mutex */
252 static struct move_charge_struct {
253 struct mem_cgroup *from;
254 struct mem_cgroup *to;
255 unsigned long precharge;
259 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
260 * limit reclaim to prevent infinite loops, if they ever occur.
262 #define MEM_CGROUP_MAX_RECLAIM_LOOPS (100)
263 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS (2)
266 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
267 MEM_CGROUP_CHARGE_TYPE_MAPPED,
268 MEM_CGROUP_CHARGE_TYPE_SHMEM, /* used by page migration of shmem */
269 MEM_CGROUP_CHARGE_TYPE_FORCE, /* used by force_empty */
270 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
271 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
275 /* only for here (for easy reading.) */
276 #define PCGF_CACHE (1UL << PCG_CACHE)
277 #define PCGF_USED (1UL << PCG_USED)
278 #define PCGF_LOCK (1UL << PCG_LOCK)
279 /* Not used, but added here for completeness */
280 #define PCGF_ACCT (1UL << PCG_ACCT)
282 /* for encoding cft->private value on file */
285 #define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val))
286 #define MEMFILE_TYPE(val) (((val) >> 16) & 0xffff)
287 #define MEMFILE_ATTR(val) ((val) & 0xffff)
290 * Reclaim flags for mem_cgroup_hierarchical_reclaim
292 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
293 #define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
294 #define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
295 #define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
296 #define MEM_CGROUP_RECLAIM_SOFT_BIT 0x2
297 #define MEM_CGROUP_RECLAIM_SOFT (1 << MEM_CGROUP_RECLAIM_SOFT_BIT)
299 static void mem_cgroup_get(struct mem_cgroup *mem);
300 static void mem_cgroup_put(struct mem_cgroup *mem);
301 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem);
302 static void drain_all_stock_async(void);
304 static struct mem_cgroup_per_zone *
305 mem_cgroup_zoneinfo(struct mem_cgroup *mem, int nid, int zid)
307 return &mem->info.nodeinfo[nid]->zoneinfo[zid];
310 struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *mem)
315 static struct mem_cgroup_per_zone *
316 page_cgroup_zoneinfo(struct page_cgroup *pc)
318 struct mem_cgroup *mem = pc->mem_cgroup;
319 int nid = page_cgroup_nid(pc);
320 int zid = page_cgroup_zid(pc);
325 return mem_cgroup_zoneinfo(mem, nid, zid);
328 static struct mem_cgroup_tree_per_zone *
329 soft_limit_tree_node_zone(int nid, int zid)
331 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
334 static struct mem_cgroup_tree_per_zone *
335 soft_limit_tree_from_page(struct page *page)
337 int nid = page_to_nid(page);
338 int zid = page_zonenum(page);
340 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
344 __mem_cgroup_insert_exceeded(struct mem_cgroup *mem,
345 struct mem_cgroup_per_zone *mz,
346 struct mem_cgroup_tree_per_zone *mctz,
347 unsigned long long new_usage_in_excess)
349 struct rb_node **p = &mctz->rb_root.rb_node;
350 struct rb_node *parent = NULL;
351 struct mem_cgroup_per_zone *mz_node;
356 mz->usage_in_excess = new_usage_in_excess;
357 if (!mz->usage_in_excess)
361 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
363 if (mz->usage_in_excess < mz_node->usage_in_excess)
366 * We can't avoid mem cgroups that are over their soft
367 * limit by the same amount
369 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
372 rb_link_node(&mz->tree_node, parent, p);
373 rb_insert_color(&mz->tree_node, &mctz->rb_root);
378 __mem_cgroup_remove_exceeded(struct mem_cgroup *mem,
379 struct mem_cgroup_per_zone *mz,
380 struct mem_cgroup_tree_per_zone *mctz)
384 rb_erase(&mz->tree_node, &mctz->rb_root);
389 mem_cgroup_remove_exceeded(struct mem_cgroup *mem,
390 struct mem_cgroup_per_zone *mz,
391 struct mem_cgroup_tree_per_zone *mctz)
393 spin_lock(&mctz->lock);
394 __mem_cgroup_remove_exceeded(mem, mz, mctz);
395 spin_unlock(&mctz->lock);
398 static bool mem_cgroup_soft_limit_check(struct mem_cgroup *mem)
403 struct mem_cgroup_stat_cpu *cpustat;
406 cpustat = &mem->stat.cpustat[cpu];
407 val = __mem_cgroup_stat_read_local(cpustat, MEM_CGROUP_STAT_EVENTS);
408 if (unlikely(val > SOFTLIMIT_EVENTS_THRESH)) {
409 __mem_cgroup_stat_reset_safe(cpustat, MEM_CGROUP_STAT_EVENTS);
416 static void mem_cgroup_update_tree(struct mem_cgroup *mem, struct page *page)
418 unsigned long long excess;
419 struct mem_cgroup_per_zone *mz;
420 struct mem_cgroup_tree_per_zone *mctz;
421 int nid = page_to_nid(page);
422 int zid = page_zonenum(page);
423 mctz = soft_limit_tree_from_page(page);
426 * Necessary to update all ancestors when hierarchy is used.
427 * because their event counter is not touched.
429 for (; mem; mem = parent_mem_cgroup(mem)) {
430 mz = mem_cgroup_zoneinfo(mem, nid, zid);
431 excess = res_counter_soft_limit_excess(&mem->res);
433 * We have to update the tree if mz is on RB-tree or
434 * mem is over its softlimit.
436 if (excess || mz->on_tree) {
437 spin_lock(&mctz->lock);
438 /* if on-tree, remove it */
440 __mem_cgroup_remove_exceeded(mem, mz, mctz);
442 * Insert again. mz->usage_in_excess will be updated.
443 * If excess is 0, no tree ops.
445 __mem_cgroup_insert_exceeded(mem, mz, mctz, excess);
446 spin_unlock(&mctz->lock);
451 static void mem_cgroup_remove_from_trees(struct mem_cgroup *mem)
454 struct mem_cgroup_per_zone *mz;
455 struct mem_cgroup_tree_per_zone *mctz;
457 for_each_node_state(node, N_POSSIBLE) {
458 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
459 mz = mem_cgroup_zoneinfo(mem, node, zone);
460 mctz = soft_limit_tree_node_zone(node, zone);
461 mem_cgroup_remove_exceeded(mem, mz, mctz);
466 static inline unsigned long mem_cgroup_get_excess(struct mem_cgroup *mem)
468 return res_counter_soft_limit_excess(&mem->res) >> PAGE_SHIFT;
471 static struct mem_cgroup_per_zone *
472 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
474 struct rb_node *rightmost = NULL;
475 struct mem_cgroup_per_zone *mz;
479 rightmost = rb_last(&mctz->rb_root);
481 goto done; /* Nothing to reclaim from */
483 mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
485 * Remove the node now but someone else can add it back,
486 * we will to add it back at the end of reclaim to its correct
487 * position in the tree.
489 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
490 if (!res_counter_soft_limit_excess(&mz->mem->res) ||
491 !css_tryget(&mz->mem->css))
497 static struct mem_cgroup_per_zone *
498 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
500 struct mem_cgroup_per_zone *mz;
502 spin_lock(&mctz->lock);
503 mz = __mem_cgroup_largest_soft_limit_node(mctz);
504 spin_unlock(&mctz->lock);
508 static void mem_cgroup_swap_statistics(struct mem_cgroup *mem,
511 int val = (charge) ? 1 : -1;
512 struct mem_cgroup_stat *stat = &mem->stat;
513 struct mem_cgroup_stat_cpu *cpustat;
516 cpustat = &stat->cpustat[cpu];
517 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_SWAPOUT, val);
521 static void mem_cgroup_charge_statistics(struct mem_cgroup *mem,
522 struct page_cgroup *pc,
525 int val = (charge) ? 1 : -1;
526 struct mem_cgroup_stat *stat = &mem->stat;
527 struct mem_cgroup_stat_cpu *cpustat;
530 cpustat = &stat->cpustat[cpu];
531 if (PageCgroupCache(pc))
532 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_CACHE, val);
534 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_RSS, val);
537 __mem_cgroup_stat_add_safe(cpustat,
538 MEM_CGROUP_STAT_PGPGIN_COUNT, 1);
540 __mem_cgroup_stat_add_safe(cpustat,
541 MEM_CGROUP_STAT_PGPGOUT_COUNT, 1);
542 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_EVENTS, 1);
546 static unsigned long mem_cgroup_get_local_zonestat(struct mem_cgroup *mem,
550 struct mem_cgroup_per_zone *mz;
553 for_each_online_node(nid)
554 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
555 mz = mem_cgroup_zoneinfo(mem, nid, zid);
556 total += MEM_CGROUP_ZSTAT(mz, idx);
561 static struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
563 return container_of(cgroup_subsys_state(cont,
564 mem_cgroup_subsys_id), struct mem_cgroup,
568 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
571 * mm_update_next_owner() may clear mm->owner to NULL
572 * if it races with swapoff, page migration, etc.
573 * So this can be called with p == NULL.
578 return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
579 struct mem_cgroup, css);
582 static struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
584 struct mem_cgroup *mem = NULL;
589 * Because we have no locks, mm->owner's may be being moved to other
590 * cgroup. We use css_tryget() here even if this looks
591 * pessimistic (rather than adding locks here).
595 mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
598 } while (!css_tryget(&mem->css));
604 * Call callback function against all cgroup under hierarchy tree.
606 static int mem_cgroup_walk_tree(struct mem_cgroup *root, void *data,
607 int (*func)(struct mem_cgroup *, void *))
609 int found, ret, nextid;
610 struct cgroup_subsys_state *css;
611 struct mem_cgroup *mem;
613 if (!root->use_hierarchy)
614 return (*func)(root, data);
622 css = css_get_next(&mem_cgroup_subsys, nextid, &root->css,
624 if (css && css_tryget(css))
625 mem = container_of(css, struct mem_cgroup, css);
629 ret = (*func)(mem, data);
633 } while (!ret && css);
638 static inline bool mem_cgroup_is_root(struct mem_cgroup *mem)
640 return (mem == root_mem_cgroup);
644 * Following LRU functions are allowed to be used without PCG_LOCK.
645 * Operations are called by routine of global LRU independently from memcg.
646 * What we have to take care of here is validness of pc->mem_cgroup.
648 * Changes to pc->mem_cgroup happens when
651 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
652 * It is added to LRU before charge.
653 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
654 * When moving account, the page is not on LRU. It's isolated.
657 void mem_cgroup_del_lru_list(struct page *page, enum lru_list lru)
659 struct page_cgroup *pc;
660 struct mem_cgroup_per_zone *mz;
662 if (mem_cgroup_disabled())
664 pc = lookup_page_cgroup(page);
665 /* can happen while we handle swapcache. */
666 if (!TestClearPageCgroupAcctLRU(pc))
668 VM_BUG_ON(!pc->mem_cgroup);
670 * We don't check PCG_USED bit. It's cleared when the "page" is finally
671 * removed from global LRU.
673 mz = page_cgroup_zoneinfo(pc);
674 MEM_CGROUP_ZSTAT(mz, lru) -= 1;
675 if (mem_cgroup_is_root(pc->mem_cgroup))
677 VM_BUG_ON(list_empty(&pc->lru));
678 list_del_init(&pc->lru);
682 void mem_cgroup_del_lru(struct page *page)
684 mem_cgroup_del_lru_list(page, page_lru(page));
687 void mem_cgroup_rotate_lru_list(struct page *page, enum lru_list lru)
689 struct mem_cgroup_per_zone *mz;
690 struct page_cgroup *pc;
692 if (mem_cgroup_disabled())
695 pc = lookup_page_cgroup(page);
697 * Used bit is set without atomic ops but after smp_wmb().
698 * For making pc->mem_cgroup visible, insert smp_rmb() here.
701 /* unused or root page is not rotated. */
702 if (!PageCgroupUsed(pc) || mem_cgroup_is_root(pc->mem_cgroup))
704 mz = page_cgroup_zoneinfo(pc);
705 list_move(&pc->lru, &mz->lists[lru]);
708 void mem_cgroup_add_lru_list(struct page *page, enum lru_list lru)
710 struct page_cgroup *pc;
711 struct mem_cgroup_per_zone *mz;
713 if (mem_cgroup_disabled())
715 pc = lookup_page_cgroup(page);
716 VM_BUG_ON(PageCgroupAcctLRU(pc));
718 * Used bit is set without atomic ops but after smp_wmb().
719 * For making pc->mem_cgroup visible, insert smp_rmb() here.
722 if (!PageCgroupUsed(pc))
725 mz = page_cgroup_zoneinfo(pc);
726 MEM_CGROUP_ZSTAT(mz, lru) += 1;
727 SetPageCgroupAcctLRU(pc);
728 if (mem_cgroup_is_root(pc->mem_cgroup))
730 list_add(&pc->lru, &mz->lists[lru]);
734 * At handling SwapCache, pc->mem_cgroup may be changed while it's linked to
735 * lru because the page may.be reused after it's fully uncharged (because of
736 * SwapCache behavior).To handle that, unlink page_cgroup from LRU when charge
737 * it again. This function is only used to charge SwapCache. It's done under
738 * lock_page and expected that zone->lru_lock is never held.
740 static void mem_cgroup_lru_del_before_commit_swapcache(struct page *page)
743 struct zone *zone = page_zone(page);
744 struct page_cgroup *pc = lookup_page_cgroup(page);
746 spin_lock_irqsave(&zone->lru_lock, flags);
748 * Forget old LRU when this page_cgroup is *not* used. This Used bit
749 * is guarded by lock_page() because the page is SwapCache.
751 if (!PageCgroupUsed(pc))
752 mem_cgroup_del_lru_list(page, page_lru(page));
753 spin_unlock_irqrestore(&zone->lru_lock, flags);
756 static void mem_cgroup_lru_add_after_commit_swapcache(struct page *page)
759 struct zone *zone = page_zone(page);
760 struct page_cgroup *pc = lookup_page_cgroup(page);
762 spin_lock_irqsave(&zone->lru_lock, flags);
763 /* link when the page is linked to LRU but page_cgroup isn't */
764 if (PageLRU(page) && !PageCgroupAcctLRU(pc))
765 mem_cgroup_add_lru_list(page, page_lru(page));
766 spin_unlock_irqrestore(&zone->lru_lock, flags);
770 void mem_cgroup_move_lists(struct page *page,
771 enum lru_list from, enum lru_list to)
773 if (mem_cgroup_disabled())
775 mem_cgroup_del_lru_list(page, from);
776 mem_cgroup_add_lru_list(page, to);
779 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *mem)
782 struct mem_cgroup *curr = NULL;
786 curr = try_get_mem_cgroup_from_mm(task->mm);
792 * We should check use_hierarchy of "mem" not "curr". Because checking
793 * use_hierarchy of "curr" here make this function true if hierarchy is
794 * enabled in "curr" and "curr" is a child of "mem" in *cgroup*
795 * hierarchy(even if use_hierarchy is disabled in "mem").
797 if (mem->use_hierarchy)
798 ret = css_is_ancestor(&curr->css, &mem->css);
806 * prev_priority control...this will be used in memory reclaim path.
808 int mem_cgroup_get_reclaim_priority(struct mem_cgroup *mem)
812 spin_lock(&mem->reclaim_param_lock);
813 prev_priority = mem->prev_priority;
814 spin_unlock(&mem->reclaim_param_lock);
816 return prev_priority;
819 void mem_cgroup_note_reclaim_priority(struct mem_cgroup *mem, int priority)
821 spin_lock(&mem->reclaim_param_lock);
822 if (priority < mem->prev_priority)
823 mem->prev_priority = priority;
824 spin_unlock(&mem->reclaim_param_lock);
827 void mem_cgroup_record_reclaim_priority(struct mem_cgroup *mem, int priority)
829 spin_lock(&mem->reclaim_param_lock);
830 mem->prev_priority = priority;
831 spin_unlock(&mem->reclaim_param_lock);
834 static int calc_inactive_ratio(struct mem_cgroup *memcg, unsigned long *present_pages)
836 unsigned long active;
837 unsigned long inactive;
839 unsigned long inactive_ratio;
841 inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_ANON);
842 active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_ANON);
844 gb = (inactive + active) >> (30 - PAGE_SHIFT);
846 inactive_ratio = int_sqrt(10 * gb);
851 present_pages[0] = inactive;
852 present_pages[1] = active;
855 return inactive_ratio;
858 int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg)
860 unsigned long active;
861 unsigned long inactive;
862 unsigned long present_pages[2];
863 unsigned long inactive_ratio;
865 inactive_ratio = calc_inactive_ratio(memcg, present_pages);
867 inactive = present_pages[0];
868 active = present_pages[1];
870 if (inactive * inactive_ratio < active)
876 int mem_cgroup_inactive_file_is_low(struct mem_cgroup *memcg)
878 unsigned long active;
879 unsigned long inactive;
881 inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_FILE);
882 active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_FILE);
884 return (active > inactive);
887 unsigned long mem_cgroup_zone_nr_pages(struct mem_cgroup *memcg,
891 int nid = zone->zone_pgdat->node_id;
892 int zid = zone_idx(zone);
893 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
895 return MEM_CGROUP_ZSTAT(mz, lru);
898 struct zone_reclaim_stat *mem_cgroup_get_reclaim_stat(struct mem_cgroup *memcg,
901 int nid = zone->zone_pgdat->node_id;
902 int zid = zone_idx(zone);
903 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
905 return &mz->reclaim_stat;
908 struct zone_reclaim_stat *
909 mem_cgroup_get_reclaim_stat_from_page(struct page *page)
911 struct page_cgroup *pc;
912 struct mem_cgroup_per_zone *mz;
914 if (mem_cgroup_disabled())
917 pc = lookup_page_cgroup(page);
919 * Used bit is set without atomic ops but after smp_wmb().
920 * For making pc->mem_cgroup visible, insert smp_rmb() here.
923 if (!PageCgroupUsed(pc))
926 mz = page_cgroup_zoneinfo(pc);
930 return &mz->reclaim_stat;
933 unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan,
934 struct list_head *dst,
935 unsigned long *scanned, int order,
936 int mode, struct zone *z,
937 struct mem_cgroup *mem_cont,
938 int active, int file)
940 unsigned long nr_taken = 0;
944 struct list_head *src;
945 struct page_cgroup *pc, *tmp;
946 int nid = z->zone_pgdat->node_id;
947 int zid = zone_idx(z);
948 struct mem_cgroup_per_zone *mz;
949 int lru = LRU_FILE * file + active;
953 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
954 src = &mz->lists[lru];
957 list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
958 if (scan >= nr_to_scan)
962 if (unlikely(!PageCgroupUsed(pc)))
964 if (unlikely(!PageLRU(page)))
968 ret = __isolate_lru_page(page, mode, file);
971 list_move(&page->lru, dst);
972 mem_cgroup_del_lru(page);
976 /* we don't affect global LRU but rotate in our LRU */
977 mem_cgroup_rotate_lru_list(page, page_lru(page));
988 #define mem_cgroup_from_res_counter(counter, member) \
989 container_of(counter, struct mem_cgroup, member)
991 static bool mem_cgroup_check_under_limit(struct mem_cgroup *mem)
993 if (do_swap_account) {
994 if (res_counter_check_under_limit(&mem->res) &&
995 res_counter_check_under_limit(&mem->memsw))
998 if (res_counter_check_under_limit(&mem->res))
1003 static unsigned int get_swappiness(struct mem_cgroup *memcg)
1005 struct cgroup *cgrp = memcg->css.cgroup;
1006 unsigned int swappiness;
1009 if (cgrp->parent == NULL)
1010 return vm_swappiness;
1012 spin_lock(&memcg->reclaim_param_lock);
1013 swappiness = memcg->swappiness;
1014 spin_unlock(&memcg->reclaim_param_lock);
1019 static int mem_cgroup_count_children_cb(struct mem_cgroup *mem, void *data)
1027 * mem_cgroup_print_mem_info: Called from OOM with tasklist_lock held in read mode.
1028 * @memcg: The memory cgroup that went over limit
1029 * @p: Task that is going to be killed
1031 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1034 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1036 struct cgroup *task_cgrp;
1037 struct cgroup *mem_cgrp;
1039 * Need a buffer in BSS, can't rely on allocations. The code relies
1040 * on the assumption that OOM is serialized for memory controller.
1041 * If this assumption is broken, revisit this code.
1043 static char memcg_name[PATH_MAX];
1052 mem_cgrp = memcg->css.cgroup;
1053 task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1055 ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1058 * Unfortunately, we are unable to convert to a useful name
1059 * But we'll still print out the usage information
1066 printk(KERN_INFO "Task in %s killed", memcg_name);
1069 ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1077 * Continues from above, so we don't need an KERN_ level
1079 printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
1082 printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
1083 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1084 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1085 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1086 printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
1088 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1089 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1090 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1094 * This function returns the number of memcg under hierarchy tree. Returns
1095 * 1(self count) if no children.
1097 static int mem_cgroup_count_children(struct mem_cgroup *mem)
1100 mem_cgroup_walk_tree(mem, &num, mem_cgroup_count_children_cb);
1105 * Visit the first child (need not be the first child as per the ordering
1106 * of the cgroup list, since we track last_scanned_child) of @mem and use
1107 * that to reclaim free pages from.
1109 static struct mem_cgroup *
1110 mem_cgroup_select_victim(struct mem_cgroup *root_mem)
1112 struct mem_cgroup *ret = NULL;
1113 struct cgroup_subsys_state *css;
1116 if (!root_mem->use_hierarchy) {
1117 css_get(&root_mem->css);
1123 nextid = root_mem->last_scanned_child + 1;
1124 css = css_get_next(&mem_cgroup_subsys, nextid, &root_mem->css,
1126 if (css && css_tryget(css))
1127 ret = container_of(css, struct mem_cgroup, css);
1130 /* Updates scanning parameter */
1131 spin_lock(&root_mem->reclaim_param_lock);
1133 /* this means start scan from ID:1 */
1134 root_mem->last_scanned_child = 0;
1136 root_mem->last_scanned_child = found;
1137 spin_unlock(&root_mem->reclaim_param_lock);
1144 * Scan the hierarchy if needed to reclaim memory. We remember the last child
1145 * we reclaimed from, so that we don't end up penalizing one child extensively
1146 * based on its position in the children list.
1148 * root_mem is the original ancestor that we've been reclaim from.
1150 * We give up and return to the caller when we visit root_mem twice.
1151 * (other groups can be removed while we're walking....)
1153 * If shrink==true, for avoiding to free too much, this returns immedieately.
1155 static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup *root_mem,
1158 unsigned long reclaim_options)
1160 struct mem_cgroup *victim;
1163 bool noswap = reclaim_options & MEM_CGROUP_RECLAIM_NOSWAP;
1164 bool shrink = reclaim_options & MEM_CGROUP_RECLAIM_SHRINK;
1165 bool check_soft = reclaim_options & MEM_CGROUP_RECLAIM_SOFT;
1166 unsigned long excess = mem_cgroup_get_excess(root_mem);
1168 /* If memsw_is_minimum==1, swap-out is of-no-use. */
1169 if (root_mem->memsw_is_minimum)
1173 victim = mem_cgroup_select_victim(root_mem);
1174 if (victim == root_mem) {
1177 drain_all_stock_async();
1180 * If we have not been able to reclaim
1181 * anything, it might because there are
1182 * no reclaimable pages under this hierarchy
1184 if (!check_soft || !total) {
1185 css_put(&victim->css);
1189 * We want to do more targetted reclaim.
1190 * excess >> 2 is not to excessive so as to
1191 * reclaim too much, nor too less that we keep
1192 * coming back to reclaim from this cgroup
1194 if (total >= (excess >> 2) ||
1195 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS)) {
1196 css_put(&victim->css);
1201 if (!mem_cgroup_local_usage(&victim->stat)) {
1202 /* this cgroup's local usage == 0 */
1203 css_put(&victim->css);
1206 /* we use swappiness of local cgroup */
1208 ret = mem_cgroup_shrink_node_zone(victim, gfp_mask,
1209 noswap, get_swappiness(victim), zone,
1210 zone->zone_pgdat->node_id);
1212 ret = try_to_free_mem_cgroup_pages(victim, gfp_mask,
1213 noswap, get_swappiness(victim));
1214 css_put(&victim->css);
1216 * At shrinking usage, we can't check we should stop here or
1217 * reclaim more. It's depends on callers. last_scanned_child
1218 * will work enough for keeping fairness under tree.
1224 if (res_counter_check_under_soft_limit(&root_mem->res))
1226 } else if (mem_cgroup_check_under_limit(root_mem))
1232 bool mem_cgroup_oom_called(struct task_struct *task)
1235 struct mem_cgroup *mem;
1236 struct mm_struct *mm;
1242 mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
1243 if (mem && time_before(jiffies, mem->last_oom_jiffies + HZ/10))
1249 static int record_last_oom_cb(struct mem_cgroup *mem, void *data)
1251 mem->last_oom_jiffies = jiffies;
1255 static void record_last_oom(struct mem_cgroup *mem)
1257 mem_cgroup_walk_tree(mem, NULL, record_last_oom_cb);
1261 * Currently used to update mapped file statistics, but the routine can be
1262 * generalized to update other statistics as well.
1264 void mem_cgroup_update_file_mapped(struct page *page, int val)
1266 struct mem_cgroup *mem;
1267 struct mem_cgroup_stat *stat;
1268 struct mem_cgroup_stat_cpu *cpustat;
1270 struct page_cgroup *pc;
1272 pc = lookup_page_cgroup(page);
1276 lock_page_cgroup(pc);
1277 mem = pc->mem_cgroup;
1281 if (!PageCgroupUsed(pc))
1285 * Preemption is already disabled, we don't need get_cpu()
1287 cpu = smp_processor_id();
1289 cpustat = &stat->cpustat[cpu];
1291 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_FILE_MAPPED, val);
1293 unlock_page_cgroup(pc);
1297 * size of first charge trial. "32" comes from vmscan.c's magic value.
1298 * TODO: maybe necessary to use big numbers in big irons.
1300 #define CHARGE_SIZE (32 * PAGE_SIZE)
1301 struct memcg_stock_pcp {
1302 struct mem_cgroup *cached; /* this never be root cgroup */
1304 struct work_struct work;
1306 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
1307 static atomic_t memcg_drain_count;
1310 * Try to consume stocked charge on this cpu. If success, PAGE_SIZE is consumed
1311 * from local stock and true is returned. If the stock is 0 or charges from a
1312 * cgroup which is not current target, returns false. This stock will be
1315 static bool consume_stock(struct mem_cgroup *mem)
1317 struct memcg_stock_pcp *stock;
1320 stock = &get_cpu_var(memcg_stock);
1321 if (mem == stock->cached && stock->charge)
1322 stock->charge -= PAGE_SIZE;
1323 else /* need to call res_counter_charge */
1325 put_cpu_var(memcg_stock);
1330 * Returns stocks cached in percpu to res_counter and reset cached information.
1332 static void drain_stock(struct memcg_stock_pcp *stock)
1334 struct mem_cgroup *old = stock->cached;
1336 if (stock->charge) {
1337 res_counter_uncharge(&old->res, stock->charge);
1338 if (do_swap_account)
1339 res_counter_uncharge(&old->memsw, stock->charge);
1341 stock->cached = NULL;
1346 * This must be called under preempt disabled or must be called by
1347 * a thread which is pinned to local cpu.
1349 static void drain_local_stock(struct work_struct *dummy)
1351 struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
1356 * Cache charges(val) which is from res_counter, to local per_cpu area.
1357 * This will be consumed by consumt_stock() function, later.
1359 static void refill_stock(struct mem_cgroup *mem, int val)
1361 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
1363 if (stock->cached != mem) { /* reset if necessary */
1365 stock->cached = mem;
1367 stock->charge += val;
1368 put_cpu_var(memcg_stock);
1372 * Tries to drain stocked charges in other cpus. This function is asynchronous
1373 * and just put a work per cpu for draining localy on each cpu. Caller can
1374 * expects some charges will be back to res_counter later but cannot wait for
1377 static void drain_all_stock_async(void)
1380 /* This function is for scheduling "drain" in asynchronous way.
1381 * The result of "drain" is not directly handled by callers. Then,
1382 * if someone is calling drain, we don't have to call drain more.
1383 * Anyway, WORK_STRUCT_PENDING check in queue_work_on() will catch if
1384 * there is a race. We just do loose check here.
1386 if (atomic_read(&memcg_drain_count))
1388 /* Notify other cpus that system-wide "drain" is running */
1389 atomic_inc(&memcg_drain_count);
1391 for_each_online_cpu(cpu) {
1392 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
1393 schedule_work_on(cpu, &stock->work);
1396 atomic_dec(&memcg_drain_count);
1397 /* We don't wait for flush_work */
1400 /* This is a synchronous drain interface. */
1401 static void drain_all_stock_sync(void)
1403 /* called when force_empty is called */
1404 atomic_inc(&memcg_drain_count);
1405 schedule_on_each_cpu(drain_local_stock);
1406 atomic_dec(&memcg_drain_count);
1409 static int __cpuinit memcg_stock_cpu_callback(struct notifier_block *nb,
1410 unsigned long action,
1413 int cpu = (unsigned long)hcpu;
1414 struct memcg_stock_pcp *stock;
1416 if (action != CPU_DEAD)
1418 stock = &per_cpu(memcg_stock, cpu);
1424 * Unlike exported interface, "oom" parameter is added. if oom==true,
1425 * oom-killer can be invoked.
1427 static int __mem_cgroup_try_charge(struct mm_struct *mm,
1428 gfp_t gfp_mask, struct mem_cgroup **memcg,
1429 bool oom, struct page *page)
1431 struct mem_cgroup *mem, *mem_over_limit;
1432 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
1433 struct res_counter *fail_res;
1434 int csize = CHARGE_SIZE;
1436 if (unlikely(test_thread_flag(TIF_MEMDIE))) {
1437 /* Don't account this! */
1443 * We always charge the cgroup the mm_struct belongs to.
1444 * The mm_struct's mem_cgroup changes on task migration if the
1445 * thread group leader migrates. It's possible that mm is not
1446 * set, if so charge the init_mm (happens for pagecache usage).
1450 mem = try_get_mem_cgroup_from_mm(mm);
1458 VM_BUG_ON(css_is_removed(&mem->css));
1459 if (mem_cgroup_is_root(mem))
1464 unsigned long flags = 0;
1466 if (consume_stock(mem))
1469 ret = res_counter_charge(&mem->res, csize, &fail_res);
1471 if (!do_swap_account)
1473 ret = res_counter_charge(&mem->memsw, csize, &fail_res);
1476 /* mem+swap counter fails */
1477 res_counter_uncharge(&mem->res, csize);
1478 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
1479 mem_over_limit = mem_cgroup_from_res_counter(fail_res,
1482 /* mem counter fails */
1483 mem_over_limit = mem_cgroup_from_res_counter(fail_res,
1486 /* reduce request size and retry */
1487 if (csize > PAGE_SIZE) {
1491 if (!(gfp_mask & __GFP_WAIT))
1494 ret = mem_cgroup_hierarchical_reclaim(mem_over_limit, NULL,
1500 * try_to_free_mem_cgroup_pages() might not give us a full
1501 * picture of reclaim. Some pages are reclaimed and might be
1502 * moved to swap cache or just unmapped from the cgroup.
1503 * Check the limit again to see if the reclaim reduced the
1504 * current usage of the cgroup before giving up
1507 if (mem_cgroup_check_under_limit(mem_over_limit))
1510 if (!nr_retries--) {
1512 mem_cgroup_out_of_memory(mem_over_limit, gfp_mask);
1513 record_last_oom(mem_over_limit);
1518 if (csize > PAGE_SIZE)
1519 refill_stock(mem, csize - PAGE_SIZE);
1522 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
1523 * if they exceeds softlimit.
1525 if (page && mem_cgroup_soft_limit_check(mem))
1526 mem_cgroup_update_tree(mem, page);
1535 * Somemtimes we have to undo a charge we got by try_charge().
1536 * This function is for that and do uncharge, put css's refcnt.
1537 * gotten by try_charge().
1539 static void mem_cgroup_cancel_charge(struct mem_cgroup *mem)
1541 if (!mem_cgroup_is_root(mem)) {
1542 res_counter_uncharge(&mem->res, PAGE_SIZE);
1543 if (do_swap_account)
1544 res_counter_uncharge(&mem->memsw, PAGE_SIZE);
1550 * A helper function to get mem_cgroup from ID. must be called under
1551 * rcu_read_lock(). The caller must check css_is_removed() or some if
1552 * it's concern. (dropping refcnt from swap can be called against removed
1555 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
1557 struct cgroup_subsys_state *css;
1559 /* ID 0 is unused ID */
1562 css = css_lookup(&mem_cgroup_subsys, id);
1565 return container_of(css, struct mem_cgroup, css);
1568 struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
1570 struct mem_cgroup *mem = NULL;
1571 struct page_cgroup *pc;
1575 VM_BUG_ON(!PageLocked(page));
1577 pc = lookup_page_cgroup(page);
1578 lock_page_cgroup(pc);
1579 if (PageCgroupUsed(pc)) {
1580 mem = pc->mem_cgroup;
1581 if (mem && !css_tryget(&mem->css))
1583 } else if (PageSwapCache(page)) {
1584 ent.val = page_private(page);
1585 id = lookup_swap_cgroup(ent);
1587 mem = mem_cgroup_lookup(id);
1588 if (mem && !css_tryget(&mem->css))
1592 unlock_page_cgroup(pc);
1597 * commit a charge got by __mem_cgroup_try_charge() and makes page_cgroup to be
1598 * USED state. If already USED, uncharge and return.
1601 static void __mem_cgroup_commit_charge(struct mem_cgroup *mem,
1602 struct page_cgroup *pc,
1603 enum charge_type ctype)
1605 /* try_charge() can return NULL to *memcg, taking care of it. */
1609 lock_page_cgroup(pc);
1610 if (unlikely(PageCgroupUsed(pc))) {
1611 unlock_page_cgroup(pc);
1612 mem_cgroup_cancel_charge(mem);
1616 pc->mem_cgroup = mem;
1618 * We access a page_cgroup asynchronously without lock_page_cgroup().
1619 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
1620 * is accessed after testing USED bit. To make pc->mem_cgroup visible
1621 * before USED bit, we need memory barrier here.
1622 * See mem_cgroup_add_lru_list(), etc.
1626 case MEM_CGROUP_CHARGE_TYPE_CACHE:
1627 case MEM_CGROUP_CHARGE_TYPE_SHMEM:
1628 SetPageCgroupCache(pc);
1629 SetPageCgroupUsed(pc);
1631 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
1632 ClearPageCgroupCache(pc);
1633 SetPageCgroupUsed(pc);
1639 mem_cgroup_charge_statistics(mem, pc, true);
1641 unlock_page_cgroup(pc);
1645 * __mem_cgroup_move_account - move account of the page
1646 * @pc: page_cgroup of the page.
1647 * @from: mem_cgroup which the page is moved from.
1648 * @to: mem_cgroup which the page is moved to. @from != @to.
1650 * The caller must confirm following.
1651 * - page is not on LRU (isolate_page() is useful.)
1652 * - the pc is locked, used, and ->mem_cgroup points to @from.
1654 * This function does "uncharge" from old cgroup but doesn't do "charge" to
1655 * new cgroup. It should be done by a caller.
1658 static void __mem_cgroup_move_account(struct page_cgroup *pc,
1659 struct mem_cgroup *from, struct mem_cgroup *to)
1663 struct mem_cgroup_stat *stat;
1664 struct mem_cgroup_stat_cpu *cpustat;
1666 VM_BUG_ON(from == to);
1667 VM_BUG_ON(PageLRU(pc->page));
1668 VM_BUG_ON(!PageCgroupLocked(pc));
1669 VM_BUG_ON(!PageCgroupUsed(pc));
1670 VM_BUG_ON(pc->mem_cgroup != from);
1672 if (!mem_cgroup_is_root(from))
1673 res_counter_uncharge(&from->res, PAGE_SIZE);
1674 mem_cgroup_charge_statistics(from, pc, false);
1677 if (page_mapped(page) && !PageAnon(page)) {
1678 cpu = smp_processor_id();
1679 /* Update mapped_file data for mem_cgroup "from" */
1681 cpustat = &stat->cpustat[cpu];
1682 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_FILE_MAPPED,
1685 /* Update mapped_file data for mem_cgroup "to" */
1687 cpustat = &stat->cpustat[cpu];
1688 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_FILE_MAPPED,
1692 if (do_swap_account && !mem_cgroup_is_root(from))
1693 res_counter_uncharge(&from->memsw, PAGE_SIZE);
1694 css_put(&from->css);
1697 pc->mem_cgroup = to;
1698 mem_cgroup_charge_statistics(to, pc, true);
1700 * We charges against "to" which may not have any tasks. Then, "to"
1701 * can be under rmdir(). But in current implementation, caller of
1702 * this function is just force_empty() and move charge, so it's
1703 * garanteed that "to" is never removed. So, we don't check rmdir
1709 * check whether the @pc is valid for moving account and call
1710 * __mem_cgroup_move_account()
1712 static int mem_cgroup_move_account(struct page_cgroup *pc,
1713 struct mem_cgroup *from, struct mem_cgroup *to)
1716 lock_page_cgroup(pc);
1717 if (PageCgroupUsed(pc) && pc->mem_cgroup == from) {
1718 __mem_cgroup_move_account(pc, from, to);
1721 unlock_page_cgroup(pc);
1726 * move charges to its parent.
1729 static int mem_cgroup_move_parent(struct page_cgroup *pc,
1730 struct mem_cgroup *child,
1733 struct page *page = pc->page;
1734 struct cgroup *cg = child->css.cgroup;
1735 struct cgroup *pcg = cg->parent;
1736 struct mem_cgroup *parent;
1744 if (!get_page_unless_zero(page))
1746 if (isolate_lru_page(page))
1749 parent = mem_cgroup_from_cont(pcg);
1750 ret = __mem_cgroup_try_charge(NULL, gfp_mask, &parent, false, page);
1754 ret = mem_cgroup_move_account(pc, child, parent);
1756 css_put(&parent->css); /* drop extra refcnt by try_charge() */
1758 mem_cgroup_cancel_charge(parent); /* does css_put */
1760 putback_lru_page(page);
1768 * Charge the memory controller for page usage.
1770 * 0 if the charge was successful
1771 * < 0 if the cgroup is over its limit
1773 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
1774 gfp_t gfp_mask, enum charge_type ctype,
1775 struct mem_cgroup *memcg)
1777 struct mem_cgroup *mem;
1778 struct page_cgroup *pc;
1781 pc = lookup_page_cgroup(page);
1782 /* can happen at boot */
1788 ret = __mem_cgroup_try_charge(mm, gfp_mask, &mem, true, page);
1792 __mem_cgroup_commit_charge(mem, pc, ctype);
1796 int mem_cgroup_newpage_charge(struct page *page,
1797 struct mm_struct *mm, gfp_t gfp_mask)
1799 if (mem_cgroup_disabled())
1801 if (PageCompound(page))
1804 * If already mapped, we don't have to account.
1805 * If page cache, page->mapping has address_space.
1806 * But page->mapping may have out-of-use anon_vma pointer,
1807 * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
1810 if (page_mapped(page) || (page->mapping && !PageAnon(page)))
1814 return mem_cgroup_charge_common(page, mm, gfp_mask,
1815 MEM_CGROUP_CHARGE_TYPE_MAPPED, NULL);
1819 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
1820 enum charge_type ctype);
1822 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
1825 struct mem_cgroup *mem = NULL;
1828 if (mem_cgroup_disabled())
1830 if (PageCompound(page))
1833 * Corner case handling. This is called from add_to_page_cache()
1834 * in usual. But some FS (shmem) precharges this page before calling it
1835 * and call add_to_page_cache() with GFP_NOWAIT.
1837 * For GFP_NOWAIT case, the page may be pre-charged before calling
1838 * add_to_page_cache(). (See shmem.c) check it here and avoid to call
1839 * charge twice. (It works but has to pay a bit larger cost.)
1840 * And when the page is SwapCache, it should take swap information
1841 * into account. This is under lock_page() now.
1843 if (!(gfp_mask & __GFP_WAIT)) {
1844 struct page_cgroup *pc;
1847 pc = lookup_page_cgroup(page);
1850 lock_page_cgroup(pc);
1851 if (PageCgroupUsed(pc)) {
1852 unlock_page_cgroup(pc);
1855 unlock_page_cgroup(pc);
1858 if (unlikely(!mm && !mem))
1861 if (page_is_file_cache(page))
1862 return mem_cgroup_charge_common(page, mm, gfp_mask,
1863 MEM_CGROUP_CHARGE_TYPE_CACHE, NULL);
1866 if (PageSwapCache(page)) {
1867 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
1869 __mem_cgroup_commit_charge_swapin(page, mem,
1870 MEM_CGROUP_CHARGE_TYPE_SHMEM);
1872 ret = mem_cgroup_charge_common(page, mm, gfp_mask,
1873 MEM_CGROUP_CHARGE_TYPE_SHMEM, mem);
1879 * While swap-in, try_charge -> commit or cancel, the page is locked.
1880 * And when try_charge() successfully returns, one refcnt to memcg without
1881 * struct page_cgroup is acquired. This refcnt will be consumed by
1882 * "commit()" or removed by "cancel()"
1884 int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
1886 gfp_t mask, struct mem_cgroup **ptr)
1888 struct mem_cgroup *mem;
1891 if (mem_cgroup_disabled())
1894 if (!do_swap_account)
1897 * A racing thread's fault, or swapoff, may have already updated
1898 * the pte, and even removed page from swap cache: in those cases
1899 * do_swap_page()'s pte_same() test will fail; but there's also a
1900 * KSM case which does need to charge the page.
1902 if (!PageSwapCache(page))
1904 mem = try_get_mem_cgroup_from_page(page);
1908 ret = __mem_cgroup_try_charge(NULL, mask, ptr, true, page);
1909 /* drop extra refcnt from tryget */
1915 return __mem_cgroup_try_charge(mm, mask, ptr, true, page);
1919 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
1920 enum charge_type ctype)
1922 struct page_cgroup *pc;
1924 if (mem_cgroup_disabled())
1928 cgroup_exclude_rmdir(&ptr->css);
1929 pc = lookup_page_cgroup(page);
1930 mem_cgroup_lru_del_before_commit_swapcache(page);
1931 __mem_cgroup_commit_charge(ptr, pc, ctype);
1932 mem_cgroup_lru_add_after_commit_swapcache(page);
1934 * Now swap is on-memory. This means this page may be
1935 * counted both as mem and swap....double count.
1936 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
1937 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
1938 * may call delete_from_swap_cache() before reach here.
1940 if (do_swap_account && PageSwapCache(page)) {
1941 swp_entry_t ent = {.val = page_private(page)};
1943 struct mem_cgroup *memcg;
1945 id = swap_cgroup_record(ent, 0);
1947 memcg = mem_cgroup_lookup(id);
1950 * This recorded memcg can be obsolete one. So, avoid
1951 * calling css_tryget
1953 if (!mem_cgroup_is_root(memcg))
1954 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
1955 mem_cgroup_swap_statistics(memcg, false);
1956 mem_cgroup_put(memcg);
1961 * At swapin, we may charge account against cgroup which has no tasks.
1962 * So, rmdir()->pre_destroy() can be called while we do this charge.
1963 * In that case, we need to call pre_destroy() again. check it here.
1965 cgroup_release_and_wakeup_rmdir(&ptr->css);
1968 void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
1970 __mem_cgroup_commit_charge_swapin(page, ptr,
1971 MEM_CGROUP_CHARGE_TYPE_MAPPED);
1974 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *mem)
1976 if (mem_cgroup_disabled())
1980 mem_cgroup_cancel_charge(mem);
1984 __do_uncharge(struct mem_cgroup *mem, const enum charge_type ctype)
1986 struct memcg_batch_info *batch = NULL;
1987 bool uncharge_memsw = true;
1988 /* If swapout, usage of swap doesn't decrease */
1989 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
1990 uncharge_memsw = false;
1992 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
1993 * In those cases, all pages freed continously can be expected to be in
1994 * the same cgroup and we have chance to coalesce uncharges.
1995 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
1996 * because we want to do uncharge as soon as possible.
1998 if (!current->memcg_batch.do_batch || test_thread_flag(TIF_MEMDIE))
1999 goto direct_uncharge;
2001 batch = ¤t->memcg_batch;
2003 * In usual, we do css_get() when we remember memcg pointer.
2004 * But in this case, we keep res->usage until end of a series of
2005 * uncharges. Then, it's ok to ignore memcg's refcnt.
2010 * In typical case, batch->memcg == mem. This means we can
2011 * merge a series of uncharges to an uncharge of res_counter.
2012 * If not, we uncharge res_counter ony by one.
2014 if (batch->memcg != mem)
2015 goto direct_uncharge;
2016 /* remember freed charge and uncharge it later */
2017 batch->bytes += PAGE_SIZE;
2019 batch->memsw_bytes += PAGE_SIZE;
2022 res_counter_uncharge(&mem->res, PAGE_SIZE);
2024 res_counter_uncharge(&mem->memsw, PAGE_SIZE);
2029 * uncharge if !page_mapped(page)
2031 static struct mem_cgroup *
2032 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
2034 struct page_cgroup *pc;
2035 struct mem_cgroup *mem = NULL;
2036 struct mem_cgroup_per_zone *mz;
2038 if (mem_cgroup_disabled())
2041 if (PageSwapCache(page))
2045 * Check if our page_cgroup is valid
2047 pc = lookup_page_cgroup(page);
2048 if (unlikely(!pc || !PageCgroupUsed(pc)))
2051 lock_page_cgroup(pc);
2053 mem = pc->mem_cgroup;
2055 if (!PageCgroupUsed(pc))
2059 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
2060 case MEM_CGROUP_CHARGE_TYPE_DROP:
2061 if (page_mapped(page))
2064 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
2065 if (!PageAnon(page)) { /* Shared memory */
2066 if (page->mapping && !page_is_file_cache(page))
2068 } else if (page_mapped(page)) /* Anon */
2075 if (!mem_cgroup_is_root(mem))
2076 __do_uncharge(mem, ctype);
2077 if (ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2078 mem_cgroup_swap_statistics(mem, true);
2079 mem_cgroup_charge_statistics(mem, pc, false);
2081 ClearPageCgroupUsed(pc);
2083 * pc->mem_cgroup is not cleared here. It will be accessed when it's
2084 * freed from LRU. This is safe because uncharged page is expected not
2085 * to be reused (freed soon). Exception is SwapCache, it's handled by
2086 * special functions.
2089 mz = page_cgroup_zoneinfo(pc);
2090 unlock_page_cgroup(pc);
2092 if (mem_cgroup_soft_limit_check(mem))
2093 mem_cgroup_update_tree(mem, page);
2094 /* at swapout, this memcg will be accessed to record to swap */
2095 if (ctype != MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2101 unlock_page_cgroup(pc);
2105 void mem_cgroup_uncharge_page(struct page *page)
2108 if (page_mapped(page))
2110 if (page->mapping && !PageAnon(page))
2112 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
2115 void mem_cgroup_uncharge_cache_page(struct page *page)
2117 VM_BUG_ON(page_mapped(page));
2118 VM_BUG_ON(page->mapping);
2119 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
2123 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
2124 * In that cases, pages are freed continuously and we can expect pages
2125 * are in the same memcg. All these calls itself limits the number of
2126 * pages freed at once, then uncharge_start/end() is called properly.
2127 * This may be called prural(2) times in a context,
2130 void mem_cgroup_uncharge_start(void)
2132 current->memcg_batch.do_batch++;
2133 /* We can do nest. */
2134 if (current->memcg_batch.do_batch == 1) {
2135 current->memcg_batch.memcg = NULL;
2136 current->memcg_batch.bytes = 0;
2137 current->memcg_batch.memsw_bytes = 0;
2141 void mem_cgroup_uncharge_end(void)
2143 struct memcg_batch_info *batch = ¤t->memcg_batch;
2145 if (!batch->do_batch)
2149 if (batch->do_batch) /* If stacked, do nothing. */
2155 * This "batch->memcg" is valid without any css_get/put etc...
2156 * bacause we hide charges behind us.
2159 res_counter_uncharge(&batch->memcg->res, batch->bytes);
2160 if (batch->memsw_bytes)
2161 res_counter_uncharge(&batch->memcg->memsw, batch->memsw_bytes);
2162 /* forget this pointer (for sanity check) */
2163 batch->memcg = NULL;
2168 * called after __delete_from_swap_cache() and drop "page" account.
2169 * memcg information is recorded to swap_cgroup of "ent"
2172 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
2174 struct mem_cgroup *memcg;
2175 int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
2177 if (!swapout) /* this was a swap cache but the swap is unused ! */
2178 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
2180 memcg = __mem_cgroup_uncharge_common(page, ctype);
2182 /* record memcg information */
2183 if (do_swap_account && swapout && memcg) {
2184 swap_cgroup_record(ent, css_id(&memcg->css));
2185 mem_cgroup_get(memcg);
2187 if (swapout && memcg)
2188 css_put(&memcg->css);
2192 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
2194 * called from swap_entry_free(). remove record in swap_cgroup and
2195 * uncharge "memsw" account.
2197 void mem_cgroup_uncharge_swap(swp_entry_t ent)
2199 struct mem_cgroup *memcg;
2202 if (!do_swap_account)
2205 id = swap_cgroup_record(ent, 0);
2207 memcg = mem_cgroup_lookup(id);
2210 * We uncharge this because swap is freed.
2211 * This memcg can be obsolete one. We avoid calling css_tryget
2213 if (!mem_cgroup_is_root(memcg))
2214 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
2215 mem_cgroup_swap_statistics(memcg, false);
2216 mem_cgroup_put(memcg);
2223 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
2226 int mem_cgroup_prepare_migration(struct page *page, struct mem_cgroup **ptr)
2228 struct page_cgroup *pc;
2229 struct mem_cgroup *mem = NULL;
2232 if (mem_cgroup_disabled())
2235 pc = lookup_page_cgroup(page);
2236 lock_page_cgroup(pc);
2237 if (PageCgroupUsed(pc)) {
2238 mem = pc->mem_cgroup;
2241 unlock_page_cgroup(pc);
2244 ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, &mem, false,
2252 /* remove redundant charge if migration failed*/
2253 void mem_cgroup_end_migration(struct mem_cgroup *mem,
2254 struct page *oldpage, struct page *newpage)
2256 struct page *target, *unused;
2257 struct page_cgroup *pc;
2258 enum charge_type ctype;
2262 cgroup_exclude_rmdir(&mem->css);
2263 /* at migration success, oldpage->mapping is NULL. */
2264 if (oldpage->mapping) {
2272 if (PageAnon(target))
2273 ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
2274 else if (page_is_file_cache(target))
2275 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
2277 ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
2279 /* unused page is not on radix-tree now. */
2281 __mem_cgroup_uncharge_common(unused, ctype);
2283 pc = lookup_page_cgroup(target);
2285 * __mem_cgroup_commit_charge() check PCG_USED bit of page_cgroup.
2286 * So, double-counting is effectively avoided.
2288 __mem_cgroup_commit_charge(mem, pc, ctype);
2291 * Both of oldpage and newpage are still under lock_page().
2292 * Then, we don't have to care about race in radix-tree.
2293 * But we have to be careful that this page is unmapped or not.
2295 * There is a case for !page_mapped(). At the start of
2296 * migration, oldpage was mapped. But now, it's zapped.
2297 * But we know *target* page is not freed/reused under us.
2298 * mem_cgroup_uncharge_page() does all necessary checks.
2300 if (ctype == MEM_CGROUP_CHARGE_TYPE_MAPPED)
2301 mem_cgroup_uncharge_page(target);
2303 * At migration, we may charge account against cgroup which has no tasks
2304 * So, rmdir()->pre_destroy() can be called while we do this charge.
2305 * In that case, we need to call pre_destroy() again. check it here.
2307 cgroup_release_and_wakeup_rmdir(&mem->css);
2311 * A call to try to shrink memory usage on charge failure at shmem's swapin.
2312 * Calling hierarchical_reclaim is not enough because we should update
2313 * last_oom_jiffies to prevent pagefault_out_of_memory from invoking global OOM.
2314 * Moreover considering hierarchy, we should reclaim from the mem_over_limit,
2315 * not from the memcg which this page would be charged to.
2316 * try_charge_swapin does all of these works properly.
2318 int mem_cgroup_shmem_charge_fallback(struct page *page,
2319 struct mm_struct *mm,
2322 struct mem_cgroup *mem = NULL;
2325 if (mem_cgroup_disabled())
2328 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
2330 mem_cgroup_cancel_charge_swapin(mem); /* it does !mem check */
2335 static DEFINE_MUTEX(set_limit_mutex);
2337 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
2338 unsigned long long val)
2343 int children = mem_cgroup_count_children(memcg);
2344 u64 curusage, oldusage;
2347 * For keeping hierarchical_reclaim simple, how long we should retry
2348 * is depends on callers. We set our retry-count to be function
2349 * of # of children which we should visit in this loop.
2351 retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
2353 oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
2355 while (retry_count) {
2356 if (signal_pending(current)) {
2361 * Rather than hide all in some function, I do this in
2362 * open coded manner. You see what this really does.
2363 * We have to guarantee mem->res.limit < mem->memsw.limit.
2365 mutex_lock(&set_limit_mutex);
2366 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
2367 if (memswlimit < val) {
2369 mutex_unlock(&set_limit_mutex);
2372 ret = res_counter_set_limit(&memcg->res, val);
2374 if (memswlimit == val)
2375 memcg->memsw_is_minimum = true;
2377 memcg->memsw_is_minimum = false;
2379 mutex_unlock(&set_limit_mutex);
2384 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
2385 MEM_CGROUP_RECLAIM_SHRINK);
2386 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
2387 /* Usage is reduced ? */
2388 if (curusage >= oldusage)
2391 oldusage = curusage;
2397 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
2398 unsigned long long val)
2401 u64 memlimit, oldusage, curusage;
2402 int children = mem_cgroup_count_children(memcg);
2405 /* see mem_cgroup_resize_res_limit */
2406 retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
2407 oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
2408 while (retry_count) {
2409 if (signal_pending(current)) {
2414 * Rather than hide all in some function, I do this in
2415 * open coded manner. You see what this really does.
2416 * We have to guarantee mem->res.limit < mem->memsw.limit.
2418 mutex_lock(&set_limit_mutex);
2419 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
2420 if (memlimit > val) {
2422 mutex_unlock(&set_limit_mutex);
2425 ret = res_counter_set_limit(&memcg->memsw, val);
2427 if (memlimit == val)
2428 memcg->memsw_is_minimum = true;
2430 memcg->memsw_is_minimum = false;
2432 mutex_unlock(&set_limit_mutex);
2437 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
2438 MEM_CGROUP_RECLAIM_NOSWAP |
2439 MEM_CGROUP_RECLAIM_SHRINK);
2440 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
2441 /* Usage is reduced ? */
2442 if (curusage >= oldusage)
2445 oldusage = curusage;
2450 unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
2451 gfp_t gfp_mask, int nid,
2454 unsigned long nr_reclaimed = 0;
2455 struct mem_cgroup_per_zone *mz, *next_mz = NULL;
2456 unsigned long reclaimed;
2458 struct mem_cgroup_tree_per_zone *mctz;
2459 unsigned long long excess;
2464 mctz = soft_limit_tree_node_zone(nid, zid);
2466 * This loop can run a while, specially if mem_cgroup's continuously
2467 * keep exceeding their soft limit and putting the system under
2474 mz = mem_cgroup_largest_soft_limit_node(mctz);
2478 reclaimed = mem_cgroup_hierarchical_reclaim(mz->mem, zone,
2480 MEM_CGROUP_RECLAIM_SOFT);
2481 nr_reclaimed += reclaimed;
2482 spin_lock(&mctz->lock);
2485 * If we failed to reclaim anything from this memory cgroup
2486 * it is time to move on to the next cgroup
2492 * Loop until we find yet another one.
2494 * By the time we get the soft_limit lock
2495 * again, someone might have aded the
2496 * group back on the RB tree. Iterate to
2497 * make sure we get a different mem.
2498 * mem_cgroup_largest_soft_limit_node returns
2499 * NULL if no other cgroup is present on
2503 __mem_cgroup_largest_soft_limit_node(mctz);
2504 if (next_mz == mz) {
2505 css_put(&next_mz->mem->css);
2507 } else /* next_mz == NULL or other memcg */
2511 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
2512 excess = res_counter_soft_limit_excess(&mz->mem->res);
2514 * One school of thought says that we should not add
2515 * back the node to the tree if reclaim returns 0.
2516 * But our reclaim could return 0, simply because due
2517 * to priority we are exposing a smaller subset of
2518 * memory to reclaim from. Consider this as a longer
2521 /* If excess == 0, no tree ops */
2522 __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
2523 spin_unlock(&mctz->lock);
2524 css_put(&mz->mem->css);
2527 * Could not reclaim anything and there are no more
2528 * mem cgroups to try or we seem to be looping without
2529 * reclaiming anything.
2531 if (!nr_reclaimed &&
2533 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
2535 } while (!nr_reclaimed);
2537 css_put(&next_mz->mem->css);
2538 return nr_reclaimed;
2542 * This routine traverse page_cgroup in given list and drop them all.
2543 * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
2545 static int mem_cgroup_force_empty_list(struct mem_cgroup *mem,
2546 int node, int zid, enum lru_list lru)
2549 struct mem_cgroup_per_zone *mz;
2550 struct page_cgroup *pc, *busy;
2551 unsigned long flags, loop;
2552 struct list_head *list;
2555 zone = &NODE_DATA(node)->node_zones[zid];
2556 mz = mem_cgroup_zoneinfo(mem, node, zid);
2557 list = &mz->lists[lru];
2559 loop = MEM_CGROUP_ZSTAT(mz, lru);
2560 /* give some margin against EBUSY etc...*/
2565 spin_lock_irqsave(&zone->lru_lock, flags);
2566 if (list_empty(list)) {
2567 spin_unlock_irqrestore(&zone->lru_lock, flags);
2570 pc = list_entry(list->prev, struct page_cgroup, lru);
2572 list_move(&pc->lru, list);
2574 spin_unlock_irqrestore(&zone->lru_lock, flags);
2577 spin_unlock_irqrestore(&zone->lru_lock, flags);
2579 ret = mem_cgroup_move_parent(pc, mem, GFP_KERNEL);
2583 if (ret == -EBUSY || ret == -EINVAL) {
2584 /* found lock contention or "pc" is obsolete. */
2591 if (!ret && !list_empty(list))
2597 * make mem_cgroup's charge to be 0 if there is no task.
2598 * This enables deleting this mem_cgroup.
2600 static int mem_cgroup_force_empty(struct mem_cgroup *mem, bool free_all)
2603 int node, zid, shrink;
2604 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
2605 struct cgroup *cgrp = mem->css.cgroup;
2610 /* should free all ? */
2616 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
2619 if (signal_pending(current))
2621 /* This is for making all *used* pages to be on LRU. */
2622 lru_add_drain_all();
2623 drain_all_stock_sync();
2625 for_each_node_state(node, N_HIGH_MEMORY) {
2626 for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
2629 ret = mem_cgroup_force_empty_list(mem,
2638 /* it seems parent cgroup doesn't have enough mem */
2642 /* "ret" should also be checked to ensure all lists are empty. */
2643 } while (mem->res.usage > 0 || ret);
2649 /* returns EBUSY if there is a task or if we come here twice. */
2650 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
2654 /* we call try-to-free pages for make this cgroup empty */
2655 lru_add_drain_all();
2656 /* try to free all pages in this cgroup */
2658 while (nr_retries && mem->res.usage > 0) {
2661 if (signal_pending(current)) {
2665 progress = try_to_free_mem_cgroup_pages(mem, GFP_KERNEL,
2666 false, get_swappiness(mem));
2669 /* maybe some writeback is necessary */
2670 congestion_wait(BLK_RW_ASYNC, HZ/10);
2675 /* try move_account...there may be some *locked* pages. */
2679 int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
2681 return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
2685 static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
2687 return mem_cgroup_from_cont(cont)->use_hierarchy;
2690 static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
2694 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
2695 struct cgroup *parent = cont->parent;
2696 struct mem_cgroup *parent_mem = NULL;
2699 parent_mem = mem_cgroup_from_cont(parent);
2703 * If parent's use_hierarchy is set, we can't make any modifications
2704 * in the child subtrees. If it is unset, then the change can
2705 * occur, provided the current cgroup has no children.
2707 * For the root cgroup, parent_mem is NULL, we allow value to be
2708 * set if there are no children.
2710 if ((!parent_mem || !parent_mem->use_hierarchy) &&
2711 (val == 1 || val == 0)) {
2712 if (list_empty(&cont->children))
2713 mem->use_hierarchy = val;
2723 struct mem_cgroup_idx_data {
2725 enum mem_cgroup_stat_index idx;
2729 mem_cgroup_get_idx_stat(struct mem_cgroup *mem, void *data)
2731 struct mem_cgroup_idx_data *d = data;
2732 d->val += mem_cgroup_read_stat(&mem->stat, d->idx);
2737 mem_cgroup_get_recursive_idx_stat(struct mem_cgroup *mem,
2738 enum mem_cgroup_stat_index idx, s64 *val)
2740 struct mem_cgroup_idx_data d;
2743 mem_cgroup_walk_tree(mem, &d, mem_cgroup_get_idx_stat);
2747 static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
2749 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
2753 type = MEMFILE_TYPE(cft->private);
2754 name = MEMFILE_ATTR(cft->private);
2757 if (name == RES_USAGE && mem_cgroup_is_root(mem)) {
2758 mem_cgroup_get_recursive_idx_stat(mem,
2759 MEM_CGROUP_STAT_CACHE, &idx_val);
2761 mem_cgroup_get_recursive_idx_stat(mem,
2762 MEM_CGROUP_STAT_RSS, &idx_val);
2766 val = res_counter_read_u64(&mem->res, name);
2769 if (name == RES_USAGE && mem_cgroup_is_root(mem)) {
2770 mem_cgroup_get_recursive_idx_stat(mem,
2771 MEM_CGROUP_STAT_CACHE, &idx_val);
2773 mem_cgroup_get_recursive_idx_stat(mem,
2774 MEM_CGROUP_STAT_RSS, &idx_val);
2776 mem_cgroup_get_recursive_idx_stat(mem,
2777 MEM_CGROUP_STAT_SWAPOUT, &idx_val);
2781 val = res_counter_read_u64(&mem->memsw, name);
2790 * The user of this function is...
2793 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
2796 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
2798 unsigned long long val;
2801 type = MEMFILE_TYPE(cft->private);
2802 name = MEMFILE_ATTR(cft->private);
2805 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
2809 /* This function does all necessary parse...reuse it */
2810 ret = res_counter_memparse_write_strategy(buffer, &val);
2814 ret = mem_cgroup_resize_limit(memcg, val);
2816 ret = mem_cgroup_resize_memsw_limit(memcg, val);
2818 case RES_SOFT_LIMIT:
2819 ret = res_counter_memparse_write_strategy(buffer, &val);
2823 * For memsw, soft limits are hard to implement in terms
2824 * of semantics, for now, we support soft limits for
2825 * control without swap
2828 ret = res_counter_set_soft_limit(&memcg->res, val);
2833 ret = -EINVAL; /* should be BUG() ? */
2839 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
2840 unsigned long long *mem_limit, unsigned long long *memsw_limit)
2842 struct cgroup *cgroup;
2843 unsigned long long min_limit, min_memsw_limit, tmp;
2845 min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
2846 min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
2847 cgroup = memcg->css.cgroup;
2848 if (!memcg->use_hierarchy)
2851 while (cgroup->parent) {
2852 cgroup = cgroup->parent;
2853 memcg = mem_cgroup_from_cont(cgroup);
2854 if (!memcg->use_hierarchy)
2856 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
2857 min_limit = min(min_limit, tmp);
2858 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
2859 min_memsw_limit = min(min_memsw_limit, tmp);
2862 *mem_limit = min_limit;
2863 *memsw_limit = min_memsw_limit;
2867 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
2869 struct mem_cgroup *mem;
2872 mem = mem_cgroup_from_cont(cont);
2873 type = MEMFILE_TYPE(event);
2874 name = MEMFILE_ATTR(event);
2878 res_counter_reset_max(&mem->res);
2880 res_counter_reset_max(&mem->memsw);
2884 res_counter_reset_failcnt(&mem->res);
2886 res_counter_reset_failcnt(&mem->memsw);
2893 static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
2896 return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
2899 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
2900 struct cftype *cft, u64 val)
2902 struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
2904 if (val >= (1 << NR_MOVE_TYPE))
2907 * We check this value several times in both in can_attach() and
2908 * attach(), so we need cgroup lock to prevent this value from being
2912 mem->move_charge_at_immigrate = val;
2919 /* For read statistics */
2935 struct mcs_total_stat {
2936 s64 stat[NR_MCS_STAT];
2942 } memcg_stat_strings[NR_MCS_STAT] = {
2943 {"cache", "total_cache"},
2944 {"rss", "total_rss"},
2945 {"mapped_file", "total_mapped_file"},
2946 {"pgpgin", "total_pgpgin"},
2947 {"pgpgout", "total_pgpgout"},
2948 {"swap", "total_swap"},
2949 {"inactive_anon", "total_inactive_anon"},
2950 {"active_anon", "total_active_anon"},
2951 {"inactive_file", "total_inactive_file"},
2952 {"active_file", "total_active_file"},
2953 {"unevictable", "total_unevictable"}
2957 static int mem_cgroup_get_local_stat(struct mem_cgroup *mem, void *data)
2959 struct mcs_total_stat *s = data;
2963 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_CACHE);
2964 s->stat[MCS_CACHE] += val * PAGE_SIZE;
2965 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_RSS);
2966 s->stat[MCS_RSS] += val * PAGE_SIZE;
2967 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_FILE_MAPPED);
2968 s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE;
2969 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_PGPGIN_COUNT);
2970 s->stat[MCS_PGPGIN] += val;
2971 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_PGPGOUT_COUNT);
2972 s->stat[MCS_PGPGOUT] += val;
2973 if (do_swap_account) {
2974 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_SWAPOUT);
2975 s->stat[MCS_SWAP] += val * PAGE_SIZE;
2979 val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_ANON);
2980 s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
2981 val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_ANON);
2982 s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
2983 val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_FILE);
2984 s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
2985 val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_FILE);
2986 s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
2987 val = mem_cgroup_get_local_zonestat(mem, LRU_UNEVICTABLE);
2988 s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
2993 mem_cgroup_get_total_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
2995 mem_cgroup_walk_tree(mem, s, mem_cgroup_get_local_stat);
2998 static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
2999 struct cgroup_map_cb *cb)
3001 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
3002 struct mcs_total_stat mystat;
3005 memset(&mystat, 0, sizeof(mystat));
3006 mem_cgroup_get_local_stat(mem_cont, &mystat);
3008 for (i = 0; i < NR_MCS_STAT; i++) {
3009 if (i == MCS_SWAP && !do_swap_account)
3011 cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
3014 /* Hierarchical information */
3016 unsigned long long limit, memsw_limit;
3017 memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
3018 cb->fill(cb, "hierarchical_memory_limit", limit);
3019 if (do_swap_account)
3020 cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
3023 memset(&mystat, 0, sizeof(mystat));
3024 mem_cgroup_get_total_stat(mem_cont, &mystat);
3025 for (i = 0; i < NR_MCS_STAT; i++) {
3026 if (i == MCS_SWAP && !do_swap_account)
3028 cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
3031 #ifdef CONFIG_DEBUG_VM
3032 cb->fill(cb, "inactive_ratio", calc_inactive_ratio(mem_cont, NULL));
3036 struct mem_cgroup_per_zone *mz;
3037 unsigned long recent_rotated[2] = {0, 0};
3038 unsigned long recent_scanned[2] = {0, 0};
3040 for_each_online_node(nid)
3041 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
3042 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
3044 recent_rotated[0] +=
3045 mz->reclaim_stat.recent_rotated[0];
3046 recent_rotated[1] +=
3047 mz->reclaim_stat.recent_rotated[1];
3048 recent_scanned[0] +=
3049 mz->reclaim_stat.recent_scanned[0];
3050 recent_scanned[1] +=
3051 mz->reclaim_stat.recent_scanned[1];
3053 cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
3054 cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
3055 cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
3056 cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
3063 static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
3065 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3067 return get_swappiness(memcg);
3070 static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
3073 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3074 struct mem_cgroup *parent;
3079 if (cgrp->parent == NULL)
3082 parent = mem_cgroup_from_cont(cgrp->parent);
3086 /* If under hierarchy, only empty-root can set this value */
3087 if ((parent->use_hierarchy) ||
3088 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
3093 spin_lock(&memcg->reclaim_param_lock);
3094 memcg->swappiness = val;
3095 spin_unlock(&memcg->reclaim_param_lock);
3103 static struct cftype mem_cgroup_files[] = {
3105 .name = "usage_in_bytes",
3106 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
3107 .read_u64 = mem_cgroup_read,
3110 .name = "max_usage_in_bytes",
3111 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
3112 .trigger = mem_cgroup_reset,
3113 .read_u64 = mem_cgroup_read,
3116 .name = "limit_in_bytes",
3117 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
3118 .write_string = mem_cgroup_write,
3119 .read_u64 = mem_cgroup_read,
3122 .name = "soft_limit_in_bytes",
3123 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
3124 .write_string = mem_cgroup_write,
3125 .read_u64 = mem_cgroup_read,
3129 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
3130 .trigger = mem_cgroup_reset,
3131 .read_u64 = mem_cgroup_read,
3135 .read_map = mem_control_stat_show,
3138 .name = "force_empty",
3139 .trigger = mem_cgroup_force_empty_write,
3142 .name = "use_hierarchy",
3143 .write_u64 = mem_cgroup_hierarchy_write,
3144 .read_u64 = mem_cgroup_hierarchy_read,
3147 .name = "swappiness",
3148 .read_u64 = mem_cgroup_swappiness_read,
3149 .write_u64 = mem_cgroup_swappiness_write,
3152 .name = "move_charge_at_immigrate",
3153 .read_u64 = mem_cgroup_move_charge_read,
3154 .write_u64 = mem_cgroup_move_charge_write,
3158 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3159 static struct cftype memsw_cgroup_files[] = {
3161 .name = "memsw.usage_in_bytes",
3162 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
3163 .read_u64 = mem_cgroup_read,
3166 .name = "memsw.max_usage_in_bytes",
3167 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
3168 .trigger = mem_cgroup_reset,
3169 .read_u64 = mem_cgroup_read,
3172 .name = "memsw.limit_in_bytes",
3173 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
3174 .write_string = mem_cgroup_write,
3175 .read_u64 = mem_cgroup_read,
3178 .name = "memsw.failcnt",
3179 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
3180 .trigger = mem_cgroup_reset,
3181 .read_u64 = mem_cgroup_read,
3185 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
3187 if (!do_swap_account)
3189 return cgroup_add_files(cont, ss, memsw_cgroup_files,
3190 ARRAY_SIZE(memsw_cgroup_files));
3193 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
3199 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
3201 struct mem_cgroup_per_node *pn;
3202 struct mem_cgroup_per_zone *mz;
3204 int zone, tmp = node;
3206 * This routine is called against possible nodes.
3207 * But it's BUG to call kmalloc() against offline node.
3209 * TODO: this routine can waste much memory for nodes which will
3210 * never be onlined. It's better to use memory hotplug callback
3213 if (!node_state(node, N_NORMAL_MEMORY))
3215 pn = kmalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
3219 mem->info.nodeinfo[node] = pn;
3220 memset(pn, 0, sizeof(*pn));
3222 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3223 mz = &pn->zoneinfo[zone];
3225 INIT_LIST_HEAD(&mz->lists[l]);
3226 mz->usage_in_excess = 0;
3227 mz->on_tree = false;
3233 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
3235 kfree(mem->info.nodeinfo[node]);
3238 static int mem_cgroup_size(void)
3240 int cpustat_size = nr_cpu_ids * sizeof(struct mem_cgroup_stat_cpu);
3241 return sizeof(struct mem_cgroup) + cpustat_size;
3244 static struct mem_cgroup *mem_cgroup_alloc(void)
3246 struct mem_cgroup *mem;
3247 int size = mem_cgroup_size();
3249 if (size < PAGE_SIZE)
3250 mem = kmalloc(size, GFP_KERNEL);
3252 mem = vmalloc(size);
3255 memset(mem, 0, size);
3260 * At destroying mem_cgroup, references from swap_cgroup can remain.
3261 * (scanning all at force_empty is too costly...)
3263 * Instead of clearing all references at force_empty, we remember
3264 * the number of reference from swap_cgroup and free mem_cgroup when
3265 * it goes down to 0.
3267 * Removal of cgroup itself succeeds regardless of refs from swap.
3270 static void __mem_cgroup_free(struct mem_cgroup *mem)
3274 mem_cgroup_remove_from_trees(mem);
3275 free_css_id(&mem_cgroup_subsys, &mem->css);
3277 for_each_node_state(node, N_POSSIBLE)
3278 free_mem_cgroup_per_zone_info(mem, node);
3280 if (mem_cgroup_size() < PAGE_SIZE)
3286 static void mem_cgroup_get(struct mem_cgroup *mem)
3288 atomic_inc(&mem->refcnt);
3291 static void mem_cgroup_put(struct mem_cgroup *mem)
3293 if (atomic_dec_and_test(&mem->refcnt)) {
3294 struct mem_cgroup *parent = parent_mem_cgroup(mem);
3295 __mem_cgroup_free(mem);
3297 mem_cgroup_put(parent);
3302 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
3304 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem)
3306 if (!mem->res.parent)
3308 return mem_cgroup_from_res_counter(mem->res.parent, res);
3311 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3312 static void __init enable_swap_cgroup(void)
3314 if (!mem_cgroup_disabled() && really_do_swap_account)
3315 do_swap_account = 1;
3318 static void __init enable_swap_cgroup(void)
3323 static int mem_cgroup_soft_limit_tree_init(void)
3325 struct mem_cgroup_tree_per_node *rtpn;
3326 struct mem_cgroup_tree_per_zone *rtpz;
3327 int tmp, node, zone;
3329 for_each_node_state(node, N_POSSIBLE) {
3331 if (!node_state(node, N_NORMAL_MEMORY))
3333 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
3337 soft_limit_tree.rb_tree_per_node[node] = rtpn;
3339 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3340 rtpz = &rtpn->rb_tree_per_zone[zone];
3341 rtpz->rb_root = RB_ROOT;
3342 spin_lock_init(&rtpz->lock);
3348 static struct cgroup_subsys_state * __ref
3349 mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
3351 struct mem_cgroup *mem, *parent;
3352 long error = -ENOMEM;
3355 mem = mem_cgroup_alloc();
3357 return ERR_PTR(error);
3359 for_each_node_state(node, N_POSSIBLE)
3360 if (alloc_mem_cgroup_per_zone_info(mem, node))
3364 if (cont->parent == NULL) {
3366 enable_swap_cgroup();
3368 root_mem_cgroup = mem;
3369 if (mem_cgroup_soft_limit_tree_init())
3371 for_each_possible_cpu(cpu) {
3372 struct memcg_stock_pcp *stock =
3373 &per_cpu(memcg_stock, cpu);
3374 INIT_WORK(&stock->work, drain_local_stock);
3376 hotcpu_notifier(memcg_stock_cpu_callback, 0);
3379 parent = mem_cgroup_from_cont(cont->parent);
3380 mem->use_hierarchy = parent->use_hierarchy;
3383 if (parent && parent->use_hierarchy) {
3384 res_counter_init(&mem->res, &parent->res);
3385 res_counter_init(&mem->memsw, &parent->memsw);
3387 * We increment refcnt of the parent to ensure that we can
3388 * safely access it on res_counter_charge/uncharge.
3389 * This refcnt will be decremented when freeing this
3390 * mem_cgroup(see mem_cgroup_put).
3392 mem_cgroup_get(parent);
3394 res_counter_init(&mem->res, NULL);
3395 res_counter_init(&mem->memsw, NULL);
3397 mem->last_scanned_child = 0;
3398 spin_lock_init(&mem->reclaim_param_lock);
3401 mem->swappiness = get_swappiness(parent);
3402 atomic_set(&mem->refcnt, 1);
3403 mem->move_charge_at_immigrate = 0;
3406 __mem_cgroup_free(mem);
3407 root_mem_cgroup = NULL;
3408 return ERR_PTR(error);
3411 static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
3412 struct cgroup *cont)
3414 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
3416 return mem_cgroup_force_empty(mem, false);
3419 static void mem_cgroup_destroy(struct cgroup_subsys *ss,
3420 struct cgroup *cont)
3422 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
3424 mem_cgroup_put(mem);
3427 static int mem_cgroup_populate(struct cgroup_subsys *ss,
3428 struct cgroup *cont)
3432 ret = cgroup_add_files(cont, ss, mem_cgroup_files,
3433 ARRAY_SIZE(mem_cgroup_files));
3436 ret = register_memsw_files(cont, ss);
3440 /* Handlers for move charge at task migration. */
3441 static int mem_cgroup_do_precharge(void)
3444 struct mem_cgroup *mem = mc.to;
3446 ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, &mem, false, NULL);
3455 * is_target_pte_for_mc - check a pte whether it is valid for move charge
3456 * @vma: the vma the pte to be checked belongs
3457 * @addr: the address corresponding to the pte to be checked
3458 * @ptent: the pte to be checked
3459 * @target: the pointer the target page will be stored(can be NULL)
3462 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
3463 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
3464 * move charge. if @target is not NULL, the page is stored in target->page
3465 * with extra refcnt got(Callers should handle it).
3467 * Called with pte lock held.
3469 /* We add a new member later. */
3474 /* We add a new type later. */
3475 enum mc_target_type {
3476 MC_TARGET_NONE, /* not used */
3480 static int is_target_pte_for_mc(struct vm_area_struct *vma,
3481 unsigned long addr, pte_t ptent, union mc_target *target)
3484 struct page_cgroup *pc;
3486 bool move_anon = test_bit(MOVE_CHARGE_TYPE_ANON,
3487 &mc.to->move_charge_at_immigrate);
3489 if (!pte_present(ptent))
3492 page = vm_normal_page(vma, addr, ptent);
3493 if (!page || !page_mapped(page))
3496 * TODO: We don't move charges of file(including shmem/tmpfs) pages for
3499 if (!move_anon || !PageAnon(page))
3502 * TODO: We don't move charges of shared(used by multiple processes)
3505 if (page_mapcount(page) > 1)
3507 if (!get_page_unless_zero(page))
3510 pc = lookup_page_cgroup(page);
3512 * Do only loose check w/o page_cgroup lock. mem_cgroup_move_account()
3513 * checks the pc is valid or not under the lock.
3515 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
3516 ret = MC_TARGET_PAGE;
3518 target->page = page;
3521 if (!ret || !target)
3527 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
3528 unsigned long addr, unsigned long end,
3529 struct mm_walk *walk)
3531 struct vm_area_struct *vma = walk->private;
3535 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
3536 for (; addr != end; pte++, addr += PAGE_SIZE)
3537 if (is_target_pte_for_mc(vma, addr, *pte, NULL))
3538 mc.precharge++; /* increment precharge temporarily */
3539 pte_unmap_unlock(pte - 1, ptl);
3545 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
3547 unsigned long precharge;
3548 struct vm_area_struct *vma;
3550 down_read(&mm->mmap_sem);
3551 for (vma = mm->mmap; vma; vma = vma->vm_next) {
3552 struct mm_walk mem_cgroup_count_precharge_walk = {
3553 .pmd_entry = mem_cgroup_count_precharge_pte_range,
3557 if (is_vm_hugetlb_page(vma))
3559 /* TODO: We don't move charges of shmem/tmpfs pages for now. */
3560 if (vma->vm_flags & VM_SHARED)
3562 walk_page_range(vma->vm_start, vma->vm_end,
3563 &mem_cgroup_count_precharge_walk);
3565 up_read(&mm->mmap_sem);
3567 precharge = mc.precharge;
3573 #define PRECHARGE_AT_ONCE 256
3574 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
3577 int count = PRECHARGE_AT_ONCE;
3578 unsigned long precharge = mem_cgroup_count_precharge(mm);
3580 while (!ret && precharge--) {
3581 if (signal_pending(current)) {
3586 count = PRECHARGE_AT_ONCE;
3589 ret = mem_cgroup_do_precharge();
3595 static void mem_cgroup_clear_mc(void)
3597 /* we must uncharge all the leftover precharges from mc.to */
3598 while (mc.precharge) {
3599 mem_cgroup_cancel_charge(mc.to);
3606 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
3607 struct cgroup *cgroup,
3608 struct task_struct *p,
3612 struct mem_cgroup *mem = mem_cgroup_from_cont(cgroup);
3614 if (mem->move_charge_at_immigrate) {
3615 struct mm_struct *mm;
3616 struct mem_cgroup *from = mem_cgroup_from_task(p);
3618 VM_BUG_ON(from == mem);
3620 mm = get_task_mm(p);
3623 /* We move charges only when we move a owner of the mm */
3624 if (mm->owner == p) {
3627 VM_BUG_ON(mc.precharge);
3632 ret = mem_cgroup_precharge_mc(mm);
3634 mem_cgroup_clear_mc();
3641 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
3642 struct cgroup *cgroup,
3643 struct task_struct *p,
3646 mem_cgroup_clear_mc();
3649 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
3650 unsigned long addr, unsigned long end,
3651 struct mm_walk *walk)
3654 struct vm_area_struct *vma = walk->private;
3659 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
3660 for (; addr != end; addr += PAGE_SIZE) {
3661 pte_t ptent = *(pte++);
3662 union mc_target target;
3665 struct page_cgroup *pc;
3670 type = is_target_pte_for_mc(vma, addr, ptent, &target);
3672 case MC_TARGET_PAGE:
3674 if (isolate_lru_page(page))
3676 pc = lookup_page_cgroup(page);
3677 if (!mem_cgroup_move_account(pc, mc.from, mc.to)) {
3678 css_put(&mc.to->css);
3681 putback_lru_page(page);
3682 put: /* is_target_pte_for_mc() gets the page */
3689 pte_unmap_unlock(pte - 1, ptl);
3694 * We have consumed all precharges we got in can_attach().
3695 * We try charge one by one, but don't do any additional
3696 * charges to mc.to if we have failed in charge once in attach()
3699 ret = mem_cgroup_do_precharge();
3707 static void mem_cgroup_move_charge(struct mm_struct *mm)
3709 struct vm_area_struct *vma;
3711 lru_add_drain_all();
3712 down_read(&mm->mmap_sem);
3713 for (vma = mm->mmap; vma; vma = vma->vm_next) {
3715 struct mm_walk mem_cgroup_move_charge_walk = {
3716 .pmd_entry = mem_cgroup_move_charge_pte_range,
3720 if (is_vm_hugetlb_page(vma))
3722 /* TODO: We don't move charges of shmem/tmpfs pages for now. */
3723 if (vma->vm_flags & VM_SHARED)
3725 ret = walk_page_range(vma->vm_start, vma->vm_end,
3726 &mem_cgroup_move_charge_walk);
3729 * means we have consumed all precharges and failed in
3730 * doing additional charge. Just abandon here.
3734 up_read(&mm->mmap_sem);
3737 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
3738 struct cgroup *cont,
3739 struct cgroup *old_cont,
3740 struct task_struct *p,
3743 struct mm_struct *mm;
3746 /* no need to move charge */
3749 mm = get_task_mm(p);
3751 mem_cgroup_move_charge(mm);
3754 mem_cgroup_clear_mc();
3757 struct cgroup_subsys mem_cgroup_subsys = {
3759 .subsys_id = mem_cgroup_subsys_id,
3760 .create = mem_cgroup_create,
3761 .pre_destroy = mem_cgroup_pre_destroy,
3762 .destroy = mem_cgroup_destroy,
3763 .populate = mem_cgroup_populate,
3764 .can_attach = mem_cgroup_can_attach,
3765 .cancel_attach = mem_cgroup_cancel_attach,
3766 .attach = mem_cgroup_move_task,
3771 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3773 static int __init disable_swap_account(char *s)
3775 really_do_swap_account = 0;
3778 __setup("noswapaccount", disable_swap_account);