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;
256 unsigned long moved_charge;
257 struct task_struct *moving_task; /* a task moving charges */
258 wait_queue_head_t waitq; /* a waitq for other context */
260 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
264 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
265 * limit reclaim to prevent infinite loops, if they ever occur.
267 #define MEM_CGROUP_MAX_RECLAIM_LOOPS (100)
268 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS (2)
271 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
272 MEM_CGROUP_CHARGE_TYPE_MAPPED,
273 MEM_CGROUP_CHARGE_TYPE_SHMEM, /* used by page migration of shmem */
274 MEM_CGROUP_CHARGE_TYPE_FORCE, /* used by force_empty */
275 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
276 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
280 /* only for here (for easy reading.) */
281 #define PCGF_CACHE (1UL << PCG_CACHE)
282 #define PCGF_USED (1UL << PCG_USED)
283 #define PCGF_LOCK (1UL << PCG_LOCK)
284 /* Not used, but added here for completeness */
285 #define PCGF_ACCT (1UL << PCG_ACCT)
287 /* for encoding cft->private value on file */
290 #define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val))
291 #define MEMFILE_TYPE(val) (((val) >> 16) & 0xffff)
292 #define MEMFILE_ATTR(val) ((val) & 0xffff)
295 * Reclaim flags for mem_cgroup_hierarchical_reclaim
297 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
298 #define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
299 #define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
300 #define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
301 #define MEM_CGROUP_RECLAIM_SOFT_BIT 0x2
302 #define MEM_CGROUP_RECLAIM_SOFT (1 << MEM_CGROUP_RECLAIM_SOFT_BIT)
304 static void mem_cgroup_get(struct mem_cgroup *mem);
305 static void mem_cgroup_put(struct mem_cgroup *mem);
306 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem);
307 static void drain_all_stock_async(void);
309 static struct mem_cgroup_per_zone *
310 mem_cgroup_zoneinfo(struct mem_cgroup *mem, int nid, int zid)
312 return &mem->info.nodeinfo[nid]->zoneinfo[zid];
315 struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *mem)
320 static struct mem_cgroup_per_zone *
321 page_cgroup_zoneinfo(struct page_cgroup *pc)
323 struct mem_cgroup *mem = pc->mem_cgroup;
324 int nid = page_cgroup_nid(pc);
325 int zid = page_cgroup_zid(pc);
330 return mem_cgroup_zoneinfo(mem, nid, zid);
333 static struct mem_cgroup_tree_per_zone *
334 soft_limit_tree_node_zone(int nid, int zid)
336 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
339 static struct mem_cgroup_tree_per_zone *
340 soft_limit_tree_from_page(struct page *page)
342 int nid = page_to_nid(page);
343 int zid = page_zonenum(page);
345 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
349 __mem_cgroup_insert_exceeded(struct mem_cgroup *mem,
350 struct mem_cgroup_per_zone *mz,
351 struct mem_cgroup_tree_per_zone *mctz,
352 unsigned long long new_usage_in_excess)
354 struct rb_node **p = &mctz->rb_root.rb_node;
355 struct rb_node *parent = NULL;
356 struct mem_cgroup_per_zone *mz_node;
361 mz->usage_in_excess = new_usage_in_excess;
362 if (!mz->usage_in_excess)
366 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
368 if (mz->usage_in_excess < mz_node->usage_in_excess)
371 * We can't avoid mem cgroups that are over their soft
372 * limit by the same amount
374 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
377 rb_link_node(&mz->tree_node, parent, p);
378 rb_insert_color(&mz->tree_node, &mctz->rb_root);
383 __mem_cgroup_remove_exceeded(struct mem_cgroup *mem,
384 struct mem_cgroup_per_zone *mz,
385 struct mem_cgroup_tree_per_zone *mctz)
389 rb_erase(&mz->tree_node, &mctz->rb_root);
394 mem_cgroup_remove_exceeded(struct mem_cgroup *mem,
395 struct mem_cgroup_per_zone *mz,
396 struct mem_cgroup_tree_per_zone *mctz)
398 spin_lock(&mctz->lock);
399 __mem_cgroup_remove_exceeded(mem, mz, mctz);
400 spin_unlock(&mctz->lock);
403 static bool mem_cgroup_soft_limit_check(struct mem_cgroup *mem)
408 struct mem_cgroup_stat_cpu *cpustat;
411 cpustat = &mem->stat.cpustat[cpu];
412 val = __mem_cgroup_stat_read_local(cpustat, MEM_CGROUP_STAT_EVENTS);
413 if (unlikely(val > SOFTLIMIT_EVENTS_THRESH)) {
414 __mem_cgroup_stat_reset_safe(cpustat, MEM_CGROUP_STAT_EVENTS);
421 static void mem_cgroup_update_tree(struct mem_cgroup *mem, struct page *page)
423 unsigned long long excess;
424 struct mem_cgroup_per_zone *mz;
425 struct mem_cgroup_tree_per_zone *mctz;
426 int nid = page_to_nid(page);
427 int zid = page_zonenum(page);
428 mctz = soft_limit_tree_from_page(page);
431 * Necessary to update all ancestors when hierarchy is used.
432 * because their event counter is not touched.
434 for (; mem; mem = parent_mem_cgroup(mem)) {
435 mz = mem_cgroup_zoneinfo(mem, nid, zid);
436 excess = res_counter_soft_limit_excess(&mem->res);
438 * We have to update the tree if mz is on RB-tree or
439 * mem is over its softlimit.
441 if (excess || mz->on_tree) {
442 spin_lock(&mctz->lock);
443 /* if on-tree, remove it */
445 __mem_cgroup_remove_exceeded(mem, mz, mctz);
447 * Insert again. mz->usage_in_excess will be updated.
448 * If excess is 0, no tree ops.
450 __mem_cgroup_insert_exceeded(mem, mz, mctz, excess);
451 spin_unlock(&mctz->lock);
456 static void mem_cgroup_remove_from_trees(struct mem_cgroup *mem)
459 struct mem_cgroup_per_zone *mz;
460 struct mem_cgroup_tree_per_zone *mctz;
462 for_each_node_state(node, N_POSSIBLE) {
463 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
464 mz = mem_cgroup_zoneinfo(mem, node, zone);
465 mctz = soft_limit_tree_node_zone(node, zone);
466 mem_cgroup_remove_exceeded(mem, mz, mctz);
471 static inline unsigned long mem_cgroup_get_excess(struct mem_cgroup *mem)
473 return res_counter_soft_limit_excess(&mem->res) >> PAGE_SHIFT;
476 static struct mem_cgroup_per_zone *
477 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
479 struct rb_node *rightmost = NULL;
480 struct mem_cgroup_per_zone *mz;
484 rightmost = rb_last(&mctz->rb_root);
486 goto done; /* Nothing to reclaim from */
488 mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
490 * Remove the node now but someone else can add it back,
491 * we will to add it back at the end of reclaim to its correct
492 * position in the tree.
494 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
495 if (!res_counter_soft_limit_excess(&mz->mem->res) ||
496 !css_tryget(&mz->mem->css))
502 static struct mem_cgroup_per_zone *
503 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
505 struct mem_cgroup_per_zone *mz;
507 spin_lock(&mctz->lock);
508 mz = __mem_cgroup_largest_soft_limit_node(mctz);
509 spin_unlock(&mctz->lock);
513 static void mem_cgroup_swap_statistics(struct mem_cgroup *mem,
516 int val = (charge) ? 1 : -1;
517 struct mem_cgroup_stat *stat = &mem->stat;
518 struct mem_cgroup_stat_cpu *cpustat;
521 cpustat = &stat->cpustat[cpu];
522 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_SWAPOUT, val);
526 static void mem_cgroup_charge_statistics(struct mem_cgroup *mem,
527 struct page_cgroup *pc,
530 int val = (charge) ? 1 : -1;
531 struct mem_cgroup_stat *stat = &mem->stat;
532 struct mem_cgroup_stat_cpu *cpustat;
535 cpustat = &stat->cpustat[cpu];
536 if (PageCgroupCache(pc))
537 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_CACHE, val);
539 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_RSS, val);
542 __mem_cgroup_stat_add_safe(cpustat,
543 MEM_CGROUP_STAT_PGPGIN_COUNT, 1);
545 __mem_cgroup_stat_add_safe(cpustat,
546 MEM_CGROUP_STAT_PGPGOUT_COUNT, 1);
547 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_EVENTS, 1);
551 static unsigned long mem_cgroup_get_local_zonestat(struct mem_cgroup *mem,
555 struct mem_cgroup_per_zone *mz;
558 for_each_online_node(nid)
559 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
560 mz = mem_cgroup_zoneinfo(mem, nid, zid);
561 total += MEM_CGROUP_ZSTAT(mz, idx);
566 static struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
568 return container_of(cgroup_subsys_state(cont,
569 mem_cgroup_subsys_id), struct mem_cgroup,
573 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
576 * mm_update_next_owner() may clear mm->owner to NULL
577 * if it races with swapoff, page migration, etc.
578 * So this can be called with p == NULL.
583 return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
584 struct mem_cgroup, css);
587 static struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
589 struct mem_cgroup *mem = NULL;
594 * Because we have no locks, mm->owner's may be being moved to other
595 * cgroup. We use css_tryget() here even if this looks
596 * pessimistic (rather than adding locks here).
600 mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
603 } while (!css_tryget(&mem->css));
609 * Call callback function against all cgroup under hierarchy tree.
611 static int mem_cgroup_walk_tree(struct mem_cgroup *root, void *data,
612 int (*func)(struct mem_cgroup *, void *))
614 int found, ret, nextid;
615 struct cgroup_subsys_state *css;
616 struct mem_cgroup *mem;
618 if (!root->use_hierarchy)
619 return (*func)(root, data);
627 css = css_get_next(&mem_cgroup_subsys, nextid, &root->css,
629 if (css && css_tryget(css))
630 mem = container_of(css, struct mem_cgroup, css);
634 ret = (*func)(mem, data);
638 } while (!ret && css);
643 static inline bool mem_cgroup_is_root(struct mem_cgroup *mem)
645 return (mem == root_mem_cgroup);
649 * Following LRU functions are allowed to be used without PCG_LOCK.
650 * Operations are called by routine of global LRU independently from memcg.
651 * What we have to take care of here is validness of pc->mem_cgroup.
653 * Changes to pc->mem_cgroup happens when
656 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
657 * It is added to LRU before charge.
658 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
659 * When moving account, the page is not on LRU. It's isolated.
662 void mem_cgroup_del_lru_list(struct page *page, enum lru_list lru)
664 struct page_cgroup *pc;
665 struct mem_cgroup_per_zone *mz;
667 if (mem_cgroup_disabled())
669 pc = lookup_page_cgroup(page);
670 /* can happen while we handle swapcache. */
671 if (!TestClearPageCgroupAcctLRU(pc))
673 VM_BUG_ON(!pc->mem_cgroup);
675 * We don't check PCG_USED bit. It's cleared when the "page" is finally
676 * removed from global LRU.
678 mz = page_cgroup_zoneinfo(pc);
679 MEM_CGROUP_ZSTAT(mz, lru) -= 1;
680 if (mem_cgroup_is_root(pc->mem_cgroup))
682 VM_BUG_ON(list_empty(&pc->lru));
683 list_del_init(&pc->lru);
687 void mem_cgroup_del_lru(struct page *page)
689 mem_cgroup_del_lru_list(page, page_lru(page));
692 void mem_cgroup_rotate_lru_list(struct page *page, enum lru_list lru)
694 struct mem_cgroup_per_zone *mz;
695 struct page_cgroup *pc;
697 if (mem_cgroup_disabled())
700 pc = lookup_page_cgroup(page);
702 * Used bit is set without atomic ops but after smp_wmb().
703 * For making pc->mem_cgroup visible, insert smp_rmb() here.
706 /* unused or root page is not rotated. */
707 if (!PageCgroupUsed(pc) || mem_cgroup_is_root(pc->mem_cgroup))
709 mz = page_cgroup_zoneinfo(pc);
710 list_move(&pc->lru, &mz->lists[lru]);
713 void mem_cgroup_add_lru_list(struct page *page, enum lru_list lru)
715 struct page_cgroup *pc;
716 struct mem_cgroup_per_zone *mz;
718 if (mem_cgroup_disabled())
720 pc = lookup_page_cgroup(page);
721 VM_BUG_ON(PageCgroupAcctLRU(pc));
723 * Used bit is set without atomic ops but after smp_wmb().
724 * For making pc->mem_cgroup visible, insert smp_rmb() here.
727 if (!PageCgroupUsed(pc))
730 mz = page_cgroup_zoneinfo(pc);
731 MEM_CGROUP_ZSTAT(mz, lru) += 1;
732 SetPageCgroupAcctLRU(pc);
733 if (mem_cgroup_is_root(pc->mem_cgroup))
735 list_add(&pc->lru, &mz->lists[lru]);
739 * At handling SwapCache, pc->mem_cgroup may be changed while it's linked to
740 * lru because the page may.be reused after it's fully uncharged (because of
741 * SwapCache behavior).To handle that, unlink page_cgroup from LRU when charge
742 * it again. This function is only used to charge SwapCache. It's done under
743 * lock_page and expected that zone->lru_lock is never held.
745 static void mem_cgroup_lru_del_before_commit_swapcache(struct page *page)
748 struct zone *zone = page_zone(page);
749 struct page_cgroup *pc = lookup_page_cgroup(page);
751 spin_lock_irqsave(&zone->lru_lock, flags);
753 * Forget old LRU when this page_cgroup is *not* used. This Used bit
754 * is guarded by lock_page() because the page is SwapCache.
756 if (!PageCgroupUsed(pc))
757 mem_cgroup_del_lru_list(page, page_lru(page));
758 spin_unlock_irqrestore(&zone->lru_lock, flags);
761 static void mem_cgroup_lru_add_after_commit_swapcache(struct page *page)
764 struct zone *zone = page_zone(page);
765 struct page_cgroup *pc = lookup_page_cgroup(page);
767 spin_lock_irqsave(&zone->lru_lock, flags);
768 /* link when the page is linked to LRU but page_cgroup isn't */
769 if (PageLRU(page) && !PageCgroupAcctLRU(pc))
770 mem_cgroup_add_lru_list(page, page_lru(page));
771 spin_unlock_irqrestore(&zone->lru_lock, flags);
775 void mem_cgroup_move_lists(struct page *page,
776 enum lru_list from, enum lru_list to)
778 if (mem_cgroup_disabled())
780 mem_cgroup_del_lru_list(page, from);
781 mem_cgroup_add_lru_list(page, to);
784 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *mem)
787 struct mem_cgroup *curr = NULL;
791 curr = try_get_mem_cgroup_from_mm(task->mm);
797 * We should check use_hierarchy of "mem" not "curr". Because checking
798 * use_hierarchy of "curr" here make this function true if hierarchy is
799 * enabled in "curr" and "curr" is a child of "mem" in *cgroup*
800 * hierarchy(even if use_hierarchy is disabled in "mem").
802 if (mem->use_hierarchy)
803 ret = css_is_ancestor(&curr->css, &mem->css);
811 * prev_priority control...this will be used in memory reclaim path.
813 int mem_cgroup_get_reclaim_priority(struct mem_cgroup *mem)
817 spin_lock(&mem->reclaim_param_lock);
818 prev_priority = mem->prev_priority;
819 spin_unlock(&mem->reclaim_param_lock);
821 return prev_priority;
824 void mem_cgroup_note_reclaim_priority(struct mem_cgroup *mem, int priority)
826 spin_lock(&mem->reclaim_param_lock);
827 if (priority < mem->prev_priority)
828 mem->prev_priority = priority;
829 spin_unlock(&mem->reclaim_param_lock);
832 void mem_cgroup_record_reclaim_priority(struct mem_cgroup *mem, int priority)
834 spin_lock(&mem->reclaim_param_lock);
835 mem->prev_priority = priority;
836 spin_unlock(&mem->reclaim_param_lock);
839 static int calc_inactive_ratio(struct mem_cgroup *memcg, unsigned long *present_pages)
841 unsigned long active;
842 unsigned long inactive;
844 unsigned long inactive_ratio;
846 inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_ANON);
847 active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_ANON);
849 gb = (inactive + active) >> (30 - PAGE_SHIFT);
851 inactive_ratio = int_sqrt(10 * gb);
856 present_pages[0] = inactive;
857 present_pages[1] = active;
860 return inactive_ratio;
863 int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg)
865 unsigned long active;
866 unsigned long inactive;
867 unsigned long present_pages[2];
868 unsigned long inactive_ratio;
870 inactive_ratio = calc_inactive_ratio(memcg, present_pages);
872 inactive = present_pages[0];
873 active = present_pages[1];
875 if (inactive * inactive_ratio < active)
881 int mem_cgroup_inactive_file_is_low(struct mem_cgroup *memcg)
883 unsigned long active;
884 unsigned long inactive;
886 inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_FILE);
887 active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_FILE);
889 return (active > inactive);
892 unsigned long mem_cgroup_zone_nr_pages(struct mem_cgroup *memcg,
896 int nid = zone->zone_pgdat->node_id;
897 int zid = zone_idx(zone);
898 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
900 return MEM_CGROUP_ZSTAT(mz, lru);
903 struct zone_reclaim_stat *mem_cgroup_get_reclaim_stat(struct mem_cgroup *memcg,
906 int nid = zone->zone_pgdat->node_id;
907 int zid = zone_idx(zone);
908 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
910 return &mz->reclaim_stat;
913 struct zone_reclaim_stat *
914 mem_cgroup_get_reclaim_stat_from_page(struct page *page)
916 struct page_cgroup *pc;
917 struct mem_cgroup_per_zone *mz;
919 if (mem_cgroup_disabled())
922 pc = lookup_page_cgroup(page);
924 * Used bit is set without atomic ops but after smp_wmb().
925 * For making pc->mem_cgroup visible, insert smp_rmb() here.
928 if (!PageCgroupUsed(pc))
931 mz = page_cgroup_zoneinfo(pc);
935 return &mz->reclaim_stat;
938 unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan,
939 struct list_head *dst,
940 unsigned long *scanned, int order,
941 int mode, struct zone *z,
942 struct mem_cgroup *mem_cont,
943 int active, int file)
945 unsigned long nr_taken = 0;
949 struct list_head *src;
950 struct page_cgroup *pc, *tmp;
951 int nid = z->zone_pgdat->node_id;
952 int zid = zone_idx(z);
953 struct mem_cgroup_per_zone *mz;
954 int lru = LRU_FILE * file + active;
958 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
959 src = &mz->lists[lru];
962 list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
963 if (scan >= nr_to_scan)
967 if (unlikely(!PageCgroupUsed(pc)))
969 if (unlikely(!PageLRU(page)))
973 ret = __isolate_lru_page(page, mode, file);
976 list_move(&page->lru, dst);
977 mem_cgroup_del_lru(page);
981 /* we don't affect global LRU but rotate in our LRU */
982 mem_cgroup_rotate_lru_list(page, page_lru(page));
993 #define mem_cgroup_from_res_counter(counter, member) \
994 container_of(counter, struct mem_cgroup, member)
996 static bool mem_cgroup_check_under_limit(struct mem_cgroup *mem)
998 if (do_swap_account) {
999 if (res_counter_check_under_limit(&mem->res) &&
1000 res_counter_check_under_limit(&mem->memsw))
1003 if (res_counter_check_under_limit(&mem->res))
1008 static unsigned int get_swappiness(struct mem_cgroup *memcg)
1010 struct cgroup *cgrp = memcg->css.cgroup;
1011 unsigned int swappiness;
1014 if (cgrp->parent == NULL)
1015 return vm_swappiness;
1017 spin_lock(&memcg->reclaim_param_lock);
1018 swappiness = memcg->swappiness;
1019 spin_unlock(&memcg->reclaim_param_lock);
1024 static int mem_cgroup_count_children_cb(struct mem_cgroup *mem, void *data)
1032 * mem_cgroup_print_mem_info: Called from OOM with tasklist_lock held in read mode.
1033 * @memcg: The memory cgroup that went over limit
1034 * @p: Task that is going to be killed
1036 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1039 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1041 struct cgroup *task_cgrp;
1042 struct cgroup *mem_cgrp;
1044 * Need a buffer in BSS, can't rely on allocations. The code relies
1045 * on the assumption that OOM is serialized for memory controller.
1046 * If this assumption is broken, revisit this code.
1048 static char memcg_name[PATH_MAX];
1057 mem_cgrp = memcg->css.cgroup;
1058 task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1060 ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1063 * Unfortunately, we are unable to convert to a useful name
1064 * But we'll still print out the usage information
1071 printk(KERN_INFO "Task in %s killed", memcg_name);
1074 ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1082 * Continues from above, so we don't need an KERN_ level
1084 printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
1087 printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
1088 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1089 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1090 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1091 printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
1093 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1094 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1095 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1099 * This function returns the number of memcg under hierarchy tree. Returns
1100 * 1(self count) if no children.
1102 static int mem_cgroup_count_children(struct mem_cgroup *mem)
1105 mem_cgroup_walk_tree(mem, &num, mem_cgroup_count_children_cb);
1110 * Visit the first child (need not be the first child as per the ordering
1111 * of the cgroup list, since we track last_scanned_child) of @mem and use
1112 * that to reclaim free pages from.
1114 static struct mem_cgroup *
1115 mem_cgroup_select_victim(struct mem_cgroup *root_mem)
1117 struct mem_cgroup *ret = NULL;
1118 struct cgroup_subsys_state *css;
1121 if (!root_mem->use_hierarchy) {
1122 css_get(&root_mem->css);
1128 nextid = root_mem->last_scanned_child + 1;
1129 css = css_get_next(&mem_cgroup_subsys, nextid, &root_mem->css,
1131 if (css && css_tryget(css))
1132 ret = container_of(css, struct mem_cgroup, css);
1135 /* Updates scanning parameter */
1136 spin_lock(&root_mem->reclaim_param_lock);
1138 /* this means start scan from ID:1 */
1139 root_mem->last_scanned_child = 0;
1141 root_mem->last_scanned_child = found;
1142 spin_unlock(&root_mem->reclaim_param_lock);
1149 * Scan the hierarchy if needed to reclaim memory. We remember the last child
1150 * we reclaimed from, so that we don't end up penalizing one child extensively
1151 * based on its position in the children list.
1153 * root_mem is the original ancestor that we've been reclaim from.
1155 * We give up and return to the caller when we visit root_mem twice.
1156 * (other groups can be removed while we're walking....)
1158 * If shrink==true, for avoiding to free too much, this returns immedieately.
1160 static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup *root_mem,
1163 unsigned long reclaim_options)
1165 struct mem_cgroup *victim;
1168 bool noswap = reclaim_options & MEM_CGROUP_RECLAIM_NOSWAP;
1169 bool shrink = reclaim_options & MEM_CGROUP_RECLAIM_SHRINK;
1170 bool check_soft = reclaim_options & MEM_CGROUP_RECLAIM_SOFT;
1171 unsigned long excess = mem_cgroup_get_excess(root_mem);
1173 /* If memsw_is_minimum==1, swap-out is of-no-use. */
1174 if (root_mem->memsw_is_minimum)
1178 victim = mem_cgroup_select_victim(root_mem);
1179 if (victim == root_mem) {
1182 drain_all_stock_async();
1185 * If we have not been able to reclaim
1186 * anything, it might because there are
1187 * no reclaimable pages under this hierarchy
1189 if (!check_soft || !total) {
1190 css_put(&victim->css);
1194 * We want to do more targetted reclaim.
1195 * excess >> 2 is not to excessive so as to
1196 * reclaim too much, nor too less that we keep
1197 * coming back to reclaim from this cgroup
1199 if (total >= (excess >> 2) ||
1200 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS)) {
1201 css_put(&victim->css);
1206 if (!mem_cgroup_local_usage(&victim->stat)) {
1207 /* this cgroup's local usage == 0 */
1208 css_put(&victim->css);
1211 /* we use swappiness of local cgroup */
1213 ret = mem_cgroup_shrink_node_zone(victim, gfp_mask,
1214 noswap, get_swappiness(victim), zone,
1215 zone->zone_pgdat->node_id);
1217 ret = try_to_free_mem_cgroup_pages(victim, gfp_mask,
1218 noswap, get_swappiness(victim));
1219 css_put(&victim->css);
1221 * At shrinking usage, we can't check we should stop here or
1222 * reclaim more. It's depends on callers. last_scanned_child
1223 * will work enough for keeping fairness under tree.
1229 if (res_counter_check_under_soft_limit(&root_mem->res))
1231 } else if (mem_cgroup_check_under_limit(root_mem))
1237 bool mem_cgroup_oom_called(struct task_struct *task)
1240 struct mem_cgroup *mem;
1241 struct mm_struct *mm;
1247 mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
1248 if (mem && time_before(jiffies, mem->last_oom_jiffies + HZ/10))
1254 static int record_last_oom_cb(struct mem_cgroup *mem, void *data)
1256 mem->last_oom_jiffies = jiffies;
1260 static void record_last_oom(struct mem_cgroup *mem)
1262 mem_cgroup_walk_tree(mem, NULL, record_last_oom_cb);
1266 * Currently used to update mapped file statistics, but the routine can be
1267 * generalized to update other statistics as well.
1269 void mem_cgroup_update_file_mapped(struct page *page, int val)
1271 struct mem_cgroup *mem;
1272 struct mem_cgroup_stat *stat;
1273 struct mem_cgroup_stat_cpu *cpustat;
1275 struct page_cgroup *pc;
1277 pc = lookup_page_cgroup(page);
1281 lock_page_cgroup(pc);
1282 mem = pc->mem_cgroup;
1286 if (!PageCgroupUsed(pc))
1290 * Preemption is already disabled, we don't need get_cpu()
1292 cpu = smp_processor_id();
1294 cpustat = &stat->cpustat[cpu];
1296 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_FILE_MAPPED, val);
1298 unlock_page_cgroup(pc);
1302 * size of first charge trial. "32" comes from vmscan.c's magic value.
1303 * TODO: maybe necessary to use big numbers in big irons.
1305 #define CHARGE_SIZE (32 * PAGE_SIZE)
1306 struct memcg_stock_pcp {
1307 struct mem_cgroup *cached; /* this never be root cgroup */
1309 struct work_struct work;
1311 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
1312 static atomic_t memcg_drain_count;
1315 * Try to consume stocked charge on this cpu. If success, PAGE_SIZE is consumed
1316 * from local stock and true is returned. If the stock is 0 or charges from a
1317 * cgroup which is not current target, returns false. This stock will be
1320 static bool consume_stock(struct mem_cgroup *mem)
1322 struct memcg_stock_pcp *stock;
1325 stock = &get_cpu_var(memcg_stock);
1326 if (mem == stock->cached && stock->charge)
1327 stock->charge -= PAGE_SIZE;
1328 else /* need to call res_counter_charge */
1330 put_cpu_var(memcg_stock);
1335 * Returns stocks cached in percpu to res_counter and reset cached information.
1337 static void drain_stock(struct memcg_stock_pcp *stock)
1339 struct mem_cgroup *old = stock->cached;
1341 if (stock->charge) {
1342 res_counter_uncharge(&old->res, stock->charge);
1343 if (do_swap_account)
1344 res_counter_uncharge(&old->memsw, stock->charge);
1346 stock->cached = NULL;
1351 * This must be called under preempt disabled or must be called by
1352 * a thread which is pinned to local cpu.
1354 static void drain_local_stock(struct work_struct *dummy)
1356 struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
1361 * Cache charges(val) which is from res_counter, to local per_cpu area.
1362 * This will be consumed by consumt_stock() function, later.
1364 static void refill_stock(struct mem_cgroup *mem, int val)
1366 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
1368 if (stock->cached != mem) { /* reset if necessary */
1370 stock->cached = mem;
1372 stock->charge += val;
1373 put_cpu_var(memcg_stock);
1377 * Tries to drain stocked charges in other cpus. This function is asynchronous
1378 * and just put a work per cpu for draining localy on each cpu. Caller can
1379 * expects some charges will be back to res_counter later but cannot wait for
1382 static void drain_all_stock_async(void)
1385 /* This function is for scheduling "drain" in asynchronous way.
1386 * The result of "drain" is not directly handled by callers. Then,
1387 * if someone is calling drain, we don't have to call drain more.
1388 * Anyway, WORK_STRUCT_PENDING check in queue_work_on() will catch if
1389 * there is a race. We just do loose check here.
1391 if (atomic_read(&memcg_drain_count))
1393 /* Notify other cpus that system-wide "drain" is running */
1394 atomic_inc(&memcg_drain_count);
1396 for_each_online_cpu(cpu) {
1397 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
1398 schedule_work_on(cpu, &stock->work);
1401 atomic_dec(&memcg_drain_count);
1402 /* We don't wait for flush_work */
1405 /* This is a synchronous drain interface. */
1406 static void drain_all_stock_sync(void)
1408 /* called when force_empty is called */
1409 atomic_inc(&memcg_drain_count);
1410 schedule_on_each_cpu(drain_local_stock);
1411 atomic_dec(&memcg_drain_count);
1414 static int __cpuinit memcg_stock_cpu_callback(struct notifier_block *nb,
1415 unsigned long action,
1418 int cpu = (unsigned long)hcpu;
1419 struct memcg_stock_pcp *stock;
1421 if (action != CPU_DEAD)
1423 stock = &per_cpu(memcg_stock, cpu);
1429 * Unlike exported interface, "oom" parameter is added. if oom==true,
1430 * oom-killer can be invoked.
1432 static int __mem_cgroup_try_charge(struct mm_struct *mm,
1433 gfp_t gfp_mask, struct mem_cgroup **memcg,
1434 bool oom, struct page *page)
1436 struct mem_cgroup *mem, *mem_over_limit;
1437 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
1438 struct res_counter *fail_res;
1439 int csize = CHARGE_SIZE;
1441 if (unlikely(test_thread_flag(TIF_MEMDIE))) {
1442 /* Don't account this! */
1448 * We always charge the cgroup the mm_struct belongs to.
1449 * The mm_struct's mem_cgroup changes on task migration if the
1450 * thread group leader migrates. It's possible that mm is not
1451 * set, if so charge the init_mm (happens for pagecache usage).
1455 mem = try_get_mem_cgroup_from_mm(mm);
1463 VM_BUG_ON(css_is_removed(&mem->css));
1464 if (mem_cgroup_is_root(mem))
1469 unsigned long flags = 0;
1471 if (consume_stock(mem))
1474 ret = res_counter_charge(&mem->res, csize, &fail_res);
1476 if (!do_swap_account)
1478 ret = res_counter_charge(&mem->memsw, csize, &fail_res);
1481 /* mem+swap counter fails */
1482 res_counter_uncharge(&mem->res, csize);
1483 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
1484 mem_over_limit = mem_cgroup_from_res_counter(fail_res,
1487 /* mem counter fails */
1488 mem_over_limit = mem_cgroup_from_res_counter(fail_res,
1491 /* reduce request size and retry */
1492 if (csize > PAGE_SIZE) {
1496 if (!(gfp_mask & __GFP_WAIT))
1499 ret = mem_cgroup_hierarchical_reclaim(mem_over_limit, NULL,
1505 * try_to_free_mem_cgroup_pages() might not give us a full
1506 * picture of reclaim. Some pages are reclaimed and might be
1507 * moved to swap cache or just unmapped from the cgroup.
1508 * Check the limit again to see if the reclaim reduced the
1509 * current usage of the cgroup before giving up
1512 if (mem_cgroup_check_under_limit(mem_over_limit))
1515 /* try to avoid oom while someone is moving charge */
1516 if (mc.moving_task && current != mc.moving_task) {
1517 struct mem_cgroup *from, *to;
1518 bool do_continue = false;
1520 * There is a small race that "from" or "to" can be
1521 * freed by rmdir, so we use css_tryget().
1526 if (from && css_tryget(&from->css)) {
1527 if (mem_over_limit->use_hierarchy)
1528 do_continue = css_is_ancestor(
1530 &mem_over_limit->css);
1532 do_continue = (from == mem_over_limit);
1533 css_put(&from->css);
1535 if (!do_continue && to && css_tryget(&to->css)) {
1536 if (mem_over_limit->use_hierarchy)
1537 do_continue = css_is_ancestor(
1539 &mem_over_limit->css);
1541 do_continue = (to == mem_over_limit);
1547 prepare_to_wait(&mc.waitq, &wait,
1548 TASK_INTERRUPTIBLE);
1549 /* moving charge context might have finished. */
1552 finish_wait(&mc.waitq, &wait);
1557 if (!nr_retries--) {
1559 mem_cgroup_out_of_memory(mem_over_limit, gfp_mask);
1560 record_last_oom(mem_over_limit);
1565 if (csize > PAGE_SIZE)
1566 refill_stock(mem, csize - PAGE_SIZE);
1569 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
1570 * if they exceeds softlimit.
1572 if (page && mem_cgroup_soft_limit_check(mem))
1573 mem_cgroup_update_tree(mem, page);
1582 * Somemtimes we have to undo a charge we got by try_charge().
1583 * This function is for that and do uncharge, put css's refcnt.
1584 * gotten by try_charge().
1586 static void __mem_cgroup_cancel_charge(struct mem_cgroup *mem,
1587 unsigned long count)
1589 if (!mem_cgroup_is_root(mem)) {
1590 res_counter_uncharge(&mem->res, PAGE_SIZE * count);
1591 if (do_swap_account)
1592 res_counter_uncharge(&mem->memsw, PAGE_SIZE * count);
1593 VM_BUG_ON(test_bit(CSS_ROOT, &mem->css.flags));
1594 WARN_ON_ONCE(count > INT_MAX);
1595 __css_put(&mem->css, (int)count);
1597 /* we don't need css_put for root */
1600 static void mem_cgroup_cancel_charge(struct mem_cgroup *mem)
1602 __mem_cgroup_cancel_charge(mem, 1);
1606 * A helper function to get mem_cgroup from ID. must be called under
1607 * rcu_read_lock(). The caller must check css_is_removed() or some if
1608 * it's concern. (dropping refcnt from swap can be called against removed
1611 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
1613 struct cgroup_subsys_state *css;
1615 /* ID 0 is unused ID */
1618 css = css_lookup(&mem_cgroup_subsys, id);
1621 return container_of(css, struct mem_cgroup, css);
1624 struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
1626 struct mem_cgroup *mem = NULL;
1627 struct page_cgroup *pc;
1631 VM_BUG_ON(!PageLocked(page));
1633 pc = lookup_page_cgroup(page);
1634 lock_page_cgroup(pc);
1635 if (PageCgroupUsed(pc)) {
1636 mem = pc->mem_cgroup;
1637 if (mem && !css_tryget(&mem->css))
1639 } else if (PageSwapCache(page)) {
1640 ent.val = page_private(page);
1641 id = lookup_swap_cgroup(ent);
1643 mem = mem_cgroup_lookup(id);
1644 if (mem && !css_tryget(&mem->css))
1648 unlock_page_cgroup(pc);
1653 * commit a charge got by __mem_cgroup_try_charge() and makes page_cgroup to be
1654 * USED state. If already USED, uncharge and return.
1657 static void __mem_cgroup_commit_charge(struct mem_cgroup *mem,
1658 struct page_cgroup *pc,
1659 enum charge_type ctype)
1661 /* try_charge() can return NULL to *memcg, taking care of it. */
1665 lock_page_cgroup(pc);
1666 if (unlikely(PageCgroupUsed(pc))) {
1667 unlock_page_cgroup(pc);
1668 mem_cgroup_cancel_charge(mem);
1672 pc->mem_cgroup = mem;
1674 * We access a page_cgroup asynchronously without lock_page_cgroup().
1675 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
1676 * is accessed after testing USED bit. To make pc->mem_cgroup visible
1677 * before USED bit, we need memory barrier here.
1678 * See mem_cgroup_add_lru_list(), etc.
1682 case MEM_CGROUP_CHARGE_TYPE_CACHE:
1683 case MEM_CGROUP_CHARGE_TYPE_SHMEM:
1684 SetPageCgroupCache(pc);
1685 SetPageCgroupUsed(pc);
1687 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
1688 ClearPageCgroupCache(pc);
1689 SetPageCgroupUsed(pc);
1695 mem_cgroup_charge_statistics(mem, pc, true);
1697 unlock_page_cgroup(pc);
1701 * __mem_cgroup_move_account - move account of the page
1702 * @pc: page_cgroup of the page.
1703 * @from: mem_cgroup which the page is moved from.
1704 * @to: mem_cgroup which the page is moved to. @from != @to.
1705 * @uncharge: whether we should call uncharge and css_put against @from.
1707 * The caller must confirm following.
1708 * - page is not on LRU (isolate_page() is useful.)
1709 * - the pc is locked, used, and ->mem_cgroup points to @from.
1711 * This function doesn't do "charge" nor css_get to new cgroup. It should be
1712 * done by a caller(__mem_cgroup_try_charge would be usefull). If @uncharge is
1713 * true, this function does "uncharge" from old cgroup, but it doesn't if
1714 * @uncharge is false, so a caller should do "uncharge".
1717 static void __mem_cgroup_move_account(struct page_cgroup *pc,
1718 struct mem_cgroup *from, struct mem_cgroup *to, bool uncharge)
1722 struct mem_cgroup_stat *stat;
1723 struct mem_cgroup_stat_cpu *cpustat;
1725 VM_BUG_ON(from == to);
1726 VM_BUG_ON(PageLRU(pc->page));
1727 VM_BUG_ON(!PageCgroupLocked(pc));
1728 VM_BUG_ON(!PageCgroupUsed(pc));
1729 VM_BUG_ON(pc->mem_cgroup != from);
1732 if (page_mapped(page) && !PageAnon(page)) {
1733 cpu = smp_processor_id();
1734 /* Update mapped_file data for mem_cgroup "from" */
1736 cpustat = &stat->cpustat[cpu];
1737 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_FILE_MAPPED,
1740 /* Update mapped_file data for mem_cgroup "to" */
1742 cpustat = &stat->cpustat[cpu];
1743 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_FILE_MAPPED,
1746 mem_cgroup_charge_statistics(from, pc, false);
1748 /* This is not "cancel", but cancel_charge does all we need. */
1749 mem_cgroup_cancel_charge(from);
1751 /* caller should have done css_get */
1752 pc->mem_cgroup = to;
1753 mem_cgroup_charge_statistics(to, pc, true);
1755 * We charges against "to" which may not have any tasks. Then, "to"
1756 * can be under rmdir(). But in current implementation, caller of
1757 * this function is just force_empty() and move charge, so it's
1758 * garanteed that "to" is never removed. So, we don't check rmdir
1764 * check whether the @pc is valid for moving account and call
1765 * __mem_cgroup_move_account()
1767 static int mem_cgroup_move_account(struct page_cgroup *pc,
1768 struct mem_cgroup *from, struct mem_cgroup *to, bool uncharge)
1771 lock_page_cgroup(pc);
1772 if (PageCgroupUsed(pc) && pc->mem_cgroup == from) {
1773 __mem_cgroup_move_account(pc, from, to, uncharge);
1776 unlock_page_cgroup(pc);
1781 * move charges to its parent.
1784 static int mem_cgroup_move_parent(struct page_cgroup *pc,
1785 struct mem_cgroup *child,
1788 struct page *page = pc->page;
1789 struct cgroup *cg = child->css.cgroup;
1790 struct cgroup *pcg = cg->parent;
1791 struct mem_cgroup *parent;
1799 if (!get_page_unless_zero(page))
1801 if (isolate_lru_page(page))
1804 parent = mem_cgroup_from_cont(pcg);
1805 ret = __mem_cgroup_try_charge(NULL, gfp_mask, &parent, false, page);
1809 ret = mem_cgroup_move_account(pc, child, parent, true);
1811 mem_cgroup_cancel_charge(parent);
1813 putback_lru_page(page);
1821 * Charge the memory controller for page usage.
1823 * 0 if the charge was successful
1824 * < 0 if the cgroup is over its limit
1826 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
1827 gfp_t gfp_mask, enum charge_type ctype,
1828 struct mem_cgroup *memcg)
1830 struct mem_cgroup *mem;
1831 struct page_cgroup *pc;
1834 pc = lookup_page_cgroup(page);
1835 /* can happen at boot */
1841 ret = __mem_cgroup_try_charge(mm, gfp_mask, &mem, true, page);
1845 __mem_cgroup_commit_charge(mem, pc, ctype);
1849 int mem_cgroup_newpage_charge(struct page *page,
1850 struct mm_struct *mm, gfp_t gfp_mask)
1852 if (mem_cgroup_disabled())
1854 if (PageCompound(page))
1857 * If already mapped, we don't have to account.
1858 * If page cache, page->mapping has address_space.
1859 * But page->mapping may have out-of-use anon_vma pointer,
1860 * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
1863 if (page_mapped(page) || (page->mapping && !PageAnon(page)))
1867 return mem_cgroup_charge_common(page, mm, gfp_mask,
1868 MEM_CGROUP_CHARGE_TYPE_MAPPED, NULL);
1872 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
1873 enum charge_type ctype);
1875 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
1878 struct mem_cgroup *mem = NULL;
1881 if (mem_cgroup_disabled())
1883 if (PageCompound(page))
1886 * Corner case handling. This is called from add_to_page_cache()
1887 * in usual. But some FS (shmem) precharges this page before calling it
1888 * and call add_to_page_cache() with GFP_NOWAIT.
1890 * For GFP_NOWAIT case, the page may be pre-charged before calling
1891 * add_to_page_cache(). (See shmem.c) check it here and avoid to call
1892 * charge twice. (It works but has to pay a bit larger cost.)
1893 * And when the page is SwapCache, it should take swap information
1894 * into account. This is under lock_page() now.
1896 if (!(gfp_mask & __GFP_WAIT)) {
1897 struct page_cgroup *pc;
1900 pc = lookup_page_cgroup(page);
1903 lock_page_cgroup(pc);
1904 if (PageCgroupUsed(pc)) {
1905 unlock_page_cgroup(pc);
1908 unlock_page_cgroup(pc);
1911 if (unlikely(!mm && !mem))
1914 if (page_is_file_cache(page))
1915 return mem_cgroup_charge_common(page, mm, gfp_mask,
1916 MEM_CGROUP_CHARGE_TYPE_CACHE, NULL);
1919 if (PageSwapCache(page)) {
1920 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
1922 __mem_cgroup_commit_charge_swapin(page, mem,
1923 MEM_CGROUP_CHARGE_TYPE_SHMEM);
1925 ret = mem_cgroup_charge_common(page, mm, gfp_mask,
1926 MEM_CGROUP_CHARGE_TYPE_SHMEM, mem);
1932 * While swap-in, try_charge -> commit or cancel, the page is locked.
1933 * And when try_charge() successfully returns, one refcnt to memcg without
1934 * struct page_cgroup is acquired. This refcnt will be consumed by
1935 * "commit()" or removed by "cancel()"
1937 int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
1939 gfp_t mask, struct mem_cgroup **ptr)
1941 struct mem_cgroup *mem;
1944 if (mem_cgroup_disabled())
1947 if (!do_swap_account)
1950 * A racing thread's fault, or swapoff, may have already updated
1951 * the pte, and even removed page from swap cache: in those cases
1952 * do_swap_page()'s pte_same() test will fail; but there's also a
1953 * KSM case which does need to charge the page.
1955 if (!PageSwapCache(page))
1957 mem = try_get_mem_cgroup_from_page(page);
1961 ret = __mem_cgroup_try_charge(NULL, mask, ptr, true, page);
1962 /* drop extra refcnt from tryget */
1968 return __mem_cgroup_try_charge(mm, mask, ptr, true, page);
1972 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
1973 enum charge_type ctype)
1975 struct page_cgroup *pc;
1977 if (mem_cgroup_disabled())
1981 cgroup_exclude_rmdir(&ptr->css);
1982 pc = lookup_page_cgroup(page);
1983 mem_cgroup_lru_del_before_commit_swapcache(page);
1984 __mem_cgroup_commit_charge(ptr, pc, ctype);
1985 mem_cgroup_lru_add_after_commit_swapcache(page);
1987 * Now swap is on-memory. This means this page may be
1988 * counted both as mem and swap....double count.
1989 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
1990 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
1991 * may call delete_from_swap_cache() before reach here.
1993 if (do_swap_account && PageSwapCache(page)) {
1994 swp_entry_t ent = {.val = page_private(page)};
1996 struct mem_cgroup *memcg;
1998 id = swap_cgroup_record(ent, 0);
2000 memcg = mem_cgroup_lookup(id);
2003 * This recorded memcg can be obsolete one. So, avoid
2004 * calling css_tryget
2006 if (!mem_cgroup_is_root(memcg))
2007 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
2008 mem_cgroup_swap_statistics(memcg, false);
2009 mem_cgroup_put(memcg);
2014 * At swapin, we may charge account against cgroup which has no tasks.
2015 * So, rmdir()->pre_destroy() can be called while we do this charge.
2016 * In that case, we need to call pre_destroy() again. check it here.
2018 cgroup_release_and_wakeup_rmdir(&ptr->css);
2021 void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
2023 __mem_cgroup_commit_charge_swapin(page, ptr,
2024 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2027 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *mem)
2029 if (mem_cgroup_disabled())
2033 mem_cgroup_cancel_charge(mem);
2037 __do_uncharge(struct mem_cgroup *mem, const enum charge_type ctype)
2039 struct memcg_batch_info *batch = NULL;
2040 bool uncharge_memsw = true;
2041 /* If swapout, usage of swap doesn't decrease */
2042 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2043 uncharge_memsw = false;
2045 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
2046 * In those cases, all pages freed continously can be expected to be in
2047 * the same cgroup and we have chance to coalesce uncharges.
2048 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
2049 * because we want to do uncharge as soon as possible.
2051 if (!current->memcg_batch.do_batch || test_thread_flag(TIF_MEMDIE))
2052 goto direct_uncharge;
2054 batch = ¤t->memcg_batch;
2056 * In usual, we do css_get() when we remember memcg pointer.
2057 * But in this case, we keep res->usage until end of a series of
2058 * uncharges. Then, it's ok to ignore memcg's refcnt.
2063 * In typical case, batch->memcg == mem. This means we can
2064 * merge a series of uncharges to an uncharge of res_counter.
2065 * If not, we uncharge res_counter ony by one.
2067 if (batch->memcg != mem)
2068 goto direct_uncharge;
2069 /* remember freed charge and uncharge it later */
2070 batch->bytes += PAGE_SIZE;
2072 batch->memsw_bytes += PAGE_SIZE;
2075 res_counter_uncharge(&mem->res, PAGE_SIZE);
2077 res_counter_uncharge(&mem->memsw, PAGE_SIZE);
2082 * uncharge if !page_mapped(page)
2084 static struct mem_cgroup *
2085 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
2087 struct page_cgroup *pc;
2088 struct mem_cgroup *mem = NULL;
2089 struct mem_cgroup_per_zone *mz;
2091 if (mem_cgroup_disabled())
2094 if (PageSwapCache(page))
2098 * Check if our page_cgroup is valid
2100 pc = lookup_page_cgroup(page);
2101 if (unlikely(!pc || !PageCgroupUsed(pc)))
2104 lock_page_cgroup(pc);
2106 mem = pc->mem_cgroup;
2108 if (!PageCgroupUsed(pc))
2112 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
2113 case MEM_CGROUP_CHARGE_TYPE_DROP:
2114 if (page_mapped(page))
2117 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
2118 if (!PageAnon(page)) { /* Shared memory */
2119 if (page->mapping && !page_is_file_cache(page))
2121 } else if (page_mapped(page)) /* Anon */
2128 if (!mem_cgroup_is_root(mem))
2129 __do_uncharge(mem, ctype);
2130 if (ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2131 mem_cgroup_swap_statistics(mem, true);
2132 mem_cgroup_charge_statistics(mem, pc, false);
2134 ClearPageCgroupUsed(pc);
2136 * pc->mem_cgroup is not cleared here. It will be accessed when it's
2137 * freed from LRU. This is safe because uncharged page is expected not
2138 * to be reused (freed soon). Exception is SwapCache, it's handled by
2139 * special functions.
2142 mz = page_cgroup_zoneinfo(pc);
2143 unlock_page_cgroup(pc);
2145 if (mem_cgroup_soft_limit_check(mem))
2146 mem_cgroup_update_tree(mem, page);
2147 /* at swapout, this memcg will be accessed to record to swap */
2148 if (ctype != MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2154 unlock_page_cgroup(pc);
2158 void mem_cgroup_uncharge_page(struct page *page)
2161 if (page_mapped(page))
2163 if (page->mapping && !PageAnon(page))
2165 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
2168 void mem_cgroup_uncharge_cache_page(struct page *page)
2170 VM_BUG_ON(page_mapped(page));
2171 VM_BUG_ON(page->mapping);
2172 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
2176 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
2177 * In that cases, pages are freed continuously and we can expect pages
2178 * are in the same memcg. All these calls itself limits the number of
2179 * pages freed at once, then uncharge_start/end() is called properly.
2180 * This may be called prural(2) times in a context,
2183 void mem_cgroup_uncharge_start(void)
2185 current->memcg_batch.do_batch++;
2186 /* We can do nest. */
2187 if (current->memcg_batch.do_batch == 1) {
2188 current->memcg_batch.memcg = NULL;
2189 current->memcg_batch.bytes = 0;
2190 current->memcg_batch.memsw_bytes = 0;
2194 void mem_cgroup_uncharge_end(void)
2196 struct memcg_batch_info *batch = ¤t->memcg_batch;
2198 if (!batch->do_batch)
2202 if (batch->do_batch) /* If stacked, do nothing. */
2208 * This "batch->memcg" is valid without any css_get/put etc...
2209 * bacause we hide charges behind us.
2212 res_counter_uncharge(&batch->memcg->res, batch->bytes);
2213 if (batch->memsw_bytes)
2214 res_counter_uncharge(&batch->memcg->memsw, batch->memsw_bytes);
2215 /* forget this pointer (for sanity check) */
2216 batch->memcg = NULL;
2221 * called after __delete_from_swap_cache() and drop "page" account.
2222 * memcg information is recorded to swap_cgroup of "ent"
2225 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
2227 struct mem_cgroup *memcg;
2228 int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
2230 if (!swapout) /* this was a swap cache but the swap is unused ! */
2231 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
2233 memcg = __mem_cgroup_uncharge_common(page, ctype);
2235 /* record memcg information */
2236 if (do_swap_account && swapout && memcg) {
2237 swap_cgroup_record(ent, css_id(&memcg->css));
2238 mem_cgroup_get(memcg);
2240 if (swapout && memcg)
2241 css_put(&memcg->css);
2245 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
2247 * called from swap_entry_free(). remove record in swap_cgroup and
2248 * uncharge "memsw" account.
2250 void mem_cgroup_uncharge_swap(swp_entry_t ent)
2252 struct mem_cgroup *memcg;
2255 if (!do_swap_account)
2258 id = swap_cgroup_record(ent, 0);
2260 memcg = mem_cgroup_lookup(id);
2263 * We uncharge this because swap is freed.
2264 * This memcg can be obsolete one. We avoid calling css_tryget
2266 if (!mem_cgroup_is_root(memcg))
2267 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
2268 mem_cgroup_swap_statistics(memcg, false);
2269 mem_cgroup_put(memcg);
2276 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
2279 int mem_cgroup_prepare_migration(struct page *page, struct mem_cgroup **ptr)
2281 struct page_cgroup *pc;
2282 struct mem_cgroup *mem = NULL;
2285 if (mem_cgroup_disabled())
2288 pc = lookup_page_cgroup(page);
2289 lock_page_cgroup(pc);
2290 if (PageCgroupUsed(pc)) {
2291 mem = pc->mem_cgroup;
2294 unlock_page_cgroup(pc);
2297 ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, &mem, false,
2305 /* remove redundant charge if migration failed*/
2306 void mem_cgroup_end_migration(struct mem_cgroup *mem,
2307 struct page *oldpage, struct page *newpage)
2309 struct page *target, *unused;
2310 struct page_cgroup *pc;
2311 enum charge_type ctype;
2315 cgroup_exclude_rmdir(&mem->css);
2316 /* at migration success, oldpage->mapping is NULL. */
2317 if (oldpage->mapping) {
2325 if (PageAnon(target))
2326 ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
2327 else if (page_is_file_cache(target))
2328 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
2330 ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
2332 /* unused page is not on radix-tree now. */
2334 __mem_cgroup_uncharge_common(unused, ctype);
2336 pc = lookup_page_cgroup(target);
2338 * __mem_cgroup_commit_charge() check PCG_USED bit of page_cgroup.
2339 * So, double-counting is effectively avoided.
2341 __mem_cgroup_commit_charge(mem, pc, ctype);
2344 * Both of oldpage and newpage are still under lock_page().
2345 * Then, we don't have to care about race in radix-tree.
2346 * But we have to be careful that this page is unmapped or not.
2348 * There is a case for !page_mapped(). At the start of
2349 * migration, oldpage was mapped. But now, it's zapped.
2350 * But we know *target* page is not freed/reused under us.
2351 * mem_cgroup_uncharge_page() does all necessary checks.
2353 if (ctype == MEM_CGROUP_CHARGE_TYPE_MAPPED)
2354 mem_cgroup_uncharge_page(target);
2356 * At migration, we may charge account against cgroup which has no tasks
2357 * So, rmdir()->pre_destroy() can be called while we do this charge.
2358 * In that case, we need to call pre_destroy() again. check it here.
2360 cgroup_release_and_wakeup_rmdir(&mem->css);
2364 * A call to try to shrink memory usage on charge failure at shmem's swapin.
2365 * Calling hierarchical_reclaim is not enough because we should update
2366 * last_oom_jiffies to prevent pagefault_out_of_memory from invoking global OOM.
2367 * Moreover considering hierarchy, we should reclaim from the mem_over_limit,
2368 * not from the memcg which this page would be charged to.
2369 * try_charge_swapin does all of these works properly.
2371 int mem_cgroup_shmem_charge_fallback(struct page *page,
2372 struct mm_struct *mm,
2375 struct mem_cgroup *mem = NULL;
2378 if (mem_cgroup_disabled())
2381 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
2383 mem_cgroup_cancel_charge_swapin(mem); /* it does !mem check */
2388 static DEFINE_MUTEX(set_limit_mutex);
2390 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
2391 unsigned long long val)
2396 int children = mem_cgroup_count_children(memcg);
2397 u64 curusage, oldusage;
2400 * For keeping hierarchical_reclaim simple, how long we should retry
2401 * is depends on callers. We set our retry-count to be function
2402 * of # of children which we should visit in this loop.
2404 retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
2406 oldusage = res_counter_read_u64(&memcg->res, 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 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
2420 if (memswlimit < val) {
2422 mutex_unlock(&set_limit_mutex);
2425 ret = res_counter_set_limit(&memcg->res, val);
2427 if (memswlimit == 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_SHRINK);
2439 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
2440 /* Usage is reduced ? */
2441 if (curusage >= oldusage)
2444 oldusage = curusage;
2450 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
2451 unsigned long long val)
2454 u64 memlimit, oldusage, curusage;
2455 int children = mem_cgroup_count_children(memcg);
2458 /* see mem_cgroup_resize_res_limit */
2459 retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
2460 oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
2461 while (retry_count) {
2462 if (signal_pending(current)) {
2467 * Rather than hide all in some function, I do this in
2468 * open coded manner. You see what this really does.
2469 * We have to guarantee mem->res.limit < mem->memsw.limit.
2471 mutex_lock(&set_limit_mutex);
2472 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
2473 if (memlimit > val) {
2475 mutex_unlock(&set_limit_mutex);
2478 ret = res_counter_set_limit(&memcg->memsw, val);
2480 if (memlimit == val)
2481 memcg->memsw_is_minimum = true;
2483 memcg->memsw_is_minimum = false;
2485 mutex_unlock(&set_limit_mutex);
2490 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
2491 MEM_CGROUP_RECLAIM_NOSWAP |
2492 MEM_CGROUP_RECLAIM_SHRINK);
2493 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
2494 /* Usage is reduced ? */
2495 if (curusage >= oldusage)
2498 oldusage = curusage;
2503 unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
2504 gfp_t gfp_mask, int nid,
2507 unsigned long nr_reclaimed = 0;
2508 struct mem_cgroup_per_zone *mz, *next_mz = NULL;
2509 unsigned long reclaimed;
2511 struct mem_cgroup_tree_per_zone *mctz;
2512 unsigned long long excess;
2517 mctz = soft_limit_tree_node_zone(nid, zid);
2519 * This loop can run a while, specially if mem_cgroup's continuously
2520 * keep exceeding their soft limit and putting the system under
2527 mz = mem_cgroup_largest_soft_limit_node(mctz);
2531 reclaimed = mem_cgroup_hierarchical_reclaim(mz->mem, zone,
2533 MEM_CGROUP_RECLAIM_SOFT);
2534 nr_reclaimed += reclaimed;
2535 spin_lock(&mctz->lock);
2538 * If we failed to reclaim anything from this memory cgroup
2539 * it is time to move on to the next cgroup
2545 * Loop until we find yet another one.
2547 * By the time we get the soft_limit lock
2548 * again, someone might have aded the
2549 * group back on the RB tree. Iterate to
2550 * make sure we get a different mem.
2551 * mem_cgroup_largest_soft_limit_node returns
2552 * NULL if no other cgroup is present on
2556 __mem_cgroup_largest_soft_limit_node(mctz);
2557 if (next_mz == mz) {
2558 css_put(&next_mz->mem->css);
2560 } else /* next_mz == NULL or other memcg */
2564 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
2565 excess = res_counter_soft_limit_excess(&mz->mem->res);
2567 * One school of thought says that we should not add
2568 * back the node to the tree if reclaim returns 0.
2569 * But our reclaim could return 0, simply because due
2570 * to priority we are exposing a smaller subset of
2571 * memory to reclaim from. Consider this as a longer
2574 /* If excess == 0, no tree ops */
2575 __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
2576 spin_unlock(&mctz->lock);
2577 css_put(&mz->mem->css);
2580 * Could not reclaim anything and there are no more
2581 * mem cgroups to try or we seem to be looping without
2582 * reclaiming anything.
2584 if (!nr_reclaimed &&
2586 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
2588 } while (!nr_reclaimed);
2590 css_put(&next_mz->mem->css);
2591 return nr_reclaimed;
2595 * This routine traverse page_cgroup in given list and drop them all.
2596 * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
2598 static int mem_cgroup_force_empty_list(struct mem_cgroup *mem,
2599 int node, int zid, enum lru_list lru)
2602 struct mem_cgroup_per_zone *mz;
2603 struct page_cgroup *pc, *busy;
2604 unsigned long flags, loop;
2605 struct list_head *list;
2608 zone = &NODE_DATA(node)->node_zones[zid];
2609 mz = mem_cgroup_zoneinfo(mem, node, zid);
2610 list = &mz->lists[lru];
2612 loop = MEM_CGROUP_ZSTAT(mz, lru);
2613 /* give some margin against EBUSY etc...*/
2618 spin_lock_irqsave(&zone->lru_lock, flags);
2619 if (list_empty(list)) {
2620 spin_unlock_irqrestore(&zone->lru_lock, flags);
2623 pc = list_entry(list->prev, struct page_cgroup, lru);
2625 list_move(&pc->lru, list);
2627 spin_unlock_irqrestore(&zone->lru_lock, flags);
2630 spin_unlock_irqrestore(&zone->lru_lock, flags);
2632 ret = mem_cgroup_move_parent(pc, mem, GFP_KERNEL);
2636 if (ret == -EBUSY || ret == -EINVAL) {
2637 /* found lock contention or "pc" is obsolete. */
2644 if (!ret && !list_empty(list))
2650 * make mem_cgroup's charge to be 0 if there is no task.
2651 * This enables deleting this mem_cgroup.
2653 static int mem_cgroup_force_empty(struct mem_cgroup *mem, bool free_all)
2656 int node, zid, shrink;
2657 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
2658 struct cgroup *cgrp = mem->css.cgroup;
2663 /* should free all ? */
2669 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
2672 if (signal_pending(current))
2674 /* This is for making all *used* pages to be on LRU. */
2675 lru_add_drain_all();
2676 drain_all_stock_sync();
2678 for_each_node_state(node, N_HIGH_MEMORY) {
2679 for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
2682 ret = mem_cgroup_force_empty_list(mem,
2691 /* it seems parent cgroup doesn't have enough mem */
2695 /* "ret" should also be checked to ensure all lists are empty. */
2696 } while (mem->res.usage > 0 || ret);
2702 /* returns EBUSY if there is a task or if we come here twice. */
2703 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
2707 /* we call try-to-free pages for make this cgroup empty */
2708 lru_add_drain_all();
2709 /* try to free all pages in this cgroup */
2711 while (nr_retries && mem->res.usage > 0) {
2714 if (signal_pending(current)) {
2718 progress = try_to_free_mem_cgroup_pages(mem, GFP_KERNEL,
2719 false, get_swappiness(mem));
2722 /* maybe some writeback is necessary */
2723 congestion_wait(BLK_RW_ASYNC, HZ/10);
2728 /* try move_account...there may be some *locked* pages. */
2732 int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
2734 return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
2738 static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
2740 return mem_cgroup_from_cont(cont)->use_hierarchy;
2743 static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
2747 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
2748 struct cgroup *parent = cont->parent;
2749 struct mem_cgroup *parent_mem = NULL;
2752 parent_mem = mem_cgroup_from_cont(parent);
2756 * If parent's use_hierarchy is set, we can't make any modifications
2757 * in the child subtrees. If it is unset, then the change can
2758 * occur, provided the current cgroup has no children.
2760 * For the root cgroup, parent_mem is NULL, we allow value to be
2761 * set if there are no children.
2763 if ((!parent_mem || !parent_mem->use_hierarchy) &&
2764 (val == 1 || val == 0)) {
2765 if (list_empty(&cont->children))
2766 mem->use_hierarchy = val;
2776 struct mem_cgroup_idx_data {
2778 enum mem_cgroup_stat_index idx;
2782 mem_cgroup_get_idx_stat(struct mem_cgroup *mem, void *data)
2784 struct mem_cgroup_idx_data *d = data;
2785 d->val += mem_cgroup_read_stat(&mem->stat, d->idx);
2790 mem_cgroup_get_recursive_idx_stat(struct mem_cgroup *mem,
2791 enum mem_cgroup_stat_index idx, s64 *val)
2793 struct mem_cgroup_idx_data d;
2796 mem_cgroup_walk_tree(mem, &d, mem_cgroup_get_idx_stat);
2800 static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
2802 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
2806 type = MEMFILE_TYPE(cft->private);
2807 name = MEMFILE_ATTR(cft->private);
2810 if (name == RES_USAGE && mem_cgroup_is_root(mem)) {
2811 mem_cgroup_get_recursive_idx_stat(mem,
2812 MEM_CGROUP_STAT_CACHE, &idx_val);
2814 mem_cgroup_get_recursive_idx_stat(mem,
2815 MEM_CGROUP_STAT_RSS, &idx_val);
2819 val = res_counter_read_u64(&mem->res, name);
2822 if (name == RES_USAGE && mem_cgroup_is_root(mem)) {
2823 mem_cgroup_get_recursive_idx_stat(mem,
2824 MEM_CGROUP_STAT_CACHE, &idx_val);
2826 mem_cgroup_get_recursive_idx_stat(mem,
2827 MEM_CGROUP_STAT_RSS, &idx_val);
2829 mem_cgroup_get_recursive_idx_stat(mem,
2830 MEM_CGROUP_STAT_SWAPOUT, &idx_val);
2834 val = res_counter_read_u64(&mem->memsw, name);
2843 * The user of this function is...
2846 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
2849 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
2851 unsigned long long val;
2854 type = MEMFILE_TYPE(cft->private);
2855 name = MEMFILE_ATTR(cft->private);
2858 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
2862 /* This function does all necessary parse...reuse it */
2863 ret = res_counter_memparse_write_strategy(buffer, &val);
2867 ret = mem_cgroup_resize_limit(memcg, val);
2869 ret = mem_cgroup_resize_memsw_limit(memcg, val);
2871 case RES_SOFT_LIMIT:
2872 ret = res_counter_memparse_write_strategy(buffer, &val);
2876 * For memsw, soft limits are hard to implement in terms
2877 * of semantics, for now, we support soft limits for
2878 * control without swap
2881 ret = res_counter_set_soft_limit(&memcg->res, val);
2886 ret = -EINVAL; /* should be BUG() ? */
2892 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
2893 unsigned long long *mem_limit, unsigned long long *memsw_limit)
2895 struct cgroup *cgroup;
2896 unsigned long long min_limit, min_memsw_limit, tmp;
2898 min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
2899 min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
2900 cgroup = memcg->css.cgroup;
2901 if (!memcg->use_hierarchy)
2904 while (cgroup->parent) {
2905 cgroup = cgroup->parent;
2906 memcg = mem_cgroup_from_cont(cgroup);
2907 if (!memcg->use_hierarchy)
2909 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
2910 min_limit = min(min_limit, tmp);
2911 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
2912 min_memsw_limit = min(min_memsw_limit, tmp);
2915 *mem_limit = min_limit;
2916 *memsw_limit = min_memsw_limit;
2920 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
2922 struct mem_cgroup *mem;
2925 mem = mem_cgroup_from_cont(cont);
2926 type = MEMFILE_TYPE(event);
2927 name = MEMFILE_ATTR(event);
2931 res_counter_reset_max(&mem->res);
2933 res_counter_reset_max(&mem->memsw);
2937 res_counter_reset_failcnt(&mem->res);
2939 res_counter_reset_failcnt(&mem->memsw);
2946 static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
2949 return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
2952 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
2953 struct cftype *cft, u64 val)
2955 struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
2957 if (val >= (1 << NR_MOVE_TYPE))
2960 * We check this value several times in both in can_attach() and
2961 * attach(), so we need cgroup lock to prevent this value from being
2965 mem->move_charge_at_immigrate = val;
2972 /* For read statistics */
2988 struct mcs_total_stat {
2989 s64 stat[NR_MCS_STAT];
2995 } memcg_stat_strings[NR_MCS_STAT] = {
2996 {"cache", "total_cache"},
2997 {"rss", "total_rss"},
2998 {"mapped_file", "total_mapped_file"},
2999 {"pgpgin", "total_pgpgin"},
3000 {"pgpgout", "total_pgpgout"},
3001 {"swap", "total_swap"},
3002 {"inactive_anon", "total_inactive_anon"},
3003 {"active_anon", "total_active_anon"},
3004 {"inactive_file", "total_inactive_file"},
3005 {"active_file", "total_active_file"},
3006 {"unevictable", "total_unevictable"}
3010 static int mem_cgroup_get_local_stat(struct mem_cgroup *mem, void *data)
3012 struct mcs_total_stat *s = data;
3016 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_CACHE);
3017 s->stat[MCS_CACHE] += val * PAGE_SIZE;
3018 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_RSS);
3019 s->stat[MCS_RSS] += val * PAGE_SIZE;
3020 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_FILE_MAPPED);
3021 s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE;
3022 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_PGPGIN_COUNT);
3023 s->stat[MCS_PGPGIN] += val;
3024 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_PGPGOUT_COUNT);
3025 s->stat[MCS_PGPGOUT] += val;
3026 if (do_swap_account) {
3027 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_SWAPOUT);
3028 s->stat[MCS_SWAP] += val * PAGE_SIZE;
3032 val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_ANON);
3033 s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
3034 val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_ANON);
3035 s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
3036 val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_FILE);
3037 s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
3038 val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_FILE);
3039 s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
3040 val = mem_cgroup_get_local_zonestat(mem, LRU_UNEVICTABLE);
3041 s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
3046 mem_cgroup_get_total_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
3048 mem_cgroup_walk_tree(mem, s, mem_cgroup_get_local_stat);
3051 static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
3052 struct cgroup_map_cb *cb)
3054 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
3055 struct mcs_total_stat mystat;
3058 memset(&mystat, 0, sizeof(mystat));
3059 mem_cgroup_get_local_stat(mem_cont, &mystat);
3061 for (i = 0; i < NR_MCS_STAT; i++) {
3062 if (i == MCS_SWAP && !do_swap_account)
3064 cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
3067 /* Hierarchical information */
3069 unsigned long long limit, memsw_limit;
3070 memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
3071 cb->fill(cb, "hierarchical_memory_limit", limit);
3072 if (do_swap_account)
3073 cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
3076 memset(&mystat, 0, sizeof(mystat));
3077 mem_cgroup_get_total_stat(mem_cont, &mystat);
3078 for (i = 0; i < NR_MCS_STAT; i++) {
3079 if (i == MCS_SWAP && !do_swap_account)
3081 cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
3084 #ifdef CONFIG_DEBUG_VM
3085 cb->fill(cb, "inactive_ratio", calc_inactive_ratio(mem_cont, NULL));
3089 struct mem_cgroup_per_zone *mz;
3090 unsigned long recent_rotated[2] = {0, 0};
3091 unsigned long recent_scanned[2] = {0, 0};
3093 for_each_online_node(nid)
3094 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
3095 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
3097 recent_rotated[0] +=
3098 mz->reclaim_stat.recent_rotated[0];
3099 recent_rotated[1] +=
3100 mz->reclaim_stat.recent_rotated[1];
3101 recent_scanned[0] +=
3102 mz->reclaim_stat.recent_scanned[0];
3103 recent_scanned[1] +=
3104 mz->reclaim_stat.recent_scanned[1];
3106 cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
3107 cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
3108 cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
3109 cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
3116 static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
3118 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3120 return get_swappiness(memcg);
3123 static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
3126 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3127 struct mem_cgroup *parent;
3132 if (cgrp->parent == NULL)
3135 parent = mem_cgroup_from_cont(cgrp->parent);
3139 /* If under hierarchy, only empty-root can set this value */
3140 if ((parent->use_hierarchy) ||
3141 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
3146 spin_lock(&memcg->reclaim_param_lock);
3147 memcg->swappiness = val;
3148 spin_unlock(&memcg->reclaim_param_lock);
3156 static struct cftype mem_cgroup_files[] = {
3158 .name = "usage_in_bytes",
3159 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
3160 .read_u64 = mem_cgroup_read,
3163 .name = "max_usage_in_bytes",
3164 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
3165 .trigger = mem_cgroup_reset,
3166 .read_u64 = mem_cgroup_read,
3169 .name = "limit_in_bytes",
3170 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
3171 .write_string = mem_cgroup_write,
3172 .read_u64 = mem_cgroup_read,
3175 .name = "soft_limit_in_bytes",
3176 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
3177 .write_string = mem_cgroup_write,
3178 .read_u64 = mem_cgroup_read,
3182 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
3183 .trigger = mem_cgroup_reset,
3184 .read_u64 = mem_cgroup_read,
3188 .read_map = mem_control_stat_show,
3191 .name = "force_empty",
3192 .trigger = mem_cgroup_force_empty_write,
3195 .name = "use_hierarchy",
3196 .write_u64 = mem_cgroup_hierarchy_write,
3197 .read_u64 = mem_cgroup_hierarchy_read,
3200 .name = "swappiness",
3201 .read_u64 = mem_cgroup_swappiness_read,
3202 .write_u64 = mem_cgroup_swappiness_write,
3205 .name = "move_charge_at_immigrate",
3206 .read_u64 = mem_cgroup_move_charge_read,
3207 .write_u64 = mem_cgroup_move_charge_write,
3211 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3212 static struct cftype memsw_cgroup_files[] = {
3214 .name = "memsw.usage_in_bytes",
3215 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
3216 .read_u64 = mem_cgroup_read,
3219 .name = "memsw.max_usage_in_bytes",
3220 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
3221 .trigger = mem_cgroup_reset,
3222 .read_u64 = mem_cgroup_read,
3225 .name = "memsw.limit_in_bytes",
3226 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
3227 .write_string = mem_cgroup_write,
3228 .read_u64 = mem_cgroup_read,
3231 .name = "memsw.failcnt",
3232 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
3233 .trigger = mem_cgroup_reset,
3234 .read_u64 = mem_cgroup_read,
3238 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
3240 if (!do_swap_account)
3242 return cgroup_add_files(cont, ss, memsw_cgroup_files,
3243 ARRAY_SIZE(memsw_cgroup_files));
3246 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
3252 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
3254 struct mem_cgroup_per_node *pn;
3255 struct mem_cgroup_per_zone *mz;
3257 int zone, tmp = node;
3259 * This routine is called against possible nodes.
3260 * But it's BUG to call kmalloc() against offline node.
3262 * TODO: this routine can waste much memory for nodes which will
3263 * never be onlined. It's better to use memory hotplug callback
3266 if (!node_state(node, N_NORMAL_MEMORY))
3268 pn = kmalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
3272 mem->info.nodeinfo[node] = pn;
3273 memset(pn, 0, sizeof(*pn));
3275 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3276 mz = &pn->zoneinfo[zone];
3278 INIT_LIST_HEAD(&mz->lists[l]);
3279 mz->usage_in_excess = 0;
3280 mz->on_tree = false;
3286 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
3288 kfree(mem->info.nodeinfo[node]);
3291 static int mem_cgroup_size(void)
3293 int cpustat_size = nr_cpu_ids * sizeof(struct mem_cgroup_stat_cpu);
3294 return sizeof(struct mem_cgroup) + cpustat_size;
3297 static struct mem_cgroup *mem_cgroup_alloc(void)
3299 struct mem_cgroup *mem;
3300 int size = mem_cgroup_size();
3302 if (size < PAGE_SIZE)
3303 mem = kmalloc(size, GFP_KERNEL);
3305 mem = vmalloc(size);
3308 memset(mem, 0, size);
3313 * At destroying mem_cgroup, references from swap_cgroup can remain.
3314 * (scanning all at force_empty is too costly...)
3316 * Instead of clearing all references at force_empty, we remember
3317 * the number of reference from swap_cgroup and free mem_cgroup when
3318 * it goes down to 0.
3320 * Removal of cgroup itself succeeds regardless of refs from swap.
3323 static void __mem_cgroup_free(struct mem_cgroup *mem)
3327 mem_cgroup_remove_from_trees(mem);
3328 free_css_id(&mem_cgroup_subsys, &mem->css);
3330 for_each_node_state(node, N_POSSIBLE)
3331 free_mem_cgroup_per_zone_info(mem, node);
3333 if (mem_cgroup_size() < PAGE_SIZE)
3339 static void mem_cgroup_get(struct mem_cgroup *mem)
3341 atomic_inc(&mem->refcnt);
3344 static void mem_cgroup_put(struct mem_cgroup *mem)
3346 if (atomic_dec_and_test(&mem->refcnt)) {
3347 struct mem_cgroup *parent = parent_mem_cgroup(mem);
3348 __mem_cgroup_free(mem);
3350 mem_cgroup_put(parent);
3355 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
3357 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem)
3359 if (!mem->res.parent)
3361 return mem_cgroup_from_res_counter(mem->res.parent, res);
3364 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3365 static void __init enable_swap_cgroup(void)
3367 if (!mem_cgroup_disabled() && really_do_swap_account)
3368 do_swap_account = 1;
3371 static void __init enable_swap_cgroup(void)
3376 static int mem_cgroup_soft_limit_tree_init(void)
3378 struct mem_cgroup_tree_per_node *rtpn;
3379 struct mem_cgroup_tree_per_zone *rtpz;
3380 int tmp, node, zone;
3382 for_each_node_state(node, N_POSSIBLE) {
3384 if (!node_state(node, N_NORMAL_MEMORY))
3386 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
3390 soft_limit_tree.rb_tree_per_node[node] = rtpn;
3392 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3393 rtpz = &rtpn->rb_tree_per_zone[zone];
3394 rtpz->rb_root = RB_ROOT;
3395 spin_lock_init(&rtpz->lock);
3401 static struct cgroup_subsys_state * __ref
3402 mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
3404 struct mem_cgroup *mem, *parent;
3405 long error = -ENOMEM;
3408 mem = mem_cgroup_alloc();
3410 return ERR_PTR(error);
3412 for_each_node_state(node, N_POSSIBLE)
3413 if (alloc_mem_cgroup_per_zone_info(mem, node))
3417 if (cont->parent == NULL) {
3419 enable_swap_cgroup();
3421 root_mem_cgroup = mem;
3422 if (mem_cgroup_soft_limit_tree_init())
3424 for_each_possible_cpu(cpu) {
3425 struct memcg_stock_pcp *stock =
3426 &per_cpu(memcg_stock, cpu);
3427 INIT_WORK(&stock->work, drain_local_stock);
3429 hotcpu_notifier(memcg_stock_cpu_callback, 0);
3431 parent = mem_cgroup_from_cont(cont->parent);
3432 mem->use_hierarchy = parent->use_hierarchy;
3435 if (parent && parent->use_hierarchy) {
3436 res_counter_init(&mem->res, &parent->res);
3437 res_counter_init(&mem->memsw, &parent->memsw);
3439 * We increment refcnt of the parent to ensure that we can
3440 * safely access it on res_counter_charge/uncharge.
3441 * This refcnt will be decremented when freeing this
3442 * mem_cgroup(see mem_cgroup_put).
3444 mem_cgroup_get(parent);
3446 res_counter_init(&mem->res, NULL);
3447 res_counter_init(&mem->memsw, NULL);
3449 mem->last_scanned_child = 0;
3450 spin_lock_init(&mem->reclaim_param_lock);
3453 mem->swappiness = get_swappiness(parent);
3454 atomic_set(&mem->refcnt, 1);
3455 mem->move_charge_at_immigrate = 0;
3458 __mem_cgroup_free(mem);
3459 root_mem_cgroup = NULL;
3460 return ERR_PTR(error);
3463 static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
3464 struct cgroup *cont)
3466 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
3468 return mem_cgroup_force_empty(mem, false);
3471 static void mem_cgroup_destroy(struct cgroup_subsys *ss,
3472 struct cgroup *cont)
3474 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
3476 mem_cgroup_put(mem);
3479 static int mem_cgroup_populate(struct cgroup_subsys *ss,
3480 struct cgroup *cont)
3484 ret = cgroup_add_files(cont, ss, mem_cgroup_files,
3485 ARRAY_SIZE(mem_cgroup_files));
3488 ret = register_memsw_files(cont, ss);
3492 /* Handlers for move charge at task migration. */
3493 #define PRECHARGE_COUNT_AT_ONCE 256
3494 static int mem_cgroup_do_precharge(unsigned long count)
3497 int batch_count = PRECHARGE_COUNT_AT_ONCE;
3498 struct mem_cgroup *mem = mc.to;
3500 if (mem_cgroup_is_root(mem)) {
3501 mc.precharge += count;
3502 /* we don't need css_get for root */
3505 /* try to charge at once */
3507 struct res_counter *dummy;
3509 * "mem" cannot be under rmdir() because we've already checked
3510 * by cgroup_lock_live_cgroup() that it is not removed and we
3511 * are still under the same cgroup_mutex. So we can postpone
3514 if (res_counter_charge(&mem->res, PAGE_SIZE * count, &dummy))
3516 if (do_swap_account && res_counter_charge(&mem->memsw,
3517 PAGE_SIZE * count, &dummy)) {
3518 res_counter_uncharge(&mem->res, PAGE_SIZE * count);
3521 mc.precharge += count;
3522 VM_BUG_ON(test_bit(CSS_ROOT, &mem->css.flags));
3523 WARN_ON_ONCE(count > INT_MAX);
3524 __css_get(&mem->css, (int)count);
3528 /* fall back to one by one charge */
3530 if (signal_pending(current)) {
3534 if (!batch_count--) {
3535 batch_count = PRECHARGE_COUNT_AT_ONCE;
3538 ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, &mem,
3541 /* mem_cgroup_clear_mc() will do uncharge later */
3549 * is_target_pte_for_mc - check a pte whether it is valid for move charge
3550 * @vma: the vma the pte to be checked belongs
3551 * @addr: the address corresponding to the pte to be checked
3552 * @ptent: the pte to be checked
3553 * @target: the pointer the target page will be stored(can be NULL)
3556 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
3557 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
3558 * move charge. if @target is not NULL, the page is stored in target->page
3559 * with extra refcnt got(Callers should handle it).
3561 * Called with pte lock held.
3563 /* We add a new member later. */
3568 /* We add a new type later. */
3569 enum mc_target_type {
3570 MC_TARGET_NONE, /* not used */
3574 static int is_target_pte_for_mc(struct vm_area_struct *vma,
3575 unsigned long addr, pte_t ptent, union mc_target *target)
3578 struct page_cgroup *pc;
3580 bool move_anon = test_bit(MOVE_CHARGE_TYPE_ANON,
3581 &mc.to->move_charge_at_immigrate);
3583 if (!pte_present(ptent))
3586 page = vm_normal_page(vma, addr, ptent);
3587 if (!page || !page_mapped(page))
3590 * TODO: We don't move charges of file(including shmem/tmpfs) pages for
3593 if (!move_anon || !PageAnon(page))
3596 * TODO: We don't move charges of shared(used by multiple processes)
3599 if (page_mapcount(page) > 1)
3601 if (!get_page_unless_zero(page))
3604 pc = lookup_page_cgroup(page);
3606 * Do only loose check w/o page_cgroup lock. mem_cgroup_move_account()
3607 * checks the pc is valid or not under the lock.
3609 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
3610 ret = MC_TARGET_PAGE;
3612 target->page = page;
3615 if (!ret || !target)
3621 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
3622 unsigned long addr, unsigned long end,
3623 struct mm_walk *walk)
3625 struct vm_area_struct *vma = walk->private;
3629 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
3630 for (; addr != end; pte++, addr += PAGE_SIZE)
3631 if (is_target_pte_for_mc(vma, addr, *pte, NULL))
3632 mc.precharge++; /* increment precharge temporarily */
3633 pte_unmap_unlock(pte - 1, ptl);
3639 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
3641 unsigned long precharge;
3642 struct vm_area_struct *vma;
3644 down_read(&mm->mmap_sem);
3645 for (vma = mm->mmap; vma; vma = vma->vm_next) {
3646 struct mm_walk mem_cgroup_count_precharge_walk = {
3647 .pmd_entry = mem_cgroup_count_precharge_pte_range,
3651 if (is_vm_hugetlb_page(vma))
3653 /* TODO: We don't move charges of shmem/tmpfs pages for now. */
3654 if (vma->vm_flags & VM_SHARED)
3656 walk_page_range(vma->vm_start, vma->vm_end,
3657 &mem_cgroup_count_precharge_walk);
3659 up_read(&mm->mmap_sem);
3661 precharge = mc.precharge;
3667 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
3669 return mem_cgroup_do_precharge(mem_cgroup_count_precharge(mm));
3672 static void mem_cgroup_clear_mc(void)
3674 /* we must uncharge all the leftover precharges from mc.to */
3676 __mem_cgroup_cancel_charge(mc.to, mc.precharge);
3680 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
3681 * we must uncharge here.
3683 if (mc.moved_charge) {
3684 __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
3685 mc.moved_charge = 0;
3689 mc.moving_task = NULL;
3690 wake_up_all(&mc.waitq);
3693 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
3694 struct cgroup *cgroup,
3695 struct task_struct *p,
3699 struct mem_cgroup *mem = mem_cgroup_from_cont(cgroup);
3701 if (mem->move_charge_at_immigrate) {
3702 struct mm_struct *mm;
3703 struct mem_cgroup *from = mem_cgroup_from_task(p);
3705 VM_BUG_ON(from == mem);
3707 mm = get_task_mm(p);
3710 /* We move charges only when we move a owner of the mm */
3711 if (mm->owner == p) {
3714 VM_BUG_ON(mc.precharge);
3715 VM_BUG_ON(mc.moved_charge);
3716 VM_BUG_ON(mc.moving_task);
3720 mc.moved_charge = 0;
3721 mc.moving_task = current;
3723 ret = mem_cgroup_precharge_mc(mm);
3725 mem_cgroup_clear_mc();
3732 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
3733 struct cgroup *cgroup,
3734 struct task_struct *p,
3737 mem_cgroup_clear_mc();
3740 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
3741 unsigned long addr, unsigned long end,
3742 struct mm_walk *walk)
3745 struct vm_area_struct *vma = walk->private;
3750 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
3751 for (; addr != end; addr += PAGE_SIZE) {
3752 pte_t ptent = *(pte++);
3753 union mc_target target;
3756 struct page_cgroup *pc;
3761 type = is_target_pte_for_mc(vma, addr, ptent, &target);
3763 case MC_TARGET_PAGE:
3765 if (isolate_lru_page(page))
3767 pc = lookup_page_cgroup(page);
3768 if (!mem_cgroup_move_account(pc,
3769 mc.from, mc.to, false)) {
3771 /* we uncharge from mc.from later. */
3774 putback_lru_page(page);
3775 put: /* is_target_pte_for_mc() gets the page */
3782 pte_unmap_unlock(pte - 1, ptl);
3787 * We have consumed all precharges we got in can_attach().
3788 * We try charge one by one, but don't do any additional
3789 * charges to mc.to if we have failed in charge once in attach()
3792 ret = mem_cgroup_do_precharge(1);
3800 static void mem_cgroup_move_charge(struct mm_struct *mm)
3802 struct vm_area_struct *vma;
3804 lru_add_drain_all();
3805 down_read(&mm->mmap_sem);
3806 for (vma = mm->mmap; vma; vma = vma->vm_next) {
3808 struct mm_walk mem_cgroup_move_charge_walk = {
3809 .pmd_entry = mem_cgroup_move_charge_pte_range,
3813 if (is_vm_hugetlb_page(vma))
3815 /* TODO: We don't move charges of shmem/tmpfs pages for now. */
3816 if (vma->vm_flags & VM_SHARED)
3818 ret = walk_page_range(vma->vm_start, vma->vm_end,
3819 &mem_cgroup_move_charge_walk);
3822 * means we have consumed all precharges and failed in
3823 * doing additional charge. Just abandon here.
3827 up_read(&mm->mmap_sem);
3830 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
3831 struct cgroup *cont,
3832 struct cgroup *old_cont,
3833 struct task_struct *p,
3836 struct mm_struct *mm;
3839 /* no need to move charge */
3842 mm = get_task_mm(p);
3844 mem_cgroup_move_charge(mm);
3847 mem_cgroup_clear_mc();
3850 struct cgroup_subsys mem_cgroup_subsys = {
3852 .subsys_id = mem_cgroup_subsys_id,
3853 .create = mem_cgroup_create,
3854 .pre_destroy = mem_cgroup_pre_destroy,
3855 .destroy = mem_cgroup_destroy,
3856 .populate = mem_cgroup_populate,
3857 .can_attach = mem_cgroup_can_attach,
3858 .cancel_attach = mem_cgroup_cancel_attach,
3859 .attach = mem_cgroup_move_task,
3864 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3866 static int __init disable_swap_account(char *s)
3868 really_do_swap_account = 0;
3871 __setup("noswapaccount", disable_swap_account);