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)
66 #define SOFTLIMIT_EVENTS_THRESH (1000)
67 #define THRESHOLDS_EVENTS_THRESH (100)
70 * Statistics for memory cgroup.
72 enum mem_cgroup_stat_index {
74 * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
76 MEM_CGROUP_STAT_CACHE, /* # of pages charged as cache */
77 MEM_CGROUP_STAT_RSS, /* # of pages charged as anon rss */
78 MEM_CGROUP_STAT_FILE_MAPPED, /* # of pages charged as file rss */
79 MEM_CGROUP_STAT_PGPGIN_COUNT, /* # of pages paged in */
80 MEM_CGROUP_STAT_PGPGOUT_COUNT, /* # of pages paged out */
81 MEM_CGROUP_STAT_SWAPOUT, /* # of pages, swapped out */
82 MEM_CGROUP_STAT_SOFTLIMIT, /* decrements on each page in/out.
83 used by soft limit implementation */
84 MEM_CGROUP_STAT_THRESHOLDS, /* decrements on each page in/out.
85 used by threshold implementation */
87 MEM_CGROUP_STAT_NSTATS,
90 struct mem_cgroup_stat_cpu {
91 s64 count[MEM_CGROUP_STAT_NSTATS];
92 } ____cacheline_aligned_in_smp;
94 struct mem_cgroup_stat {
95 struct mem_cgroup_stat_cpu cpustat[0];
99 __mem_cgroup_stat_set_safe(struct mem_cgroup_stat_cpu *stat,
100 enum mem_cgroup_stat_index idx, s64 val)
102 stat->count[idx] = val;
106 __mem_cgroup_stat_read_local(struct mem_cgroup_stat_cpu *stat,
107 enum mem_cgroup_stat_index idx)
109 return stat->count[idx];
113 * For accounting under irq disable, no need for increment preempt count.
115 static inline void __mem_cgroup_stat_add_safe(struct mem_cgroup_stat_cpu *stat,
116 enum mem_cgroup_stat_index idx, int val)
118 stat->count[idx] += val;
121 static s64 mem_cgroup_read_stat(struct mem_cgroup_stat *stat,
122 enum mem_cgroup_stat_index idx)
126 for_each_possible_cpu(cpu)
127 ret += stat->cpustat[cpu].count[idx];
131 static s64 mem_cgroup_local_usage(struct mem_cgroup_stat *stat)
135 ret = mem_cgroup_read_stat(stat, MEM_CGROUP_STAT_CACHE);
136 ret += mem_cgroup_read_stat(stat, MEM_CGROUP_STAT_RSS);
141 * per-zone information in memory controller.
143 struct mem_cgroup_per_zone {
145 * spin_lock to protect the per cgroup LRU
147 struct list_head lists[NR_LRU_LISTS];
148 unsigned long count[NR_LRU_LISTS];
150 struct zone_reclaim_stat reclaim_stat;
151 struct rb_node tree_node; /* RB tree node */
152 unsigned long long usage_in_excess;/* Set to the value by which */
153 /* the soft limit is exceeded*/
155 struct mem_cgroup *mem; /* Back pointer, we cannot */
156 /* use container_of */
158 /* Macro for accessing counter */
159 #define MEM_CGROUP_ZSTAT(mz, idx) ((mz)->count[(idx)])
161 struct mem_cgroup_per_node {
162 struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
165 struct mem_cgroup_lru_info {
166 struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
170 * Cgroups above their limits are maintained in a RB-Tree, independent of
171 * their hierarchy representation
174 struct mem_cgroup_tree_per_zone {
175 struct rb_root rb_root;
179 struct mem_cgroup_tree_per_node {
180 struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
183 struct mem_cgroup_tree {
184 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
187 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
189 struct mem_cgroup_threshold {
190 struct eventfd_ctx *eventfd;
194 struct mem_cgroup_threshold_ary {
195 /* An array index points to threshold just below usage. */
196 atomic_t current_threshold;
197 /* Size of entries[] */
199 /* Array of thresholds */
200 struct mem_cgroup_threshold entries[0];
203 static bool mem_cgroup_threshold_check(struct mem_cgroup *mem);
204 static void mem_cgroup_threshold(struct mem_cgroup *mem);
207 * The memory controller data structure. The memory controller controls both
208 * page cache and RSS per cgroup. We would eventually like to provide
209 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
210 * to help the administrator determine what knobs to tune.
212 * TODO: Add a water mark for the memory controller. Reclaim will begin when
213 * we hit the water mark. May be even add a low water mark, such that
214 * no reclaim occurs from a cgroup at it's low water mark, this is
215 * a feature that will be implemented much later in the future.
218 struct cgroup_subsys_state css;
220 * the counter to account for memory usage
222 struct res_counter res;
224 * the counter to account for mem+swap usage.
226 struct res_counter memsw;
228 * Per cgroup active and inactive list, similar to the
229 * per zone LRU lists.
231 struct mem_cgroup_lru_info info;
234 protect against reclaim related member.
236 spinlock_t reclaim_param_lock;
238 int prev_priority; /* for recording reclaim priority */
241 * While reclaiming in a hierarchy, we cache the last child we
244 int last_scanned_child;
246 * Should the accounting and control be hierarchical, per subtree?
249 unsigned long last_oom_jiffies;
252 unsigned int swappiness;
254 /* set when res.limit == memsw.limit */
255 bool memsw_is_minimum;
257 /* protect arrays of thresholds */
258 struct mutex thresholds_lock;
260 /* thresholds for memory usage. RCU-protected */
261 struct mem_cgroup_threshold_ary *thresholds;
263 /* thresholds for mem+swap usage. RCU-protected */
264 struct mem_cgroup_threshold_ary *memsw_thresholds;
267 * Should we move charges of a task when a task is moved into this
268 * mem_cgroup ? And what type of charges should we move ?
270 unsigned long move_charge_at_immigrate;
273 * statistics. This must be placed at the end of memcg.
275 struct mem_cgroup_stat stat;
278 /* Stuffs for move charges at task migration. */
280 * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a
281 * left-shifted bitmap of these types.
284 MOVE_CHARGE_TYPE_ANON, /* private anonymous page and swap of it */
288 /* "mc" and its members are protected by cgroup_mutex */
289 static struct move_charge_struct {
290 struct mem_cgroup *from;
291 struct mem_cgroup *to;
292 unsigned long precharge;
293 unsigned long moved_charge;
294 unsigned long moved_swap;
295 struct task_struct *moving_task; /* a task moving charges */
296 wait_queue_head_t waitq; /* a waitq for other context */
298 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
302 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
303 * limit reclaim to prevent infinite loops, if they ever occur.
305 #define MEM_CGROUP_MAX_RECLAIM_LOOPS (100)
306 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS (2)
309 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
310 MEM_CGROUP_CHARGE_TYPE_MAPPED,
311 MEM_CGROUP_CHARGE_TYPE_SHMEM, /* used by page migration of shmem */
312 MEM_CGROUP_CHARGE_TYPE_FORCE, /* used by force_empty */
313 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
314 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
318 /* only for here (for easy reading.) */
319 #define PCGF_CACHE (1UL << PCG_CACHE)
320 #define PCGF_USED (1UL << PCG_USED)
321 #define PCGF_LOCK (1UL << PCG_LOCK)
322 /* Not used, but added here for completeness */
323 #define PCGF_ACCT (1UL << PCG_ACCT)
325 /* for encoding cft->private value on file */
328 #define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val))
329 #define MEMFILE_TYPE(val) (((val) >> 16) & 0xffff)
330 #define MEMFILE_ATTR(val) ((val) & 0xffff)
333 * Reclaim flags for mem_cgroup_hierarchical_reclaim
335 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
336 #define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
337 #define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
338 #define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
339 #define MEM_CGROUP_RECLAIM_SOFT_BIT 0x2
340 #define MEM_CGROUP_RECLAIM_SOFT (1 << MEM_CGROUP_RECLAIM_SOFT_BIT)
342 static void mem_cgroup_get(struct mem_cgroup *mem);
343 static void mem_cgroup_put(struct mem_cgroup *mem);
344 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem);
345 static void drain_all_stock_async(void);
347 static struct mem_cgroup_per_zone *
348 mem_cgroup_zoneinfo(struct mem_cgroup *mem, int nid, int zid)
350 return &mem->info.nodeinfo[nid]->zoneinfo[zid];
353 struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *mem)
358 static struct mem_cgroup_per_zone *
359 page_cgroup_zoneinfo(struct page_cgroup *pc)
361 struct mem_cgroup *mem = pc->mem_cgroup;
362 int nid = page_cgroup_nid(pc);
363 int zid = page_cgroup_zid(pc);
368 return mem_cgroup_zoneinfo(mem, nid, zid);
371 static struct mem_cgroup_tree_per_zone *
372 soft_limit_tree_node_zone(int nid, int zid)
374 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
377 static struct mem_cgroup_tree_per_zone *
378 soft_limit_tree_from_page(struct page *page)
380 int nid = page_to_nid(page);
381 int zid = page_zonenum(page);
383 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
387 __mem_cgroup_insert_exceeded(struct mem_cgroup *mem,
388 struct mem_cgroup_per_zone *mz,
389 struct mem_cgroup_tree_per_zone *mctz,
390 unsigned long long new_usage_in_excess)
392 struct rb_node **p = &mctz->rb_root.rb_node;
393 struct rb_node *parent = NULL;
394 struct mem_cgroup_per_zone *mz_node;
399 mz->usage_in_excess = new_usage_in_excess;
400 if (!mz->usage_in_excess)
404 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
406 if (mz->usage_in_excess < mz_node->usage_in_excess)
409 * We can't avoid mem cgroups that are over their soft
410 * limit by the same amount
412 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
415 rb_link_node(&mz->tree_node, parent, p);
416 rb_insert_color(&mz->tree_node, &mctz->rb_root);
421 __mem_cgroup_remove_exceeded(struct mem_cgroup *mem,
422 struct mem_cgroup_per_zone *mz,
423 struct mem_cgroup_tree_per_zone *mctz)
427 rb_erase(&mz->tree_node, &mctz->rb_root);
432 mem_cgroup_remove_exceeded(struct mem_cgroup *mem,
433 struct mem_cgroup_per_zone *mz,
434 struct mem_cgroup_tree_per_zone *mctz)
436 spin_lock(&mctz->lock);
437 __mem_cgroup_remove_exceeded(mem, mz, mctz);
438 spin_unlock(&mctz->lock);
441 static bool mem_cgroup_soft_limit_check(struct mem_cgroup *mem)
446 struct mem_cgroup_stat_cpu *cpustat;
449 cpustat = &mem->stat.cpustat[cpu];
450 val = __mem_cgroup_stat_read_local(cpustat, MEM_CGROUP_STAT_SOFTLIMIT);
451 if (unlikely(val < 0)) {
452 __mem_cgroup_stat_set_safe(cpustat, MEM_CGROUP_STAT_SOFTLIMIT,
453 SOFTLIMIT_EVENTS_THRESH);
460 static void mem_cgroup_update_tree(struct mem_cgroup *mem, struct page *page)
462 unsigned long long excess;
463 struct mem_cgroup_per_zone *mz;
464 struct mem_cgroup_tree_per_zone *mctz;
465 int nid = page_to_nid(page);
466 int zid = page_zonenum(page);
467 mctz = soft_limit_tree_from_page(page);
470 * Necessary to update all ancestors when hierarchy is used.
471 * because their event counter is not touched.
473 for (; mem; mem = parent_mem_cgroup(mem)) {
474 mz = mem_cgroup_zoneinfo(mem, nid, zid);
475 excess = res_counter_soft_limit_excess(&mem->res);
477 * We have to update the tree if mz is on RB-tree or
478 * mem is over its softlimit.
480 if (excess || mz->on_tree) {
481 spin_lock(&mctz->lock);
482 /* if on-tree, remove it */
484 __mem_cgroup_remove_exceeded(mem, mz, mctz);
486 * Insert again. mz->usage_in_excess will be updated.
487 * If excess is 0, no tree ops.
489 __mem_cgroup_insert_exceeded(mem, mz, mctz, excess);
490 spin_unlock(&mctz->lock);
495 static void mem_cgroup_remove_from_trees(struct mem_cgroup *mem)
498 struct mem_cgroup_per_zone *mz;
499 struct mem_cgroup_tree_per_zone *mctz;
501 for_each_node_state(node, N_POSSIBLE) {
502 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
503 mz = mem_cgroup_zoneinfo(mem, node, zone);
504 mctz = soft_limit_tree_node_zone(node, zone);
505 mem_cgroup_remove_exceeded(mem, mz, mctz);
510 static inline unsigned long mem_cgroup_get_excess(struct mem_cgroup *mem)
512 return res_counter_soft_limit_excess(&mem->res) >> PAGE_SHIFT;
515 static struct mem_cgroup_per_zone *
516 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
518 struct rb_node *rightmost = NULL;
519 struct mem_cgroup_per_zone *mz;
523 rightmost = rb_last(&mctz->rb_root);
525 goto done; /* Nothing to reclaim from */
527 mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
529 * Remove the node now but someone else can add it back,
530 * we will to add it back at the end of reclaim to its correct
531 * position in the tree.
533 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
534 if (!res_counter_soft_limit_excess(&mz->mem->res) ||
535 !css_tryget(&mz->mem->css))
541 static struct mem_cgroup_per_zone *
542 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
544 struct mem_cgroup_per_zone *mz;
546 spin_lock(&mctz->lock);
547 mz = __mem_cgroup_largest_soft_limit_node(mctz);
548 spin_unlock(&mctz->lock);
552 static void mem_cgroup_swap_statistics(struct mem_cgroup *mem,
555 int val = (charge) ? 1 : -1;
556 struct mem_cgroup_stat *stat = &mem->stat;
557 struct mem_cgroup_stat_cpu *cpustat;
560 cpustat = &stat->cpustat[cpu];
561 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_SWAPOUT, val);
565 static void mem_cgroup_charge_statistics(struct mem_cgroup *mem,
566 struct page_cgroup *pc,
569 int val = (charge) ? 1 : -1;
570 struct mem_cgroup_stat *stat = &mem->stat;
571 struct mem_cgroup_stat_cpu *cpustat;
574 cpustat = &stat->cpustat[cpu];
575 if (PageCgroupCache(pc))
576 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_CACHE, val);
578 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_RSS, val);
581 __mem_cgroup_stat_add_safe(cpustat,
582 MEM_CGROUP_STAT_PGPGIN_COUNT, 1);
584 __mem_cgroup_stat_add_safe(cpustat,
585 MEM_CGROUP_STAT_PGPGOUT_COUNT, 1);
586 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_SOFTLIMIT, -1);
587 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_THRESHOLDS, -1);
592 static unsigned long mem_cgroup_get_local_zonestat(struct mem_cgroup *mem,
596 struct mem_cgroup_per_zone *mz;
599 for_each_online_node(nid)
600 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
601 mz = mem_cgroup_zoneinfo(mem, nid, zid);
602 total += MEM_CGROUP_ZSTAT(mz, idx);
607 static struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
609 return container_of(cgroup_subsys_state(cont,
610 mem_cgroup_subsys_id), struct mem_cgroup,
614 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
617 * mm_update_next_owner() may clear mm->owner to NULL
618 * if it races with swapoff, page migration, etc.
619 * So this can be called with p == NULL.
624 return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
625 struct mem_cgroup, css);
628 static struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
630 struct mem_cgroup *mem = NULL;
635 * Because we have no locks, mm->owner's may be being moved to other
636 * cgroup. We use css_tryget() here even if this looks
637 * pessimistic (rather than adding locks here).
641 mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
644 } while (!css_tryget(&mem->css));
650 * Call callback function against all cgroup under hierarchy tree.
652 static int mem_cgroup_walk_tree(struct mem_cgroup *root, void *data,
653 int (*func)(struct mem_cgroup *, void *))
655 int found, ret, nextid;
656 struct cgroup_subsys_state *css;
657 struct mem_cgroup *mem;
659 if (!root->use_hierarchy)
660 return (*func)(root, data);
668 css = css_get_next(&mem_cgroup_subsys, nextid, &root->css,
670 if (css && css_tryget(css))
671 mem = container_of(css, struct mem_cgroup, css);
675 ret = (*func)(mem, data);
679 } while (!ret && css);
684 static inline bool mem_cgroup_is_root(struct mem_cgroup *mem)
686 return (mem == root_mem_cgroup);
690 * Following LRU functions are allowed to be used without PCG_LOCK.
691 * Operations are called by routine of global LRU independently from memcg.
692 * What we have to take care of here is validness of pc->mem_cgroup.
694 * Changes to pc->mem_cgroup happens when
697 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
698 * It is added to LRU before charge.
699 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
700 * When moving account, the page is not on LRU. It's isolated.
703 void mem_cgroup_del_lru_list(struct page *page, enum lru_list lru)
705 struct page_cgroup *pc;
706 struct mem_cgroup_per_zone *mz;
708 if (mem_cgroup_disabled())
710 pc = lookup_page_cgroup(page);
711 /* can happen while we handle swapcache. */
712 if (!TestClearPageCgroupAcctLRU(pc))
714 VM_BUG_ON(!pc->mem_cgroup);
716 * We don't check PCG_USED bit. It's cleared when the "page" is finally
717 * removed from global LRU.
719 mz = page_cgroup_zoneinfo(pc);
720 MEM_CGROUP_ZSTAT(mz, lru) -= 1;
721 if (mem_cgroup_is_root(pc->mem_cgroup))
723 VM_BUG_ON(list_empty(&pc->lru));
724 list_del_init(&pc->lru);
728 void mem_cgroup_del_lru(struct page *page)
730 mem_cgroup_del_lru_list(page, page_lru(page));
733 void mem_cgroup_rotate_lru_list(struct page *page, enum lru_list lru)
735 struct mem_cgroup_per_zone *mz;
736 struct page_cgroup *pc;
738 if (mem_cgroup_disabled())
741 pc = lookup_page_cgroup(page);
743 * Used bit is set without atomic ops but after smp_wmb().
744 * For making pc->mem_cgroup visible, insert smp_rmb() here.
747 /* unused or root page is not rotated. */
748 if (!PageCgroupUsed(pc) || mem_cgroup_is_root(pc->mem_cgroup))
750 mz = page_cgroup_zoneinfo(pc);
751 list_move(&pc->lru, &mz->lists[lru]);
754 void mem_cgroup_add_lru_list(struct page *page, enum lru_list lru)
756 struct page_cgroup *pc;
757 struct mem_cgroup_per_zone *mz;
759 if (mem_cgroup_disabled())
761 pc = lookup_page_cgroup(page);
762 VM_BUG_ON(PageCgroupAcctLRU(pc));
764 * Used bit is set without atomic ops but after smp_wmb().
765 * For making pc->mem_cgroup visible, insert smp_rmb() here.
768 if (!PageCgroupUsed(pc))
771 mz = page_cgroup_zoneinfo(pc);
772 MEM_CGROUP_ZSTAT(mz, lru) += 1;
773 SetPageCgroupAcctLRU(pc);
774 if (mem_cgroup_is_root(pc->mem_cgroup))
776 list_add(&pc->lru, &mz->lists[lru]);
780 * At handling SwapCache, pc->mem_cgroup may be changed while it's linked to
781 * lru because the page may.be reused after it's fully uncharged (because of
782 * SwapCache behavior).To handle that, unlink page_cgroup from LRU when charge
783 * it again. This function is only used to charge SwapCache. It's done under
784 * lock_page and expected that zone->lru_lock is never held.
786 static void mem_cgroup_lru_del_before_commit_swapcache(struct page *page)
789 struct zone *zone = page_zone(page);
790 struct page_cgroup *pc = lookup_page_cgroup(page);
792 spin_lock_irqsave(&zone->lru_lock, flags);
794 * Forget old LRU when this page_cgroup is *not* used. This Used bit
795 * is guarded by lock_page() because the page is SwapCache.
797 if (!PageCgroupUsed(pc))
798 mem_cgroup_del_lru_list(page, page_lru(page));
799 spin_unlock_irqrestore(&zone->lru_lock, flags);
802 static void mem_cgroup_lru_add_after_commit_swapcache(struct page *page)
805 struct zone *zone = page_zone(page);
806 struct page_cgroup *pc = lookup_page_cgroup(page);
808 spin_lock_irqsave(&zone->lru_lock, flags);
809 /* link when the page is linked to LRU but page_cgroup isn't */
810 if (PageLRU(page) && !PageCgroupAcctLRU(pc))
811 mem_cgroup_add_lru_list(page, page_lru(page));
812 spin_unlock_irqrestore(&zone->lru_lock, flags);
816 void mem_cgroup_move_lists(struct page *page,
817 enum lru_list from, enum lru_list to)
819 if (mem_cgroup_disabled())
821 mem_cgroup_del_lru_list(page, from);
822 mem_cgroup_add_lru_list(page, to);
825 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *mem)
828 struct mem_cgroup *curr = NULL;
832 curr = try_get_mem_cgroup_from_mm(task->mm);
838 * We should check use_hierarchy of "mem" not "curr". Because checking
839 * use_hierarchy of "curr" here make this function true if hierarchy is
840 * enabled in "curr" and "curr" is a child of "mem" in *cgroup*
841 * hierarchy(even if use_hierarchy is disabled in "mem").
843 if (mem->use_hierarchy)
844 ret = css_is_ancestor(&curr->css, &mem->css);
852 * prev_priority control...this will be used in memory reclaim path.
854 int mem_cgroup_get_reclaim_priority(struct mem_cgroup *mem)
858 spin_lock(&mem->reclaim_param_lock);
859 prev_priority = mem->prev_priority;
860 spin_unlock(&mem->reclaim_param_lock);
862 return prev_priority;
865 void mem_cgroup_note_reclaim_priority(struct mem_cgroup *mem, int priority)
867 spin_lock(&mem->reclaim_param_lock);
868 if (priority < mem->prev_priority)
869 mem->prev_priority = priority;
870 spin_unlock(&mem->reclaim_param_lock);
873 void mem_cgroup_record_reclaim_priority(struct mem_cgroup *mem, int priority)
875 spin_lock(&mem->reclaim_param_lock);
876 mem->prev_priority = priority;
877 spin_unlock(&mem->reclaim_param_lock);
880 static int calc_inactive_ratio(struct mem_cgroup *memcg, unsigned long *present_pages)
882 unsigned long active;
883 unsigned long inactive;
885 unsigned long inactive_ratio;
887 inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_ANON);
888 active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_ANON);
890 gb = (inactive + active) >> (30 - PAGE_SHIFT);
892 inactive_ratio = int_sqrt(10 * gb);
897 present_pages[0] = inactive;
898 present_pages[1] = active;
901 return inactive_ratio;
904 int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg)
906 unsigned long active;
907 unsigned long inactive;
908 unsigned long present_pages[2];
909 unsigned long inactive_ratio;
911 inactive_ratio = calc_inactive_ratio(memcg, present_pages);
913 inactive = present_pages[0];
914 active = present_pages[1];
916 if (inactive * inactive_ratio < active)
922 int mem_cgroup_inactive_file_is_low(struct mem_cgroup *memcg)
924 unsigned long active;
925 unsigned long inactive;
927 inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_FILE);
928 active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_FILE);
930 return (active > inactive);
933 unsigned long mem_cgroup_zone_nr_pages(struct mem_cgroup *memcg,
937 int nid = zone->zone_pgdat->node_id;
938 int zid = zone_idx(zone);
939 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
941 return MEM_CGROUP_ZSTAT(mz, lru);
944 struct zone_reclaim_stat *mem_cgroup_get_reclaim_stat(struct mem_cgroup *memcg,
947 int nid = zone->zone_pgdat->node_id;
948 int zid = zone_idx(zone);
949 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
951 return &mz->reclaim_stat;
954 struct zone_reclaim_stat *
955 mem_cgroup_get_reclaim_stat_from_page(struct page *page)
957 struct page_cgroup *pc;
958 struct mem_cgroup_per_zone *mz;
960 if (mem_cgroup_disabled())
963 pc = lookup_page_cgroup(page);
965 * Used bit is set without atomic ops but after smp_wmb().
966 * For making pc->mem_cgroup visible, insert smp_rmb() here.
969 if (!PageCgroupUsed(pc))
972 mz = page_cgroup_zoneinfo(pc);
976 return &mz->reclaim_stat;
979 unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan,
980 struct list_head *dst,
981 unsigned long *scanned, int order,
982 int mode, struct zone *z,
983 struct mem_cgroup *mem_cont,
984 int active, int file)
986 unsigned long nr_taken = 0;
990 struct list_head *src;
991 struct page_cgroup *pc, *tmp;
992 int nid = z->zone_pgdat->node_id;
993 int zid = zone_idx(z);
994 struct mem_cgroup_per_zone *mz;
995 int lru = LRU_FILE * file + active;
999 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
1000 src = &mz->lists[lru];
1003 list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
1004 if (scan >= nr_to_scan)
1008 if (unlikely(!PageCgroupUsed(pc)))
1010 if (unlikely(!PageLRU(page)))
1014 ret = __isolate_lru_page(page, mode, file);
1017 list_move(&page->lru, dst);
1018 mem_cgroup_del_lru(page);
1022 /* we don't affect global LRU but rotate in our LRU */
1023 mem_cgroup_rotate_lru_list(page, page_lru(page));
1034 #define mem_cgroup_from_res_counter(counter, member) \
1035 container_of(counter, struct mem_cgroup, member)
1037 static bool mem_cgroup_check_under_limit(struct mem_cgroup *mem)
1039 if (do_swap_account) {
1040 if (res_counter_check_under_limit(&mem->res) &&
1041 res_counter_check_under_limit(&mem->memsw))
1044 if (res_counter_check_under_limit(&mem->res))
1049 static unsigned int get_swappiness(struct mem_cgroup *memcg)
1051 struct cgroup *cgrp = memcg->css.cgroup;
1052 unsigned int swappiness;
1055 if (cgrp->parent == NULL)
1056 return vm_swappiness;
1058 spin_lock(&memcg->reclaim_param_lock);
1059 swappiness = memcg->swappiness;
1060 spin_unlock(&memcg->reclaim_param_lock);
1065 static int mem_cgroup_count_children_cb(struct mem_cgroup *mem, void *data)
1073 * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode.
1074 * @memcg: The memory cgroup that went over limit
1075 * @p: Task that is going to be killed
1077 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1080 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1082 struct cgroup *task_cgrp;
1083 struct cgroup *mem_cgrp;
1085 * Need a buffer in BSS, can't rely on allocations. The code relies
1086 * on the assumption that OOM is serialized for memory controller.
1087 * If this assumption is broken, revisit this code.
1089 static char memcg_name[PATH_MAX];
1098 mem_cgrp = memcg->css.cgroup;
1099 task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1101 ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1104 * Unfortunately, we are unable to convert to a useful name
1105 * But we'll still print out the usage information
1112 printk(KERN_INFO "Task in %s killed", memcg_name);
1115 ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1123 * Continues from above, so we don't need an KERN_ level
1125 printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
1128 printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
1129 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1130 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1131 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1132 printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
1134 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1135 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1136 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1140 * This function returns the number of memcg under hierarchy tree. Returns
1141 * 1(self count) if no children.
1143 static int mem_cgroup_count_children(struct mem_cgroup *mem)
1146 mem_cgroup_walk_tree(mem, &num, mem_cgroup_count_children_cb);
1151 * Visit the first child (need not be the first child as per the ordering
1152 * of the cgroup list, since we track last_scanned_child) of @mem and use
1153 * that to reclaim free pages from.
1155 static struct mem_cgroup *
1156 mem_cgroup_select_victim(struct mem_cgroup *root_mem)
1158 struct mem_cgroup *ret = NULL;
1159 struct cgroup_subsys_state *css;
1162 if (!root_mem->use_hierarchy) {
1163 css_get(&root_mem->css);
1169 nextid = root_mem->last_scanned_child + 1;
1170 css = css_get_next(&mem_cgroup_subsys, nextid, &root_mem->css,
1172 if (css && css_tryget(css))
1173 ret = container_of(css, struct mem_cgroup, css);
1176 /* Updates scanning parameter */
1177 spin_lock(&root_mem->reclaim_param_lock);
1179 /* this means start scan from ID:1 */
1180 root_mem->last_scanned_child = 0;
1182 root_mem->last_scanned_child = found;
1183 spin_unlock(&root_mem->reclaim_param_lock);
1190 * Scan the hierarchy if needed to reclaim memory. We remember the last child
1191 * we reclaimed from, so that we don't end up penalizing one child extensively
1192 * based on its position in the children list.
1194 * root_mem is the original ancestor that we've been reclaim from.
1196 * We give up and return to the caller when we visit root_mem twice.
1197 * (other groups can be removed while we're walking....)
1199 * If shrink==true, for avoiding to free too much, this returns immedieately.
1201 static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup *root_mem,
1204 unsigned long reclaim_options)
1206 struct mem_cgroup *victim;
1209 bool noswap = reclaim_options & MEM_CGROUP_RECLAIM_NOSWAP;
1210 bool shrink = reclaim_options & MEM_CGROUP_RECLAIM_SHRINK;
1211 bool check_soft = reclaim_options & MEM_CGROUP_RECLAIM_SOFT;
1212 unsigned long excess = mem_cgroup_get_excess(root_mem);
1214 /* If memsw_is_minimum==1, swap-out is of-no-use. */
1215 if (root_mem->memsw_is_minimum)
1219 victim = mem_cgroup_select_victim(root_mem);
1220 if (victim == root_mem) {
1223 drain_all_stock_async();
1226 * If we have not been able to reclaim
1227 * anything, it might because there are
1228 * no reclaimable pages under this hierarchy
1230 if (!check_soft || !total) {
1231 css_put(&victim->css);
1235 * We want to do more targetted reclaim.
1236 * excess >> 2 is not to excessive so as to
1237 * reclaim too much, nor too less that we keep
1238 * coming back to reclaim from this cgroup
1240 if (total >= (excess >> 2) ||
1241 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS)) {
1242 css_put(&victim->css);
1247 if (!mem_cgroup_local_usage(&victim->stat)) {
1248 /* this cgroup's local usage == 0 */
1249 css_put(&victim->css);
1252 /* we use swappiness of local cgroup */
1254 ret = mem_cgroup_shrink_node_zone(victim, gfp_mask,
1255 noswap, get_swappiness(victim), zone,
1256 zone->zone_pgdat->node_id);
1258 ret = try_to_free_mem_cgroup_pages(victim, gfp_mask,
1259 noswap, get_swappiness(victim));
1260 css_put(&victim->css);
1262 * At shrinking usage, we can't check we should stop here or
1263 * reclaim more. It's depends on callers. last_scanned_child
1264 * will work enough for keeping fairness under tree.
1270 if (res_counter_check_under_soft_limit(&root_mem->res))
1272 } else if (mem_cgroup_check_under_limit(root_mem))
1278 bool mem_cgroup_oom_called(struct task_struct *task)
1281 struct mem_cgroup *mem;
1282 struct mm_struct *mm;
1288 mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
1289 if (mem && time_before(jiffies, mem->last_oom_jiffies + HZ/10))
1295 static int record_last_oom_cb(struct mem_cgroup *mem, void *data)
1297 mem->last_oom_jiffies = jiffies;
1301 static void record_last_oom(struct mem_cgroup *mem)
1303 mem_cgroup_walk_tree(mem, NULL, record_last_oom_cb);
1307 * Currently used to update mapped file statistics, but the routine can be
1308 * generalized to update other statistics as well.
1310 void mem_cgroup_update_file_mapped(struct page *page, int val)
1312 struct mem_cgroup *mem;
1313 struct mem_cgroup_stat *stat;
1314 struct mem_cgroup_stat_cpu *cpustat;
1316 struct page_cgroup *pc;
1318 pc = lookup_page_cgroup(page);
1322 lock_page_cgroup(pc);
1323 mem = pc->mem_cgroup;
1327 if (!PageCgroupUsed(pc))
1331 * Preemption is already disabled, we don't need get_cpu()
1333 cpu = smp_processor_id();
1335 cpustat = &stat->cpustat[cpu];
1337 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_FILE_MAPPED, val);
1339 unlock_page_cgroup(pc);
1343 * size of first charge trial. "32" comes from vmscan.c's magic value.
1344 * TODO: maybe necessary to use big numbers in big irons.
1346 #define CHARGE_SIZE (32 * PAGE_SIZE)
1347 struct memcg_stock_pcp {
1348 struct mem_cgroup *cached; /* this never be root cgroup */
1350 struct work_struct work;
1352 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
1353 static atomic_t memcg_drain_count;
1356 * Try to consume stocked charge on this cpu. If success, PAGE_SIZE is consumed
1357 * from local stock and true is returned. If the stock is 0 or charges from a
1358 * cgroup which is not current target, returns false. This stock will be
1361 static bool consume_stock(struct mem_cgroup *mem)
1363 struct memcg_stock_pcp *stock;
1366 stock = &get_cpu_var(memcg_stock);
1367 if (mem == stock->cached && stock->charge)
1368 stock->charge -= PAGE_SIZE;
1369 else /* need to call res_counter_charge */
1371 put_cpu_var(memcg_stock);
1376 * Returns stocks cached in percpu to res_counter and reset cached information.
1378 static void drain_stock(struct memcg_stock_pcp *stock)
1380 struct mem_cgroup *old = stock->cached;
1382 if (stock->charge) {
1383 res_counter_uncharge(&old->res, stock->charge);
1384 if (do_swap_account)
1385 res_counter_uncharge(&old->memsw, stock->charge);
1387 stock->cached = NULL;
1392 * This must be called under preempt disabled or must be called by
1393 * a thread which is pinned to local cpu.
1395 static void drain_local_stock(struct work_struct *dummy)
1397 struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
1402 * Cache charges(val) which is from res_counter, to local per_cpu area.
1403 * This will be consumed by consumt_stock() function, later.
1405 static void refill_stock(struct mem_cgroup *mem, int val)
1407 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
1409 if (stock->cached != mem) { /* reset if necessary */
1411 stock->cached = mem;
1413 stock->charge += val;
1414 put_cpu_var(memcg_stock);
1418 * Tries to drain stocked charges in other cpus. This function is asynchronous
1419 * and just put a work per cpu for draining localy on each cpu. Caller can
1420 * expects some charges will be back to res_counter later but cannot wait for
1423 static void drain_all_stock_async(void)
1426 /* This function is for scheduling "drain" in asynchronous way.
1427 * The result of "drain" is not directly handled by callers. Then,
1428 * if someone is calling drain, we don't have to call drain more.
1429 * Anyway, WORK_STRUCT_PENDING check in queue_work_on() will catch if
1430 * there is a race. We just do loose check here.
1432 if (atomic_read(&memcg_drain_count))
1434 /* Notify other cpus that system-wide "drain" is running */
1435 atomic_inc(&memcg_drain_count);
1437 for_each_online_cpu(cpu) {
1438 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
1439 schedule_work_on(cpu, &stock->work);
1442 atomic_dec(&memcg_drain_count);
1443 /* We don't wait for flush_work */
1446 /* This is a synchronous drain interface. */
1447 static void drain_all_stock_sync(void)
1449 /* called when force_empty is called */
1450 atomic_inc(&memcg_drain_count);
1451 schedule_on_each_cpu(drain_local_stock);
1452 atomic_dec(&memcg_drain_count);
1455 static int __cpuinit memcg_stock_cpu_callback(struct notifier_block *nb,
1456 unsigned long action,
1459 int cpu = (unsigned long)hcpu;
1460 struct memcg_stock_pcp *stock;
1462 if (action != CPU_DEAD)
1464 stock = &per_cpu(memcg_stock, cpu);
1470 * Unlike exported interface, "oom" parameter is added. if oom==true,
1471 * oom-killer can be invoked.
1473 static int __mem_cgroup_try_charge(struct mm_struct *mm,
1474 gfp_t gfp_mask, struct mem_cgroup **memcg,
1475 bool oom, struct page *page)
1477 struct mem_cgroup *mem, *mem_over_limit;
1478 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
1479 struct res_counter *fail_res;
1480 int csize = CHARGE_SIZE;
1482 if (unlikely(test_thread_flag(TIF_MEMDIE))) {
1483 /* Don't account this! */
1489 * We always charge the cgroup the mm_struct belongs to.
1490 * The mm_struct's mem_cgroup changes on task migration if the
1491 * thread group leader migrates. It's possible that mm is not
1492 * set, if so charge the init_mm (happens for pagecache usage).
1496 mem = try_get_mem_cgroup_from_mm(mm);
1504 VM_BUG_ON(css_is_removed(&mem->css));
1505 if (mem_cgroup_is_root(mem))
1510 unsigned long flags = 0;
1512 if (consume_stock(mem))
1515 ret = res_counter_charge(&mem->res, csize, &fail_res);
1517 if (!do_swap_account)
1519 ret = res_counter_charge(&mem->memsw, csize, &fail_res);
1522 /* mem+swap counter fails */
1523 res_counter_uncharge(&mem->res, csize);
1524 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
1525 mem_over_limit = mem_cgroup_from_res_counter(fail_res,
1528 /* mem counter fails */
1529 mem_over_limit = mem_cgroup_from_res_counter(fail_res,
1532 /* reduce request size and retry */
1533 if (csize > PAGE_SIZE) {
1537 if (!(gfp_mask & __GFP_WAIT))
1540 ret = mem_cgroup_hierarchical_reclaim(mem_over_limit, NULL,
1546 * try_to_free_mem_cgroup_pages() might not give us a full
1547 * picture of reclaim. Some pages are reclaimed and might be
1548 * moved to swap cache or just unmapped from the cgroup.
1549 * Check the limit again to see if the reclaim reduced the
1550 * current usage of the cgroup before giving up
1553 if (mem_cgroup_check_under_limit(mem_over_limit))
1556 /* try to avoid oom while someone is moving charge */
1557 if (mc.moving_task && current != mc.moving_task) {
1558 struct mem_cgroup *from, *to;
1559 bool do_continue = false;
1561 * There is a small race that "from" or "to" can be
1562 * freed by rmdir, so we use css_tryget().
1567 if (from && css_tryget(&from->css)) {
1568 if (mem_over_limit->use_hierarchy)
1569 do_continue = css_is_ancestor(
1571 &mem_over_limit->css);
1573 do_continue = (from == mem_over_limit);
1574 css_put(&from->css);
1576 if (!do_continue && to && css_tryget(&to->css)) {
1577 if (mem_over_limit->use_hierarchy)
1578 do_continue = css_is_ancestor(
1580 &mem_over_limit->css);
1582 do_continue = (to == mem_over_limit);
1588 prepare_to_wait(&mc.waitq, &wait,
1589 TASK_INTERRUPTIBLE);
1590 /* moving charge context might have finished. */
1593 finish_wait(&mc.waitq, &wait);
1598 if (!nr_retries--) {
1600 mem_cgroup_out_of_memory(mem_over_limit, gfp_mask);
1601 record_last_oom(mem_over_limit);
1606 if (csize > PAGE_SIZE)
1607 refill_stock(mem, csize - PAGE_SIZE);
1610 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
1611 * if they exceeds softlimit.
1613 if (page && mem_cgroup_soft_limit_check(mem))
1614 mem_cgroup_update_tree(mem, page);
1616 if (mem_cgroup_threshold_check(mem))
1617 mem_cgroup_threshold(mem);
1625 * Somemtimes we have to undo a charge we got by try_charge().
1626 * This function is for that and do uncharge, put css's refcnt.
1627 * gotten by try_charge().
1629 static void __mem_cgroup_cancel_charge(struct mem_cgroup *mem,
1630 unsigned long count)
1632 if (!mem_cgroup_is_root(mem)) {
1633 res_counter_uncharge(&mem->res, PAGE_SIZE * count);
1634 if (do_swap_account)
1635 res_counter_uncharge(&mem->memsw, PAGE_SIZE * count);
1636 VM_BUG_ON(test_bit(CSS_ROOT, &mem->css.flags));
1637 WARN_ON_ONCE(count > INT_MAX);
1638 __css_put(&mem->css, (int)count);
1640 /* we don't need css_put for root */
1643 static void mem_cgroup_cancel_charge(struct mem_cgroup *mem)
1645 __mem_cgroup_cancel_charge(mem, 1);
1649 * A helper function to get mem_cgroup from ID. must be called under
1650 * rcu_read_lock(). The caller must check css_is_removed() or some if
1651 * it's concern. (dropping refcnt from swap can be called against removed
1654 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
1656 struct cgroup_subsys_state *css;
1658 /* ID 0 is unused ID */
1661 css = css_lookup(&mem_cgroup_subsys, id);
1664 return container_of(css, struct mem_cgroup, css);
1667 struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
1669 struct mem_cgroup *mem = NULL;
1670 struct page_cgroup *pc;
1674 VM_BUG_ON(!PageLocked(page));
1676 pc = lookup_page_cgroup(page);
1677 lock_page_cgroup(pc);
1678 if (PageCgroupUsed(pc)) {
1679 mem = pc->mem_cgroup;
1680 if (mem && !css_tryget(&mem->css))
1682 } else if (PageSwapCache(page)) {
1683 ent.val = page_private(page);
1684 id = lookup_swap_cgroup(ent);
1686 mem = mem_cgroup_lookup(id);
1687 if (mem && !css_tryget(&mem->css))
1691 unlock_page_cgroup(pc);
1696 * commit a charge got by __mem_cgroup_try_charge() and makes page_cgroup to be
1697 * USED state. If already USED, uncharge and return.
1700 static void __mem_cgroup_commit_charge(struct mem_cgroup *mem,
1701 struct page_cgroup *pc,
1702 enum charge_type ctype)
1704 /* try_charge() can return NULL to *memcg, taking care of it. */
1708 lock_page_cgroup(pc);
1709 if (unlikely(PageCgroupUsed(pc))) {
1710 unlock_page_cgroup(pc);
1711 mem_cgroup_cancel_charge(mem);
1715 pc->mem_cgroup = mem;
1717 * We access a page_cgroup asynchronously without lock_page_cgroup().
1718 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
1719 * is accessed after testing USED bit. To make pc->mem_cgroup visible
1720 * before USED bit, we need memory barrier here.
1721 * See mem_cgroup_add_lru_list(), etc.
1725 case MEM_CGROUP_CHARGE_TYPE_CACHE:
1726 case MEM_CGROUP_CHARGE_TYPE_SHMEM:
1727 SetPageCgroupCache(pc);
1728 SetPageCgroupUsed(pc);
1730 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
1731 ClearPageCgroupCache(pc);
1732 SetPageCgroupUsed(pc);
1738 mem_cgroup_charge_statistics(mem, pc, true);
1740 unlock_page_cgroup(pc);
1744 * __mem_cgroup_move_account - move account of the page
1745 * @pc: page_cgroup of the page.
1746 * @from: mem_cgroup which the page is moved from.
1747 * @to: mem_cgroup which the page is moved to. @from != @to.
1748 * @uncharge: whether we should call uncharge and css_put against @from.
1750 * The caller must confirm following.
1751 * - page is not on LRU (isolate_page() is useful.)
1752 * - the pc is locked, used, and ->mem_cgroup points to @from.
1754 * This function doesn't do "charge" nor css_get to new cgroup. It should be
1755 * done by a caller(__mem_cgroup_try_charge would be usefull). If @uncharge is
1756 * true, this function does "uncharge" from old cgroup, but it doesn't if
1757 * @uncharge is false, so a caller should do "uncharge".
1760 static void __mem_cgroup_move_account(struct page_cgroup *pc,
1761 struct mem_cgroup *from, struct mem_cgroup *to, bool uncharge)
1765 struct mem_cgroup_stat *stat;
1766 struct mem_cgroup_stat_cpu *cpustat;
1768 VM_BUG_ON(from == to);
1769 VM_BUG_ON(PageLRU(pc->page));
1770 VM_BUG_ON(!PageCgroupLocked(pc));
1771 VM_BUG_ON(!PageCgroupUsed(pc));
1772 VM_BUG_ON(pc->mem_cgroup != from);
1775 if (page_mapped(page) && !PageAnon(page)) {
1776 cpu = smp_processor_id();
1777 /* Update mapped_file data for mem_cgroup "from" */
1779 cpustat = &stat->cpustat[cpu];
1780 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_FILE_MAPPED,
1783 /* Update mapped_file data for mem_cgroup "to" */
1785 cpustat = &stat->cpustat[cpu];
1786 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_FILE_MAPPED,
1789 mem_cgroup_charge_statistics(from, pc, false);
1791 /* This is not "cancel", but cancel_charge does all we need. */
1792 mem_cgroup_cancel_charge(from);
1794 /* caller should have done css_get */
1795 pc->mem_cgroup = to;
1796 mem_cgroup_charge_statistics(to, pc, true);
1798 * We charges against "to" which may not have any tasks. Then, "to"
1799 * can be under rmdir(). But in current implementation, caller of
1800 * this function is just force_empty() and move charge, so it's
1801 * garanteed that "to" is never removed. So, we don't check rmdir
1807 * check whether the @pc is valid for moving account and call
1808 * __mem_cgroup_move_account()
1810 static int mem_cgroup_move_account(struct page_cgroup *pc,
1811 struct mem_cgroup *from, struct mem_cgroup *to, bool uncharge)
1814 lock_page_cgroup(pc);
1815 if (PageCgroupUsed(pc) && pc->mem_cgroup == from) {
1816 __mem_cgroup_move_account(pc, from, to, uncharge);
1819 unlock_page_cgroup(pc);
1824 * move charges to its parent.
1827 static int mem_cgroup_move_parent(struct page_cgroup *pc,
1828 struct mem_cgroup *child,
1831 struct page *page = pc->page;
1832 struct cgroup *cg = child->css.cgroup;
1833 struct cgroup *pcg = cg->parent;
1834 struct mem_cgroup *parent;
1842 if (!get_page_unless_zero(page))
1844 if (isolate_lru_page(page))
1847 parent = mem_cgroup_from_cont(pcg);
1848 ret = __mem_cgroup_try_charge(NULL, gfp_mask, &parent, false, page);
1852 ret = mem_cgroup_move_account(pc, child, parent, true);
1854 mem_cgroup_cancel_charge(parent);
1856 putback_lru_page(page);
1864 * Charge the memory controller for page usage.
1866 * 0 if the charge was successful
1867 * < 0 if the cgroup is over its limit
1869 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
1870 gfp_t gfp_mask, enum charge_type ctype,
1871 struct mem_cgroup *memcg)
1873 struct mem_cgroup *mem;
1874 struct page_cgroup *pc;
1877 pc = lookup_page_cgroup(page);
1878 /* can happen at boot */
1884 ret = __mem_cgroup_try_charge(mm, gfp_mask, &mem, true, page);
1888 __mem_cgroup_commit_charge(mem, pc, ctype);
1892 int mem_cgroup_newpage_charge(struct page *page,
1893 struct mm_struct *mm, gfp_t gfp_mask)
1895 if (mem_cgroup_disabled())
1897 if (PageCompound(page))
1900 * If already mapped, we don't have to account.
1901 * If page cache, page->mapping has address_space.
1902 * But page->mapping may have out-of-use anon_vma pointer,
1903 * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
1906 if (page_mapped(page) || (page->mapping && !PageAnon(page)))
1910 return mem_cgroup_charge_common(page, mm, gfp_mask,
1911 MEM_CGROUP_CHARGE_TYPE_MAPPED, NULL);
1915 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
1916 enum charge_type ctype);
1918 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
1921 struct mem_cgroup *mem = NULL;
1924 if (mem_cgroup_disabled())
1926 if (PageCompound(page))
1929 * Corner case handling. This is called from add_to_page_cache()
1930 * in usual. But some FS (shmem) precharges this page before calling it
1931 * and call add_to_page_cache() with GFP_NOWAIT.
1933 * For GFP_NOWAIT case, the page may be pre-charged before calling
1934 * add_to_page_cache(). (See shmem.c) check it here and avoid to call
1935 * charge twice. (It works but has to pay a bit larger cost.)
1936 * And when the page is SwapCache, it should take swap information
1937 * into account. This is under lock_page() now.
1939 if (!(gfp_mask & __GFP_WAIT)) {
1940 struct page_cgroup *pc;
1943 pc = lookup_page_cgroup(page);
1946 lock_page_cgroup(pc);
1947 if (PageCgroupUsed(pc)) {
1948 unlock_page_cgroup(pc);
1951 unlock_page_cgroup(pc);
1954 if (unlikely(!mm && !mem))
1957 if (page_is_file_cache(page))
1958 return mem_cgroup_charge_common(page, mm, gfp_mask,
1959 MEM_CGROUP_CHARGE_TYPE_CACHE, NULL);
1962 if (PageSwapCache(page)) {
1963 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
1965 __mem_cgroup_commit_charge_swapin(page, mem,
1966 MEM_CGROUP_CHARGE_TYPE_SHMEM);
1968 ret = mem_cgroup_charge_common(page, mm, gfp_mask,
1969 MEM_CGROUP_CHARGE_TYPE_SHMEM, mem);
1975 * While swap-in, try_charge -> commit or cancel, the page is locked.
1976 * And when try_charge() successfully returns, one refcnt to memcg without
1977 * struct page_cgroup is acquired. This refcnt will be consumed by
1978 * "commit()" or removed by "cancel()"
1980 int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
1982 gfp_t mask, struct mem_cgroup **ptr)
1984 struct mem_cgroup *mem;
1987 if (mem_cgroup_disabled())
1990 if (!do_swap_account)
1993 * A racing thread's fault, or swapoff, may have already updated
1994 * the pte, and even removed page from swap cache: in those cases
1995 * do_swap_page()'s pte_same() test will fail; but there's also a
1996 * KSM case which does need to charge the page.
1998 if (!PageSwapCache(page))
2000 mem = try_get_mem_cgroup_from_page(page);
2004 ret = __mem_cgroup_try_charge(NULL, mask, ptr, true, page);
2005 /* drop extra refcnt from tryget */
2011 return __mem_cgroup_try_charge(mm, mask, ptr, true, page);
2015 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2016 enum charge_type ctype)
2018 struct page_cgroup *pc;
2020 if (mem_cgroup_disabled())
2024 cgroup_exclude_rmdir(&ptr->css);
2025 pc = lookup_page_cgroup(page);
2026 mem_cgroup_lru_del_before_commit_swapcache(page);
2027 __mem_cgroup_commit_charge(ptr, pc, ctype);
2028 mem_cgroup_lru_add_after_commit_swapcache(page);
2030 * Now swap is on-memory. This means this page may be
2031 * counted both as mem and swap....double count.
2032 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
2033 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
2034 * may call delete_from_swap_cache() before reach here.
2036 if (do_swap_account && PageSwapCache(page)) {
2037 swp_entry_t ent = {.val = page_private(page)};
2039 struct mem_cgroup *memcg;
2041 id = swap_cgroup_record(ent, 0);
2043 memcg = mem_cgroup_lookup(id);
2046 * This recorded memcg can be obsolete one. So, avoid
2047 * calling css_tryget
2049 if (!mem_cgroup_is_root(memcg))
2050 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
2051 mem_cgroup_swap_statistics(memcg, false);
2052 mem_cgroup_put(memcg);
2057 * At swapin, we may charge account against cgroup which has no tasks.
2058 * So, rmdir()->pre_destroy() can be called while we do this charge.
2059 * In that case, we need to call pre_destroy() again. check it here.
2061 cgroup_release_and_wakeup_rmdir(&ptr->css);
2064 void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
2066 __mem_cgroup_commit_charge_swapin(page, ptr,
2067 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2070 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *mem)
2072 if (mem_cgroup_disabled())
2076 mem_cgroup_cancel_charge(mem);
2080 __do_uncharge(struct mem_cgroup *mem, const enum charge_type ctype)
2082 struct memcg_batch_info *batch = NULL;
2083 bool uncharge_memsw = true;
2084 /* If swapout, usage of swap doesn't decrease */
2085 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2086 uncharge_memsw = false;
2088 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
2089 * In those cases, all pages freed continously can be expected to be in
2090 * the same cgroup and we have chance to coalesce uncharges.
2091 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
2092 * because we want to do uncharge as soon as possible.
2094 if (!current->memcg_batch.do_batch || test_thread_flag(TIF_MEMDIE))
2095 goto direct_uncharge;
2097 batch = ¤t->memcg_batch;
2099 * In usual, we do css_get() when we remember memcg pointer.
2100 * But in this case, we keep res->usage until end of a series of
2101 * uncharges. Then, it's ok to ignore memcg's refcnt.
2106 * In typical case, batch->memcg == mem. This means we can
2107 * merge a series of uncharges to an uncharge of res_counter.
2108 * If not, we uncharge res_counter ony by one.
2110 if (batch->memcg != mem)
2111 goto direct_uncharge;
2112 /* remember freed charge and uncharge it later */
2113 batch->bytes += PAGE_SIZE;
2115 batch->memsw_bytes += PAGE_SIZE;
2118 res_counter_uncharge(&mem->res, PAGE_SIZE);
2120 res_counter_uncharge(&mem->memsw, PAGE_SIZE);
2125 * uncharge if !page_mapped(page)
2127 static struct mem_cgroup *
2128 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
2130 struct page_cgroup *pc;
2131 struct mem_cgroup *mem = NULL;
2132 struct mem_cgroup_per_zone *mz;
2134 if (mem_cgroup_disabled())
2137 if (PageSwapCache(page))
2141 * Check if our page_cgroup is valid
2143 pc = lookup_page_cgroup(page);
2144 if (unlikely(!pc || !PageCgroupUsed(pc)))
2147 lock_page_cgroup(pc);
2149 mem = pc->mem_cgroup;
2151 if (!PageCgroupUsed(pc))
2155 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
2156 case MEM_CGROUP_CHARGE_TYPE_DROP:
2157 if (page_mapped(page))
2160 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
2161 if (!PageAnon(page)) { /* Shared memory */
2162 if (page->mapping && !page_is_file_cache(page))
2164 } else if (page_mapped(page)) /* Anon */
2171 if (!mem_cgroup_is_root(mem))
2172 __do_uncharge(mem, ctype);
2173 if (ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2174 mem_cgroup_swap_statistics(mem, true);
2175 mem_cgroup_charge_statistics(mem, pc, false);
2177 ClearPageCgroupUsed(pc);
2179 * pc->mem_cgroup is not cleared here. It will be accessed when it's
2180 * freed from LRU. This is safe because uncharged page is expected not
2181 * to be reused (freed soon). Exception is SwapCache, it's handled by
2182 * special functions.
2185 mz = page_cgroup_zoneinfo(pc);
2186 unlock_page_cgroup(pc);
2188 if (mem_cgroup_soft_limit_check(mem))
2189 mem_cgroup_update_tree(mem, page);
2190 if (mem_cgroup_threshold_check(mem))
2191 mem_cgroup_threshold(mem);
2192 /* at swapout, this memcg will be accessed to record to swap */
2193 if (ctype != MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2199 unlock_page_cgroup(pc);
2203 void mem_cgroup_uncharge_page(struct page *page)
2206 if (page_mapped(page))
2208 if (page->mapping && !PageAnon(page))
2210 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
2213 void mem_cgroup_uncharge_cache_page(struct page *page)
2215 VM_BUG_ON(page_mapped(page));
2216 VM_BUG_ON(page->mapping);
2217 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
2221 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
2222 * In that cases, pages are freed continuously and we can expect pages
2223 * are in the same memcg. All these calls itself limits the number of
2224 * pages freed at once, then uncharge_start/end() is called properly.
2225 * This may be called prural(2) times in a context,
2228 void mem_cgroup_uncharge_start(void)
2230 current->memcg_batch.do_batch++;
2231 /* We can do nest. */
2232 if (current->memcg_batch.do_batch == 1) {
2233 current->memcg_batch.memcg = NULL;
2234 current->memcg_batch.bytes = 0;
2235 current->memcg_batch.memsw_bytes = 0;
2239 void mem_cgroup_uncharge_end(void)
2241 struct memcg_batch_info *batch = ¤t->memcg_batch;
2243 if (!batch->do_batch)
2247 if (batch->do_batch) /* If stacked, do nothing. */
2253 * This "batch->memcg" is valid without any css_get/put etc...
2254 * bacause we hide charges behind us.
2257 res_counter_uncharge(&batch->memcg->res, batch->bytes);
2258 if (batch->memsw_bytes)
2259 res_counter_uncharge(&batch->memcg->memsw, batch->memsw_bytes);
2260 /* forget this pointer (for sanity check) */
2261 batch->memcg = NULL;
2266 * called after __delete_from_swap_cache() and drop "page" account.
2267 * memcg information is recorded to swap_cgroup of "ent"
2270 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
2272 struct mem_cgroup *memcg;
2273 int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
2275 if (!swapout) /* this was a swap cache but the swap is unused ! */
2276 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
2278 memcg = __mem_cgroup_uncharge_common(page, ctype);
2280 /* record memcg information */
2281 if (do_swap_account && swapout && memcg) {
2282 swap_cgroup_record(ent, css_id(&memcg->css));
2283 mem_cgroup_get(memcg);
2285 if (swapout && memcg)
2286 css_put(&memcg->css);
2290 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
2292 * called from swap_entry_free(). remove record in swap_cgroup and
2293 * uncharge "memsw" account.
2295 void mem_cgroup_uncharge_swap(swp_entry_t ent)
2297 struct mem_cgroup *memcg;
2300 if (!do_swap_account)
2303 id = swap_cgroup_record(ent, 0);
2305 memcg = mem_cgroup_lookup(id);
2308 * We uncharge this because swap is freed.
2309 * This memcg can be obsolete one. We avoid calling css_tryget
2311 if (!mem_cgroup_is_root(memcg))
2312 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
2313 mem_cgroup_swap_statistics(memcg, false);
2314 mem_cgroup_put(memcg);
2320 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
2321 * @entry: swap entry to be moved
2322 * @from: mem_cgroup which the entry is moved from
2323 * @to: mem_cgroup which the entry is moved to
2324 * @need_fixup: whether we should fixup res_counters and refcounts.
2326 * It succeeds only when the swap_cgroup's record for this entry is the same
2327 * as the mem_cgroup's id of @from.
2329 * Returns 0 on success, -EINVAL on failure.
2331 * The caller must have charged to @to, IOW, called res_counter_charge() about
2332 * both res and memsw, and called css_get().
2334 static int mem_cgroup_move_swap_account(swp_entry_t entry,
2335 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
2337 unsigned short old_id, new_id;
2339 old_id = css_id(&from->css);
2340 new_id = css_id(&to->css);
2342 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
2343 mem_cgroup_swap_statistics(from, false);
2344 mem_cgroup_swap_statistics(to, true);
2346 * This function is only called from task migration context now.
2347 * It postpones res_counter and refcount handling till the end
2348 * of task migration(mem_cgroup_clear_mc()) for performance
2349 * improvement. But we cannot postpone mem_cgroup_get(to)
2350 * because if the process that has been moved to @to does
2351 * swap-in, the refcount of @to might be decreased to 0.
2355 if (!mem_cgroup_is_root(from))
2356 res_counter_uncharge(&from->memsw, PAGE_SIZE);
2357 mem_cgroup_put(from);
2359 * we charged both to->res and to->memsw, so we should
2362 if (!mem_cgroup_is_root(to))
2363 res_counter_uncharge(&to->res, PAGE_SIZE);
2371 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
2372 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
2379 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
2382 int mem_cgroup_prepare_migration(struct page *page, struct mem_cgroup **ptr)
2384 struct page_cgroup *pc;
2385 struct mem_cgroup *mem = NULL;
2388 if (mem_cgroup_disabled())
2391 pc = lookup_page_cgroup(page);
2392 lock_page_cgroup(pc);
2393 if (PageCgroupUsed(pc)) {
2394 mem = pc->mem_cgroup;
2397 unlock_page_cgroup(pc);
2400 ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, &mem, false,
2408 /* remove redundant charge if migration failed*/
2409 void mem_cgroup_end_migration(struct mem_cgroup *mem,
2410 struct page *oldpage, struct page *newpage)
2412 struct page *target, *unused;
2413 struct page_cgroup *pc;
2414 enum charge_type ctype;
2418 cgroup_exclude_rmdir(&mem->css);
2419 /* at migration success, oldpage->mapping is NULL. */
2420 if (oldpage->mapping) {
2428 if (PageAnon(target))
2429 ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
2430 else if (page_is_file_cache(target))
2431 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
2433 ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
2435 /* unused page is not on radix-tree now. */
2437 __mem_cgroup_uncharge_common(unused, ctype);
2439 pc = lookup_page_cgroup(target);
2441 * __mem_cgroup_commit_charge() check PCG_USED bit of page_cgroup.
2442 * So, double-counting is effectively avoided.
2444 __mem_cgroup_commit_charge(mem, pc, ctype);
2447 * Both of oldpage and newpage are still under lock_page().
2448 * Then, we don't have to care about race in radix-tree.
2449 * But we have to be careful that this page is unmapped or not.
2451 * There is a case for !page_mapped(). At the start of
2452 * migration, oldpage was mapped. But now, it's zapped.
2453 * But we know *target* page is not freed/reused under us.
2454 * mem_cgroup_uncharge_page() does all necessary checks.
2456 if (ctype == MEM_CGROUP_CHARGE_TYPE_MAPPED)
2457 mem_cgroup_uncharge_page(target);
2459 * At migration, we may charge account against cgroup which has no tasks
2460 * So, rmdir()->pre_destroy() can be called while we do this charge.
2461 * In that case, we need to call pre_destroy() again. check it here.
2463 cgroup_release_and_wakeup_rmdir(&mem->css);
2467 * A call to try to shrink memory usage on charge failure at shmem's swapin.
2468 * Calling hierarchical_reclaim is not enough because we should update
2469 * last_oom_jiffies to prevent pagefault_out_of_memory from invoking global OOM.
2470 * Moreover considering hierarchy, we should reclaim from the mem_over_limit,
2471 * not from the memcg which this page would be charged to.
2472 * try_charge_swapin does all of these works properly.
2474 int mem_cgroup_shmem_charge_fallback(struct page *page,
2475 struct mm_struct *mm,
2478 struct mem_cgroup *mem = NULL;
2481 if (mem_cgroup_disabled())
2484 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
2486 mem_cgroup_cancel_charge_swapin(mem); /* it does !mem check */
2491 static DEFINE_MUTEX(set_limit_mutex);
2493 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
2494 unsigned long long val)
2499 int children = mem_cgroup_count_children(memcg);
2500 u64 curusage, oldusage;
2503 * For keeping hierarchical_reclaim simple, how long we should retry
2504 * is depends on callers. We set our retry-count to be function
2505 * of # of children which we should visit in this loop.
2507 retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
2509 oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
2511 while (retry_count) {
2512 if (signal_pending(current)) {
2517 * Rather than hide all in some function, I do this in
2518 * open coded manner. You see what this really does.
2519 * We have to guarantee mem->res.limit < mem->memsw.limit.
2521 mutex_lock(&set_limit_mutex);
2522 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
2523 if (memswlimit < val) {
2525 mutex_unlock(&set_limit_mutex);
2528 ret = res_counter_set_limit(&memcg->res, val);
2530 if (memswlimit == val)
2531 memcg->memsw_is_minimum = true;
2533 memcg->memsw_is_minimum = false;
2535 mutex_unlock(&set_limit_mutex);
2540 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
2541 MEM_CGROUP_RECLAIM_SHRINK);
2542 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
2543 /* Usage is reduced ? */
2544 if (curusage >= oldusage)
2547 oldusage = curusage;
2553 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
2554 unsigned long long val)
2557 u64 memlimit, oldusage, curusage;
2558 int children = mem_cgroup_count_children(memcg);
2561 /* see mem_cgroup_resize_res_limit */
2562 retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
2563 oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
2564 while (retry_count) {
2565 if (signal_pending(current)) {
2570 * Rather than hide all in some function, I do this in
2571 * open coded manner. You see what this really does.
2572 * We have to guarantee mem->res.limit < mem->memsw.limit.
2574 mutex_lock(&set_limit_mutex);
2575 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
2576 if (memlimit > val) {
2578 mutex_unlock(&set_limit_mutex);
2581 ret = res_counter_set_limit(&memcg->memsw, val);
2583 if (memlimit == val)
2584 memcg->memsw_is_minimum = true;
2586 memcg->memsw_is_minimum = false;
2588 mutex_unlock(&set_limit_mutex);
2593 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
2594 MEM_CGROUP_RECLAIM_NOSWAP |
2595 MEM_CGROUP_RECLAIM_SHRINK);
2596 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
2597 /* Usage is reduced ? */
2598 if (curusage >= oldusage)
2601 oldusage = curusage;
2606 unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
2607 gfp_t gfp_mask, int nid,
2610 unsigned long nr_reclaimed = 0;
2611 struct mem_cgroup_per_zone *mz, *next_mz = NULL;
2612 unsigned long reclaimed;
2614 struct mem_cgroup_tree_per_zone *mctz;
2615 unsigned long long excess;
2620 mctz = soft_limit_tree_node_zone(nid, zid);
2622 * This loop can run a while, specially if mem_cgroup's continuously
2623 * keep exceeding their soft limit and putting the system under
2630 mz = mem_cgroup_largest_soft_limit_node(mctz);
2634 reclaimed = mem_cgroup_hierarchical_reclaim(mz->mem, zone,
2636 MEM_CGROUP_RECLAIM_SOFT);
2637 nr_reclaimed += reclaimed;
2638 spin_lock(&mctz->lock);
2641 * If we failed to reclaim anything from this memory cgroup
2642 * it is time to move on to the next cgroup
2648 * Loop until we find yet another one.
2650 * By the time we get the soft_limit lock
2651 * again, someone might have aded the
2652 * group back on the RB tree. Iterate to
2653 * make sure we get a different mem.
2654 * mem_cgroup_largest_soft_limit_node returns
2655 * NULL if no other cgroup is present on
2659 __mem_cgroup_largest_soft_limit_node(mctz);
2660 if (next_mz == mz) {
2661 css_put(&next_mz->mem->css);
2663 } else /* next_mz == NULL or other memcg */
2667 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
2668 excess = res_counter_soft_limit_excess(&mz->mem->res);
2670 * One school of thought says that we should not add
2671 * back the node to the tree if reclaim returns 0.
2672 * But our reclaim could return 0, simply because due
2673 * to priority we are exposing a smaller subset of
2674 * memory to reclaim from. Consider this as a longer
2677 /* If excess == 0, no tree ops */
2678 __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
2679 spin_unlock(&mctz->lock);
2680 css_put(&mz->mem->css);
2683 * Could not reclaim anything and there are no more
2684 * mem cgroups to try or we seem to be looping without
2685 * reclaiming anything.
2687 if (!nr_reclaimed &&
2689 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
2691 } while (!nr_reclaimed);
2693 css_put(&next_mz->mem->css);
2694 return nr_reclaimed;
2698 * This routine traverse page_cgroup in given list and drop them all.
2699 * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
2701 static int mem_cgroup_force_empty_list(struct mem_cgroup *mem,
2702 int node, int zid, enum lru_list lru)
2705 struct mem_cgroup_per_zone *mz;
2706 struct page_cgroup *pc, *busy;
2707 unsigned long flags, loop;
2708 struct list_head *list;
2711 zone = &NODE_DATA(node)->node_zones[zid];
2712 mz = mem_cgroup_zoneinfo(mem, node, zid);
2713 list = &mz->lists[lru];
2715 loop = MEM_CGROUP_ZSTAT(mz, lru);
2716 /* give some margin against EBUSY etc...*/
2721 spin_lock_irqsave(&zone->lru_lock, flags);
2722 if (list_empty(list)) {
2723 spin_unlock_irqrestore(&zone->lru_lock, flags);
2726 pc = list_entry(list->prev, struct page_cgroup, lru);
2728 list_move(&pc->lru, list);
2730 spin_unlock_irqrestore(&zone->lru_lock, flags);
2733 spin_unlock_irqrestore(&zone->lru_lock, flags);
2735 ret = mem_cgroup_move_parent(pc, mem, GFP_KERNEL);
2739 if (ret == -EBUSY || ret == -EINVAL) {
2740 /* found lock contention or "pc" is obsolete. */
2747 if (!ret && !list_empty(list))
2753 * make mem_cgroup's charge to be 0 if there is no task.
2754 * This enables deleting this mem_cgroup.
2756 static int mem_cgroup_force_empty(struct mem_cgroup *mem, bool free_all)
2759 int node, zid, shrink;
2760 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
2761 struct cgroup *cgrp = mem->css.cgroup;
2766 /* should free all ? */
2772 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
2775 if (signal_pending(current))
2777 /* This is for making all *used* pages to be on LRU. */
2778 lru_add_drain_all();
2779 drain_all_stock_sync();
2781 for_each_node_state(node, N_HIGH_MEMORY) {
2782 for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
2785 ret = mem_cgroup_force_empty_list(mem,
2794 /* it seems parent cgroup doesn't have enough mem */
2798 /* "ret" should also be checked to ensure all lists are empty. */
2799 } while (mem->res.usage > 0 || ret);
2805 /* returns EBUSY if there is a task or if we come here twice. */
2806 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
2810 /* we call try-to-free pages for make this cgroup empty */
2811 lru_add_drain_all();
2812 /* try to free all pages in this cgroup */
2814 while (nr_retries && mem->res.usage > 0) {
2817 if (signal_pending(current)) {
2821 progress = try_to_free_mem_cgroup_pages(mem, GFP_KERNEL,
2822 false, get_swappiness(mem));
2825 /* maybe some writeback is necessary */
2826 congestion_wait(BLK_RW_ASYNC, HZ/10);
2831 /* try move_account...there may be some *locked* pages. */
2835 int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
2837 return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
2841 static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
2843 return mem_cgroup_from_cont(cont)->use_hierarchy;
2846 static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
2850 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
2851 struct cgroup *parent = cont->parent;
2852 struct mem_cgroup *parent_mem = NULL;
2855 parent_mem = mem_cgroup_from_cont(parent);
2859 * If parent's use_hierarchy is set, we can't make any modifications
2860 * in the child subtrees. If it is unset, then the change can
2861 * occur, provided the current cgroup has no children.
2863 * For the root cgroup, parent_mem is NULL, we allow value to be
2864 * set if there are no children.
2866 if ((!parent_mem || !parent_mem->use_hierarchy) &&
2867 (val == 1 || val == 0)) {
2868 if (list_empty(&cont->children))
2869 mem->use_hierarchy = val;
2879 struct mem_cgroup_idx_data {
2881 enum mem_cgroup_stat_index idx;
2885 mem_cgroup_get_idx_stat(struct mem_cgroup *mem, void *data)
2887 struct mem_cgroup_idx_data *d = data;
2888 d->val += mem_cgroup_read_stat(&mem->stat, d->idx);
2893 mem_cgroup_get_recursive_idx_stat(struct mem_cgroup *mem,
2894 enum mem_cgroup_stat_index idx, s64 *val)
2896 struct mem_cgroup_idx_data d;
2899 mem_cgroup_walk_tree(mem, &d, mem_cgroup_get_idx_stat);
2903 static inline u64 mem_cgroup_usage(struct mem_cgroup *mem, bool swap)
2907 if (!mem_cgroup_is_root(mem)) {
2909 return res_counter_read_u64(&mem->res, RES_USAGE);
2911 return res_counter_read_u64(&mem->memsw, RES_USAGE);
2914 mem_cgroup_get_recursive_idx_stat(mem, MEM_CGROUP_STAT_CACHE, &idx_val);
2916 mem_cgroup_get_recursive_idx_stat(mem, MEM_CGROUP_STAT_RSS, &idx_val);
2920 mem_cgroup_get_recursive_idx_stat(mem,
2921 MEM_CGROUP_STAT_SWAPOUT, &idx_val);
2925 return val << PAGE_SHIFT;
2928 static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
2930 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
2934 type = MEMFILE_TYPE(cft->private);
2935 name = MEMFILE_ATTR(cft->private);
2938 if (name == RES_USAGE)
2939 val = mem_cgroup_usage(mem, false);
2941 val = res_counter_read_u64(&mem->res, name);
2944 if (name == RES_USAGE)
2945 val = mem_cgroup_usage(mem, true);
2947 val = res_counter_read_u64(&mem->memsw, name);
2956 * The user of this function is...
2959 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
2962 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
2964 unsigned long long val;
2967 type = MEMFILE_TYPE(cft->private);
2968 name = MEMFILE_ATTR(cft->private);
2971 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
2975 /* This function does all necessary parse...reuse it */
2976 ret = res_counter_memparse_write_strategy(buffer, &val);
2980 ret = mem_cgroup_resize_limit(memcg, val);
2982 ret = mem_cgroup_resize_memsw_limit(memcg, val);
2984 case RES_SOFT_LIMIT:
2985 ret = res_counter_memparse_write_strategy(buffer, &val);
2989 * For memsw, soft limits are hard to implement in terms
2990 * of semantics, for now, we support soft limits for
2991 * control without swap
2994 ret = res_counter_set_soft_limit(&memcg->res, val);
2999 ret = -EINVAL; /* should be BUG() ? */
3005 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
3006 unsigned long long *mem_limit, unsigned long long *memsw_limit)
3008 struct cgroup *cgroup;
3009 unsigned long long min_limit, min_memsw_limit, tmp;
3011 min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3012 min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3013 cgroup = memcg->css.cgroup;
3014 if (!memcg->use_hierarchy)
3017 while (cgroup->parent) {
3018 cgroup = cgroup->parent;
3019 memcg = mem_cgroup_from_cont(cgroup);
3020 if (!memcg->use_hierarchy)
3022 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
3023 min_limit = min(min_limit, tmp);
3024 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3025 min_memsw_limit = min(min_memsw_limit, tmp);
3028 *mem_limit = min_limit;
3029 *memsw_limit = min_memsw_limit;
3033 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
3035 struct mem_cgroup *mem;
3038 mem = mem_cgroup_from_cont(cont);
3039 type = MEMFILE_TYPE(event);
3040 name = MEMFILE_ATTR(event);
3044 res_counter_reset_max(&mem->res);
3046 res_counter_reset_max(&mem->memsw);
3050 res_counter_reset_failcnt(&mem->res);
3052 res_counter_reset_failcnt(&mem->memsw);
3059 static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
3062 return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
3066 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
3067 struct cftype *cft, u64 val)
3069 struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
3071 if (val >= (1 << NR_MOVE_TYPE))
3074 * We check this value several times in both in can_attach() and
3075 * attach(), so we need cgroup lock to prevent this value from being
3079 mem->move_charge_at_immigrate = val;
3085 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
3086 struct cftype *cft, u64 val)
3093 /* For read statistics */
3109 struct mcs_total_stat {
3110 s64 stat[NR_MCS_STAT];
3116 } memcg_stat_strings[NR_MCS_STAT] = {
3117 {"cache", "total_cache"},
3118 {"rss", "total_rss"},
3119 {"mapped_file", "total_mapped_file"},
3120 {"pgpgin", "total_pgpgin"},
3121 {"pgpgout", "total_pgpgout"},
3122 {"swap", "total_swap"},
3123 {"inactive_anon", "total_inactive_anon"},
3124 {"active_anon", "total_active_anon"},
3125 {"inactive_file", "total_inactive_file"},
3126 {"active_file", "total_active_file"},
3127 {"unevictable", "total_unevictable"}
3131 static int mem_cgroup_get_local_stat(struct mem_cgroup *mem, void *data)
3133 struct mcs_total_stat *s = data;
3137 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_CACHE);
3138 s->stat[MCS_CACHE] += val * PAGE_SIZE;
3139 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_RSS);
3140 s->stat[MCS_RSS] += val * PAGE_SIZE;
3141 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_FILE_MAPPED);
3142 s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE;
3143 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_PGPGIN_COUNT);
3144 s->stat[MCS_PGPGIN] += val;
3145 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_PGPGOUT_COUNT);
3146 s->stat[MCS_PGPGOUT] += val;
3147 if (do_swap_account) {
3148 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_SWAPOUT);
3149 s->stat[MCS_SWAP] += val * PAGE_SIZE;
3153 val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_ANON);
3154 s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
3155 val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_ANON);
3156 s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
3157 val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_FILE);
3158 s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
3159 val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_FILE);
3160 s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
3161 val = mem_cgroup_get_local_zonestat(mem, LRU_UNEVICTABLE);
3162 s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
3167 mem_cgroup_get_total_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
3169 mem_cgroup_walk_tree(mem, s, mem_cgroup_get_local_stat);
3172 static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
3173 struct cgroup_map_cb *cb)
3175 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
3176 struct mcs_total_stat mystat;
3179 memset(&mystat, 0, sizeof(mystat));
3180 mem_cgroup_get_local_stat(mem_cont, &mystat);
3182 for (i = 0; i < NR_MCS_STAT; i++) {
3183 if (i == MCS_SWAP && !do_swap_account)
3185 cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
3188 /* Hierarchical information */
3190 unsigned long long limit, memsw_limit;
3191 memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
3192 cb->fill(cb, "hierarchical_memory_limit", limit);
3193 if (do_swap_account)
3194 cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
3197 memset(&mystat, 0, sizeof(mystat));
3198 mem_cgroup_get_total_stat(mem_cont, &mystat);
3199 for (i = 0; i < NR_MCS_STAT; i++) {
3200 if (i == MCS_SWAP && !do_swap_account)
3202 cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
3205 #ifdef CONFIG_DEBUG_VM
3206 cb->fill(cb, "inactive_ratio", calc_inactive_ratio(mem_cont, NULL));
3210 struct mem_cgroup_per_zone *mz;
3211 unsigned long recent_rotated[2] = {0, 0};
3212 unsigned long recent_scanned[2] = {0, 0};
3214 for_each_online_node(nid)
3215 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
3216 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
3218 recent_rotated[0] +=
3219 mz->reclaim_stat.recent_rotated[0];
3220 recent_rotated[1] +=
3221 mz->reclaim_stat.recent_rotated[1];
3222 recent_scanned[0] +=
3223 mz->reclaim_stat.recent_scanned[0];
3224 recent_scanned[1] +=
3225 mz->reclaim_stat.recent_scanned[1];
3227 cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
3228 cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
3229 cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
3230 cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
3237 static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
3239 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3241 return get_swappiness(memcg);
3244 static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
3247 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3248 struct mem_cgroup *parent;
3253 if (cgrp->parent == NULL)
3256 parent = mem_cgroup_from_cont(cgrp->parent);
3260 /* If under hierarchy, only empty-root can set this value */
3261 if ((parent->use_hierarchy) ||
3262 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
3267 spin_lock(&memcg->reclaim_param_lock);
3268 memcg->swappiness = val;
3269 spin_unlock(&memcg->reclaim_param_lock);
3276 static bool mem_cgroup_threshold_check(struct mem_cgroup *mem)
3281 struct mem_cgroup_stat_cpu *cpustat;
3284 cpustat = &mem->stat.cpustat[cpu];
3285 val = __mem_cgroup_stat_read_local(cpustat, MEM_CGROUP_STAT_THRESHOLDS);
3286 if (unlikely(val < 0)) {
3287 __mem_cgroup_stat_set_safe(cpustat, MEM_CGROUP_STAT_THRESHOLDS,
3288 THRESHOLDS_EVENTS_THRESH);
3295 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
3297 struct mem_cgroup_threshold_ary *t;
3303 t = rcu_dereference(memcg->thresholds);
3305 t = rcu_dereference(memcg->memsw_thresholds);
3310 usage = mem_cgroup_usage(memcg, swap);
3313 * current_threshold points to threshold just below usage.
3314 * If it's not true, a threshold was crossed after last
3315 * call of __mem_cgroup_threshold().
3317 i = atomic_read(&t->current_threshold);
3320 * Iterate backward over array of thresholds starting from
3321 * current_threshold and check if a threshold is crossed.
3322 * If none of thresholds below usage is crossed, we read
3323 * only one element of the array here.
3325 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
3326 eventfd_signal(t->entries[i].eventfd, 1);
3328 /* i = current_threshold + 1 */
3332 * Iterate forward over array of thresholds starting from
3333 * current_threshold+1 and check if a threshold is crossed.
3334 * If none of thresholds above usage is crossed, we read
3335 * only one element of the array here.
3337 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
3338 eventfd_signal(t->entries[i].eventfd, 1);
3340 /* Update current_threshold */
3341 atomic_set(&t->current_threshold, i - 1);
3346 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
3348 __mem_cgroup_threshold(memcg, false);
3349 if (do_swap_account)
3350 __mem_cgroup_threshold(memcg, true);
3353 static int compare_thresholds(const void *a, const void *b)
3355 const struct mem_cgroup_threshold *_a = a;
3356 const struct mem_cgroup_threshold *_b = b;
3358 return _a->threshold - _b->threshold;
3361 static int mem_cgroup_register_event(struct cgroup *cgrp, struct cftype *cft,
3362 struct eventfd_ctx *eventfd, const char *args)
3364 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3365 struct mem_cgroup_threshold_ary *thresholds, *thresholds_new;
3366 int type = MEMFILE_TYPE(cft->private);
3367 u64 threshold, usage;
3371 ret = res_counter_memparse_write_strategy(args, &threshold);
3375 mutex_lock(&memcg->thresholds_lock);
3377 thresholds = memcg->thresholds;
3378 else if (type == _MEMSWAP)
3379 thresholds = memcg->memsw_thresholds;
3383 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
3385 /* Check if a threshold crossed before adding a new one */
3387 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
3390 size = thresholds->size + 1;
3394 /* Allocate memory for new array of thresholds */
3395 thresholds_new = kmalloc(sizeof(*thresholds_new) +
3396 size * sizeof(struct mem_cgroup_threshold),
3398 if (!thresholds_new) {
3402 thresholds_new->size = size;
3404 /* Copy thresholds (if any) to new array */
3406 memcpy(thresholds_new->entries, thresholds->entries,
3408 sizeof(struct mem_cgroup_threshold));
3409 /* Add new threshold */
3410 thresholds_new->entries[size - 1].eventfd = eventfd;
3411 thresholds_new->entries[size - 1].threshold = threshold;
3413 /* Sort thresholds. Registering of new threshold isn't time-critical */
3414 sort(thresholds_new->entries, size,
3415 sizeof(struct mem_cgroup_threshold),
3416 compare_thresholds, NULL);
3418 /* Find current threshold */
3419 atomic_set(&thresholds_new->current_threshold, -1);
3420 for (i = 0; i < size; i++) {
3421 if (thresholds_new->entries[i].threshold < usage) {
3423 * thresholds_new->current_threshold will not be used
3424 * until rcu_assign_pointer(), so it's safe to increment
3427 atomic_inc(&thresholds_new->current_threshold);
3432 * We need to increment refcnt to be sure that all thresholds
3433 * will be unregistered before calling __mem_cgroup_free()
3435 mem_cgroup_get(memcg);
3438 rcu_assign_pointer(memcg->thresholds, thresholds_new);
3440 rcu_assign_pointer(memcg->memsw_thresholds, thresholds_new);
3442 /* To be sure that nobody uses thresholds before freeing it */
3447 mutex_unlock(&memcg->thresholds_lock);
3452 static int mem_cgroup_unregister_event(struct cgroup *cgrp, struct cftype *cft,
3453 struct eventfd_ctx *eventfd)
3455 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3456 struct mem_cgroup_threshold_ary *thresholds, *thresholds_new;
3457 int type = MEMFILE_TYPE(cft->private);
3462 mutex_lock(&memcg->thresholds_lock);
3464 thresholds = memcg->thresholds;
3465 else if (type == _MEMSWAP)
3466 thresholds = memcg->memsw_thresholds;
3471 * Something went wrong if we trying to unregister a threshold
3472 * if we don't have thresholds
3474 BUG_ON(!thresholds);
3476 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
3478 /* Check if a threshold crossed before removing */
3479 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
3481 /* Calculate new number of threshold */
3482 for (i = 0; i < thresholds->size; i++) {
3483 if (thresholds->entries[i].eventfd != eventfd)
3487 /* Set thresholds array to NULL if we don't have thresholds */
3489 thresholds_new = NULL;
3493 /* Allocate memory for new array of thresholds */
3494 thresholds_new = kmalloc(sizeof(*thresholds_new) +
3495 size * sizeof(struct mem_cgroup_threshold),
3497 if (!thresholds_new) {
3501 thresholds_new->size = size;
3503 /* Copy thresholds and find current threshold */
3504 atomic_set(&thresholds_new->current_threshold, -1);
3505 for (i = 0, j = 0; i < thresholds->size; i++) {
3506 if (thresholds->entries[i].eventfd == eventfd)
3509 thresholds_new->entries[j] = thresholds->entries[i];
3510 if (thresholds_new->entries[j].threshold < usage) {
3512 * thresholds_new->current_threshold will not be used
3513 * until rcu_assign_pointer(), so it's safe to increment
3516 atomic_inc(&thresholds_new->current_threshold);
3523 rcu_assign_pointer(memcg->thresholds, thresholds_new);
3525 rcu_assign_pointer(memcg->memsw_thresholds, thresholds_new);
3527 /* To be sure that nobody uses thresholds before freeing it */
3530 for (i = 0; i < thresholds->size - size; i++)
3531 mem_cgroup_put(memcg);
3535 mutex_unlock(&memcg->thresholds_lock);
3540 static struct cftype mem_cgroup_files[] = {
3542 .name = "usage_in_bytes",
3543 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
3544 .read_u64 = mem_cgroup_read,
3545 .register_event = mem_cgroup_register_event,
3546 .unregister_event = mem_cgroup_unregister_event,
3549 .name = "max_usage_in_bytes",
3550 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
3551 .trigger = mem_cgroup_reset,
3552 .read_u64 = mem_cgroup_read,
3555 .name = "limit_in_bytes",
3556 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
3557 .write_string = mem_cgroup_write,
3558 .read_u64 = mem_cgroup_read,
3561 .name = "soft_limit_in_bytes",
3562 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
3563 .write_string = mem_cgroup_write,
3564 .read_u64 = mem_cgroup_read,
3568 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
3569 .trigger = mem_cgroup_reset,
3570 .read_u64 = mem_cgroup_read,
3574 .read_map = mem_control_stat_show,
3577 .name = "force_empty",
3578 .trigger = mem_cgroup_force_empty_write,
3581 .name = "use_hierarchy",
3582 .write_u64 = mem_cgroup_hierarchy_write,
3583 .read_u64 = mem_cgroup_hierarchy_read,
3586 .name = "swappiness",
3587 .read_u64 = mem_cgroup_swappiness_read,
3588 .write_u64 = mem_cgroup_swappiness_write,
3591 .name = "move_charge_at_immigrate",
3592 .read_u64 = mem_cgroup_move_charge_read,
3593 .write_u64 = mem_cgroup_move_charge_write,
3597 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3598 static struct cftype memsw_cgroup_files[] = {
3600 .name = "memsw.usage_in_bytes",
3601 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
3602 .read_u64 = mem_cgroup_read,
3603 .register_event = mem_cgroup_register_event,
3604 .unregister_event = mem_cgroup_unregister_event,
3607 .name = "memsw.max_usage_in_bytes",
3608 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
3609 .trigger = mem_cgroup_reset,
3610 .read_u64 = mem_cgroup_read,
3613 .name = "memsw.limit_in_bytes",
3614 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
3615 .write_string = mem_cgroup_write,
3616 .read_u64 = mem_cgroup_read,
3619 .name = "memsw.failcnt",
3620 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
3621 .trigger = mem_cgroup_reset,
3622 .read_u64 = mem_cgroup_read,
3626 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
3628 if (!do_swap_account)
3630 return cgroup_add_files(cont, ss, memsw_cgroup_files,
3631 ARRAY_SIZE(memsw_cgroup_files));
3634 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
3640 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
3642 struct mem_cgroup_per_node *pn;
3643 struct mem_cgroup_per_zone *mz;
3645 int zone, tmp = node;
3647 * This routine is called against possible nodes.
3648 * But it's BUG to call kmalloc() against offline node.
3650 * TODO: this routine can waste much memory for nodes which will
3651 * never be onlined. It's better to use memory hotplug callback
3654 if (!node_state(node, N_NORMAL_MEMORY))
3656 pn = kmalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
3660 mem->info.nodeinfo[node] = pn;
3661 memset(pn, 0, sizeof(*pn));
3663 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3664 mz = &pn->zoneinfo[zone];
3666 INIT_LIST_HEAD(&mz->lists[l]);
3667 mz->usage_in_excess = 0;
3668 mz->on_tree = false;
3674 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
3676 kfree(mem->info.nodeinfo[node]);
3679 static int mem_cgroup_size(void)
3681 int cpustat_size = nr_cpu_ids * sizeof(struct mem_cgroup_stat_cpu);
3682 return sizeof(struct mem_cgroup) + cpustat_size;
3685 static struct mem_cgroup *mem_cgroup_alloc(void)
3687 struct mem_cgroup *mem;
3688 int size = mem_cgroup_size();
3690 if (size < PAGE_SIZE)
3691 mem = kmalloc(size, GFP_KERNEL);
3693 mem = vmalloc(size);
3696 memset(mem, 0, size);
3701 * At destroying mem_cgroup, references from swap_cgroup can remain.
3702 * (scanning all at force_empty is too costly...)
3704 * Instead of clearing all references at force_empty, we remember
3705 * the number of reference from swap_cgroup and free mem_cgroup when
3706 * it goes down to 0.
3708 * Removal of cgroup itself succeeds regardless of refs from swap.
3711 static void __mem_cgroup_free(struct mem_cgroup *mem)
3715 mem_cgroup_remove_from_trees(mem);
3716 free_css_id(&mem_cgroup_subsys, &mem->css);
3718 for_each_node_state(node, N_POSSIBLE)
3719 free_mem_cgroup_per_zone_info(mem, node);
3721 if (mem_cgroup_size() < PAGE_SIZE)
3727 static void mem_cgroup_get(struct mem_cgroup *mem)
3729 atomic_inc(&mem->refcnt);
3732 static void __mem_cgroup_put(struct mem_cgroup *mem, int count)
3734 if (atomic_sub_and_test(count, &mem->refcnt)) {
3735 struct mem_cgroup *parent = parent_mem_cgroup(mem);
3736 __mem_cgroup_free(mem);
3738 mem_cgroup_put(parent);
3742 static void mem_cgroup_put(struct mem_cgroup *mem)
3744 __mem_cgroup_put(mem, 1);
3748 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
3750 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem)
3752 if (!mem->res.parent)
3754 return mem_cgroup_from_res_counter(mem->res.parent, res);
3757 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3758 static void __init enable_swap_cgroup(void)
3760 if (!mem_cgroup_disabled() && really_do_swap_account)
3761 do_swap_account = 1;
3764 static void __init enable_swap_cgroup(void)
3769 static int mem_cgroup_soft_limit_tree_init(void)
3771 struct mem_cgroup_tree_per_node *rtpn;
3772 struct mem_cgroup_tree_per_zone *rtpz;
3773 int tmp, node, zone;
3775 for_each_node_state(node, N_POSSIBLE) {
3777 if (!node_state(node, N_NORMAL_MEMORY))
3779 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
3783 soft_limit_tree.rb_tree_per_node[node] = rtpn;
3785 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3786 rtpz = &rtpn->rb_tree_per_zone[zone];
3787 rtpz->rb_root = RB_ROOT;
3788 spin_lock_init(&rtpz->lock);
3794 static struct cgroup_subsys_state * __ref
3795 mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
3797 struct mem_cgroup *mem, *parent;
3798 long error = -ENOMEM;
3801 mem = mem_cgroup_alloc();
3803 return ERR_PTR(error);
3805 for_each_node_state(node, N_POSSIBLE)
3806 if (alloc_mem_cgroup_per_zone_info(mem, node))
3810 if (cont->parent == NULL) {
3812 enable_swap_cgroup();
3814 root_mem_cgroup = mem;
3815 if (mem_cgroup_soft_limit_tree_init())
3817 for_each_possible_cpu(cpu) {
3818 struct memcg_stock_pcp *stock =
3819 &per_cpu(memcg_stock, cpu);
3820 INIT_WORK(&stock->work, drain_local_stock);
3822 hotcpu_notifier(memcg_stock_cpu_callback, 0);
3824 parent = mem_cgroup_from_cont(cont->parent);
3825 mem->use_hierarchy = parent->use_hierarchy;
3828 if (parent && parent->use_hierarchy) {
3829 res_counter_init(&mem->res, &parent->res);
3830 res_counter_init(&mem->memsw, &parent->memsw);
3832 * We increment refcnt of the parent to ensure that we can
3833 * safely access it on res_counter_charge/uncharge.
3834 * This refcnt will be decremented when freeing this
3835 * mem_cgroup(see mem_cgroup_put).
3837 mem_cgroup_get(parent);
3839 res_counter_init(&mem->res, NULL);
3840 res_counter_init(&mem->memsw, NULL);
3842 mem->last_scanned_child = 0;
3843 spin_lock_init(&mem->reclaim_param_lock);
3846 mem->swappiness = get_swappiness(parent);
3847 atomic_set(&mem->refcnt, 1);
3848 mem->move_charge_at_immigrate = 0;
3849 mutex_init(&mem->thresholds_lock);
3852 __mem_cgroup_free(mem);
3853 root_mem_cgroup = NULL;
3854 return ERR_PTR(error);
3857 static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
3858 struct cgroup *cont)
3860 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
3862 return mem_cgroup_force_empty(mem, false);
3865 static void mem_cgroup_destroy(struct cgroup_subsys *ss,
3866 struct cgroup *cont)
3868 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
3870 mem_cgroup_put(mem);
3873 static int mem_cgroup_populate(struct cgroup_subsys *ss,
3874 struct cgroup *cont)
3878 ret = cgroup_add_files(cont, ss, mem_cgroup_files,
3879 ARRAY_SIZE(mem_cgroup_files));
3882 ret = register_memsw_files(cont, ss);
3887 /* Handlers for move charge at task migration. */
3888 #define PRECHARGE_COUNT_AT_ONCE 256
3889 static int mem_cgroup_do_precharge(unsigned long count)
3892 int batch_count = PRECHARGE_COUNT_AT_ONCE;
3893 struct mem_cgroup *mem = mc.to;
3895 if (mem_cgroup_is_root(mem)) {
3896 mc.precharge += count;
3897 /* we don't need css_get for root */
3900 /* try to charge at once */
3902 struct res_counter *dummy;
3904 * "mem" cannot be under rmdir() because we've already checked
3905 * by cgroup_lock_live_cgroup() that it is not removed and we
3906 * are still under the same cgroup_mutex. So we can postpone
3909 if (res_counter_charge(&mem->res, PAGE_SIZE * count, &dummy))
3911 if (do_swap_account && res_counter_charge(&mem->memsw,
3912 PAGE_SIZE * count, &dummy)) {
3913 res_counter_uncharge(&mem->res, PAGE_SIZE * count);
3916 mc.precharge += count;
3917 VM_BUG_ON(test_bit(CSS_ROOT, &mem->css.flags));
3918 WARN_ON_ONCE(count > INT_MAX);
3919 __css_get(&mem->css, (int)count);
3923 /* fall back to one by one charge */
3925 if (signal_pending(current)) {
3929 if (!batch_count--) {
3930 batch_count = PRECHARGE_COUNT_AT_ONCE;
3933 ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, &mem,
3936 /* mem_cgroup_clear_mc() will do uncharge later */
3942 #else /* !CONFIG_MMU */
3943 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
3944 struct cgroup *cgroup,
3945 struct task_struct *p,
3950 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
3951 struct cgroup *cgroup,
3952 struct task_struct *p,
3956 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
3957 struct cgroup *cont,
3958 struct cgroup *old_cont,
3959 struct task_struct *p,
3966 * is_target_pte_for_mc - check a pte whether it is valid for move charge
3967 * @vma: the vma the pte to be checked belongs
3968 * @addr: the address corresponding to the pte to be checked
3969 * @ptent: the pte to be checked
3970 * @target: the pointer the target page or swap ent will be stored(can be NULL)
3973 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
3974 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
3975 * move charge. if @target is not NULL, the page is stored in target->page
3976 * with extra refcnt got(Callers should handle it).
3977 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
3978 * target for charge migration. if @target is not NULL, the entry is stored
3981 * Called with pte lock held.
3988 enum mc_target_type {
3989 MC_TARGET_NONE, /* not used */
3994 static int is_target_pte_for_mc(struct vm_area_struct *vma,
3995 unsigned long addr, pte_t ptent, union mc_target *target)
3997 struct page *page = NULL;
3998 struct page_cgroup *pc;
4000 swp_entry_t ent = { .val = 0 };
4001 int usage_count = 0;
4002 bool move_anon = test_bit(MOVE_CHARGE_TYPE_ANON,
4003 &mc.to->move_charge_at_immigrate);
4005 if (!pte_present(ptent)) {
4006 /* TODO: handle swap of shmes/tmpfs */
4007 if (pte_none(ptent) || pte_file(ptent))
4009 else if (is_swap_pte(ptent)) {
4010 ent = pte_to_swp_entry(ptent);
4011 if (!move_anon || non_swap_entry(ent))
4013 usage_count = mem_cgroup_count_swap_user(ent, &page);
4016 page = vm_normal_page(vma, addr, ptent);
4017 if (!page || !page_mapped(page))
4020 * TODO: We don't move charges of file(including shmem/tmpfs)
4023 if (!move_anon || !PageAnon(page))
4025 if (!get_page_unless_zero(page))
4027 usage_count = page_mapcount(page);
4029 if (usage_count > 1) {
4031 * TODO: We don't move charges of shared(used by multiple
4032 * processes) pages for now.
4039 pc = lookup_page_cgroup(page);
4041 * Do only loose check w/o page_cgroup lock.
4042 * mem_cgroup_move_account() checks the pc is valid or not under
4045 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
4046 ret = MC_TARGET_PAGE;
4048 target->page = page;
4050 if (!ret || !target)
4054 if (ent.val && do_swap_account && !ret &&
4055 css_id(&mc.from->css) == lookup_swap_cgroup(ent)) {
4056 ret = MC_TARGET_SWAP;
4063 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
4064 unsigned long addr, unsigned long end,
4065 struct mm_walk *walk)
4067 struct vm_area_struct *vma = walk->private;
4071 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
4072 for (; addr != end; pte++, addr += PAGE_SIZE)
4073 if (is_target_pte_for_mc(vma, addr, *pte, NULL))
4074 mc.precharge++; /* increment precharge temporarily */
4075 pte_unmap_unlock(pte - 1, ptl);
4081 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
4083 unsigned long precharge;
4084 struct vm_area_struct *vma;
4086 down_read(&mm->mmap_sem);
4087 for (vma = mm->mmap; vma; vma = vma->vm_next) {
4088 struct mm_walk mem_cgroup_count_precharge_walk = {
4089 .pmd_entry = mem_cgroup_count_precharge_pte_range,
4093 if (is_vm_hugetlb_page(vma))
4095 /* TODO: We don't move charges of shmem/tmpfs pages for now. */
4096 if (vma->vm_flags & VM_SHARED)
4098 walk_page_range(vma->vm_start, vma->vm_end,
4099 &mem_cgroup_count_precharge_walk);
4101 up_read(&mm->mmap_sem);
4103 precharge = mc.precharge;
4109 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
4111 return mem_cgroup_do_precharge(mem_cgroup_count_precharge(mm));
4114 static void mem_cgroup_clear_mc(void)
4116 /* we must uncharge all the leftover precharges from mc.to */
4118 __mem_cgroup_cancel_charge(mc.to, mc.precharge);
4122 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
4123 * we must uncharge here.
4125 if (mc.moved_charge) {
4126 __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
4127 mc.moved_charge = 0;
4129 /* we must fixup refcnts and charges */
4130 if (mc.moved_swap) {
4131 WARN_ON_ONCE(mc.moved_swap > INT_MAX);
4132 /* uncharge swap account from the old cgroup */
4133 if (!mem_cgroup_is_root(mc.from))
4134 res_counter_uncharge(&mc.from->memsw,
4135 PAGE_SIZE * mc.moved_swap);
4136 __mem_cgroup_put(mc.from, mc.moved_swap);
4138 if (!mem_cgroup_is_root(mc.to)) {
4140 * we charged both to->res and to->memsw, so we should
4143 res_counter_uncharge(&mc.to->res,
4144 PAGE_SIZE * mc.moved_swap);
4145 VM_BUG_ON(test_bit(CSS_ROOT, &mc.to->css.flags));
4146 __css_put(&mc.to->css, mc.moved_swap);
4148 /* we've already done mem_cgroup_get(mc.to) */
4154 mc.moving_task = NULL;
4155 wake_up_all(&mc.waitq);
4158 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
4159 struct cgroup *cgroup,
4160 struct task_struct *p,
4164 struct mem_cgroup *mem = mem_cgroup_from_cont(cgroup);
4166 if (mem->move_charge_at_immigrate) {
4167 struct mm_struct *mm;
4168 struct mem_cgroup *from = mem_cgroup_from_task(p);
4170 VM_BUG_ON(from == mem);
4172 mm = get_task_mm(p);
4175 /* We move charges only when we move a owner of the mm */
4176 if (mm->owner == p) {
4179 VM_BUG_ON(mc.precharge);
4180 VM_BUG_ON(mc.moved_charge);
4181 VM_BUG_ON(mc.moved_swap);
4182 VM_BUG_ON(mc.moving_task);
4186 mc.moved_charge = 0;
4188 mc.moving_task = current;
4190 ret = mem_cgroup_precharge_mc(mm);
4192 mem_cgroup_clear_mc();
4199 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
4200 struct cgroup *cgroup,
4201 struct task_struct *p,
4204 mem_cgroup_clear_mc();
4207 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
4208 unsigned long addr, unsigned long end,
4209 struct mm_walk *walk)
4212 struct vm_area_struct *vma = walk->private;
4217 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
4218 for (; addr != end; addr += PAGE_SIZE) {
4219 pte_t ptent = *(pte++);
4220 union mc_target target;
4223 struct page_cgroup *pc;
4229 type = is_target_pte_for_mc(vma, addr, ptent, &target);
4231 case MC_TARGET_PAGE:
4233 if (isolate_lru_page(page))
4235 pc = lookup_page_cgroup(page);
4236 if (!mem_cgroup_move_account(pc,
4237 mc.from, mc.to, false)) {
4239 /* we uncharge from mc.from later. */
4242 putback_lru_page(page);
4243 put: /* is_target_pte_for_mc() gets the page */
4246 case MC_TARGET_SWAP:
4248 if (!mem_cgroup_move_swap_account(ent,
4249 mc.from, mc.to, false)) {
4251 /* we fixup refcnts and charges later. */
4259 pte_unmap_unlock(pte - 1, ptl);
4264 * We have consumed all precharges we got in can_attach().
4265 * We try charge one by one, but don't do any additional
4266 * charges to mc.to if we have failed in charge once in attach()
4269 ret = mem_cgroup_do_precharge(1);
4277 static void mem_cgroup_move_charge(struct mm_struct *mm)
4279 struct vm_area_struct *vma;
4281 lru_add_drain_all();
4282 down_read(&mm->mmap_sem);
4283 for (vma = mm->mmap; vma; vma = vma->vm_next) {
4285 struct mm_walk mem_cgroup_move_charge_walk = {
4286 .pmd_entry = mem_cgroup_move_charge_pte_range,
4290 if (is_vm_hugetlb_page(vma))
4292 /* TODO: We don't move charges of shmem/tmpfs pages for now. */
4293 if (vma->vm_flags & VM_SHARED)
4295 ret = walk_page_range(vma->vm_start, vma->vm_end,
4296 &mem_cgroup_move_charge_walk);
4299 * means we have consumed all precharges and failed in
4300 * doing additional charge. Just abandon here.
4304 up_read(&mm->mmap_sem);
4307 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
4308 struct cgroup *cont,
4309 struct cgroup *old_cont,
4310 struct task_struct *p,
4313 struct mm_struct *mm;
4316 /* no need to move charge */
4319 mm = get_task_mm(p);
4321 mem_cgroup_move_charge(mm);
4324 mem_cgroup_clear_mc();
4327 struct cgroup_subsys mem_cgroup_subsys = {
4329 .subsys_id = mem_cgroup_subsys_id,
4330 .create = mem_cgroup_create,
4331 .pre_destroy = mem_cgroup_pre_destroy,
4332 .destroy = mem_cgroup_destroy,
4333 .populate = mem_cgroup_populate,
4334 .can_attach = mem_cgroup_can_attach,
4335 .cancel_attach = mem_cgroup_cancel_attach,
4336 .attach = mem_cgroup_move_task,
4341 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4343 static int __init disable_swap_account(char *s)
4345 really_do_swap_account = 0;
4348 __setup("noswapaccount", disable_swap_account);