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_EVENTS, /* sum of pagein + pageout for internal use */
75 MEM_CGROUP_STAT_SWAPOUT, /* # of pages, swapped out */
77 MEM_CGROUP_STAT_NSTATS,
80 struct mem_cgroup_stat_cpu {
81 s64 count[MEM_CGROUP_STAT_NSTATS];
82 } ____cacheline_aligned_in_smp;
84 struct mem_cgroup_stat {
85 struct mem_cgroup_stat_cpu cpustat[0];
89 __mem_cgroup_stat_reset_safe(struct mem_cgroup_stat_cpu *stat,
90 enum mem_cgroup_stat_index idx)
96 __mem_cgroup_stat_read_local(struct mem_cgroup_stat_cpu *stat,
97 enum mem_cgroup_stat_index idx)
99 return stat->count[idx];
103 * For accounting under irq disable, no need for increment preempt count.
105 static inline void __mem_cgroup_stat_add_safe(struct mem_cgroup_stat_cpu *stat,
106 enum mem_cgroup_stat_index idx, int val)
108 stat->count[idx] += val;
111 static s64 mem_cgroup_read_stat(struct mem_cgroup_stat *stat,
112 enum mem_cgroup_stat_index idx)
116 for_each_possible_cpu(cpu)
117 ret += stat->cpustat[cpu].count[idx];
121 static s64 mem_cgroup_local_usage(struct mem_cgroup_stat *stat)
125 ret = mem_cgroup_read_stat(stat, MEM_CGROUP_STAT_CACHE);
126 ret += mem_cgroup_read_stat(stat, MEM_CGROUP_STAT_RSS);
131 * per-zone information in memory controller.
133 struct mem_cgroup_per_zone {
135 * spin_lock to protect the per cgroup LRU
137 struct list_head lists[NR_LRU_LISTS];
138 unsigned long count[NR_LRU_LISTS];
140 struct zone_reclaim_stat reclaim_stat;
141 struct rb_node tree_node; /* RB tree node */
142 unsigned long long usage_in_excess;/* Set to the value by which */
143 /* the soft limit is exceeded*/
145 struct mem_cgroup *mem; /* Back pointer, we cannot */
146 /* use container_of */
148 /* Macro for accessing counter */
149 #define MEM_CGROUP_ZSTAT(mz, idx) ((mz)->count[(idx)])
151 struct mem_cgroup_per_node {
152 struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
155 struct mem_cgroup_lru_info {
156 struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
160 * Cgroups above their limits are maintained in a RB-Tree, independent of
161 * their hierarchy representation
164 struct mem_cgroup_tree_per_zone {
165 struct rb_root rb_root;
169 struct mem_cgroup_tree_per_node {
170 struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
173 struct mem_cgroup_tree {
174 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
177 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
180 * The memory controller data structure. The memory controller controls both
181 * page cache and RSS per cgroup. We would eventually like to provide
182 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
183 * to help the administrator determine what knobs to tune.
185 * TODO: Add a water mark for the memory controller. Reclaim will begin when
186 * we hit the water mark. May be even add a low water mark, such that
187 * no reclaim occurs from a cgroup at it's low water mark, this is
188 * a feature that will be implemented much later in the future.
191 struct cgroup_subsys_state css;
193 * the counter to account for memory usage
195 struct res_counter res;
197 * the counter to account for mem+swap usage.
199 struct res_counter memsw;
201 * Per cgroup active and inactive list, similar to the
202 * per zone LRU lists.
204 struct mem_cgroup_lru_info info;
207 protect against reclaim related member.
209 spinlock_t reclaim_param_lock;
211 int prev_priority; /* for recording reclaim priority */
214 * While reclaiming in a hierarchy, we cache the last child we
217 int last_scanned_child;
219 * Should the accounting and control be hierarchical, per subtree?
222 unsigned long last_oom_jiffies;
225 unsigned int swappiness;
227 /* set when res.limit == memsw.limit */
228 bool memsw_is_minimum;
231 * Should we move charges of a task when a task is moved into this
232 * mem_cgroup ? And what type of charges should we move ?
234 unsigned long move_charge_at_immigrate;
237 * statistics. This must be placed at the end of memcg.
239 struct mem_cgroup_stat stat;
242 /* Stuffs for move charges at task migration. */
244 * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a
245 * left-shifted bitmap of these types.
248 MOVE_CHARGE_TYPE_ANON, /* private anonymous page and swap of it */
252 /* "mc" and its members are protected by cgroup_mutex */
253 static struct move_charge_struct {
254 struct mem_cgroup *from;
255 struct mem_cgroup *to;
256 unsigned long precharge;
257 unsigned long moved_charge;
258 unsigned long moved_swap;
259 struct task_struct *moving_task; /* a task moving charges */
260 wait_queue_head_t waitq; /* a waitq for other context */
262 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
266 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
267 * limit reclaim to prevent infinite loops, if they ever occur.
269 #define MEM_CGROUP_MAX_RECLAIM_LOOPS (100)
270 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS (2)
273 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
274 MEM_CGROUP_CHARGE_TYPE_MAPPED,
275 MEM_CGROUP_CHARGE_TYPE_SHMEM, /* used by page migration of shmem */
276 MEM_CGROUP_CHARGE_TYPE_FORCE, /* used by force_empty */
277 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
278 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
282 /* only for here (for easy reading.) */
283 #define PCGF_CACHE (1UL << PCG_CACHE)
284 #define PCGF_USED (1UL << PCG_USED)
285 #define PCGF_LOCK (1UL << PCG_LOCK)
286 /* Not used, but added here for completeness */
287 #define PCGF_ACCT (1UL << PCG_ACCT)
289 /* for encoding cft->private value on file */
292 #define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val))
293 #define MEMFILE_TYPE(val) (((val) >> 16) & 0xffff)
294 #define MEMFILE_ATTR(val) ((val) & 0xffff)
297 * Reclaim flags for mem_cgroup_hierarchical_reclaim
299 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
300 #define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
301 #define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
302 #define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
303 #define MEM_CGROUP_RECLAIM_SOFT_BIT 0x2
304 #define MEM_CGROUP_RECLAIM_SOFT (1 << MEM_CGROUP_RECLAIM_SOFT_BIT)
306 static void mem_cgroup_get(struct mem_cgroup *mem);
307 static void mem_cgroup_put(struct mem_cgroup *mem);
308 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem);
309 static void drain_all_stock_async(void);
311 static struct mem_cgroup_per_zone *
312 mem_cgroup_zoneinfo(struct mem_cgroup *mem, int nid, int zid)
314 return &mem->info.nodeinfo[nid]->zoneinfo[zid];
317 struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *mem)
322 static struct mem_cgroup_per_zone *
323 page_cgroup_zoneinfo(struct page_cgroup *pc)
325 struct mem_cgroup *mem = pc->mem_cgroup;
326 int nid = page_cgroup_nid(pc);
327 int zid = page_cgroup_zid(pc);
332 return mem_cgroup_zoneinfo(mem, nid, zid);
335 static struct mem_cgroup_tree_per_zone *
336 soft_limit_tree_node_zone(int nid, int zid)
338 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
341 static struct mem_cgroup_tree_per_zone *
342 soft_limit_tree_from_page(struct page *page)
344 int nid = page_to_nid(page);
345 int zid = page_zonenum(page);
347 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
351 __mem_cgroup_insert_exceeded(struct mem_cgroup *mem,
352 struct mem_cgroup_per_zone *mz,
353 struct mem_cgroup_tree_per_zone *mctz,
354 unsigned long long new_usage_in_excess)
356 struct rb_node **p = &mctz->rb_root.rb_node;
357 struct rb_node *parent = NULL;
358 struct mem_cgroup_per_zone *mz_node;
363 mz->usage_in_excess = new_usage_in_excess;
364 if (!mz->usage_in_excess)
368 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
370 if (mz->usage_in_excess < mz_node->usage_in_excess)
373 * We can't avoid mem cgroups that are over their soft
374 * limit by the same amount
376 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
379 rb_link_node(&mz->tree_node, parent, p);
380 rb_insert_color(&mz->tree_node, &mctz->rb_root);
385 __mem_cgroup_remove_exceeded(struct mem_cgroup *mem,
386 struct mem_cgroup_per_zone *mz,
387 struct mem_cgroup_tree_per_zone *mctz)
391 rb_erase(&mz->tree_node, &mctz->rb_root);
396 mem_cgroup_remove_exceeded(struct mem_cgroup *mem,
397 struct mem_cgroup_per_zone *mz,
398 struct mem_cgroup_tree_per_zone *mctz)
400 spin_lock(&mctz->lock);
401 __mem_cgroup_remove_exceeded(mem, mz, mctz);
402 spin_unlock(&mctz->lock);
405 static bool mem_cgroup_soft_limit_check(struct mem_cgroup *mem)
410 struct mem_cgroup_stat_cpu *cpustat;
413 cpustat = &mem->stat.cpustat[cpu];
414 val = __mem_cgroup_stat_read_local(cpustat, MEM_CGROUP_STAT_EVENTS);
415 if (unlikely(val > SOFTLIMIT_EVENTS_THRESH)) {
416 __mem_cgroup_stat_reset_safe(cpustat, MEM_CGROUP_STAT_EVENTS);
423 static void mem_cgroup_update_tree(struct mem_cgroup *mem, struct page *page)
425 unsigned long long excess;
426 struct mem_cgroup_per_zone *mz;
427 struct mem_cgroup_tree_per_zone *mctz;
428 int nid = page_to_nid(page);
429 int zid = page_zonenum(page);
430 mctz = soft_limit_tree_from_page(page);
433 * Necessary to update all ancestors when hierarchy is used.
434 * because their event counter is not touched.
436 for (; mem; mem = parent_mem_cgroup(mem)) {
437 mz = mem_cgroup_zoneinfo(mem, nid, zid);
438 excess = res_counter_soft_limit_excess(&mem->res);
440 * We have to update the tree if mz is on RB-tree or
441 * mem is over its softlimit.
443 if (excess || mz->on_tree) {
444 spin_lock(&mctz->lock);
445 /* if on-tree, remove it */
447 __mem_cgroup_remove_exceeded(mem, mz, mctz);
449 * Insert again. mz->usage_in_excess will be updated.
450 * If excess is 0, no tree ops.
452 __mem_cgroup_insert_exceeded(mem, mz, mctz, excess);
453 spin_unlock(&mctz->lock);
458 static void mem_cgroup_remove_from_trees(struct mem_cgroup *mem)
461 struct mem_cgroup_per_zone *mz;
462 struct mem_cgroup_tree_per_zone *mctz;
464 for_each_node_state(node, N_POSSIBLE) {
465 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
466 mz = mem_cgroup_zoneinfo(mem, node, zone);
467 mctz = soft_limit_tree_node_zone(node, zone);
468 mem_cgroup_remove_exceeded(mem, mz, mctz);
473 static inline unsigned long mem_cgroup_get_excess(struct mem_cgroup *mem)
475 return res_counter_soft_limit_excess(&mem->res) >> PAGE_SHIFT;
478 static struct mem_cgroup_per_zone *
479 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
481 struct rb_node *rightmost = NULL;
482 struct mem_cgroup_per_zone *mz;
486 rightmost = rb_last(&mctz->rb_root);
488 goto done; /* Nothing to reclaim from */
490 mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
492 * Remove the node now but someone else can add it back,
493 * we will to add it back at the end of reclaim to its correct
494 * position in the tree.
496 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
497 if (!res_counter_soft_limit_excess(&mz->mem->res) ||
498 !css_tryget(&mz->mem->css))
504 static struct mem_cgroup_per_zone *
505 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
507 struct mem_cgroup_per_zone *mz;
509 spin_lock(&mctz->lock);
510 mz = __mem_cgroup_largest_soft_limit_node(mctz);
511 spin_unlock(&mctz->lock);
515 static void mem_cgroup_swap_statistics(struct mem_cgroup *mem,
518 int val = (charge) ? 1 : -1;
519 struct mem_cgroup_stat *stat = &mem->stat;
520 struct mem_cgroup_stat_cpu *cpustat;
523 cpustat = &stat->cpustat[cpu];
524 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_SWAPOUT, val);
528 static void mem_cgroup_charge_statistics(struct mem_cgroup *mem,
529 struct page_cgroup *pc,
532 int val = (charge) ? 1 : -1;
533 struct mem_cgroup_stat *stat = &mem->stat;
534 struct mem_cgroup_stat_cpu *cpustat;
537 cpustat = &stat->cpustat[cpu];
538 if (PageCgroupCache(pc))
539 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_CACHE, val);
541 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_RSS, val);
544 __mem_cgroup_stat_add_safe(cpustat,
545 MEM_CGROUP_STAT_PGPGIN_COUNT, 1);
547 __mem_cgroup_stat_add_safe(cpustat,
548 MEM_CGROUP_STAT_PGPGOUT_COUNT, 1);
549 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_EVENTS, 1);
553 static unsigned long mem_cgroup_get_local_zonestat(struct mem_cgroup *mem,
557 struct mem_cgroup_per_zone *mz;
560 for_each_online_node(nid)
561 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
562 mz = mem_cgroup_zoneinfo(mem, nid, zid);
563 total += MEM_CGROUP_ZSTAT(mz, idx);
568 static struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
570 return container_of(cgroup_subsys_state(cont,
571 mem_cgroup_subsys_id), struct mem_cgroup,
575 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
578 * mm_update_next_owner() may clear mm->owner to NULL
579 * if it races with swapoff, page migration, etc.
580 * So this can be called with p == NULL.
585 return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
586 struct mem_cgroup, css);
589 static struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
591 struct mem_cgroup *mem = NULL;
596 * Because we have no locks, mm->owner's may be being moved to other
597 * cgroup. We use css_tryget() here even if this looks
598 * pessimistic (rather than adding locks here).
602 mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
605 } while (!css_tryget(&mem->css));
611 * Call callback function against all cgroup under hierarchy tree.
613 static int mem_cgroup_walk_tree(struct mem_cgroup *root, void *data,
614 int (*func)(struct mem_cgroup *, void *))
616 int found, ret, nextid;
617 struct cgroup_subsys_state *css;
618 struct mem_cgroup *mem;
620 if (!root->use_hierarchy)
621 return (*func)(root, data);
629 css = css_get_next(&mem_cgroup_subsys, nextid, &root->css,
631 if (css && css_tryget(css))
632 mem = container_of(css, struct mem_cgroup, css);
636 ret = (*func)(mem, data);
640 } while (!ret && css);
645 static inline bool mem_cgroup_is_root(struct mem_cgroup *mem)
647 return (mem == root_mem_cgroup);
651 * Following LRU functions are allowed to be used without PCG_LOCK.
652 * Operations are called by routine of global LRU independently from memcg.
653 * What we have to take care of here is validness of pc->mem_cgroup.
655 * Changes to pc->mem_cgroup happens when
658 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
659 * It is added to LRU before charge.
660 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
661 * When moving account, the page is not on LRU. It's isolated.
664 void mem_cgroup_del_lru_list(struct page *page, enum lru_list lru)
666 struct page_cgroup *pc;
667 struct mem_cgroup_per_zone *mz;
669 if (mem_cgroup_disabled())
671 pc = lookup_page_cgroup(page);
672 /* can happen while we handle swapcache. */
673 if (!TestClearPageCgroupAcctLRU(pc))
675 VM_BUG_ON(!pc->mem_cgroup);
677 * We don't check PCG_USED bit. It's cleared when the "page" is finally
678 * removed from global LRU.
680 mz = page_cgroup_zoneinfo(pc);
681 MEM_CGROUP_ZSTAT(mz, lru) -= 1;
682 if (mem_cgroup_is_root(pc->mem_cgroup))
684 VM_BUG_ON(list_empty(&pc->lru));
685 list_del_init(&pc->lru);
689 void mem_cgroup_del_lru(struct page *page)
691 mem_cgroup_del_lru_list(page, page_lru(page));
694 void mem_cgroup_rotate_lru_list(struct page *page, enum lru_list lru)
696 struct mem_cgroup_per_zone *mz;
697 struct page_cgroup *pc;
699 if (mem_cgroup_disabled())
702 pc = lookup_page_cgroup(page);
704 * Used bit is set without atomic ops but after smp_wmb().
705 * For making pc->mem_cgroup visible, insert smp_rmb() here.
708 /* unused or root page is not rotated. */
709 if (!PageCgroupUsed(pc) || mem_cgroup_is_root(pc->mem_cgroup))
711 mz = page_cgroup_zoneinfo(pc);
712 list_move(&pc->lru, &mz->lists[lru]);
715 void mem_cgroup_add_lru_list(struct page *page, enum lru_list lru)
717 struct page_cgroup *pc;
718 struct mem_cgroup_per_zone *mz;
720 if (mem_cgroup_disabled())
722 pc = lookup_page_cgroup(page);
723 VM_BUG_ON(PageCgroupAcctLRU(pc));
725 * Used bit is set without atomic ops but after smp_wmb().
726 * For making pc->mem_cgroup visible, insert smp_rmb() here.
729 if (!PageCgroupUsed(pc))
732 mz = page_cgroup_zoneinfo(pc);
733 MEM_CGROUP_ZSTAT(mz, lru) += 1;
734 SetPageCgroupAcctLRU(pc);
735 if (mem_cgroup_is_root(pc->mem_cgroup))
737 list_add(&pc->lru, &mz->lists[lru]);
741 * At handling SwapCache, pc->mem_cgroup may be changed while it's linked to
742 * lru because the page may.be reused after it's fully uncharged (because of
743 * SwapCache behavior).To handle that, unlink page_cgroup from LRU when charge
744 * it again. This function is only used to charge SwapCache. It's done under
745 * lock_page and expected that zone->lru_lock is never held.
747 static void mem_cgroup_lru_del_before_commit_swapcache(struct page *page)
750 struct zone *zone = page_zone(page);
751 struct page_cgroup *pc = lookup_page_cgroup(page);
753 spin_lock_irqsave(&zone->lru_lock, flags);
755 * Forget old LRU when this page_cgroup is *not* used. This Used bit
756 * is guarded by lock_page() because the page is SwapCache.
758 if (!PageCgroupUsed(pc))
759 mem_cgroup_del_lru_list(page, page_lru(page));
760 spin_unlock_irqrestore(&zone->lru_lock, flags);
763 static void mem_cgroup_lru_add_after_commit_swapcache(struct page *page)
766 struct zone *zone = page_zone(page);
767 struct page_cgroup *pc = lookup_page_cgroup(page);
769 spin_lock_irqsave(&zone->lru_lock, flags);
770 /* link when the page is linked to LRU but page_cgroup isn't */
771 if (PageLRU(page) && !PageCgroupAcctLRU(pc))
772 mem_cgroup_add_lru_list(page, page_lru(page));
773 spin_unlock_irqrestore(&zone->lru_lock, flags);
777 void mem_cgroup_move_lists(struct page *page,
778 enum lru_list from, enum lru_list to)
780 if (mem_cgroup_disabled())
782 mem_cgroup_del_lru_list(page, from);
783 mem_cgroup_add_lru_list(page, to);
786 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *mem)
789 struct mem_cgroup *curr = NULL;
793 curr = try_get_mem_cgroup_from_mm(task->mm);
799 * We should check use_hierarchy of "mem" not "curr". Because checking
800 * use_hierarchy of "curr" here make this function true if hierarchy is
801 * enabled in "curr" and "curr" is a child of "mem" in *cgroup*
802 * hierarchy(even if use_hierarchy is disabled in "mem").
804 if (mem->use_hierarchy)
805 ret = css_is_ancestor(&curr->css, &mem->css);
813 * prev_priority control...this will be used in memory reclaim path.
815 int mem_cgroup_get_reclaim_priority(struct mem_cgroup *mem)
819 spin_lock(&mem->reclaim_param_lock);
820 prev_priority = mem->prev_priority;
821 spin_unlock(&mem->reclaim_param_lock);
823 return prev_priority;
826 void mem_cgroup_note_reclaim_priority(struct mem_cgroup *mem, int priority)
828 spin_lock(&mem->reclaim_param_lock);
829 if (priority < mem->prev_priority)
830 mem->prev_priority = priority;
831 spin_unlock(&mem->reclaim_param_lock);
834 void mem_cgroup_record_reclaim_priority(struct mem_cgroup *mem, int priority)
836 spin_lock(&mem->reclaim_param_lock);
837 mem->prev_priority = priority;
838 spin_unlock(&mem->reclaim_param_lock);
841 static int calc_inactive_ratio(struct mem_cgroup *memcg, unsigned long *present_pages)
843 unsigned long active;
844 unsigned long inactive;
846 unsigned long inactive_ratio;
848 inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_ANON);
849 active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_ANON);
851 gb = (inactive + active) >> (30 - PAGE_SHIFT);
853 inactive_ratio = int_sqrt(10 * gb);
858 present_pages[0] = inactive;
859 present_pages[1] = active;
862 return inactive_ratio;
865 int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg)
867 unsigned long active;
868 unsigned long inactive;
869 unsigned long present_pages[2];
870 unsigned long inactive_ratio;
872 inactive_ratio = calc_inactive_ratio(memcg, present_pages);
874 inactive = present_pages[0];
875 active = present_pages[1];
877 if (inactive * inactive_ratio < active)
883 int mem_cgroup_inactive_file_is_low(struct mem_cgroup *memcg)
885 unsigned long active;
886 unsigned long inactive;
888 inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_FILE);
889 active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_FILE);
891 return (active > inactive);
894 unsigned long mem_cgroup_zone_nr_pages(struct mem_cgroup *memcg,
898 int nid = zone->zone_pgdat->node_id;
899 int zid = zone_idx(zone);
900 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
902 return MEM_CGROUP_ZSTAT(mz, lru);
905 struct zone_reclaim_stat *mem_cgroup_get_reclaim_stat(struct mem_cgroup *memcg,
908 int nid = zone->zone_pgdat->node_id;
909 int zid = zone_idx(zone);
910 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
912 return &mz->reclaim_stat;
915 struct zone_reclaim_stat *
916 mem_cgroup_get_reclaim_stat_from_page(struct page *page)
918 struct page_cgroup *pc;
919 struct mem_cgroup_per_zone *mz;
921 if (mem_cgroup_disabled())
924 pc = lookup_page_cgroup(page);
926 * Used bit is set without atomic ops but after smp_wmb().
927 * For making pc->mem_cgroup visible, insert smp_rmb() here.
930 if (!PageCgroupUsed(pc))
933 mz = page_cgroup_zoneinfo(pc);
937 return &mz->reclaim_stat;
940 unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan,
941 struct list_head *dst,
942 unsigned long *scanned, int order,
943 int mode, struct zone *z,
944 struct mem_cgroup *mem_cont,
945 int active, int file)
947 unsigned long nr_taken = 0;
951 struct list_head *src;
952 struct page_cgroup *pc, *tmp;
953 int nid = z->zone_pgdat->node_id;
954 int zid = zone_idx(z);
955 struct mem_cgroup_per_zone *mz;
956 int lru = LRU_FILE * file + active;
960 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
961 src = &mz->lists[lru];
964 list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
965 if (scan >= nr_to_scan)
969 if (unlikely(!PageCgroupUsed(pc)))
971 if (unlikely(!PageLRU(page)))
975 ret = __isolate_lru_page(page, mode, file);
978 list_move(&page->lru, dst);
979 mem_cgroup_del_lru(page);
983 /* we don't affect global LRU but rotate in our LRU */
984 mem_cgroup_rotate_lru_list(page, page_lru(page));
995 #define mem_cgroup_from_res_counter(counter, member) \
996 container_of(counter, struct mem_cgroup, member)
998 static bool mem_cgroup_check_under_limit(struct mem_cgroup *mem)
1000 if (do_swap_account) {
1001 if (res_counter_check_under_limit(&mem->res) &&
1002 res_counter_check_under_limit(&mem->memsw))
1005 if (res_counter_check_under_limit(&mem->res))
1010 static unsigned int get_swappiness(struct mem_cgroup *memcg)
1012 struct cgroup *cgrp = memcg->css.cgroup;
1013 unsigned int swappiness;
1016 if (cgrp->parent == NULL)
1017 return vm_swappiness;
1019 spin_lock(&memcg->reclaim_param_lock);
1020 swappiness = memcg->swappiness;
1021 spin_unlock(&memcg->reclaim_param_lock);
1026 static int mem_cgroup_count_children_cb(struct mem_cgroup *mem, void *data)
1034 * mem_cgroup_print_mem_info: Called from OOM with tasklist_lock held in read mode.
1035 * @memcg: The memory cgroup that went over limit
1036 * @p: Task that is going to be killed
1038 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1041 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1043 struct cgroup *task_cgrp;
1044 struct cgroup *mem_cgrp;
1046 * Need a buffer in BSS, can't rely on allocations. The code relies
1047 * on the assumption that OOM is serialized for memory controller.
1048 * If this assumption is broken, revisit this code.
1050 static char memcg_name[PATH_MAX];
1059 mem_cgrp = memcg->css.cgroup;
1060 task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1062 ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1065 * Unfortunately, we are unable to convert to a useful name
1066 * But we'll still print out the usage information
1073 printk(KERN_INFO "Task in %s killed", memcg_name);
1076 ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1084 * Continues from above, so we don't need an KERN_ level
1086 printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
1089 printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
1090 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1091 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1092 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1093 printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
1095 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1096 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1097 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1101 * This function returns the number of memcg under hierarchy tree. Returns
1102 * 1(self count) if no children.
1104 static int mem_cgroup_count_children(struct mem_cgroup *mem)
1107 mem_cgroup_walk_tree(mem, &num, mem_cgroup_count_children_cb);
1112 * Visit the first child (need not be the first child as per the ordering
1113 * of the cgroup list, since we track last_scanned_child) of @mem and use
1114 * that to reclaim free pages from.
1116 static struct mem_cgroup *
1117 mem_cgroup_select_victim(struct mem_cgroup *root_mem)
1119 struct mem_cgroup *ret = NULL;
1120 struct cgroup_subsys_state *css;
1123 if (!root_mem->use_hierarchy) {
1124 css_get(&root_mem->css);
1130 nextid = root_mem->last_scanned_child + 1;
1131 css = css_get_next(&mem_cgroup_subsys, nextid, &root_mem->css,
1133 if (css && css_tryget(css))
1134 ret = container_of(css, struct mem_cgroup, css);
1137 /* Updates scanning parameter */
1138 spin_lock(&root_mem->reclaim_param_lock);
1140 /* this means start scan from ID:1 */
1141 root_mem->last_scanned_child = 0;
1143 root_mem->last_scanned_child = found;
1144 spin_unlock(&root_mem->reclaim_param_lock);
1151 * Scan the hierarchy if needed to reclaim memory. We remember the last child
1152 * we reclaimed from, so that we don't end up penalizing one child extensively
1153 * based on its position in the children list.
1155 * root_mem is the original ancestor that we've been reclaim from.
1157 * We give up and return to the caller when we visit root_mem twice.
1158 * (other groups can be removed while we're walking....)
1160 * If shrink==true, for avoiding to free too much, this returns immedieately.
1162 static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup *root_mem,
1165 unsigned long reclaim_options)
1167 struct mem_cgroup *victim;
1170 bool noswap = reclaim_options & MEM_CGROUP_RECLAIM_NOSWAP;
1171 bool shrink = reclaim_options & MEM_CGROUP_RECLAIM_SHRINK;
1172 bool check_soft = reclaim_options & MEM_CGROUP_RECLAIM_SOFT;
1173 unsigned long excess = mem_cgroup_get_excess(root_mem);
1175 /* If memsw_is_minimum==1, swap-out is of-no-use. */
1176 if (root_mem->memsw_is_minimum)
1180 victim = mem_cgroup_select_victim(root_mem);
1181 if (victim == root_mem) {
1184 drain_all_stock_async();
1187 * If we have not been able to reclaim
1188 * anything, it might because there are
1189 * no reclaimable pages under this hierarchy
1191 if (!check_soft || !total) {
1192 css_put(&victim->css);
1196 * We want to do more targetted reclaim.
1197 * excess >> 2 is not to excessive so as to
1198 * reclaim too much, nor too less that we keep
1199 * coming back to reclaim from this cgroup
1201 if (total >= (excess >> 2) ||
1202 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS)) {
1203 css_put(&victim->css);
1208 if (!mem_cgroup_local_usage(&victim->stat)) {
1209 /* this cgroup's local usage == 0 */
1210 css_put(&victim->css);
1213 /* we use swappiness of local cgroup */
1215 ret = mem_cgroup_shrink_node_zone(victim, gfp_mask,
1216 noswap, get_swappiness(victim), zone,
1217 zone->zone_pgdat->node_id);
1219 ret = try_to_free_mem_cgroup_pages(victim, gfp_mask,
1220 noswap, get_swappiness(victim));
1221 css_put(&victim->css);
1223 * At shrinking usage, we can't check we should stop here or
1224 * reclaim more. It's depends on callers. last_scanned_child
1225 * will work enough for keeping fairness under tree.
1231 if (res_counter_check_under_soft_limit(&root_mem->res))
1233 } else if (mem_cgroup_check_under_limit(root_mem))
1239 bool mem_cgroup_oom_called(struct task_struct *task)
1242 struct mem_cgroup *mem;
1243 struct mm_struct *mm;
1249 mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
1250 if (mem && time_before(jiffies, mem->last_oom_jiffies + HZ/10))
1256 static int record_last_oom_cb(struct mem_cgroup *mem, void *data)
1258 mem->last_oom_jiffies = jiffies;
1262 static void record_last_oom(struct mem_cgroup *mem)
1264 mem_cgroup_walk_tree(mem, NULL, record_last_oom_cb);
1268 * Currently used to update mapped file statistics, but the routine can be
1269 * generalized to update other statistics as well.
1271 void mem_cgroup_update_file_mapped(struct page *page, int val)
1273 struct mem_cgroup *mem;
1274 struct mem_cgroup_stat *stat;
1275 struct mem_cgroup_stat_cpu *cpustat;
1277 struct page_cgroup *pc;
1279 pc = lookup_page_cgroup(page);
1283 lock_page_cgroup(pc);
1284 mem = pc->mem_cgroup;
1288 if (!PageCgroupUsed(pc))
1292 * Preemption is already disabled, we don't need get_cpu()
1294 cpu = smp_processor_id();
1296 cpustat = &stat->cpustat[cpu];
1298 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_FILE_MAPPED, val);
1300 unlock_page_cgroup(pc);
1304 * size of first charge trial. "32" comes from vmscan.c's magic value.
1305 * TODO: maybe necessary to use big numbers in big irons.
1307 #define CHARGE_SIZE (32 * PAGE_SIZE)
1308 struct memcg_stock_pcp {
1309 struct mem_cgroup *cached; /* this never be root cgroup */
1311 struct work_struct work;
1313 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
1314 static atomic_t memcg_drain_count;
1317 * Try to consume stocked charge on this cpu. If success, PAGE_SIZE is consumed
1318 * from local stock and true is returned. If the stock is 0 or charges from a
1319 * cgroup which is not current target, returns false. This stock will be
1322 static bool consume_stock(struct mem_cgroup *mem)
1324 struct memcg_stock_pcp *stock;
1327 stock = &get_cpu_var(memcg_stock);
1328 if (mem == stock->cached && stock->charge)
1329 stock->charge -= PAGE_SIZE;
1330 else /* need to call res_counter_charge */
1332 put_cpu_var(memcg_stock);
1337 * Returns stocks cached in percpu to res_counter and reset cached information.
1339 static void drain_stock(struct memcg_stock_pcp *stock)
1341 struct mem_cgroup *old = stock->cached;
1343 if (stock->charge) {
1344 res_counter_uncharge(&old->res, stock->charge);
1345 if (do_swap_account)
1346 res_counter_uncharge(&old->memsw, stock->charge);
1348 stock->cached = NULL;
1353 * This must be called under preempt disabled or must be called by
1354 * a thread which is pinned to local cpu.
1356 static void drain_local_stock(struct work_struct *dummy)
1358 struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
1363 * Cache charges(val) which is from res_counter, to local per_cpu area.
1364 * This will be consumed by consumt_stock() function, later.
1366 static void refill_stock(struct mem_cgroup *mem, int val)
1368 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
1370 if (stock->cached != mem) { /* reset if necessary */
1372 stock->cached = mem;
1374 stock->charge += val;
1375 put_cpu_var(memcg_stock);
1379 * Tries to drain stocked charges in other cpus. This function is asynchronous
1380 * and just put a work per cpu for draining localy on each cpu. Caller can
1381 * expects some charges will be back to res_counter later but cannot wait for
1384 static void drain_all_stock_async(void)
1387 /* This function is for scheduling "drain" in asynchronous way.
1388 * The result of "drain" is not directly handled by callers. Then,
1389 * if someone is calling drain, we don't have to call drain more.
1390 * Anyway, WORK_STRUCT_PENDING check in queue_work_on() will catch if
1391 * there is a race. We just do loose check here.
1393 if (atomic_read(&memcg_drain_count))
1395 /* Notify other cpus that system-wide "drain" is running */
1396 atomic_inc(&memcg_drain_count);
1398 for_each_online_cpu(cpu) {
1399 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
1400 schedule_work_on(cpu, &stock->work);
1403 atomic_dec(&memcg_drain_count);
1404 /* We don't wait for flush_work */
1407 /* This is a synchronous drain interface. */
1408 static void drain_all_stock_sync(void)
1410 /* called when force_empty is called */
1411 atomic_inc(&memcg_drain_count);
1412 schedule_on_each_cpu(drain_local_stock);
1413 atomic_dec(&memcg_drain_count);
1416 static int __cpuinit memcg_stock_cpu_callback(struct notifier_block *nb,
1417 unsigned long action,
1420 int cpu = (unsigned long)hcpu;
1421 struct memcg_stock_pcp *stock;
1423 if (action != CPU_DEAD)
1425 stock = &per_cpu(memcg_stock, cpu);
1431 * Unlike exported interface, "oom" parameter is added. if oom==true,
1432 * oom-killer can be invoked.
1434 static int __mem_cgroup_try_charge(struct mm_struct *mm,
1435 gfp_t gfp_mask, struct mem_cgroup **memcg,
1436 bool oom, struct page *page)
1438 struct mem_cgroup *mem, *mem_over_limit;
1439 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
1440 struct res_counter *fail_res;
1441 int csize = CHARGE_SIZE;
1443 if (unlikely(test_thread_flag(TIF_MEMDIE))) {
1444 /* Don't account this! */
1450 * We always charge the cgroup the mm_struct belongs to.
1451 * The mm_struct's mem_cgroup changes on task migration if the
1452 * thread group leader migrates. It's possible that mm is not
1453 * set, if so charge the init_mm (happens for pagecache usage).
1457 mem = try_get_mem_cgroup_from_mm(mm);
1465 VM_BUG_ON(css_is_removed(&mem->css));
1466 if (mem_cgroup_is_root(mem))
1471 unsigned long flags = 0;
1473 if (consume_stock(mem))
1476 ret = res_counter_charge(&mem->res, csize, &fail_res);
1478 if (!do_swap_account)
1480 ret = res_counter_charge(&mem->memsw, csize, &fail_res);
1483 /* mem+swap counter fails */
1484 res_counter_uncharge(&mem->res, csize);
1485 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
1486 mem_over_limit = mem_cgroup_from_res_counter(fail_res,
1489 /* mem counter fails */
1490 mem_over_limit = mem_cgroup_from_res_counter(fail_res,
1493 /* reduce request size and retry */
1494 if (csize > PAGE_SIZE) {
1498 if (!(gfp_mask & __GFP_WAIT))
1501 ret = mem_cgroup_hierarchical_reclaim(mem_over_limit, NULL,
1507 * try_to_free_mem_cgroup_pages() might not give us a full
1508 * picture of reclaim. Some pages are reclaimed and might be
1509 * moved to swap cache or just unmapped from the cgroup.
1510 * Check the limit again to see if the reclaim reduced the
1511 * current usage of the cgroup before giving up
1514 if (mem_cgroup_check_under_limit(mem_over_limit))
1517 /* try to avoid oom while someone is moving charge */
1518 if (mc.moving_task && current != mc.moving_task) {
1519 struct mem_cgroup *from, *to;
1520 bool do_continue = false;
1522 * There is a small race that "from" or "to" can be
1523 * freed by rmdir, so we use css_tryget().
1528 if (from && css_tryget(&from->css)) {
1529 if (mem_over_limit->use_hierarchy)
1530 do_continue = css_is_ancestor(
1532 &mem_over_limit->css);
1534 do_continue = (from == mem_over_limit);
1535 css_put(&from->css);
1537 if (!do_continue && to && css_tryget(&to->css)) {
1538 if (mem_over_limit->use_hierarchy)
1539 do_continue = css_is_ancestor(
1541 &mem_over_limit->css);
1543 do_continue = (to == mem_over_limit);
1549 prepare_to_wait(&mc.waitq, &wait,
1550 TASK_INTERRUPTIBLE);
1551 /* moving charge context might have finished. */
1554 finish_wait(&mc.waitq, &wait);
1559 if (!nr_retries--) {
1561 mem_cgroup_out_of_memory(mem_over_limit, gfp_mask);
1562 record_last_oom(mem_over_limit);
1567 if (csize > PAGE_SIZE)
1568 refill_stock(mem, csize - PAGE_SIZE);
1571 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
1572 * if they exceeds softlimit.
1574 if (page && mem_cgroup_soft_limit_check(mem))
1575 mem_cgroup_update_tree(mem, page);
1584 * Somemtimes we have to undo a charge we got by try_charge().
1585 * This function is for that and do uncharge, put css's refcnt.
1586 * gotten by try_charge().
1588 static void __mem_cgroup_cancel_charge(struct mem_cgroup *mem,
1589 unsigned long count)
1591 if (!mem_cgroup_is_root(mem)) {
1592 res_counter_uncharge(&mem->res, PAGE_SIZE * count);
1593 if (do_swap_account)
1594 res_counter_uncharge(&mem->memsw, PAGE_SIZE * count);
1595 VM_BUG_ON(test_bit(CSS_ROOT, &mem->css.flags));
1596 WARN_ON_ONCE(count > INT_MAX);
1597 __css_put(&mem->css, (int)count);
1599 /* we don't need css_put for root */
1602 static void mem_cgroup_cancel_charge(struct mem_cgroup *mem)
1604 __mem_cgroup_cancel_charge(mem, 1);
1608 * A helper function to get mem_cgroup from ID. must be called under
1609 * rcu_read_lock(). The caller must check css_is_removed() or some if
1610 * it's concern. (dropping refcnt from swap can be called against removed
1613 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
1615 struct cgroup_subsys_state *css;
1617 /* ID 0 is unused ID */
1620 css = css_lookup(&mem_cgroup_subsys, id);
1623 return container_of(css, struct mem_cgroup, css);
1626 struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
1628 struct mem_cgroup *mem = NULL;
1629 struct page_cgroup *pc;
1633 VM_BUG_ON(!PageLocked(page));
1635 pc = lookup_page_cgroup(page);
1636 lock_page_cgroup(pc);
1637 if (PageCgroupUsed(pc)) {
1638 mem = pc->mem_cgroup;
1639 if (mem && !css_tryget(&mem->css))
1641 } else if (PageSwapCache(page)) {
1642 ent.val = page_private(page);
1643 id = lookup_swap_cgroup(ent);
1645 mem = mem_cgroup_lookup(id);
1646 if (mem && !css_tryget(&mem->css))
1650 unlock_page_cgroup(pc);
1655 * commit a charge got by __mem_cgroup_try_charge() and makes page_cgroup to be
1656 * USED state. If already USED, uncharge and return.
1659 static void __mem_cgroup_commit_charge(struct mem_cgroup *mem,
1660 struct page_cgroup *pc,
1661 enum charge_type ctype)
1663 /* try_charge() can return NULL to *memcg, taking care of it. */
1667 lock_page_cgroup(pc);
1668 if (unlikely(PageCgroupUsed(pc))) {
1669 unlock_page_cgroup(pc);
1670 mem_cgroup_cancel_charge(mem);
1674 pc->mem_cgroup = mem;
1676 * We access a page_cgroup asynchronously without lock_page_cgroup().
1677 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
1678 * is accessed after testing USED bit. To make pc->mem_cgroup visible
1679 * before USED bit, we need memory barrier here.
1680 * See mem_cgroup_add_lru_list(), etc.
1684 case MEM_CGROUP_CHARGE_TYPE_CACHE:
1685 case MEM_CGROUP_CHARGE_TYPE_SHMEM:
1686 SetPageCgroupCache(pc);
1687 SetPageCgroupUsed(pc);
1689 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
1690 ClearPageCgroupCache(pc);
1691 SetPageCgroupUsed(pc);
1697 mem_cgroup_charge_statistics(mem, pc, true);
1699 unlock_page_cgroup(pc);
1703 * __mem_cgroup_move_account - move account of the page
1704 * @pc: page_cgroup of the page.
1705 * @from: mem_cgroup which the page is moved from.
1706 * @to: mem_cgroup which the page is moved to. @from != @to.
1707 * @uncharge: whether we should call uncharge and css_put against @from.
1709 * The caller must confirm following.
1710 * - page is not on LRU (isolate_page() is useful.)
1711 * - the pc is locked, used, and ->mem_cgroup points to @from.
1713 * This function doesn't do "charge" nor css_get to new cgroup. It should be
1714 * done by a caller(__mem_cgroup_try_charge would be usefull). If @uncharge is
1715 * true, this function does "uncharge" from old cgroup, but it doesn't if
1716 * @uncharge is false, so a caller should do "uncharge".
1719 static void __mem_cgroup_move_account(struct page_cgroup *pc,
1720 struct mem_cgroup *from, struct mem_cgroup *to, bool uncharge)
1724 struct mem_cgroup_stat *stat;
1725 struct mem_cgroup_stat_cpu *cpustat;
1727 VM_BUG_ON(from == to);
1728 VM_BUG_ON(PageLRU(pc->page));
1729 VM_BUG_ON(!PageCgroupLocked(pc));
1730 VM_BUG_ON(!PageCgroupUsed(pc));
1731 VM_BUG_ON(pc->mem_cgroup != from);
1734 if (page_mapped(page) && !PageAnon(page)) {
1735 cpu = smp_processor_id();
1736 /* Update mapped_file data for mem_cgroup "from" */
1738 cpustat = &stat->cpustat[cpu];
1739 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_FILE_MAPPED,
1742 /* Update mapped_file data for mem_cgroup "to" */
1744 cpustat = &stat->cpustat[cpu];
1745 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_FILE_MAPPED,
1748 mem_cgroup_charge_statistics(from, pc, false);
1750 /* This is not "cancel", but cancel_charge does all we need. */
1751 mem_cgroup_cancel_charge(from);
1753 /* caller should have done css_get */
1754 pc->mem_cgroup = to;
1755 mem_cgroup_charge_statistics(to, pc, true);
1757 * We charges against "to" which may not have any tasks. Then, "to"
1758 * can be under rmdir(). But in current implementation, caller of
1759 * this function is just force_empty() and move charge, so it's
1760 * garanteed that "to" is never removed. So, we don't check rmdir
1766 * check whether the @pc is valid for moving account and call
1767 * __mem_cgroup_move_account()
1769 static int mem_cgroup_move_account(struct page_cgroup *pc,
1770 struct mem_cgroup *from, struct mem_cgroup *to, bool uncharge)
1773 lock_page_cgroup(pc);
1774 if (PageCgroupUsed(pc) && pc->mem_cgroup == from) {
1775 __mem_cgroup_move_account(pc, from, to, uncharge);
1778 unlock_page_cgroup(pc);
1783 * move charges to its parent.
1786 static int mem_cgroup_move_parent(struct page_cgroup *pc,
1787 struct mem_cgroup *child,
1790 struct page *page = pc->page;
1791 struct cgroup *cg = child->css.cgroup;
1792 struct cgroup *pcg = cg->parent;
1793 struct mem_cgroup *parent;
1801 if (!get_page_unless_zero(page))
1803 if (isolate_lru_page(page))
1806 parent = mem_cgroup_from_cont(pcg);
1807 ret = __mem_cgroup_try_charge(NULL, gfp_mask, &parent, false, page);
1811 ret = mem_cgroup_move_account(pc, child, parent, true);
1813 mem_cgroup_cancel_charge(parent);
1815 putback_lru_page(page);
1823 * Charge the memory controller for page usage.
1825 * 0 if the charge was successful
1826 * < 0 if the cgroup is over its limit
1828 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
1829 gfp_t gfp_mask, enum charge_type ctype,
1830 struct mem_cgroup *memcg)
1832 struct mem_cgroup *mem;
1833 struct page_cgroup *pc;
1836 pc = lookup_page_cgroup(page);
1837 /* can happen at boot */
1843 ret = __mem_cgroup_try_charge(mm, gfp_mask, &mem, true, page);
1847 __mem_cgroup_commit_charge(mem, pc, ctype);
1851 int mem_cgroup_newpage_charge(struct page *page,
1852 struct mm_struct *mm, gfp_t gfp_mask)
1854 if (mem_cgroup_disabled())
1856 if (PageCompound(page))
1859 * If already mapped, we don't have to account.
1860 * If page cache, page->mapping has address_space.
1861 * But page->mapping may have out-of-use anon_vma pointer,
1862 * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
1865 if (page_mapped(page) || (page->mapping && !PageAnon(page)))
1869 return mem_cgroup_charge_common(page, mm, gfp_mask,
1870 MEM_CGROUP_CHARGE_TYPE_MAPPED, NULL);
1874 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
1875 enum charge_type ctype);
1877 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
1880 struct mem_cgroup *mem = NULL;
1883 if (mem_cgroup_disabled())
1885 if (PageCompound(page))
1888 * Corner case handling. This is called from add_to_page_cache()
1889 * in usual. But some FS (shmem) precharges this page before calling it
1890 * and call add_to_page_cache() with GFP_NOWAIT.
1892 * For GFP_NOWAIT case, the page may be pre-charged before calling
1893 * add_to_page_cache(). (See shmem.c) check it here and avoid to call
1894 * charge twice. (It works but has to pay a bit larger cost.)
1895 * And when the page is SwapCache, it should take swap information
1896 * into account. This is under lock_page() now.
1898 if (!(gfp_mask & __GFP_WAIT)) {
1899 struct page_cgroup *pc;
1902 pc = lookup_page_cgroup(page);
1905 lock_page_cgroup(pc);
1906 if (PageCgroupUsed(pc)) {
1907 unlock_page_cgroup(pc);
1910 unlock_page_cgroup(pc);
1913 if (unlikely(!mm && !mem))
1916 if (page_is_file_cache(page))
1917 return mem_cgroup_charge_common(page, mm, gfp_mask,
1918 MEM_CGROUP_CHARGE_TYPE_CACHE, NULL);
1921 if (PageSwapCache(page)) {
1922 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
1924 __mem_cgroup_commit_charge_swapin(page, mem,
1925 MEM_CGROUP_CHARGE_TYPE_SHMEM);
1927 ret = mem_cgroup_charge_common(page, mm, gfp_mask,
1928 MEM_CGROUP_CHARGE_TYPE_SHMEM, mem);
1934 * While swap-in, try_charge -> commit or cancel, the page is locked.
1935 * And when try_charge() successfully returns, one refcnt to memcg without
1936 * struct page_cgroup is acquired. This refcnt will be consumed by
1937 * "commit()" or removed by "cancel()"
1939 int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
1941 gfp_t mask, struct mem_cgroup **ptr)
1943 struct mem_cgroup *mem;
1946 if (mem_cgroup_disabled())
1949 if (!do_swap_account)
1952 * A racing thread's fault, or swapoff, may have already updated
1953 * the pte, and even removed page from swap cache: in those cases
1954 * do_swap_page()'s pte_same() test will fail; but there's also a
1955 * KSM case which does need to charge the page.
1957 if (!PageSwapCache(page))
1959 mem = try_get_mem_cgroup_from_page(page);
1963 ret = __mem_cgroup_try_charge(NULL, mask, ptr, true, page);
1964 /* drop extra refcnt from tryget */
1970 return __mem_cgroup_try_charge(mm, mask, ptr, true, page);
1974 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
1975 enum charge_type ctype)
1977 struct page_cgroup *pc;
1979 if (mem_cgroup_disabled())
1983 cgroup_exclude_rmdir(&ptr->css);
1984 pc = lookup_page_cgroup(page);
1985 mem_cgroup_lru_del_before_commit_swapcache(page);
1986 __mem_cgroup_commit_charge(ptr, pc, ctype);
1987 mem_cgroup_lru_add_after_commit_swapcache(page);
1989 * Now swap is on-memory. This means this page may be
1990 * counted both as mem and swap....double count.
1991 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
1992 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
1993 * may call delete_from_swap_cache() before reach here.
1995 if (do_swap_account && PageSwapCache(page)) {
1996 swp_entry_t ent = {.val = page_private(page)};
1998 struct mem_cgroup *memcg;
2000 id = swap_cgroup_record(ent, 0);
2002 memcg = mem_cgroup_lookup(id);
2005 * This recorded memcg can be obsolete one. So, avoid
2006 * calling css_tryget
2008 if (!mem_cgroup_is_root(memcg))
2009 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
2010 mem_cgroup_swap_statistics(memcg, false);
2011 mem_cgroup_put(memcg);
2016 * At swapin, we may charge account against cgroup which has no tasks.
2017 * So, rmdir()->pre_destroy() can be called while we do this charge.
2018 * In that case, we need to call pre_destroy() again. check it here.
2020 cgroup_release_and_wakeup_rmdir(&ptr->css);
2023 void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
2025 __mem_cgroup_commit_charge_swapin(page, ptr,
2026 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2029 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *mem)
2031 if (mem_cgroup_disabled())
2035 mem_cgroup_cancel_charge(mem);
2039 __do_uncharge(struct mem_cgroup *mem, const enum charge_type ctype)
2041 struct memcg_batch_info *batch = NULL;
2042 bool uncharge_memsw = true;
2043 /* If swapout, usage of swap doesn't decrease */
2044 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2045 uncharge_memsw = false;
2047 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
2048 * In those cases, all pages freed continously can be expected to be in
2049 * the same cgroup and we have chance to coalesce uncharges.
2050 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
2051 * because we want to do uncharge as soon as possible.
2053 if (!current->memcg_batch.do_batch || test_thread_flag(TIF_MEMDIE))
2054 goto direct_uncharge;
2056 batch = ¤t->memcg_batch;
2058 * In usual, we do css_get() when we remember memcg pointer.
2059 * But in this case, we keep res->usage until end of a series of
2060 * uncharges. Then, it's ok to ignore memcg's refcnt.
2065 * In typical case, batch->memcg == mem. This means we can
2066 * merge a series of uncharges to an uncharge of res_counter.
2067 * If not, we uncharge res_counter ony by one.
2069 if (batch->memcg != mem)
2070 goto direct_uncharge;
2071 /* remember freed charge and uncharge it later */
2072 batch->bytes += PAGE_SIZE;
2074 batch->memsw_bytes += PAGE_SIZE;
2077 res_counter_uncharge(&mem->res, PAGE_SIZE);
2079 res_counter_uncharge(&mem->memsw, PAGE_SIZE);
2084 * uncharge if !page_mapped(page)
2086 static struct mem_cgroup *
2087 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
2089 struct page_cgroup *pc;
2090 struct mem_cgroup *mem = NULL;
2091 struct mem_cgroup_per_zone *mz;
2093 if (mem_cgroup_disabled())
2096 if (PageSwapCache(page))
2100 * Check if our page_cgroup is valid
2102 pc = lookup_page_cgroup(page);
2103 if (unlikely(!pc || !PageCgroupUsed(pc)))
2106 lock_page_cgroup(pc);
2108 mem = pc->mem_cgroup;
2110 if (!PageCgroupUsed(pc))
2114 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
2115 case MEM_CGROUP_CHARGE_TYPE_DROP:
2116 if (page_mapped(page))
2119 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
2120 if (!PageAnon(page)) { /* Shared memory */
2121 if (page->mapping && !page_is_file_cache(page))
2123 } else if (page_mapped(page)) /* Anon */
2130 if (!mem_cgroup_is_root(mem))
2131 __do_uncharge(mem, ctype);
2132 if (ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2133 mem_cgroup_swap_statistics(mem, true);
2134 mem_cgroup_charge_statistics(mem, pc, false);
2136 ClearPageCgroupUsed(pc);
2138 * pc->mem_cgroup is not cleared here. It will be accessed when it's
2139 * freed from LRU. This is safe because uncharged page is expected not
2140 * to be reused (freed soon). Exception is SwapCache, it's handled by
2141 * special functions.
2144 mz = page_cgroup_zoneinfo(pc);
2145 unlock_page_cgroup(pc);
2147 if (mem_cgroup_soft_limit_check(mem))
2148 mem_cgroup_update_tree(mem, page);
2149 /* at swapout, this memcg will be accessed to record to swap */
2150 if (ctype != MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2156 unlock_page_cgroup(pc);
2160 void mem_cgroup_uncharge_page(struct page *page)
2163 if (page_mapped(page))
2165 if (page->mapping && !PageAnon(page))
2167 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
2170 void mem_cgroup_uncharge_cache_page(struct page *page)
2172 VM_BUG_ON(page_mapped(page));
2173 VM_BUG_ON(page->mapping);
2174 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
2178 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
2179 * In that cases, pages are freed continuously and we can expect pages
2180 * are in the same memcg. All these calls itself limits the number of
2181 * pages freed at once, then uncharge_start/end() is called properly.
2182 * This may be called prural(2) times in a context,
2185 void mem_cgroup_uncharge_start(void)
2187 current->memcg_batch.do_batch++;
2188 /* We can do nest. */
2189 if (current->memcg_batch.do_batch == 1) {
2190 current->memcg_batch.memcg = NULL;
2191 current->memcg_batch.bytes = 0;
2192 current->memcg_batch.memsw_bytes = 0;
2196 void mem_cgroup_uncharge_end(void)
2198 struct memcg_batch_info *batch = ¤t->memcg_batch;
2200 if (!batch->do_batch)
2204 if (batch->do_batch) /* If stacked, do nothing. */
2210 * This "batch->memcg" is valid without any css_get/put etc...
2211 * bacause we hide charges behind us.
2214 res_counter_uncharge(&batch->memcg->res, batch->bytes);
2215 if (batch->memsw_bytes)
2216 res_counter_uncharge(&batch->memcg->memsw, batch->memsw_bytes);
2217 /* forget this pointer (for sanity check) */
2218 batch->memcg = NULL;
2223 * called after __delete_from_swap_cache() and drop "page" account.
2224 * memcg information is recorded to swap_cgroup of "ent"
2227 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
2229 struct mem_cgroup *memcg;
2230 int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
2232 if (!swapout) /* this was a swap cache but the swap is unused ! */
2233 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
2235 memcg = __mem_cgroup_uncharge_common(page, ctype);
2237 /* record memcg information */
2238 if (do_swap_account && swapout && memcg) {
2239 swap_cgroup_record(ent, css_id(&memcg->css));
2240 mem_cgroup_get(memcg);
2242 if (swapout && memcg)
2243 css_put(&memcg->css);
2247 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
2249 * called from swap_entry_free(). remove record in swap_cgroup and
2250 * uncharge "memsw" account.
2252 void mem_cgroup_uncharge_swap(swp_entry_t ent)
2254 struct mem_cgroup *memcg;
2257 if (!do_swap_account)
2260 id = swap_cgroup_record(ent, 0);
2262 memcg = mem_cgroup_lookup(id);
2265 * We uncharge this because swap is freed.
2266 * This memcg can be obsolete one. We avoid calling css_tryget
2268 if (!mem_cgroup_is_root(memcg))
2269 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
2270 mem_cgroup_swap_statistics(memcg, false);
2271 mem_cgroup_put(memcg);
2277 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
2278 * @entry: swap entry to be moved
2279 * @from: mem_cgroup which the entry is moved from
2280 * @to: mem_cgroup which the entry is moved to
2281 * @need_fixup: whether we should fixup res_counters and refcounts.
2283 * It succeeds only when the swap_cgroup's record for this entry is the same
2284 * as the mem_cgroup's id of @from.
2286 * Returns 0 on success, -EINVAL on failure.
2288 * The caller must have charged to @to, IOW, called res_counter_charge() about
2289 * both res and memsw, and called css_get().
2291 static int mem_cgroup_move_swap_account(swp_entry_t entry,
2292 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
2294 unsigned short old_id, new_id;
2296 old_id = css_id(&from->css);
2297 new_id = css_id(&to->css);
2299 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
2300 mem_cgroup_swap_statistics(from, false);
2301 mem_cgroup_swap_statistics(to, true);
2303 * This function is only called from task migration context now.
2304 * It postpones res_counter and refcount handling till the end
2305 * of task migration(mem_cgroup_clear_mc()) for performance
2306 * improvement. But we cannot postpone mem_cgroup_get(to)
2307 * because if the process that has been moved to @to does
2308 * swap-in, the refcount of @to might be decreased to 0.
2312 if (!mem_cgroup_is_root(from))
2313 res_counter_uncharge(&from->memsw, PAGE_SIZE);
2314 mem_cgroup_put(from);
2316 * we charged both to->res and to->memsw, so we should
2319 if (!mem_cgroup_is_root(to))
2320 res_counter_uncharge(&to->res, PAGE_SIZE);
2328 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
2329 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
2336 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
2339 int mem_cgroup_prepare_migration(struct page *page, struct mem_cgroup **ptr)
2341 struct page_cgroup *pc;
2342 struct mem_cgroup *mem = NULL;
2345 if (mem_cgroup_disabled())
2348 pc = lookup_page_cgroup(page);
2349 lock_page_cgroup(pc);
2350 if (PageCgroupUsed(pc)) {
2351 mem = pc->mem_cgroup;
2354 unlock_page_cgroup(pc);
2357 ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, &mem, false,
2365 /* remove redundant charge if migration failed*/
2366 void mem_cgroup_end_migration(struct mem_cgroup *mem,
2367 struct page *oldpage, struct page *newpage)
2369 struct page *target, *unused;
2370 struct page_cgroup *pc;
2371 enum charge_type ctype;
2375 cgroup_exclude_rmdir(&mem->css);
2376 /* at migration success, oldpage->mapping is NULL. */
2377 if (oldpage->mapping) {
2385 if (PageAnon(target))
2386 ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
2387 else if (page_is_file_cache(target))
2388 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
2390 ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
2392 /* unused page is not on radix-tree now. */
2394 __mem_cgroup_uncharge_common(unused, ctype);
2396 pc = lookup_page_cgroup(target);
2398 * __mem_cgroup_commit_charge() check PCG_USED bit of page_cgroup.
2399 * So, double-counting is effectively avoided.
2401 __mem_cgroup_commit_charge(mem, pc, ctype);
2404 * Both of oldpage and newpage are still under lock_page().
2405 * Then, we don't have to care about race in radix-tree.
2406 * But we have to be careful that this page is unmapped or not.
2408 * There is a case for !page_mapped(). At the start of
2409 * migration, oldpage was mapped. But now, it's zapped.
2410 * But we know *target* page is not freed/reused under us.
2411 * mem_cgroup_uncharge_page() does all necessary checks.
2413 if (ctype == MEM_CGROUP_CHARGE_TYPE_MAPPED)
2414 mem_cgroup_uncharge_page(target);
2416 * At migration, we may charge account against cgroup which has no tasks
2417 * So, rmdir()->pre_destroy() can be called while we do this charge.
2418 * In that case, we need to call pre_destroy() again. check it here.
2420 cgroup_release_and_wakeup_rmdir(&mem->css);
2424 * A call to try to shrink memory usage on charge failure at shmem's swapin.
2425 * Calling hierarchical_reclaim is not enough because we should update
2426 * last_oom_jiffies to prevent pagefault_out_of_memory from invoking global OOM.
2427 * Moreover considering hierarchy, we should reclaim from the mem_over_limit,
2428 * not from the memcg which this page would be charged to.
2429 * try_charge_swapin does all of these works properly.
2431 int mem_cgroup_shmem_charge_fallback(struct page *page,
2432 struct mm_struct *mm,
2435 struct mem_cgroup *mem = NULL;
2438 if (mem_cgroup_disabled())
2441 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
2443 mem_cgroup_cancel_charge_swapin(mem); /* it does !mem check */
2448 static DEFINE_MUTEX(set_limit_mutex);
2450 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
2451 unsigned long long val)
2456 int children = mem_cgroup_count_children(memcg);
2457 u64 curusage, oldusage;
2460 * For keeping hierarchical_reclaim simple, how long we should retry
2461 * is depends on callers. We set our retry-count to be function
2462 * of # of children which we should visit in this loop.
2464 retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
2466 oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
2468 while (retry_count) {
2469 if (signal_pending(current)) {
2474 * Rather than hide all in some function, I do this in
2475 * open coded manner. You see what this really does.
2476 * We have to guarantee mem->res.limit < mem->memsw.limit.
2478 mutex_lock(&set_limit_mutex);
2479 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
2480 if (memswlimit < val) {
2482 mutex_unlock(&set_limit_mutex);
2485 ret = res_counter_set_limit(&memcg->res, val);
2487 if (memswlimit == val)
2488 memcg->memsw_is_minimum = true;
2490 memcg->memsw_is_minimum = false;
2492 mutex_unlock(&set_limit_mutex);
2497 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
2498 MEM_CGROUP_RECLAIM_SHRINK);
2499 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
2500 /* Usage is reduced ? */
2501 if (curusage >= oldusage)
2504 oldusage = curusage;
2510 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
2511 unsigned long long val)
2514 u64 memlimit, oldusage, curusage;
2515 int children = mem_cgroup_count_children(memcg);
2518 /* see mem_cgroup_resize_res_limit */
2519 retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
2520 oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
2521 while (retry_count) {
2522 if (signal_pending(current)) {
2527 * Rather than hide all in some function, I do this in
2528 * open coded manner. You see what this really does.
2529 * We have to guarantee mem->res.limit < mem->memsw.limit.
2531 mutex_lock(&set_limit_mutex);
2532 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
2533 if (memlimit > val) {
2535 mutex_unlock(&set_limit_mutex);
2538 ret = res_counter_set_limit(&memcg->memsw, val);
2540 if (memlimit == val)
2541 memcg->memsw_is_minimum = true;
2543 memcg->memsw_is_minimum = false;
2545 mutex_unlock(&set_limit_mutex);
2550 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
2551 MEM_CGROUP_RECLAIM_NOSWAP |
2552 MEM_CGROUP_RECLAIM_SHRINK);
2553 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
2554 /* Usage is reduced ? */
2555 if (curusage >= oldusage)
2558 oldusage = curusage;
2563 unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
2564 gfp_t gfp_mask, int nid,
2567 unsigned long nr_reclaimed = 0;
2568 struct mem_cgroup_per_zone *mz, *next_mz = NULL;
2569 unsigned long reclaimed;
2571 struct mem_cgroup_tree_per_zone *mctz;
2572 unsigned long long excess;
2577 mctz = soft_limit_tree_node_zone(nid, zid);
2579 * This loop can run a while, specially if mem_cgroup's continuously
2580 * keep exceeding their soft limit and putting the system under
2587 mz = mem_cgroup_largest_soft_limit_node(mctz);
2591 reclaimed = mem_cgroup_hierarchical_reclaim(mz->mem, zone,
2593 MEM_CGROUP_RECLAIM_SOFT);
2594 nr_reclaimed += reclaimed;
2595 spin_lock(&mctz->lock);
2598 * If we failed to reclaim anything from this memory cgroup
2599 * it is time to move on to the next cgroup
2605 * Loop until we find yet another one.
2607 * By the time we get the soft_limit lock
2608 * again, someone might have aded the
2609 * group back on the RB tree. Iterate to
2610 * make sure we get a different mem.
2611 * mem_cgroup_largest_soft_limit_node returns
2612 * NULL if no other cgroup is present on
2616 __mem_cgroup_largest_soft_limit_node(mctz);
2617 if (next_mz == mz) {
2618 css_put(&next_mz->mem->css);
2620 } else /* next_mz == NULL or other memcg */
2624 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
2625 excess = res_counter_soft_limit_excess(&mz->mem->res);
2627 * One school of thought says that we should not add
2628 * back the node to the tree if reclaim returns 0.
2629 * But our reclaim could return 0, simply because due
2630 * to priority we are exposing a smaller subset of
2631 * memory to reclaim from. Consider this as a longer
2634 /* If excess == 0, no tree ops */
2635 __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
2636 spin_unlock(&mctz->lock);
2637 css_put(&mz->mem->css);
2640 * Could not reclaim anything and there are no more
2641 * mem cgroups to try or we seem to be looping without
2642 * reclaiming anything.
2644 if (!nr_reclaimed &&
2646 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
2648 } while (!nr_reclaimed);
2650 css_put(&next_mz->mem->css);
2651 return nr_reclaimed;
2655 * This routine traverse page_cgroup in given list and drop them all.
2656 * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
2658 static int mem_cgroup_force_empty_list(struct mem_cgroup *mem,
2659 int node, int zid, enum lru_list lru)
2662 struct mem_cgroup_per_zone *mz;
2663 struct page_cgroup *pc, *busy;
2664 unsigned long flags, loop;
2665 struct list_head *list;
2668 zone = &NODE_DATA(node)->node_zones[zid];
2669 mz = mem_cgroup_zoneinfo(mem, node, zid);
2670 list = &mz->lists[lru];
2672 loop = MEM_CGROUP_ZSTAT(mz, lru);
2673 /* give some margin against EBUSY etc...*/
2678 spin_lock_irqsave(&zone->lru_lock, flags);
2679 if (list_empty(list)) {
2680 spin_unlock_irqrestore(&zone->lru_lock, flags);
2683 pc = list_entry(list->prev, struct page_cgroup, lru);
2685 list_move(&pc->lru, list);
2687 spin_unlock_irqrestore(&zone->lru_lock, flags);
2690 spin_unlock_irqrestore(&zone->lru_lock, flags);
2692 ret = mem_cgroup_move_parent(pc, mem, GFP_KERNEL);
2696 if (ret == -EBUSY || ret == -EINVAL) {
2697 /* found lock contention or "pc" is obsolete. */
2704 if (!ret && !list_empty(list))
2710 * make mem_cgroup's charge to be 0 if there is no task.
2711 * This enables deleting this mem_cgroup.
2713 static int mem_cgroup_force_empty(struct mem_cgroup *mem, bool free_all)
2716 int node, zid, shrink;
2717 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
2718 struct cgroup *cgrp = mem->css.cgroup;
2723 /* should free all ? */
2729 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
2732 if (signal_pending(current))
2734 /* This is for making all *used* pages to be on LRU. */
2735 lru_add_drain_all();
2736 drain_all_stock_sync();
2738 for_each_node_state(node, N_HIGH_MEMORY) {
2739 for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
2742 ret = mem_cgroup_force_empty_list(mem,
2751 /* it seems parent cgroup doesn't have enough mem */
2755 /* "ret" should also be checked to ensure all lists are empty. */
2756 } while (mem->res.usage > 0 || ret);
2762 /* returns EBUSY if there is a task or if we come here twice. */
2763 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
2767 /* we call try-to-free pages for make this cgroup empty */
2768 lru_add_drain_all();
2769 /* try to free all pages in this cgroup */
2771 while (nr_retries && mem->res.usage > 0) {
2774 if (signal_pending(current)) {
2778 progress = try_to_free_mem_cgroup_pages(mem, GFP_KERNEL,
2779 false, get_swappiness(mem));
2782 /* maybe some writeback is necessary */
2783 congestion_wait(BLK_RW_ASYNC, HZ/10);
2788 /* try move_account...there may be some *locked* pages. */
2792 int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
2794 return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
2798 static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
2800 return mem_cgroup_from_cont(cont)->use_hierarchy;
2803 static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
2807 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
2808 struct cgroup *parent = cont->parent;
2809 struct mem_cgroup *parent_mem = NULL;
2812 parent_mem = mem_cgroup_from_cont(parent);
2816 * If parent's use_hierarchy is set, we can't make any modifications
2817 * in the child subtrees. If it is unset, then the change can
2818 * occur, provided the current cgroup has no children.
2820 * For the root cgroup, parent_mem is NULL, we allow value to be
2821 * set if there are no children.
2823 if ((!parent_mem || !parent_mem->use_hierarchy) &&
2824 (val == 1 || val == 0)) {
2825 if (list_empty(&cont->children))
2826 mem->use_hierarchy = val;
2836 struct mem_cgroup_idx_data {
2838 enum mem_cgroup_stat_index idx;
2842 mem_cgroup_get_idx_stat(struct mem_cgroup *mem, void *data)
2844 struct mem_cgroup_idx_data *d = data;
2845 d->val += mem_cgroup_read_stat(&mem->stat, d->idx);
2850 mem_cgroup_get_recursive_idx_stat(struct mem_cgroup *mem,
2851 enum mem_cgroup_stat_index idx, s64 *val)
2853 struct mem_cgroup_idx_data d;
2856 mem_cgroup_walk_tree(mem, &d, mem_cgroup_get_idx_stat);
2860 static inline u64 mem_cgroup_usage(struct mem_cgroup *mem, bool swap)
2864 if (!mem_cgroup_is_root(mem)) {
2866 return res_counter_read_u64(&mem->res, RES_USAGE);
2868 return res_counter_read_u64(&mem->memsw, RES_USAGE);
2871 mem_cgroup_get_recursive_idx_stat(mem, MEM_CGROUP_STAT_CACHE, &idx_val);
2873 mem_cgroup_get_recursive_idx_stat(mem, MEM_CGROUP_STAT_RSS, &idx_val);
2877 mem_cgroup_get_recursive_idx_stat(mem,
2878 MEM_CGROUP_STAT_SWAPOUT, &idx_val);
2882 return val << PAGE_SHIFT;
2885 static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
2887 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
2891 type = MEMFILE_TYPE(cft->private);
2892 name = MEMFILE_ATTR(cft->private);
2895 if (name == RES_USAGE)
2896 val = mem_cgroup_usage(mem, false);
2898 val = res_counter_read_u64(&mem->res, name);
2901 if (name == RES_USAGE)
2902 val = mem_cgroup_usage(mem, true);
2904 val = res_counter_read_u64(&mem->memsw, name);
2913 * The user of this function is...
2916 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
2919 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
2921 unsigned long long val;
2924 type = MEMFILE_TYPE(cft->private);
2925 name = MEMFILE_ATTR(cft->private);
2928 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
2932 /* This function does all necessary parse...reuse it */
2933 ret = res_counter_memparse_write_strategy(buffer, &val);
2937 ret = mem_cgroup_resize_limit(memcg, val);
2939 ret = mem_cgroup_resize_memsw_limit(memcg, val);
2941 case RES_SOFT_LIMIT:
2942 ret = res_counter_memparse_write_strategy(buffer, &val);
2946 * For memsw, soft limits are hard to implement in terms
2947 * of semantics, for now, we support soft limits for
2948 * control without swap
2951 ret = res_counter_set_soft_limit(&memcg->res, val);
2956 ret = -EINVAL; /* should be BUG() ? */
2962 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
2963 unsigned long long *mem_limit, unsigned long long *memsw_limit)
2965 struct cgroup *cgroup;
2966 unsigned long long min_limit, min_memsw_limit, tmp;
2968 min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
2969 min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
2970 cgroup = memcg->css.cgroup;
2971 if (!memcg->use_hierarchy)
2974 while (cgroup->parent) {
2975 cgroup = cgroup->parent;
2976 memcg = mem_cgroup_from_cont(cgroup);
2977 if (!memcg->use_hierarchy)
2979 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
2980 min_limit = min(min_limit, tmp);
2981 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
2982 min_memsw_limit = min(min_memsw_limit, tmp);
2985 *mem_limit = min_limit;
2986 *memsw_limit = min_memsw_limit;
2990 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
2992 struct mem_cgroup *mem;
2995 mem = mem_cgroup_from_cont(cont);
2996 type = MEMFILE_TYPE(event);
2997 name = MEMFILE_ATTR(event);
3001 res_counter_reset_max(&mem->res);
3003 res_counter_reset_max(&mem->memsw);
3007 res_counter_reset_failcnt(&mem->res);
3009 res_counter_reset_failcnt(&mem->memsw);
3016 static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
3019 return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
3023 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
3024 struct cftype *cft, u64 val)
3026 struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
3028 if (val >= (1 << NR_MOVE_TYPE))
3031 * We check this value several times in both in can_attach() and
3032 * attach(), so we need cgroup lock to prevent this value from being
3036 mem->move_charge_at_immigrate = val;
3042 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
3043 struct cftype *cft, u64 val)
3050 /* For read statistics */
3066 struct mcs_total_stat {
3067 s64 stat[NR_MCS_STAT];
3073 } memcg_stat_strings[NR_MCS_STAT] = {
3074 {"cache", "total_cache"},
3075 {"rss", "total_rss"},
3076 {"mapped_file", "total_mapped_file"},
3077 {"pgpgin", "total_pgpgin"},
3078 {"pgpgout", "total_pgpgout"},
3079 {"swap", "total_swap"},
3080 {"inactive_anon", "total_inactive_anon"},
3081 {"active_anon", "total_active_anon"},
3082 {"inactive_file", "total_inactive_file"},
3083 {"active_file", "total_active_file"},
3084 {"unevictable", "total_unevictable"}
3088 static int mem_cgroup_get_local_stat(struct mem_cgroup *mem, void *data)
3090 struct mcs_total_stat *s = data;
3094 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_CACHE);
3095 s->stat[MCS_CACHE] += val * PAGE_SIZE;
3096 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_RSS);
3097 s->stat[MCS_RSS] += val * PAGE_SIZE;
3098 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_FILE_MAPPED);
3099 s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE;
3100 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_PGPGIN_COUNT);
3101 s->stat[MCS_PGPGIN] += val;
3102 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_PGPGOUT_COUNT);
3103 s->stat[MCS_PGPGOUT] += val;
3104 if (do_swap_account) {
3105 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_SWAPOUT);
3106 s->stat[MCS_SWAP] += val * PAGE_SIZE;
3110 val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_ANON);
3111 s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
3112 val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_ANON);
3113 s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
3114 val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_FILE);
3115 s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
3116 val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_FILE);
3117 s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
3118 val = mem_cgroup_get_local_zonestat(mem, LRU_UNEVICTABLE);
3119 s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
3124 mem_cgroup_get_total_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
3126 mem_cgroup_walk_tree(mem, s, mem_cgroup_get_local_stat);
3129 static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
3130 struct cgroup_map_cb *cb)
3132 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
3133 struct mcs_total_stat mystat;
3136 memset(&mystat, 0, sizeof(mystat));
3137 mem_cgroup_get_local_stat(mem_cont, &mystat);
3139 for (i = 0; i < NR_MCS_STAT; i++) {
3140 if (i == MCS_SWAP && !do_swap_account)
3142 cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
3145 /* Hierarchical information */
3147 unsigned long long limit, memsw_limit;
3148 memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
3149 cb->fill(cb, "hierarchical_memory_limit", limit);
3150 if (do_swap_account)
3151 cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
3154 memset(&mystat, 0, sizeof(mystat));
3155 mem_cgroup_get_total_stat(mem_cont, &mystat);
3156 for (i = 0; i < NR_MCS_STAT; i++) {
3157 if (i == MCS_SWAP && !do_swap_account)
3159 cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
3162 #ifdef CONFIG_DEBUG_VM
3163 cb->fill(cb, "inactive_ratio", calc_inactive_ratio(mem_cont, NULL));
3167 struct mem_cgroup_per_zone *mz;
3168 unsigned long recent_rotated[2] = {0, 0};
3169 unsigned long recent_scanned[2] = {0, 0};
3171 for_each_online_node(nid)
3172 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
3173 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
3175 recent_rotated[0] +=
3176 mz->reclaim_stat.recent_rotated[0];
3177 recent_rotated[1] +=
3178 mz->reclaim_stat.recent_rotated[1];
3179 recent_scanned[0] +=
3180 mz->reclaim_stat.recent_scanned[0];
3181 recent_scanned[1] +=
3182 mz->reclaim_stat.recent_scanned[1];
3184 cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
3185 cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
3186 cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
3187 cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
3194 static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
3196 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3198 return get_swappiness(memcg);
3201 static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
3204 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3205 struct mem_cgroup *parent;
3210 if (cgrp->parent == NULL)
3213 parent = mem_cgroup_from_cont(cgrp->parent);
3217 /* If under hierarchy, only empty-root can set this value */
3218 if ((parent->use_hierarchy) ||
3219 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
3224 spin_lock(&memcg->reclaim_param_lock);
3225 memcg->swappiness = val;
3226 spin_unlock(&memcg->reclaim_param_lock);
3234 static struct cftype mem_cgroup_files[] = {
3236 .name = "usage_in_bytes",
3237 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
3238 .read_u64 = mem_cgroup_read,
3241 .name = "max_usage_in_bytes",
3242 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
3243 .trigger = mem_cgroup_reset,
3244 .read_u64 = mem_cgroup_read,
3247 .name = "limit_in_bytes",
3248 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
3249 .write_string = mem_cgroup_write,
3250 .read_u64 = mem_cgroup_read,
3253 .name = "soft_limit_in_bytes",
3254 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
3255 .write_string = mem_cgroup_write,
3256 .read_u64 = mem_cgroup_read,
3260 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
3261 .trigger = mem_cgroup_reset,
3262 .read_u64 = mem_cgroup_read,
3266 .read_map = mem_control_stat_show,
3269 .name = "force_empty",
3270 .trigger = mem_cgroup_force_empty_write,
3273 .name = "use_hierarchy",
3274 .write_u64 = mem_cgroup_hierarchy_write,
3275 .read_u64 = mem_cgroup_hierarchy_read,
3278 .name = "swappiness",
3279 .read_u64 = mem_cgroup_swappiness_read,
3280 .write_u64 = mem_cgroup_swappiness_write,
3283 .name = "move_charge_at_immigrate",
3284 .read_u64 = mem_cgroup_move_charge_read,
3285 .write_u64 = mem_cgroup_move_charge_write,
3289 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3290 static struct cftype memsw_cgroup_files[] = {
3292 .name = "memsw.usage_in_bytes",
3293 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
3294 .read_u64 = mem_cgroup_read,
3297 .name = "memsw.max_usage_in_bytes",
3298 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
3299 .trigger = mem_cgroup_reset,
3300 .read_u64 = mem_cgroup_read,
3303 .name = "memsw.limit_in_bytes",
3304 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
3305 .write_string = mem_cgroup_write,
3306 .read_u64 = mem_cgroup_read,
3309 .name = "memsw.failcnt",
3310 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
3311 .trigger = mem_cgroup_reset,
3312 .read_u64 = mem_cgroup_read,
3316 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
3318 if (!do_swap_account)
3320 return cgroup_add_files(cont, ss, memsw_cgroup_files,
3321 ARRAY_SIZE(memsw_cgroup_files));
3324 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
3330 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
3332 struct mem_cgroup_per_node *pn;
3333 struct mem_cgroup_per_zone *mz;
3335 int zone, tmp = node;
3337 * This routine is called against possible nodes.
3338 * But it's BUG to call kmalloc() against offline node.
3340 * TODO: this routine can waste much memory for nodes which will
3341 * never be onlined. It's better to use memory hotplug callback
3344 if (!node_state(node, N_NORMAL_MEMORY))
3346 pn = kmalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
3350 mem->info.nodeinfo[node] = pn;
3351 memset(pn, 0, sizeof(*pn));
3353 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3354 mz = &pn->zoneinfo[zone];
3356 INIT_LIST_HEAD(&mz->lists[l]);
3357 mz->usage_in_excess = 0;
3358 mz->on_tree = false;
3364 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
3366 kfree(mem->info.nodeinfo[node]);
3369 static int mem_cgroup_size(void)
3371 int cpustat_size = nr_cpu_ids * sizeof(struct mem_cgroup_stat_cpu);
3372 return sizeof(struct mem_cgroup) + cpustat_size;
3375 static struct mem_cgroup *mem_cgroup_alloc(void)
3377 struct mem_cgroup *mem;
3378 int size = mem_cgroup_size();
3380 if (size < PAGE_SIZE)
3381 mem = kmalloc(size, GFP_KERNEL);
3383 mem = vmalloc(size);
3386 memset(mem, 0, size);
3391 * At destroying mem_cgroup, references from swap_cgroup can remain.
3392 * (scanning all at force_empty is too costly...)
3394 * Instead of clearing all references at force_empty, we remember
3395 * the number of reference from swap_cgroup and free mem_cgroup when
3396 * it goes down to 0.
3398 * Removal of cgroup itself succeeds regardless of refs from swap.
3401 static void __mem_cgroup_free(struct mem_cgroup *mem)
3405 mem_cgroup_remove_from_trees(mem);
3406 free_css_id(&mem_cgroup_subsys, &mem->css);
3408 for_each_node_state(node, N_POSSIBLE)
3409 free_mem_cgroup_per_zone_info(mem, node);
3411 if (mem_cgroup_size() < PAGE_SIZE)
3417 static void mem_cgroup_get(struct mem_cgroup *mem)
3419 atomic_inc(&mem->refcnt);
3422 static void __mem_cgroup_put(struct mem_cgroup *mem, int count)
3424 if (atomic_sub_and_test(count, &mem->refcnt)) {
3425 struct mem_cgroup *parent = parent_mem_cgroup(mem);
3426 __mem_cgroup_free(mem);
3428 mem_cgroup_put(parent);
3432 static void mem_cgroup_put(struct mem_cgroup *mem)
3434 __mem_cgroup_put(mem, 1);
3438 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
3440 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem)
3442 if (!mem->res.parent)
3444 return mem_cgroup_from_res_counter(mem->res.parent, res);
3447 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3448 static void __init enable_swap_cgroup(void)
3450 if (!mem_cgroup_disabled() && really_do_swap_account)
3451 do_swap_account = 1;
3454 static void __init enable_swap_cgroup(void)
3459 static int mem_cgroup_soft_limit_tree_init(void)
3461 struct mem_cgroup_tree_per_node *rtpn;
3462 struct mem_cgroup_tree_per_zone *rtpz;
3463 int tmp, node, zone;
3465 for_each_node_state(node, N_POSSIBLE) {
3467 if (!node_state(node, N_NORMAL_MEMORY))
3469 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
3473 soft_limit_tree.rb_tree_per_node[node] = rtpn;
3475 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3476 rtpz = &rtpn->rb_tree_per_zone[zone];
3477 rtpz->rb_root = RB_ROOT;
3478 spin_lock_init(&rtpz->lock);
3484 static struct cgroup_subsys_state * __ref
3485 mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
3487 struct mem_cgroup *mem, *parent;
3488 long error = -ENOMEM;
3491 mem = mem_cgroup_alloc();
3493 return ERR_PTR(error);
3495 for_each_node_state(node, N_POSSIBLE)
3496 if (alloc_mem_cgroup_per_zone_info(mem, node))
3500 if (cont->parent == NULL) {
3502 enable_swap_cgroup();
3504 root_mem_cgroup = mem;
3505 if (mem_cgroup_soft_limit_tree_init())
3507 for_each_possible_cpu(cpu) {
3508 struct memcg_stock_pcp *stock =
3509 &per_cpu(memcg_stock, cpu);
3510 INIT_WORK(&stock->work, drain_local_stock);
3512 hotcpu_notifier(memcg_stock_cpu_callback, 0);
3514 parent = mem_cgroup_from_cont(cont->parent);
3515 mem->use_hierarchy = parent->use_hierarchy;
3518 if (parent && parent->use_hierarchy) {
3519 res_counter_init(&mem->res, &parent->res);
3520 res_counter_init(&mem->memsw, &parent->memsw);
3522 * We increment refcnt of the parent to ensure that we can
3523 * safely access it on res_counter_charge/uncharge.
3524 * This refcnt will be decremented when freeing this
3525 * mem_cgroup(see mem_cgroup_put).
3527 mem_cgroup_get(parent);
3529 res_counter_init(&mem->res, NULL);
3530 res_counter_init(&mem->memsw, NULL);
3532 mem->last_scanned_child = 0;
3533 spin_lock_init(&mem->reclaim_param_lock);
3536 mem->swappiness = get_swappiness(parent);
3537 atomic_set(&mem->refcnt, 1);
3538 mem->move_charge_at_immigrate = 0;
3541 __mem_cgroup_free(mem);
3542 root_mem_cgroup = NULL;
3543 return ERR_PTR(error);
3546 static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
3547 struct cgroup *cont)
3549 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
3551 return mem_cgroup_force_empty(mem, false);
3554 static void mem_cgroup_destroy(struct cgroup_subsys *ss,
3555 struct cgroup *cont)
3557 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
3559 mem_cgroup_put(mem);
3562 static int mem_cgroup_populate(struct cgroup_subsys *ss,
3563 struct cgroup *cont)
3567 ret = cgroup_add_files(cont, ss, mem_cgroup_files,
3568 ARRAY_SIZE(mem_cgroup_files));
3571 ret = register_memsw_files(cont, ss);
3576 /* Handlers for move charge at task migration. */
3577 #define PRECHARGE_COUNT_AT_ONCE 256
3578 static int mem_cgroup_do_precharge(unsigned long count)
3581 int batch_count = PRECHARGE_COUNT_AT_ONCE;
3582 struct mem_cgroup *mem = mc.to;
3584 if (mem_cgroup_is_root(mem)) {
3585 mc.precharge += count;
3586 /* we don't need css_get for root */
3589 /* try to charge at once */
3591 struct res_counter *dummy;
3593 * "mem" cannot be under rmdir() because we've already checked
3594 * by cgroup_lock_live_cgroup() that it is not removed and we
3595 * are still under the same cgroup_mutex. So we can postpone
3598 if (res_counter_charge(&mem->res, PAGE_SIZE * count, &dummy))
3600 if (do_swap_account && res_counter_charge(&mem->memsw,
3601 PAGE_SIZE * count, &dummy)) {
3602 res_counter_uncharge(&mem->res, PAGE_SIZE * count);
3605 mc.precharge += count;
3606 VM_BUG_ON(test_bit(CSS_ROOT, &mem->css.flags));
3607 WARN_ON_ONCE(count > INT_MAX);
3608 __css_get(&mem->css, (int)count);
3612 /* fall back to one by one charge */
3614 if (signal_pending(current)) {
3618 if (!batch_count--) {
3619 batch_count = PRECHARGE_COUNT_AT_ONCE;
3622 ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, &mem,
3625 /* mem_cgroup_clear_mc() will do uncharge later */
3631 #else /* !CONFIG_MMU */
3632 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
3633 struct cgroup *cgroup,
3634 struct task_struct *p,
3639 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
3640 struct cgroup *cgroup,
3641 struct task_struct *p,
3645 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
3646 struct cgroup *cont,
3647 struct cgroup *old_cont,
3648 struct task_struct *p,
3655 * is_target_pte_for_mc - check a pte whether it is valid for move charge
3656 * @vma: the vma the pte to be checked belongs
3657 * @addr: the address corresponding to the pte to be checked
3658 * @ptent: the pte to be checked
3659 * @target: the pointer the target page or swap ent will be stored(can be NULL)
3662 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
3663 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
3664 * move charge. if @target is not NULL, the page is stored in target->page
3665 * with extra refcnt got(Callers should handle it).
3666 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
3667 * target for charge migration. if @target is not NULL, the entry is stored
3670 * Called with pte lock held.
3677 enum mc_target_type {
3678 MC_TARGET_NONE, /* not used */
3683 static int is_target_pte_for_mc(struct vm_area_struct *vma,
3684 unsigned long addr, pte_t ptent, union mc_target *target)
3686 struct page *page = NULL;
3687 struct page_cgroup *pc;
3689 swp_entry_t ent = { .val = 0 };
3690 int usage_count = 0;
3691 bool move_anon = test_bit(MOVE_CHARGE_TYPE_ANON,
3692 &mc.to->move_charge_at_immigrate);
3694 if (!pte_present(ptent)) {
3695 /* TODO: handle swap of shmes/tmpfs */
3696 if (pte_none(ptent) || pte_file(ptent))
3698 else if (is_swap_pte(ptent)) {
3699 ent = pte_to_swp_entry(ptent);
3700 if (!move_anon || non_swap_entry(ent))
3702 usage_count = mem_cgroup_count_swap_user(ent, &page);
3705 page = vm_normal_page(vma, addr, ptent);
3706 if (!page || !page_mapped(page))
3709 * TODO: We don't move charges of file(including shmem/tmpfs)
3712 if (!move_anon || !PageAnon(page))
3714 if (!get_page_unless_zero(page))
3716 usage_count = page_mapcount(page);
3718 if (usage_count > 1) {
3720 * TODO: We don't move charges of shared(used by multiple
3721 * processes) pages for now.
3728 pc = lookup_page_cgroup(page);
3730 * Do only loose check w/o page_cgroup lock.
3731 * mem_cgroup_move_account() checks the pc is valid or not under
3734 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
3735 ret = MC_TARGET_PAGE;
3737 target->page = page;
3739 if (!ret || !target)
3743 if (ent.val && do_swap_account && !ret &&
3744 css_id(&mc.from->css) == lookup_swap_cgroup(ent)) {
3745 ret = MC_TARGET_SWAP;
3752 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
3753 unsigned long addr, unsigned long end,
3754 struct mm_walk *walk)
3756 struct vm_area_struct *vma = walk->private;
3760 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
3761 for (; addr != end; pte++, addr += PAGE_SIZE)
3762 if (is_target_pte_for_mc(vma, addr, *pte, NULL))
3763 mc.precharge++; /* increment precharge temporarily */
3764 pte_unmap_unlock(pte - 1, ptl);
3770 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
3772 unsigned long precharge;
3773 struct vm_area_struct *vma;
3775 down_read(&mm->mmap_sem);
3776 for (vma = mm->mmap; vma; vma = vma->vm_next) {
3777 struct mm_walk mem_cgroup_count_precharge_walk = {
3778 .pmd_entry = mem_cgroup_count_precharge_pte_range,
3782 if (is_vm_hugetlb_page(vma))
3784 /* TODO: We don't move charges of shmem/tmpfs pages for now. */
3785 if (vma->vm_flags & VM_SHARED)
3787 walk_page_range(vma->vm_start, vma->vm_end,
3788 &mem_cgroup_count_precharge_walk);
3790 up_read(&mm->mmap_sem);
3792 precharge = mc.precharge;
3798 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
3800 return mem_cgroup_do_precharge(mem_cgroup_count_precharge(mm));
3803 static void mem_cgroup_clear_mc(void)
3805 /* we must uncharge all the leftover precharges from mc.to */
3807 __mem_cgroup_cancel_charge(mc.to, mc.precharge);
3811 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
3812 * we must uncharge here.
3814 if (mc.moved_charge) {
3815 __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
3816 mc.moved_charge = 0;
3818 /* we must fixup refcnts and charges */
3819 if (mc.moved_swap) {
3820 WARN_ON_ONCE(mc.moved_swap > INT_MAX);
3821 /* uncharge swap account from the old cgroup */
3822 if (!mem_cgroup_is_root(mc.from))
3823 res_counter_uncharge(&mc.from->memsw,
3824 PAGE_SIZE * mc.moved_swap);
3825 __mem_cgroup_put(mc.from, mc.moved_swap);
3827 if (!mem_cgroup_is_root(mc.to)) {
3829 * we charged both to->res and to->memsw, so we should
3832 res_counter_uncharge(&mc.to->res,
3833 PAGE_SIZE * mc.moved_swap);
3834 VM_BUG_ON(test_bit(CSS_ROOT, &mc.to->css.flags));
3835 __css_put(&mc.to->css, mc.moved_swap);
3837 /* we've already done mem_cgroup_get(mc.to) */
3843 mc.moving_task = NULL;
3844 wake_up_all(&mc.waitq);
3847 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
3848 struct cgroup *cgroup,
3849 struct task_struct *p,
3853 struct mem_cgroup *mem = mem_cgroup_from_cont(cgroup);
3855 if (mem->move_charge_at_immigrate) {
3856 struct mm_struct *mm;
3857 struct mem_cgroup *from = mem_cgroup_from_task(p);
3859 VM_BUG_ON(from == mem);
3861 mm = get_task_mm(p);
3864 /* We move charges only when we move a owner of the mm */
3865 if (mm->owner == p) {
3868 VM_BUG_ON(mc.precharge);
3869 VM_BUG_ON(mc.moved_charge);
3870 VM_BUG_ON(mc.moved_swap);
3871 VM_BUG_ON(mc.moving_task);
3875 mc.moved_charge = 0;
3877 mc.moving_task = current;
3879 ret = mem_cgroup_precharge_mc(mm);
3881 mem_cgroup_clear_mc();
3888 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
3889 struct cgroup *cgroup,
3890 struct task_struct *p,
3893 mem_cgroup_clear_mc();
3896 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
3897 unsigned long addr, unsigned long end,
3898 struct mm_walk *walk)
3901 struct vm_area_struct *vma = walk->private;
3906 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
3907 for (; addr != end; addr += PAGE_SIZE) {
3908 pte_t ptent = *(pte++);
3909 union mc_target target;
3912 struct page_cgroup *pc;
3918 type = is_target_pte_for_mc(vma, addr, ptent, &target);
3920 case MC_TARGET_PAGE:
3922 if (isolate_lru_page(page))
3924 pc = lookup_page_cgroup(page);
3925 if (!mem_cgroup_move_account(pc,
3926 mc.from, mc.to, false)) {
3928 /* we uncharge from mc.from later. */
3931 putback_lru_page(page);
3932 put: /* is_target_pte_for_mc() gets the page */
3935 case MC_TARGET_SWAP:
3937 if (!mem_cgroup_move_swap_account(ent,
3938 mc.from, mc.to, false)) {
3940 /* we fixup refcnts and charges later. */
3948 pte_unmap_unlock(pte - 1, ptl);
3953 * We have consumed all precharges we got in can_attach().
3954 * We try charge one by one, but don't do any additional
3955 * charges to mc.to if we have failed in charge once in attach()
3958 ret = mem_cgroup_do_precharge(1);
3966 static void mem_cgroup_move_charge(struct mm_struct *mm)
3968 struct vm_area_struct *vma;
3970 lru_add_drain_all();
3971 down_read(&mm->mmap_sem);
3972 for (vma = mm->mmap; vma; vma = vma->vm_next) {
3974 struct mm_walk mem_cgroup_move_charge_walk = {
3975 .pmd_entry = mem_cgroup_move_charge_pte_range,
3979 if (is_vm_hugetlb_page(vma))
3981 /* TODO: We don't move charges of shmem/tmpfs pages for now. */
3982 if (vma->vm_flags & VM_SHARED)
3984 ret = walk_page_range(vma->vm_start, vma->vm_end,
3985 &mem_cgroup_move_charge_walk);
3988 * means we have consumed all precharges and failed in
3989 * doing additional charge. Just abandon here.
3993 up_read(&mm->mmap_sem);
3996 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
3997 struct cgroup *cont,
3998 struct cgroup *old_cont,
3999 struct task_struct *p,
4002 struct mm_struct *mm;
4005 /* no need to move charge */
4008 mm = get_task_mm(p);
4010 mem_cgroup_move_charge(mm);
4013 mem_cgroup_clear_mc();
4016 struct cgroup_subsys mem_cgroup_subsys = {
4018 .subsys_id = mem_cgroup_subsys_id,
4019 .create = mem_cgroup_create,
4020 .pre_destroy = mem_cgroup_pre_destroy,
4021 .destroy = mem_cgroup_destroy,
4022 .populate = mem_cgroup_populate,
4023 .can_attach = mem_cgroup_can_attach,
4024 .cancel_attach = mem_cgroup_cancel_attach,
4025 .attach = mem_cgroup_move_task,
4030 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4032 static int __init disable_swap_account(char *s)
4034 really_do_swap_account = 0;
4037 __setup("noswapaccount", disable_swap_account);