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/swapops.h>
37 #include <linux/spinlock.h>
39 #include <linux/seq_file.h>
40 #include <linux/vmalloc.h>
41 #include <linux/mm_inline.h>
42 #include <linux/page_cgroup.h>
43 #include <linux/cpu.h>
46 #include <asm/uaccess.h>
48 struct cgroup_subsys mem_cgroup_subsys __read_mostly;
49 #define MEM_CGROUP_RECLAIM_RETRIES 5
50 struct mem_cgroup *root_mem_cgroup __read_mostly;
52 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
53 /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
54 int do_swap_account __read_mostly;
55 static int really_do_swap_account __initdata = 1; /* for remember boot option*/
57 #define do_swap_account (0)
60 #define SOFTLIMIT_EVENTS_THRESH (1000)
63 * Statistics for memory cgroup.
65 enum mem_cgroup_stat_index {
67 * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
69 MEM_CGROUP_STAT_CACHE, /* # of pages charged as cache */
70 MEM_CGROUP_STAT_RSS, /* # of pages charged as anon rss */
71 MEM_CGROUP_STAT_FILE_MAPPED, /* # of pages charged as file rss */
72 MEM_CGROUP_STAT_PGPGIN_COUNT, /* # of pages paged in */
73 MEM_CGROUP_STAT_PGPGOUT_COUNT, /* # of pages paged out */
74 MEM_CGROUP_STAT_SWAPOUT, /* # of pages, swapped out */
75 MEM_CGROUP_STAT_SOFTLIMIT, /* decrements on each page in/out.
76 used by soft limit implementation */
78 MEM_CGROUP_STAT_NSTATS,
81 struct mem_cgroup_stat_cpu {
82 s64 count[MEM_CGROUP_STAT_NSTATS];
83 } ____cacheline_aligned_in_smp;
85 struct mem_cgroup_stat {
86 struct mem_cgroup_stat_cpu cpustat[0];
90 __mem_cgroup_stat_set_safe(struct mem_cgroup_stat_cpu *stat,
91 enum mem_cgroup_stat_index idx, s64 val)
93 stat->count[idx] = val;
97 __mem_cgroup_stat_read_local(struct mem_cgroup_stat_cpu *stat,
98 enum mem_cgroup_stat_index idx)
100 return stat->count[idx];
104 * For accounting under irq disable, no need for increment preempt count.
106 static inline void __mem_cgroup_stat_add_safe(struct mem_cgroup_stat_cpu *stat,
107 enum mem_cgroup_stat_index idx, int val)
109 stat->count[idx] += val;
112 static s64 mem_cgroup_read_stat(struct mem_cgroup_stat *stat,
113 enum mem_cgroup_stat_index idx)
117 for_each_possible_cpu(cpu)
118 ret += stat->cpustat[cpu].count[idx];
122 static s64 mem_cgroup_local_usage(struct mem_cgroup_stat *stat)
126 ret = mem_cgroup_read_stat(stat, MEM_CGROUP_STAT_CACHE);
127 ret += mem_cgroup_read_stat(stat, MEM_CGROUP_STAT_RSS);
132 * per-zone information in memory controller.
134 struct mem_cgroup_per_zone {
136 * spin_lock to protect the per cgroup LRU
138 struct list_head lists[NR_LRU_LISTS];
139 unsigned long count[NR_LRU_LISTS];
141 struct zone_reclaim_stat reclaim_stat;
142 struct rb_node tree_node; /* RB tree node */
143 unsigned long long usage_in_excess;/* Set to the value by which */
144 /* the soft limit is exceeded*/
146 struct mem_cgroup *mem; /* Back pointer, we cannot */
147 /* use container_of */
149 /* Macro for accessing counter */
150 #define MEM_CGROUP_ZSTAT(mz, idx) ((mz)->count[(idx)])
152 struct mem_cgroup_per_node {
153 struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
156 struct mem_cgroup_lru_info {
157 struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
161 * Cgroups above their limits are maintained in a RB-Tree, independent of
162 * their hierarchy representation
165 struct mem_cgroup_tree_per_zone {
166 struct rb_root rb_root;
170 struct mem_cgroup_tree_per_node {
171 struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
174 struct mem_cgroup_tree {
175 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
178 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
181 * The memory controller data structure. The memory controller controls both
182 * page cache and RSS per cgroup. We would eventually like to provide
183 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
184 * to help the administrator determine what knobs to tune.
186 * TODO: Add a water mark for the memory controller. Reclaim will begin when
187 * we hit the water mark. May be even add a low water mark, such that
188 * no reclaim occurs from a cgroup at it's low water mark, this is
189 * a feature that will be implemented much later in the future.
192 struct cgroup_subsys_state css;
194 * the counter to account for memory usage
196 struct res_counter res;
198 * the counter to account for mem+swap usage.
200 struct res_counter memsw;
202 * Per cgroup active and inactive list, similar to the
203 * per zone LRU lists.
205 struct mem_cgroup_lru_info info;
208 protect against reclaim related member.
210 spinlock_t reclaim_param_lock;
212 int prev_priority; /* for recording reclaim priority */
215 * While reclaiming in a hierarchy, we cache the last child we
218 int last_scanned_child;
220 * Should the accounting and control be hierarchical, per subtree?
223 unsigned long last_oom_jiffies;
226 unsigned int swappiness;
228 /* set when res.limit == memsw.limit */
229 bool memsw_is_minimum;
232 * Should we move charges of a task when a task is moved into this
233 * mem_cgroup ? And what type of charges should we move ?
235 unsigned long move_charge_at_immigrate;
238 * statistics. This must be placed at the end of memcg.
240 struct mem_cgroup_stat stat;
243 /* Stuffs for move charges at task migration. */
245 * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a
246 * left-shifted bitmap of these types.
249 MOVE_CHARGE_TYPE_ANON, /* private anonymous page and swap of it */
253 /* "mc" and its members are protected by cgroup_mutex */
254 static struct move_charge_struct {
255 struct mem_cgroup *from;
256 struct mem_cgroup *to;
257 unsigned long precharge;
258 unsigned long moved_charge;
259 unsigned long moved_swap;
260 struct task_struct *moving_task; /* a task moving charges */
261 wait_queue_head_t waitq; /* a waitq for other context */
263 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
267 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
268 * limit reclaim to prevent infinite loops, if they ever occur.
270 #define MEM_CGROUP_MAX_RECLAIM_LOOPS (100)
271 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS (2)
274 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
275 MEM_CGROUP_CHARGE_TYPE_MAPPED,
276 MEM_CGROUP_CHARGE_TYPE_SHMEM, /* used by page migration of shmem */
277 MEM_CGROUP_CHARGE_TYPE_FORCE, /* used by force_empty */
278 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
279 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
283 /* only for here (for easy reading.) */
284 #define PCGF_CACHE (1UL << PCG_CACHE)
285 #define PCGF_USED (1UL << PCG_USED)
286 #define PCGF_LOCK (1UL << PCG_LOCK)
287 /* Not used, but added here for completeness */
288 #define PCGF_ACCT (1UL << PCG_ACCT)
290 /* for encoding cft->private value on file */
293 #define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val))
294 #define MEMFILE_TYPE(val) (((val) >> 16) & 0xffff)
295 #define MEMFILE_ATTR(val) ((val) & 0xffff)
298 * Reclaim flags for mem_cgroup_hierarchical_reclaim
300 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
301 #define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
302 #define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
303 #define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
304 #define MEM_CGROUP_RECLAIM_SOFT_BIT 0x2
305 #define MEM_CGROUP_RECLAIM_SOFT (1 << MEM_CGROUP_RECLAIM_SOFT_BIT)
307 static void mem_cgroup_get(struct mem_cgroup *mem);
308 static void mem_cgroup_put(struct mem_cgroup *mem);
309 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem);
310 static void drain_all_stock_async(void);
312 static struct mem_cgroup_per_zone *
313 mem_cgroup_zoneinfo(struct mem_cgroup *mem, int nid, int zid)
315 return &mem->info.nodeinfo[nid]->zoneinfo[zid];
318 struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *mem)
323 static struct mem_cgroup_per_zone *
324 page_cgroup_zoneinfo(struct page_cgroup *pc)
326 struct mem_cgroup *mem = pc->mem_cgroup;
327 int nid = page_cgroup_nid(pc);
328 int zid = page_cgroup_zid(pc);
333 return mem_cgroup_zoneinfo(mem, nid, zid);
336 static struct mem_cgroup_tree_per_zone *
337 soft_limit_tree_node_zone(int nid, int zid)
339 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
342 static struct mem_cgroup_tree_per_zone *
343 soft_limit_tree_from_page(struct page *page)
345 int nid = page_to_nid(page);
346 int zid = page_zonenum(page);
348 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
352 __mem_cgroup_insert_exceeded(struct mem_cgroup *mem,
353 struct mem_cgroup_per_zone *mz,
354 struct mem_cgroup_tree_per_zone *mctz,
355 unsigned long long new_usage_in_excess)
357 struct rb_node **p = &mctz->rb_root.rb_node;
358 struct rb_node *parent = NULL;
359 struct mem_cgroup_per_zone *mz_node;
364 mz->usage_in_excess = new_usage_in_excess;
365 if (!mz->usage_in_excess)
369 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
371 if (mz->usage_in_excess < mz_node->usage_in_excess)
374 * We can't avoid mem cgroups that are over their soft
375 * limit by the same amount
377 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
380 rb_link_node(&mz->tree_node, parent, p);
381 rb_insert_color(&mz->tree_node, &mctz->rb_root);
386 __mem_cgroup_remove_exceeded(struct mem_cgroup *mem,
387 struct mem_cgroup_per_zone *mz,
388 struct mem_cgroup_tree_per_zone *mctz)
392 rb_erase(&mz->tree_node, &mctz->rb_root);
397 mem_cgroup_remove_exceeded(struct mem_cgroup *mem,
398 struct mem_cgroup_per_zone *mz,
399 struct mem_cgroup_tree_per_zone *mctz)
401 spin_lock(&mctz->lock);
402 __mem_cgroup_remove_exceeded(mem, mz, mctz);
403 spin_unlock(&mctz->lock);
406 static bool mem_cgroup_soft_limit_check(struct mem_cgroup *mem)
411 struct mem_cgroup_stat_cpu *cpustat;
414 cpustat = &mem->stat.cpustat[cpu];
415 val = __mem_cgroup_stat_read_local(cpustat, MEM_CGROUP_STAT_SOFTLIMIT);
416 if (unlikely(val < 0)) {
417 __mem_cgroup_stat_set_safe(cpustat, MEM_CGROUP_STAT_SOFTLIMIT,
418 SOFTLIMIT_EVENTS_THRESH);
425 static void mem_cgroup_update_tree(struct mem_cgroup *mem, struct page *page)
427 unsigned long long excess;
428 struct mem_cgroup_per_zone *mz;
429 struct mem_cgroup_tree_per_zone *mctz;
430 int nid = page_to_nid(page);
431 int zid = page_zonenum(page);
432 mctz = soft_limit_tree_from_page(page);
435 * Necessary to update all ancestors when hierarchy is used.
436 * because their event counter is not touched.
438 for (; mem; mem = parent_mem_cgroup(mem)) {
439 mz = mem_cgroup_zoneinfo(mem, nid, zid);
440 excess = res_counter_soft_limit_excess(&mem->res);
442 * We have to update the tree if mz is on RB-tree or
443 * mem is over its softlimit.
445 if (excess || mz->on_tree) {
446 spin_lock(&mctz->lock);
447 /* if on-tree, remove it */
449 __mem_cgroup_remove_exceeded(mem, mz, mctz);
451 * Insert again. mz->usage_in_excess will be updated.
452 * If excess is 0, no tree ops.
454 __mem_cgroup_insert_exceeded(mem, mz, mctz, excess);
455 spin_unlock(&mctz->lock);
460 static void mem_cgroup_remove_from_trees(struct mem_cgroup *mem)
463 struct mem_cgroup_per_zone *mz;
464 struct mem_cgroup_tree_per_zone *mctz;
466 for_each_node_state(node, N_POSSIBLE) {
467 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
468 mz = mem_cgroup_zoneinfo(mem, node, zone);
469 mctz = soft_limit_tree_node_zone(node, zone);
470 mem_cgroup_remove_exceeded(mem, mz, mctz);
475 static inline unsigned long mem_cgroup_get_excess(struct mem_cgroup *mem)
477 return res_counter_soft_limit_excess(&mem->res) >> PAGE_SHIFT;
480 static struct mem_cgroup_per_zone *
481 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
483 struct rb_node *rightmost = NULL;
484 struct mem_cgroup_per_zone *mz;
488 rightmost = rb_last(&mctz->rb_root);
490 goto done; /* Nothing to reclaim from */
492 mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
494 * Remove the node now but someone else can add it back,
495 * we will to add it back at the end of reclaim to its correct
496 * position in the tree.
498 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
499 if (!res_counter_soft_limit_excess(&mz->mem->res) ||
500 !css_tryget(&mz->mem->css))
506 static struct mem_cgroup_per_zone *
507 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
509 struct mem_cgroup_per_zone *mz;
511 spin_lock(&mctz->lock);
512 mz = __mem_cgroup_largest_soft_limit_node(mctz);
513 spin_unlock(&mctz->lock);
517 static void mem_cgroup_swap_statistics(struct mem_cgroup *mem,
520 int val = (charge) ? 1 : -1;
521 struct mem_cgroup_stat *stat = &mem->stat;
522 struct mem_cgroup_stat_cpu *cpustat;
525 cpustat = &stat->cpustat[cpu];
526 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_SWAPOUT, val);
530 static void mem_cgroup_charge_statistics(struct mem_cgroup *mem,
531 struct page_cgroup *pc,
534 int val = (charge) ? 1 : -1;
535 struct mem_cgroup_stat *stat = &mem->stat;
536 struct mem_cgroup_stat_cpu *cpustat;
539 cpustat = &stat->cpustat[cpu];
540 if (PageCgroupCache(pc))
541 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_CACHE, val);
543 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_RSS, val);
546 __mem_cgroup_stat_add_safe(cpustat,
547 MEM_CGROUP_STAT_PGPGIN_COUNT, 1);
549 __mem_cgroup_stat_add_safe(cpustat,
550 MEM_CGROUP_STAT_PGPGOUT_COUNT, 1);
551 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_SOFTLIMIT, -1);
555 static unsigned long mem_cgroup_get_local_zonestat(struct mem_cgroup *mem,
559 struct mem_cgroup_per_zone *mz;
562 for_each_online_node(nid)
563 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
564 mz = mem_cgroup_zoneinfo(mem, nid, zid);
565 total += MEM_CGROUP_ZSTAT(mz, idx);
570 static struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
572 return container_of(cgroup_subsys_state(cont,
573 mem_cgroup_subsys_id), struct mem_cgroup,
577 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
580 * mm_update_next_owner() may clear mm->owner to NULL
581 * if it races with swapoff, page migration, etc.
582 * So this can be called with p == NULL.
587 return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
588 struct mem_cgroup, css);
591 static struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
593 struct mem_cgroup *mem = NULL;
598 * Because we have no locks, mm->owner's may be being moved to other
599 * cgroup. We use css_tryget() here even if this looks
600 * pessimistic (rather than adding locks here).
604 mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
607 } while (!css_tryget(&mem->css));
613 * Call callback function against all cgroup under hierarchy tree.
615 static int mem_cgroup_walk_tree(struct mem_cgroup *root, void *data,
616 int (*func)(struct mem_cgroup *, void *))
618 int found, ret, nextid;
619 struct cgroup_subsys_state *css;
620 struct mem_cgroup *mem;
622 if (!root->use_hierarchy)
623 return (*func)(root, data);
631 css = css_get_next(&mem_cgroup_subsys, nextid, &root->css,
633 if (css && css_tryget(css))
634 mem = container_of(css, struct mem_cgroup, css);
638 ret = (*func)(mem, data);
642 } while (!ret && css);
647 static inline bool mem_cgroup_is_root(struct mem_cgroup *mem)
649 return (mem == root_mem_cgroup);
653 * Following LRU functions are allowed to be used without PCG_LOCK.
654 * Operations are called by routine of global LRU independently from memcg.
655 * What we have to take care of here is validness of pc->mem_cgroup.
657 * Changes to pc->mem_cgroup happens when
660 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
661 * It is added to LRU before charge.
662 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
663 * When moving account, the page is not on LRU. It's isolated.
666 void mem_cgroup_del_lru_list(struct page *page, enum lru_list lru)
668 struct page_cgroup *pc;
669 struct mem_cgroup_per_zone *mz;
671 if (mem_cgroup_disabled())
673 pc = lookup_page_cgroup(page);
674 /* can happen while we handle swapcache. */
675 if (!TestClearPageCgroupAcctLRU(pc))
677 VM_BUG_ON(!pc->mem_cgroup);
679 * We don't check PCG_USED bit. It's cleared when the "page" is finally
680 * removed from global LRU.
682 mz = page_cgroup_zoneinfo(pc);
683 MEM_CGROUP_ZSTAT(mz, lru) -= 1;
684 if (mem_cgroup_is_root(pc->mem_cgroup))
686 VM_BUG_ON(list_empty(&pc->lru));
687 list_del_init(&pc->lru);
691 void mem_cgroup_del_lru(struct page *page)
693 mem_cgroup_del_lru_list(page, page_lru(page));
696 void mem_cgroup_rotate_lru_list(struct page *page, enum lru_list lru)
698 struct mem_cgroup_per_zone *mz;
699 struct page_cgroup *pc;
701 if (mem_cgroup_disabled())
704 pc = lookup_page_cgroup(page);
706 * Used bit is set without atomic ops but after smp_wmb().
707 * For making pc->mem_cgroup visible, insert smp_rmb() here.
710 /* unused or root page is not rotated. */
711 if (!PageCgroupUsed(pc) || mem_cgroup_is_root(pc->mem_cgroup))
713 mz = page_cgroup_zoneinfo(pc);
714 list_move(&pc->lru, &mz->lists[lru]);
717 void mem_cgroup_add_lru_list(struct page *page, enum lru_list lru)
719 struct page_cgroup *pc;
720 struct mem_cgroup_per_zone *mz;
722 if (mem_cgroup_disabled())
724 pc = lookup_page_cgroup(page);
725 VM_BUG_ON(PageCgroupAcctLRU(pc));
727 * Used bit is set without atomic ops but after smp_wmb().
728 * For making pc->mem_cgroup visible, insert smp_rmb() here.
731 if (!PageCgroupUsed(pc))
734 mz = page_cgroup_zoneinfo(pc);
735 MEM_CGROUP_ZSTAT(mz, lru) += 1;
736 SetPageCgroupAcctLRU(pc);
737 if (mem_cgroup_is_root(pc->mem_cgroup))
739 list_add(&pc->lru, &mz->lists[lru]);
743 * At handling SwapCache, pc->mem_cgroup may be changed while it's linked to
744 * lru because the page may.be reused after it's fully uncharged (because of
745 * SwapCache behavior).To handle that, unlink page_cgroup from LRU when charge
746 * it again. This function is only used to charge SwapCache. It's done under
747 * lock_page and expected that zone->lru_lock is never held.
749 static void mem_cgroup_lru_del_before_commit_swapcache(struct page *page)
752 struct zone *zone = page_zone(page);
753 struct page_cgroup *pc = lookup_page_cgroup(page);
755 spin_lock_irqsave(&zone->lru_lock, flags);
757 * Forget old LRU when this page_cgroup is *not* used. This Used bit
758 * is guarded by lock_page() because the page is SwapCache.
760 if (!PageCgroupUsed(pc))
761 mem_cgroup_del_lru_list(page, page_lru(page));
762 spin_unlock_irqrestore(&zone->lru_lock, flags);
765 static void mem_cgroup_lru_add_after_commit_swapcache(struct page *page)
768 struct zone *zone = page_zone(page);
769 struct page_cgroup *pc = lookup_page_cgroup(page);
771 spin_lock_irqsave(&zone->lru_lock, flags);
772 /* link when the page is linked to LRU but page_cgroup isn't */
773 if (PageLRU(page) && !PageCgroupAcctLRU(pc))
774 mem_cgroup_add_lru_list(page, page_lru(page));
775 spin_unlock_irqrestore(&zone->lru_lock, flags);
779 void mem_cgroup_move_lists(struct page *page,
780 enum lru_list from, enum lru_list to)
782 if (mem_cgroup_disabled())
784 mem_cgroup_del_lru_list(page, from);
785 mem_cgroup_add_lru_list(page, to);
788 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *mem)
791 struct mem_cgroup *curr = NULL;
795 curr = try_get_mem_cgroup_from_mm(task->mm);
801 * We should check use_hierarchy of "mem" not "curr". Because checking
802 * use_hierarchy of "curr" here make this function true if hierarchy is
803 * enabled in "curr" and "curr" is a child of "mem" in *cgroup*
804 * hierarchy(even if use_hierarchy is disabled in "mem").
806 if (mem->use_hierarchy)
807 ret = css_is_ancestor(&curr->css, &mem->css);
815 * prev_priority control...this will be used in memory reclaim path.
817 int mem_cgroup_get_reclaim_priority(struct mem_cgroup *mem)
821 spin_lock(&mem->reclaim_param_lock);
822 prev_priority = mem->prev_priority;
823 spin_unlock(&mem->reclaim_param_lock);
825 return prev_priority;
828 void mem_cgroup_note_reclaim_priority(struct mem_cgroup *mem, int priority)
830 spin_lock(&mem->reclaim_param_lock);
831 if (priority < mem->prev_priority)
832 mem->prev_priority = priority;
833 spin_unlock(&mem->reclaim_param_lock);
836 void mem_cgroup_record_reclaim_priority(struct mem_cgroup *mem, int priority)
838 spin_lock(&mem->reclaim_param_lock);
839 mem->prev_priority = priority;
840 spin_unlock(&mem->reclaim_param_lock);
843 static int calc_inactive_ratio(struct mem_cgroup *memcg, unsigned long *present_pages)
845 unsigned long active;
846 unsigned long inactive;
848 unsigned long inactive_ratio;
850 inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_ANON);
851 active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_ANON);
853 gb = (inactive + active) >> (30 - PAGE_SHIFT);
855 inactive_ratio = int_sqrt(10 * gb);
860 present_pages[0] = inactive;
861 present_pages[1] = active;
864 return inactive_ratio;
867 int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg)
869 unsigned long active;
870 unsigned long inactive;
871 unsigned long present_pages[2];
872 unsigned long inactive_ratio;
874 inactive_ratio = calc_inactive_ratio(memcg, present_pages);
876 inactive = present_pages[0];
877 active = present_pages[1];
879 if (inactive * inactive_ratio < active)
885 int mem_cgroup_inactive_file_is_low(struct mem_cgroup *memcg)
887 unsigned long active;
888 unsigned long inactive;
890 inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_FILE);
891 active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_FILE);
893 return (active > inactive);
896 unsigned long mem_cgroup_zone_nr_pages(struct mem_cgroup *memcg,
900 int nid = zone->zone_pgdat->node_id;
901 int zid = zone_idx(zone);
902 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
904 return MEM_CGROUP_ZSTAT(mz, lru);
907 struct zone_reclaim_stat *mem_cgroup_get_reclaim_stat(struct mem_cgroup *memcg,
910 int nid = zone->zone_pgdat->node_id;
911 int zid = zone_idx(zone);
912 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
914 return &mz->reclaim_stat;
917 struct zone_reclaim_stat *
918 mem_cgroup_get_reclaim_stat_from_page(struct page *page)
920 struct page_cgroup *pc;
921 struct mem_cgroup_per_zone *mz;
923 if (mem_cgroup_disabled())
926 pc = lookup_page_cgroup(page);
928 * Used bit is set without atomic ops but after smp_wmb().
929 * For making pc->mem_cgroup visible, insert smp_rmb() here.
932 if (!PageCgroupUsed(pc))
935 mz = page_cgroup_zoneinfo(pc);
939 return &mz->reclaim_stat;
942 unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan,
943 struct list_head *dst,
944 unsigned long *scanned, int order,
945 int mode, struct zone *z,
946 struct mem_cgroup *mem_cont,
947 int active, int file)
949 unsigned long nr_taken = 0;
953 struct list_head *src;
954 struct page_cgroup *pc, *tmp;
955 int nid = z->zone_pgdat->node_id;
956 int zid = zone_idx(z);
957 struct mem_cgroup_per_zone *mz;
958 int lru = LRU_FILE * file + active;
962 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
963 src = &mz->lists[lru];
966 list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
967 if (scan >= nr_to_scan)
971 if (unlikely(!PageCgroupUsed(pc)))
973 if (unlikely(!PageLRU(page)))
977 ret = __isolate_lru_page(page, mode, file);
980 list_move(&page->lru, dst);
981 mem_cgroup_del_lru(page);
985 /* we don't affect global LRU but rotate in our LRU */
986 mem_cgroup_rotate_lru_list(page, page_lru(page));
997 #define mem_cgroup_from_res_counter(counter, member) \
998 container_of(counter, struct mem_cgroup, member)
1000 static bool mem_cgroup_check_under_limit(struct mem_cgroup *mem)
1002 if (do_swap_account) {
1003 if (res_counter_check_under_limit(&mem->res) &&
1004 res_counter_check_under_limit(&mem->memsw))
1007 if (res_counter_check_under_limit(&mem->res))
1012 static unsigned int get_swappiness(struct mem_cgroup *memcg)
1014 struct cgroup *cgrp = memcg->css.cgroup;
1015 unsigned int swappiness;
1018 if (cgrp->parent == NULL)
1019 return vm_swappiness;
1021 spin_lock(&memcg->reclaim_param_lock);
1022 swappiness = memcg->swappiness;
1023 spin_unlock(&memcg->reclaim_param_lock);
1028 static int mem_cgroup_count_children_cb(struct mem_cgroup *mem, void *data)
1036 * mem_cgroup_print_mem_info: Called from OOM with tasklist_lock held in read mode.
1037 * @memcg: The memory cgroup that went over limit
1038 * @p: Task that is going to be killed
1040 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1043 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1045 struct cgroup *task_cgrp;
1046 struct cgroup *mem_cgrp;
1048 * Need a buffer in BSS, can't rely on allocations. The code relies
1049 * on the assumption that OOM is serialized for memory controller.
1050 * If this assumption is broken, revisit this code.
1052 static char memcg_name[PATH_MAX];
1061 mem_cgrp = memcg->css.cgroup;
1062 task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1064 ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1067 * Unfortunately, we are unable to convert to a useful name
1068 * But we'll still print out the usage information
1075 printk(KERN_INFO "Task in %s killed", memcg_name);
1078 ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1086 * Continues from above, so we don't need an KERN_ level
1088 printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
1091 printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
1092 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1093 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1094 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1095 printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
1097 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1098 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1099 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1103 * This function returns the number of memcg under hierarchy tree. Returns
1104 * 1(self count) if no children.
1106 static int mem_cgroup_count_children(struct mem_cgroup *mem)
1109 mem_cgroup_walk_tree(mem, &num, mem_cgroup_count_children_cb);
1114 * Visit the first child (need not be the first child as per the ordering
1115 * of the cgroup list, since we track last_scanned_child) of @mem and use
1116 * that to reclaim free pages from.
1118 static struct mem_cgroup *
1119 mem_cgroup_select_victim(struct mem_cgroup *root_mem)
1121 struct mem_cgroup *ret = NULL;
1122 struct cgroup_subsys_state *css;
1125 if (!root_mem->use_hierarchy) {
1126 css_get(&root_mem->css);
1132 nextid = root_mem->last_scanned_child + 1;
1133 css = css_get_next(&mem_cgroup_subsys, nextid, &root_mem->css,
1135 if (css && css_tryget(css))
1136 ret = container_of(css, struct mem_cgroup, css);
1139 /* Updates scanning parameter */
1140 spin_lock(&root_mem->reclaim_param_lock);
1142 /* this means start scan from ID:1 */
1143 root_mem->last_scanned_child = 0;
1145 root_mem->last_scanned_child = found;
1146 spin_unlock(&root_mem->reclaim_param_lock);
1153 * Scan the hierarchy if needed to reclaim memory. We remember the last child
1154 * we reclaimed from, so that we don't end up penalizing one child extensively
1155 * based on its position in the children list.
1157 * root_mem is the original ancestor that we've been reclaim from.
1159 * We give up and return to the caller when we visit root_mem twice.
1160 * (other groups can be removed while we're walking....)
1162 * If shrink==true, for avoiding to free too much, this returns immedieately.
1164 static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup *root_mem,
1167 unsigned long reclaim_options)
1169 struct mem_cgroup *victim;
1172 bool noswap = reclaim_options & MEM_CGROUP_RECLAIM_NOSWAP;
1173 bool shrink = reclaim_options & MEM_CGROUP_RECLAIM_SHRINK;
1174 bool check_soft = reclaim_options & MEM_CGROUP_RECLAIM_SOFT;
1175 unsigned long excess = mem_cgroup_get_excess(root_mem);
1177 /* If memsw_is_minimum==1, swap-out is of-no-use. */
1178 if (root_mem->memsw_is_minimum)
1182 victim = mem_cgroup_select_victim(root_mem);
1183 if (victim == root_mem) {
1186 drain_all_stock_async();
1189 * If we have not been able to reclaim
1190 * anything, it might because there are
1191 * no reclaimable pages under this hierarchy
1193 if (!check_soft || !total) {
1194 css_put(&victim->css);
1198 * We want to do more targetted reclaim.
1199 * excess >> 2 is not to excessive so as to
1200 * reclaim too much, nor too less that we keep
1201 * coming back to reclaim from this cgroup
1203 if (total >= (excess >> 2) ||
1204 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS)) {
1205 css_put(&victim->css);
1210 if (!mem_cgroup_local_usage(&victim->stat)) {
1211 /* this cgroup's local usage == 0 */
1212 css_put(&victim->css);
1215 /* we use swappiness of local cgroup */
1217 ret = mem_cgroup_shrink_node_zone(victim, gfp_mask,
1218 noswap, get_swappiness(victim), zone,
1219 zone->zone_pgdat->node_id);
1221 ret = try_to_free_mem_cgroup_pages(victim, gfp_mask,
1222 noswap, get_swappiness(victim));
1223 css_put(&victim->css);
1225 * At shrinking usage, we can't check we should stop here or
1226 * reclaim more. It's depends on callers. last_scanned_child
1227 * will work enough for keeping fairness under tree.
1233 if (res_counter_check_under_soft_limit(&root_mem->res))
1235 } else if (mem_cgroup_check_under_limit(root_mem))
1241 bool mem_cgroup_oom_called(struct task_struct *task)
1244 struct mem_cgroup *mem;
1245 struct mm_struct *mm;
1251 mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
1252 if (mem && time_before(jiffies, mem->last_oom_jiffies + HZ/10))
1258 static int record_last_oom_cb(struct mem_cgroup *mem, void *data)
1260 mem->last_oom_jiffies = jiffies;
1264 static void record_last_oom(struct mem_cgroup *mem)
1266 mem_cgroup_walk_tree(mem, NULL, record_last_oom_cb);
1270 * Currently used to update mapped file statistics, but the routine can be
1271 * generalized to update other statistics as well.
1273 void mem_cgroup_update_file_mapped(struct page *page, int val)
1275 struct mem_cgroup *mem;
1276 struct mem_cgroup_stat *stat;
1277 struct mem_cgroup_stat_cpu *cpustat;
1279 struct page_cgroup *pc;
1281 pc = lookup_page_cgroup(page);
1285 lock_page_cgroup(pc);
1286 mem = pc->mem_cgroup;
1290 if (!PageCgroupUsed(pc))
1294 * Preemption is already disabled, we don't need get_cpu()
1296 cpu = smp_processor_id();
1298 cpustat = &stat->cpustat[cpu];
1300 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_FILE_MAPPED, val);
1302 unlock_page_cgroup(pc);
1306 * size of first charge trial. "32" comes from vmscan.c's magic value.
1307 * TODO: maybe necessary to use big numbers in big irons.
1309 #define CHARGE_SIZE (32 * PAGE_SIZE)
1310 struct memcg_stock_pcp {
1311 struct mem_cgroup *cached; /* this never be root cgroup */
1313 struct work_struct work;
1315 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
1316 static atomic_t memcg_drain_count;
1319 * Try to consume stocked charge on this cpu. If success, PAGE_SIZE is consumed
1320 * from local stock and true is returned. If the stock is 0 or charges from a
1321 * cgroup which is not current target, returns false. This stock will be
1324 static bool consume_stock(struct mem_cgroup *mem)
1326 struct memcg_stock_pcp *stock;
1329 stock = &get_cpu_var(memcg_stock);
1330 if (mem == stock->cached && stock->charge)
1331 stock->charge -= PAGE_SIZE;
1332 else /* need to call res_counter_charge */
1334 put_cpu_var(memcg_stock);
1339 * Returns stocks cached in percpu to res_counter and reset cached information.
1341 static void drain_stock(struct memcg_stock_pcp *stock)
1343 struct mem_cgroup *old = stock->cached;
1345 if (stock->charge) {
1346 res_counter_uncharge(&old->res, stock->charge);
1347 if (do_swap_account)
1348 res_counter_uncharge(&old->memsw, stock->charge);
1350 stock->cached = NULL;
1355 * This must be called under preempt disabled or must be called by
1356 * a thread which is pinned to local cpu.
1358 static void drain_local_stock(struct work_struct *dummy)
1360 struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
1365 * Cache charges(val) which is from res_counter, to local per_cpu area.
1366 * This will be consumed by consumt_stock() function, later.
1368 static void refill_stock(struct mem_cgroup *mem, int val)
1370 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
1372 if (stock->cached != mem) { /* reset if necessary */
1374 stock->cached = mem;
1376 stock->charge += val;
1377 put_cpu_var(memcg_stock);
1381 * Tries to drain stocked charges in other cpus. This function is asynchronous
1382 * and just put a work per cpu for draining localy on each cpu. Caller can
1383 * expects some charges will be back to res_counter later but cannot wait for
1386 static void drain_all_stock_async(void)
1389 /* This function is for scheduling "drain" in asynchronous way.
1390 * The result of "drain" is not directly handled by callers. Then,
1391 * if someone is calling drain, we don't have to call drain more.
1392 * Anyway, WORK_STRUCT_PENDING check in queue_work_on() will catch if
1393 * there is a race. We just do loose check here.
1395 if (atomic_read(&memcg_drain_count))
1397 /* Notify other cpus that system-wide "drain" is running */
1398 atomic_inc(&memcg_drain_count);
1400 for_each_online_cpu(cpu) {
1401 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
1402 schedule_work_on(cpu, &stock->work);
1405 atomic_dec(&memcg_drain_count);
1406 /* We don't wait for flush_work */
1409 /* This is a synchronous drain interface. */
1410 static void drain_all_stock_sync(void)
1412 /* called when force_empty is called */
1413 atomic_inc(&memcg_drain_count);
1414 schedule_on_each_cpu(drain_local_stock);
1415 atomic_dec(&memcg_drain_count);
1418 static int __cpuinit memcg_stock_cpu_callback(struct notifier_block *nb,
1419 unsigned long action,
1422 int cpu = (unsigned long)hcpu;
1423 struct memcg_stock_pcp *stock;
1425 if (action != CPU_DEAD)
1427 stock = &per_cpu(memcg_stock, cpu);
1433 * Unlike exported interface, "oom" parameter is added. if oom==true,
1434 * oom-killer can be invoked.
1436 static int __mem_cgroup_try_charge(struct mm_struct *mm,
1437 gfp_t gfp_mask, struct mem_cgroup **memcg,
1438 bool oom, struct page *page)
1440 struct mem_cgroup *mem, *mem_over_limit;
1441 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
1442 struct res_counter *fail_res;
1443 int csize = CHARGE_SIZE;
1445 if (unlikely(test_thread_flag(TIF_MEMDIE))) {
1446 /* Don't account this! */
1452 * We always charge the cgroup the mm_struct belongs to.
1453 * The mm_struct's mem_cgroup changes on task migration if the
1454 * thread group leader migrates. It's possible that mm is not
1455 * set, if so charge the init_mm (happens for pagecache usage).
1459 mem = try_get_mem_cgroup_from_mm(mm);
1467 VM_BUG_ON(css_is_removed(&mem->css));
1468 if (mem_cgroup_is_root(mem))
1473 unsigned long flags = 0;
1475 if (consume_stock(mem))
1478 ret = res_counter_charge(&mem->res, csize, &fail_res);
1480 if (!do_swap_account)
1482 ret = res_counter_charge(&mem->memsw, csize, &fail_res);
1485 /* mem+swap counter fails */
1486 res_counter_uncharge(&mem->res, csize);
1487 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
1488 mem_over_limit = mem_cgroup_from_res_counter(fail_res,
1491 /* mem counter fails */
1492 mem_over_limit = mem_cgroup_from_res_counter(fail_res,
1495 /* reduce request size and retry */
1496 if (csize > PAGE_SIZE) {
1500 if (!(gfp_mask & __GFP_WAIT))
1503 ret = mem_cgroup_hierarchical_reclaim(mem_over_limit, NULL,
1509 * try_to_free_mem_cgroup_pages() might not give us a full
1510 * picture of reclaim. Some pages are reclaimed and might be
1511 * moved to swap cache or just unmapped from the cgroup.
1512 * Check the limit again to see if the reclaim reduced the
1513 * current usage of the cgroup before giving up
1516 if (mem_cgroup_check_under_limit(mem_over_limit))
1519 /* try to avoid oom while someone is moving charge */
1520 if (mc.moving_task && current != mc.moving_task) {
1521 struct mem_cgroup *from, *to;
1522 bool do_continue = false;
1524 * There is a small race that "from" or "to" can be
1525 * freed by rmdir, so we use css_tryget().
1530 if (from && css_tryget(&from->css)) {
1531 if (mem_over_limit->use_hierarchy)
1532 do_continue = css_is_ancestor(
1534 &mem_over_limit->css);
1536 do_continue = (from == mem_over_limit);
1537 css_put(&from->css);
1539 if (!do_continue && to && css_tryget(&to->css)) {
1540 if (mem_over_limit->use_hierarchy)
1541 do_continue = css_is_ancestor(
1543 &mem_over_limit->css);
1545 do_continue = (to == mem_over_limit);
1551 prepare_to_wait(&mc.waitq, &wait,
1552 TASK_INTERRUPTIBLE);
1553 /* moving charge context might have finished. */
1556 finish_wait(&mc.waitq, &wait);
1561 if (!nr_retries--) {
1563 mem_cgroup_out_of_memory(mem_over_limit, gfp_mask);
1564 record_last_oom(mem_over_limit);
1569 if (csize > PAGE_SIZE)
1570 refill_stock(mem, csize - PAGE_SIZE);
1573 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
1574 * if they exceeds softlimit.
1576 if (page && mem_cgroup_soft_limit_check(mem))
1577 mem_cgroup_update_tree(mem, page);
1586 * Somemtimes we have to undo a charge we got by try_charge().
1587 * This function is for that and do uncharge, put css's refcnt.
1588 * gotten by try_charge().
1590 static void __mem_cgroup_cancel_charge(struct mem_cgroup *mem,
1591 unsigned long count)
1593 if (!mem_cgroup_is_root(mem)) {
1594 res_counter_uncharge(&mem->res, PAGE_SIZE * count);
1595 if (do_swap_account)
1596 res_counter_uncharge(&mem->memsw, PAGE_SIZE * count);
1597 VM_BUG_ON(test_bit(CSS_ROOT, &mem->css.flags));
1598 WARN_ON_ONCE(count > INT_MAX);
1599 __css_put(&mem->css, (int)count);
1601 /* we don't need css_put for root */
1604 static void mem_cgroup_cancel_charge(struct mem_cgroup *mem)
1606 __mem_cgroup_cancel_charge(mem, 1);
1610 * A helper function to get mem_cgroup from ID. must be called under
1611 * rcu_read_lock(). The caller must check css_is_removed() or some if
1612 * it's concern. (dropping refcnt from swap can be called against removed
1615 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
1617 struct cgroup_subsys_state *css;
1619 /* ID 0 is unused ID */
1622 css = css_lookup(&mem_cgroup_subsys, id);
1625 return container_of(css, struct mem_cgroup, css);
1628 struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
1630 struct mem_cgroup *mem = NULL;
1631 struct page_cgroup *pc;
1635 VM_BUG_ON(!PageLocked(page));
1637 pc = lookup_page_cgroup(page);
1638 lock_page_cgroup(pc);
1639 if (PageCgroupUsed(pc)) {
1640 mem = pc->mem_cgroup;
1641 if (mem && !css_tryget(&mem->css))
1643 } else if (PageSwapCache(page)) {
1644 ent.val = page_private(page);
1645 id = lookup_swap_cgroup(ent);
1647 mem = mem_cgroup_lookup(id);
1648 if (mem && !css_tryget(&mem->css))
1652 unlock_page_cgroup(pc);
1657 * commit a charge got by __mem_cgroup_try_charge() and makes page_cgroup to be
1658 * USED state. If already USED, uncharge and return.
1661 static void __mem_cgroup_commit_charge(struct mem_cgroup *mem,
1662 struct page_cgroup *pc,
1663 enum charge_type ctype)
1665 /* try_charge() can return NULL to *memcg, taking care of it. */
1669 lock_page_cgroup(pc);
1670 if (unlikely(PageCgroupUsed(pc))) {
1671 unlock_page_cgroup(pc);
1672 mem_cgroup_cancel_charge(mem);
1676 pc->mem_cgroup = mem;
1678 * We access a page_cgroup asynchronously without lock_page_cgroup().
1679 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
1680 * is accessed after testing USED bit. To make pc->mem_cgroup visible
1681 * before USED bit, we need memory barrier here.
1682 * See mem_cgroup_add_lru_list(), etc.
1686 case MEM_CGROUP_CHARGE_TYPE_CACHE:
1687 case MEM_CGROUP_CHARGE_TYPE_SHMEM:
1688 SetPageCgroupCache(pc);
1689 SetPageCgroupUsed(pc);
1691 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
1692 ClearPageCgroupCache(pc);
1693 SetPageCgroupUsed(pc);
1699 mem_cgroup_charge_statistics(mem, pc, true);
1701 unlock_page_cgroup(pc);
1705 * __mem_cgroup_move_account - move account of the page
1706 * @pc: page_cgroup of the page.
1707 * @from: mem_cgroup which the page is moved from.
1708 * @to: mem_cgroup which the page is moved to. @from != @to.
1709 * @uncharge: whether we should call uncharge and css_put against @from.
1711 * The caller must confirm following.
1712 * - page is not on LRU (isolate_page() is useful.)
1713 * - the pc is locked, used, and ->mem_cgroup points to @from.
1715 * This function doesn't do "charge" nor css_get to new cgroup. It should be
1716 * done by a caller(__mem_cgroup_try_charge would be usefull). If @uncharge is
1717 * true, this function does "uncharge" from old cgroup, but it doesn't if
1718 * @uncharge is false, so a caller should do "uncharge".
1721 static void __mem_cgroup_move_account(struct page_cgroup *pc,
1722 struct mem_cgroup *from, struct mem_cgroup *to, bool uncharge)
1726 struct mem_cgroup_stat *stat;
1727 struct mem_cgroup_stat_cpu *cpustat;
1729 VM_BUG_ON(from == to);
1730 VM_BUG_ON(PageLRU(pc->page));
1731 VM_BUG_ON(!PageCgroupLocked(pc));
1732 VM_BUG_ON(!PageCgroupUsed(pc));
1733 VM_BUG_ON(pc->mem_cgroup != from);
1736 if (page_mapped(page) && !PageAnon(page)) {
1737 cpu = smp_processor_id();
1738 /* Update mapped_file data for mem_cgroup "from" */
1740 cpustat = &stat->cpustat[cpu];
1741 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_FILE_MAPPED,
1744 /* Update mapped_file data for mem_cgroup "to" */
1746 cpustat = &stat->cpustat[cpu];
1747 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_FILE_MAPPED,
1750 mem_cgroup_charge_statistics(from, pc, false);
1752 /* This is not "cancel", but cancel_charge does all we need. */
1753 mem_cgroup_cancel_charge(from);
1755 /* caller should have done css_get */
1756 pc->mem_cgroup = to;
1757 mem_cgroup_charge_statistics(to, pc, true);
1759 * We charges against "to" which may not have any tasks. Then, "to"
1760 * can be under rmdir(). But in current implementation, caller of
1761 * this function is just force_empty() and move charge, so it's
1762 * garanteed that "to" is never removed. So, we don't check rmdir
1768 * check whether the @pc is valid for moving account and call
1769 * __mem_cgroup_move_account()
1771 static int mem_cgroup_move_account(struct page_cgroup *pc,
1772 struct mem_cgroup *from, struct mem_cgroup *to, bool uncharge)
1775 lock_page_cgroup(pc);
1776 if (PageCgroupUsed(pc) && pc->mem_cgroup == from) {
1777 __mem_cgroup_move_account(pc, from, to, uncharge);
1780 unlock_page_cgroup(pc);
1785 * move charges to its parent.
1788 static int mem_cgroup_move_parent(struct page_cgroup *pc,
1789 struct mem_cgroup *child,
1792 struct page *page = pc->page;
1793 struct cgroup *cg = child->css.cgroup;
1794 struct cgroup *pcg = cg->parent;
1795 struct mem_cgroup *parent;
1803 if (!get_page_unless_zero(page))
1805 if (isolate_lru_page(page))
1808 parent = mem_cgroup_from_cont(pcg);
1809 ret = __mem_cgroup_try_charge(NULL, gfp_mask, &parent, false, page);
1813 ret = mem_cgroup_move_account(pc, child, parent, true);
1815 mem_cgroup_cancel_charge(parent);
1817 putback_lru_page(page);
1825 * Charge the memory controller for page usage.
1827 * 0 if the charge was successful
1828 * < 0 if the cgroup is over its limit
1830 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
1831 gfp_t gfp_mask, enum charge_type ctype,
1832 struct mem_cgroup *memcg)
1834 struct mem_cgroup *mem;
1835 struct page_cgroup *pc;
1838 pc = lookup_page_cgroup(page);
1839 /* can happen at boot */
1845 ret = __mem_cgroup_try_charge(mm, gfp_mask, &mem, true, page);
1849 __mem_cgroup_commit_charge(mem, pc, ctype);
1853 int mem_cgroup_newpage_charge(struct page *page,
1854 struct mm_struct *mm, gfp_t gfp_mask)
1856 if (mem_cgroup_disabled())
1858 if (PageCompound(page))
1861 * If already mapped, we don't have to account.
1862 * If page cache, page->mapping has address_space.
1863 * But page->mapping may have out-of-use anon_vma pointer,
1864 * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
1867 if (page_mapped(page) || (page->mapping && !PageAnon(page)))
1871 return mem_cgroup_charge_common(page, mm, gfp_mask,
1872 MEM_CGROUP_CHARGE_TYPE_MAPPED, NULL);
1876 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
1877 enum charge_type ctype);
1879 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
1882 struct mem_cgroup *mem = NULL;
1885 if (mem_cgroup_disabled())
1887 if (PageCompound(page))
1890 * Corner case handling. This is called from add_to_page_cache()
1891 * in usual. But some FS (shmem) precharges this page before calling it
1892 * and call add_to_page_cache() with GFP_NOWAIT.
1894 * For GFP_NOWAIT case, the page may be pre-charged before calling
1895 * add_to_page_cache(). (See shmem.c) check it here and avoid to call
1896 * charge twice. (It works but has to pay a bit larger cost.)
1897 * And when the page is SwapCache, it should take swap information
1898 * into account. This is under lock_page() now.
1900 if (!(gfp_mask & __GFP_WAIT)) {
1901 struct page_cgroup *pc;
1904 pc = lookup_page_cgroup(page);
1907 lock_page_cgroup(pc);
1908 if (PageCgroupUsed(pc)) {
1909 unlock_page_cgroup(pc);
1912 unlock_page_cgroup(pc);
1915 if (unlikely(!mm && !mem))
1918 if (page_is_file_cache(page))
1919 return mem_cgroup_charge_common(page, mm, gfp_mask,
1920 MEM_CGROUP_CHARGE_TYPE_CACHE, NULL);
1923 if (PageSwapCache(page)) {
1924 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
1926 __mem_cgroup_commit_charge_swapin(page, mem,
1927 MEM_CGROUP_CHARGE_TYPE_SHMEM);
1929 ret = mem_cgroup_charge_common(page, mm, gfp_mask,
1930 MEM_CGROUP_CHARGE_TYPE_SHMEM, mem);
1936 * While swap-in, try_charge -> commit or cancel, the page is locked.
1937 * And when try_charge() successfully returns, one refcnt to memcg without
1938 * struct page_cgroup is acquired. This refcnt will be consumed by
1939 * "commit()" or removed by "cancel()"
1941 int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
1943 gfp_t mask, struct mem_cgroup **ptr)
1945 struct mem_cgroup *mem;
1948 if (mem_cgroup_disabled())
1951 if (!do_swap_account)
1954 * A racing thread's fault, or swapoff, may have already updated
1955 * the pte, and even removed page from swap cache: in those cases
1956 * do_swap_page()'s pte_same() test will fail; but there's also a
1957 * KSM case which does need to charge the page.
1959 if (!PageSwapCache(page))
1961 mem = try_get_mem_cgroup_from_page(page);
1965 ret = __mem_cgroup_try_charge(NULL, mask, ptr, true, page);
1966 /* drop extra refcnt from tryget */
1972 return __mem_cgroup_try_charge(mm, mask, ptr, true, page);
1976 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
1977 enum charge_type ctype)
1979 struct page_cgroup *pc;
1981 if (mem_cgroup_disabled())
1985 cgroup_exclude_rmdir(&ptr->css);
1986 pc = lookup_page_cgroup(page);
1987 mem_cgroup_lru_del_before_commit_swapcache(page);
1988 __mem_cgroup_commit_charge(ptr, pc, ctype);
1989 mem_cgroup_lru_add_after_commit_swapcache(page);
1991 * Now swap is on-memory. This means this page may be
1992 * counted both as mem and swap....double count.
1993 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
1994 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
1995 * may call delete_from_swap_cache() before reach here.
1997 if (do_swap_account && PageSwapCache(page)) {
1998 swp_entry_t ent = {.val = page_private(page)};
2000 struct mem_cgroup *memcg;
2002 id = swap_cgroup_record(ent, 0);
2004 memcg = mem_cgroup_lookup(id);
2007 * This recorded memcg can be obsolete one. So, avoid
2008 * calling css_tryget
2010 if (!mem_cgroup_is_root(memcg))
2011 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
2012 mem_cgroup_swap_statistics(memcg, false);
2013 mem_cgroup_put(memcg);
2018 * At swapin, we may charge account against cgroup which has no tasks.
2019 * So, rmdir()->pre_destroy() can be called while we do this charge.
2020 * In that case, we need to call pre_destroy() again. check it here.
2022 cgroup_release_and_wakeup_rmdir(&ptr->css);
2025 void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
2027 __mem_cgroup_commit_charge_swapin(page, ptr,
2028 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2031 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *mem)
2033 if (mem_cgroup_disabled())
2037 mem_cgroup_cancel_charge(mem);
2041 __do_uncharge(struct mem_cgroup *mem, const enum charge_type ctype)
2043 struct memcg_batch_info *batch = NULL;
2044 bool uncharge_memsw = true;
2045 /* If swapout, usage of swap doesn't decrease */
2046 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2047 uncharge_memsw = false;
2049 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
2050 * In those cases, all pages freed continously can be expected to be in
2051 * the same cgroup and we have chance to coalesce uncharges.
2052 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
2053 * because we want to do uncharge as soon as possible.
2055 if (!current->memcg_batch.do_batch || test_thread_flag(TIF_MEMDIE))
2056 goto direct_uncharge;
2058 batch = ¤t->memcg_batch;
2060 * In usual, we do css_get() when we remember memcg pointer.
2061 * But in this case, we keep res->usage until end of a series of
2062 * uncharges. Then, it's ok to ignore memcg's refcnt.
2067 * In typical case, batch->memcg == mem. This means we can
2068 * merge a series of uncharges to an uncharge of res_counter.
2069 * If not, we uncharge res_counter ony by one.
2071 if (batch->memcg != mem)
2072 goto direct_uncharge;
2073 /* remember freed charge and uncharge it later */
2074 batch->bytes += PAGE_SIZE;
2076 batch->memsw_bytes += PAGE_SIZE;
2079 res_counter_uncharge(&mem->res, PAGE_SIZE);
2081 res_counter_uncharge(&mem->memsw, PAGE_SIZE);
2086 * uncharge if !page_mapped(page)
2088 static struct mem_cgroup *
2089 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
2091 struct page_cgroup *pc;
2092 struct mem_cgroup *mem = NULL;
2093 struct mem_cgroup_per_zone *mz;
2095 if (mem_cgroup_disabled())
2098 if (PageSwapCache(page))
2102 * Check if our page_cgroup is valid
2104 pc = lookup_page_cgroup(page);
2105 if (unlikely(!pc || !PageCgroupUsed(pc)))
2108 lock_page_cgroup(pc);
2110 mem = pc->mem_cgroup;
2112 if (!PageCgroupUsed(pc))
2116 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
2117 case MEM_CGROUP_CHARGE_TYPE_DROP:
2118 if (page_mapped(page))
2121 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
2122 if (!PageAnon(page)) { /* Shared memory */
2123 if (page->mapping && !page_is_file_cache(page))
2125 } else if (page_mapped(page)) /* Anon */
2132 if (!mem_cgroup_is_root(mem))
2133 __do_uncharge(mem, ctype);
2134 if (ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2135 mem_cgroup_swap_statistics(mem, true);
2136 mem_cgroup_charge_statistics(mem, pc, false);
2138 ClearPageCgroupUsed(pc);
2140 * pc->mem_cgroup is not cleared here. It will be accessed when it's
2141 * freed from LRU. This is safe because uncharged page is expected not
2142 * to be reused (freed soon). Exception is SwapCache, it's handled by
2143 * special functions.
2146 mz = page_cgroup_zoneinfo(pc);
2147 unlock_page_cgroup(pc);
2149 if (mem_cgroup_soft_limit_check(mem))
2150 mem_cgroup_update_tree(mem, page);
2151 /* at swapout, this memcg will be accessed to record to swap */
2152 if (ctype != MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2158 unlock_page_cgroup(pc);
2162 void mem_cgroup_uncharge_page(struct page *page)
2165 if (page_mapped(page))
2167 if (page->mapping && !PageAnon(page))
2169 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
2172 void mem_cgroup_uncharge_cache_page(struct page *page)
2174 VM_BUG_ON(page_mapped(page));
2175 VM_BUG_ON(page->mapping);
2176 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
2180 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
2181 * In that cases, pages are freed continuously and we can expect pages
2182 * are in the same memcg. All these calls itself limits the number of
2183 * pages freed at once, then uncharge_start/end() is called properly.
2184 * This may be called prural(2) times in a context,
2187 void mem_cgroup_uncharge_start(void)
2189 current->memcg_batch.do_batch++;
2190 /* We can do nest. */
2191 if (current->memcg_batch.do_batch == 1) {
2192 current->memcg_batch.memcg = NULL;
2193 current->memcg_batch.bytes = 0;
2194 current->memcg_batch.memsw_bytes = 0;
2198 void mem_cgroup_uncharge_end(void)
2200 struct memcg_batch_info *batch = ¤t->memcg_batch;
2202 if (!batch->do_batch)
2206 if (batch->do_batch) /* If stacked, do nothing. */
2212 * This "batch->memcg" is valid without any css_get/put etc...
2213 * bacause we hide charges behind us.
2216 res_counter_uncharge(&batch->memcg->res, batch->bytes);
2217 if (batch->memsw_bytes)
2218 res_counter_uncharge(&batch->memcg->memsw, batch->memsw_bytes);
2219 /* forget this pointer (for sanity check) */
2220 batch->memcg = NULL;
2225 * called after __delete_from_swap_cache() and drop "page" account.
2226 * memcg information is recorded to swap_cgroup of "ent"
2229 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
2231 struct mem_cgroup *memcg;
2232 int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
2234 if (!swapout) /* this was a swap cache but the swap is unused ! */
2235 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
2237 memcg = __mem_cgroup_uncharge_common(page, ctype);
2239 /* record memcg information */
2240 if (do_swap_account && swapout && memcg) {
2241 swap_cgroup_record(ent, css_id(&memcg->css));
2242 mem_cgroup_get(memcg);
2244 if (swapout && memcg)
2245 css_put(&memcg->css);
2249 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
2251 * called from swap_entry_free(). remove record in swap_cgroup and
2252 * uncharge "memsw" account.
2254 void mem_cgroup_uncharge_swap(swp_entry_t ent)
2256 struct mem_cgroup *memcg;
2259 if (!do_swap_account)
2262 id = swap_cgroup_record(ent, 0);
2264 memcg = mem_cgroup_lookup(id);
2267 * We uncharge this because swap is freed.
2268 * This memcg can be obsolete one. We avoid calling css_tryget
2270 if (!mem_cgroup_is_root(memcg))
2271 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
2272 mem_cgroup_swap_statistics(memcg, false);
2273 mem_cgroup_put(memcg);
2279 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
2280 * @entry: swap entry to be moved
2281 * @from: mem_cgroup which the entry is moved from
2282 * @to: mem_cgroup which the entry is moved to
2283 * @need_fixup: whether we should fixup res_counters and refcounts.
2285 * It succeeds only when the swap_cgroup's record for this entry is the same
2286 * as the mem_cgroup's id of @from.
2288 * Returns 0 on success, -EINVAL on failure.
2290 * The caller must have charged to @to, IOW, called res_counter_charge() about
2291 * both res and memsw, and called css_get().
2293 static int mem_cgroup_move_swap_account(swp_entry_t entry,
2294 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
2296 unsigned short old_id, new_id;
2298 old_id = css_id(&from->css);
2299 new_id = css_id(&to->css);
2301 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
2302 mem_cgroup_swap_statistics(from, false);
2303 mem_cgroup_swap_statistics(to, true);
2305 * This function is only called from task migration context now.
2306 * It postpones res_counter and refcount handling till the end
2307 * of task migration(mem_cgroup_clear_mc()) for performance
2308 * improvement. But we cannot postpone mem_cgroup_get(to)
2309 * because if the process that has been moved to @to does
2310 * swap-in, the refcount of @to might be decreased to 0.
2314 if (!mem_cgroup_is_root(from))
2315 res_counter_uncharge(&from->memsw, PAGE_SIZE);
2316 mem_cgroup_put(from);
2318 * we charged both to->res and to->memsw, so we should
2321 if (!mem_cgroup_is_root(to))
2322 res_counter_uncharge(&to->res, PAGE_SIZE);
2330 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
2331 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
2338 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
2341 int mem_cgroup_prepare_migration(struct page *page, struct mem_cgroup **ptr)
2343 struct page_cgroup *pc;
2344 struct mem_cgroup *mem = NULL;
2347 if (mem_cgroup_disabled())
2350 pc = lookup_page_cgroup(page);
2351 lock_page_cgroup(pc);
2352 if (PageCgroupUsed(pc)) {
2353 mem = pc->mem_cgroup;
2356 unlock_page_cgroup(pc);
2359 ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, &mem, false,
2367 /* remove redundant charge if migration failed*/
2368 void mem_cgroup_end_migration(struct mem_cgroup *mem,
2369 struct page *oldpage, struct page *newpage)
2371 struct page *target, *unused;
2372 struct page_cgroup *pc;
2373 enum charge_type ctype;
2377 cgroup_exclude_rmdir(&mem->css);
2378 /* at migration success, oldpage->mapping is NULL. */
2379 if (oldpage->mapping) {
2387 if (PageAnon(target))
2388 ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
2389 else if (page_is_file_cache(target))
2390 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
2392 ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
2394 /* unused page is not on radix-tree now. */
2396 __mem_cgroup_uncharge_common(unused, ctype);
2398 pc = lookup_page_cgroup(target);
2400 * __mem_cgroup_commit_charge() check PCG_USED bit of page_cgroup.
2401 * So, double-counting is effectively avoided.
2403 __mem_cgroup_commit_charge(mem, pc, ctype);
2406 * Both of oldpage and newpage are still under lock_page().
2407 * Then, we don't have to care about race in radix-tree.
2408 * But we have to be careful that this page is unmapped or not.
2410 * There is a case for !page_mapped(). At the start of
2411 * migration, oldpage was mapped. But now, it's zapped.
2412 * But we know *target* page is not freed/reused under us.
2413 * mem_cgroup_uncharge_page() does all necessary checks.
2415 if (ctype == MEM_CGROUP_CHARGE_TYPE_MAPPED)
2416 mem_cgroup_uncharge_page(target);
2418 * At migration, we may charge account against cgroup which has no tasks
2419 * So, rmdir()->pre_destroy() can be called while we do this charge.
2420 * In that case, we need to call pre_destroy() again. check it here.
2422 cgroup_release_and_wakeup_rmdir(&mem->css);
2426 * A call to try to shrink memory usage on charge failure at shmem's swapin.
2427 * Calling hierarchical_reclaim is not enough because we should update
2428 * last_oom_jiffies to prevent pagefault_out_of_memory from invoking global OOM.
2429 * Moreover considering hierarchy, we should reclaim from the mem_over_limit,
2430 * not from the memcg which this page would be charged to.
2431 * try_charge_swapin does all of these works properly.
2433 int mem_cgroup_shmem_charge_fallback(struct page *page,
2434 struct mm_struct *mm,
2437 struct mem_cgroup *mem = NULL;
2440 if (mem_cgroup_disabled())
2443 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
2445 mem_cgroup_cancel_charge_swapin(mem); /* it does !mem check */
2450 static DEFINE_MUTEX(set_limit_mutex);
2452 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
2453 unsigned long long val)
2458 int children = mem_cgroup_count_children(memcg);
2459 u64 curusage, oldusage;
2462 * For keeping hierarchical_reclaim simple, how long we should retry
2463 * is depends on callers. We set our retry-count to be function
2464 * of # of children which we should visit in this loop.
2466 retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
2468 oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
2470 while (retry_count) {
2471 if (signal_pending(current)) {
2476 * Rather than hide all in some function, I do this in
2477 * open coded manner. You see what this really does.
2478 * We have to guarantee mem->res.limit < mem->memsw.limit.
2480 mutex_lock(&set_limit_mutex);
2481 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
2482 if (memswlimit < val) {
2484 mutex_unlock(&set_limit_mutex);
2487 ret = res_counter_set_limit(&memcg->res, val);
2489 if (memswlimit == val)
2490 memcg->memsw_is_minimum = true;
2492 memcg->memsw_is_minimum = false;
2494 mutex_unlock(&set_limit_mutex);
2499 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
2500 MEM_CGROUP_RECLAIM_SHRINK);
2501 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
2502 /* Usage is reduced ? */
2503 if (curusage >= oldusage)
2506 oldusage = curusage;
2512 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
2513 unsigned long long val)
2516 u64 memlimit, oldusage, curusage;
2517 int children = mem_cgroup_count_children(memcg);
2520 /* see mem_cgroup_resize_res_limit */
2521 retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
2522 oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
2523 while (retry_count) {
2524 if (signal_pending(current)) {
2529 * Rather than hide all in some function, I do this in
2530 * open coded manner. You see what this really does.
2531 * We have to guarantee mem->res.limit < mem->memsw.limit.
2533 mutex_lock(&set_limit_mutex);
2534 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
2535 if (memlimit > val) {
2537 mutex_unlock(&set_limit_mutex);
2540 ret = res_counter_set_limit(&memcg->memsw, val);
2542 if (memlimit == val)
2543 memcg->memsw_is_minimum = true;
2545 memcg->memsw_is_minimum = false;
2547 mutex_unlock(&set_limit_mutex);
2552 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
2553 MEM_CGROUP_RECLAIM_NOSWAP |
2554 MEM_CGROUP_RECLAIM_SHRINK);
2555 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
2556 /* Usage is reduced ? */
2557 if (curusage >= oldusage)
2560 oldusage = curusage;
2565 unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
2566 gfp_t gfp_mask, int nid,
2569 unsigned long nr_reclaimed = 0;
2570 struct mem_cgroup_per_zone *mz, *next_mz = NULL;
2571 unsigned long reclaimed;
2573 struct mem_cgroup_tree_per_zone *mctz;
2574 unsigned long long excess;
2579 mctz = soft_limit_tree_node_zone(nid, zid);
2581 * This loop can run a while, specially if mem_cgroup's continuously
2582 * keep exceeding their soft limit and putting the system under
2589 mz = mem_cgroup_largest_soft_limit_node(mctz);
2593 reclaimed = mem_cgroup_hierarchical_reclaim(mz->mem, zone,
2595 MEM_CGROUP_RECLAIM_SOFT);
2596 nr_reclaimed += reclaimed;
2597 spin_lock(&mctz->lock);
2600 * If we failed to reclaim anything from this memory cgroup
2601 * it is time to move on to the next cgroup
2607 * Loop until we find yet another one.
2609 * By the time we get the soft_limit lock
2610 * again, someone might have aded the
2611 * group back on the RB tree. Iterate to
2612 * make sure we get a different mem.
2613 * mem_cgroup_largest_soft_limit_node returns
2614 * NULL if no other cgroup is present on
2618 __mem_cgroup_largest_soft_limit_node(mctz);
2619 if (next_mz == mz) {
2620 css_put(&next_mz->mem->css);
2622 } else /* next_mz == NULL or other memcg */
2626 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
2627 excess = res_counter_soft_limit_excess(&mz->mem->res);
2629 * One school of thought says that we should not add
2630 * back the node to the tree if reclaim returns 0.
2631 * But our reclaim could return 0, simply because due
2632 * to priority we are exposing a smaller subset of
2633 * memory to reclaim from. Consider this as a longer
2636 /* If excess == 0, no tree ops */
2637 __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
2638 spin_unlock(&mctz->lock);
2639 css_put(&mz->mem->css);
2642 * Could not reclaim anything and there are no more
2643 * mem cgroups to try or we seem to be looping without
2644 * reclaiming anything.
2646 if (!nr_reclaimed &&
2648 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
2650 } while (!nr_reclaimed);
2652 css_put(&next_mz->mem->css);
2653 return nr_reclaimed;
2657 * This routine traverse page_cgroup in given list and drop them all.
2658 * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
2660 static int mem_cgroup_force_empty_list(struct mem_cgroup *mem,
2661 int node, int zid, enum lru_list lru)
2664 struct mem_cgroup_per_zone *mz;
2665 struct page_cgroup *pc, *busy;
2666 unsigned long flags, loop;
2667 struct list_head *list;
2670 zone = &NODE_DATA(node)->node_zones[zid];
2671 mz = mem_cgroup_zoneinfo(mem, node, zid);
2672 list = &mz->lists[lru];
2674 loop = MEM_CGROUP_ZSTAT(mz, lru);
2675 /* give some margin against EBUSY etc...*/
2680 spin_lock_irqsave(&zone->lru_lock, flags);
2681 if (list_empty(list)) {
2682 spin_unlock_irqrestore(&zone->lru_lock, flags);
2685 pc = list_entry(list->prev, struct page_cgroup, lru);
2687 list_move(&pc->lru, list);
2689 spin_unlock_irqrestore(&zone->lru_lock, flags);
2692 spin_unlock_irqrestore(&zone->lru_lock, flags);
2694 ret = mem_cgroup_move_parent(pc, mem, GFP_KERNEL);
2698 if (ret == -EBUSY || ret == -EINVAL) {
2699 /* found lock contention or "pc" is obsolete. */
2706 if (!ret && !list_empty(list))
2712 * make mem_cgroup's charge to be 0 if there is no task.
2713 * This enables deleting this mem_cgroup.
2715 static int mem_cgroup_force_empty(struct mem_cgroup *mem, bool free_all)
2718 int node, zid, shrink;
2719 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
2720 struct cgroup *cgrp = mem->css.cgroup;
2725 /* should free all ? */
2731 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
2734 if (signal_pending(current))
2736 /* This is for making all *used* pages to be on LRU. */
2737 lru_add_drain_all();
2738 drain_all_stock_sync();
2740 for_each_node_state(node, N_HIGH_MEMORY) {
2741 for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
2744 ret = mem_cgroup_force_empty_list(mem,
2753 /* it seems parent cgroup doesn't have enough mem */
2757 /* "ret" should also be checked to ensure all lists are empty. */
2758 } while (mem->res.usage > 0 || ret);
2764 /* returns EBUSY if there is a task or if we come here twice. */
2765 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
2769 /* we call try-to-free pages for make this cgroup empty */
2770 lru_add_drain_all();
2771 /* try to free all pages in this cgroup */
2773 while (nr_retries && mem->res.usage > 0) {
2776 if (signal_pending(current)) {
2780 progress = try_to_free_mem_cgroup_pages(mem, GFP_KERNEL,
2781 false, get_swappiness(mem));
2784 /* maybe some writeback is necessary */
2785 congestion_wait(BLK_RW_ASYNC, HZ/10);
2790 /* try move_account...there may be some *locked* pages. */
2794 int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
2796 return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
2800 static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
2802 return mem_cgroup_from_cont(cont)->use_hierarchy;
2805 static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
2809 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
2810 struct cgroup *parent = cont->parent;
2811 struct mem_cgroup *parent_mem = NULL;
2814 parent_mem = mem_cgroup_from_cont(parent);
2818 * If parent's use_hierarchy is set, we can't make any modifications
2819 * in the child subtrees. If it is unset, then the change can
2820 * occur, provided the current cgroup has no children.
2822 * For the root cgroup, parent_mem is NULL, we allow value to be
2823 * set if there are no children.
2825 if ((!parent_mem || !parent_mem->use_hierarchy) &&
2826 (val == 1 || val == 0)) {
2827 if (list_empty(&cont->children))
2828 mem->use_hierarchy = val;
2838 struct mem_cgroup_idx_data {
2840 enum mem_cgroup_stat_index idx;
2844 mem_cgroup_get_idx_stat(struct mem_cgroup *mem, void *data)
2846 struct mem_cgroup_idx_data *d = data;
2847 d->val += mem_cgroup_read_stat(&mem->stat, d->idx);
2852 mem_cgroup_get_recursive_idx_stat(struct mem_cgroup *mem,
2853 enum mem_cgroup_stat_index idx, s64 *val)
2855 struct mem_cgroup_idx_data d;
2858 mem_cgroup_walk_tree(mem, &d, mem_cgroup_get_idx_stat);
2862 static inline u64 mem_cgroup_usage(struct mem_cgroup *mem, bool swap)
2866 if (!mem_cgroup_is_root(mem)) {
2868 return res_counter_read_u64(&mem->res, RES_USAGE);
2870 return res_counter_read_u64(&mem->memsw, RES_USAGE);
2873 mem_cgroup_get_recursive_idx_stat(mem, MEM_CGROUP_STAT_CACHE, &idx_val);
2875 mem_cgroup_get_recursive_idx_stat(mem, MEM_CGROUP_STAT_RSS, &idx_val);
2879 mem_cgroup_get_recursive_idx_stat(mem,
2880 MEM_CGROUP_STAT_SWAPOUT, &idx_val);
2884 return val << PAGE_SHIFT;
2887 static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
2889 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
2893 type = MEMFILE_TYPE(cft->private);
2894 name = MEMFILE_ATTR(cft->private);
2897 if (name == RES_USAGE)
2898 val = mem_cgroup_usage(mem, false);
2900 val = res_counter_read_u64(&mem->res, name);
2903 if (name == RES_USAGE)
2904 val = mem_cgroup_usage(mem, true);
2906 val = res_counter_read_u64(&mem->memsw, name);
2915 * The user of this function is...
2918 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
2921 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
2923 unsigned long long val;
2926 type = MEMFILE_TYPE(cft->private);
2927 name = MEMFILE_ATTR(cft->private);
2930 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
2934 /* This function does all necessary parse...reuse it */
2935 ret = res_counter_memparse_write_strategy(buffer, &val);
2939 ret = mem_cgroup_resize_limit(memcg, val);
2941 ret = mem_cgroup_resize_memsw_limit(memcg, val);
2943 case RES_SOFT_LIMIT:
2944 ret = res_counter_memparse_write_strategy(buffer, &val);
2948 * For memsw, soft limits are hard to implement in terms
2949 * of semantics, for now, we support soft limits for
2950 * control without swap
2953 ret = res_counter_set_soft_limit(&memcg->res, val);
2958 ret = -EINVAL; /* should be BUG() ? */
2964 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
2965 unsigned long long *mem_limit, unsigned long long *memsw_limit)
2967 struct cgroup *cgroup;
2968 unsigned long long min_limit, min_memsw_limit, tmp;
2970 min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
2971 min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
2972 cgroup = memcg->css.cgroup;
2973 if (!memcg->use_hierarchy)
2976 while (cgroup->parent) {
2977 cgroup = cgroup->parent;
2978 memcg = mem_cgroup_from_cont(cgroup);
2979 if (!memcg->use_hierarchy)
2981 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
2982 min_limit = min(min_limit, tmp);
2983 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
2984 min_memsw_limit = min(min_memsw_limit, tmp);
2987 *mem_limit = min_limit;
2988 *memsw_limit = min_memsw_limit;
2992 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
2994 struct mem_cgroup *mem;
2997 mem = mem_cgroup_from_cont(cont);
2998 type = MEMFILE_TYPE(event);
2999 name = MEMFILE_ATTR(event);
3003 res_counter_reset_max(&mem->res);
3005 res_counter_reset_max(&mem->memsw);
3009 res_counter_reset_failcnt(&mem->res);
3011 res_counter_reset_failcnt(&mem->memsw);
3018 static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
3021 return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
3025 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
3026 struct cftype *cft, u64 val)
3028 struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
3030 if (val >= (1 << NR_MOVE_TYPE))
3033 * We check this value several times in both in can_attach() and
3034 * attach(), so we need cgroup lock to prevent this value from being
3038 mem->move_charge_at_immigrate = val;
3044 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
3045 struct cftype *cft, u64 val)
3052 /* For read statistics */
3068 struct mcs_total_stat {
3069 s64 stat[NR_MCS_STAT];
3075 } memcg_stat_strings[NR_MCS_STAT] = {
3076 {"cache", "total_cache"},
3077 {"rss", "total_rss"},
3078 {"mapped_file", "total_mapped_file"},
3079 {"pgpgin", "total_pgpgin"},
3080 {"pgpgout", "total_pgpgout"},
3081 {"swap", "total_swap"},
3082 {"inactive_anon", "total_inactive_anon"},
3083 {"active_anon", "total_active_anon"},
3084 {"inactive_file", "total_inactive_file"},
3085 {"active_file", "total_active_file"},
3086 {"unevictable", "total_unevictable"}
3090 static int mem_cgroup_get_local_stat(struct mem_cgroup *mem, void *data)
3092 struct mcs_total_stat *s = data;
3096 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_CACHE);
3097 s->stat[MCS_CACHE] += val * PAGE_SIZE;
3098 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_RSS);
3099 s->stat[MCS_RSS] += val * PAGE_SIZE;
3100 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_FILE_MAPPED);
3101 s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE;
3102 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_PGPGIN_COUNT);
3103 s->stat[MCS_PGPGIN] += val;
3104 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_PGPGOUT_COUNT);
3105 s->stat[MCS_PGPGOUT] += val;
3106 if (do_swap_account) {
3107 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_SWAPOUT);
3108 s->stat[MCS_SWAP] += val * PAGE_SIZE;
3112 val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_ANON);
3113 s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
3114 val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_ANON);
3115 s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
3116 val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_FILE);
3117 s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
3118 val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_FILE);
3119 s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
3120 val = mem_cgroup_get_local_zonestat(mem, LRU_UNEVICTABLE);
3121 s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
3126 mem_cgroup_get_total_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
3128 mem_cgroup_walk_tree(mem, s, mem_cgroup_get_local_stat);
3131 static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
3132 struct cgroup_map_cb *cb)
3134 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
3135 struct mcs_total_stat mystat;
3138 memset(&mystat, 0, sizeof(mystat));
3139 mem_cgroup_get_local_stat(mem_cont, &mystat);
3141 for (i = 0; i < NR_MCS_STAT; i++) {
3142 if (i == MCS_SWAP && !do_swap_account)
3144 cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
3147 /* Hierarchical information */
3149 unsigned long long limit, memsw_limit;
3150 memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
3151 cb->fill(cb, "hierarchical_memory_limit", limit);
3152 if (do_swap_account)
3153 cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
3156 memset(&mystat, 0, sizeof(mystat));
3157 mem_cgroup_get_total_stat(mem_cont, &mystat);
3158 for (i = 0; i < NR_MCS_STAT; i++) {
3159 if (i == MCS_SWAP && !do_swap_account)
3161 cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
3164 #ifdef CONFIG_DEBUG_VM
3165 cb->fill(cb, "inactive_ratio", calc_inactive_ratio(mem_cont, NULL));
3169 struct mem_cgroup_per_zone *mz;
3170 unsigned long recent_rotated[2] = {0, 0};
3171 unsigned long recent_scanned[2] = {0, 0};
3173 for_each_online_node(nid)
3174 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
3175 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
3177 recent_rotated[0] +=
3178 mz->reclaim_stat.recent_rotated[0];
3179 recent_rotated[1] +=
3180 mz->reclaim_stat.recent_rotated[1];
3181 recent_scanned[0] +=
3182 mz->reclaim_stat.recent_scanned[0];
3183 recent_scanned[1] +=
3184 mz->reclaim_stat.recent_scanned[1];
3186 cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
3187 cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
3188 cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
3189 cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
3196 static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
3198 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3200 return get_swappiness(memcg);
3203 static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
3206 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3207 struct mem_cgroup *parent;
3212 if (cgrp->parent == NULL)
3215 parent = mem_cgroup_from_cont(cgrp->parent);
3219 /* If under hierarchy, only empty-root can set this value */
3220 if ((parent->use_hierarchy) ||
3221 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
3226 spin_lock(&memcg->reclaim_param_lock);
3227 memcg->swappiness = val;
3228 spin_unlock(&memcg->reclaim_param_lock);
3236 static struct cftype mem_cgroup_files[] = {
3238 .name = "usage_in_bytes",
3239 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
3240 .read_u64 = mem_cgroup_read,
3243 .name = "max_usage_in_bytes",
3244 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
3245 .trigger = mem_cgroup_reset,
3246 .read_u64 = mem_cgroup_read,
3249 .name = "limit_in_bytes",
3250 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
3251 .write_string = mem_cgroup_write,
3252 .read_u64 = mem_cgroup_read,
3255 .name = "soft_limit_in_bytes",
3256 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
3257 .write_string = mem_cgroup_write,
3258 .read_u64 = mem_cgroup_read,
3262 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
3263 .trigger = mem_cgroup_reset,
3264 .read_u64 = mem_cgroup_read,
3268 .read_map = mem_control_stat_show,
3271 .name = "force_empty",
3272 .trigger = mem_cgroup_force_empty_write,
3275 .name = "use_hierarchy",
3276 .write_u64 = mem_cgroup_hierarchy_write,
3277 .read_u64 = mem_cgroup_hierarchy_read,
3280 .name = "swappiness",
3281 .read_u64 = mem_cgroup_swappiness_read,
3282 .write_u64 = mem_cgroup_swappiness_write,
3285 .name = "move_charge_at_immigrate",
3286 .read_u64 = mem_cgroup_move_charge_read,
3287 .write_u64 = mem_cgroup_move_charge_write,
3291 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3292 static struct cftype memsw_cgroup_files[] = {
3294 .name = "memsw.usage_in_bytes",
3295 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
3296 .read_u64 = mem_cgroup_read,
3299 .name = "memsw.max_usage_in_bytes",
3300 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
3301 .trigger = mem_cgroup_reset,
3302 .read_u64 = mem_cgroup_read,
3305 .name = "memsw.limit_in_bytes",
3306 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
3307 .write_string = mem_cgroup_write,
3308 .read_u64 = mem_cgroup_read,
3311 .name = "memsw.failcnt",
3312 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
3313 .trigger = mem_cgroup_reset,
3314 .read_u64 = mem_cgroup_read,
3318 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
3320 if (!do_swap_account)
3322 return cgroup_add_files(cont, ss, memsw_cgroup_files,
3323 ARRAY_SIZE(memsw_cgroup_files));
3326 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
3332 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
3334 struct mem_cgroup_per_node *pn;
3335 struct mem_cgroup_per_zone *mz;
3337 int zone, tmp = node;
3339 * This routine is called against possible nodes.
3340 * But it's BUG to call kmalloc() against offline node.
3342 * TODO: this routine can waste much memory for nodes which will
3343 * never be onlined. It's better to use memory hotplug callback
3346 if (!node_state(node, N_NORMAL_MEMORY))
3348 pn = kmalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
3352 mem->info.nodeinfo[node] = pn;
3353 memset(pn, 0, sizeof(*pn));
3355 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3356 mz = &pn->zoneinfo[zone];
3358 INIT_LIST_HEAD(&mz->lists[l]);
3359 mz->usage_in_excess = 0;
3360 mz->on_tree = false;
3366 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
3368 kfree(mem->info.nodeinfo[node]);
3371 static int mem_cgroup_size(void)
3373 int cpustat_size = nr_cpu_ids * sizeof(struct mem_cgroup_stat_cpu);
3374 return sizeof(struct mem_cgroup) + cpustat_size;
3377 static struct mem_cgroup *mem_cgroup_alloc(void)
3379 struct mem_cgroup *mem;
3380 int size = mem_cgroup_size();
3382 if (size < PAGE_SIZE)
3383 mem = kmalloc(size, GFP_KERNEL);
3385 mem = vmalloc(size);
3388 memset(mem, 0, size);
3393 * At destroying mem_cgroup, references from swap_cgroup can remain.
3394 * (scanning all at force_empty is too costly...)
3396 * Instead of clearing all references at force_empty, we remember
3397 * the number of reference from swap_cgroup and free mem_cgroup when
3398 * it goes down to 0.
3400 * Removal of cgroup itself succeeds regardless of refs from swap.
3403 static void __mem_cgroup_free(struct mem_cgroup *mem)
3407 mem_cgroup_remove_from_trees(mem);
3408 free_css_id(&mem_cgroup_subsys, &mem->css);
3410 for_each_node_state(node, N_POSSIBLE)
3411 free_mem_cgroup_per_zone_info(mem, node);
3413 if (mem_cgroup_size() < PAGE_SIZE)
3419 static void mem_cgroup_get(struct mem_cgroup *mem)
3421 atomic_inc(&mem->refcnt);
3424 static void __mem_cgroup_put(struct mem_cgroup *mem, int count)
3426 if (atomic_sub_and_test(count, &mem->refcnt)) {
3427 struct mem_cgroup *parent = parent_mem_cgroup(mem);
3428 __mem_cgroup_free(mem);
3430 mem_cgroup_put(parent);
3434 static void mem_cgroup_put(struct mem_cgroup *mem)
3436 __mem_cgroup_put(mem, 1);
3440 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
3442 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem)
3444 if (!mem->res.parent)
3446 return mem_cgroup_from_res_counter(mem->res.parent, res);
3449 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3450 static void __init enable_swap_cgroup(void)
3452 if (!mem_cgroup_disabled() && really_do_swap_account)
3453 do_swap_account = 1;
3456 static void __init enable_swap_cgroup(void)
3461 static int mem_cgroup_soft_limit_tree_init(void)
3463 struct mem_cgroup_tree_per_node *rtpn;
3464 struct mem_cgroup_tree_per_zone *rtpz;
3465 int tmp, node, zone;
3467 for_each_node_state(node, N_POSSIBLE) {
3469 if (!node_state(node, N_NORMAL_MEMORY))
3471 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
3475 soft_limit_tree.rb_tree_per_node[node] = rtpn;
3477 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3478 rtpz = &rtpn->rb_tree_per_zone[zone];
3479 rtpz->rb_root = RB_ROOT;
3480 spin_lock_init(&rtpz->lock);
3486 static struct cgroup_subsys_state * __ref
3487 mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
3489 struct mem_cgroup *mem, *parent;
3490 long error = -ENOMEM;
3493 mem = mem_cgroup_alloc();
3495 return ERR_PTR(error);
3497 for_each_node_state(node, N_POSSIBLE)
3498 if (alloc_mem_cgroup_per_zone_info(mem, node))
3502 if (cont->parent == NULL) {
3504 enable_swap_cgroup();
3506 root_mem_cgroup = mem;
3507 if (mem_cgroup_soft_limit_tree_init())
3509 for_each_possible_cpu(cpu) {
3510 struct memcg_stock_pcp *stock =
3511 &per_cpu(memcg_stock, cpu);
3512 INIT_WORK(&stock->work, drain_local_stock);
3514 hotcpu_notifier(memcg_stock_cpu_callback, 0);
3516 parent = mem_cgroup_from_cont(cont->parent);
3517 mem->use_hierarchy = parent->use_hierarchy;
3520 if (parent && parent->use_hierarchy) {
3521 res_counter_init(&mem->res, &parent->res);
3522 res_counter_init(&mem->memsw, &parent->memsw);
3524 * We increment refcnt of the parent to ensure that we can
3525 * safely access it on res_counter_charge/uncharge.
3526 * This refcnt will be decremented when freeing this
3527 * mem_cgroup(see mem_cgroup_put).
3529 mem_cgroup_get(parent);
3531 res_counter_init(&mem->res, NULL);
3532 res_counter_init(&mem->memsw, NULL);
3534 mem->last_scanned_child = 0;
3535 spin_lock_init(&mem->reclaim_param_lock);
3538 mem->swappiness = get_swappiness(parent);
3539 atomic_set(&mem->refcnt, 1);
3540 mem->move_charge_at_immigrate = 0;
3543 __mem_cgroup_free(mem);
3544 root_mem_cgroup = NULL;
3545 return ERR_PTR(error);
3548 static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
3549 struct cgroup *cont)
3551 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
3553 return mem_cgroup_force_empty(mem, false);
3556 static void mem_cgroup_destroy(struct cgroup_subsys *ss,
3557 struct cgroup *cont)
3559 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
3561 mem_cgroup_put(mem);
3564 static int mem_cgroup_populate(struct cgroup_subsys *ss,
3565 struct cgroup *cont)
3569 ret = cgroup_add_files(cont, ss, mem_cgroup_files,
3570 ARRAY_SIZE(mem_cgroup_files));
3573 ret = register_memsw_files(cont, ss);
3578 /* Handlers for move charge at task migration. */
3579 #define PRECHARGE_COUNT_AT_ONCE 256
3580 static int mem_cgroup_do_precharge(unsigned long count)
3583 int batch_count = PRECHARGE_COUNT_AT_ONCE;
3584 struct mem_cgroup *mem = mc.to;
3586 if (mem_cgroup_is_root(mem)) {
3587 mc.precharge += count;
3588 /* we don't need css_get for root */
3591 /* try to charge at once */
3593 struct res_counter *dummy;
3595 * "mem" cannot be under rmdir() because we've already checked
3596 * by cgroup_lock_live_cgroup() that it is not removed and we
3597 * are still under the same cgroup_mutex. So we can postpone
3600 if (res_counter_charge(&mem->res, PAGE_SIZE * count, &dummy))
3602 if (do_swap_account && res_counter_charge(&mem->memsw,
3603 PAGE_SIZE * count, &dummy)) {
3604 res_counter_uncharge(&mem->res, PAGE_SIZE * count);
3607 mc.precharge += count;
3608 VM_BUG_ON(test_bit(CSS_ROOT, &mem->css.flags));
3609 WARN_ON_ONCE(count > INT_MAX);
3610 __css_get(&mem->css, (int)count);
3614 /* fall back to one by one charge */
3616 if (signal_pending(current)) {
3620 if (!batch_count--) {
3621 batch_count = PRECHARGE_COUNT_AT_ONCE;
3624 ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, &mem,
3627 /* mem_cgroup_clear_mc() will do uncharge later */
3633 #else /* !CONFIG_MMU */
3634 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
3635 struct cgroup *cgroup,
3636 struct task_struct *p,
3641 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
3642 struct cgroup *cgroup,
3643 struct task_struct *p,
3647 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
3648 struct cgroup *cont,
3649 struct cgroup *old_cont,
3650 struct task_struct *p,
3657 * is_target_pte_for_mc - check a pte whether it is valid for move charge
3658 * @vma: the vma the pte to be checked belongs
3659 * @addr: the address corresponding to the pte to be checked
3660 * @ptent: the pte to be checked
3661 * @target: the pointer the target page or swap ent will be stored(can be NULL)
3664 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
3665 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
3666 * move charge. if @target is not NULL, the page is stored in target->page
3667 * with extra refcnt got(Callers should handle it).
3668 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
3669 * target for charge migration. if @target is not NULL, the entry is stored
3672 * Called with pte lock held.
3679 enum mc_target_type {
3680 MC_TARGET_NONE, /* not used */
3685 static int is_target_pte_for_mc(struct vm_area_struct *vma,
3686 unsigned long addr, pte_t ptent, union mc_target *target)
3688 struct page *page = NULL;
3689 struct page_cgroup *pc;
3691 swp_entry_t ent = { .val = 0 };
3692 int usage_count = 0;
3693 bool move_anon = test_bit(MOVE_CHARGE_TYPE_ANON,
3694 &mc.to->move_charge_at_immigrate);
3696 if (!pte_present(ptent)) {
3697 /* TODO: handle swap of shmes/tmpfs */
3698 if (pte_none(ptent) || pte_file(ptent))
3700 else if (is_swap_pte(ptent)) {
3701 ent = pte_to_swp_entry(ptent);
3702 if (!move_anon || non_swap_entry(ent))
3704 usage_count = mem_cgroup_count_swap_user(ent, &page);
3707 page = vm_normal_page(vma, addr, ptent);
3708 if (!page || !page_mapped(page))
3711 * TODO: We don't move charges of file(including shmem/tmpfs)
3714 if (!move_anon || !PageAnon(page))
3716 if (!get_page_unless_zero(page))
3718 usage_count = page_mapcount(page);
3720 if (usage_count > 1) {
3722 * TODO: We don't move charges of shared(used by multiple
3723 * processes) pages for now.
3730 pc = lookup_page_cgroup(page);
3732 * Do only loose check w/o page_cgroup lock.
3733 * mem_cgroup_move_account() checks the pc is valid or not under
3736 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
3737 ret = MC_TARGET_PAGE;
3739 target->page = page;
3741 if (!ret || !target)
3745 if (ent.val && do_swap_account && !ret &&
3746 css_id(&mc.from->css) == lookup_swap_cgroup(ent)) {
3747 ret = MC_TARGET_SWAP;
3754 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
3755 unsigned long addr, unsigned long end,
3756 struct mm_walk *walk)
3758 struct vm_area_struct *vma = walk->private;
3762 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
3763 for (; addr != end; pte++, addr += PAGE_SIZE)
3764 if (is_target_pte_for_mc(vma, addr, *pte, NULL))
3765 mc.precharge++; /* increment precharge temporarily */
3766 pte_unmap_unlock(pte - 1, ptl);
3772 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
3774 unsigned long precharge;
3775 struct vm_area_struct *vma;
3777 down_read(&mm->mmap_sem);
3778 for (vma = mm->mmap; vma; vma = vma->vm_next) {
3779 struct mm_walk mem_cgroup_count_precharge_walk = {
3780 .pmd_entry = mem_cgroup_count_precharge_pte_range,
3784 if (is_vm_hugetlb_page(vma))
3786 /* TODO: We don't move charges of shmem/tmpfs pages for now. */
3787 if (vma->vm_flags & VM_SHARED)
3789 walk_page_range(vma->vm_start, vma->vm_end,
3790 &mem_cgroup_count_precharge_walk);
3792 up_read(&mm->mmap_sem);
3794 precharge = mc.precharge;
3800 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
3802 return mem_cgroup_do_precharge(mem_cgroup_count_precharge(mm));
3805 static void mem_cgroup_clear_mc(void)
3807 /* we must uncharge all the leftover precharges from mc.to */
3809 __mem_cgroup_cancel_charge(mc.to, mc.precharge);
3813 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
3814 * we must uncharge here.
3816 if (mc.moved_charge) {
3817 __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
3818 mc.moved_charge = 0;
3820 /* we must fixup refcnts and charges */
3821 if (mc.moved_swap) {
3822 WARN_ON_ONCE(mc.moved_swap > INT_MAX);
3823 /* uncharge swap account from the old cgroup */
3824 if (!mem_cgroup_is_root(mc.from))
3825 res_counter_uncharge(&mc.from->memsw,
3826 PAGE_SIZE * mc.moved_swap);
3827 __mem_cgroup_put(mc.from, mc.moved_swap);
3829 if (!mem_cgroup_is_root(mc.to)) {
3831 * we charged both to->res and to->memsw, so we should
3834 res_counter_uncharge(&mc.to->res,
3835 PAGE_SIZE * mc.moved_swap);
3836 VM_BUG_ON(test_bit(CSS_ROOT, &mc.to->css.flags));
3837 __css_put(&mc.to->css, mc.moved_swap);
3839 /* we've already done mem_cgroup_get(mc.to) */
3845 mc.moving_task = NULL;
3846 wake_up_all(&mc.waitq);
3849 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
3850 struct cgroup *cgroup,
3851 struct task_struct *p,
3855 struct mem_cgroup *mem = mem_cgroup_from_cont(cgroup);
3857 if (mem->move_charge_at_immigrate) {
3858 struct mm_struct *mm;
3859 struct mem_cgroup *from = mem_cgroup_from_task(p);
3861 VM_BUG_ON(from == mem);
3863 mm = get_task_mm(p);
3866 /* We move charges only when we move a owner of the mm */
3867 if (mm->owner == p) {
3870 VM_BUG_ON(mc.precharge);
3871 VM_BUG_ON(mc.moved_charge);
3872 VM_BUG_ON(mc.moved_swap);
3873 VM_BUG_ON(mc.moving_task);
3877 mc.moved_charge = 0;
3879 mc.moving_task = current;
3881 ret = mem_cgroup_precharge_mc(mm);
3883 mem_cgroup_clear_mc();
3890 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
3891 struct cgroup *cgroup,
3892 struct task_struct *p,
3895 mem_cgroup_clear_mc();
3898 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
3899 unsigned long addr, unsigned long end,
3900 struct mm_walk *walk)
3903 struct vm_area_struct *vma = walk->private;
3908 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
3909 for (; addr != end; addr += PAGE_SIZE) {
3910 pte_t ptent = *(pte++);
3911 union mc_target target;
3914 struct page_cgroup *pc;
3920 type = is_target_pte_for_mc(vma, addr, ptent, &target);
3922 case MC_TARGET_PAGE:
3924 if (isolate_lru_page(page))
3926 pc = lookup_page_cgroup(page);
3927 if (!mem_cgroup_move_account(pc,
3928 mc.from, mc.to, false)) {
3930 /* we uncharge from mc.from later. */
3933 putback_lru_page(page);
3934 put: /* is_target_pte_for_mc() gets the page */
3937 case MC_TARGET_SWAP:
3939 if (!mem_cgroup_move_swap_account(ent,
3940 mc.from, mc.to, false)) {
3942 /* we fixup refcnts and charges later. */
3950 pte_unmap_unlock(pte - 1, ptl);
3955 * We have consumed all precharges we got in can_attach().
3956 * We try charge one by one, but don't do any additional
3957 * charges to mc.to if we have failed in charge once in attach()
3960 ret = mem_cgroup_do_precharge(1);
3968 static void mem_cgroup_move_charge(struct mm_struct *mm)
3970 struct vm_area_struct *vma;
3972 lru_add_drain_all();
3973 down_read(&mm->mmap_sem);
3974 for (vma = mm->mmap; vma; vma = vma->vm_next) {
3976 struct mm_walk mem_cgroup_move_charge_walk = {
3977 .pmd_entry = mem_cgroup_move_charge_pte_range,
3981 if (is_vm_hugetlb_page(vma))
3983 /* TODO: We don't move charges of shmem/tmpfs pages for now. */
3984 if (vma->vm_flags & VM_SHARED)
3986 ret = walk_page_range(vma->vm_start, vma->vm_end,
3987 &mem_cgroup_move_charge_walk);
3990 * means we have consumed all precharges and failed in
3991 * doing additional charge. Just abandon here.
3995 up_read(&mm->mmap_sem);
3998 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
3999 struct cgroup *cont,
4000 struct cgroup *old_cont,
4001 struct task_struct *p,
4004 struct mm_struct *mm;
4007 /* no need to move charge */
4010 mm = get_task_mm(p);
4012 mem_cgroup_move_charge(mm);
4015 mem_cgroup_clear_mc();
4018 struct cgroup_subsys mem_cgroup_subsys = {
4020 .subsys_id = mem_cgroup_subsys_id,
4021 .create = mem_cgroup_create,
4022 .pre_destroy = mem_cgroup_pre_destroy,
4023 .destroy = mem_cgroup_destroy,
4024 .populate = mem_cgroup_populate,
4025 .can_attach = mem_cgroup_can_attach,
4026 .cancel_attach = mem_cgroup_cancel_attach,
4027 .attach = mem_cgroup_move_task,
4032 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4034 static int __init disable_swap_account(char *s)
4036 really_do_swap_account = 0;
4039 __setup("noswapaccount", disable_swap_account);