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 #include <trace/events/vmscan.h>
56 struct cgroup_subsys mem_cgroup_subsys __read_mostly
;
57 #define MEM_CGROUP_RECLAIM_RETRIES 5
58 struct mem_cgroup
*root_mem_cgroup __read_mostly
;
60 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
61 /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
62 int do_swap_account __read_mostly
;
63 static int really_do_swap_account __initdata
= 1; /* for remember boot option*/
65 #define do_swap_account (0)
69 * Per memcg event counter is incremented at every pagein/pageout. This counter
70 * is used for trigger some periodic events. This is straightforward and better
71 * than using jiffies etc. to handle periodic memcg event.
73 * These values will be used as !((event) & ((1 <<(thresh)) - 1))
75 #define THRESHOLDS_EVENTS_THRESH (7) /* once in 128 */
76 #define SOFTLIMIT_EVENTS_THRESH (10) /* once in 1024 */
79 * Statistics for memory cgroup.
81 enum mem_cgroup_stat_index
{
83 * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
85 MEM_CGROUP_STAT_CACHE
, /* # of pages charged as cache */
86 MEM_CGROUP_STAT_RSS
, /* # of pages charged as anon rss */
87 MEM_CGROUP_STAT_FILE_MAPPED
, /* # of pages charged as file rss */
88 MEM_CGROUP_STAT_PGPGIN_COUNT
, /* # of pages paged in */
89 MEM_CGROUP_STAT_PGPGOUT_COUNT
, /* # of pages paged out */
90 MEM_CGROUP_STAT_SWAPOUT
, /* # of pages, swapped out */
91 MEM_CGROUP_EVENTS
, /* incremented at every pagein/pageout */
93 MEM_CGROUP_STAT_NSTATS
,
96 struct mem_cgroup_stat_cpu
{
97 s64 count
[MEM_CGROUP_STAT_NSTATS
];
101 * per-zone information in memory controller.
103 struct mem_cgroup_per_zone
{
105 * spin_lock to protect the per cgroup LRU
107 struct list_head lists
[NR_LRU_LISTS
];
108 unsigned long count
[NR_LRU_LISTS
];
110 struct zone_reclaim_stat reclaim_stat
;
111 struct rb_node tree_node
; /* RB tree node */
112 unsigned long long usage_in_excess
;/* Set to the value by which */
113 /* the soft limit is exceeded*/
115 struct mem_cgroup
*mem
; /* Back pointer, we cannot */
116 /* use container_of */
118 /* Macro for accessing counter */
119 #define MEM_CGROUP_ZSTAT(mz, idx) ((mz)->count[(idx)])
121 struct mem_cgroup_per_node
{
122 struct mem_cgroup_per_zone zoneinfo
[MAX_NR_ZONES
];
125 struct mem_cgroup_lru_info
{
126 struct mem_cgroup_per_node
*nodeinfo
[MAX_NUMNODES
];
130 * Cgroups above their limits are maintained in a RB-Tree, independent of
131 * their hierarchy representation
134 struct mem_cgroup_tree_per_zone
{
135 struct rb_root rb_root
;
139 struct mem_cgroup_tree_per_node
{
140 struct mem_cgroup_tree_per_zone rb_tree_per_zone
[MAX_NR_ZONES
];
143 struct mem_cgroup_tree
{
144 struct mem_cgroup_tree_per_node
*rb_tree_per_node
[MAX_NUMNODES
];
147 static struct mem_cgroup_tree soft_limit_tree __read_mostly
;
149 struct mem_cgroup_threshold
{
150 struct eventfd_ctx
*eventfd
;
155 struct mem_cgroup_threshold_ary
{
156 /* An array index points to threshold just below usage. */
157 int current_threshold
;
158 /* Size of entries[] */
160 /* Array of thresholds */
161 struct mem_cgroup_threshold entries
[0];
164 struct mem_cgroup_thresholds
{
165 /* Primary thresholds array */
166 struct mem_cgroup_threshold_ary
*primary
;
168 * Spare threshold array.
169 * This is needed to make mem_cgroup_unregister_event() "never fail".
170 * It must be able to store at least primary->size - 1 entries.
172 struct mem_cgroup_threshold_ary
*spare
;
176 struct mem_cgroup_eventfd_list
{
177 struct list_head list
;
178 struct eventfd_ctx
*eventfd
;
181 static void mem_cgroup_threshold(struct mem_cgroup
*mem
);
182 static void mem_cgroup_oom_notify(struct mem_cgroup
*mem
);
185 * The memory controller data structure. The memory controller controls both
186 * page cache and RSS per cgroup. We would eventually like to provide
187 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
188 * to help the administrator determine what knobs to tune.
190 * TODO: Add a water mark for the memory controller. Reclaim will begin when
191 * we hit the water mark. May be even add a low water mark, such that
192 * no reclaim occurs from a cgroup at it's low water mark, this is
193 * a feature that will be implemented much later in the future.
196 struct cgroup_subsys_state css
;
198 * the counter to account for memory usage
200 struct res_counter res
;
202 * the counter to account for mem+swap usage.
204 struct res_counter memsw
;
206 * Per cgroup active and inactive list, similar to the
207 * per zone LRU lists.
209 struct mem_cgroup_lru_info info
;
212 protect against reclaim related member.
214 spinlock_t reclaim_param_lock
;
217 * While reclaiming in a hierarchy, we cache the last child we
220 int last_scanned_child
;
222 * Should the accounting and control be hierarchical, per subtree?
228 unsigned int swappiness
;
229 /* OOM-Killer disable */
230 int oom_kill_disable
;
232 /* set when res.limit == memsw.limit */
233 bool memsw_is_minimum
;
235 /* protect arrays of thresholds */
236 struct mutex thresholds_lock
;
238 /* thresholds for memory usage. RCU-protected */
239 struct mem_cgroup_thresholds thresholds
;
241 /* thresholds for mem+swap usage. RCU-protected */
242 struct mem_cgroup_thresholds memsw_thresholds
;
244 /* For oom notifier event fd */
245 struct list_head oom_notify
;
248 * Should we move charges of a task when a task is moved into this
249 * mem_cgroup ? And what type of charges should we move ?
251 unsigned long move_charge_at_immigrate
;
255 struct mem_cgroup_stat_cpu
*stat
;
258 /* Stuffs for move charges at task migration. */
260 * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a
261 * left-shifted bitmap of these types.
264 MOVE_CHARGE_TYPE_ANON
, /* private anonymous page and swap of it */
265 MOVE_CHARGE_TYPE_FILE
, /* file page(including tmpfs) and swap of it */
269 /* "mc" and its members are protected by cgroup_mutex */
270 static struct move_charge_struct
{
271 spinlock_t lock
; /* for from, to, moving_task */
272 struct mem_cgroup
*from
;
273 struct mem_cgroup
*to
;
274 unsigned long precharge
;
275 unsigned long moved_charge
;
276 unsigned long moved_swap
;
277 struct task_struct
*moving_task
; /* a task moving charges */
278 wait_queue_head_t waitq
; /* a waitq for other context */
280 .lock
= __SPIN_LOCK_UNLOCKED(mc
.lock
),
281 .waitq
= __WAIT_QUEUE_HEAD_INITIALIZER(mc
.waitq
),
284 static bool move_anon(void)
286 return test_bit(MOVE_CHARGE_TYPE_ANON
,
287 &mc
.to
->move_charge_at_immigrate
);
290 static bool move_file(void)
292 return test_bit(MOVE_CHARGE_TYPE_FILE
,
293 &mc
.to
->move_charge_at_immigrate
);
297 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
298 * limit reclaim to prevent infinite loops, if they ever occur.
300 #define MEM_CGROUP_MAX_RECLAIM_LOOPS (100)
301 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS (2)
304 MEM_CGROUP_CHARGE_TYPE_CACHE
= 0,
305 MEM_CGROUP_CHARGE_TYPE_MAPPED
,
306 MEM_CGROUP_CHARGE_TYPE_SHMEM
, /* used by page migration of shmem */
307 MEM_CGROUP_CHARGE_TYPE_FORCE
, /* used by force_empty */
308 MEM_CGROUP_CHARGE_TYPE_SWAPOUT
, /* for accounting swapcache */
309 MEM_CGROUP_CHARGE_TYPE_DROP
, /* a page was unused swap cache */
313 /* only for here (for easy reading.) */
314 #define PCGF_CACHE (1UL << PCG_CACHE)
315 #define PCGF_USED (1UL << PCG_USED)
316 #define PCGF_LOCK (1UL << PCG_LOCK)
317 /* Not used, but added here for completeness */
318 #define PCGF_ACCT (1UL << PCG_ACCT)
320 /* for encoding cft->private value on file */
323 #define _OOM_TYPE (2)
324 #define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val))
325 #define MEMFILE_TYPE(val) (((val) >> 16) & 0xffff)
326 #define MEMFILE_ATTR(val) ((val) & 0xffff)
327 /* Used for OOM nofiier */
328 #define OOM_CONTROL (0)
331 * Reclaim flags for mem_cgroup_hierarchical_reclaim
333 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
334 #define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
335 #define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
336 #define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
337 #define MEM_CGROUP_RECLAIM_SOFT_BIT 0x2
338 #define MEM_CGROUP_RECLAIM_SOFT (1 << MEM_CGROUP_RECLAIM_SOFT_BIT)
340 static void mem_cgroup_get(struct mem_cgroup
*mem
);
341 static void mem_cgroup_put(struct mem_cgroup
*mem
);
342 static struct mem_cgroup
*parent_mem_cgroup(struct mem_cgroup
*mem
);
343 static void drain_all_stock_async(void);
345 static struct mem_cgroup_per_zone
*
346 mem_cgroup_zoneinfo(struct mem_cgroup
*mem
, int nid
, int zid
)
348 return &mem
->info
.nodeinfo
[nid
]->zoneinfo
[zid
];
351 struct cgroup_subsys_state
*mem_cgroup_css(struct mem_cgroup
*mem
)
356 static struct mem_cgroup_per_zone
*
357 page_cgroup_zoneinfo(struct page_cgroup
*pc
)
359 struct mem_cgroup
*mem
= pc
->mem_cgroup
;
360 int nid
= page_cgroup_nid(pc
);
361 int zid
= page_cgroup_zid(pc
);
366 return mem_cgroup_zoneinfo(mem
, nid
, zid
);
369 static struct mem_cgroup_tree_per_zone
*
370 soft_limit_tree_node_zone(int nid
, int zid
)
372 return &soft_limit_tree
.rb_tree_per_node
[nid
]->rb_tree_per_zone
[zid
];
375 static struct mem_cgroup_tree_per_zone
*
376 soft_limit_tree_from_page(struct page
*page
)
378 int nid
= page_to_nid(page
);
379 int zid
= page_zonenum(page
);
381 return &soft_limit_tree
.rb_tree_per_node
[nid
]->rb_tree_per_zone
[zid
];
385 __mem_cgroup_insert_exceeded(struct mem_cgroup
*mem
,
386 struct mem_cgroup_per_zone
*mz
,
387 struct mem_cgroup_tree_per_zone
*mctz
,
388 unsigned long long new_usage_in_excess
)
390 struct rb_node
**p
= &mctz
->rb_root
.rb_node
;
391 struct rb_node
*parent
= NULL
;
392 struct mem_cgroup_per_zone
*mz_node
;
397 mz
->usage_in_excess
= new_usage_in_excess
;
398 if (!mz
->usage_in_excess
)
402 mz_node
= rb_entry(parent
, struct mem_cgroup_per_zone
,
404 if (mz
->usage_in_excess
< mz_node
->usage_in_excess
)
407 * We can't avoid mem cgroups that are over their soft
408 * limit by the same amount
410 else if (mz
->usage_in_excess
>= mz_node
->usage_in_excess
)
413 rb_link_node(&mz
->tree_node
, parent
, p
);
414 rb_insert_color(&mz
->tree_node
, &mctz
->rb_root
);
419 __mem_cgroup_remove_exceeded(struct mem_cgroup
*mem
,
420 struct mem_cgroup_per_zone
*mz
,
421 struct mem_cgroup_tree_per_zone
*mctz
)
425 rb_erase(&mz
->tree_node
, &mctz
->rb_root
);
430 mem_cgroup_remove_exceeded(struct mem_cgroup
*mem
,
431 struct mem_cgroup_per_zone
*mz
,
432 struct mem_cgroup_tree_per_zone
*mctz
)
434 spin_lock(&mctz
->lock
);
435 __mem_cgroup_remove_exceeded(mem
, mz
, mctz
);
436 spin_unlock(&mctz
->lock
);
440 static void mem_cgroup_update_tree(struct mem_cgroup
*mem
, struct page
*page
)
442 unsigned long long excess
;
443 struct mem_cgroup_per_zone
*mz
;
444 struct mem_cgroup_tree_per_zone
*mctz
;
445 int nid
= page_to_nid(page
);
446 int zid
= page_zonenum(page
);
447 mctz
= soft_limit_tree_from_page(page
);
450 * Necessary to update all ancestors when hierarchy is used.
451 * because their event counter is not touched.
453 for (; mem
; mem
= parent_mem_cgroup(mem
)) {
454 mz
= mem_cgroup_zoneinfo(mem
, nid
, zid
);
455 excess
= res_counter_soft_limit_excess(&mem
->res
);
457 * We have to update the tree if mz is on RB-tree or
458 * mem is over its softlimit.
460 if (excess
|| mz
->on_tree
) {
461 spin_lock(&mctz
->lock
);
462 /* if on-tree, remove it */
464 __mem_cgroup_remove_exceeded(mem
, mz
, mctz
);
466 * Insert again. mz->usage_in_excess will be updated.
467 * If excess is 0, no tree ops.
469 __mem_cgroup_insert_exceeded(mem
, mz
, mctz
, excess
);
470 spin_unlock(&mctz
->lock
);
475 static void mem_cgroup_remove_from_trees(struct mem_cgroup
*mem
)
478 struct mem_cgroup_per_zone
*mz
;
479 struct mem_cgroup_tree_per_zone
*mctz
;
481 for_each_node_state(node
, N_POSSIBLE
) {
482 for (zone
= 0; zone
< MAX_NR_ZONES
; zone
++) {
483 mz
= mem_cgroup_zoneinfo(mem
, node
, zone
);
484 mctz
= soft_limit_tree_node_zone(node
, zone
);
485 mem_cgroup_remove_exceeded(mem
, mz
, mctz
);
490 static inline unsigned long mem_cgroup_get_excess(struct mem_cgroup
*mem
)
492 return res_counter_soft_limit_excess(&mem
->res
) >> PAGE_SHIFT
;
495 static struct mem_cgroup_per_zone
*
496 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone
*mctz
)
498 struct rb_node
*rightmost
= NULL
;
499 struct mem_cgroup_per_zone
*mz
;
503 rightmost
= rb_last(&mctz
->rb_root
);
505 goto done
; /* Nothing to reclaim from */
507 mz
= rb_entry(rightmost
, struct mem_cgroup_per_zone
, tree_node
);
509 * Remove the node now but someone else can add it back,
510 * we will to add it back at the end of reclaim to its correct
511 * position in the tree.
513 __mem_cgroup_remove_exceeded(mz
->mem
, mz
, mctz
);
514 if (!res_counter_soft_limit_excess(&mz
->mem
->res
) ||
515 !css_tryget(&mz
->mem
->css
))
521 static struct mem_cgroup_per_zone
*
522 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone
*mctz
)
524 struct mem_cgroup_per_zone
*mz
;
526 spin_lock(&mctz
->lock
);
527 mz
= __mem_cgroup_largest_soft_limit_node(mctz
);
528 spin_unlock(&mctz
->lock
);
532 static s64
mem_cgroup_read_stat(struct mem_cgroup
*mem
,
533 enum mem_cgroup_stat_index idx
)
538 for_each_possible_cpu(cpu
)
539 val
+= per_cpu(mem
->stat
->count
[idx
], cpu
);
543 static s64
mem_cgroup_local_usage(struct mem_cgroup
*mem
)
547 ret
= mem_cgroup_read_stat(mem
, MEM_CGROUP_STAT_RSS
);
548 ret
+= mem_cgroup_read_stat(mem
, MEM_CGROUP_STAT_CACHE
);
552 static void mem_cgroup_swap_statistics(struct mem_cgroup
*mem
,
555 int val
= (charge
) ? 1 : -1;
556 this_cpu_add(mem
->stat
->count
[MEM_CGROUP_STAT_SWAPOUT
], val
);
559 static void mem_cgroup_charge_statistics(struct mem_cgroup
*mem
,
560 struct page_cgroup
*pc
,
563 int val
= (charge
) ? 1 : -1;
567 if (PageCgroupCache(pc
))
568 __this_cpu_add(mem
->stat
->count
[MEM_CGROUP_STAT_CACHE
], val
);
570 __this_cpu_add(mem
->stat
->count
[MEM_CGROUP_STAT_RSS
], val
);
573 __this_cpu_inc(mem
->stat
->count
[MEM_CGROUP_STAT_PGPGIN_COUNT
]);
575 __this_cpu_inc(mem
->stat
->count
[MEM_CGROUP_STAT_PGPGOUT_COUNT
]);
576 __this_cpu_inc(mem
->stat
->count
[MEM_CGROUP_EVENTS
]);
581 static unsigned long mem_cgroup_get_local_zonestat(struct mem_cgroup
*mem
,
585 struct mem_cgroup_per_zone
*mz
;
588 for_each_online_node(nid
)
589 for (zid
= 0; zid
< MAX_NR_ZONES
; zid
++) {
590 mz
= mem_cgroup_zoneinfo(mem
, nid
, zid
);
591 total
+= MEM_CGROUP_ZSTAT(mz
, idx
);
596 static bool __memcg_event_check(struct mem_cgroup
*mem
, int event_mask_shift
)
600 val
= this_cpu_read(mem
->stat
->count
[MEM_CGROUP_EVENTS
]);
602 return !(val
& ((1 << event_mask_shift
) - 1));
606 * Check events in order.
609 static void memcg_check_events(struct mem_cgroup
*mem
, struct page
*page
)
611 /* threshold event is triggered in finer grain than soft limit */
612 if (unlikely(__memcg_event_check(mem
, THRESHOLDS_EVENTS_THRESH
))) {
613 mem_cgroup_threshold(mem
);
614 if (unlikely(__memcg_event_check(mem
, SOFTLIMIT_EVENTS_THRESH
)))
615 mem_cgroup_update_tree(mem
, page
);
619 static struct mem_cgroup
*mem_cgroup_from_cont(struct cgroup
*cont
)
621 return container_of(cgroup_subsys_state(cont
,
622 mem_cgroup_subsys_id
), struct mem_cgroup
,
626 struct mem_cgroup
*mem_cgroup_from_task(struct task_struct
*p
)
629 * mm_update_next_owner() may clear mm->owner to NULL
630 * if it races with swapoff, page migration, etc.
631 * So this can be called with p == NULL.
636 return container_of(task_subsys_state(p
, mem_cgroup_subsys_id
),
637 struct mem_cgroup
, css
);
640 static struct mem_cgroup
*try_get_mem_cgroup_from_mm(struct mm_struct
*mm
)
642 struct mem_cgroup
*mem
= NULL
;
647 * Because we have no locks, mm->owner's may be being moved to other
648 * cgroup. We use css_tryget() here even if this looks
649 * pessimistic (rather than adding locks here).
653 mem
= mem_cgroup_from_task(rcu_dereference(mm
->owner
));
656 } while (!css_tryget(&mem
->css
));
662 * Call callback function against all cgroup under hierarchy tree.
664 static int mem_cgroup_walk_tree(struct mem_cgroup
*root
, void *data
,
665 int (*func
)(struct mem_cgroup
*, void *))
667 int found
, ret
, nextid
;
668 struct cgroup_subsys_state
*css
;
669 struct mem_cgroup
*mem
;
671 if (!root
->use_hierarchy
)
672 return (*func
)(root
, data
);
680 css
= css_get_next(&mem_cgroup_subsys
, nextid
, &root
->css
,
682 if (css
&& css_tryget(css
))
683 mem
= container_of(css
, struct mem_cgroup
, css
);
687 ret
= (*func
)(mem
, data
);
691 } while (!ret
&& css
);
696 static inline bool mem_cgroup_is_root(struct mem_cgroup
*mem
)
698 return (mem
== root_mem_cgroup
);
702 * Following LRU functions are allowed to be used without PCG_LOCK.
703 * Operations are called by routine of global LRU independently from memcg.
704 * What we have to take care of here is validness of pc->mem_cgroup.
706 * Changes to pc->mem_cgroup happens when
709 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
710 * It is added to LRU before charge.
711 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
712 * When moving account, the page is not on LRU. It's isolated.
715 void mem_cgroup_del_lru_list(struct page
*page
, enum lru_list lru
)
717 struct page_cgroup
*pc
;
718 struct mem_cgroup_per_zone
*mz
;
720 if (mem_cgroup_disabled())
722 pc
= lookup_page_cgroup(page
);
723 /* can happen while we handle swapcache. */
724 if (!TestClearPageCgroupAcctLRU(pc
))
726 VM_BUG_ON(!pc
->mem_cgroup
);
728 * We don't check PCG_USED bit. It's cleared when the "page" is finally
729 * removed from global LRU.
731 mz
= page_cgroup_zoneinfo(pc
);
732 MEM_CGROUP_ZSTAT(mz
, lru
) -= 1;
733 if (mem_cgroup_is_root(pc
->mem_cgroup
))
735 VM_BUG_ON(list_empty(&pc
->lru
));
736 list_del_init(&pc
->lru
);
740 void mem_cgroup_del_lru(struct page
*page
)
742 mem_cgroup_del_lru_list(page
, page_lru(page
));
745 void mem_cgroup_rotate_lru_list(struct page
*page
, enum lru_list lru
)
747 struct mem_cgroup_per_zone
*mz
;
748 struct page_cgroup
*pc
;
750 if (mem_cgroup_disabled())
753 pc
= lookup_page_cgroup(page
);
755 * Used bit is set without atomic ops but after smp_wmb().
756 * For making pc->mem_cgroup visible, insert smp_rmb() here.
759 /* unused or root page is not rotated. */
760 if (!PageCgroupUsed(pc
) || mem_cgroup_is_root(pc
->mem_cgroup
))
762 mz
= page_cgroup_zoneinfo(pc
);
763 list_move(&pc
->lru
, &mz
->lists
[lru
]);
766 void mem_cgroup_add_lru_list(struct page
*page
, enum lru_list lru
)
768 struct page_cgroup
*pc
;
769 struct mem_cgroup_per_zone
*mz
;
771 if (mem_cgroup_disabled())
773 pc
= lookup_page_cgroup(page
);
774 VM_BUG_ON(PageCgroupAcctLRU(pc
));
776 * Used bit is set without atomic ops but after smp_wmb().
777 * For making pc->mem_cgroup visible, insert smp_rmb() here.
780 if (!PageCgroupUsed(pc
))
783 mz
= page_cgroup_zoneinfo(pc
);
784 MEM_CGROUP_ZSTAT(mz
, lru
) += 1;
785 SetPageCgroupAcctLRU(pc
);
786 if (mem_cgroup_is_root(pc
->mem_cgroup
))
788 list_add(&pc
->lru
, &mz
->lists
[lru
]);
792 * At handling SwapCache, pc->mem_cgroup may be changed while it's linked to
793 * lru because the page may.be reused after it's fully uncharged (because of
794 * SwapCache behavior).To handle that, unlink page_cgroup from LRU when charge
795 * it again. This function is only used to charge SwapCache. It's done under
796 * lock_page and expected that zone->lru_lock is never held.
798 static void mem_cgroup_lru_del_before_commit_swapcache(struct page
*page
)
801 struct zone
*zone
= page_zone(page
);
802 struct page_cgroup
*pc
= lookup_page_cgroup(page
);
804 spin_lock_irqsave(&zone
->lru_lock
, flags
);
806 * Forget old LRU when this page_cgroup is *not* used. This Used bit
807 * is guarded by lock_page() because the page is SwapCache.
809 if (!PageCgroupUsed(pc
))
810 mem_cgroup_del_lru_list(page
, page_lru(page
));
811 spin_unlock_irqrestore(&zone
->lru_lock
, flags
);
814 static void mem_cgroup_lru_add_after_commit_swapcache(struct page
*page
)
817 struct zone
*zone
= page_zone(page
);
818 struct page_cgroup
*pc
= lookup_page_cgroup(page
);
820 spin_lock_irqsave(&zone
->lru_lock
, flags
);
821 /* link when the page is linked to LRU but page_cgroup isn't */
822 if (PageLRU(page
) && !PageCgroupAcctLRU(pc
))
823 mem_cgroup_add_lru_list(page
, page_lru(page
));
824 spin_unlock_irqrestore(&zone
->lru_lock
, flags
);
828 void mem_cgroup_move_lists(struct page
*page
,
829 enum lru_list from
, enum lru_list to
)
831 if (mem_cgroup_disabled())
833 mem_cgroup_del_lru_list(page
, from
);
834 mem_cgroup_add_lru_list(page
, to
);
837 int task_in_mem_cgroup(struct task_struct
*task
, const struct mem_cgroup
*mem
)
840 struct mem_cgroup
*curr
= NULL
;
844 curr
= try_get_mem_cgroup_from_mm(task
->mm
);
850 * We should check use_hierarchy of "mem" not "curr". Because checking
851 * use_hierarchy of "curr" here make this function true if hierarchy is
852 * enabled in "curr" and "curr" is a child of "mem" in *cgroup*
853 * hierarchy(even if use_hierarchy is disabled in "mem").
855 if (mem
->use_hierarchy
)
856 ret
= css_is_ancestor(&curr
->css
, &mem
->css
);
863 static int calc_inactive_ratio(struct mem_cgroup
*memcg
, unsigned long *present_pages
)
865 unsigned long active
;
866 unsigned long inactive
;
868 unsigned long inactive_ratio
;
870 inactive
= mem_cgroup_get_local_zonestat(memcg
, LRU_INACTIVE_ANON
);
871 active
= mem_cgroup_get_local_zonestat(memcg
, LRU_ACTIVE_ANON
);
873 gb
= (inactive
+ active
) >> (30 - PAGE_SHIFT
);
875 inactive_ratio
= int_sqrt(10 * gb
);
880 present_pages
[0] = inactive
;
881 present_pages
[1] = active
;
884 return inactive_ratio
;
887 int mem_cgroup_inactive_anon_is_low(struct mem_cgroup
*memcg
)
889 unsigned long active
;
890 unsigned long inactive
;
891 unsigned long present_pages
[2];
892 unsigned long inactive_ratio
;
894 inactive_ratio
= calc_inactive_ratio(memcg
, present_pages
);
896 inactive
= present_pages
[0];
897 active
= present_pages
[1];
899 if (inactive
* inactive_ratio
< active
)
905 int mem_cgroup_inactive_file_is_low(struct mem_cgroup
*memcg
)
907 unsigned long active
;
908 unsigned long inactive
;
910 inactive
= mem_cgroup_get_local_zonestat(memcg
, LRU_INACTIVE_FILE
);
911 active
= mem_cgroup_get_local_zonestat(memcg
, LRU_ACTIVE_FILE
);
913 return (active
> inactive
);
916 unsigned long mem_cgroup_zone_nr_pages(struct mem_cgroup
*memcg
,
920 int nid
= zone
->zone_pgdat
->node_id
;
921 int zid
= zone_idx(zone
);
922 struct mem_cgroup_per_zone
*mz
= mem_cgroup_zoneinfo(memcg
, nid
, zid
);
924 return MEM_CGROUP_ZSTAT(mz
, lru
);
927 struct zone_reclaim_stat
*mem_cgroup_get_reclaim_stat(struct mem_cgroup
*memcg
,
930 int nid
= zone
->zone_pgdat
->node_id
;
931 int zid
= zone_idx(zone
);
932 struct mem_cgroup_per_zone
*mz
= mem_cgroup_zoneinfo(memcg
, nid
, zid
);
934 return &mz
->reclaim_stat
;
937 struct zone_reclaim_stat
*
938 mem_cgroup_get_reclaim_stat_from_page(struct page
*page
)
940 struct page_cgroup
*pc
;
941 struct mem_cgroup_per_zone
*mz
;
943 if (mem_cgroup_disabled())
946 pc
= lookup_page_cgroup(page
);
948 * Used bit is set without atomic ops but after smp_wmb().
949 * For making pc->mem_cgroup visible, insert smp_rmb() here.
952 if (!PageCgroupUsed(pc
))
955 mz
= page_cgroup_zoneinfo(pc
);
959 return &mz
->reclaim_stat
;
962 unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan
,
963 struct list_head
*dst
,
964 unsigned long *scanned
, int order
,
965 int mode
, struct zone
*z
,
966 struct mem_cgroup
*mem_cont
,
967 int active
, int file
)
969 unsigned long nr_taken
= 0;
973 struct list_head
*src
;
974 struct page_cgroup
*pc
, *tmp
;
975 int nid
= z
->zone_pgdat
->node_id
;
976 int zid
= zone_idx(z
);
977 struct mem_cgroup_per_zone
*mz
;
978 int lru
= LRU_FILE
* file
+ active
;
982 mz
= mem_cgroup_zoneinfo(mem_cont
, nid
, zid
);
983 src
= &mz
->lists
[lru
];
986 list_for_each_entry_safe_reverse(pc
, tmp
, src
, lru
) {
987 if (scan
>= nr_to_scan
)
991 if (unlikely(!PageCgroupUsed(pc
)))
993 if (unlikely(!PageLRU(page
)))
997 ret
= __isolate_lru_page(page
, mode
, file
);
1000 list_move(&page
->lru
, dst
);
1001 mem_cgroup_del_lru(page
);
1005 /* we don't affect global LRU but rotate in our LRU */
1006 mem_cgroup_rotate_lru_list(page
, page_lru(page
));
1015 trace_mm_vmscan_memcg_isolate(0, nr_to_scan
, scan
, nr_taken
,
1021 #define mem_cgroup_from_res_counter(counter, member) \
1022 container_of(counter, struct mem_cgroup, member)
1024 static bool mem_cgroup_check_under_limit(struct mem_cgroup
*mem
)
1026 if (do_swap_account
) {
1027 if (res_counter_check_under_limit(&mem
->res
) &&
1028 res_counter_check_under_limit(&mem
->memsw
))
1031 if (res_counter_check_under_limit(&mem
->res
))
1036 static unsigned int get_swappiness(struct mem_cgroup
*memcg
)
1038 struct cgroup
*cgrp
= memcg
->css
.cgroup
;
1039 unsigned int swappiness
;
1042 if (cgrp
->parent
== NULL
)
1043 return vm_swappiness
;
1045 spin_lock(&memcg
->reclaim_param_lock
);
1046 swappiness
= memcg
->swappiness
;
1047 spin_unlock(&memcg
->reclaim_param_lock
);
1052 /* A routine for testing mem is not under move_account */
1054 static bool mem_cgroup_under_move(struct mem_cgroup
*mem
)
1056 struct mem_cgroup
*from
;
1057 struct mem_cgroup
*to
;
1060 * Unlike task_move routines, we access mc.to, mc.from not under
1061 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1063 spin_lock(&mc
.lock
);
1068 if (from
== mem
|| to
== mem
1069 || (mem
->use_hierarchy
&& css_is_ancestor(&from
->css
, &mem
->css
))
1070 || (mem
->use_hierarchy
&& css_is_ancestor(&to
->css
, &mem
->css
)))
1073 spin_unlock(&mc
.lock
);
1077 static bool mem_cgroup_wait_acct_move(struct mem_cgroup
*mem
)
1079 if (mc
.moving_task
&& current
!= mc
.moving_task
) {
1080 if (mem_cgroup_under_move(mem
)) {
1082 prepare_to_wait(&mc
.waitq
, &wait
, TASK_INTERRUPTIBLE
);
1083 /* moving charge context might have finished. */
1086 finish_wait(&mc
.waitq
, &wait
);
1093 static int mem_cgroup_count_children_cb(struct mem_cgroup
*mem
, void *data
)
1101 * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode.
1102 * @memcg: The memory cgroup that went over limit
1103 * @p: Task that is going to be killed
1105 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1108 void mem_cgroup_print_oom_info(struct mem_cgroup
*memcg
, struct task_struct
*p
)
1110 struct cgroup
*task_cgrp
;
1111 struct cgroup
*mem_cgrp
;
1113 * Need a buffer in BSS, can't rely on allocations. The code relies
1114 * on the assumption that OOM is serialized for memory controller.
1115 * If this assumption is broken, revisit this code.
1117 static char memcg_name
[PATH_MAX
];
1126 mem_cgrp
= memcg
->css
.cgroup
;
1127 task_cgrp
= task_cgroup(p
, mem_cgroup_subsys_id
);
1129 ret
= cgroup_path(task_cgrp
, memcg_name
, PATH_MAX
);
1132 * Unfortunately, we are unable to convert to a useful name
1133 * But we'll still print out the usage information
1140 printk(KERN_INFO
"Task in %s killed", memcg_name
);
1143 ret
= cgroup_path(mem_cgrp
, memcg_name
, PATH_MAX
);
1151 * Continues from above, so we don't need an KERN_ level
1153 printk(KERN_CONT
" as a result of limit of %s\n", memcg_name
);
1156 printk(KERN_INFO
"memory: usage %llukB, limit %llukB, failcnt %llu\n",
1157 res_counter_read_u64(&memcg
->res
, RES_USAGE
) >> 10,
1158 res_counter_read_u64(&memcg
->res
, RES_LIMIT
) >> 10,
1159 res_counter_read_u64(&memcg
->res
, RES_FAILCNT
));
1160 printk(KERN_INFO
"memory+swap: usage %llukB, limit %llukB, "
1162 res_counter_read_u64(&memcg
->memsw
, RES_USAGE
) >> 10,
1163 res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
) >> 10,
1164 res_counter_read_u64(&memcg
->memsw
, RES_FAILCNT
));
1168 * This function returns the number of memcg under hierarchy tree. Returns
1169 * 1(self count) if no children.
1171 static int mem_cgroup_count_children(struct mem_cgroup
*mem
)
1174 mem_cgroup_walk_tree(mem
, &num
, mem_cgroup_count_children_cb
);
1179 * Return the memory (and swap, if configured) limit for a memcg.
1181 u64
mem_cgroup_get_limit(struct mem_cgroup
*memcg
)
1186 limit
= res_counter_read_u64(&memcg
->res
, RES_LIMIT
) +
1188 memsw
= res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
);
1190 * If memsw is finite and limits the amount of swap space available
1191 * to this memcg, return that limit.
1193 return min(limit
, memsw
);
1197 * Visit the first child (need not be the first child as per the ordering
1198 * of the cgroup list, since we track last_scanned_child) of @mem and use
1199 * that to reclaim free pages from.
1201 static struct mem_cgroup
*
1202 mem_cgroup_select_victim(struct mem_cgroup
*root_mem
)
1204 struct mem_cgroup
*ret
= NULL
;
1205 struct cgroup_subsys_state
*css
;
1208 if (!root_mem
->use_hierarchy
) {
1209 css_get(&root_mem
->css
);
1215 nextid
= root_mem
->last_scanned_child
+ 1;
1216 css
= css_get_next(&mem_cgroup_subsys
, nextid
, &root_mem
->css
,
1218 if (css
&& css_tryget(css
))
1219 ret
= container_of(css
, struct mem_cgroup
, css
);
1222 /* Updates scanning parameter */
1223 spin_lock(&root_mem
->reclaim_param_lock
);
1225 /* this means start scan from ID:1 */
1226 root_mem
->last_scanned_child
= 0;
1228 root_mem
->last_scanned_child
= found
;
1229 spin_unlock(&root_mem
->reclaim_param_lock
);
1236 * Scan the hierarchy if needed to reclaim memory. We remember the last child
1237 * we reclaimed from, so that we don't end up penalizing one child extensively
1238 * based on its position in the children list.
1240 * root_mem is the original ancestor that we've been reclaim from.
1242 * We give up and return to the caller when we visit root_mem twice.
1243 * (other groups can be removed while we're walking....)
1245 * If shrink==true, for avoiding to free too much, this returns immedieately.
1247 static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup
*root_mem
,
1250 unsigned long reclaim_options
)
1252 struct mem_cgroup
*victim
;
1255 bool noswap
= reclaim_options
& MEM_CGROUP_RECLAIM_NOSWAP
;
1256 bool shrink
= reclaim_options
& MEM_CGROUP_RECLAIM_SHRINK
;
1257 bool check_soft
= reclaim_options
& MEM_CGROUP_RECLAIM_SOFT
;
1258 unsigned long excess
= mem_cgroup_get_excess(root_mem
);
1260 /* If memsw_is_minimum==1, swap-out is of-no-use. */
1261 if (root_mem
->memsw_is_minimum
)
1265 victim
= mem_cgroup_select_victim(root_mem
);
1266 if (victim
== root_mem
) {
1269 drain_all_stock_async();
1272 * If we have not been able to reclaim
1273 * anything, it might because there are
1274 * no reclaimable pages under this hierarchy
1276 if (!check_soft
|| !total
) {
1277 css_put(&victim
->css
);
1281 * We want to do more targetted reclaim.
1282 * excess >> 2 is not to excessive so as to
1283 * reclaim too much, nor too less that we keep
1284 * coming back to reclaim from this cgroup
1286 if (total
>= (excess
>> 2) ||
1287 (loop
> MEM_CGROUP_MAX_RECLAIM_LOOPS
)) {
1288 css_put(&victim
->css
);
1293 if (!mem_cgroup_local_usage(victim
)) {
1294 /* this cgroup's local usage == 0 */
1295 css_put(&victim
->css
);
1298 /* we use swappiness of local cgroup */
1300 ret
= mem_cgroup_shrink_node_zone(victim
, gfp_mask
,
1301 noswap
, get_swappiness(victim
), zone
,
1302 zone
->zone_pgdat
->node_id
);
1304 ret
= try_to_free_mem_cgroup_pages(victim
, gfp_mask
,
1305 noswap
, get_swappiness(victim
));
1306 css_put(&victim
->css
);
1308 * At shrinking usage, we can't check we should stop here or
1309 * reclaim more. It's depends on callers. last_scanned_child
1310 * will work enough for keeping fairness under tree.
1316 if (res_counter_check_under_soft_limit(&root_mem
->res
))
1318 } else if (mem_cgroup_check_under_limit(root_mem
))
1324 static int mem_cgroup_oom_lock_cb(struct mem_cgroup
*mem
, void *data
)
1326 int *val
= (int *)data
;
1329 * Logically, we can stop scanning immediately when we find
1330 * a memcg is already locked. But condidering unlock ops and
1331 * creation/removal of memcg, scan-all is simple operation.
1333 x
= atomic_inc_return(&mem
->oom_lock
);
1334 *val
= max(x
, *val
);
1338 * Check OOM-Killer is already running under our hierarchy.
1339 * If someone is running, return false.
1341 static bool mem_cgroup_oom_lock(struct mem_cgroup
*mem
)
1345 mem_cgroup_walk_tree(mem
, &lock_count
, mem_cgroup_oom_lock_cb
);
1347 if (lock_count
== 1)
1352 static int mem_cgroup_oom_unlock_cb(struct mem_cgroup
*mem
, void *data
)
1355 * When a new child is created while the hierarchy is under oom,
1356 * mem_cgroup_oom_lock() may not be called. We have to use
1357 * atomic_add_unless() here.
1359 atomic_add_unless(&mem
->oom_lock
, -1, 0);
1363 static void mem_cgroup_oom_unlock(struct mem_cgroup
*mem
)
1365 mem_cgroup_walk_tree(mem
, NULL
, mem_cgroup_oom_unlock_cb
);
1368 static DEFINE_MUTEX(memcg_oom_mutex
);
1369 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq
);
1371 struct oom_wait_info
{
1372 struct mem_cgroup
*mem
;
1376 static int memcg_oom_wake_function(wait_queue_t
*wait
,
1377 unsigned mode
, int sync
, void *arg
)
1379 struct mem_cgroup
*wake_mem
= (struct mem_cgroup
*)arg
;
1380 struct oom_wait_info
*oom_wait_info
;
1382 oom_wait_info
= container_of(wait
, struct oom_wait_info
, wait
);
1384 if (oom_wait_info
->mem
== wake_mem
)
1386 /* if no hierarchy, no match */
1387 if (!oom_wait_info
->mem
->use_hierarchy
|| !wake_mem
->use_hierarchy
)
1390 * Both of oom_wait_info->mem and wake_mem are stable under us.
1391 * Then we can use css_is_ancestor without taking care of RCU.
1393 if (!css_is_ancestor(&oom_wait_info
->mem
->css
, &wake_mem
->css
) &&
1394 !css_is_ancestor(&wake_mem
->css
, &oom_wait_info
->mem
->css
))
1398 return autoremove_wake_function(wait
, mode
, sync
, arg
);
1401 static void memcg_wakeup_oom(struct mem_cgroup
*mem
)
1403 /* for filtering, pass "mem" as argument. */
1404 __wake_up(&memcg_oom_waitq
, TASK_NORMAL
, 0, mem
);
1407 static void memcg_oom_recover(struct mem_cgroup
*mem
)
1409 if (mem
&& atomic_read(&mem
->oom_lock
))
1410 memcg_wakeup_oom(mem
);
1414 * try to call OOM killer. returns false if we should exit memory-reclaim loop.
1416 bool mem_cgroup_handle_oom(struct mem_cgroup
*mem
, gfp_t mask
)
1418 struct oom_wait_info owait
;
1419 bool locked
, need_to_kill
;
1422 owait
.wait
.flags
= 0;
1423 owait
.wait
.func
= memcg_oom_wake_function
;
1424 owait
.wait
.private = current
;
1425 INIT_LIST_HEAD(&owait
.wait
.task_list
);
1426 need_to_kill
= true;
1427 /* At first, try to OOM lock hierarchy under mem.*/
1428 mutex_lock(&memcg_oom_mutex
);
1429 locked
= mem_cgroup_oom_lock(mem
);
1431 * Even if signal_pending(), we can't quit charge() loop without
1432 * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
1433 * under OOM is always welcomed, use TASK_KILLABLE here.
1435 prepare_to_wait(&memcg_oom_waitq
, &owait
.wait
, TASK_KILLABLE
);
1436 if (!locked
|| mem
->oom_kill_disable
)
1437 need_to_kill
= false;
1439 mem_cgroup_oom_notify(mem
);
1440 mutex_unlock(&memcg_oom_mutex
);
1443 finish_wait(&memcg_oom_waitq
, &owait
.wait
);
1444 mem_cgroup_out_of_memory(mem
, mask
);
1447 finish_wait(&memcg_oom_waitq
, &owait
.wait
);
1449 mutex_lock(&memcg_oom_mutex
);
1450 mem_cgroup_oom_unlock(mem
);
1451 memcg_wakeup_oom(mem
);
1452 mutex_unlock(&memcg_oom_mutex
);
1454 if (test_thread_flag(TIF_MEMDIE
) || fatal_signal_pending(current
))
1456 /* Give chance to dying process */
1457 schedule_timeout(1);
1462 * Currently used to update mapped file statistics, but the routine can be
1463 * generalized to update other statistics as well.
1465 void mem_cgroup_update_file_mapped(struct page
*page
, int val
)
1467 struct mem_cgroup
*mem
;
1468 struct page_cgroup
*pc
;
1470 pc
= lookup_page_cgroup(page
);
1474 lock_page_cgroup(pc
);
1475 mem
= pc
->mem_cgroup
;
1476 if (!mem
|| !PageCgroupUsed(pc
))
1480 * Preemption is already disabled. We can use __this_cpu_xxx
1483 __this_cpu_inc(mem
->stat
->count
[MEM_CGROUP_STAT_FILE_MAPPED
]);
1484 SetPageCgroupFileMapped(pc
);
1486 __this_cpu_dec(mem
->stat
->count
[MEM_CGROUP_STAT_FILE_MAPPED
]);
1487 ClearPageCgroupFileMapped(pc
);
1491 unlock_page_cgroup(pc
);
1495 * size of first charge trial. "32" comes from vmscan.c's magic value.
1496 * TODO: maybe necessary to use big numbers in big irons.
1498 #define CHARGE_SIZE (32 * PAGE_SIZE)
1499 struct memcg_stock_pcp
{
1500 struct mem_cgroup
*cached
; /* this never be root cgroup */
1502 struct work_struct work
;
1504 static DEFINE_PER_CPU(struct memcg_stock_pcp
, memcg_stock
);
1505 static atomic_t memcg_drain_count
;
1508 * Try to consume stocked charge on this cpu. If success, PAGE_SIZE is consumed
1509 * from local stock and true is returned. If the stock is 0 or charges from a
1510 * cgroup which is not current target, returns false. This stock will be
1513 static bool consume_stock(struct mem_cgroup
*mem
)
1515 struct memcg_stock_pcp
*stock
;
1518 stock
= &get_cpu_var(memcg_stock
);
1519 if (mem
== stock
->cached
&& stock
->charge
)
1520 stock
->charge
-= PAGE_SIZE
;
1521 else /* need to call res_counter_charge */
1523 put_cpu_var(memcg_stock
);
1528 * Returns stocks cached in percpu to res_counter and reset cached information.
1530 static void drain_stock(struct memcg_stock_pcp
*stock
)
1532 struct mem_cgroup
*old
= stock
->cached
;
1534 if (stock
->charge
) {
1535 res_counter_uncharge(&old
->res
, stock
->charge
);
1536 if (do_swap_account
)
1537 res_counter_uncharge(&old
->memsw
, stock
->charge
);
1539 stock
->cached
= NULL
;
1544 * This must be called under preempt disabled or must be called by
1545 * a thread which is pinned to local cpu.
1547 static void drain_local_stock(struct work_struct
*dummy
)
1549 struct memcg_stock_pcp
*stock
= &__get_cpu_var(memcg_stock
);
1554 * Cache charges(val) which is from res_counter, to local per_cpu area.
1555 * This will be consumed by consume_stock() function, later.
1557 static void refill_stock(struct mem_cgroup
*mem
, int val
)
1559 struct memcg_stock_pcp
*stock
= &get_cpu_var(memcg_stock
);
1561 if (stock
->cached
!= mem
) { /* reset if necessary */
1563 stock
->cached
= mem
;
1565 stock
->charge
+= val
;
1566 put_cpu_var(memcg_stock
);
1570 * Tries to drain stocked charges in other cpus. This function is asynchronous
1571 * and just put a work per cpu for draining localy on each cpu. Caller can
1572 * expects some charges will be back to res_counter later but cannot wait for
1575 static void drain_all_stock_async(void)
1578 /* This function is for scheduling "drain" in asynchronous way.
1579 * The result of "drain" is not directly handled by callers. Then,
1580 * if someone is calling drain, we don't have to call drain more.
1581 * Anyway, WORK_STRUCT_PENDING check in queue_work_on() will catch if
1582 * there is a race. We just do loose check here.
1584 if (atomic_read(&memcg_drain_count
))
1586 /* Notify other cpus that system-wide "drain" is running */
1587 atomic_inc(&memcg_drain_count
);
1589 for_each_online_cpu(cpu
) {
1590 struct memcg_stock_pcp
*stock
= &per_cpu(memcg_stock
, cpu
);
1591 schedule_work_on(cpu
, &stock
->work
);
1594 atomic_dec(&memcg_drain_count
);
1595 /* We don't wait for flush_work */
1598 /* This is a synchronous drain interface. */
1599 static void drain_all_stock_sync(void)
1601 /* called when force_empty is called */
1602 atomic_inc(&memcg_drain_count
);
1603 schedule_on_each_cpu(drain_local_stock
);
1604 atomic_dec(&memcg_drain_count
);
1607 static int __cpuinit
memcg_stock_cpu_callback(struct notifier_block
*nb
,
1608 unsigned long action
,
1611 int cpu
= (unsigned long)hcpu
;
1612 struct memcg_stock_pcp
*stock
;
1614 if (action
!= CPU_DEAD
)
1616 stock
= &per_cpu(memcg_stock
, cpu
);
1622 /* See __mem_cgroup_try_charge() for details */
1624 CHARGE_OK
, /* success */
1625 CHARGE_RETRY
, /* need to retry but retry is not bad */
1626 CHARGE_NOMEM
, /* we can't do more. return -ENOMEM */
1627 CHARGE_WOULDBLOCK
, /* GFP_WAIT wasn't set and no enough res. */
1628 CHARGE_OOM_DIE
, /* the current is killed because of OOM */
1631 static int __mem_cgroup_do_charge(struct mem_cgroup
*mem
, gfp_t gfp_mask
,
1632 int csize
, bool oom_check
)
1634 struct mem_cgroup
*mem_over_limit
;
1635 struct res_counter
*fail_res
;
1636 unsigned long flags
= 0;
1639 ret
= res_counter_charge(&mem
->res
, csize
, &fail_res
);
1642 if (!do_swap_account
)
1644 ret
= res_counter_charge(&mem
->memsw
, csize
, &fail_res
);
1648 mem_over_limit
= mem_cgroup_from_res_counter(fail_res
, memsw
);
1649 flags
|= MEM_CGROUP_RECLAIM_NOSWAP
;
1651 mem_over_limit
= mem_cgroup_from_res_counter(fail_res
, res
);
1653 if (csize
> PAGE_SIZE
) /* change csize and retry */
1654 return CHARGE_RETRY
;
1656 if (!(gfp_mask
& __GFP_WAIT
))
1657 return CHARGE_WOULDBLOCK
;
1659 ret
= mem_cgroup_hierarchical_reclaim(mem_over_limit
, NULL
,
1662 * try_to_free_mem_cgroup_pages() might not give us a full
1663 * picture of reclaim. Some pages are reclaimed and might be
1664 * moved to swap cache or just unmapped from the cgroup.
1665 * Check the limit again to see if the reclaim reduced the
1666 * current usage of the cgroup before giving up
1668 if (ret
|| mem_cgroup_check_under_limit(mem_over_limit
))
1669 return CHARGE_RETRY
;
1672 * At task move, charge accounts can be doubly counted. So, it's
1673 * better to wait until the end of task_move if something is going on.
1675 if (mem_cgroup_wait_acct_move(mem_over_limit
))
1676 return CHARGE_RETRY
;
1678 /* If we don't need to call oom-killer at el, return immediately */
1680 return CHARGE_NOMEM
;
1682 if (!mem_cgroup_handle_oom(mem_over_limit
, gfp_mask
))
1683 return CHARGE_OOM_DIE
;
1685 return CHARGE_RETRY
;
1689 * Unlike exported interface, "oom" parameter is added. if oom==true,
1690 * oom-killer can be invoked.
1692 static int __mem_cgroup_try_charge(struct mm_struct
*mm
,
1693 gfp_t gfp_mask
, struct mem_cgroup
**memcg
, bool oom
)
1695 int nr_oom_retries
= MEM_CGROUP_RECLAIM_RETRIES
;
1696 struct mem_cgroup
*mem
= NULL
;
1698 int csize
= CHARGE_SIZE
;
1701 * Unlike gloval-vm's OOM-kill, we're not in memory shortage
1702 * in system level. So, allow to go ahead dying process in addition to
1705 if (unlikely(test_thread_flag(TIF_MEMDIE
)
1706 || fatal_signal_pending(current
)))
1710 * We always charge the cgroup the mm_struct belongs to.
1711 * The mm_struct's mem_cgroup changes on task migration if the
1712 * thread group leader migrates. It's possible that mm is not
1713 * set, if so charge the init_mm (happens for pagecache usage).
1719 mem
= try_get_mem_cgroup_from_mm(mm
);
1725 VM_BUG_ON(css_is_removed(&mem
->css
));
1726 if (mem_cgroup_is_root(mem
))
1732 if (consume_stock(mem
))
1733 goto done
; /* don't need to fill stock */
1734 /* If killed, bypass charge */
1735 if (fatal_signal_pending(current
))
1739 if (oom
&& !nr_oom_retries
) {
1741 nr_oom_retries
= MEM_CGROUP_RECLAIM_RETRIES
;
1744 ret
= __mem_cgroup_do_charge(mem
, gfp_mask
, csize
, oom_check
);
1749 case CHARGE_RETRY
: /* not in OOM situation but retry */
1752 case CHARGE_WOULDBLOCK
: /* !__GFP_WAIT */
1754 case CHARGE_NOMEM
: /* OOM routine works */
1757 /* If oom, we never return -ENOMEM */
1760 case CHARGE_OOM_DIE
: /* Killed by OOM Killer */
1763 } while (ret
!= CHARGE_OK
);
1765 if (csize
> PAGE_SIZE
)
1766 refill_stock(mem
, csize
- PAGE_SIZE
);
1780 * Somemtimes we have to undo a charge we got by try_charge().
1781 * This function is for that and do uncharge, put css's refcnt.
1782 * gotten by try_charge().
1784 static void __mem_cgroup_cancel_charge(struct mem_cgroup
*mem
,
1785 unsigned long count
)
1787 if (!mem_cgroup_is_root(mem
)) {
1788 res_counter_uncharge(&mem
->res
, PAGE_SIZE
* count
);
1789 if (do_swap_account
)
1790 res_counter_uncharge(&mem
->memsw
, PAGE_SIZE
* count
);
1791 VM_BUG_ON(test_bit(CSS_ROOT
, &mem
->css
.flags
));
1792 WARN_ON_ONCE(count
> INT_MAX
);
1793 __css_put(&mem
->css
, (int)count
);
1795 /* we don't need css_put for root */
1798 static void mem_cgroup_cancel_charge(struct mem_cgroup
*mem
)
1800 __mem_cgroup_cancel_charge(mem
, 1);
1804 * A helper function to get mem_cgroup from ID. must be called under
1805 * rcu_read_lock(). The caller must check css_is_removed() or some if
1806 * it's concern. (dropping refcnt from swap can be called against removed
1809 static struct mem_cgroup
*mem_cgroup_lookup(unsigned short id
)
1811 struct cgroup_subsys_state
*css
;
1813 /* ID 0 is unused ID */
1816 css
= css_lookup(&mem_cgroup_subsys
, id
);
1819 return container_of(css
, struct mem_cgroup
, css
);
1822 struct mem_cgroup
*try_get_mem_cgroup_from_page(struct page
*page
)
1824 struct mem_cgroup
*mem
= NULL
;
1825 struct page_cgroup
*pc
;
1829 VM_BUG_ON(!PageLocked(page
));
1831 pc
= lookup_page_cgroup(page
);
1832 lock_page_cgroup(pc
);
1833 if (PageCgroupUsed(pc
)) {
1834 mem
= pc
->mem_cgroup
;
1835 if (mem
&& !css_tryget(&mem
->css
))
1837 } else if (PageSwapCache(page
)) {
1838 ent
.val
= page_private(page
);
1839 id
= lookup_swap_cgroup(ent
);
1841 mem
= mem_cgroup_lookup(id
);
1842 if (mem
&& !css_tryget(&mem
->css
))
1846 unlock_page_cgroup(pc
);
1851 * commit a charge got by __mem_cgroup_try_charge() and makes page_cgroup to be
1852 * USED state. If already USED, uncharge and return.
1855 static void __mem_cgroup_commit_charge(struct mem_cgroup
*mem
,
1856 struct page_cgroup
*pc
,
1857 enum charge_type ctype
)
1859 /* try_charge() can return NULL to *memcg, taking care of it. */
1863 lock_page_cgroup(pc
);
1864 if (unlikely(PageCgroupUsed(pc
))) {
1865 unlock_page_cgroup(pc
);
1866 mem_cgroup_cancel_charge(mem
);
1870 pc
->mem_cgroup
= mem
;
1872 * We access a page_cgroup asynchronously without lock_page_cgroup().
1873 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
1874 * is accessed after testing USED bit. To make pc->mem_cgroup visible
1875 * before USED bit, we need memory barrier here.
1876 * See mem_cgroup_add_lru_list(), etc.
1880 case MEM_CGROUP_CHARGE_TYPE_CACHE
:
1881 case MEM_CGROUP_CHARGE_TYPE_SHMEM
:
1882 SetPageCgroupCache(pc
);
1883 SetPageCgroupUsed(pc
);
1885 case MEM_CGROUP_CHARGE_TYPE_MAPPED
:
1886 ClearPageCgroupCache(pc
);
1887 SetPageCgroupUsed(pc
);
1893 mem_cgroup_charge_statistics(mem
, pc
, true);
1895 unlock_page_cgroup(pc
);
1897 * "charge_statistics" updated event counter. Then, check it.
1898 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
1899 * if they exceeds softlimit.
1901 memcg_check_events(mem
, pc
->page
);
1905 * __mem_cgroup_move_account - move account of the page
1906 * @pc: page_cgroup of the page.
1907 * @from: mem_cgroup which the page is moved from.
1908 * @to: mem_cgroup which the page is moved to. @from != @to.
1909 * @uncharge: whether we should call uncharge and css_put against @from.
1911 * The caller must confirm following.
1912 * - page is not on LRU (isolate_page() is useful.)
1913 * - the pc is locked, used, and ->mem_cgroup points to @from.
1915 * This function doesn't do "charge" nor css_get to new cgroup. It should be
1916 * done by a caller(__mem_cgroup_try_charge would be usefull). If @uncharge is
1917 * true, this function does "uncharge" from old cgroup, but it doesn't if
1918 * @uncharge is false, so a caller should do "uncharge".
1921 static void __mem_cgroup_move_account(struct page_cgroup
*pc
,
1922 struct mem_cgroup
*from
, struct mem_cgroup
*to
, bool uncharge
)
1924 VM_BUG_ON(from
== to
);
1925 VM_BUG_ON(PageLRU(pc
->page
));
1926 VM_BUG_ON(!PageCgroupLocked(pc
));
1927 VM_BUG_ON(!PageCgroupUsed(pc
));
1928 VM_BUG_ON(pc
->mem_cgroup
!= from
);
1930 if (PageCgroupFileMapped(pc
)) {
1931 /* Update mapped_file data for mem_cgroup */
1933 __this_cpu_dec(from
->stat
->count
[MEM_CGROUP_STAT_FILE_MAPPED
]);
1934 __this_cpu_inc(to
->stat
->count
[MEM_CGROUP_STAT_FILE_MAPPED
]);
1937 mem_cgroup_charge_statistics(from
, pc
, false);
1939 /* This is not "cancel", but cancel_charge does all we need. */
1940 mem_cgroup_cancel_charge(from
);
1942 /* caller should have done css_get */
1943 pc
->mem_cgroup
= to
;
1944 mem_cgroup_charge_statistics(to
, pc
, true);
1946 * We charges against "to" which may not have any tasks. Then, "to"
1947 * can be under rmdir(). But in current implementation, caller of
1948 * this function is just force_empty() and move charge, so it's
1949 * garanteed that "to" is never removed. So, we don't check rmdir
1955 * check whether the @pc is valid for moving account and call
1956 * __mem_cgroup_move_account()
1958 static int mem_cgroup_move_account(struct page_cgroup
*pc
,
1959 struct mem_cgroup
*from
, struct mem_cgroup
*to
, bool uncharge
)
1962 lock_page_cgroup(pc
);
1963 if (PageCgroupUsed(pc
) && pc
->mem_cgroup
== from
) {
1964 __mem_cgroup_move_account(pc
, from
, to
, uncharge
);
1967 unlock_page_cgroup(pc
);
1971 memcg_check_events(to
, pc
->page
);
1972 memcg_check_events(from
, pc
->page
);
1977 * move charges to its parent.
1980 static int mem_cgroup_move_parent(struct page_cgroup
*pc
,
1981 struct mem_cgroup
*child
,
1984 struct page
*page
= pc
->page
;
1985 struct cgroup
*cg
= child
->css
.cgroup
;
1986 struct cgroup
*pcg
= cg
->parent
;
1987 struct mem_cgroup
*parent
;
1995 if (!get_page_unless_zero(page
))
1997 if (isolate_lru_page(page
))
2000 parent
= mem_cgroup_from_cont(pcg
);
2001 ret
= __mem_cgroup_try_charge(NULL
, gfp_mask
, &parent
, false);
2005 ret
= mem_cgroup_move_account(pc
, child
, parent
, true);
2007 mem_cgroup_cancel_charge(parent
);
2009 putback_lru_page(page
);
2017 * Charge the memory controller for page usage.
2019 * 0 if the charge was successful
2020 * < 0 if the cgroup is over its limit
2022 static int mem_cgroup_charge_common(struct page
*page
, struct mm_struct
*mm
,
2023 gfp_t gfp_mask
, enum charge_type ctype
,
2024 struct mem_cgroup
*memcg
)
2026 struct mem_cgroup
*mem
;
2027 struct page_cgroup
*pc
;
2030 pc
= lookup_page_cgroup(page
);
2031 /* can happen at boot */
2037 ret
= __mem_cgroup_try_charge(mm
, gfp_mask
, &mem
, true);
2041 __mem_cgroup_commit_charge(mem
, pc
, ctype
);
2045 int mem_cgroup_newpage_charge(struct page
*page
,
2046 struct mm_struct
*mm
, gfp_t gfp_mask
)
2048 if (mem_cgroup_disabled())
2050 if (PageCompound(page
))
2053 * If already mapped, we don't have to account.
2054 * If page cache, page->mapping has address_space.
2055 * But page->mapping may have out-of-use anon_vma pointer,
2056 * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
2059 if (page_mapped(page
) || (page
->mapping
&& !PageAnon(page
)))
2063 return mem_cgroup_charge_common(page
, mm
, gfp_mask
,
2064 MEM_CGROUP_CHARGE_TYPE_MAPPED
, NULL
);
2068 __mem_cgroup_commit_charge_swapin(struct page
*page
, struct mem_cgroup
*ptr
,
2069 enum charge_type ctype
);
2071 int mem_cgroup_cache_charge(struct page
*page
, struct mm_struct
*mm
,
2074 struct mem_cgroup
*mem
= NULL
;
2077 if (mem_cgroup_disabled())
2079 if (PageCompound(page
))
2082 * Corner case handling. This is called from add_to_page_cache()
2083 * in usual. But some FS (shmem) precharges this page before calling it
2084 * and call add_to_page_cache() with GFP_NOWAIT.
2086 * For GFP_NOWAIT case, the page may be pre-charged before calling
2087 * add_to_page_cache(). (See shmem.c) check it here and avoid to call
2088 * charge twice. (It works but has to pay a bit larger cost.)
2089 * And when the page is SwapCache, it should take swap information
2090 * into account. This is under lock_page() now.
2092 if (!(gfp_mask
& __GFP_WAIT
)) {
2093 struct page_cgroup
*pc
;
2096 pc
= lookup_page_cgroup(page
);
2099 lock_page_cgroup(pc
);
2100 if (PageCgroupUsed(pc
)) {
2101 unlock_page_cgroup(pc
);
2104 unlock_page_cgroup(pc
);
2107 if (unlikely(!mm
&& !mem
))
2110 if (page_is_file_cache(page
))
2111 return mem_cgroup_charge_common(page
, mm
, gfp_mask
,
2112 MEM_CGROUP_CHARGE_TYPE_CACHE
, NULL
);
2115 if (PageSwapCache(page
)) {
2116 ret
= mem_cgroup_try_charge_swapin(mm
, page
, gfp_mask
, &mem
);
2118 __mem_cgroup_commit_charge_swapin(page
, mem
,
2119 MEM_CGROUP_CHARGE_TYPE_SHMEM
);
2121 ret
= mem_cgroup_charge_common(page
, mm
, gfp_mask
,
2122 MEM_CGROUP_CHARGE_TYPE_SHMEM
, mem
);
2128 * While swap-in, try_charge -> commit or cancel, the page is locked.
2129 * And when try_charge() successfully returns, one refcnt to memcg without
2130 * struct page_cgroup is acquired. This refcnt will be consumed by
2131 * "commit()" or removed by "cancel()"
2133 int mem_cgroup_try_charge_swapin(struct mm_struct
*mm
,
2135 gfp_t mask
, struct mem_cgroup
**ptr
)
2137 struct mem_cgroup
*mem
;
2140 if (mem_cgroup_disabled())
2143 if (!do_swap_account
)
2146 * A racing thread's fault, or swapoff, may have already updated
2147 * the pte, and even removed page from swap cache: in those cases
2148 * do_swap_page()'s pte_same() test will fail; but there's also a
2149 * KSM case which does need to charge the page.
2151 if (!PageSwapCache(page
))
2153 mem
= try_get_mem_cgroup_from_page(page
);
2157 ret
= __mem_cgroup_try_charge(NULL
, mask
, ptr
, true);
2158 /* drop extra refcnt from tryget */
2164 return __mem_cgroup_try_charge(mm
, mask
, ptr
, true);
2168 __mem_cgroup_commit_charge_swapin(struct page
*page
, struct mem_cgroup
*ptr
,
2169 enum charge_type ctype
)
2171 struct page_cgroup
*pc
;
2173 if (mem_cgroup_disabled())
2177 cgroup_exclude_rmdir(&ptr
->css
);
2178 pc
= lookup_page_cgroup(page
);
2179 mem_cgroup_lru_del_before_commit_swapcache(page
);
2180 __mem_cgroup_commit_charge(ptr
, pc
, ctype
);
2181 mem_cgroup_lru_add_after_commit_swapcache(page
);
2183 * Now swap is on-memory. This means this page may be
2184 * counted both as mem and swap....double count.
2185 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
2186 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
2187 * may call delete_from_swap_cache() before reach here.
2189 if (do_swap_account
&& PageSwapCache(page
)) {
2190 swp_entry_t ent
= {.val
= page_private(page
)};
2192 struct mem_cgroup
*memcg
;
2194 id
= swap_cgroup_record(ent
, 0);
2196 memcg
= mem_cgroup_lookup(id
);
2199 * This recorded memcg can be obsolete one. So, avoid
2200 * calling css_tryget
2202 if (!mem_cgroup_is_root(memcg
))
2203 res_counter_uncharge(&memcg
->memsw
, PAGE_SIZE
);
2204 mem_cgroup_swap_statistics(memcg
, false);
2205 mem_cgroup_put(memcg
);
2210 * At swapin, we may charge account against cgroup which has no tasks.
2211 * So, rmdir()->pre_destroy() can be called while we do this charge.
2212 * In that case, we need to call pre_destroy() again. check it here.
2214 cgroup_release_and_wakeup_rmdir(&ptr
->css
);
2217 void mem_cgroup_commit_charge_swapin(struct page
*page
, struct mem_cgroup
*ptr
)
2219 __mem_cgroup_commit_charge_swapin(page
, ptr
,
2220 MEM_CGROUP_CHARGE_TYPE_MAPPED
);
2223 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup
*mem
)
2225 if (mem_cgroup_disabled())
2229 mem_cgroup_cancel_charge(mem
);
2233 __do_uncharge(struct mem_cgroup
*mem
, const enum charge_type ctype
)
2235 struct memcg_batch_info
*batch
= NULL
;
2236 bool uncharge_memsw
= true;
2237 /* If swapout, usage of swap doesn't decrease */
2238 if (!do_swap_account
|| ctype
== MEM_CGROUP_CHARGE_TYPE_SWAPOUT
)
2239 uncharge_memsw
= false;
2241 batch
= ¤t
->memcg_batch
;
2243 * In usual, we do css_get() when we remember memcg pointer.
2244 * But in this case, we keep res->usage until end of a series of
2245 * uncharges. Then, it's ok to ignore memcg's refcnt.
2250 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
2251 * In those cases, all pages freed continously can be expected to be in
2252 * the same cgroup and we have chance to coalesce uncharges.
2253 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
2254 * because we want to do uncharge as soon as possible.
2257 if (!batch
->do_batch
|| test_thread_flag(TIF_MEMDIE
))
2258 goto direct_uncharge
;
2261 * In typical case, batch->memcg == mem. This means we can
2262 * merge a series of uncharges to an uncharge of res_counter.
2263 * If not, we uncharge res_counter ony by one.
2265 if (batch
->memcg
!= mem
)
2266 goto direct_uncharge
;
2267 /* remember freed charge and uncharge it later */
2268 batch
->bytes
+= PAGE_SIZE
;
2270 batch
->memsw_bytes
+= PAGE_SIZE
;
2273 res_counter_uncharge(&mem
->res
, PAGE_SIZE
);
2275 res_counter_uncharge(&mem
->memsw
, PAGE_SIZE
);
2276 if (unlikely(batch
->memcg
!= mem
))
2277 memcg_oom_recover(mem
);
2282 * uncharge if !page_mapped(page)
2284 static struct mem_cgroup
*
2285 __mem_cgroup_uncharge_common(struct page
*page
, enum charge_type ctype
)
2287 struct page_cgroup
*pc
;
2288 struct mem_cgroup
*mem
= NULL
;
2289 struct mem_cgroup_per_zone
*mz
;
2291 if (mem_cgroup_disabled())
2294 if (PageSwapCache(page
))
2298 * Check if our page_cgroup is valid
2300 pc
= lookup_page_cgroup(page
);
2301 if (unlikely(!pc
|| !PageCgroupUsed(pc
)))
2304 lock_page_cgroup(pc
);
2306 mem
= pc
->mem_cgroup
;
2308 if (!PageCgroupUsed(pc
))
2312 case MEM_CGROUP_CHARGE_TYPE_MAPPED
:
2313 case MEM_CGROUP_CHARGE_TYPE_DROP
:
2314 /* See mem_cgroup_prepare_migration() */
2315 if (page_mapped(page
) || PageCgroupMigration(pc
))
2318 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT
:
2319 if (!PageAnon(page
)) { /* Shared memory */
2320 if (page
->mapping
&& !page_is_file_cache(page
))
2322 } else if (page_mapped(page
)) /* Anon */
2329 if (!mem_cgroup_is_root(mem
))
2330 __do_uncharge(mem
, ctype
);
2331 if (ctype
== MEM_CGROUP_CHARGE_TYPE_SWAPOUT
)
2332 mem_cgroup_swap_statistics(mem
, true);
2333 mem_cgroup_charge_statistics(mem
, pc
, false);
2335 ClearPageCgroupUsed(pc
);
2337 * pc->mem_cgroup is not cleared here. It will be accessed when it's
2338 * freed from LRU. This is safe because uncharged page is expected not
2339 * to be reused (freed soon). Exception is SwapCache, it's handled by
2340 * special functions.
2343 mz
= page_cgroup_zoneinfo(pc
);
2344 unlock_page_cgroup(pc
);
2346 memcg_check_events(mem
, page
);
2347 /* at swapout, this memcg will be accessed to record to swap */
2348 if (ctype
!= MEM_CGROUP_CHARGE_TYPE_SWAPOUT
)
2354 unlock_page_cgroup(pc
);
2358 void mem_cgroup_uncharge_page(struct page
*page
)
2361 if (page_mapped(page
))
2363 if (page
->mapping
&& !PageAnon(page
))
2365 __mem_cgroup_uncharge_common(page
, MEM_CGROUP_CHARGE_TYPE_MAPPED
);
2368 void mem_cgroup_uncharge_cache_page(struct page
*page
)
2370 VM_BUG_ON(page_mapped(page
));
2371 VM_BUG_ON(page
->mapping
);
2372 __mem_cgroup_uncharge_common(page
, MEM_CGROUP_CHARGE_TYPE_CACHE
);
2376 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
2377 * In that cases, pages are freed continuously and we can expect pages
2378 * are in the same memcg. All these calls itself limits the number of
2379 * pages freed at once, then uncharge_start/end() is called properly.
2380 * This may be called prural(2) times in a context,
2383 void mem_cgroup_uncharge_start(void)
2385 current
->memcg_batch
.do_batch
++;
2386 /* We can do nest. */
2387 if (current
->memcg_batch
.do_batch
== 1) {
2388 current
->memcg_batch
.memcg
= NULL
;
2389 current
->memcg_batch
.bytes
= 0;
2390 current
->memcg_batch
.memsw_bytes
= 0;
2394 void mem_cgroup_uncharge_end(void)
2396 struct memcg_batch_info
*batch
= ¤t
->memcg_batch
;
2398 if (!batch
->do_batch
)
2402 if (batch
->do_batch
) /* If stacked, do nothing. */
2408 * This "batch->memcg" is valid without any css_get/put etc...
2409 * bacause we hide charges behind us.
2412 res_counter_uncharge(&batch
->memcg
->res
, batch
->bytes
);
2413 if (batch
->memsw_bytes
)
2414 res_counter_uncharge(&batch
->memcg
->memsw
, batch
->memsw_bytes
);
2415 memcg_oom_recover(batch
->memcg
);
2416 /* forget this pointer (for sanity check) */
2417 batch
->memcg
= NULL
;
2422 * called after __delete_from_swap_cache() and drop "page" account.
2423 * memcg information is recorded to swap_cgroup of "ent"
2426 mem_cgroup_uncharge_swapcache(struct page
*page
, swp_entry_t ent
, bool swapout
)
2428 struct mem_cgroup
*memcg
;
2429 int ctype
= MEM_CGROUP_CHARGE_TYPE_SWAPOUT
;
2431 if (!swapout
) /* this was a swap cache but the swap is unused ! */
2432 ctype
= MEM_CGROUP_CHARGE_TYPE_DROP
;
2434 memcg
= __mem_cgroup_uncharge_common(page
, ctype
);
2436 /* record memcg information */
2437 if (do_swap_account
&& swapout
&& memcg
) {
2438 swap_cgroup_record(ent
, css_id(&memcg
->css
));
2439 mem_cgroup_get(memcg
);
2441 if (swapout
&& memcg
)
2442 css_put(&memcg
->css
);
2446 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
2448 * called from swap_entry_free(). remove record in swap_cgroup and
2449 * uncharge "memsw" account.
2451 void mem_cgroup_uncharge_swap(swp_entry_t ent
)
2453 struct mem_cgroup
*memcg
;
2456 if (!do_swap_account
)
2459 id
= swap_cgroup_record(ent
, 0);
2461 memcg
= mem_cgroup_lookup(id
);
2464 * We uncharge this because swap is freed.
2465 * This memcg can be obsolete one. We avoid calling css_tryget
2467 if (!mem_cgroup_is_root(memcg
))
2468 res_counter_uncharge(&memcg
->memsw
, PAGE_SIZE
);
2469 mem_cgroup_swap_statistics(memcg
, false);
2470 mem_cgroup_put(memcg
);
2476 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
2477 * @entry: swap entry to be moved
2478 * @from: mem_cgroup which the entry is moved from
2479 * @to: mem_cgroup which the entry is moved to
2480 * @need_fixup: whether we should fixup res_counters and refcounts.
2482 * It succeeds only when the swap_cgroup's record for this entry is the same
2483 * as the mem_cgroup's id of @from.
2485 * Returns 0 on success, -EINVAL on failure.
2487 * The caller must have charged to @to, IOW, called res_counter_charge() about
2488 * both res and memsw, and called css_get().
2490 static int mem_cgroup_move_swap_account(swp_entry_t entry
,
2491 struct mem_cgroup
*from
, struct mem_cgroup
*to
, bool need_fixup
)
2493 unsigned short old_id
, new_id
;
2495 old_id
= css_id(&from
->css
);
2496 new_id
= css_id(&to
->css
);
2498 if (swap_cgroup_cmpxchg(entry
, old_id
, new_id
) == old_id
) {
2499 mem_cgroup_swap_statistics(from
, false);
2500 mem_cgroup_swap_statistics(to
, true);
2502 * This function is only called from task migration context now.
2503 * It postpones res_counter and refcount handling till the end
2504 * of task migration(mem_cgroup_clear_mc()) for performance
2505 * improvement. But we cannot postpone mem_cgroup_get(to)
2506 * because if the process that has been moved to @to does
2507 * swap-in, the refcount of @to might be decreased to 0.
2511 if (!mem_cgroup_is_root(from
))
2512 res_counter_uncharge(&from
->memsw
, PAGE_SIZE
);
2513 mem_cgroup_put(from
);
2515 * we charged both to->res and to->memsw, so we should
2518 if (!mem_cgroup_is_root(to
))
2519 res_counter_uncharge(&to
->res
, PAGE_SIZE
);
2527 static inline int mem_cgroup_move_swap_account(swp_entry_t entry
,
2528 struct mem_cgroup
*from
, struct mem_cgroup
*to
, bool need_fixup
)
2535 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
2538 int mem_cgroup_prepare_migration(struct page
*page
,
2539 struct page
*newpage
, struct mem_cgroup
**ptr
)
2541 struct page_cgroup
*pc
;
2542 struct mem_cgroup
*mem
= NULL
;
2543 enum charge_type ctype
;
2546 if (mem_cgroup_disabled())
2549 pc
= lookup_page_cgroup(page
);
2550 lock_page_cgroup(pc
);
2551 if (PageCgroupUsed(pc
)) {
2552 mem
= pc
->mem_cgroup
;
2555 * At migrating an anonymous page, its mapcount goes down
2556 * to 0 and uncharge() will be called. But, even if it's fully
2557 * unmapped, migration may fail and this page has to be
2558 * charged again. We set MIGRATION flag here and delay uncharge
2559 * until end_migration() is called
2561 * Corner Case Thinking
2563 * When the old page was mapped as Anon and it's unmap-and-freed
2564 * while migration was ongoing.
2565 * If unmap finds the old page, uncharge() of it will be delayed
2566 * until end_migration(). If unmap finds a new page, it's
2567 * uncharged when it make mapcount to be 1->0. If unmap code
2568 * finds swap_migration_entry, the new page will not be mapped
2569 * and end_migration() will find it(mapcount==0).
2572 * When the old page was mapped but migraion fails, the kernel
2573 * remaps it. A charge for it is kept by MIGRATION flag even
2574 * if mapcount goes down to 0. We can do remap successfully
2575 * without charging it again.
2578 * The "old" page is under lock_page() until the end of
2579 * migration, so, the old page itself will not be swapped-out.
2580 * If the new page is swapped out before end_migraton, our
2581 * hook to usual swap-out path will catch the event.
2584 SetPageCgroupMigration(pc
);
2586 unlock_page_cgroup(pc
);
2588 * If the page is not charged at this point,
2595 ret
= __mem_cgroup_try_charge(NULL
, GFP_KERNEL
, ptr
, false);
2596 css_put(&mem
->css
);/* drop extra refcnt */
2597 if (ret
|| *ptr
== NULL
) {
2598 if (PageAnon(page
)) {
2599 lock_page_cgroup(pc
);
2600 ClearPageCgroupMigration(pc
);
2601 unlock_page_cgroup(pc
);
2603 * The old page may be fully unmapped while we kept it.
2605 mem_cgroup_uncharge_page(page
);
2610 * We charge new page before it's used/mapped. So, even if unlock_page()
2611 * is called before end_migration, we can catch all events on this new
2612 * page. In the case new page is migrated but not remapped, new page's
2613 * mapcount will be finally 0 and we call uncharge in end_migration().
2615 pc
= lookup_page_cgroup(newpage
);
2617 ctype
= MEM_CGROUP_CHARGE_TYPE_MAPPED
;
2618 else if (page_is_file_cache(page
))
2619 ctype
= MEM_CGROUP_CHARGE_TYPE_CACHE
;
2621 ctype
= MEM_CGROUP_CHARGE_TYPE_SHMEM
;
2622 __mem_cgroup_commit_charge(mem
, pc
, ctype
);
2626 /* remove redundant charge if migration failed*/
2627 void mem_cgroup_end_migration(struct mem_cgroup
*mem
,
2628 struct page
*oldpage
, struct page
*newpage
)
2630 struct page
*used
, *unused
;
2631 struct page_cgroup
*pc
;
2635 /* blocks rmdir() */
2636 cgroup_exclude_rmdir(&mem
->css
);
2637 /* at migration success, oldpage->mapping is NULL. */
2638 if (oldpage
->mapping
) {
2646 * We disallowed uncharge of pages under migration because mapcount
2647 * of the page goes down to zero, temporarly.
2648 * Clear the flag and check the page should be charged.
2650 pc
= lookup_page_cgroup(oldpage
);
2651 lock_page_cgroup(pc
);
2652 ClearPageCgroupMigration(pc
);
2653 unlock_page_cgroup(pc
);
2655 if (unused
!= oldpage
)
2656 pc
= lookup_page_cgroup(unused
);
2657 __mem_cgroup_uncharge_common(unused
, MEM_CGROUP_CHARGE_TYPE_FORCE
);
2659 pc
= lookup_page_cgroup(used
);
2661 * If a page is a file cache, radix-tree replacement is very atomic
2662 * and we can skip this check. When it was an Anon page, its mapcount
2663 * goes down to 0. But because we added MIGRATION flage, it's not
2664 * uncharged yet. There are several case but page->mapcount check
2665 * and USED bit check in mem_cgroup_uncharge_page() will do enough
2666 * check. (see prepare_charge() also)
2669 mem_cgroup_uncharge_page(used
);
2671 * At migration, we may charge account against cgroup which has no
2673 * So, rmdir()->pre_destroy() can be called while we do this charge.
2674 * In that case, we need to call pre_destroy() again. check it here.
2676 cgroup_release_and_wakeup_rmdir(&mem
->css
);
2680 * A call to try to shrink memory usage on charge failure at shmem's swapin.
2681 * Calling hierarchical_reclaim is not enough because we should update
2682 * last_oom_jiffies to prevent pagefault_out_of_memory from invoking global OOM.
2683 * Moreover considering hierarchy, we should reclaim from the mem_over_limit,
2684 * not from the memcg which this page would be charged to.
2685 * try_charge_swapin does all of these works properly.
2687 int mem_cgroup_shmem_charge_fallback(struct page
*page
,
2688 struct mm_struct
*mm
,
2691 struct mem_cgroup
*mem
= NULL
;
2694 if (mem_cgroup_disabled())
2697 ret
= mem_cgroup_try_charge_swapin(mm
, page
, gfp_mask
, &mem
);
2699 mem_cgroup_cancel_charge_swapin(mem
); /* it does !mem check */
2704 static DEFINE_MUTEX(set_limit_mutex
);
2706 static int mem_cgroup_resize_limit(struct mem_cgroup
*memcg
,
2707 unsigned long long val
)
2710 u64 memswlimit
, memlimit
;
2712 int children
= mem_cgroup_count_children(memcg
);
2713 u64 curusage
, oldusage
;
2717 * For keeping hierarchical_reclaim simple, how long we should retry
2718 * is depends on callers. We set our retry-count to be function
2719 * of # of children which we should visit in this loop.
2721 retry_count
= MEM_CGROUP_RECLAIM_RETRIES
* children
;
2723 oldusage
= res_counter_read_u64(&memcg
->res
, RES_USAGE
);
2726 while (retry_count
) {
2727 if (signal_pending(current
)) {
2732 * Rather than hide all in some function, I do this in
2733 * open coded manner. You see what this really does.
2734 * We have to guarantee mem->res.limit < mem->memsw.limit.
2736 mutex_lock(&set_limit_mutex
);
2737 memswlimit
= res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
);
2738 if (memswlimit
< val
) {
2740 mutex_unlock(&set_limit_mutex
);
2744 memlimit
= res_counter_read_u64(&memcg
->res
, RES_LIMIT
);
2748 ret
= res_counter_set_limit(&memcg
->res
, val
);
2750 if (memswlimit
== val
)
2751 memcg
->memsw_is_minimum
= true;
2753 memcg
->memsw_is_minimum
= false;
2755 mutex_unlock(&set_limit_mutex
);
2760 mem_cgroup_hierarchical_reclaim(memcg
, NULL
, GFP_KERNEL
,
2761 MEM_CGROUP_RECLAIM_SHRINK
);
2762 curusage
= res_counter_read_u64(&memcg
->res
, RES_USAGE
);
2763 /* Usage is reduced ? */
2764 if (curusage
>= oldusage
)
2767 oldusage
= curusage
;
2769 if (!ret
&& enlarge
)
2770 memcg_oom_recover(memcg
);
2775 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup
*memcg
,
2776 unsigned long long val
)
2779 u64 memlimit
, memswlimit
, oldusage
, curusage
;
2780 int children
= mem_cgroup_count_children(memcg
);
2784 /* see mem_cgroup_resize_res_limit */
2785 retry_count
= children
* MEM_CGROUP_RECLAIM_RETRIES
;
2786 oldusage
= res_counter_read_u64(&memcg
->memsw
, RES_USAGE
);
2787 while (retry_count
) {
2788 if (signal_pending(current
)) {
2793 * Rather than hide all in some function, I do this in
2794 * open coded manner. You see what this really does.
2795 * We have to guarantee mem->res.limit < mem->memsw.limit.
2797 mutex_lock(&set_limit_mutex
);
2798 memlimit
= res_counter_read_u64(&memcg
->res
, RES_LIMIT
);
2799 if (memlimit
> val
) {
2801 mutex_unlock(&set_limit_mutex
);
2804 memswlimit
= res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
);
2805 if (memswlimit
< val
)
2807 ret
= res_counter_set_limit(&memcg
->memsw
, val
);
2809 if (memlimit
== val
)
2810 memcg
->memsw_is_minimum
= true;
2812 memcg
->memsw_is_minimum
= false;
2814 mutex_unlock(&set_limit_mutex
);
2819 mem_cgroup_hierarchical_reclaim(memcg
, NULL
, GFP_KERNEL
,
2820 MEM_CGROUP_RECLAIM_NOSWAP
|
2821 MEM_CGROUP_RECLAIM_SHRINK
);
2822 curusage
= res_counter_read_u64(&memcg
->memsw
, RES_USAGE
);
2823 /* Usage is reduced ? */
2824 if (curusage
>= oldusage
)
2827 oldusage
= curusage
;
2829 if (!ret
&& enlarge
)
2830 memcg_oom_recover(memcg
);
2834 unsigned long mem_cgroup_soft_limit_reclaim(struct zone
*zone
, int order
,
2835 gfp_t gfp_mask
, int nid
,
2838 unsigned long nr_reclaimed
= 0;
2839 struct mem_cgroup_per_zone
*mz
, *next_mz
= NULL
;
2840 unsigned long reclaimed
;
2842 struct mem_cgroup_tree_per_zone
*mctz
;
2843 unsigned long long excess
;
2848 mctz
= soft_limit_tree_node_zone(nid
, zid
);
2850 * This loop can run a while, specially if mem_cgroup's continuously
2851 * keep exceeding their soft limit and putting the system under
2858 mz
= mem_cgroup_largest_soft_limit_node(mctz
);
2862 reclaimed
= mem_cgroup_hierarchical_reclaim(mz
->mem
, zone
,
2864 MEM_CGROUP_RECLAIM_SOFT
);
2865 nr_reclaimed
+= reclaimed
;
2866 spin_lock(&mctz
->lock
);
2869 * If we failed to reclaim anything from this memory cgroup
2870 * it is time to move on to the next cgroup
2876 * Loop until we find yet another one.
2878 * By the time we get the soft_limit lock
2879 * again, someone might have aded the
2880 * group back on the RB tree. Iterate to
2881 * make sure we get a different mem.
2882 * mem_cgroup_largest_soft_limit_node returns
2883 * NULL if no other cgroup is present on
2887 __mem_cgroup_largest_soft_limit_node(mctz
);
2888 if (next_mz
== mz
) {
2889 css_put(&next_mz
->mem
->css
);
2891 } else /* next_mz == NULL or other memcg */
2895 __mem_cgroup_remove_exceeded(mz
->mem
, mz
, mctz
);
2896 excess
= res_counter_soft_limit_excess(&mz
->mem
->res
);
2898 * One school of thought says that we should not add
2899 * back the node to the tree if reclaim returns 0.
2900 * But our reclaim could return 0, simply because due
2901 * to priority we are exposing a smaller subset of
2902 * memory to reclaim from. Consider this as a longer
2905 /* If excess == 0, no tree ops */
2906 __mem_cgroup_insert_exceeded(mz
->mem
, mz
, mctz
, excess
);
2907 spin_unlock(&mctz
->lock
);
2908 css_put(&mz
->mem
->css
);
2911 * Could not reclaim anything and there are no more
2912 * mem cgroups to try or we seem to be looping without
2913 * reclaiming anything.
2915 if (!nr_reclaimed
&&
2917 loop
> MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS
))
2919 } while (!nr_reclaimed
);
2921 css_put(&next_mz
->mem
->css
);
2922 return nr_reclaimed
;
2926 * This routine traverse page_cgroup in given list and drop them all.
2927 * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
2929 static int mem_cgroup_force_empty_list(struct mem_cgroup
*mem
,
2930 int node
, int zid
, enum lru_list lru
)
2933 struct mem_cgroup_per_zone
*mz
;
2934 struct page_cgroup
*pc
, *busy
;
2935 unsigned long flags
, loop
;
2936 struct list_head
*list
;
2939 zone
= &NODE_DATA(node
)->node_zones
[zid
];
2940 mz
= mem_cgroup_zoneinfo(mem
, node
, zid
);
2941 list
= &mz
->lists
[lru
];
2943 loop
= MEM_CGROUP_ZSTAT(mz
, lru
);
2944 /* give some margin against EBUSY etc...*/
2949 spin_lock_irqsave(&zone
->lru_lock
, flags
);
2950 if (list_empty(list
)) {
2951 spin_unlock_irqrestore(&zone
->lru_lock
, flags
);
2954 pc
= list_entry(list
->prev
, struct page_cgroup
, lru
);
2956 list_move(&pc
->lru
, list
);
2958 spin_unlock_irqrestore(&zone
->lru_lock
, flags
);
2961 spin_unlock_irqrestore(&zone
->lru_lock
, flags
);
2963 ret
= mem_cgroup_move_parent(pc
, mem
, GFP_KERNEL
);
2967 if (ret
== -EBUSY
|| ret
== -EINVAL
) {
2968 /* found lock contention or "pc" is obsolete. */
2975 if (!ret
&& !list_empty(list
))
2981 * make mem_cgroup's charge to be 0 if there is no task.
2982 * This enables deleting this mem_cgroup.
2984 static int mem_cgroup_force_empty(struct mem_cgroup
*mem
, bool free_all
)
2987 int node
, zid
, shrink
;
2988 int nr_retries
= MEM_CGROUP_RECLAIM_RETRIES
;
2989 struct cgroup
*cgrp
= mem
->css
.cgroup
;
2994 /* should free all ? */
3000 if (cgroup_task_count(cgrp
) || !list_empty(&cgrp
->children
))
3003 if (signal_pending(current
))
3005 /* This is for making all *used* pages to be on LRU. */
3006 lru_add_drain_all();
3007 drain_all_stock_sync();
3009 for_each_node_state(node
, N_HIGH_MEMORY
) {
3010 for (zid
= 0; !ret
&& zid
< MAX_NR_ZONES
; zid
++) {
3013 ret
= mem_cgroup_force_empty_list(mem
,
3022 memcg_oom_recover(mem
);
3023 /* it seems parent cgroup doesn't have enough mem */
3027 /* "ret" should also be checked to ensure all lists are empty. */
3028 } while (mem
->res
.usage
> 0 || ret
);
3034 /* returns EBUSY if there is a task or if we come here twice. */
3035 if (cgroup_task_count(cgrp
) || !list_empty(&cgrp
->children
) || shrink
) {
3039 /* we call try-to-free pages for make this cgroup empty */
3040 lru_add_drain_all();
3041 /* try to free all pages in this cgroup */
3043 while (nr_retries
&& mem
->res
.usage
> 0) {
3046 if (signal_pending(current
)) {
3050 progress
= try_to_free_mem_cgroup_pages(mem
, GFP_KERNEL
,
3051 false, get_swappiness(mem
));
3054 /* maybe some writeback is necessary */
3055 congestion_wait(BLK_RW_ASYNC
, HZ
/10);
3060 /* try move_account...there may be some *locked* pages. */
3064 int mem_cgroup_force_empty_write(struct cgroup
*cont
, unsigned int event
)
3066 return mem_cgroup_force_empty(mem_cgroup_from_cont(cont
), true);
3070 static u64
mem_cgroup_hierarchy_read(struct cgroup
*cont
, struct cftype
*cft
)
3072 return mem_cgroup_from_cont(cont
)->use_hierarchy
;
3075 static int mem_cgroup_hierarchy_write(struct cgroup
*cont
, struct cftype
*cft
,
3079 struct mem_cgroup
*mem
= mem_cgroup_from_cont(cont
);
3080 struct cgroup
*parent
= cont
->parent
;
3081 struct mem_cgroup
*parent_mem
= NULL
;
3084 parent_mem
= mem_cgroup_from_cont(parent
);
3088 * If parent's use_hierarchy is set, we can't make any modifications
3089 * in the child subtrees. If it is unset, then the change can
3090 * occur, provided the current cgroup has no children.
3092 * For the root cgroup, parent_mem is NULL, we allow value to be
3093 * set if there are no children.
3095 if ((!parent_mem
|| !parent_mem
->use_hierarchy
) &&
3096 (val
== 1 || val
== 0)) {
3097 if (list_empty(&cont
->children
))
3098 mem
->use_hierarchy
= val
;
3108 struct mem_cgroup_idx_data
{
3110 enum mem_cgroup_stat_index idx
;
3114 mem_cgroup_get_idx_stat(struct mem_cgroup
*mem
, void *data
)
3116 struct mem_cgroup_idx_data
*d
= data
;
3117 d
->val
+= mem_cgroup_read_stat(mem
, d
->idx
);
3122 mem_cgroup_get_recursive_idx_stat(struct mem_cgroup
*mem
,
3123 enum mem_cgroup_stat_index idx
, s64
*val
)
3125 struct mem_cgroup_idx_data d
;
3128 mem_cgroup_walk_tree(mem
, &d
, mem_cgroup_get_idx_stat
);
3132 static inline u64
mem_cgroup_usage(struct mem_cgroup
*mem
, bool swap
)
3136 if (!mem_cgroup_is_root(mem
)) {
3138 return res_counter_read_u64(&mem
->res
, RES_USAGE
);
3140 return res_counter_read_u64(&mem
->memsw
, RES_USAGE
);
3143 mem_cgroup_get_recursive_idx_stat(mem
, MEM_CGROUP_STAT_CACHE
, &idx_val
);
3145 mem_cgroup_get_recursive_idx_stat(mem
, MEM_CGROUP_STAT_RSS
, &idx_val
);
3149 mem_cgroup_get_recursive_idx_stat(mem
,
3150 MEM_CGROUP_STAT_SWAPOUT
, &idx_val
);
3154 return val
<< PAGE_SHIFT
;
3157 static u64
mem_cgroup_read(struct cgroup
*cont
, struct cftype
*cft
)
3159 struct mem_cgroup
*mem
= mem_cgroup_from_cont(cont
);
3163 type
= MEMFILE_TYPE(cft
->private);
3164 name
= MEMFILE_ATTR(cft
->private);
3167 if (name
== RES_USAGE
)
3168 val
= mem_cgroup_usage(mem
, false);
3170 val
= res_counter_read_u64(&mem
->res
, name
);
3173 if (name
== RES_USAGE
)
3174 val
= mem_cgroup_usage(mem
, true);
3176 val
= res_counter_read_u64(&mem
->memsw
, name
);
3185 * The user of this function is...
3188 static int mem_cgroup_write(struct cgroup
*cont
, struct cftype
*cft
,
3191 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cont
);
3193 unsigned long long val
;
3196 type
= MEMFILE_TYPE(cft
->private);
3197 name
= MEMFILE_ATTR(cft
->private);
3200 if (mem_cgroup_is_root(memcg
)) { /* Can't set limit on root */
3204 /* This function does all necessary parse...reuse it */
3205 ret
= res_counter_memparse_write_strategy(buffer
, &val
);
3209 ret
= mem_cgroup_resize_limit(memcg
, val
);
3211 ret
= mem_cgroup_resize_memsw_limit(memcg
, val
);
3213 case RES_SOFT_LIMIT
:
3214 ret
= res_counter_memparse_write_strategy(buffer
, &val
);
3218 * For memsw, soft limits are hard to implement in terms
3219 * of semantics, for now, we support soft limits for
3220 * control without swap
3223 ret
= res_counter_set_soft_limit(&memcg
->res
, val
);
3228 ret
= -EINVAL
; /* should be BUG() ? */
3234 static void memcg_get_hierarchical_limit(struct mem_cgroup
*memcg
,
3235 unsigned long long *mem_limit
, unsigned long long *memsw_limit
)
3237 struct cgroup
*cgroup
;
3238 unsigned long long min_limit
, min_memsw_limit
, tmp
;
3240 min_limit
= res_counter_read_u64(&memcg
->res
, RES_LIMIT
);
3241 min_memsw_limit
= res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
);
3242 cgroup
= memcg
->css
.cgroup
;
3243 if (!memcg
->use_hierarchy
)
3246 while (cgroup
->parent
) {
3247 cgroup
= cgroup
->parent
;
3248 memcg
= mem_cgroup_from_cont(cgroup
);
3249 if (!memcg
->use_hierarchy
)
3251 tmp
= res_counter_read_u64(&memcg
->res
, RES_LIMIT
);
3252 min_limit
= min(min_limit
, tmp
);
3253 tmp
= res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
);
3254 min_memsw_limit
= min(min_memsw_limit
, tmp
);
3257 *mem_limit
= min_limit
;
3258 *memsw_limit
= min_memsw_limit
;
3262 static int mem_cgroup_reset(struct cgroup
*cont
, unsigned int event
)
3264 struct mem_cgroup
*mem
;
3267 mem
= mem_cgroup_from_cont(cont
);
3268 type
= MEMFILE_TYPE(event
);
3269 name
= MEMFILE_ATTR(event
);
3273 res_counter_reset_max(&mem
->res
);
3275 res_counter_reset_max(&mem
->memsw
);
3279 res_counter_reset_failcnt(&mem
->res
);
3281 res_counter_reset_failcnt(&mem
->memsw
);
3288 static u64
mem_cgroup_move_charge_read(struct cgroup
*cgrp
,
3291 return mem_cgroup_from_cont(cgrp
)->move_charge_at_immigrate
;
3295 static int mem_cgroup_move_charge_write(struct cgroup
*cgrp
,
3296 struct cftype
*cft
, u64 val
)
3298 struct mem_cgroup
*mem
= mem_cgroup_from_cont(cgrp
);
3300 if (val
>= (1 << NR_MOVE_TYPE
))
3303 * We check this value several times in both in can_attach() and
3304 * attach(), so we need cgroup lock to prevent this value from being
3308 mem
->move_charge_at_immigrate
= val
;
3314 static int mem_cgroup_move_charge_write(struct cgroup
*cgrp
,
3315 struct cftype
*cft
, u64 val
)
3322 /* For read statistics */
3338 struct mcs_total_stat
{
3339 s64 stat
[NR_MCS_STAT
];
3345 } memcg_stat_strings
[NR_MCS_STAT
] = {
3346 {"cache", "total_cache"},
3347 {"rss", "total_rss"},
3348 {"mapped_file", "total_mapped_file"},
3349 {"pgpgin", "total_pgpgin"},
3350 {"pgpgout", "total_pgpgout"},
3351 {"swap", "total_swap"},
3352 {"inactive_anon", "total_inactive_anon"},
3353 {"active_anon", "total_active_anon"},
3354 {"inactive_file", "total_inactive_file"},
3355 {"active_file", "total_active_file"},
3356 {"unevictable", "total_unevictable"}
3360 static int mem_cgroup_get_local_stat(struct mem_cgroup
*mem
, void *data
)
3362 struct mcs_total_stat
*s
= data
;
3366 val
= mem_cgroup_read_stat(mem
, MEM_CGROUP_STAT_CACHE
);
3367 s
->stat
[MCS_CACHE
] += val
* PAGE_SIZE
;
3368 val
= mem_cgroup_read_stat(mem
, MEM_CGROUP_STAT_RSS
);
3369 s
->stat
[MCS_RSS
] += val
* PAGE_SIZE
;
3370 val
= mem_cgroup_read_stat(mem
, MEM_CGROUP_STAT_FILE_MAPPED
);
3371 s
->stat
[MCS_FILE_MAPPED
] += val
* PAGE_SIZE
;
3372 val
= mem_cgroup_read_stat(mem
, MEM_CGROUP_STAT_PGPGIN_COUNT
);
3373 s
->stat
[MCS_PGPGIN
] += val
;
3374 val
= mem_cgroup_read_stat(mem
, MEM_CGROUP_STAT_PGPGOUT_COUNT
);
3375 s
->stat
[MCS_PGPGOUT
] += val
;
3376 if (do_swap_account
) {
3377 val
= mem_cgroup_read_stat(mem
, MEM_CGROUP_STAT_SWAPOUT
);
3378 s
->stat
[MCS_SWAP
] += val
* PAGE_SIZE
;
3382 val
= mem_cgroup_get_local_zonestat(mem
, LRU_INACTIVE_ANON
);
3383 s
->stat
[MCS_INACTIVE_ANON
] += val
* PAGE_SIZE
;
3384 val
= mem_cgroup_get_local_zonestat(mem
, LRU_ACTIVE_ANON
);
3385 s
->stat
[MCS_ACTIVE_ANON
] += val
* PAGE_SIZE
;
3386 val
= mem_cgroup_get_local_zonestat(mem
, LRU_INACTIVE_FILE
);
3387 s
->stat
[MCS_INACTIVE_FILE
] += val
* PAGE_SIZE
;
3388 val
= mem_cgroup_get_local_zonestat(mem
, LRU_ACTIVE_FILE
);
3389 s
->stat
[MCS_ACTIVE_FILE
] += val
* PAGE_SIZE
;
3390 val
= mem_cgroup_get_local_zonestat(mem
, LRU_UNEVICTABLE
);
3391 s
->stat
[MCS_UNEVICTABLE
] += val
* PAGE_SIZE
;
3396 mem_cgroup_get_total_stat(struct mem_cgroup
*mem
, struct mcs_total_stat
*s
)
3398 mem_cgroup_walk_tree(mem
, s
, mem_cgroup_get_local_stat
);
3401 static int mem_control_stat_show(struct cgroup
*cont
, struct cftype
*cft
,
3402 struct cgroup_map_cb
*cb
)
3404 struct mem_cgroup
*mem_cont
= mem_cgroup_from_cont(cont
);
3405 struct mcs_total_stat mystat
;
3408 memset(&mystat
, 0, sizeof(mystat
));
3409 mem_cgroup_get_local_stat(mem_cont
, &mystat
);
3411 for (i
= 0; i
< NR_MCS_STAT
; i
++) {
3412 if (i
== MCS_SWAP
&& !do_swap_account
)
3414 cb
->fill(cb
, memcg_stat_strings
[i
].local_name
, mystat
.stat
[i
]);
3417 /* Hierarchical information */
3419 unsigned long long limit
, memsw_limit
;
3420 memcg_get_hierarchical_limit(mem_cont
, &limit
, &memsw_limit
);
3421 cb
->fill(cb
, "hierarchical_memory_limit", limit
);
3422 if (do_swap_account
)
3423 cb
->fill(cb
, "hierarchical_memsw_limit", memsw_limit
);
3426 memset(&mystat
, 0, sizeof(mystat
));
3427 mem_cgroup_get_total_stat(mem_cont
, &mystat
);
3428 for (i
= 0; i
< NR_MCS_STAT
; i
++) {
3429 if (i
== MCS_SWAP
&& !do_swap_account
)
3431 cb
->fill(cb
, memcg_stat_strings
[i
].total_name
, mystat
.stat
[i
]);
3434 #ifdef CONFIG_DEBUG_VM
3435 cb
->fill(cb
, "inactive_ratio", calc_inactive_ratio(mem_cont
, NULL
));
3439 struct mem_cgroup_per_zone
*mz
;
3440 unsigned long recent_rotated
[2] = {0, 0};
3441 unsigned long recent_scanned
[2] = {0, 0};
3443 for_each_online_node(nid
)
3444 for (zid
= 0; zid
< MAX_NR_ZONES
; zid
++) {
3445 mz
= mem_cgroup_zoneinfo(mem_cont
, nid
, zid
);
3447 recent_rotated
[0] +=
3448 mz
->reclaim_stat
.recent_rotated
[0];
3449 recent_rotated
[1] +=
3450 mz
->reclaim_stat
.recent_rotated
[1];
3451 recent_scanned
[0] +=
3452 mz
->reclaim_stat
.recent_scanned
[0];
3453 recent_scanned
[1] +=
3454 mz
->reclaim_stat
.recent_scanned
[1];
3456 cb
->fill(cb
, "recent_rotated_anon", recent_rotated
[0]);
3457 cb
->fill(cb
, "recent_rotated_file", recent_rotated
[1]);
3458 cb
->fill(cb
, "recent_scanned_anon", recent_scanned
[0]);
3459 cb
->fill(cb
, "recent_scanned_file", recent_scanned
[1]);
3466 static u64
mem_cgroup_swappiness_read(struct cgroup
*cgrp
, struct cftype
*cft
)
3468 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
3470 return get_swappiness(memcg
);
3473 static int mem_cgroup_swappiness_write(struct cgroup
*cgrp
, struct cftype
*cft
,
3476 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
3477 struct mem_cgroup
*parent
;
3482 if (cgrp
->parent
== NULL
)
3485 parent
= mem_cgroup_from_cont(cgrp
->parent
);
3489 /* If under hierarchy, only empty-root can set this value */
3490 if ((parent
->use_hierarchy
) ||
3491 (memcg
->use_hierarchy
&& !list_empty(&cgrp
->children
))) {
3496 spin_lock(&memcg
->reclaim_param_lock
);
3497 memcg
->swappiness
= val
;
3498 spin_unlock(&memcg
->reclaim_param_lock
);
3505 static void __mem_cgroup_threshold(struct mem_cgroup
*memcg
, bool swap
)
3507 struct mem_cgroup_threshold_ary
*t
;
3513 t
= rcu_dereference(memcg
->thresholds
.primary
);
3515 t
= rcu_dereference(memcg
->memsw_thresholds
.primary
);
3520 usage
= mem_cgroup_usage(memcg
, swap
);
3523 * current_threshold points to threshold just below usage.
3524 * If it's not true, a threshold was crossed after last
3525 * call of __mem_cgroup_threshold().
3527 i
= t
->current_threshold
;
3530 * Iterate backward over array of thresholds starting from
3531 * current_threshold and check if a threshold is crossed.
3532 * If none of thresholds below usage is crossed, we read
3533 * only one element of the array here.
3535 for (; i
>= 0 && unlikely(t
->entries
[i
].threshold
> usage
); i
--)
3536 eventfd_signal(t
->entries
[i
].eventfd
, 1);
3538 /* i = current_threshold + 1 */
3542 * Iterate forward over array of thresholds starting from
3543 * current_threshold+1 and check if a threshold is crossed.
3544 * If none of thresholds above usage is crossed, we read
3545 * only one element of the array here.
3547 for (; i
< t
->size
&& unlikely(t
->entries
[i
].threshold
<= usage
); i
++)
3548 eventfd_signal(t
->entries
[i
].eventfd
, 1);
3550 /* Update current_threshold */
3551 t
->current_threshold
= i
- 1;
3556 static void mem_cgroup_threshold(struct mem_cgroup
*memcg
)
3558 __mem_cgroup_threshold(memcg
, false);
3559 if (do_swap_account
)
3560 __mem_cgroup_threshold(memcg
, true);
3563 static int compare_thresholds(const void *a
, const void *b
)
3565 const struct mem_cgroup_threshold
*_a
= a
;
3566 const struct mem_cgroup_threshold
*_b
= b
;
3568 return _a
->threshold
- _b
->threshold
;
3571 static int mem_cgroup_oom_notify_cb(struct mem_cgroup
*mem
, void *data
)
3573 struct mem_cgroup_eventfd_list
*ev
;
3575 list_for_each_entry(ev
, &mem
->oom_notify
, list
)
3576 eventfd_signal(ev
->eventfd
, 1);
3580 static void mem_cgroup_oom_notify(struct mem_cgroup
*mem
)
3582 mem_cgroup_walk_tree(mem
, NULL
, mem_cgroup_oom_notify_cb
);
3585 static int mem_cgroup_usage_register_event(struct cgroup
*cgrp
,
3586 struct cftype
*cft
, struct eventfd_ctx
*eventfd
, const char *args
)
3588 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
3589 struct mem_cgroup_thresholds
*thresholds
;
3590 struct mem_cgroup_threshold_ary
*new;
3591 int type
= MEMFILE_TYPE(cft
->private);
3592 u64 threshold
, usage
;
3595 ret
= res_counter_memparse_write_strategy(args
, &threshold
);
3599 mutex_lock(&memcg
->thresholds_lock
);
3602 thresholds
= &memcg
->thresholds
;
3603 else if (type
== _MEMSWAP
)
3604 thresholds
= &memcg
->memsw_thresholds
;
3608 usage
= mem_cgroup_usage(memcg
, type
== _MEMSWAP
);
3610 /* Check if a threshold crossed before adding a new one */
3611 if (thresholds
->primary
)
3612 __mem_cgroup_threshold(memcg
, type
== _MEMSWAP
);
3614 size
= thresholds
->primary
? thresholds
->primary
->size
+ 1 : 1;
3616 /* Allocate memory for new array of thresholds */
3617 new = kmalloc(sizeof(*new) + size
* sizeof(struct mem_cgroup_threshold
),
3625 /* Copy thresholds (if any) to new array */
3626 if (thresholds
->primary
) {
3627 memcpy(new->entries
, thresholds
->primary
->entries
, (size
- 1) *
3628 sizeof(struct mem_cgroup_threshold
));
3631 /* Add new threshold */
3632 new->entries
[size
- 1].eventfd
= eventfd
;
3633 new->entries
[size
- 1].threshold
= threshold
;
3635 /* Sort thresholds. Registering of new threshold isn't time-critical */
3636 sort(new->entries
, size
, sizeof(struct mem_cgroup_threshold
),
3637 compare_thresholds
, NULL
);
3639 /* Find current threshold */
3640 new->current_threshold
= -1;
3641 for (i
= 0; i
< size
; i
++) {
3642 if (new->entries
[i
].threshold
< usage
) {
3644 * new->current_threshold will not be used until
3645 * rcu_assign_pointer(), so it's safe to increment
3648 ++new->current_threshold
;
3652 /* Free old spare buffer and save old primary buffer as spare */
3653 kfree(thresholds
->spare
);
3654 thresholds
->spare
= thresholds
->primary
;
3656 rcu_assign_pointer(thresholds
->primary
, new);
3658 /* To be sure that nobody uses thresholds */
3662 mutex_unlock(&memcg
->thresholds_lock
);
3667 static void mem_cgroup_usage_unregister_event(struct cgroup
*cgrp
,
3668 struct cftype
*cft
, struct eventfd_ctx
*eventfd
)
3670 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
3671 struct mem_cgroup_thresholds
*thresholds
;
3672 struct mem_cgroup_threshold_ary
*new;
3673 int type
= MEMFILE_TYPE(cft
->private);
3677 mutex_lock(&memcg
->thresholds_lock
);
3679 thresholds
= &memcg
->thresholds
;
3680 else if (type
== _MEMSWAP
)
3681 thresholds
= &memcg
->memsw_thresholds
;
3686 * Something went wrong if we trying to unregister a threshold
3687 * if we don't have thresholds
3689 BUG_ON(!thresholds
);
3691 usage
= mem_cgroup_usage(memcg
, type
== _MEMSWAP
);
3693 /* Check if a threshold crossed before removing */
3694 __mem_cgroup_threshold(memcg
, type
== _MEMSWAP
);
3696 /* Calculate new number of threshold */
3698 for (i
= 0; i
< thresholds
->primary
->size
; i
++) {
3699 if (thresholds
->primary
->entries
[i
].eventfd
!= eventfd
)
3703 new = thresholds
->spare
;
3705 /* Set thresholds array to NULL if we don't have thresholds */
3714 /* Copy thresholds and find current threshold */
3715 new->current_threshold
= -1;
3716 for (i
= 0, j
= 0; i
< thresholds
->primary
->size
; i
++) {
3717 if (thresholds
->primary
->entries
[i
].eventfd
== eventfd
)
3720 new->entries
[j
] = thresholds
->primary
->entries
[i
];
3721 if (new->entries
[j
].threshold
< usage
) {
3723 * new->current_threshold will not be used
3724 * until rcu_assign_pointer(), so it's safe to increment
3727 ++new->current_threshold
;
3733 /* Swap primary and spare array */
3734 thresholds
->spare
= thresholds
->primary
;
3735 rcu_assign_pointer(thresholds
->primary
, new);
3737 /* To be sure that nobody uses thresholds */
3740 mutex_unlock(&memcg
->thresholds_lock
);
3743 static int mem_cgroup_oom_register_event(struct cgroup
*cgrp
,
3744 struct cftype
*cft
, struct eventfd_ctx
*eventfd
, const char *args
)
3746 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
3747 struct mem_cgroup_eventfd_list
*event
;
3748 int type
= MEMFILE_TYPE(cft
->private);
3750 BUG_ON(type
!= _OOM_TYPE
);
3751 event
= kmalloc(sizeof(*event
), GFP_KERNEL
);
3755 mutex_lock(&memcg_oom_mutex
);
3757 event
->eventfd
= eventfd
;
3758 list_add(&event
->list
, &memcg
->oom_notify
);
3760 /* already in OOM ? */
3761 if (atomic_read(&memcg
->oom_lock
))
3762 eventfd_signal(eventfd
, 1);
3763 mutex_unlock(&memcg_oom_mutex
);
3768 static void mem_cgroup_oom_unregister_event(struct cgroup
*cgrp
,
3769 struct cftype
*cft
, struct eventfd_ctx
*eventfd
)
3771 struct mem_cgroup
*mem
= mem_cgroup_from_cont(cgrp
);
3772 struct mem_cgroup_eventfd_list
*ev
, *tmp
;
3773 int type
= MEMFILE_TYPE(cft
->private);
3775 BUG_ON(type
!= _OOM_TYPE
);
3777 mutex_lock(&memcg_oom_mutex
);
3779 list_for_each_entry_safe(ev
, tmp
, &mem
->oom_notify
, list
) {
3780 if (ev
->eventfd
== eventfd
) {
3781 list_del(&ev
->list
);
3786 mutex_unlock(&memcg_oom_mutex
);
3789 static int mem_cgroup_oom_control_read(struct cgroup
*cgrp
,
3790 struct cftype
*cft
, struct cgroup_map_cb
*cb
)
3792 struct mem_cgroup
*mem
= mem_cgroup_from_cont(cgrp
);
3794 cb
->fill(cb
, "oom_kill_disable", mem
->oom_kill_disable
);
3796 if (atomic_read(&mem
->oom_lock
))
3797 cb
->fill(cb
, "under_oom", 1);
3799 cb
->fill(cb
, "under_oom", 0);
3805 static int mem_cgroup_oom_control_write(struct cgroup
*cgrp
,
3806 struct cftype
*cft
, u64 val
)
3808 struct mem_cgroup
*mem
= mem_cgroup_from_cont(cgrp
);
3809 struct mem_cgroup
*parent
;
3811 /* cannot set to root cgroup and only 0 and 1 are allowed */
3812 if (!cgrp
->parent
|| !((val
== 0) || (val
== 1)))
3815 parent
= mem_cgroup_from_cont(cgrp
->parent
);
3818 /* oom-kill-disable is a flag for subhierarchy. */
3819 if ((parent
->use_hierarchy
) ||
3820 (mem
->use_hierarchy
&& !list_empty(&cgrp
->children
))) {
3824 mem
->oom_kill_disable
= val
;
3826 memcg_oom_recover(mem
);
3831 static struct cftype mem_cgroup_files
[] = {
3833 .name
= "usage_in_bytes",
3834 .private = MEMFILE_PRIVATE(_MEM
, RES_USAGE
),
3835 .read_u64
= mem_cgroup_read
,
3836 .register_event
= mem_cgroup_usage_register_event
,
3837 .unregister_event
= mem_cgroup_usage_unregister_event
,
3840 .name
= "max_usage_in_bytes",
3841 .private = MEMFILE_PRIVATE(_MEM
, RES_MAX_USAGE
),
3842 .trigger
= mem_cgroup_reset
,
3843 .read_u64
= mem_cgroup_read
,
3846 .name
= "limit_in_bytes",
3847 .private = MEMFILE_PRIVATE(_MEM
, RES_LIMIT
),
3848 .write_string
= mem_cgroup_write
,
3849 .read_u64
= mem_cgroup_read
,
3852 .name
= "soft_limit_in_bytes",
3853 .private = MEMFILE_PRIVATE(_MEM
, RES_SOFT_LIMIT
),
3854 .write_string
= mem_cgroup_write
,
3855 .read_u64
= mem_cgroup_read
,
3859 .private = MEMFILE_PRIVATE(_MEM
, RES_FAILCNT
),
3860 .trigger
= mem_cgroup_reset
,
3861 .read_u64
= mem_cgroup_read
,
3865 .read_map
= mem_control_stat_show
,
3868 .name
= "force_empty",
3869 .trigger
= mem_cgroup_force_empty_write
,
3872 .name
= "use_hierarchy",
3873 .write_u64
= mem_cgroup_hierarchy_write
,
3874 .read_u64
= mem_cgroup_hierarchy_read
,
3877 .name
= "swappiness",
3878 .read_u64
= mem_cgroup_swappiness_read
,
3879 .write_u64
= mem_cgroup_swappiness_write
,
3882 .name
= "move_charge_at_immigrate",
3883 .read_u64
= mem_cgroup_move_charge_read
,
3884 .write_u64
= mem_cgroup_move_charge_write
,
3887 .name
= "oom_control",
3888 .read_map
= mem_cgroup_oom_control_read
,
3889 .write_u64
= mem_cgroup_oom_control_write
,
3890 .register_event
= mem_cgroup_oom_register_event
,
3891 .unregister_event
= mem_cgroup_oom_unregister_event
,
3892 .private = MEMFILE_PRIVATE(_OOM_TYPE
, OOM_CONTROL
),
3896 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3897 static struct cftype memsw_cgroup_files
[] = {
3899 .name
= "memsw.usage_in_bytes",
3900 .private = MEMFILE_PRIVATE(_MEMSWAP
, RES_USAGE
),
3901 .read_u64
= mem_cgroup_read
,
3902 .register_event
= mem_cgroup_usage_register_event
,
3903 .unregister_event
= mem_cgroup_usage_unregister_event
,
3906 .name
= "memsw.max_usage_in_bytes",
3907 .private = MEMFILE_PRIVATE(_MEMSWAP
, RES_MAX_USAGE
),
3908 .trigger
= mem_cgroup_reset
,
3909 .read_u64
= mem_cgroup_read
,
3912 .name
= "memsw.limit_in_bytes",
3913 .private = MEMFILE_PRIVATE(_MEMSWAP
, RES_LIMIT
),
3914 .write_string
= mem_cgroup_write
,
3915 .read_u64
= mem_cgroup_read
,
3918 .name
= "memsw.failcnt",
3919 .private = MEMFILE_PRIVATE(_MEMSWAP
, RES_FAILCNT
),
3920 .trigger
= mem_cgroup_reset
,
3921 .read_u64
= mem_cgroup_read
,
3925 static int register_memsw_files(struct cgroup
*cont
, struct cgroup_subsys
*ss
)
3927 if (!do_swap_account
)
3929 return cgroup_add_files(cont
, ss
, memsw_cgroup_files
,
3930 ARRAY_SIZE(memsw_cgroup_files
));
3933 static int register_memsw_files(struct cgroup
*cont
, struct cgroup_subsys
*ss
)
3939 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup
*mem
, int node
)
3941 struct mem_cgroup_per_node
*pn
;
3942 struct mem_cgroup_per_zone
*mz
;
3944 int zone
, tmp
= node
;
3946 * This routine is called against possible nodes.
3947 * But it's BUG to call kmalloc() against offline node.
3949 * TODO: this routine can waste much memory for nodes which will
3950 * never be onlined. It's better to use memory hotplug callback
3953 if (!node_state(node
, N_NORMAL_MEMORY
))
3955 pn
= kmalloc_node(sizeof(*pn
), GFP_KERNEL
, tmp
);
3959 mem
->info
.nodeinfo
[node
] = pn
;
3960 memset(pn
, 0, sizeof(*pn
));
3962 for (zone
= 0; zone
< MAX_NR_ZONES
; zone
++) {
3963 mz
= &pn
->zoneinfo
[zone
];
3965 INIT_LIST_HEAD(&mz
->lists
[l
]);
3966 mz
->usage_in_excess
= 0;
3967 mz
->on_tree
= false;
3973 static void free_mem_cgroup_per_zone_info(struct mem_cgroup
*mem
, int node
)
3975 kfree(mem
->info
.nodeinfo
[node
]);
3978 static struct mem_cgroup
*mem_cgroup_alloc(void)
3980 struct mem_cgroup
*mem
;
3981 int size
= sizeof(struct mem_cgroup
);
3983 /* Can be very big if MAX_NUMNODES is very big */
3984 if (size
< PAGE_SIZE
)
3985 mem
= kmalloc(size
, GFP_KERNEL
);
3987 mem
= vmalloc(size
);
3992 memset(mem
, 0, size
);
3993 mem
->stat
= alloc_percpu(struct mem_cgroup_stat_cpu
);
3995 if (size
< PAGE_SIZE
)
4005 * At destroying mem_cgroup, references from swap_cgroup can remain.
4006 * (scanning all at force_empty is too costly...)
4008 * Instead of clearing all references at force_empty, we remember
4009 * the number of reference from swap_cgroup and free mem_cgroup when
4010 * it goes down to 0.
4012 * Removal of cgroup itself succeeds regardless of refs from swap.
4015 static void __mem_cgroup_free(struct mem_cgroup
*mem
)
4019 mem_cgroup_remove_from_trees(mem
);
4020 free_css_id(&mem_cgroup_subsys
, &mem
->css
);
4022 for_each_node_state(node
, N_POSSIBLE
)
4023 free_mem_cgroup_per_zone_info(mem
, node
);
4025 free_percpu(mem
->stat
);
4026 if (sizeof(struct mem_cgroup
) < PAGE_SIZE
)
4032 static void mem_cgroup_get(struct mem_cgroup
*mem
)
4034 atomic_inc(&mem
->refcnt
);
4037 static void __mem_cgroup_put(struct mem_cgroup
*mem
, int count
)
4039 if (atomic_sub_and_test(count
, &mem
->refcnt
)) {
4040 struct mem_cgroup
*parent
= parent_mem_cgroup(mem
);
4041 __mem_cgroup_free(mem
);
4043 mem_cgroup_put(parent
);
4047 static void mem_cgroup_put(struct mem_cgroup
*mem
)
4049 __mem_cgroup_put(mem
, 1);
4053 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
4055 static struct mem_cgroup
*parent_mem_cgroup(struct mem_cgroup
*mem
)
4057 if (!mem
->res
.parent
)
4059 return mem_cgroup_from_res_counter(mem
->res
.parent
, res
);
4062 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4063 static void __init
enable_swap_cgroup(void)
4065 if (!mem_cgroup_disabled() && really_do_swap_account
)
4066 do_swap_account
= 1;
4069 static void __init
enable_swap_cgroup(void)
4074 static int mem_cgroup_soft_limit_tree_init(void)
4076 struct mem_cgroup_tree_per_node
*rtpn
;
4077 struct mem_cgroup_tree_per_zone
*rtpz
;
4078 int tmp
, node
, zone
;
4080 for_each_node_state(node
, N_POSSIBLE
) {
4082 if (!node_state(node
, N_NORMAL_MEMORY
))
4084 rtpn
= kzalloc_node(sizeof(*rtpn
), GFP_KERNEL
, tmp
);
4088 soft_limit_tree
.rb_tree_per_node
[node
] = rtpn
;
4090 for (zone
= 0; zone
< MAX_NR_ZONES
; zone
++) {
4091 rtpz
= &rtpn
->rb_tree_per_zone
[zone
];
4092 rtpz
->rb_root
= RB_ROOT
;
4093 spin_lock_init(&rtpz
->lock
);
4099 static struct cgroup_subsys_state
* __ref
4100 mem_cgroup_create(struct cgroup_subsys
*ss
, struct cgroup
*cont
)
4102 struct mem_cgroup
*mem
, *parent
;
4103 long error
= -ENOMEM
;
4106 mem
= mem_cgroup_alloc();
4108 return ERR_PTR(error
);
4110 for_each_node_state(node
, N_POSSIBLE
)
4111 if (alloc_mem_cgroup_per_zone_info(mem
, node
))
4115 if (cont
->parent
== NULL
) {
4117 enable_swap_cgroup();
4119 root_mem_cgroup
= mem
;
4120 if (mem_cgroup_soft_limit_tree_init())
4122 for_each_possible_cpu(cpu
) {
4123 struct memcg_stock_pcp
*stock
=
4124 &per_cpu(memcg_stock
, cpu
);
4125 INIT_WORK(&stock
->work
, drain_local_stock
);
4127 hotcpu_notifier(memcg_stock_cpu_callback
, 0);
4129 parent
= mem_cgroup_from_cont(cont
->parent
);
4130 mem
->use_hierarchy
= parent
->use_hierarchy
;
4131 mem
->oom_kill_disable
= parent
->oom_kill_disable
;
4134 if (parent
&& parent
->use_hierarchy
) {
4135 res_counter_init(&mem
->res
, &parent
->res
);
4136 res_counter_init(&mem
->memsw
, &parent
->memsw
);
4138 * We increment refcnt of the parent to ensure that we can
4139 * safely access it on res_counter_charge/uncharge.
4140 * This refcnt will be decremented when freeing this
4141 * mem_cgroup(see mem_cgroup_put).
4143 mem_cgroup_get(parent
);
4145 res_counter_init(&mem
->res
, NULL
);
4146 res_counter_init(&mem
->memsw
, NULL
);
4148 mem
->last_scanned_child
= 0;
4149 spin_lock_init(&mem
->reclaim_param_lock
);
4150 INIT_LIST_HEAD(&mem
->oom_notify
);
4153 mem
->swappiness
= get_swappiness(parent
);
4154 atomic_set(&mem
->refcnt
, 1);
4155 mem
->move_charge_at_immigrate
= 0;
4156 mutex_init(&mem
->thresholds_lock
);
4159 __mem_cgroup_free(mem
);
4160 root_mem_cgroup
= NULL
;
4161 return ERR_PTR(error
);
4164 static int mem_cgroup_pre_destroy(struct cgroup_subsys
*ss
,
4165 struct cgroup
*cont
)
4167 struct mem_cgroup
*mem
= mem_cgroup_from_cont(cont
);
4169 return mem_cgroup_force_empty(mem
, false);
4172 static void mem_cgroup_destroy(struct cgroup_subsys
*ss
,
4173 struct cgroup
*cont
)
4175 struct mem_cgroup
*mem
= mem_cgroup_from_cont(cont
);
4177 mem_cgroup_put(mem
);
4180 static int mem_cgroup_populate(struct cgroup_subsys
*ss
,
4181 struct cgroup
*cont
)
4185 ret
= cgroup_add_files(cont
, ss
, mem_cgroup_files
,
4186 ARRAY_SIZE(mem_cgroup_files
));
4189 ret
= register_memsw_files(cont
, ss
);
4194 /* Handlers for move charge at task migration. */
4195 #define PRECHARGE_COUNT_AT_ONCE 256
4196 static int mem_cgroup_do_precharge(unsigned long count
)
4199 int batch_count
= PRECHARGE_COUNT_AT_ONCE
;
4200 struct mem_cgroup
*mem
= mc
.to
;
4202 if (mem_cgroup_is_root(mem
)) {
4203 mc
.precharge
+= count
;
4204 /* we don't need css_get for root */
4207 /* try to charge at once */
4209 struct res_counter
*dummy
;
4211 * "mem" cannot be under rmdir() because we've already checked
4212 * by cgroup_lock_live_cgroup() that it is not removed and we
4213 * are still under the same cgroup_mutex. So we can postpone
4216 if (res_counter_charge(&mem
->res
, PAGE_SIZE
* count
, &dummy
))
4218 if (do_swap_account
&& res_counter_charge(&mem
->memsw
,
4219 PAGE_SIZE
* count
, &dummy
)) {
4220 res_counter_uncharge(&mem
->res
, PAGE_SIZE
* count
);
4223 mc
.precharge
+= count
;
4224 VM_BUG_ON(test_bit(CSS_ROOT
, &mem
->css
.flags
));
4225 WARN_ON_ONCE(count
> INT_MAX
);
4226 __css_get(&mem
->css
, (int)count
);
4230 /* fall back to one by one charge */
4232 if (signal_pending(current
)) {
4236 if (!batch_count
--) {
4237 batch_count
= PRECHARGE_COUNT_AT_ONCE
;
4240 ret
= __mem_cgroup_try_charge(NULL
, GFP_KERNEL
, &mem
, false);
4242 /* mem_cgroup_clear_mc() will do uncharge later */
4250 * is_target_pte_for_mc - check a pte whether it is valid for move charge
4251 * @vma: the vma the pte to be checked belongs
4252 * @addr: the address corresponding to the pte to be checked
4253 * @ptent: the pte to be checked
4254 * @target: the pointer the target page or swap ent will be stored(can be NULL)
4257 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
4258 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
4259 * move charge. if @target is not NULL, the page is stored in target->page
4260 * with extra refcnt got(Callers should handle it).
4261 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
4262 * target for charge migration. if @target is not NULL, the entry is stored
4265 * Called with pte lock held.
4272 enum mc_target_type
{
4273 MC_TARGET_NONE
, /* not used */
4278 static struct page
*mc_handle_present_pte(struct vm_area_struct
*vma
,
4279 unsigned long addr
, pte_t ptent
)
4281 struct page
*page
= vm_normal_page(vma
, addr
, ptent
);
4283 if (!page
|| !page_mapped(page
))
4285 if (PageAnon(page
)) {
4286 /* we don't move shared anon */
4287 if (!move_anon() || page_mapcount(page
) > 2)
4289 } else if (!move_file())
4290 /* we ignore mapcount for file pages */
4292 if (!get_page_unless_zero(page
))
4298 static struct page
*mc_handle_swap_pte(struct vm_area_struct
*vma
,
4299 unsigned long addr
, pte_t ptent
, swp_entry_t
*entry
)
4302 struct page
*page
= NULL
;
4303 swp_entry_t ent
= pte_to_swp_entry(ptent
);
4305 if (!move_anon() || non_swap_entry(ent
))
4307 usage_count
= mem_cgroup_count_swap_user(ent
, &page
);
4308 if (usage_count
> 1) { /* we don't move shared anon */
4313 if (do_swap_account
)
4314 entry
->val
= ent
.val
;
4319 static struct page
*mc_handle_file_pte(struct vm_area_struct
*vma
,
4320 unsigned long addr
, pte_t ptent
, swp_entry_t
*entry
)
4322 struct page
*page
= NULL
;
4323 struct inode
*inode
;
4324 struct address_space
*mapping
;
4327 if (!vma
->vm_file
) /* anonymous vma */
4332 inode
= vma
->vm_file
->f_path
.dentry
->d_inode
;
4333 mapping
= vma
->vm_file
->f_mapping
;
4334 if (pte_none(ptent
))
4335 pgoff
= linear_page_index(vma
, addr
);
4336 else /* pte_file(ptent) is true */
4337 pgoff
= pte_to_pgoff(ptent
);
4339 /* page is moved even if it's not RSS of this task(page-faulted). */
4340 if (!mapping_cap_swap_backed(mapping
)) { /* normal file */
4341 page
= find_get_page(mapping
, pgoff
);
4342 } else { /* shmem/tmpfs file. we should take account of swap too. */
4344 mem_cgroup_get_shmem_target(inode
, pgoff
, &page
, &ent
);
4345 if (do_swap_account
)
4346 entry
->val
= ent
.val
;
4352 static int is_target_pte_for_mc(struct vm_area_struct
*vma
,
4353 unsigned long addr
, pte_t ptent
, union mc_target
*target
)
4355 struct page
*page
= NULL
;
4356 struct page_cgroup
*pc
;
4358 swp_entry_t ent
= { .val
= 0 };
4360 if (pte_present(ptent
))
4361 page
= mc_handle_present_pte(vma
, addr
, ptent
);
4362 else if (is_swap_pte(ptent
))
4363 page
= mc_handle_swap_pte(vma
, addr
, ptent
, &ent
);
4364 else if (pte_none(ptent
) || pte_file(ptent
))
4365 page
= mc_handle_file_pte(vma
, addr
, ptent
, &ent
);
4367 if (!page
&& !ent
.val
)
4370 pc
= lookup_page_cgroup(page
);
4372 * Do only loose check w/o page_cgroup lock.
4373 * mem_cgroup_move_account() checks the pc is valid or not under
4376 if (PageCgroupUsed(pc
) && pc
->mem_cgroup
== mc
.from
) {
4377 ret
= MC_TARGET_PAGE
;
4379 target
->page
= page
;
4381 if (!ret
|| !target
)
4384 /* There is a swap entry and a page doesn't exist or isn't charged */
4385 if (ent
.val
&& !ret
&&
4386 css_id(&mc
.from
->css
) == lookup_swap_cgroup(ent
)) {
4387 ret
= MC_TARGET_SWAP
;
4394 static int mem_cgroup_count_precharge_pte_range(pmd_t
*pmd
,
4395 unsigned long addr
, unsigned long end
,
4396 struct mm_walk
*walk
)
4398 struct vm_area_struct
*vma
= walk
->private;
4402 pte
= pte_offset_map_lock(vma
->vm_mm
, pmd
, addr
, &ptl
);
4403 for (; addr
!= end
; pte
++, addr
+= PAGE_SIZE
)
4404 if (is_target_pte_for_mc(vma
, addr
, *pte
, NULL
))
4405 mc
.precharge
++; /* increment precharge temporarily */
4406 pte_unmap_unlock(pte
- 1, ptl
);
4412 static unsigned long mem_cgroup_count_precharge(struct mm_struct
*mm
)
4414 unsigned long precharge
;
4415 struct vm_area_struct
*vma
;
4417 down_read(&mm
->mmap_sem
);
4418 for (vma
= mm
->mmap
; vma
; vma
= vma
->vm_next
) {
4419 struct mm_walk mem_cgroup_count_precharge_walk
= {
4420 .pmd_entry
= mem_cgroup_count_precharge_pte_range
,
4424 if (is_vm_hugetlb_page(vma
))
4426 walk_page_range(vma
->vm_start
, vma
->vm_end
,
4427 &mem_cgroup_count_precharge_walk
);
4429 up_read(&mm
->mmap_sem
);
4431 precharge
= mc
.precharge
;
4437 static int mem_cgroup_precharge_mc(struct mm_struct
*mm
)
4439 return mem_cgroup_do_precharge(mem_cgroup_count_precharge(mm
));
4442 static void mem_cgroup_clear_mc(void)
4444 struct mem_cgroup
*from
= mc
.from
;
4445 struct mem_cgroup
*to
= mc
.to
;
4447 /* we must uncharge all the leftover precharges from mc.to */
4449 __mem_cgroup_cancel_charge(mc
.to
, mc
.precharge
);
4453 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
4454 * we must uncharge here.
4456 if (mc
.moved_charge
) {
4457 __mem_cgroup_cancel_charge(mc
.from
, mc
.moved_charge
);
4458 mc
.moved_charge
= 0;
4460 /* we must fixup refcnts and charges */
4461 if (mc
.moved_swap
) {
4462 WARN_ON_ONCE(mc
.moved_swap
> INT_MAX
);
4463 /* uncharge swap account from the old cgroup */
4464 if (!mem_cgroup_is_root(mc
.from
))
4465 res_counter_uncharge(&mc
.from
->memsw
,
4466 PAGE_SIZE
* mc
.moved_swap
);
4467 __mem_cgroup_put(mc
.from
, mc
.moved_swap
);
4469 if (!mem_cgroup_is_root(mc
.to
)) {
4471 * we charged both to->res and to->memsw, so we should
4474 res_counter_uncharge(&mc
.to
->res
,
4475 PAGE_SIZE
* mc
.moved_swap
);
4476 VM_BUG_ON(test_bit(CSS_ROOT
, &mc
.to
->css
.flags
));
4477 __css_put(&mc
.to
->css
, mc
.moved_swap
);
4479 /* we've already done mem_cgroup_get(mc.to) */
4483 spin_lock(&mc
.lock
);
4486 mc
.moving_task
= NULL
;
4487 spin_unlock(&mc
.lock
);
4488 memcg_oom_recover(from
);
4489 memcg_oom_recover(to
);
4490 wake_up_all(&mc
.waitq
);
4493 static int mem_cgroup_can_attach(struct cgroup_subsys
*ss
,
4494 struct cgroup
*cgroup
,
4495 struct task_struct
*p
,
4499 struct mem_cgroup
*mem
= mem_cgroup_from_cont(cgroup
);
4501 if (mem
->move_charge_at_immigrate
) {
4502 struct mm_struct
*mm
;
4503 struct mem_cgroup
*from
= mem_cgroup_from_task(p
);
4505 VM_BUG_ON(from
== mem
);
4507 mm
= get_task_mm(p
);
4510 /* We move charges only when we move a owner of the mm */
4511 if (mm
->owner
== p
) {
4514 VM_BUG_ON(mc
.precharge
);
4515 VM_BUG_ON(mc
.moved_charge
);
4516 VM_BUG_ON(mc
.moved_swap
);
4517 VM_BUG_ON(mc
.moving_task
);
4518 spin_lock(&mc
.lock
);
4522 mc
.moved_charge
= 0;
4524 mc
.moving_task
= current
;
4525 spin_unlock(&mc
.lock
);
4527 ret
= mem_cgroup_precharge_mc(mm
);
4529 mem_cgroup_clear_mc();
4536 static void mem_cgroup_cancel_attach(struct cgroup_subsys
*ss
,
4537 struct cgroup
*cgroup
,
4538 struct task_struct
*p
,
4541 mem_cgroup_clear_mc();
4544 static int mem_cgroup_move_charge_pte_range(pmd_t
*pmd
,
4545 unsigned long addr
, unsigned long end
,
4546 struct mm_walk
*walk
)
4549 struct vm_area_struct
*vma
= walk
->private;
4554 pte
= pte_offset_map_lock(vma
->vm_mm
, pmd
, addr
, &ptl
);
4555 for (; addr
!= end
; addr
+= PAGE_SIZE
) {
4556 pte_t ptent
= *(pte
++);
4557 union mc_target target
;
4560 struct page_cgroup
*pc
;
4566 type
= is_target_pte_for_mc(vma
, addr
, ptent
, &target
);
4568 case MC_TARGET_PAGE
:
4570 if (isolate_lru_page(page
))
4572 pc
= lookup_page_cgroup(page
);
4573 if (!mem_cgroup_move_account(pc
,
4574 mc
.from
, mc
.to
, false)) {
4576 /* we uncharge from mc.from later. */
4579 putback_lru_page(page
);
4580 put
: /* is_target_pte_for_mc() gets the page */
4583 case MC_TARGET_SWAP
:
4585 if (!mem_cgroup_move_swap_account(ent
,
4586 mc
.from
, mc
.to
, false)) {
4588 /* we fixup refcnts and charges later. */
4596 pte_unmap_unlock(pte
- 1, ptl
);
4601 * We have consumed all precharges we got in can_attach().
4602 * We try charge one by one, but don't do any additional
4603 * charges to mc.to if we have failed in charge once in attach()
4606 ret
= mem_cgroup_do_precharge(1);
4614 static void mem_cgroup_move_charge(struct mm_struct
*mm
)
4616 struct vm_area_struct
*vma
;
4618 lru_add_drain_all();
4619 down_read(&mm
->mmap_sem
);
4620 for (vma
= mm
->mmap
; vma
; vma
= vma
->vm_next
) {
4622 struct mm_walk mem_cgroup_move_charge_walk
= {
4623 .pmd_entry
= mem_cgroup_move_charge_pte_range
,
4627 if (is_vm_hugetlb_page(vma
))
4629 ret
= walk_page_range(vma
->vm_start
, vma
->vm_end
,
4630 &mem_cgroup_move_charge_walk
);
4633 * means we have consumed all precharges and failed in
4634 * doing additional charge. Just abandon here.
4638 up_read(&mm
->mmap_sem
);
4641 static void mem_cgroup_move_task(struct cgroup_subsys
*ss
,
4642 struct cgroup
*cont
,
4643 struct cgroup
*old_cont
,
4644 struct task_struct
*p
,
4647 struct mm_struct
*mm
;
4650 /* no need to move charge */
4653 mm
= get_task_mm(p
);
4655 mem_cgroup_move_charge(mm
);
4658 mem_cgroup_clear_mc();
4660 #else /* !CONFIG_MMU */
4661 static int mem_cgroup_can_attach(struct cgroup_subsys
*ss
,
4662 struct cgroup
*cgroup
,
4663 struct task_struct
*p
,
4668 static void mem_cgroup_cancel_attach(struct cgroup_subsys
*ss
,
4669 struct cgroup
*cgroup
,
4670 struct task_struct
*p
,
4674 static void mem_cgroup_move_task(struct cgroup_subsys
*ss
,
4675 struct cgroup
*cont
,
4676 struct cgroup
*old_cont
,
4677 struct task_struct
*p
,
4683 struct cgroup_subsys mem_cgroup_subsys
= {
4685 .subsys_id
= mem_cgroup_subsys_id
,
4686 .create
= mem_cgroup_create
,
4687 .pre_destroy
= mem_cgroup_pre_destroy
,
4688 .destroy
= mem_cgroup_destroy
,
4689 .populate
= mem_cgroup_populate
,
4690 .can_attach
= mem_cgroup_can_attach
,
4691 .cancel_attach
= mem_cgroup_cancel_attach
,
4692 .attach
= mem_cgroup_move_task
,
4697 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4699 static int __init
disable_swap_account(char *s
)
4701 really_do_swap_account
= 0;
4704 __setup("noswapaccount", disable_swap_account
);