1 /* memcontrol.c - Memory Controller
3 * Copyright IBM Corporation, 2007
4 * Author Balbir Singh <balbir@linux.vnet.ibm.com>
6 * Copyright 2007 OpenVZ SWsoft Inc
7 * Author: Pavel Emelianov <xemul@openvz.org>
10 * Copyright (C) 2009 Nokia Corporation
11 * Author: Kirill A. Shutemov
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
24 #include <linux/res_counter.h>
25 #include <linux/memcontrol.h>
26 #include <linux/cgroup.h>
28 #include <linux/hugetlb.h>
29 #include <linux/pagemap.h>
30 #include <linux/smp.h>
31 #include <linux/page-flags.h>
32 #include <linux/backing-dev.h>
33 #include <linux/bit_spinlock.h>
34 #include <linux/rcupdate.h>
35 #include <linux/limits.h>
36 #include <linux/mutex.h>
37 #include <linux/rbtree.h>
38 #include <linux/slab.h>
39 #include <linux/swap.h>
40 #include <linux/swapops.h>
41 #include <linux/spinlock.h>
42 #include <linux/eventfd.h>
43 #include <linux/sort.h>
45 #include <linux/seq_file.h>
46 #include <linux/vmalloc.h>
47 #include <linux/mm_inline.h>
48 #include <linux/page_cgroup.h>
49 #include <linux/cpu.h>
52 #include <asm/uaccess.h>
54 struct cgroup_subsys mem_cgroup_subsys __read_mostly;
55 #define MEM_CGROUP_RECLAIM_RETRIES 5
56 struct mem_cgroup *root_mem_cgroup __read_mostly;
58 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
59 /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
60 int do_swap_account __read_mostly;
61 static int really_do_swap_account __initdata = 1; /* for remember boot option*/
63 #define do_swap_account (0)
67 * Per memcg event counter is incremented at every pagein/pageout. This counter
68 * is used for trigger some periodic events. This is straightforward and better
69 * than using jiffies etc. to handle periodic memcg event.
71 * These values will be used as !((event) & ((1 <<(thresh)) - 1))
73 #define THRESHOLDS_EVENTS_THRESH (7) /* once in 128 */
74 #define SOFTLIMIT_EVENTS_THRESH (10) /* once in 1024 */
77 * Statistics for memory cgroup.
79 enum mem_cgroup_stat_index {
81 * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
83 MEM_CGROUP_STAT_CACHE, /* # of pages charged as cache */
84 MEM_CGROUP_STAT_RSS, /* # of pages charged as anon rss */
85 MEM_CGROUP_STAT_FILE_MAPPED, /* # of pages charged as file rss */
86 MEM_CGROUP_STAT_PGPGIN_COUNT, /* # of pages paged in */
87 MEM_CGROUP_STAT_PGPGOUT_COUNT, /* # of pages paged out */
88 MEM_CGROUP_STAT_SWAPOUT, /* # of pages, swapped out */
89 MEM_CGROUP_EVENTS, /* incremented at every pagein/pageout */
91 MEM_CGROUP_STAT_NSTATS,
94 struct mem_cgroup_stat_cpu {
95 s64 count[MEM_CGROUP_STAT_NSTATS];
99 * per-zone information in memory controller.
101 struct mem_cgroup_per_zone {
103 * spin_lock to protect the per cgroup LRU
105 struct list_head lists[NR_LRU_LISTS];
106 unsigned long count[NR_LRU_LISTS];
108 struct zone_reclaim_stat reclaim_stat;
109 struct rb_node tree_node; /* RB tree node */
110 unsigned long long usage_in_excess;/* Set to the value by which */
111 /* the soft limit is exceeded*/
113 struct mem_cgroup *mem; /* Back pointer, we cannot */
114 /* use container_of */
116 /* Macro for accessing counter */
117 #define MEM_CGROUP_ZSTAT(mz, idx) ((mz)->count[(idx)])
119 struct mem_cgroup_per_node {
120 struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
123 struct mem_cgroup_lru_info {
124 struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
128 * Cgroups above their limits are maintained in a RB-Tree, independent of
129 * their hierarchy representation
132 struct mem_cgroup_tree_per_zone {
133 struct rb_root rb_root;
137 struct mem_cgroup_tree_per_node {
138 struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
141 struct mem_cgroup_tree {
142 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
145 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
147 struct mem_cgroup_threshold {
148 struct eventfd_ctx *eventfd;
153 struct mem_cgroup_threshold_ary {
154 /* An array index points to threshold just below usage. */
155 int current_threshold;
156 /* Size of entries[] */
158 /* Array of thresholds */
159 struct mem_cgroup_threshold entries[0];
162 struct mem_cgroup_thresholds {
163 /* Primary thresholds array */
164 struct mem_cgroup_threshold_ary *primary;
166 * Spare threshold array.
167 * This is needed to make mem_cgroup_unregister_event() "never fail".
168 * It must be able to store at least primary->size - 1 entries.
170 struct mem_cgroup_threshold_ary *spare;
174 struct mem_cgroup_eventfd_list {
175 struct list_head list;
176 struct eventfd_ctx *eventfd;
179 static void mem_cgroup_threshold(struct mem_cgroup *mem);
180 static void mem_cgroup_oom_notify(struct mem_cgroup *mem);
183 * The memory controller data structure. The memory controller controls both
184 * page cache and RSS per cgroup. We would eventually like to provide
185 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
186 * to help the administrator determine what knobs to tune.
188 * TODO: Add a water mark for the memory controller. Reclaim will begin when
189 * we hit the water mark. May be even add a low water mark, such that
190 * no reclaim occurs from a cgroup at it's low water mark, this is
191 * a feature that will be implemented much later in the future.
194 struct cgroup_subsys_state css;
196 * the counter to account for memory usage
198 struct res_counter res;
200 * the counter to account for mem+swap usage.
202 struct res_counter memsw;
204 * Per cgroup active and inactive list, similar to the
205 * per zone LRU lists.
207 struct mem_cgroup_lru_info info;
210 protect against reclaim related member.
212 spinlock_t reclaim_param_lock;
215 * While reclaiming in a hierarchy, we cache the last child we
218 int last_scanned_child;
220 * Should the accounting and control be hierarchical, per subtree?
226 unsigned int swappiness;
227 /* OOM-Killer disable */
228 int oom_kill_disable;
230 /* set when res.limit == memsw.limit */
231 bool memsw_is_minimum;
233 /* protect arrays of thresholds */
234 struct mutex thresholds_lock;
236 /* thresholds for memory usage. RCU-protected */
237 struct mem_cgroup_thresholds thresholds;
239 /* thresholds for mem+swap usage. RCU-protected */
240 struct mem_cgroup_thresholds memsw_thresholds;
242 /* For oom notifier event fd */
243 struct list_head oom_notify;
246 * Should we move charges of a task when a task is moved into this
247 * mem_cgroup ? And what type of charges should we move ?
249 unsigned long move_charge_at_immigrate;
253 struct mem_cgroup_stat_cpu *stat;
256 /* Stuffs for move charges at task migration. */
258 * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a
259 * left-shifted bitmap of these types.
262 MOVE_CHARGE_TYPE_ANON, /* private anonymous page and swap of it */
263 MOVE_CHARGE_TYPE_FILE, /* file page(including tmpfs) and swap of it */
267 /* "mc" and its members are protected by cgroup_mutex */
268 static struct move_charge_struct {
269 struct mem_cgroup *from;
270 struct mem_cgroup *to;
271 unsigned long precharge;
272 unsigned long moved_charge;
273 unsigned long moved_swap;
274 struct task_struct *moving_task; /* a task moving charges */
275 wait_queue_head_t waitq; /* a waitq for other context */
277 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
280 static bool move_anon(void)
282 return test_bit(MOVE_CHARGE_TYPE_ANON,
283 &mc.to->move_charge_at_immigrate);
286 static bool move_file(void)
288 return test_bit(MOVE_CHARGE_TYPE_FILE,
289 &mc.to->move_charge_at_immigrate);
293 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
294 * limit reclaim to prevent infinite loops, if they ever occur.
296 #define MEM_CGROUP_MAX_RECLAIM_LOOPS (100)
297 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS (2)
300 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
301 MEM_CGROUP_CHARGE_TYPE_MAPPED,
302 MEM_CGROUP_CHARGE_TYPE_SHMEM, /* used by page migration of shmem */
303 MEM_CGROUP_CHARGE_TYPE_FORCE, /* used by force_empty */
304 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
305 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
309 /* only for here (for easy reading.) */
310 #define PCGF_CACHE (1UL << PCG_CACHE)
311 #define PCGF_USED (1UL << PCG_USED)
312 #define PCGF_LOCK (1UL << PCG_LOCK)
313 /* Not used, but added here for completeness */
314 #define PCGF_ACCT (1UL << PCG_ACCT)
316 /* for encoding cft->private value on file */
319 #define _OOM_TYPE (2)
320 #define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val))
321 #define MEMFILE_TYPE(val) (((val) >> 16) & 0xffff)
322 #define MEMFILE_ATTR(val) ((val) & 0xffff)
323 /* Used for OOM nofiier */
324 #define OOM_CONTROL (0)
327 * Reclaim flags for mem_cgroup_hierarchical_reclaim
329 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
330 #define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
331 #define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
332 #define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
333 #define MEM_CGROUP_RECLAIM_SOFT_BIT 0x2
334 #define MEM_CGROUP_RECLAIM_SOFT (1 << MEM_CGROUP_RECLAIM_SOFT_BIT)
336 static void mem_cgroup_get(struct mem_cgroup *mem);
337 static void mem_cgroup_put(struct mem_cgroup *mem);
338 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem);
339 static void drain_all_stock_async(void);
341 static struct mem_cgroup_per_zone *
342 mem_cgroup_zoneinfo(struct mem_cgroup *mem, int nid, int zid)
344 return &mem->info.nodeinfo[nid]->zoneinfo[zid];
347 struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *mem)
352 static struct mem_cgroup_per_zone *
353 page_cgroup_zoneinfo(struct page_cgroup *pc)
355 struct mem_cgroup *mem = pc->mem_cgroup;
356 int nid = page_cgroup_nid(pc);
357 int zid = page_cgroup_zid(pc);
362 return mem_cgroup_zoneinfo(mem, nid, zid);
365 static struct mem_cgroup_tree_per_zone *
366 soft_limit_tree_node_zone(int nid, int zid)
368 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
371 static struct mem_cgroup_tree_per_zone *
372 soft_limit_tree_from_page(struct page *page)
374 int nid = page_to_nid(page);
375 int zid = page_zonenum(page);
377 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
381 __mem_cgroup_insert_exceeded(struct mem_cgroup *mem,
382 struct mem_cgroup_per_zone *mz,
383 struct mem_cgroup_tree_per_zone *mctz,
384 unsigned long long new_usage_in_excess)
386 struct rb_node **p = &mctz->rb_root.rb_node;
387 struct rb_node *parent = NULL;
388 struct mem_cgroup_per_zone *mz_node;
393 mz->usage_in_excess = new_usage_in_excess;
394 if (!mz->usage_in_excess)
398 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
400 if (mz->usage_in_excess < mz_node->usage_in_excess)
403 * We can't avoid mem cgroups that are over their soft
404 * limit by the same amount
406 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
409 rb_link_node(&mz->tree_node, parent, p);
410 rb_insert_color(&mz->tree_node, &mctz->rb_root);
415 __mem_cgroup_remove_exceeded(struct mem_cgroup *mem,
416 struct mem_cgroup_per_zone *mz,
417 struct mem_cgroup_tree_per_zone *mctz)
421 rb_erase(&mz->tree_node, &mctz->rb_root);
426 mem_cgroup_remove_exceeded(struct mem_cgroup *mem,
427 struct mem_cgroup_per_zone *mz,
428 struct mem_cgroup_tree_per_zone *mctz)
430 spin_lock(&mctz->lock);
431 __mem_cgroup_remove_exceeded(mem, mz, mctz);
432 spin_unlock(&mctz->lock);
436 static void mem_cgroup_update_tree(struct mem_cgroup *mem, struct page *page)
438 unsigned long long excess;
439 struct mem_cgroup_per_zone *mz;
440 struct mem_cgroup_tree_per_zone *mctz;
441 int nid = page_to_nid(page);
442 int zid = page_zonenum(page);
443 mctz = soft_limit_tree_from_page(page);
446 * Necessary to update all ancestors when hierarchy is used.
447 * because their event counter is not touched.
449 for (; mem; mem = parent_mem_cgroup(mem)) {
450 mz = mem_cgroup_zoneinfo(mem, nid, zid);
451 excess = res_counter_soft_limit_excess(&mem->res);
453 * We have to update the tree if mz is on RB-tree or
454 * mem is over its softlimit.
456 if (excess || mz->on_tree) {
457 spin_lock(&mctz->lock);
458 /* if on-tree, remove it */
460 __mem_cgroup_remove_exceeded(mem, mz, mctz);
462 * Insert again. mz->usage_in_excess will be updated.
463 * If excess is 0, no tree ops.
465 __mem_cgroup_insert_exceeded(mem, mz, mctz, excess);
466 spin_unlock(&mctz->lock);
471 static void mem_cgroup_remove_from_trees(struct mem_cgroup *mem)
474 struct mem_cgroup_per_zone *mz;
475 struct mem_cgroup_tree_per_zone *mctz;
477 for_each_node_state(node, N_POSSIBLE) {
478 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
479 mz = mem_cgroup_zoneinfo(mem, node, zone);
480 mctz = soft_limit_tree_node_zone(node, zone);
481 mem_cgroup_remove_exceeded(mem, mz, mctz);
486 static inline unsigned long mem_cgroup_get_excess(struct mem_cgroup *mem)
488 return res_counter_soft_limit_excess(&mem->res) >> PAGE_SHIFT;
491 static struct mem_cgroup_per_zone *
492 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
494 struct rb_node *rightmost = NULL;
495 struct mem_cgroup_per_zone *mz;
499 rightmost = rb_last(&mctz->rb_root);
501 goto done; /* Nothing to reclaim from */
503 mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
505 * Remove the node now but someone else can add it back,
506 * we will to add it back at the end of reclaim to its correct
507 * position in the tree.
509 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
510 if (!res_counter_soft_limit_excess(&mz->mem->res) ||
511 !css_tryget(&mz->mem->css))
517 static struct mem_cgroup_per_zone *
518 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
520 struct mem_cgroup_per_zone *mz;
522 spin_lock(&mctz->lock);
523 mz = __mem_cgroup_largest_soft_limit_node(mctz);
524 spin_unlock(&mctz->lock);
528 static s64 mem_cgroup_read_stat(struct mem_cgroup *mem,
529 enum mem_cgroup_stat_index idx)
534 for_each_possible_cpu(cpu)
535 val += per_cpu(mem->stat->count[idx], cpu);
539 static s64 mem_cgroup_local_usage(struct mem_cgroup *mem)
543 ret = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_RSS);
544 ret += mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_CACHE);
548 static void mem_cgroup_swap_statistics(struct mem_cgroup *mem,
551 int val = (charge) ? 1 : -1;
552 this_cpu_add(mem->stat->count[MEM_CGROUP_STAT_SWAPOUT], val);
555 static void mem_cgroup_charge_statistics(struct mem_cgroup *mem,
556 struct page_cgroup *pc,
559 int val = (charge) ? 1 : -1;
563 if (PageCgroupCache(pc))
564 __this_cpu_add(mem->stat->count[MEM_CGROUP_STAT_CACHE], val);
566 __this_cpu_add(mem->stat->count[MEM_CGROUP_STAT_RSS], val);
569 __this_cpu_inc(mem->stat->count[MEM_CGROUP_STAT_PGPGIN_COUNT]);
571 __this_cpu_inc(mem->stat->count[MEM_CGROUP_STAT_PGPGOUT_COUNT]);
572 __this_cpu_inc(mem->stat->count[MEM_CGROUP_EVENTS]);
577 static unsigned long mem_cgroup_get_local_zonestat(struct mem_cgroup *mem,
581 struct mem_cgroup_per_zone *mz;
584 for_each_online_node(nid)
585 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
586 mz = mem_cgroup_zoneinfo(mem, nid, zid);
587 total += MEM_CGROUP_ZSTAT(mz, idx);
592 static bool __memcg_event_check(struct mem_cgroup *mem, int event_mask_shift)
596 val = this_cpu_read(mem->stat->count[MEM_CGROUP_EVENTS]);
598 return !(val & ((1 << event_mask_shift) - 1));
602 * Check events in order.
605 static void memcg_check_events(struct mem_cgroup *mem, struct page *page)
607 /* threshold event is triggered in finer grain than soft limit */
608 if (unlikely(__memcg_event_check(mem, THRESHOLDS_EVENTS_THRESH))) {
609 mem_cgroup_threshold(mem);
610 if (unlikely(__memcg_event_check(mem, SOFTLIMIT_EVENTS_THRESH)))
611 mem_cgroup_update_tree(mem, page);
615 static struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
617 return container_of(cgroup_subsys_state(cont,
618 mem_cgroup_subsys_id), struct mem_cgroup,
622 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
625 * mm_update_next_owner() may clear mm->owner to NULL
626 * if it races with swapoff, page migration, etc.
627 * So this can be called with p == NULL.
632 return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
633 struct mem_cgroup, css);
636 static struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
638 struct mem_cgroup *mem = NULL;
643 * Because we have no locks, mm->owner's may be being moved to other
644 * cgroup. We use css_tryget() here even if this looks
645 * pessimistic (rather than adding locks here).
649 mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
652 } while (!css_tryget(&mem->css));
658 * Call callback function against all cgroup under hierarchy tree.
660 static int mem_cgroup_walk_tree(struct mem_cgroup *root, void *data,
661 int (*func)(struct mem_cgroup *, void *))
663 int found, ret, nextid;
664 struct cgroup_subsys_state *css;
665 struct mem_cgroup *mem;
667 if (!root->use_hierarchy)
668 return (*func)(root, data);
676 css = css_get_next(&mem_cgroup_subsys, nextid, &root->css,
678 if (css && css_tryget(css))
679 mem = container_of(css, struct mem_cgroup, css);
683 ret = (*func)(mem, data);
687 } while (!ret && css);
692 static inline bool mem_cgroup_is_root(struct mem_cgroup *mem)
694 return (mem == root_mem_cgroup);
698 * Following LRU functions are allowed to be used without PCG_LOCK.
699 * Operations are called by routine of global LRU independently from memcg.
700 * What we have to take care of here is validness of pc->mem_cgroup.
702 * Changes to pc->mem_cgroup happens when
705 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
706 * It is added to LRU before charge.
707 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
708 * When moving account, the page is not on LRU. It's isolated.
711 void mem_cgroup_del_lru_list(struct page *page, enum lru_list lru)
713 struct page_cgroup *pc;
714 struct mem_cgroup_per_zone *mz;
716 if (mem_cgroup_disabled())
718 pc = lookup_page_cgroup(page);
719 /* can happen while we handle swapcache. */
720 if (!TestClearPageCgroupAcctLRU(pc))
722 VM_BUG_ON(!pc->mem_cgroup);
724 * We don't check PCG_USED bit. It's cleared when the "page" is finally
725 * removed from global LRU.
727 mz = page_cgroup_zoneinfo(pc);
728 MEM_CGROUP_ZSTAT(mz, lru) -= 1;
729 if (mem_cgroup_is_root(pc->mem_cgroup))
731 VM_BUG_ON(list_empty(&pc->lru));
732 list_del_init(&pc->lru);
736 void mem_cgroup_del_lru(struct page *page)
738 mem_cgroup_del_lru_list(page, page_lru(page));
741 void mem_cgroup_rotate_lru_list(struct page *page, enum lru_list lru)
743 struct mem_cgroup_per_zone *mz;
744 struct page_cgroup *pc;
746 if (mem_cgroup_disabled())
749 pc = lookup_page_cgroup(page);
751 * Used bit is set without atomic ops but after smp_wmb().
752 * For making pc->mem_cgroup visible, insert smp_rmb() here.
755 /* unused or root page is not rotated. */
756 if (!PageCgroupUsed(pc) || mem_cgroup_is_root(pc->mem_cgroup))
758 mz = page_cgroup_zoneinfo(pc);
759 list_move(&pc->lru, &mz->lists[lru]);
762 void mem_cgroup_add_lru_list(struct page *page, enum lru_list lru)
764 struct page_cgroup *pc;
765 struct mem_cgroup_per_zone *mz;
767 if (mem_cgroup_disabled())
769 pc = lookup_page_cgroup(page);
770 VM_BUG_ON(PageCgroupAcctLRU(pc));
772 * Used bit is set without atomic ops but after smp_wmb().
773 * For making pc->mem_cgroup visible, insert smp_rmb() here.
776 if (!PageCgroupUsed(pc))
779 mz = page_cgroup_zoneinfo(pc);
780 MEM_CGROUP_ZSTAT(mz, lru) += 1;
781 SetPageCgroupAcctLRU(pc);
782 if (mem_cgroup_is_root(pc->mem_cgroup))
784 list_add(&pc->lru, &mz->lists[lru]);
788 * At handling SwapCache, pc->mem_cgroup may be changed while it's linked to
789 * lru because the page may.be reused after it's fully uncharged (because of
790 * SwapCache behavior).To handle that, unlink page_cgroup from LRU when charge
791 * it again. This function is only used to charge SwapCache. It's done under
792 * lock_page and expected that zone->lru_lock is never held.
794 static void mem_cgroup_lru_del_before_commit_swapcache(struct page *page)
797 struct zone *zone = page_zone(page);
798 struct page_cgroup *pc = lookup_page_cgroup(page);
800 spin_lock_irqsave(&zone->lru_lock, flags);
802 * Forget old LRU when this page_cgroup is *not* used. This Used bit
803 * is guarded by lock_page() because the page is SwapCache.
805 if (!PageCgroupUsed(pc))
806 mem_cgroup_del_lru_list(page, page_lru(page));
807 spin_unlock_irqrestore(&zone->lru_lock, flags);
810 static void mem_cgroup_lru_add_after_commit_swapcache(struct page *page)
813 struct zone *zone = page_zone(page);
814 struct page_cgroup *pc = lookup_page_cgroup(page);
816 spin_lock_irqsave(&zone->lru_lock, flags);
817 /* link when the page is linked to LRU but page_cgroup isn't */
818 if (PageLRU(page) && !PageCgroupAcctLRU(pc))
819 mem_cgroup_add_lru_list(page, page_lru(page));
820 spin_unlock_irqrestore(&zone->lru_lock, flags);
824 void mem_cgroup_move_lists(struct page *page,
825 enum lru_list from, enum lru_list to)
827 if (mem_cgroup_disabled())
829 mem_cgroup_del_lru_list(page, from);
830 mem_cgroup_add_lru_list(page, to);
833 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *mem)
836 struct mem_cgroup *curr = NULL;
840 curr = try_get_mem_cgroup_from_mm(task->mm);
846 * We should check use_hierarchy of "mem" not "curr". Because checking
847 * use_hierarchy of "curr" here make this function true if hierarchy is
848 * enabled in "curr" and "curr" is a child of "mem" in *cgroup*
849 * hierarchy(even if use_hierarchy is disabled in "mem").
851 if (mem->use_hierarchy)
852 ret = css_is_ancestor(&curr->css, &mem->css);
859 static int calc_inactive_ratio(struct mem_cgroup *memcg, unsigned long *present_pages)
861 unsigned long active;
862 unsigned long inactive;
864 unsigned long inactive_ratio;
866 inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_ANON);
867 active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_ANON);
869 gb = (inactive + active) >> (30 - PAGE_SHIFT);
871 inactive_ratio = int_sqrt(10 * gb);
876 present_pages[0] = inactive;
877 present_pages[1] = active;
880 return inactive_ratio;
883 int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg)
885 unsigned long active;
886 unsigned long inactive;
887 unsigned long present_pages[2];
888 unsigned long inactive_ratio;
890 inactive_ratio = calc_inactive_ratio(memcg, present_pages);
892 inactive = present_pages[0];
893 active = present_pages[1];
895 if (inactive * inactive_ratio < active)
901 int mem_cgroup_inactive_file_is_low(struct mem_cgroup *memcg)
903 unsigned long active;
904 unsigned long inactive;
906 inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_FILE);
907 active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_FILE);
909 return (active > inactive);
912 unsigned long mem_cgroup_zone_nr_pages(struct mem_cgroup *memcg,
916 int nid = zone->zone_pgdat->node_id;
917 int zid = zone_idx(zone);
918 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
920 return MEM_CGROUP_ZSTAT(mz, lru);
923 struct zone_reclaim_stat *mem_cgroup_get_reclaim_stat(struct mem_cgroup *memcg,
926 int nid = zone->zone_pgdat->node_id;
927 int zid = zone_idx(zone);
928 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
930 return &mz->reclaim_stat;
933 struct zone_reclaim_stat *
934 mem_cgroup_get_reclaim_stat_from_page(struct page *page)
936 struct page_cgroup *pc;
937 struct mem_cgroup_per_zone *mz;
939 if (mem_cgroup_disabled())
942 pc = lookup_page_cgroup(page);
944 * Used bit is set without atomic ops but after smp_wmb().
945 * For making pc->mem_cgroup visible, insert smp_rmb() here.
948 if (!PageCgroupUsed(pc))
951 mz = page_cgroup_zoneinfo(pc);
955 return &mz->reclaim_stat;
958 unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan,
959 struct list_head *dst,
960 unsigned long *scanned, int order,
961 int mode, struct zone *z,
962 struct mem_cgroup *mem_cont,
963 int active, int file)
965 unsigned long nr_taken = 0;
969 struct list_head *src;
970 struct page_cgroup *pc, *tmp;
971 int nid = z->zone_pgdat->node_id;
972 int zid = zone_idx(z);
973 struct mem_cgroup_per_zone *mz;
974 int lru = LRU_FILE * file + active;
978 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
979 src = &mz->lists[lru];
982 list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
983 if (scan >= nr_to_scan)
987 if (unlikely(!PageCgroupUsed(pc)))
989 if (unlikely(!PageLRU(page)))
993 ret = __isolate_lru_page(page, mode, file);
996 list_move(&page->lru, dst);
997 mem_cgroup_del_lru(page);
1001 /* we don't affect global LRU but rotate in our LRU */
1002 mem_cgroup_rotate_lru_list(page, page_lru(page));
1013 #define mem_cgroup_from_res_counter(counter, member) \
1014 container_of(counter, struct mem_cgroup, member)
1016 static bool mem_cgroup_check_under_limit(struct mem_cgroup *mem)
1018 if (do_swap_account) {
1019 if (res_counter_check_under_limit(&mem->res) &&
1020 res_counter_check_under_limit(&mem->memsw))
1023 if (res_counter_check_under_limit(&mem->res))
1028 static unsigned int get_swappiness(struct mem_cgroup *memcg)
1030 struct cgroup *cgrp = memcg->css.cgroup;
1031 unsigned int swappiness;
1034 if (cgrp->parent == NULL)
1035 return vm_swappiness;
1037 spin_lock(&memcg->reclaim_param_lock);
1038 swappiness = memcg->swappiness;
1039 spin_unlock(&memcg->reclaim_param_lock);
1044 static int mem_cgroup_count_children_cb(struct mem_cgroup *mem, void *data)
1052 * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode.
1053 * @memcg: The memory cgroup that went over limit
1054 * @p: Task that is going to be killed
1056 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1059 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1061 struct cgroup *task_cgrp;
1062 struct cgroup *mem_cgrp;
1064 * Need a buffer in BSS, can't rely on allocations. The code relies
1065 * on the assumption that OOM is serialized for memory controller.
1066 * If this assumption is broken, revisit this code.
1068 static char memcg_name[PATH_MAX];
1077 mem_cgrp = memcg->css.cgroup;
1078 task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1080 ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1083 * Unfortunately, we are unable to convert to a useful name
1084 * But we'll still print out the usage information
1091 printk(KERN_INFO "Task in %s killed", memcg_name);
1094 ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1102 * Continues from above, so we don't need an KERN_ level
1104 printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
1107 printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
1108 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1109 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1110 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1111 printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
1113 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1114 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1115 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1119 * This function returns the number of memcg under hierarchy tree. Returns
1120 * 1(self count) if no children.
1122 static int mem_cgroup_count_children(struct mem_cgroup *mem)
1125 mem_cgroup_walk_tree(mem, &num, mem_cgroup_count_children_cb);
1130 * Return the memory (and swap, if configured) limit for a memcg.
1132 u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
1137 limit = res_counter_read_u64(&memcg->res, RES_LIMIT) +
1139 memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
1141 * If memsw is finite and limits the amount of swap space available
1142 * to this memcg, return that limit.
1144 return min(limit, memsw);
1148 * Visit the first child (need not be the first child as per the ordering
1149 * of the cgroup list, since we track last_scanned_child) of @mem and use
1150 * that to reclaim free pages from.
1152 static struct mem_cgroup *
1153 mem_cgroup_select_victim(struct mem_cgroup *root_mem)
1155 struct mem_cgroup *ret = NULL;
1156 struct cgroup_subsys_state *css;
1159 if (!root_mem->use_hierarchy) {
1160 css_get(&root_mem->css);
1166 nextid = root_mem->last_scanned_child + 1;
1167 css = css_get_next(&mem_cgroup_subsys, nextid, &root_mem->css,
1169 if (css && css_tryget(css))
1170 ret = container_of(css, struct mem_cgroup, css);
1173 /* Updates scanning parameter */
1174 spin_lock(&root_mem->reclaim_param_lock);
1176 /* this means start scan from ID:1 */
1177 root_mem->last_scanned_child = 0;
1179 root_mem->last_scanned_child = found;
1180 spin_unlock(&root_mem->reclaim_param_lock);
1187 * Scan the hierarchy if needed to reclaim memory. We remember the last child
1188 * we reclaimed from, so that we don't end up penalizing one child extensively
1189 * based on its position in the children list.
1191 * root_mem is the original ancestor that we've been reclaim from.
1193 * We give up and return to the caller when we visit root_mem twice.
1194 * (other groups can be removed while we're walking....)
1196 * If shrink==true, for avoiding to free too much, this returns immedieately.
1198 static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup *root_mem,
1201 unsigned long reclaim_options)
1203 struct mem_cgroup *victim;
1206 bool noswap = reclaim_options & MEM_CGROUP_RECLAIM_NOSWAP;
1207 bool shrink = reclaim_options & MEM_CGROUP_RECLAIM_SHRINK;
1208 bool check_soft = reclaim_options & MEM_CGROUP_RECLAIM_SOFT;
1209 unsigned long excess = mem_cgroup_get_excess(root_mem);
1211 /* If memsw_is_minimum==1, swap-out is of-no-use. */
1212 if (root_mem->memsw_is_minimum)
1216 victim = mem_cgroup_select_victim(root_mem);
1217 if (victim == root_mem) {
1220 drain_all_stock_async();
1223 * If we have not been able to reclaim
1224 * anything, it might because there are
1225 * no reclaimable pages under this hierarchy
1227 if (!check_soft || !total) {
1228 css_put(&victim->css);
1232 * We want to do more targetted reclaim.
1233 * excess >> 2 is not to excessive so as to
1234 * reclaim too much, nor too less that we keep
1235 * coming back to reclaim from this cgroup
1237 if (total >= (excess >> 2) ||
1238 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS)) {
1239 css_put(&victim->css);
1244 if (!mem_cgroup_local_usage(victim)) {
1245 /* this cgroup's local usage == 0 */
1246 css_put(&victim->css);
1249 /* we use swappiness of local cgroup */
1251 ret = mem_cgroup_shrink_node_zone(victim, gfp_mask,
1252 noswap, get_swappiness(victim), zone,
1253 zone->zone_pgdat->node_id);
1255 ret = try_to_free_mem_cgroup_pages(victim, gfp_mask,
1256 noswap, get_swappiness(victim));
1257 css_put(&victim->css);
1259 * At shrinking usage, we can't check we should stop here or
1260 * reclaim more. It's depends on callers. last_scanned_child
1261 * will work enough for keeping fairness under tree.
1267 if (res_counter_check_under_soft_limit(&root_mem->res))
1269 } else if (mem_cgroup_check_under_limit(root_mem))
1275 static int mem_cgroup_oom_lock_cb(struct mem_cgroup *mem, void *data)
1277 int *val = (int *)data;
1280 * Logically, we can stop scanning immediately when we find
1281 * a memcg is already locked. But condidering unlock ops and
1282 * creation/removal of memcg, scan-all is simple operation.
1284 x = atomic_inc_return(&mem->oom_lock);
1285 *val = max(x, *val);
1289 * Check OOM-Killer is already running under our hierarchy.
1290 * If someone is running, return false.
1292 static bool mem_cgroup_oom_lock(struct mem_cgroup *mem)
1296 mem_cgroup_walk_tree(mem, &lock_count, mem_cgroup_oom_lock_cb);
1298 if (lock_count == 1)
1303 static int mem_cgroup_oom_unlock_cb(struct mem_cgroup *mem, void *data)
1306 * When a new child is created while the hierarchy is under oom,
1307 * mem_cgroup_oom_lock() may not be called. We have to use
1308 * atomic_add_unless() here.
1310 atomic_add_unless(&mem->oom_lock, -1, 0);
1314 static void mem_cgroup_oom_unlock(struct mem_cgroup *mem)
1316 mem_cgroup_walk_tree(mem, NULL, mem_cgroup_oom_unlock_cb);
1319 static DEFINE_MUTEX(memcg_oom_mutex);
1320 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1322 struct oom_wait_info {
1323 struct mem_cgroup *mem;
1327 static int memcg_oom_wake_function(wait_queue_t *wait,
1328 unsigned mode, int sync, void *arg)
1330 struct mem_cgroup *wake_mem = (struct mem_cgroup *)arg;
1331 struct oom_wait_info *oom_wait_info;
1333 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1335 if (oom_wait_info->mem == wake_mem)
1337 /* if no hierarchy, no match */
1338 if (!oom_wait_info->mem->use_hierarchy || !wake_mem->use_hierarchy)
1341 * Both of oom_wait_info->mem and wake_mem are stable under us.
1342 * Then we can use css_is_ancestor without taking care of RCU.
1344 if (!css_is_ancestor(&oom_wait_info->mem->css, &wake_mem->css) &&
1345 !css_is_ancestor(&wake_mem->css, &oom_wait_info->mem->css))
1349 return autoremove_wake_function(wait, mode, sync, arg);
1352 static void memcg_wakeup_oom(struct mem_cgroup *mem)
1354 /* for filtering, pass "mem" as argument. */
1355 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, mem);
1358 static void memcg_oom_recover(struct mem_cgroup *mem)
1360 if (atomic_read(&mem->oom_lock))
1361 memcg_wakeup_oom(mem);
1365 * try to call OOM killer. returns false if we should exit memory-reclaim loop.
1367 bool mem_cgroup_handle_oom(struct mem_cgroup *mem, gfp_t mask)
1369 struct oom_wait_info owait;
1370 bool locked, need_to_kill;
1373 owait.wait.flags = 0;
1374 owait.wait.func = memcg_oom_wake_function;
1375 owait.wait.private = current;
1376 INIT_LIST_HEAD(&owait.wait.task_list);
1377 need_to_kill = true;
1378 /* At first, try to OOM lock hierarchy under mem.*/
1379 mutex_lock(&memcg_oom_mutex);
1380 locked = mem_cgroup_oom_lock(mem);
1382 * Even if signal_pending(), we can't quit charge() loop without
1383 * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
1384 * under OOM is always welcomed, use TASK_KILLABLE here.
1386 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
1387 if (!locked || mem->oom_kill_disable)
1388 need_to_kill = false;
1390 mem_cgroup_oom_notify(mem);
1391 mutex_unlock(&memcg_oom_mutex);
1394 finish_wait(&memcg_oom_waitq, &owait.wait);
1395 mem_cgroup_out_of_memory(mem, mask);
1398 finish_wait(&memcg_oom_waitq, &owait.wait);
1400 mutex_lock(&memcg_oom_mutex);
1401 mem_cgroup_oom_unlock(mem);
1402 memcg_wakeup_oom(mem);
1403 mutex_unlock(&memcg_oom_mutex);
1405 if (test_thread_flag(TIF_MEMDIE) || fatal_signal_pending(current))
1407 /* Give chance to dying process */
1408 schedule_timeout(1);
1413 * Currently used to update mapped file statistics, but the routine can be
1414 * generalized to update other statistics as well.
1416 void mem_cgroup_update_file_mapped(struct page *page, int val)
1418 struct mem_cgroup *mem;
1419 struct page_cgroup *pc;
1421 pc = lookup_page_cgroup(page);
1425 lock_page_cgroup(pc);
1426 mem = pc->mem_cgroup;
1427 if (!mem || !PageCgroupUsed(pc))
1431 * Preemption is already disabled. We can use __this_cpu_xxx
1434 __this_cpu_inc(mem->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
1435 SetPageCgroupFileMapped(pc);
1437 __this_cpu_dec(mem->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
1438 ClearPageCgroupFileMapped(pc);
1442 unlock_page_cgroup(pc);
1446 * size of first charge trial. "32" comes from vmscan.c's magic value.
1447 * TODO: maybe necessary to use big numbers in big irons.
1449 #define CHARGE_SIZE (32 * PAGE_SIZE)
1450 struct memcg_stock_pcp {
1451 struct mem_cgroup *cached; /* this never be root cgroup */
1453 struct work_struct work;
1455 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
1456 static atomic_t memcg_drain_count;
1459 * Try to consume stocked charge on this cpu. If success, PAGE_SIZE is consumed
1460 * from local stock and true is returned. If the stock is 0 or charges from a
1461 * cgroup which is not current target, returns false. This stock will be
1464 static bool consume_stock(struct mem_cgroup *mem)
1466 struct memcg_stock_pcp *stock;
1469 stock = &get_cpu_var(memcg_stock);
1470 if (mem == stock->cached && stock->charge)
1471 stock->charge -= PAGE_SIZE;
1472 else /* need to call res_counter_charge */
1474 put_cpu_var(memcg_stock);
1479 * Returns stocks cached in percpu to res_counter and reset cached information.
1481 static void drain_stock(struct memcg_stock_pcp *stock)
1483 struct mem_cgroup *old = stock->cached;
1485 if (stock->charge) {
1486 res_counter_uncharge(&old->res, stock->charge);
1487 if (do_swap_account)
1488 res_counter_uncharge(&old->memsw, stock->charge);
1490 stock->cached = NULL;
1495 * This must be called under preempt disabled or must be called by
1496 * a thread which is pinned to local cpu.
1498 static void drain_local_stock(struct work_struct *dummy)
1500 struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
1505 * Cache charges(val) which is from res_counter, to local per_cpu area.
1506 * This will be consumed by consume_stock() function, later.
1508 static void refill_stock(struct mem_cgroup *mem, int val)
1510 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
1512 if (stock->cached != mem) { /* reset if necessary */
1514 stock->cached = mem;
1516 stock->charge += val;
1517 put_cpu_var(memcg_stock);
1521 * Tries to drain stocked charges in other cpus. This function is asynchronous
1522 * and just put a work per cpu for draining localy on each cpu. Caller can
1523 * expects some charges will be back to res_counter later but cannot wait for
1526 static void drain_all_stock_async(void)
1529 /* This function is for scheduling "drain" in asynchronous way.
1530 * The result of "drain" is not directly handled by callers. Then,
1531 * if someone is calling drain, we don't have to call drain more.
1532 * Anyway, WORK_STRUCT_PENDING check in queue_work_on() will catch if
1533 * there is a race. We just do loose check here.
1535 if (atomic_read(&memcg_drain_count))
1537 /* Notify other cpus that system-wide "drain" is running */
1538 atomic_inc(&memcg_drain_count);
1540 for_each_online_cpu(cpu) {
1541 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
1542 schedule_work_on(cpu, &stock->work);
1545 atomic_dec(&memcg_drain_count);
1546 /* We don't wait for flush_work */
1549 /* This is a synchronous drain interface. */
1550 static void drain_all_stock_sync(void)
1552 /* called when force_empty is called */
1553 atomic_inc(&memcg_drain_count);
1554 schedule_on_each_cpu(drain_local_stock);
1555 atomic_dec(&memcg_drain_count);
1558 static int __cpuinit memcg_stock_cpu_callback(struct notifier_block *nb,
1559 unsigned long action,
1562 int cpu = (unsigned long)hcpu;
1563 struct memcg_stock_pcp *stock;
1565 if (action != CPU_DEAD)
1567 stock = &per_cpu(memcg_stock, cpu);
1573 * Unlike exported interface, "oom" parameter is added. if oom==true,
1574 * oom-killer can be invoked.
1576 static int __mem_cgroup_try_charge(struct mm_struct *mm,
1577 gfp_t gfp_mask, struct mem_cgroup **memcg, bool oom)
1579 struct mem_cgroup *mem, *mem_over_limit;
1580 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
1581 struct res_counter *fail_res;
1582 int csize = CHARGE_SIZE;
1585 * Unlike gloval-vm's OOM-kill, we're not in memory shortage
1586 * in system level. So, allow to go ahead dying process in addition to
1589 if (unlikely(test_thread_flag(TIF_MEMDIE)
1590 || fatal_signal_pending(current)))
1594 * We always charge the cgroup the mm_struct belongs to.
1595 * The mm_struct's mem_cgroup changes on task migration if the
1596 * thread group leader migrates. It's possible that mm is not
1597 * set, if so charge the init_mm (happens for pagecache usage).
1601 mem = try_get_mem_cgroup_from_mm(mm);
1609 VM_BUG_ON(css_is_removed(&mem->css));
1610 if (mem_cgroup_is_root(mem))
1615 unsigned long flags = 0;
1617 if (consume_stock(mem))
1620 ret = res_counter_charge(&mem->res, csize, &fail_res);
1622 if (!do_swap_account)
1624 ret = res_counter_charge(&mem->memsw, csize, &fail_res);
1627 /* mem+swap counter fails */
1628 res_counter_uncharge(&mem->res, csize);
1629 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
1630 mem_over_limit = mem_cgroup_from_res_counter(fail_res,
1633 /* mem counter fails */
1634 mem_over_limit = mem_cgroup_from_res_counter(fail_res,
1637 /* reduce request size and retry */
1638 if (csize > PAGE_SIZE) {
1642 if (!(gfp_mask & __GFP_WAIT))
1645 ret = mem_cgroup_hierarchical_reclaim(mem_over_limit, NULL,
1651 * try_to_free_mem_cgroup_pages() might not give us a full
1652 * picture of reclaim. Some pages are reclaimed and might be
1653 * moved to swap cache or just unmapped from the cgroup.
1654 * Check the limit again to see if the reclaim reduced the
1655 * current usage of the cgroup before giving up
1658 if (mem_cgroup_check_under_limit(mem_over_limit))
1661 /* try to avoid oom while someone is moving charge */
1662 if (mc.moving_task && current != mc.moving_task) {
1663 struct mem_cgroup *from, *to;
1664 bool do_continue = false;
1666 * There is a small race that "from" or "to" can be
1667 * freed by rmdir, so we use css_tryget().
1671 if (from && css_tryget(&from->css)) {
1672 if (mem_over_limit->use_hierarchy)
1673 do_continue = css_is_ancestor(
1675 &mem_over_limit->css);
1677 do_continue = (from == mem_over_limit);
1678 css_put(&from->css);
1680 if (!do_continue && to && css_tryget(&to->css)) {
1681 if (mem_over_limit->use_hierarchy)
1682 do_continue = css_is_ancestor(
1684 &mem_over_limit->css);
1686 do_continue = (to == mem_over_limit);
1691 prepare_to_wait(&mc.waitq, &wait,
1692 TASK_INTERRUPTIBLE);
1693 /* moving charge context might have finished. */
1696 finish_wait(&mc.waitq, &wait);
1701 if (!nr_retries--) {
1704 if (mem_cgroup_handle_oom(mem_over_limit, gfp_mask)) {
1705 nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
1708 /* When we reach here, current task is dying .*/
1713 if (csize > PAGE_SIZE)
1714 refill_stock(mem, csize - PAGE_SIZE);
1726 * Somemtimes we have to undo a charge we got by try_charge().
1727 * This function is for that and do uncharge, put css's refcnt.
1728 * gotten by try_charge().
1730 static void __mem_cgroup_cancel_charge(struct mem_cgroup *mem,
1731 unsigned long count)
1733 if (!mem_cgroup_is_root(mem)) {
1734 res_counter_uncharge(&mem->res, PAGE_SIZE * count);
1735 if (do_swap_account)
1736 res_counter_uncharge(&mem->memsw, PAGE_SIZE * count);
1737 VM_BUG_ON(test_bit(CSS_ROOT, &mem->css.flags));
1738 WARN_ON_ONCE(count > INT_MAX);
1739 __css_put(&mem->css, (int)count);
1741 /* we don't need css_put for root */
1744 static void mem_cgroup_cancel_charge(struct mem_cgroup *mem)
1746 __mem_cgroup_cancel_charge(mem, 1);
1750 * A helper function to get mem_cgroup from ID. must be called under
1751 * rcu_read_lock(). The caller must check css_is_removed() or some if
1752 * it's concern. (dropping refcnt from swap can be called against removed
1755 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
1757 struct cgroup_subsys_state *css;
1759 /* ID 0 is unused ID */
1762 css = css_lookup(&mem_cgroup_subsys, id);
1765 return container_of(css, struct mem_cgroup, css);
1768 struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
1770 struct mem_cgroup *mem = NULL;
1771 struct page_cgroup *pc;
1775 VM_BUG_ON(!PageLocked(page));
1777 pc = lookup_page_cgroup(page);
1778 lock_page_cgroup(pc);
1779 if (PageCgroupUsed(pc)) {
1780 mem = pc->mem_cgroup;
1781 if (mem && !css_tryget(&mem->css))
1783 } else if (PageSwapCache(page)) {
1784 ent.val = page_private(page);
1785 id = lookup_swap_cgroup(ent);
1787 mem = mem_cgroup_lookup(id);
1788 if (mem && !css_tryget(&mem->css))
1792 unlock_page_cgroup(pc);
1797 * commit a charge got by __mem_cgroup_try_charge() and makes page_cgroup to be
1798 * USED state. If already USED, uncharge and return.
1801 static void __mem_cgroup_commit_charge(struct mem_cgroup *mem,
1802 struct page_cgroup *pc,
1803 enum charge_type ctype)
1805 /* try_charge() can return NULL to *memcg, taking care of it. */
1809 lock_page_cgroup(pc);
1810 if (unlikely(PageCgroupUsed(pc))) {
1811 unlock_page_cgroup(pc);
1812 mem_cgroup_cancel_charge(mem);
1816 pc->mem_cgroup = mem;
1818 * We access a page_cgroup asynchronously without lock_page_cgroup().
1819 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
1820 * is accessed after testing USED bit. To make pc->mem_cgroup visible
1821 * before USED bit, we need memory barrier here.
1822 * See mem_cgroup_add_lru_list(), etc.
1826 case MEM_CGROUP_CHARGE_TYPE_CACHE:
1827 case MEM_CGROUP_CHARGE_TYPE_SHMEM:
1828 SetPageCgroupCache(pc);
1829 SetPageCgroupUsed(pc);
1831 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
1832 ClearPageCgroupCache(pc);
1833 SetPageCgroupUsed(pc);
1839 mem_cgroup_charge_statistics(mem, pc, true);
1841 unlock_page_cgroup(pc);
1843 * "charge_statistics" updated event counter. Then, check it.
1844 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
1845 * if they exceeds softlimit.
1847 memcg_check_events(mem, pc->page);
1851 * __mem_cgroup_move_account - move account of the page
1852 * @pc: page_cgroup of the page.
1853 * @from: mem_cgroup which the page is moved from.
1854 * @to: mem_cgroup which the page is moved to. @from != @to.
1855 * @uncharge: whether we should call uncharge and css_put against @from.
1857 * The caller must confirm following.
1858 * - page is not on LRU (isolate_page() is useful.)
1859 * - the pc is locked, used, and ->mem_cgroup points to @from.
1861 * This function doesn't do "charge" nor css_get to new cgroup. It should be
1862 * done by a caller(__mem_cgroup_try_charge would be usefull). If @uncharge is
1863 * true, this function does "uncharge" from old cgroup, but it doesn't if
1864 * @uncharge is false, so a caller should do "uncharge".
1867 static void __mem_cgroup_move_account(struct page_cgroup *pc,
1868 struct mem_cgroup *from, struct mem_cgroup *to, bool uncharge)
1870 VM_BUG_ON(from == to);
1871 VM_BUG_ON(PageLRU(pc->page));
1872 VM_BUG_ON(!PageCgroupLocked(pc));
1873 VM_BUG_ON(!PageCgroupUsed(pc));
1874 VM_BUG_ON(pc->mem_cgroup != from);
1876 if (PageCgroupFileMapped(pc)) {
1877 /* Update mapped_file data for mem_cgroup */
1879 __this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
1880 __this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
1883 mem_cgroup_charge_statistics(from, pc, false);
1885 /* This is not "cancel", but cancel_charge does all we need. */
1886 mem_cgroup_cancel_charge(from);
1888 /* caller should have done css_get */
1889 pc->mem_cgroup = to;
1890 mem_cgroup_charge_statistics(to, pc, true);
1892 * We charges against "to" which may not have any tasks. Then, "to"
1893 * can be under rmdir(). But in current implementation, caller of
1894 * this function is just force_empty() and move charge, so it's
1895 * garanteed that "to" is never removed. So, we don't check rmdir
1901 * check whether the @pc is valid for moving account and call
1902 * __mem_cgroup_move_account()
1904 static int mem_cgroup_move_account(struct page_cgroup *pc,
1905 struct mem_cgroup *from, struct mem_cgroup *to, bool uncharge)
1908 lock_page_cgroup(pc);
1909 if (PageCgroupUsed(pc) && pc->mem_cgroup == from) {
1910 __mem_cgroup_move_account(pc, from, to, uncharge);
1913 unlock_page_cgroup(pc);
1917 memcg_check_events(to, pc->page);
1918 memcg_check_events(from, pc->page);
1923 * move charges to its parent.
1926 static int mem_cgroup_move_parent(struct page_cgroup *pc,
1927 struct mem_cgroup *child,
1930 struct page *page = pc->page;
1931 struct cgroup *cg = child->css.cgroup;
1932 struct cgroup *pcg = cg->parent;
1933 struct mem_cgroup *parent;
1941 if (!get_page_unless_zero(page))
1943 if (isolate_lru_page(page))
1946 parent = mem_cgroup_from_cont(pcg);
1947 ret = __mem_cgroup_try_charge(NULL, gfp_mask, &parent, false);
1951 ret = mem_cgroup_move_account(pc, child, parent, true);
1953 mem_cgroup_cancel_charge(parent);
1955 putback_lru_page(page);
1963 * Charge the memory controller for page usage.
1965 * 0 if the charge was successful
1966 * < 0 if the cgroup is over its limit
1968 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
1969 gfp_t gfp_mask, enum charge_type ctype,
1970 struct mem_cgroup *memcg)
1972 struct mem_cgroup *mem;
1973 struct page_cgroup *pc;
1976 pc = lookup_page_cgroup(page);
1977 /* can happen at boot */
1983 ret = __mem_cgroup_try_charge(mm, gfp_mask, &mem, true);
1987 __mem_cgroup_commit_charge(mem, pc, ctype);
1991 int mem_cgroup_newpage_charge(struct page *page,
1992 struct mm_struct *mm, gfp_t gfp_mask)
1994 if (mem_cgroup_disabled())
1996 if (PageCompound(page))
1999 * If already mapped, we don't have to account.
2000 * If page cache, page->mapping has address_space.
2001 * But page->mapping may have out-of-use anon_vma pointer,
2002 * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
2005 if (page_mapped(page) || (page->mapping && !PageAnon(page)))
2009 return mem_cgroup_charge_common(page, mm, gfp_mask,
2010 MEM_CGROUP_CHARGE_TYPE_MAPPED, NULL);
2014 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2015 enum charge_type ctype);
2017 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
2020 struct mem_cgroup *mem = NULL;
2023 if (mem_cgroup_disabled())
2025 if (PageCompound(page))
2028 * Corner case handling. This is called from add_to_page_cache()
2029 * in usual. But some FS (shmem) precharges this page before calling it
2030 * and call add_to_page_cache() with GFP_NOWAIT.
2032 * For GFP_NOWAIT case, the page may be pre-charged before calling
2033 * add_to_page_cache(). (See shmem.c) check it here and avoid to call
2034 * charge twice. (It works but has to pay a bit larger cost.)
2035 * And when the page is SwapCache, it should take swap information
2036 * into account. This is under lock_page() now.
2038 if (!(gfp_mask & __GFP_WAIT)) {
2039 struct page_cgroup *pc;
2042 pc = lookup_page_cgroup(page);
2045 lock_page_cgroup(pc);
2046 if (PageCgroupUsed(pc)) {
2047 unlock_page_cgroup(pc);
2050 unlock_page_cgroup(pc);
2053 if (unlikely(!mm && !mem))
2056 if (page_is_file_cache(page))
2057 return mem_cgroup_charge_common(page, mm, gfp_mask,
2058 MEM_CGROUP_CHARGE_TYPE_CACHE, NULL);
2061 if (PageSwapCache(page)) {
2062 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
2064 __mem_cgroup_commit_charge_swapin(page, mem,
2065 MEM_CGROUP_CHARGE_TYPE_SHMEM);
2067 ret = mem_cgroup_charge_common(page, mm, gfp_mask,
2068 MEM_CGROUP_CHARGE_TYPE_SHMEM, mem);
2074 * While swap-in, try_charge -> commit or cancel, the page is locked.
2075 * And when try_charge() successfully returns, one refcnt to memcg without
2076 * struct page_cgroup is acquired. This refcnt will be consumed by
2077 * "commit()" or removed by "cancel()"
2079 int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
2081 gfp_t mask, struct mem_cgroup **ptr)
2083 struct mem_cgroup *mem;
2086 if (mem_cgroup_disabled())
2089 if (!do_swap_account)
2092 * A racing thread's fault, or swapoff, may have already updated
2093 * the pte, and even removed page from swap cache: in those cases
2094 * do_swap_page()'s pte_same() test will fail; but there's also a
2095 * KSM case which does need to charge the page.
2097 if (!PageSwapCache(page))
2099 mem = try_get_mem_cgroup_from_page(page);
2103 ret = __mem_cgroup_try_charge(NULL, mask, ptr, true);
2104 /* drop extra refcnt from tryget */
2110 return __mem_cgroup_try_charge(mm, mask, ptr, true);
2114 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2115 enum charge_type ctype)
2117 struct page_cgroup *pc;
2119 if (mem_cgroup_disabled())
2123 cgroup_exclude_rmdir(&ptr->css);
2124 pc = lookup_page_cgroup(page);
2125 mem_cgroup_lru_del_before_commit_swapcache(page);
2126 __mem_cgroup_commit_charge(ptr, pc, ctype);
2127 mem_cgroup_lru_add_after_commit_swapcache(page);
2129 * Now swap is on-memory. This means this page may be
2130 * counted both as mem and swap....double count.
2131 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
2132 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
2133 * may call delete_from_swap_cache() before reach here.
2135 if (do_swap_account && PageSwapCache(page)) {
2136 swp_entry_t ent = {.val = page_private(page)};
2138 struct mem_cgroup *memcg;
2140 id = swap_cgroup_record(ent, 0);
2142 memcg = mem_cgroup_lookup(id);
2145 * This recorded memcg can be obsolete one. So, avoid
2146 * calling css_tryget
2148 if (!mem_cgroup_is_root(memcg))
2149 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
2150 mem_cgroup_swap_statistics(memcg, false);
2151 mem_cgroup_put(memcg);
2156 * At swapin, we may charge account against cgroup which has no tasks.
2157 * So, rmdir()->pre_destroy() can be called while we do this charge.
2158 * In that case, we need to call pre_destroy() again. check it here.
2160 cgroup_release_and_wakeup_rmdir(&ptr->css);
2163 void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
2165 __mem_cgroup_commit_charge_swapin(page, ptr,
2166 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2169 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *mem)
2171 if (mem_cgroup_disabled())
2175 mem_cgroup_cancel_charge(mem);
2179 __do_uncharge(struct mem_cgroup *mem, const enum charge_type ctype)
2181 struct memcg_batch_info *batch = NULL;
2182 bool uncharge_memsw = true;
2183 /* If swapout, usage of swap doesn't decrease */
2184 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2185 uncharge_memsw = false;
2187 batch = ¤t->memcg_batch;
2189 * In usual, we do css_get() when we remember memcg pointer.
2190 * But in this case, we keep res->usage until end of a series of
2191 * uncharges. Then, it's ok to ignore memcg's refcnt.
2196 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
2197 * In those cases, all pages freed continously can be expected to be in
2198 * the same cgroup and we have chance to coalesce uncharges.
2199 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
2200 * because we want to do uncharge as soon as possible.
2203 if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
2204 goto direct_uncharge;
2207 * In typical case, batch->memcg == mem. This means we can
2208 * merge a series of uncharges to an uncharge of res_counter.
2209 * If not, we uncharge res_counter ony by one.
2211 if (batch->memcg != mem)
2212 goto direct_uncharge;
2213 /* remember freed charge and uncharge it later */
2214 batch->bytes += PAGE_SIZE;
2216 batch->memsw_bytes += PAGE_SIZE;
2219 res_counter_uncharge(&mem->res, PAGE_SIZE);
2221 res_counter_uncharge(&mem->memsw, PAGE_SIZE);
2222 if (unlikely(batch->memcg != mem))
2223 memcg_oom_recover(mem);
2228 * uncharge if !page_mapped(page)
2230 static struct mem_cgroup *
2231 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
2233 struct page_cgroup *pc;
2234 struct mem_cgroup *mem = NULL;
2235 struct mem_cgroup_per_zone *mz;
2237 if (mem_cgroup_disabled())
2240 if (PageSwapCache(page))
2244 * Check if our page_cgroup is valid
2246 pc = lookup_page_cgroup(page);
2247 if (unlikely(!pc || !PageCgroupUsed(pc)))
2250 lock_page_cgroup(pc);
2252 mem = pc->mem_cgroup;
2254 if (!PageCgroupUsed(pc))
2258 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
2259 case MEM_CGROUP_CHARGE_TYPE_DROP:
2260 /* See mem_cgroup_prepare_migration() */
2261 if (page_mapped(page) || PageCgroupMigration(pc))
2264 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
2265 if (!PageAnon(page)) { /* Shared memory */
2266 if (page->mapping && !page_is_file_cache(page))
2268 } else if (page_mapped(page)) /* Anon */
2275 if (!mem_cgroup_is_root(mem))
2276 __do_uncharge(mem, ctype);
2277 if (ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2278 mem_cgroup_swap_statistics(mem, true);
2279 mem_cgroup_charge_statistics(mem, pc, false);
2281 ClearPageCgroupUsed(pc);
2283 * pc->mem_cgroup is not cleared here. It will be accessed when it's
2284 * freed from LRU. This is safe because uncharged page is expected not
2285 * to be reused (freed soon). Exception is SwapCache, it's handled by
2286 * special functions.
2289 mz = page_cgroup_zoneinfo(pc);
2290 unlock_page_cgroup(pc);
2292 memcg_check_events(mem, page);
2293 /* at swapout, this memcg will be accessed to record to swap */
2294 if (ctype != MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2300 unlock_page_cgroup(pc);
2304 void mem_cgroup_uncharge_page(struct page *page)
2307 if (page_mapped(page))
2309 if (page->mapping && !PageAnon(page))
2311 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
2314 void mem_cgroup_uncharge_cache_page(struct page *page)
2316 VM_BUG_ON(page_mapped(page));
2317 VM_BUG_ON(page->mapping);
2318 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
2322 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
2323 * In that cases, pages are freed continuously and we can expect pages
2324 * are in the same memcg. All these calls itself limits the number of
2325 * pages freed at once, then uncharge_start/end() is called properly.
2326 * This may be called prural(2) times in a context,
2329 void mem_cgroup_uncharge_start(void)
2331 current->memcg_batch.do_batch++;
2332 /* We can do nest. */
2333 if (current->memcg_batch.do_batch == 1) {
2334 current->memcg_batch.memcg = NULL;
2335 current->memcg_batch.bytes = 0;
2336 current->memcg_batch.memsw_bytes = 0;
2340 void mem_cgroup_uncharge_end(void)
2342 struct memcg_batch_info *batch = ¤t->memcg_batch;
2344 if (!batch->do_batch)
2348 if (batch->do_batch) /* If stacked, do nothing. */
2354 * This "batch->memcg" is valid without any css_get/put etc...
2355 * bacause we hide charges behind us.
2358 res_counter_uncharge(&batch->memcg->res, batch->bytes);
2359 if (batch->memsw_bytes)
2360 res_counter_uncharge(&batch->memcg->memsw, batch->memsw_bytes);
2361 memcg_oom_recover(batch->memcg);
2362 /* forget this pointer (for sanity check) */
2363 batch->memcg = NULL;
2368 * called after __delete_from_swap_cache() and drop "page" account.
2369 * memcg information is recorded to swap_cgroup of "ent"
2372 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
2374 struct mem_cgroup *memcg;
2375 int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
2377 if (!swapout) /* this was a swap cache but the swap is unused ! */
2378 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
2380 memcg = __mem_cgroup_uncharge_common(page, ctype);
2382 /* record memcg information */
2383 if (do_swap_account && swapout && memcg) {
2384 swap_cgroup_record(ent, css_id(&memcg->css));
2385 mem_cgroup_get(memcg);
2387 if (swapout && memcg)
2388 css_put(&memcg->css);
2392 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
2394 * called from swap_entry_free(). remove record in swap_cgroup and
2395 * uncharge "memsw" account.
2397 void mem_cgroup_uncharge_swap(swp_entry_t ent)
2399 struct mem_cgroup *memcg;
2402 if (!do_swap_account)
2405 id = swap_cgroup_record(ent, 0);
2407 memcg = mem_cgroup_lookup(id);
2410 * We uncharge this because swap is freed.
2411 * This memcg can be obsolete one. We avoid calling css_tryget
2413 if (!mem_cgroup_is_root(memcg))
2414 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
2415 mem_cgroup_swap_statistics(memcg, false);
2416 mem_cgroup_put(memcg);
2422 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
2423 * @entry: swap entry to be moved
2424 * @from: mem_cgroup which the entry is moved from
2425 * @to: mem_cgroup which the entry is moved to
2426 * @need_fixup: whether we should fixup res_counters and refcounts.
2428 * It succeeds only when the swap_cgroup's record for this entry is the same
2429 * as the mem_cgroup's id of @from.
2431 * Returns 0 on success, -EINVAL on failure.
2433 * The caller must have charged to @to, IOW, called res_counter_charge() about
2434 * both res and memsw, and called css_get().
2436 static int mem_cgroup_move_swap_account(swp_entry_t entry,
2437 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
2439 unsigned short old_id, new_id;
2441 old_id = css_id(&from->css);
2442 new_id = css_id(&to->css);
2444 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
2445 mem_cgroup_swap_statistics(from, false);
2446 mem_cgroup_swap_statistics(to, true);
2448 * This function is only called from task migration context now.
2449 * It postpones res_counter and refcount handling till the end
2450 * of task migration(mem_cgroup_clear_mc()) for performance
2451 * improvement. But we cannot postpone mem_cgroup_get(to)
2452 * because if the process that has been moved to @to does
2453 * swap-in, the refcount of @to might be decreased to 0.
2457 if (!mem_cgroup_is_root(from))
2458 res_counter_uncharge(&from->memsw, PAGE_SIZE);
2459 mem_cgroup_put(from);
2461 * we charged both to->res and to->memsw, so we should
2464 if (!mem_cgroup_is_root(to))
2465 res_counter_uncharge(&to->res, PAGE_SIZE);
2473 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
2474 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
2481 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
2484 int mem_cgroup_prepare_migration(struct page *page,
2485 struct page *newpage, struct mem_cgroup **ptr)
2487 struct page_cgroup *pc;
2488 struct mem_cgroup *mem = NULL;
2489 enum charge_type ctype;
2492 if (mem_cgroup_disabled())
2495 pc = lookup_page_cgroup(page);
2496 lock_page_cgroup(pc);
2497 if (PageCgroupUsed(pc)) {
2498 mem = pc->mem_cgroup;
2501 * At migrating an anonymous page, its mapcount goes down
2502 * to 0 and uncharge() will be called. But, even if it's fully
2503 * unmapped, migration may fail and this page has to be
2504 * charged again. We set MIGRATION flag here and delay uncharge
2505 * until end_migration() is called
2507 * Corner Case Thinking
2509 * When the old page was mapped as Anon and it's unmap-and-freed
2510 * while migration was ongoing.
2511 * If unmap finds the old page, uncharge() of it will be delayed
2512 * until end_migration(). If unmap finds a new page, it's
2513 * uncharged when it make mapcount to be 1->0. If unmap code
2514 * finds swap_migration_entry, the new page will not be mapped
2515 * and end_migration() will find it(mapcount==0).
2518 * When the old page was mapped but migraion fails, the kernel
2519 * remaps it. A charge for it is kept by MIGRATION flag even
2520 * if mapcount goes down to 0. We can do remap successfully
2521 * without charging it again.
2524 * The "old" page is under lock_page() until the end of
2525 * migration, so, the old page itself will not be swapped-out.
2526 * If the new page is swapped out before end_migraton, our
2527 * hook to usual swap-out path will catch the event.
2530 SetPageCgroupMigration(pc);
2532 unlock_page_cgroup(pc);
2534 * If the page is not charged at this point,
2541 ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, ptr, false);
2542 css_put(&mem->css);/* drop extra refcnt */
2543 if (ret || *ptr == NULL) {
2544 if (PageAnon(page)) {
2545 lock_page_cgroup(pc);
2546 ClearPageCgroupMigration(pc);
2547 unlock_page_cgroup(pc);
2549 * The old page may be fully unmapped while we kept it.
2551 mem_cgroup_uncharge_page(page);
2556 * We charge new page before it's used/mapped. So, even if unlock_page()
2557 * is called before end_migration, we can catch all events on this new
2558 * page. In the case new page is migrated but not remapped, new page's
2559 * mapcount will be finally 0 and we call uncharge in end_migration().
2561 pc = lookup_page_cgroup(newpage);
2563 ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
2564 else if (page_is_file_cache(page))
2565 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
2567 ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
2568 __mem_cgroup_commit_charge(mem, pc, ctype);
2572 /* remove redundant charge if migration failed*/
2573 void mem_cgroup_end_migration(struct mem_cgroup *mem,
2574 struct page *oldpage, struct page *newpage)
2576 struct page *used, *unused;
2577 struct page_cgroup *pc;
2581 /* blocks rmdir() */
2582 cgroup_exclude_rmdir(&mem->css);
2583 /* at migration success, oldpage->mapping is NULL. */
2584 if (oldpage->mapping) {
2592 * We disallowed uncharge of pages under migration because mapcount
2593 * of the page goes down to zero, temporarly.
2594 * Clear the flag and check the page should be charged.
2596 pc = lookup_page_cgroup(oldpage);
2597 lock_page_cgroup(pc);
2598 ClearPageCgroupMigration(pc);
2599 unlock_page_cgroup(pc);
2601 if (unused != oldpage)
2602 pc = lookup_page_cgroup(unused);
2603 __mem_cgroup_uncharge_common(unused, MEM_CGROUP_CHARGE_TYPE_FORCE);
2605 pc = lookup_page_cgroup(used);
2607 * If a page is a file cache, radix-tree replacement is very atomic
2608 * and we can skip this check. When it was an Anon page, its mapcount
2609 * goes down to 0. But because we added MIGRATION flage, it's not
2610 * uncharged yet. There are several case but page->mapcount check
2611 * and USED bit check in mem_cgroup_uncharge_page() will do enough
2612 * check. (see prepare_charge() also)
2615 mem_cgroup_uncharge_page(used);
2617 * At migration, we may charge account against cgroup which has no
2619 * So, rmdir()->pre_destroy() can be called while we do this charge.
2620 * In that case, we need to call pre_destroy() again. check it here.
2622 cgroup_release_and_wakeup_rmdir(&mem->css);
2626 * A call to try to shrink memory usage on charge failure at shmem's swapin.
2627 * Calling hierarchical_reclaim is not enough because we should update
2628 * last_oom_jiffies to prevent pagefault_out_of_memory from invoking global OOM.
2629 * Moreover considering hierarchy, we should reclaim from the mem_over_limit,
2630 * not from the memcg which this page would be charged to.
2631 * try_charge_swapin does all of these works properly.
2633 int mem_cgroup_shmem_charge_fallback(struct page *page,
2634 struct mm_struct *mm,
2637 struct mem_cgroup *mem = NULL;
2640 if (mem_cgroup_disabled())
2643 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
2645 mem_cgroup_cancel_charge_swapin(mem); /* it does !mem check */
2650 static DEFINE_MUTEX(set_limit_mutex);
2652 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
2653 unsigned long long val)
2656 u64 memswlimit, memlimit;
2658 int children = mem_cgroup_count_children(memcg);
2659 u64 curusage, oldusage;
2663 * For keeping hierarchical_reclaim simple, how long we should retry
2664 * is depends on callers. We set our retry-count to be function
2665 * of # of children which we should visit in this loop.
2667 retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
2669 oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
2672 while (retry_count) {
2673 if (signal_pending(current)) {
2678 * Rather than hide all in some function, I do this in
2679 * open coded manner. You see what this really does.
2680 * We have to guarantee mem->res.limit < mem->memsw.limit.
2682 mutex_lock(&set_limit_mutex);
2683 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
2684 if (memswlimit < val) {
2686 mutex_unlock(&set_limit_mutex);
2690 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
2694 ret = res_counter_set_limit(&memcg->res, val);
2696 if (memswlimit == val)
2697 memcg->memsw_is_minimum = true;
2699 memcg->memsw_is_minimum = false;
2701 mutex_unlock(&set_limit_mutex);
2706 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
2707 MEM_CGROUP_RECLAIM_SHRINK);
2708 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
2709 /* Usage is reduced ? */
2710 if (curusage >= oldusage)
2713 oldusage = curusage;
2715 if (!ret && enlarge)
2716 memcg_oom_recover(memcg);
2721 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
2722 unsigned long long val)
2725 u64 memlimit, memswlimit, oldusage, curusage;
2726 int children = mem_cgroup_count_children(memcg);
2730 /* see mem_cgroup_resize_res_limit */
2731 retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
2732 oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
2733 while (retry_count) {
2734 if (signal_pending(current)) {
2739 * Rather than hide all in some function, I do this in
2740 * open coded manner. You see what this really does.
2741 * We have to guarantee mem->res.limit < mem->memsw.limit.
2743 mutex_lock(&set_limit_mutex);
2744 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
2745 if (memlimit > val) {
2747 mutex_unlock(&set_limit_mutex);
2750 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
2751 if (memswlimit < val)
2753 ret = res_counter_set_limit(&memcg->memsw, val);
2755 if (memlimit == val)
2756 memcg->memsw_is_minimum = true;
2758 memcg->memsw_is_minimum = false;
2760 mutex_unlock(&set_limit_mutex);
2765 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
2766 MEM_CGROUP_RECLAIM_NOSWAP |
2767 MEM_CGROUP_RECLAIM_SHRINK);
2768 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
2769 /* Usage is reduced ? */
2770 if (curusage >= oldusage)
2773 oldusage = curusage;
2775 if (!ret && enlarge)
2776 memcg_oom_recover(memcg);
2780 unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
2781 gfp_t gfp_mask, int nid,
2784 unsigned long nr_reclaimed = 0;
2785 struct mem_cgroup_per_zone *mz, *next_mz = NULL;
2786 unsigned long reclaimed;
2788 struct mem_cgroup_tree_per_zone *mctz;
2789 unsigned long long excess;
2794 mctz = soft_limit_tree_node_zone(nid, zid);
2796 * This loop can run a while, specially if mem_cgroup's continuously
2797 * keep exceeding their soft limit and putting the system under
2804 mz = mem_cgroup_largest_soft_limit_node(mctz);
2808 reclaimed = mem_cgroup_hierarchical_reclaim(mz->mem, zone,
2810 MEM_CGROUP_RECLAIM_SOFT);
2811 nr_reclaimed += reclaimed;
2812 spin_lock(&mctz->lock);
2815 * If we failed to reclaim anything from this memory cgroup
2816 * it is time to move on to the next cgroup
2822 * Loop until we find yet another one.
2824 * By the time we get the soft_limit lock
2825 * again, someone might have aded the
2826 * group back on the RB tree. Iterate to
2827 * make sure we get a different mem.
2828 * mem_cgroup_largest_soft_limit_node returns
2829 * NULL if no other cgroup is present on
2833 __mem_cgroup_largest_soft_limit_node(mctz);
2834 if (next_mz == mz) {
2835 css_put(&next_mz->mem->css);
2837 } else /* next_mz == NULL or other memcg */
2841 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
2842 excess = res_counter_soft_limit_excess(&mz->mem->res);
2844 * One school of thought says that we should not add
2845 * back the node to the tree if reclaim returns 0.
2846 * But our reclaim could return 0, simply because due
2847 * to priority we are exposing a smaller subset of
2848 * memory to reclaim from. Consider this as a longer
2851 /* If excess == 0, no tree ops */
2852 __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
2853 spin_unlock(&mctz->lock);
2854 css_put(&mz->mem->css);
2857 * Could not reclaim anything and there are no more
2858 * mem cgroups to try or we seem to be looping without
2859 * reclaiming anything.
2861 if (!nr_reclaimed &&
2863 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
2865 } while (!nr_reclaimed);
2867 css_put(&next_mz->mem->css);
2868 return nr_reclaimed;
2872 * This routine traverse page_cgroup in given list and drop them all.
2873 * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
2875 static int mem_cgroup_force_empty_list(struct mem_cgroup *mem,
2876 int node, int zid, enum lru_list lru)
2879 struct mem_cgroup_per_zone *mz;
2880 struct page_cgroup *pc, *busy;
2881 unsigned long flags, loop;
2882 struct list_head *list;
2885 zone = &NODE_DATA(node)->node_zones[zid];
2886 mz = mem_cgroup_zoneinfo(mem, node, zid);
2887 list = &mz->lists[lru];
2889 loop = MEM_CGROUP_ZSTAT(mz, lru);
2890 /* give some margin against EBUSY etc...*/
2895 spin_lock_irqsave(&zone->lru_lock, flags);
2896 if (list_empty(list)) {
2897 spin_unlock_irqrestore(&zone->lru_lock, flags);
2900 pc = list_entry(list->prev, struct page_cgroup, lru);
2902 list_move(&pc->lru, list);
2904 spin_unlock_irqrestore(&zone->lru_lock, flags);
2907 spin_unlock_irqrestore(&zone->lru_lock, flags);
2909 ret = mem_cgroup_move_parent(pc, mem, GFP_KERNEL);
2913 if (ret == -EBUSY || ret == -EINVAL) {
2914 /* found lock contention or "pc" is obsolete. */
2921 if (!ret && !list_empty(list))
2927 * make mem_cgroup's charge to be 0 if there is no task.
2928 * This enables deleting this mem_cgroup.
2930 static int mem_cgroup_force_empty(struct mem_cgroup *mem, bool free_all)
2933 int node, zid, shrink;
2934 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
2935 struct cgroup *cgrp = mem->css.cgroup;
2940 /* should free all ? */
2946 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
2949 if (signal_pending(current))
2951 /* This is for making all *used* pages to be on LRU. */
2952 lru_add_drain_all();
2953 drain_all_stock_sync();
2955 for_each_node_state(node, N_HIGH_MEMORY) {
2956 for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
2959 ret = mem_cgroup_force_empty_list(mem,
2968 memcg_oom_recover(mem);
2969 /* it seems parent cgroup doesn't have enough mem */
2973 /* "ret" should also be checked to ensure all lists are empty. */
2974 } while (mem->res.usage > 0 || ret);
2980 /* returns EBUSY if there is a task or if we come here twice. */
2981 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
2985 /* we call try-to-free pages for make this cgroup empty */
2986 lru_add_drain_all();
2987 /* try to free all pages in this cgroup */
2989 while (nr_retries && mem->res.usage > 0) {
2992 if (signal_pending(current)) {
2996 progress = try_to_free_mem_cgroup_pages(mem, GFP_KERNEL,
2997 false, get_swappiness(mem));
3000 /* maybe some writeback is necessary */
3001 congestion_wait(BLK_RW_ASYNC, HZ/10);
3006 /* try move_account...there may be some *locked* pages. */
3010 int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
3012 return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
3016 static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
3018 return mem_cgroup_from_cont(cont)->use_hierarchy;
3021 static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
3025 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
3026 struct cgroup *parent = cont->parent;
3027 struct mem_cgroup *parent_mem = NULL;
3030 parent_mem = mem_cgroup_from_cont(parent);
3034 * If parent's use_hierarchy is set, we can't make any modifications
3035 * in the child subtrees. If it is unset, then the change can
3036 * occur, provided the current cgroup has no children.
3038 * For the root cgroup, parent_mem is NULL, we allow value to be
3039 * set if there are no children.
3041 if ((!parent_mem || !parent_mem->use_hierarchy) &&
3042 (val == 1 || val == 0)) {
3043 if (list_empty(&cont->children))
3044 mem->use_hierarchy = val;
3054 struct mem_cgroup_idx_data {
3056 enum mem_cgroup_stat_index idx;
3060 mem_cgroup_get_idx_stat(struct mem_cgroup *mem, void *data)
3062 struct mem_cgroup_idx_data *d = data;
3063 d->val += mem_cgroup_read_stat(mem, d->idx);
3068 mem_cgroup_get_recursive_idx_stat(struct mem_cgroup *mem,
3069 enum mem_cgroup_stat_index idx, s64 *val)
3071 struct mem_cgroup_idx_data d;
3074 mem_cgroup_walk_tree(mem, &d, mem_cgroup_get_idx_stat);
3078 static inline u64 mem_cgroup_usage(struct mem_cgroup *mem, bool swap)
3082 if (!mem_cgroup_is_root(mem)) {
3084 return res_counter_read_u64(&mem->res, RES_USAGE);
3086 return res_counter_read_u64(&mem->memsw, RES_USAGE);
3089 mem_cgroup_get_recursive_idx_stat(mem, MEM_CGROUP_STAT_CACHE, &idx_val);
3091 mem_cgroup_get_recursive_idx_stat(mem, MEM_CGROUP_STAT_RSS, &idx_val);
3095 mem_cgroup_get_recursive_idx_stat(mem,
3096 MEM_CGROUP_STAT_SWAPOUT, &idx_val);
3100 return val << PAGE_SHIFT;
3103 static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
3105 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
3109 type = MEMFILE_TYPE(cft->private);
3110 name = MEMFILE_ATTR(cft->private);
3113 if (name == RES_USAGE)
3114 val = mem_cgroup_usage(mem, false);
3116 val = res_counter_read_u64(&mem->res, name);
3119 if (name == RES_USAGE)
3120 val = mem_cgroup_usage(mem, true);
3122 val = res_counter_read_u64(&mem->memsw, name);
3131 * The user of this function is...
3134 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
3137 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3139 unsigned long long val;
3142 type = MEMFILE_TYPE(cft->private);
3143 name = MEMFILE_ATTR(cft->private);
3146 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3150 /* This function does all necessary parse...reuse it */
3151 ret = res_counter_memparse_write_strategy(buffer, &val);
3155 ret = mem_cgroup_resize_limit(memcg, val);
3157 ret = mem_cgroup_resize_memsw_limit(memcg, val);
3159 case RES_SOFT_LIMIT:
3160 ret = res_counter_memparse_write_strategy(buffer, &val);
3164 * For memsw, soft limits are hard to implement in terms
3165 * of semantics, for now, we support soft limits for
3166 * control without swap
3169 ret = res_counter_set_soft_limit(&memcg->res, val);
3174 ret = -EINVAL; /* should be BUG() ? */
3180 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
3181 unsigned long long *mem_limit, unsigned long long *memsw_limit)
3183 struct cgroup *cgroup;
3184 unsigned long long min_limit, min_memsw_limit, tmp;
3186 min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3187 min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3188 cgroup = memcg->css.cgroup;
3189 if (!memcg->use_hierarchy)
3192 while (cgroup->parent) {
3193 cgroup = cgroup->parent;
3194 memcg = mem_cgroup_from_cont(cgroup);
3195 if (!memcg->use_hierarchy)
3197 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
3198 min_limit = min(min_limit, tmp);
3199 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3200 min_memsw_limit = min(min_memsw_limit, tmp);
3203 *mem_limit = min_limit;
3204 *memsw_limit = min_memsw_limit;
3208 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
3210 struct mem_cgroup *mem;
3213 mem = mem_cgroup_from_cont(cont);
3214 type = MEMFILE_TYPE(event);
3215 name = MEMFILE_ATTR(event);
3219 res_counter_reset_max(&mem->res);
3221 res_counter_reset_max(&mem->memsw);
3225 res_counter_reset_failcnt(&mem->res);
3227 res_counter_reset_failcnt(&mem->memsw);
3234 static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
3237 return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
3241 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
3242 struct cftype *cft, u64 val)
3244 struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
3246 if (val >= (1 << NR_MOVE_TYPE))
3249 * We check this value several times in both in can_attach() and
3250 * attach(), so we need cgroup lock to prevent this value from being
3254 mem->move_charge_at_immigrate = val;
3260 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
3261 struct cftype *cft, u64 val)
3268 /* For read statistics */
3284 struct mcs_total_stat {
3285 s64 stat[NR_MCS_STAT];
3291 } memcg_stat_strings[NR_MCS_STAT] = {
3292 {"cache", "total_cache"},
3293 {"rss", "total_rss"},
3294 {"mapped_file", "total_mapped_file"},
3295 {"pgpgin", "total_pgpgin"},
3296 {"pgpgout", "total_pgpgout"},
3297 {"swap", "total_swap"},
3298 {"inactive_anon", "total_inactive_anon"},
3299 {"active_anon", "total_active_anon"},
3300 {"inactive_file", "total_inactive_file"},
3301 {"active_file", "total_active_file"},
3302 {"unevictable", "total_unevictable"}
3306 static int mem_cgroup_get_local_stat(struct mem_cgroup *mem, void *data)
3308 struct mcs_total_stat *s = data;
3312 val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_CACHE);
3313 s->stat[MCS_CACHE] += val * PAGE_SIZE;
3314 val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_RSS);
3315 s->stat[MCS_RSS] += val * PAGE_SIZE;
3316 val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_FILE_MAPPED);
3317 s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE;
3318 val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_PGPGIN_COUNT);
3319 s->stat[MCS_PGPGIN] += val;
3320 val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_PGPGOUT_COUNT);
3321 s->stat[MCS_PGPGOUT] += val;
3322 if (do_swap_account) {
3323 val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_SWAPOUT);
3324 s->stat[MCS_SWAP] += val * PAGE_SIZE;
3328 val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_ANON);
3329 s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
3330 val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_ANON);
3331 s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
3332 val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_FILE);
3333 s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
3334 val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_FILE);
3335 s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
3336 val = mem_cgroup_get_local_zonestat(mem, LRU_UNEVICTABLE);
3337 s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
3342 mem_cgroup_get_total_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
3344 mem_cgroup_walk_tree(mem, s, mem_cgroup_get_local_stat);
3347 static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
3348 struct cgroup_map_cb *cb)
3350 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
3351 struct mcs_total_stat mystat;
3354 memset(&mystat, 0, sizeof(mystat));
3355 mem_cgroup_get_local_stat(mem_cont, &mystat);
3357 for (i = 0; i < NR_MCS_STAT; i++) {
3358 if (i == MCS_SWAP && !do_swap_account)
3360 cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
3363 /* Hierarchical information */
3365 unsigned long long limit, memsw_limit;
3366 memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
3367 cb->fill(cb, "hierarchical_memory_limit", limit);
3368 if (do_swap_account)
3369 cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
3372 memset(&mystat, 0, sizeof(mystat));
3373 mem_cgroup_get_total_stat(mem_cont, &mystat);
3374 for (i = 0; i < NR_MCS_STAT; i++) {
3375 if (i == MCS_SWAP && !do_swap_account)
3377 cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
3380 #ifdef CONFIG_DEBUG_VM
3381 cb->fill(cb, "inactive_ratio", calc_inactive_ratio(mem_cont, NULL));
3385 struct mem_cgroup_per_zone *mz;
3386 unsigned long recent_rotated[2] = {0, 0};
3387 unsigned long recent_scanned[2] = {0, 0};
3389 for_each_online_node(nid)
3390 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
3391 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
3393 recent_rotated[0] +=
3394 mz->reclaim_stat.recent_rotated[0];
3395 recent_rotated[1] +=
3396 mz->reclaim_stat.recent_rotated[1];
3397 recent_scanned[0] +=
3398 mz->reclaim_stat.recent_scanned[0];
3399 recent_scanned[1] +=
3400 mz->reclaim_stat.recent_scanned[1];
3402 cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
3403 cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
3404 cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
3405 cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
3412 static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
3414 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3416 return get_swappiness(memcg);
3419 static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
3422 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3423 struct mem_cgroup *parent;
3428 if (cgrp->parent == NULL)
3431 parent = mem_cgroup_from_cont(cgrp->parent);
3435 /* If under hierarchy, only empty-root can set this value */
3436 if ((parent->use_hierarchy) ||
3437 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
3442 spin_lock(&memcg->reclaim_param_lock);
3443 memcg->swappiness = val;
3444 spin_unlock(&memcg->reclaim_param_lock);
3451 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
3453 struct mem_cgroup_threshold_ary *t;
3459 t = rcu_dereference(memcg->thresholds.primary);
3461 t = rcu_dereference(memcg->memsw_thresholds.primary);
3466 usage = mem_cgroup_usage(memcg, swap);
3469 * current_threshold points to threshold just below usage.
3470 * If it's not true, a threshold was crossed after last
3471 * call of __mem_cgroup_threshold().
3473 i = t->current_threshold;
3476 * Iterate backward over array of thresholds starting from
3477 * current_threshold and check if a threshold is crossed.
3478 * If none of thresholds below usage is crossed, we read
3479 * only one element of the array here.
3481 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
3482 eventfd_signal(t->entries[i].eventfd, 1);
3484 /* i = current_threshold + 1 */
3488 * Iterate forward over array of thresholds starting from
3489 * current_threshold+1 and check if a threshold is crossed.
3490 * If none of thresholds above usage is crossed, we read
3491 * only one element of the array here.
3493 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
3494 eventfd_signal(t->entries[i].eventfd, 1);
3496 /* Update current_threshold */
3497 t->current_threshold = i - 1;
3502 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
3504 __mem_cgroup_threshold(memcg, false);
3505 if (do_swap_account)
3506 __mem_cgroup_threshold(memcg, true);
3509 static int compare_thresholds(const void *a, const void *b)
3511 const struct mem_cgroup_threshold *_a = a;
3512 const struct mem_cgroup_threshold *_b = b;
3514 return _a->threshold - _b->threshold;
3517 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *mem, void *data)
3519 struct mem_cgroup_eventfd_list *ev;
3521 list_for_each_entry(ev, &mem->oom_notify, list)
3522 eventfd_signal(ev->eventfd, 1);
3526 static void mem_cgroup_oom_notify(struct mem_cgroup *mem)
3528 mem_cgroup_walk_tree(mem, NULL, mem_cgroup_oom_notify_cb);
3531 static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
3532 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
3534 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3535 struct mem_cgroup_thresholds *thresholds;
3536 struct mem_cgroup_threshold_ary *new;
3537 int type = MEMFILE_TYPE(cft->private);
3538 u64 threshold, usage;
3541 ret = res_counter_memparse_write_strategy(args, &threshold);
3545 mutex_lock(&memcg->thresholds_lock);
3548 thresholds = &memcg->thresholds;
3549 else if (type == _MEMSWAP)
3550 thresholds = &memcg->memsw_thresholds;
3554 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
3556 /* Check if a threshold crossed before adding a new one */
3557 if (thresholds->primary)
3558 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
3560 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
3562 /* Allocate memory for new array of thresholds */
3563 new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
3571 /* Copy thresholds (if any) to new array */
3572 if (thresholds->primary) {
3573 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
3574 sizeof(struct mem_cgroup_threshold));
3577 /* Add new threshold */
3578 new->entries[size - 1].eventfd = eventfd;
3579 new->entries[size - 1].threshold = threshold;
3581 /* Sort thresholds. Registering of new threshold isn't time-critical */
3582 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
3583 compare_thresholds, NULL);
3585 /* Find current threshold */
3586 new->current_threshold = -1;
3587 for (i = 0; i < size; i++) {
3588 if (new->entries[i].threshold < usage) {
3590 * new->current_threshold will not be used until
3591 * rcu_assign_pointer(), so it's safe to increment
3594 ++new->current_threshold;
3598 /* Free old spare buffer and save old primary buffer as spare */
3599 kfree(thresholds->spare);
3600 thresholds->spare = thresholds->primary;
3602 rcu_assign_pointer(thresholds->primary, new);
3604 /* To be sure that nobody uses thresholds */
3608 mutex_unlock(&memcg->thresholds_lock);
3613 static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
3614 struct cftype *cft, struct eventfd_ctx *eventfd)
3616 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3617 struct mem_cgroup_thresholds *thresholds;
3618 struct mem_cgroup_threshold_ary *new;
3619 int type = MEMFILE_TYPE(cft->private);
3623 mutex_lock(&memcg->thresholds_lock);
3625 thresholds = &memcg->thresholds;
3626 else if (type == _MEMSWAP)
3627 thresholds = &memcg->memsw_thresholds;
3632 * Something went wrong if we trying to unregister a threshold
3633 * if we don't have thresholds
3635 BUG_ON(!thresholds);
3637 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
3639 /* Check if a threshold crossed before removing */
3640 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
3642 /* Calculate new number of threshold */
3644 for (i = 0; i < thresholds->primary->size; i++) {
3645 if (thresholds->primary->entries[i].eventfd != eventfd)
3649 new = thresholds->spare;
3651 /* Set thresholds array to NULL if we don't have thresholds */
3660 /* Copy thresholds and find current threshold */
3661 new->current_threshold = -1;
3662 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
3663 if (thresholds->primary->entries[i].eventfd == eventfd)
3666 new->entries[j] = thresholds->primary->entries[i];
3667 if (new->entries[j].threshold < usage) {
3669 * new->current_threshold will not be used
3670 * until rcu_assign_pointer(), so it's safe to increment
3673 ++new->current_threshold;
3679 /* Swap primary and spare array */
3680 thresholds->spare = thresholds->primary;
3681 rcu_assign_pointer(thresholds->primary, new);
3683 /* To be sure that nobody uses thresholds */
3686 mutex_unlock(&memcg->thresholds_lock);
3689 static int mem_cgroup_oom_register_event(struct cgroup *cgrp,
3690 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
3692 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3693 struct mem_cgroup_eventfd_list *event;
3694 int type = MEMFILE_TYPE(cft->private);
3696 BUG_ON(type != _OOM_TYPE);
3697 event = kmalloc(sizeof(*event), GFP_KERNEL);
3701 mutex_lock(&memcg_oom_mutex);
3703 event->eventfd = eventfd;
3704 list_add(&event->list, &memcg->oom_notify);
3706 /* already in OOM ? */
3707 if (atomic_read(&memcg->oom_lock))
3708 eventfd_signal(eventfd, 1);
3709 mutex_unlock(&memcg_oom_mutex);
3714 static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
3715 struct cftype *cft, struct eventfd_ctx *eventfd)
3717 struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
3718 struct mem_cgroup_eventfd_list *ev, *tmp;
3719 int type = MEMFILE_TYPE(cft->private);
3721 BUG_ON(type != _OOM_TYPE);
3723 mutex_lock(&memcg_oom_mutex);
3725 list_for_each_entry_safe(ev, tmp, &mem->oom_notify, list) {
3726 if (ev->eventfd == eventfd) {
3727 list_del(&ev->list);
3732 mutex_unlock(&memcg_oom_mutex);
3735 static int mem_cgroup_oom_control_read(struct cgroup *cgrp,
3736 struct cftype *cft, struct cgroup_map_cb *cb)
3738 struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
3740 cb->fill(cb, "oom_kill_disable", mem->oom_kill_disable);
3742 if (atomic_read(&mem->oom_lock))
3743 cb->fill(cb, "under_oom", 1);
3745 cb->fill(cb, "under_oom", 0);
3751 static int mem_cgroup_oom_control_write(struct cgroup *cgrp,
3752 struct cftype *cft, u64 val)
3754 struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
3755 struct mem_cgroup *parent;
3757 /* cannot set to root cgroup and only 0 and 1 are allowed */
3758 if (!cgrp->parent || !((val == 0) || (val == 1)))
3761 parent = mem_cgroup_from_cont(cgrp->parent);
3764 /* oom-kill-disable is a flag for subhierarchy. */
3765 if ((parent->use_hierarchy) ||
3766 (mem->use_hierarchy && !list_empty(&cgrp->children))) {
3770 mem->oom_kill_disable = val;
3772 memcg_oom_recover(mem);
3777 static struct cftype mem_cgroup_files[] = {
3779 .name = "usage_in_bytes",
3780 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
3781 .read_u64 = mem_cgroup_read,
3782 .register_event = mem_cgroup_usage_register_event,
3783 .unregister_event = mem_cgroup_usage_unregister_event,
3786 .name = "max_usage_in_bytes",
3787 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
3788 .trigger = mem_cgroup_reset,
3789 .read_u64 = mem_cgroup_read,
3792 .name = "limit_in_bytes",
3793 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
3794 .write_string = mem_cgroup_write,
3795 .read_u64 = mem_cgroup_read,
3798 .name = "soft_limit_in_bytes",
3799 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
3800 .write_string = mem_cgroup_write,
3801 .read_u64 = mem_cgroup_read,
3805 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
3806 .trigger = mem_cgroup_reset,
3807 .read_u64 = mem_cgroup_read,
3811 .read_map = mem_control_stat_show,
3814 .name = "force_empty",
3815 .trigger = mem_cgroup_force_empty_write,
3818 .name = "use_hierarchy",
3819 .write_u64 = mem_cgroup_hierarchy_write,
3820 .read_u64 = mem_cgroup_hierarchy_read,
3823 .name = "swappiness",
3824 .read_u64 = mem_cgroup_swappiness_read,
3825 .write_u64 = mem_cgroup_swappiness_write,
3828 .name = "move_charge_at_immigrate",
3829 .read_u64 = mem_cgroup_move_charge_read,
3830 .write_u64 = mem_cgroup_move_charge_write,
3833 .name = "oom_control",
3834 .read_map = mem_cgroup_oom_control_read,
3835 .write_u64 = mem_cgroup_oom_control_write,
3836 .register_event = mem_cgroup_oom_register_event,
3837 .unregister_event = mem_cgroup_oom_unregister_event,
3838 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
3842 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3843 static struct cftype memsw_cgroup_files[] = {
3845 .name = "memsw.usage_in_bytes",
3846 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
3847 .read_u64 = mem_cgroup_read,
3848 .register_event = mem_cgroup_usage_register_event,
3849 .unregister_event = mem_cgroup_usage_unregister_event,
3852 .name = "memsw.max_usage_in_bytes",
3853 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
3854 .trigger = mem_cgroup_reset,
3855 .read_u64 = mem_cgroup_read,
3858 .name = "memsw.limit_in_bytes",
3859 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
3860 .write_string = mem_cgroup_write,
3861 .read_u64 = mem_cgroup_read,
3864 .name = "memsw.failcnt",
3865 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
3866 .trigger = mem_cgroup_reset,
3867 .read_u64 = mem_cgroup_read,
3871 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
3873 if (!do_swap_account)
3875 return cgroup_add_files(cont, ss, memsw_cgroup_files,
3876 ARRAY_SIZE(memsw_cgroup_files));
3879 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
3885 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
3887 struct mem_cgroup_per_node *pn;
3888 struct mem_cgroup_per_zone *mz;
3890 int zone, tmp = node;
3892 * This routine is called against possible nodes.
3893 * But it's BUG to call kmalloc() against offline node.
3895 * TODO: this routine can waste much memory for nodes which will
3896 * never be onlined. It's better to use memory hotplug callback
3899 if (!node_state(node, N_NORMAL_MEMORY))
3901 pn = kmalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
3905 mem->info.nodeinfo[node] = pn;
3906 memset(pn, 0, sizeof(*pn));
3908 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3909 mz = &pn->zoneinfo[zone];
3911 INIT_LIST_HEAD(&mz->lists[l]);
3912 mz->usage_in_excess = 0;
3913 mz->on_tree = false;
3919 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
3921 kfree(mem->info.nodeinfo[node]);
3924 static struct mem_cgroup *mem_cgroup_alloc(void)
3926 struct mem_cgroup *mem;
3927 int size = sizeof(struct mem_cgroup);
3929 /* Can be very big if MAX_NUMNODES is very big */
3930 if (size < PAGE_SIZE)
3931 mem = kmalloc(size, GFP_KERNEL);
3933 mem = vmalloc(size);
3938 memset(mem, 0, size);
3939 mem->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
3941 if (size < PAGE_SIZE)
3951 * At destroying mem_cgroup, references from swap_cgroup can remain.
3952 * (scanning all at force_empty is too costly...)
3954 * Instead of clearing all references at force_empty, we remember
3955 * the number of reference from swap_cgroup and free mem_cgroup when
3956 * it goes down to 0.
3958 * Removal of cgroup itself succeeds regardless of refs from swap.
3961 static void __mem_cgroup_free(struct mem_cgroup *mem)
3965 mem_cgroup_remove_from_trees(mem);
3966 free_css_id(&mem_cgroup_subsys, &mem->css);
3968 for_each_node_state(node, N_POSSIBLE)
3969 free_mem_cgroup_per_zone_info(mem, node);
3971 free_percpu(mem->stat);
3972 if (sizeof(struct mem_cgroup) < PAGE_SIZE)
3978 static void mem_cgroup_get(struct mem_cgroup *mem)
3980 atomic_inc(&mem->refcnt);
3983 static void __mem_cgroup_put(struct mem_cgroup *mem, int count)
3985 if (atomic_sub_and_test(count, &mem->refcnt)) {
3986 struct mem_cgroup *parent = parent_mem_cgroup(mem);
3987 __mem_cgroup_free(mem);
3989 mem_cgroup_put(parent);
3993 static void mem_cgroup_put(struct mem_cgroup *mem)
3995 __mem_cgroup_put(mem, 1);
3999 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
4001 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem)
4003 if (!mem->res.parent)
4005 return mem_cgroup_from_res_counter(mem->res.parent, res);
4008 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4009 static void __init enable_swap_cgroup(void)
4011 if (!mem_cgroup_disabled() && really_do_swap_account)
4012 do_swap_account = 1;
4015 static void __init enable_swap_cgroup(void)
4020 static int mem_cgroup_soft_limit_tree_init(void)
4022 struct mem_cgroup_tree_per_node *rtpn;
4023 struct mem_cgroup_tree_per_zone *rtpz;
4024 int tmp, node, zone;
4026 for_each_node_state(node, N_POSSIBLE) {
4028 if (!node_state(node, N_NORMAL_MEMORY))
4030 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
4034 soft_limit_tree.rb_tree_per_node[node] = rtpn;
4036 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4037 rtpz = &rtpn->rb_tree_per_zone[zone];
4038 rtpz->rb_root = RB_ROOT;
4039 spin_lock_init(&rtpz->lock);
4045 static struct cgroup_subsys_state * __ref
4046 mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
4048 struct mem_cgroup *mem, *parent;
4049 long error = -ENOMEM;
4052 mem = mem_cgroup_alloc();
4054 return ERR_PTR(error);
4056 for_each_node_state(node, N_POSSIBLE)
4057 if (alloc_mem_cgroup_per_zone_info(mem, node))
4061 if (cont->parent == NULL) {
4063 enable_swap_cgroup();
4065 root_mem_cgroup = mem;
4066 if (mem_cgroup_soft_limit_tree_init())
4068 for_each_possible_cpu(cpu) {
4069 struct memcg_stock_pcp *stock =
4070 &per_cpu(memcg_stock, cpu);
4071 INIT_WORK(&stock->work, drain_local_stock);
4073 hotcpu_notifier(memcg_stock_cpu_callback, 0);
4075 parent = mem_cgroup_from_cont(cont->parent);
4076 mem->use_hierarchy = parent->use_hierarchy;
4077 mem->oom_kill_disable = parent->oom_kill_disable;
4080 if (parent && parent->use_hierarchy) {
4081 res_counter_init(&mem->res, &parent->res);
4082 res_counter_init(&mem->memsw, &parent->memsw);
4084 * We increment refcnt of the parent to ensure that we can
4085 * safely access it on res_counter_charge/uncharge.
4086 * This refcnt will be decremented when freeing this
4087 * mem_cgroup(see mem_cgroup_put).
4089 mem_cgroup_get(parent);
4091 res_counter_init(&mem->res, NULL);
4092 res_counter_init(&mem->memsw, NULL);
4094 mem->last_scanned_child = 0;
4095 spin_lock_init(&mem->reclaim_param_lock);
4096 INIT_LIST_HEAD(&mem->oom_notify);
4099 mem->swappiness = get_swappiness(parent);
4100 atomic_set(&mem->refcnt, 1);
4101 mem->move_charge_at_immigrate = 0;
4102 mutex_init(&mem->thresholds_lock);
4105 __mem_cgroup_free(mem);
4106 root_mem_cgroup = NULL;
4107 return ERR_PTR(error);
4110 static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
4111 struct cgroup *cont)
4113 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
4115 return mem_cgroup_force_empty(mem, false);
4118 static void mem_cgroup_destroy(struct cgroup_subsys *ss,
4119 struct cgroup *cont)
4121 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
4123 mem_cgroup_put(mem);
4126 static int mem_cgroup_populate(struct cgroup_subsys *ss,
4127 struct cgroup *cont)
4131 ret = cgroup_add_files(cont, ss, mem_cgroup_files,
4132 ARRAY_SIZE(mem_cgroup_files));
4135 ret = register_memsw_files(cont, ss);
4140 /* Handlers for move charge at task migration. */
4141 #define PRECHARGE_COUNT_AT_ONCE 256
4142 static int mem_cgroup_do_precharge(unsigned long count)
4145 int batch_count = PRECHARGE_COUNT_AT_ONCE;
4146 struct mem_cgroup *mem = mc.to;
4148 if (mem_cgroup_is_root(mem)) {
4149 mc.precharge += count;
4150 /* we don't need css_get for root */
4153 /* try to charge at once */
4155 struct res_counter *dummy;
4157 * "mem" cannot be under rmdir() because we've already checked
4158 * by cgroup_lock_live_cgroup() that it is not removed and we
4159 * are still under the same cgroup_mutex. So we can postpone
4162 if (res_counter_charge(&mem->res, PAGE_SIZE * count, &dummy))
4164 if (do_swap_account && res_counter_charge(&mem->memsw,
4165 PAGE_SIZE * count, &dummy)) {
4166 res_counter_uncharge(&mem->res, PAGE_SIZE * count);
4169 mc.precharge += count;
4170 VM_BUG_ON(test_bit(CSS_ROOT, &mem->css.flags));
4171 WARN_ON_ONCE(count > INT_MAX);
4172 __css_get(&mem->css, (int)count);
4176 /* fall back to one by one charge */
4178 if (signal_pending(current)) {
4182 if (!batch_count--) {
4183 batch_count = PRECHARGE_COUNT_AT_ONCE;
4186 ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, &mem, false);
4188 /* mem_cgroup_clear_mc() will do uncharge later */
4196 * is_target_pte_for_mc - check a pte whether it is valid for move charge
4197 * @vma: the vma the pte to be checked belongs
4198 * @addr: the address corresponding to the pte to be checked
4199 * @ptent: the pte to be checked
4200 * @target: the pointer the target page or swap ent will be stored(can be NULL)
4203 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
4204 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
4205 * move charge. if @target is not NULL, the page is stored in target->page
4206 * with extra refcnt got(Callers should handle it).
4207 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
4208 * target for charge migration. if @target is not NULL, the entry is stored
4211 * Called with pte lock held.
4218 enum mc_target_type {
4219 MC_TARGET_NONE, /* not used */
4224 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
4225 unsigned long addr, pte_t ptent)
4227 struct page *page = vm_normal_page(vma, addr, ptent);
4229 if (!page || !page_mapped(page))
4231 if (PageAnon(page)) {
4232 /* we don't move shared anon */
4233 if (!move_anon() || page_mapcount(page) > 2)
4235 } else if (!move_file())
4236 /* we ignore mapcount for file pages */
4238 if (!get_page_unless_zero(page))
4244 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
4245 unsigned long addr, pte_t ptent, swp_entry_t *entry)
4248 struct page *page = NULL;
4249 swp_entry_t ent = pte_to_swp_entry(ptent);
4251 if (!move_anon() || non_swap_entry(ent))
4253 usage_count = mem_cgroup_count_swap_user(ent, &page);
4254 if (usage_count > 1) { /* we don't move shared anon */
4259 if (do_swap_account)
4260 entry->val = ent.val;
4265 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
4266 unsigned long addr, pte_t ptent, swp_entry_t *entry)
4268 struct page *page = NULL;
4269 struct inode *inode;
4270 struct address_space *mapping;
4273 if (!vma->vm_file) /* anonymous vma */
4278 inode = vma->vm_file->f_path.dentry->d_inode;
4279 mapping = vma->vm_file->f_mapping;
4280 if (pte_none(ptent))
4281 pgoff = linear_page_index(vma, addr);
4282 else /* pte_file(ptent) is true */
4283 pgoff = pte_to_pgoff(ptent);
4285 /* page is moved even if it's not RSS of this task(page-faulted). */
4286 if (!mapping_cap_swap_backed(mapping)) { /* normal file */
4287 page = find_get_page(mapping, pgoff);
4288 } else { /* shmem/tmpfs file. we should take account of swap too. */
4290 mem_cgroup_get_shmem_target(inode, pgoff, &page, &ent);
4291 if (do_swap_account)
4292 entry->val = ent.val;
4298 static int is_target_pte_for_mc(struct vm_area_struct *vma,
4299 unsigned long addr, pte_t ptent, union mc_target *target)
4301 struct page *page = NULL;
4302 struct page_cgroup *pc;
4304 swp_entry_t ent = { .val = 0 };
4306 if (pte_present(ptent))
4307 page = mc_handle_present_pte(vma, addr, ptent);
4308 else if (is_swap_pte(ptent))
4309 page = mc_handle_swap_pte(vma, addr, ptent, &ent);
4310 else if (pte_none(ptent) || pte_file(ptent))
4311 page = mc_handle_file_pte(vma, addr, ptent, &ent);
4313 if (!page && !ent.val)
4316 pc = lookup_page_cgroup(page);
4318 * Do only loose check w/o page_cgroup lock.
4319 * mem_cgroup_move_account() checks the pc is valid or not under
4322 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
4323 ret = MC_TARGET_PAGE;
4325 target->page = page;
4327 if (!ret || !target)
4330 /* There is a swap entry and a page doesn't exist or isn't charged */
4331 if (ent.val && !ret &&
4332 css_id(&mc.from->css) == lookup_swap_cgroup(ent)) {
4333 ret = MC_TARGET_SWAP;
4340 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
4341 unsigned long addr, unsigned long end,
4342 struct mm_walk *walk)
4344 struct vm_area_struct *vma = walk->private;
4348 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
4349 for (; addr != end; pte++, addr += PAGE_SIZE)
4350 if (is_target_pte_for_mc(vma, addr, *pte, NULL))
4351 mc.precharge++; /* increment precharge temporarily */
4352 pte_unmap_unlock(pte - 1, ptl);
4358 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
4360 unsigned long precharge;
4361 struct vm_area_struct *vma;
4363 down_read(&mm->mmap_sem);
4364 for (vma = mm->mmap; vma; vma = vma->vm_next) {
4365 struct mm_walk mem_cgroup_count_precharge_walk = {
4366 .pmd_entry = mem_cgroup_count_precharge_pte_range,
4370 if (is_vm_hugetlb_page(vma))
4372 walk_page_range(vma->vm_start, vma->vm_end,
4373 &mem_cgroup_count_precharge_walk);
4375 up_read(&mm->mmap_sem);
4377 precharge = mc.precharge;
4383 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
4385 return mem_cgroup_do_precharge(mem_cgroup_count_precharge(mm));
4388 static void mem_cgroup_clear_mc(void)
4390 /* we must uncharge all the leftover precharges from mc.to */
4392 __mem_cgroup_cancel_charge(mc.to, mc.precharge);
4394 memcg_oom_recover(mc.to);
4397 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
4398 * we must uncharge here.
4400 if (mc.moved_charge) {
4401 __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
4402 mc.moved_charge = 0;
4403 memcg_oom_recover(mc.from);
4405 /* we must fixup refcnts and charges */
4406 if (mc.moved_swap) {
4407 WARN_ON_ONCE(mc.moved_swap > INT_MAX);
4408 /* uncharge swap account from the old cgroup */
4409 if (!mem_cgroup_is_root(mc.from))
4410 res_counter_uncharge(&mc.from->memsw,
4411 PAGE_SIZE * mc.moved_swap);
4412 __mem_cgroup_put(mc.from, mc.moved_swap);
4414 if (!mem_cgroup_is_root(mc.to)) {
4416 * we charged both to->res and to->memsw, so we should
4419 res_counter_uncharge(&mc.to->res,
4420 PAGE_SIZE * mc.moved_swap);
4421 VM_BUG_ON(test_bit(CSS_ROOT, &mc.to->css.flags));
4422 __css_put(&mc.to->css, mc.moved_swap);
4424 /* we've already done mem_cgroup_get(mc.to) */
4430 mc.moving_task = NULL;
4431 wake_up_all(&mc.waitq);
4434 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
4435 struct cgroup *cgroup,
4436 struct task_struct *p,
4440 struct mem_cgroup *mem = mem_cgroup_from_cont(cgroup);
4442 if (mem->move_charge_at_immigrate) {
4443 struct mm_struct *mm;
4444 struct mem_cgroup *from = mem_cgroup_from_task(p);
4446 VM_BUG_ON(from == mem);
4448 mm = get_task_mm(p);
4451 /* We move charges only when we move a owner of the mm */
4452 if (mm->owner == p) {
4455 VM_BUG_ON(mc.precharge);
4456 VM_BUG_ON(mc.moved_charge);
4457 VM_BUG_ON(mc.moved_swap);
4458 VM_BUG_ON(mc.moving_task);
4462 mc.moved_charge = 0;
4464 mc.moving_task = current;
4466 ret = mem_cgroup_precharge_mc(mm);
4468 mem_cgroup_clear_mc();
4475 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
4476 struct cgroup *cgroup,
4477 struct task_struct *p,
4480 mem_cgroup_clear_mc();
4483 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
4484 unsigned long addr, unsigned long end,
4485 struct mm_walk *walk)
4488 struct vm_area_struct *vma = walk->private;
4493 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
4494 for (; addr != end; addr += PAGE_SIZE) {
4495 pte_t ptent = *(pte++);
4496 union mc_target target;
4499 struct page_cgroup *pc;
4505 type = is_target_pte_for_mc(vma, addr, ptent, &target);
4507 case MC_TARGET_PAGE:
4509 if (isolate_lru_page(page))
4511 pc = lookup_page_cgroup(page);
4512 if (!mem_cgroup_move_account(pc,
4513 mc.from, mc.to, false)) {
4515 /* we uncharge from mc.from later. */
4518 putback_lru_page(page);
4519 put: /* is_target_pte_for_mc() gets the page */
4522 case MC_TARGET_SWAP:
4524 if (!mem_cgroup_move_swap_account(ent,
4525 mc.from, mc.to, false)) {
4527 /* we fixup refcnts and charges later. */
4535 pte_unmap_unlock(pte - 1, ptl);
4540 * We have consumed all precharges we got in can_attach().
4541 * We try charge one by one, but don't do any additional
4542 * charges to mc.to if we have failed in charge once in attach()
4545 ret = mem_cgroup_do_precharge(1);
4553 static void mem_cgroup_move_charge(struct mm_struct *mm)
4555 struct vm_area_struct *vma;
4557 lru_add_drain_all();
4558 down_read(&mm->mmap_sem);
4559 for (vma = mm->mmap; vma; vma = vma->vm_next) {
4561 struct mm_walk mem_cgroup_move_charge_walk = {
4562 .pmd_entry = mem_cgroup_move_charge_pte_range,
4566 if (is_vm_hugetlb_page(vma))
4568 ret = walk_page_range(vma->vm_start, vma->vm_end,
4569 &mem_cgroup_move_charge_walk);
4572 * means we have consumed all precharges and failed in
4573 * doing additional charge. Just abandon here.
4577 up_read(&mm->mmap_sem);
4580 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
4581 struct cgroup *cont,
4582 struct cgroup *old_cont,
4583 struct task_struct *p,
4586 struct mm_struct *mm;
4589 /* no need to move charge */
4592 mm = get_task_mm(p);
4594 mem_cgroup_move_charge(mm);
4597 mem_cgroup_clear_mc();
4599 #else /* !CONFIG_MMU */
4600 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
4601 struct cgroup *cgroup,
4602 struct task_struct *p,
4607 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
4608 struct cgroup *cgroup,
4609 struct task_struct *p,
4613 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
4614 struct cgroup *cont,
4615 struct cgroup *old_cont,
4616 struct task_struct *p,
4622 struct cgroup_subsys mem_cgroup_subsys = {
4624 .subsys_id = mem_cgroup_subsys_id,
4625 .create = mem_cgroup_create,
4626 .pre_destroy = mem_cgroup_pre_destroy,
4627 .destroy = mem_cgroup_destroy,
4628 .populate = mem_cgroup_populate,
4629 .can_attach = mem_cgroup_can_attach,
4630 .cancel_attach = mem_cgroup_cancel_attach,
4631 .attach = mem_cgroup_move_task,
4636 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4638 static int __init disable_swap_account(char *s)
4640 really_do_swap_account = 0;
4643 __setup("noswapaccount", disable_swap_account);