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>
50 #include <linux/oom.h>
53 #include <asm/uaccess.h>
55 #include <trace/events/vmscan.h>
57 struct cgroup_subsys mem_cgroup_subsys __read_mostly
;
58 #define MEM_CGROUP_RECLAIM_RETRIES 5
59 struct mem_cgroup
*root_mem_cgroup __read_mostly
;
61 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
62 /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
63 int do_swap_account __read_mostly
;
64 static int really_do_swap_account __initdata
= 1; /* for remember boot option*/
66 #define do_swap_account (0)
70 * Per memcg event counter is incremented at every pagein/pageout. This counter
71 * is used for trigger some periodic events. This is straightforward and better
72 * than using jiffies etc. to handle periodic memcg event.
74 * These values will be used as !((event) & ((1 <<(thresh)) - 1))
76 #define THRESHOLDS_EVENTS_THRESH (7) /* once in 128 */
77 #define SOFTLIMIT_EVENTS_THRESH (10) /* once in 1024 */
80 * Statistics for memory cgroup.
82 enum mem_cgroup_stat_index
{
84 * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
86 MEM_CGROUP_STAT_CACHE
, /* # of pages charged as cache */
87 MEM_CGROUP_STAT_RSS
, /* # of pages charged as anon rss */
88 MEM_CGROUP_STAT_FILE_MAPPED
, /* # of pages charged as file rss */
89 MEM_CGROUP_STAT_PGPGIN_COUNT
, /* # of pages paged in */
90 MEM_CGROUP_STAT_PGPGOUT_COUNT
, /* # of pages paged out */
91 MEM_CGROUP_STAT_SWAPOUT
, /* # of pages, swapped out */
92 MEM_CGROUP_EVENTS
, /* incremented at every pagein/pageout */
94 MEM_CGROUP_STAT_NSTATS
,
97 struct mem_cgroup_stat_cpu
{
98 s64 count
[MEM_CGROUP_STAT_NSTATS
];
102 * per-zone information in memory controller.
104 struct mem_cgroup_per_zone
{
106 * spin_lock to protect the per cgroup LRU
108 struct list_head lists
[NR_LRU_LISTS
];
109 unsigned long count
[NR_LRU_LISTS
];
111 struct zone_reclaim_stat reclaim_stat
;
112 struct rb_node tree_node
; /* RB tree node */
113 unsigned long long usage_in_excess
;/* Set to the value by which */
114 /* the soft limit is exceeded*/
116 struct mem_cgroup
*mem
; /* Back pointer, we cannot */
117 /* use container_of */
119 /* Macro for accessing counter */
120 #define MEM_CGROUP_ZSTAT(mz, idx) ((mz)->count[(idx)])
122 struct mem_cgroup_per_node
{
123 struct mem_cgroup_per_zone zoneinfo
[MAX_NR_ZONES
];
126 struct mem_cgroup_lru_info
{
127 struct mem_cgroup_per_node
*nodeinfo
[MAX_NUMNODES
];
131 * Cgroups above their limits are maintained in a RB-Tree, independent of
132 * their hierarchy representation
135 struct mem_cgroup_tree_per_zone
{
136 struct rb_root rb_root
;
140 struct mem_cgroup_tree_per_node
{
141 struct mem_cgroup_tree_per_zone rb_tree_per_zone
[MAX_NR_ZONES
];
144 struct mem_cgroup_tree
{
145 struct mem_cgroup_tree_per_node
*rb_tree_per_node
[MAX_NUMNODES
];
148 static struct mem_cgroup_tree soft_limit_tree __read_mostly
;
150 struct mem_cgroup_threshold
{
151 struct eventfd_ctx
*eventfd
;
156 struct mem_cgroup_threshold_ary
{
157 /* An array index points to threshold just below usage. */
158 int current_threshold
;
159 /* Size of entries[] */
161 /* Array of thresholds */
162 struct mem_cgroup_threshold entries
[0];
165 struct mem_cgroup_thresholds
{
166 /* Primary thresholds array */
167 struct mem_cgroup_threshold_ary
*primary
;
169 * Spare threshold array.
170 * This is needed to make mem_cgroup_unregister_event() "never fail".
171 * It must be able to store at least primary->size - 1 entries.
173 struct mem_cgroup_threshold_ary
*spare
;
177 struct mem_cgroup_eventfd_list
{
178 struct list_head list
;
179 struct eventfd_ctx
*eventfd
;
182 static void mem_cgroup_threshold(struct mem_cgroup
*mem
);
183 static void mem_cgroup_oom_notify(struct mem_cgroup
*mem
);
186 * The memory controller data structure. The memory controller controls both
187 * page cache and RSS per cgroup. We would eventually like to provide
188 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
189 * to help the administrator determine what knobs to tune.
191 * TODO: Add a water mark for the memory controller. Reclaim will begin when
192 * we hit the water mark. May be even add a low water mark, such that
193 * no reclaim occurs from a cgroup at it's low water mark, this is
194 * a feature that will be implemented much later in the future.
197 struct cgroup_subsys_state css
;
199 * the counter to account for memory usage
201 struct res_counter res
;
203 * the counter to account for mem+swap usage.
205 struct res_counter memsw
;
207 * Per cgroup active and inactive list, similar to the
208 * per zone LRU lists.
210 struct mem_cgroup_lru_info info
;
213 protect against reclaim related member.
215 spinlock_t reclaim_param_lock
;
218 * While reclaiming in a hierarchy, we cache the last child we
221 int last_scanned_child
;
223 * Should the accounting and control be hierarchical, per subtree?
229 unsigned int swappiness
;
230 /* OOM-Killer disable */
231 int oom_kill_disable
;
233 /* set when res.limit == memsw.limit */
234 bool memsw_is_minimum
;
236 /* protect arrays of thresholds */
237 struct mutex thresholds_lock
;
239 /* thresholds for memory usage. RCU-protected */
240 struct mem_cgroup_thresholds thresholds
;
242 /* thresholds for mem+swap usage. RCU-protected */
243 struct mem_cgroup_thresholds memsw_thresholds
;
245 /* For oom notifier event fd */
246 struct list_head oom_notify
;
249 * Should we move charges of a task when a task is moved into this
250 * mem_cgroup ? And what type of charges should we move ?
252 unsigned long move_charge_at_immigrate
;
256 struct mem_cgroup_stat_cpu
*stat
;
259 /* Stuffs for move charges at task migration. */
261 * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a
262 * left-shifted bitmap of these types.
265 MOVE_CHARGE_TYPE_ANON
, /* private anonymous page and swap of it */
266 MOVE_CHARGE_TYPE_FILE
, /* file page(including tmpfs) and swap of it */
270 /* "mc" and its members are protected by cgroup_mutex */
271 static struct move_charge_struct
{
272 spinlock_t lock
; /* for from, to, moving_task */
273 struct mem_cgroup
*from
;
274 struct mem_cgroup
*to
;
275 unsigned long precharge
;
276 unsigned long moved_charge
;
277 unsigned long moved_swap
;
278 struct task_struct
*moving_task
; /* a task moving charges */
279 wait_queue_head_t waitq
; /* a waitq for other context */
281 .lock
= __SPIN_LOCK_UNLOCKED(mc
.lock
),
282 .waitq
= __WAIT_QUEUE_HEAD_INITIALIZER(mc
.waitq
),
285 static bool move_anon(void)
287 return test_bit(MOVE_CHARGE_TYPE_ANON
,
288 &mc
.to
->move_charge_at_immigrate
);
291 static bool move_file(void)
293 return test_bit(MOVE_CHARGE_TYPE_FILE
,
294 &mc
.to
->move_charge_at_immigrate
);
298 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
299 * limit reclaim to prevent infinite loops, if they ever occur.
301 #define MEM_CGROUP_MAX_RECLAIM_LOOPS (100)
302 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS (2)
305 MEM_CGROUP_CHARGE_TYPE_CACHE
= 0,
306 MEM_CGROUP_CHARGE_TYPE_MAPPED
,
307 MEM_CGROUP_CHARGE_TYPE_SHMEM
, /* used by page migration of shmem */
308 MEM_CGROUP_CHARGE_TYPE_FORCE
, /* used by force_empty */
309 MEM_CGROUP_CHARGE_TYPE_SWAPOUT
, /* for accounting swapcache */
310 MEM_CGROUP_CHARGE_TYPE_DROP
, /* a page was unused swap cache */
314 /* only for here (for easy reading.) */
315 #define PCGF_CACHE (1UL << PCG_CACHE)
316 #define PCGF_USED (1UL << PCG_USED)
317 #define PCGF_LOCK (1UL << PCG_LOCK)
318 /* Not used, but added here for completeness */
319 #define PCGF_ACCT (1UL << PCG_ACCT)
321 /* for encoding cft->private value on file */
324 #define _OOM_TYPE (2)
325 #define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val))
326 #define MEMFILE_TYPE(val) (((val) >> 16) & 0xffff)
327 #define MEMFILE_ATTR(val) ((val) & 0xffff)
328 /* Used for OOM nofiier */
329 #define OOM_CONTROL (0)
332 * Reclaim flags for mem_cgroup_hierarchical_reclaim
334 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
335 #define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
336 #define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
337 #define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
338 #define MEM_CGROUP_RECLAIM_SOFT_BIT 0x2
339 #define MEM_CGROUP_RECLAIM_SOFT (1 << MEM_CGROUP_RECLAIM_SOFT_BIT)
341 static void mem_cgroup_get(struct mem_cgroup
*mem
);
342 static void mem_cgroup_put(struct mem_cgroup
*mem
);
343 static struct mem_cgroup
*parent_mem_cgroup(struct mem_cgroup
*mem
);
344 static void drain_all_stock_async(void);
346 static struct mem_cgroup_per_zone
*
347 mem_cgroup_zoneinfo(struct mem_cgroup
*mem
, int nid
, int zid
)
349 return &mem
->info
.nodeinfo
[nid
]->zoneinfo
[zid
];
352 struct cgroup_subsys_state
*mem_cgroup_css(struct mem_cgroup
*mem
)
357 static struct mem_cgroup_per_zone
*
358 page_cgroup_zoneinfo(struct page_cgroup
*pc
)
360 struct mem_cgroup
*mem
= pc
->mem_cgroup
;
361 int nid
= page_cgroup_nid(pc
);
362 int zid
= page_cgroup_zid(pc
);
367 return mem_cgroup_zoneinfo(mem
, nid
, zid
);
370 static struct mem_cgroup_tree_per_zone
*
371 soft_limit_tree_node_zone(int nid
, int zid
)
373 return &soft_limit_tree
.rb_tree_per_node
[nid
]->rb_tree_per_zone
[zid
];
376 static struct mem_cgroup_tree_per_zone
*
377 soft_limit_tree_from_page(struct page
*page
)
379 int nid
= page_to_nid(page
);
380 int zid
= page_zonenum(page
);
382 return &soft_limit_tree
.rb_tree_per_node
[nid
]->rb_tree_per_zone
[zid
];
386 __mem_cgroup_insert_exceeded(struct mem_cgroup
*mem
,
387 struct mem_cgroup_per_zone
*mz
,
388 struct mem_cgroup_tree_per_zone
*mctz
,
389 unsigned long long new_usage_in_excess
)
391 struct rb_node
**p
= &mctz
->rb_root
.rb_node
;
392 struct rb_node
*parent
= NULL
;
393 struct mem_cgroup_per_zone
*mz_node
;
398 mz
->usage_in_excess
= new_usage_in_excess
;
399 if (!mz
->usage_in_excess
)
403 mz_node
= rb_entry(parent
, struct mem_cgroup_per_zone
,
405 if (mz
->usage_in_excess
< mz_node
->usage_in_excess
)
408 * We can't avoid mem cgroups that are over their soft
409 * limit by the same amount
411 else if (mz
->usage_in_excess
>= mz_node
->usage_in_excess
)
414 rb_link_node(&mz
->tree_node
, parent
, p
);
415 rb_insert_color(&mz
->tree_node
, &mctz
->rb_root
);
420 __mem_cgroup_remove_exceeded(struct mem_cgroup
*mem
,
421 struct mem_cgroup_per_zone
*mz
,
422 struct mem_cgroup_tree_per_zone
*mctz
)
426 rb_erase(&mz
->tree_node
, &mctz
->rb_root
);
431 mem_cgroup_remove_exceeded(struct mem_cgroup
*mem
,
432 struct mem_cgroup_per_zone
*mz
,
433 struct mem_cgroup_tree_per_zone
*mctz
)
435 spin_lock(&mctz
->lock
);
436 __mem_cgroup_remove_exceeded(mem
, mz
, mctz
);
437 spin_unlock(&mctz
->lock
);
441 static void mem_cgroup_update_tree(struct mem_cgroup
*mem
, struct page
*page
)
443 unsigned long long excess
;
444 struct mem_cgroup_per_zone
*mz
;
445 struct mem_cgroup_tree_per_zone
*mctz
;
446 int nid
= page_to_nid(page
);
447 int zid
= page_zonenum(page
);
448 mctz
= soft_limit_tree_from_page(page
);
451 * Necessary to update all ancestors when hierarchy is used.
452 * because their event counter is not touched.
454 for (; mem
; mem
= parent_mem_cgroup(mem
)) {
455 mz
= mem_cgroup_zoneinfo(mem
, nid
, zid
);
456 excess
= res_counter_soft_limit_excess(&mem
->res
);
458 * We have to update the tree if mz is on RB-tree or
459 * mem is over its softlimit.
461 if (excess
|| mz
->on_tree
) {
462 spin_lock(&mctz
->lock
);
463 /* if on-tree, remove it */
465 __mem_cgroup_remove_exceeded(mem
, mz
, mctz
);
467 * Insert again. mz->usage_in_excess will be updated.
468 * If excess is 0, no tree ops.
470 __mem_cgroup_insert_exceeded(mem
, mz
, mctz
, excess
);
471 spin_unlock(&mctz
->lock
);
476 static void mem_cgroup_remove_from_trees(struct mem_cgroup
*mem
)
479 struct mem_cgroup_per_zone
*mz
;
480 struct mem_cgroup_tree_per_zone
*mctz
;
482 for_each_node_state(node
, N_POSSIBLE
) {
483 for (zone
= 0; zone
< MAX_NR_ZONES
; zone
++) {
484 mz
= mem_cgroup_zoneinfo(mem
, node
, zone
);
485 mctz
= soft_limit_tree_node_zone(node
, zone
);
486 mem_cgroup_remove_exceeded(mem
, mz
, mctz
);
491 static inline unsigned long mem_cgroup_get_excess(struct mem_cgroup
*mem
)
493 return res_counter_soft_limit_excess(&mem
->res
) >> PAGE_SHIFT
;
496 static struct mem_cgroup_per_zone
*
497 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone
*mctz
)
499 struct rb_node
*rightmost
= NULL
;
500 struct mem_cgroup_per_zone
*mz
;
504 rightmost
= rb_last(&mctz
->rb_root
);
506 goto done
; /* Nothing to reclaim from */
508 mz
= rb_entry(rightmost
, struct mem_cgroup_per_zone
, tree_node
);
510 * Remove the node now but someone else can add it back,
511 * we will to add it back at the end of reclaim to its correct
512 * position in the tree.
514 __mem_cgroup_remove_exceeded(mz
->mem
, mz
, mctz
);
515 if (!res_counter_soft_limit_excess(&mz
->mem
->res
) ||
516 !css_tryget(&mz
->mem
->css
))
522 static struct mem_cgroup_per_zone
*
523 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone
*mctz
)
525 struct mem_cgroup_per_zone
*mz
;
527 spin_lock(&mctz
->lock
);
528 mz
= __mem_cgroup_largest_soft_limit_node(mctz
);
529 spin_unlock(&mctz
->lock
);
533 static s64
mem_cgroup_read_stat(struct mem_cgroup
*mem
,
534 enum mem_cgroup_stat_index idx
)
539 for_each_possible_cpu(cpu
)
540 val
+= per_cpu(mem
->stat
->count
[idx
], cpu
);
544 static s64
mem_cgroup_local_usage(struct mem_cgroup
*mem
)
548 ret
= mem_cgroup_read_stat(mem
, MEM_CGROUP_STAT_RSS
);
549 ret
+= mem_cgroup_read_stat(mem
, MEM_CGROUP_STAT_CACHE
);
553 static void mem_cgroup_swap_statistics(struct mem_cgroup
*mem
,
556 int val
= (charge
) ? 1 : -1;
557 this_cpu_add(mem
->stat
->count
[MEM_CGROUP_STAT_SWAPOUT
], val
);
560 static void mem_cgroup_charge_statistics(struct mem_cgroup
*mem
,
561 struct page_cgroup
*pc
,
564 int val
= (charge
) ? 1 : -1;
568 if (PageCgroupCache(pc
))
569 __this_cpu_add(mem
->stat
->count
[MEM_CGROUP_STAT_CACHE
], val
);
571 __this_cpu_add(mem
->stat
->count
[MEM_CGROUP_STAT_RSS
], val
);
574 __this_cpu_inc(mem
->stat
->count
[MEM_CGROUP_STAT_PGPGIN_COUNT
]);
576 __this_cpu_inc(mem
->stat
->count
[MEM_CGROUP_STAT_PGPGOUT_COUNT
]);
577 __this_cpu_inc(mem
->stat
->count
[MEM_CGROUP_EVENTS
]);
582 static unsigned long mem_cgroup_get_local_zonestat(struct mem_cgroup
*mem
,
586 struct mem_cgroup_per_zone
*mz
;
589 for_each_online_node(nid
)
590 for (zid
= 0; zid
< MAX_NR_ZONES
; zid
++) {
591 mz
= mem_cgroup_zoneinfo(mem
, nid
, zid
);
592 total
+= MEM_CGROUP_ZSTAT(mz
, idx
);
597 static bool __memcg_event_check(struct mem_cgroup
*mem
, int event_mask_shift
)
601 val
= this_cpu_read(mem
->stat
->count
[MEM_CGROUP_EVENTS
]);
603 return !(val
& ((1 << event_mask_shift
) - 1));
607 * Check events in order.
610 static void memcg_check_events(struct mem_cgroup
*mem
, struct page
*page
)
612 /* threshold event is triggered in finer grain than soft limit */
613 if (unlikely(__memcg_event_check(mem
, THRESHOLDS_EVENTS_THRESH
))) {
614 mem_cgroup_threshold(mem
);
615 if (unlikely(__memcg_event_check(mem
, SOFTLIMIT_EVENTS_THRESH
)))
616 mem_cgroup_update_tree(mem
, page
);
620 static struct mem_cgroup
*mem_cgroup_from_cont(struct cgroup
*cont
)
622 return container_of(cgroup_subsys_state(cont
,
623 mem_cgroup_subsys_id
), struct mem_cgroup
,
627 struct mem_cgroup
*mem_cgroup_from_task(struct task_struct
*p
)
630 * mm_update_next_owner() may clear mm->owner to NULL
631 * if it races with swapoff, page migration, etc.
632 * So this can be called with p == NULL.
637 return container_of(task_subsys_state(p
, mem_cgroup_subsys_id
),
638 struct mem_cgroup
, css
);
641 static struct mem_cgroup
*try_get_mem_cgroup_from_mm(struct mm_struct
*mm
)
643 struct mem_cgroup
*mem
= NULL
;
648 * Because we have no locks, mm->owner's may be being moved to other
649 * cgroup. We use css_tryget() here even if this looks
650 * pessimistic (rather than adding locks here).
654 mem
= mem_cgroup_from_task(rcu_dereference(mm
->owner
));
657 } while (!css_tryget(&mem
->css
));
663 * Call callback function against all cgroup under hierarchy tree.
665 static int mem_cgroup_walk_tree(struct mem_cgroup
*root
, void *data
,
666 int (*func
)(struct mem_cgroup
*, void *))
668 int found
, ret
, nextid
;
669 struct cgroup_subsys_state
*css
;
670 struct mem_cgroup
*mem
;
672 if (!root
->use_hierarchy
)
673 return (*func
)(root
, data
);
681 css
= css_get_next(&mem_cgroup_subsys
, nextid
, &root
->css
,
683 if (css
&& css_tryget(css
))
684 mem
= container_of(css
, struct mem_cgroup
, css
);
688 ret
= (*func
)(mem
, data
);
692 } while (!ret
&& css
);
697 static inline bool mem_cgroup_is_root(struct mem_cgroup
*mem
)
699 return (mem
== root_mem_cgroup
);
703 * Following LRU functions are allowed to be used without PCG_LOCK.
704 * Operations are called by routine of global LRU independently from memcg.
705 * What we have to take care of here is validness of pc->mem_cgroup.
707 * Changes to pc->mem_cgroup happens when
710 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
711 * It is added to LRU before charge.
712 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
713 * When moving account, the page is not on LRU. It's isolated.
716 void mem_cgroup_del_lru_list(struct page
*page
, enum lru_list lru
)
718 struct page_cgroup
*pc
;
719 struct mem_cgroup_per_zone
*mz
;
721 if (mem_cgroup_disabled())
723 pc
= lookup_page_cgroup(page
);
724 /* can happen while we handle swapcache. */
725 if (!TestClearPageCgroupAcctLRU(pc
))
727 VM_BUG_ON(!pc
->mem_cgroup
);
729 * We don't check PCG_USED bit. It's cleared when the "page" is finally
730 * removed from global LRU.
732 mz
= page_cgroup_zoneinfo(pc
);
733 MEM_CGROUP_ZSTAT(mz
, lru
) -= 1;
734 if (mem_cgroup_is_root(pc
->mem_cgroup
))
736 VM_BUG_ON(list_empty(&pc
->lru
));
737 list_del_init(&pc
->lru
);
741 void mem_cgroup_del_lru(struct page
*page
)
743 mem_cgroup_del_lru_list(page
, page_lru(page
));
746 void mem_cgroup_rotate_lru_list(struct page
*page
, enum lru_list lru
)
748 struct mem_cgroup_per_zone
*mz
;
749 struct page_cgroup
*pc
;
751 if (mem_cgroup_disabled())
754 pc
= lookup_page_cgroup(page
);
756 * Used bit is set without atomic ops but after smp_wmb().
757 * For making pc->mem_cgroup visible, insert smp_rmb() here.
760 /* unused or root page is not rotated. */
761 if (!PageCgroupUsed(pc
) || mem_cgroup_is_root(pc
->mem_cgroup
))
763 mz
= page_cgroup_zoneinfo(pc
);
764 list_move(&pc
->lru
, &mz
->lists
[lru
]);
767 void mem_cgroup_add_lru_list(struct page
*page
, enum lru_list lru
)
769 struct page_cgroup
*pc
;
770 struct mem_cgroup_per_zone
*mz
;
772 if (mem_cgroup_disabled())
774 pc
= lookup_page_cgroup(page
);
775 VM_BUG_ON(PageCgroupAcctLRU(pc
));
777 * Used bit is set without atomic ops but after smp_wmb().
778 * For making pc->mem_cgroup visible, insert smp_rmb() here.
781 if (!PageCgroupUsed(pc
))
784 mz
= page_cgroup_zoneinfo(pc
);
785 MEM_CGROUP_ZSTAT(mz
, lru
) += 1;
786 SetPageCgroupAcctLRU(pc
);
787 if (mem_cgroup_is_root(pc
->mem_cgroup
))
789 list_add(&pc
->lru
, &mz
->lists
[lru
]);
793 * At handling SwapCache, pc->mem_cgroup may be changed while it's linked to
794 * lru because the page may.be reused after it's fully uncharged (because of
795 * SwapCache behavior).To handle that, unlink page_cgroup from LRU when charge
796 * it again. This function is only used to charge SwapCache. It's done under
797 * lock_page and expected that zone->lru_lock is never held.
799 static void mem_cgroup_lru_del_before_commit_swapcache(struct page
*page
)
802 struct zone
*zone
= page_zone(page
);
803 struct page_cgroup
*pc
= lookup_page_cgroup(page
);
805 spin_lock_irqsave(&zone
->lru_lock
, flags
);
807 * Forget old LRU when this page_cgroup is *not* used. This Used bit
808 * is guarded by lock_page() because the page is SwapCache.
810 if (!PageCgroupUsed(pc
))
811 mem_cgroup_del_lru_list(page
, page_lru(page
));
812 spin_unlock_irqrestore(&zone
->lru_lock
, flags
);
815 static void mem_cgroup_lru_add_after_commit_swapcache(struct page
*page
)
818 struct zone
*zone
= page_zone(page
);
819 struct page_cgroup
*pc
= lookup_page_cgroup(page
);
821 spin_lock_irqsave(&zone
->lru_lock
, flags
);
822 /* link when the page is linked to LRU but page_cgroup isn't */
823 if (PageLRU(page
) && !PageCgroupAcctLRU(pc
))
824 mem_cgroup_add_lru_list(page
, page_lru(page
));
825 spin_unlock_irqrestore(&zone
->lru_lock
, flags
);
829 void mem_cgroup_move_lists(struct page
*page
,
830 enum lru_list from
, enum lru_list to
)
832 if (mem_cgroup_disabled())
834 mem_cgroup_del_lru_list(page
, from
);
835 mem_cgroup_add_lru_list(page
, to
);
838 int task_in_mem_cgroup(struct task_struct
*task
, const struct mem_cgroup
*mem
)
841 struct mem_cgroup
*curr
= NULL
;
842 struct task_struct
*p
;
844 p
= find_lock_task_mm(task
);
847 curr
= try_get_mem_cgroup_from_mm(p
->mm
);
852 * We should check use_hierarchy of "mem" not "curr". Because checking
853 * use_hierarchy of "curr" here make this function true if hierarchy is
854 * enabled in "curr" and "curr" is a child of "mem" in *cgroup*
855 * hierarchy(even if use_hierarchy is disabled in "mem").
857 if (mem
->use_hierarchy
)
858 ret
= css_is_ancestor(&curr
->css
, &mem
->css
);
865 static int calc_inactive_ratio(struct mem_cgroup
*memcg
, unsigned long *present_pages
)
867 unsigned long active
;
868 unsigned long inactive
;
870 unsigned long inactive_ratio
;
872 inactive
= mem_cgroup_get_local_zonestat(memcg
, LRU_INACTIVE_ANON
);
873 active
= mem_cgroup_get_local_zonestat(memcg
, LRU_ACTIVE_ANON
);
875 gb
= (inactive
+ active
) >> (30 - PAGE_SHIFT
);
877 inactive_ratio
= int_sqrt(10 * gb
);
882 present_pages
[0] = inactive
;
883 present_pages
[1] = active
;
886 return inactive_ratio
;
889 int mem_cgroup_inactive_anon_is_low(struct mem_cgroup
*memcg
)
891 unsigned long active
;
892 unsigned long inactive
;
893 unsigned long present_pages
[2];
894 unsigned long inactive_ratio
;
896 inactive_ratio
= calc_inactive_ratio(memcg
, present_pages
);
898 inactive
= present_pages
[0];
899 active
= present_pages
[1];
901 if (inactive
* inactive_ratio
< active
)
907 int mem_cgroup_inactive_file_is_low(struct mem_cgroup
*memcg
)
909 unsigned long active
;
910 unsigned long inactive
;
912 inactive
= mem_cgroup_get_local_zonestat(memcg
, LRU_INACTIVE_FILE
);
913 active
= mem_cgroup_get_local_zonestat(memcg
, LRU_ACTIVE_FILE
);
915 return (active
> inactive
);
918 unsigned long mem_cgroup_zone_nr_pages(struct mem_cgroup
*memcg
,
922 int nid
= zone_to_nid(zone
);
923 int zid
= zone_idx(zone
);
924 struct mem_cgroup_per_zone
*mz
= mem_cgroup_zoneinfo(memcg
, nid
, zid
);
926 return MEM_CGROUP_ZSTAT(mz
, lru
);
929 struct zone_reclaim_stat
*mem_cgroup_get_reclaim_stat(struct mem_cgroup
*memcg
,
932 int nid
= zone_to_nid(zone
);
933 int zid
= zone_idx(zone
);
934 struct mem_cgroup_per_zone
*mz
= mem_cgroup_zoneinfo(memcg
, nid
, zid
);
936 return &mz
->reclaim_stat
;
939 struct zone_reclaim_stat
*
940 mem_cgroup_get_reclaim_stat_from_page(struct page
*page
)
942 struct page_cgroup
*pc
;
943 struct mem_cgroup_per_zone
*mz
;
945 if (mem_cgroup_disabled())
948 pc
= lookup_page_cgroup(page
);
950 * Used bit is set without atomic ops but after smp_wmb().
951 * For making pc->mem_cgroup visible, insert smp_rmb() here.
954 if (!PageCgroupUsed(pc
))
957 mz
= page_cgroup_zoneinfo(pc
);
961 return &mz
->reclaim_stat
;
964 unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan
,
965 struct list_head
*dst
,
966 unsigned long *scanned
, int order
,
967 int mode
, struct zone
*z
,
968 struct mem_cgroup
*mem_cont
,
969 int active
, int file
)
971 unsigned long nr_taken
= 0;
975 struct list_head
*src
;
976 struct page_cgroup
*pc
, *tmp
;
977 int nid
= zone_to_nid(z
);
978 int zid
= zone_idx(z
);
979 struct mem_cgroup_per_zone
*mz
;
980 int lru
= LRU_FILE
* file
+ active
;
984 mz
= mem_cgroup_zoneinfo(mem_cont
, nid
, zid
);
985 src
= &mz
->lists
[lru
];
988 list_for_each_entry_safe_reverse(pc
, tmp
, src
, lru
) {
989 if (scan
>= nr_to_scan
)
993 if (unlikely(!PageCgroupUsed(pc
)))
995 if (unlikely(!PageLRU(page
)))
999 ret
= __isolate_lru_page(page
, mode
, file
);
1002 list_move(&page
->lru
, dst
);
1003 mem_cgroup_del_lru(page
);
1007 /* we don't affect global LRU but rotate in our LRU */
1008 mem_cgroup_rotate_lru_list(page
, page_lru(page
));
1017 trace_mm_vmscan_memcg_isolate(0, nr_to_scan
, scan
, nr_taken
,
1023 #define mem_cgroup_from_res_counter(counter, member) \
1024 container_of(counter, struct mem_cgroup, member)
1026 static bool mem_cgroup_check_under_limit(struct mem_cgroup
*mem
)
1028 if (do_swap_account
) {
1029 if (res_counter_check_under_limit(&mem
->res
) &&
1030 res_counter_check_under_limit(&mem
->memsw
))
1033 if (res_counter_check_under_limit(&mem
->res
))
1038 static unsigned int get_swappiness(struct mem_cgroup
*memcg
)
1040 struct cgroup
*cgrp
= memcg
->css
.cgroup
;
1041 unsigned int swappiness
;
1044 if (cgrp
->parent
== NULL
)
1045 return vm_swappiness
;
1047 spin_lock(&memcg
->reclaim_param_lock
);
1048 swappiness
= memcg
->swappiness
;
1049 spin_unlock(&memcg
->reclaim_param_lock
);
1054 /* A routine for testing mem is not under move_account */
1056 static bool mem_cgroup_under_move(struct mem_cgroup
*mem
)
1058 struct mem_cgroup
*from
;
1059 struct mem_cgroup
*to
;
1062 * Unlike task_move routines, we access mc.to, mc.from not under
1063 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1065 spin_lock(&mc
.lock
);
1070 if (from
== mem
|| to
== mem
1071 || (mem
->use_hierarchy
&& css_is_ancestor(&from
->css
, &mem
->css
))
1072 || (mem
->use_hierarchy
&& css_is_ancestor(&to
->css
, &mem
->css
)))
1075 spin_unlock(&mc
.lock
);
1079 static bool mem_cgroup_wait_acct_move(struct mem_cgroup
*mem
)
1081 if (mc
.moving_task
&& current
!= mc
.moving_task
) {
1082 if (mem_cgroup_under_move(mem
)) {
1084 prepare_to_wait(&mc
.waitq
, &wait
, TASK_INTERRUPTIBLE
);
1085 /* moving charge context might have finished. */
1088 finish_wait(&mc
.waitq
, &wait
);
1095 static int mem_cgroup_count_children_cb(struct mem_cgroup
*mem
, void *data
)
1103 * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode.
1104 * @memcg: The memory cgroup that went over limit
1105 * @p: Task that is going to be killed
1107 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1110 void mem_cgroup_print_oom_info(struct mem_cgroup
*memcg
, struct task_struct
*p
)
1112 struct cgroup
*task_cgrp
;
1113 struct cgroup
*mem_cgrp
;
1115 * Need a buffer in BSS, can't rely on allocations. The code relies
1116 * on the assumption that OOM is serialized for memory controller.
1117 * If this assumption is broken, revisit this code.
1119 static char memcg_name
[PATH_MAX
];
1128 mem_cgrp
= memcg
->css
.cgroup
;
1129 task_cgrp
= task_cgroup(p
, mem_cgroup_subsys_id
);
1131 ret
= cgroup_path(task_cgrp
, memcg_name
, PATH_MAX
);
1134 * Unfortunately, we are unable to convert to a useful name
1135 * But we'll still print out the usage information
1142 printk(KERN_INFO
"Task in %s killed", memcg_name
);
1145 ret
= cgroup_path(mem_cgrp
, memcg_name
, PATH_MAX
);
1153 * Continues from above, so we don't need an KERN_ level
1155 printk(KERN_CONT
" as a result of limit of %s\n", memcg_name
);
1158 printk(KERN_INFO
"memory: usage %llukB, limit %llukB, failcnt %llu\n",
1159 res_counter_read_u64(&memcg
->res
, RES_USAGE
) >> 10,
1160 res_counter_read_u64(&memcg
->res
, RES_LIMIT
) >> 10,
1161 res_counter_read_u64(&memcg
->res
, RES_FAILCNT
));
1162 printk(KERN_INFO
"memory+swap: usage %llukB, limit %llukB, "
1164 res_counter_read_u64(&memcg
->memsw
, RES_USAGE
) >> 10,
1165 res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
) >> 10,
1166 res_counter_read_u64(&memcg
->memsw
, RES_FAILCNT
));
1170 * This function returns the number of memcg under hierarchy tree. Returns
1171 * 1(self count) if no children.
1173 static int mem_cgroup_count_children(struct mem_cgroup
*mem
)
1176 mem_cgroup_walk_tree(mem
, &num
, mem_cgroup_count_children_cb
);
1181 * Return the memory (and swap, if configured) limit for a memcg.
1183 u64
mem_cgroup_get_limit(struct mem_cgroup
*memcg
)
1188 limit
= res_counter_read_u64(&memcg
->res
, RES_LIMIT
) +
1190 memsw
= res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
);
1192 * If memsw is finite and limits the amount of swap space available
1193 * to this memcg, return that limit.
1195 return min(limit
, memsw
);
1199 * Visit the first child (need not be the first child as per the ordering
1200 * of the cgroup list, since we track last_scanned_child) of @mem and use
1201 * that to reclaim free pages from.
1203 static struct mem_cgroup
*
1204 mem_cgroup_select_victim(struct mem_cgroup
*root_mem
)
1206 struct mem_cgroup
*ret
= NULL
;
1207 struct cgroup_subsys_state
*css
;
1210 if (!root_mem
->use_hierarchy
) {
1211 css_get(&root_mem
->css
);
1217 nextid
= root_mem
->last_scanned_child
+ 1;
1218 css
= css_get_next(&mem_cgroup_subsys
, nextid
, &root_mem
->css
,
1220 if (css
&& css_tryget(css
))
1221 ret
= container_of(css
, struct mem_cgroup
, css
);
1224 /* Updates scanning parameter */
1225 spin_lock(&root_mem
->reclaim_param_lock
);
1227 /* this means start scan from ID:1 */
1228 root_mem
->last_scanned_child
= 0;
1230 root_mem
->last_scanned_child
= found
;
1231 spin_unlock(&root_mem
->reclaim_param_lock
);
1238 * Scan the hierarchy if needed to reclaim memory. We remember the last child
1239 * we reclaimed from, so that we don't end up penalizing one child extensively
1240 * based on its position in the children list.
1242 * root_mem is the original ancestor that we've been reclaim from.
1244 * We give up and return to the caller when we visit root_mem twice.
1245 * (other groups can be removed while we're walking....)
1247 * If shrink==true, for avoiding to free too much, this returns immedieately.
1249 static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup
*root_mem
,
1252 unsigned long reclaim_options
)
1254 struct mem_cgroup
*victim
;
1257 bool noswap
= reclaim_options
& MEM_CGROUP_RECLAIM_NOSWAP
;
1258 bool shrink
= reclaim_options
& MEM_CGROUP_RECLAIM_SHRINK
;
1259 bool check_soft
= reclaim_options
& MEM_CGROUP_RECLAIM_SOFT
;
1260 unsigned long excess
= mem_cgroup_get_excess(root_mem
);
1262 /* If memsw_is_minimum==1, swap-out is of-no-use. */
1263 if (root_mem
->memsw_is_minimum
)
1267 victim
= mem_cgroup_select_victim(root_mem
);
1268 if (victim
== root_mem
) {
1271 drain_all_stock_async();
1274 * If we have not been able to reclaim
1275 * anything, it might because there are
1276 * no reclaimable pages under this hierarchy
1278 if (!check_soft
|| !total
) {
1279 css_put(&victim
->css
);
1283 * We want to do more targetted reclaim.
1284 * excess >> 2 is not to excessive so as to
1285 * reclaim too much, nor too less that we keep
1286 * coming back to reclaim from this cgroup
1288 if (total
>= (excess
>> 2) ||
1289 (loop
> MEM_CGROUP_MAX_RECLAIM_LOOPS
)) {
1290 css_put(&victim
->css
);
1295 if (!mem_cgroup_local_usage(victim
)) {
1296 /* this cgroup's local usage == 0 */
1297 css_put(&victim
->css
);
1300 /* we use swappiness of local cgroup */
1302 ret
= mem_cgroup_shrink_node_zone(victim
, gfp_mask
,
1303 noswap
, get_swappiness(victim
), zone
);
1305 ret
= try_to_free_mem_cgroup_pages(victim
, gfp_mask
,
1306 noswap
, get_swappiness(victim
));
1307 css_put(&victim
->css
);
1309 * At shrinking usage, we can't check we should stop here or
1310 * reclaim more. It's depends on callers. last_scanned_child
1311 * will work enough for keeping fairness under tree.
1317 if (res_counter_check_under_soft_limit(&root_mem
->res
))
1319 } else if (mem_cgroup_check_under_limit(root_mem
))
1325 static int mem_cgroup_oom_lock_cb(struct mem_cgroup
*mem
, void *data
)
1327 int *val
= (int *)data
;
1330 * Logically, we can stop scanning immediately when we find
1331 * a memcg is already locked. But condidering unlock ops and
1332 * creation/removal of memcg, scan-all is simple operation.
1334 x
= atomic_inc_return(&mem
->oom_lock
);
1335 *val
= max(x
, *val
);
1339 * Check OOM-Killer is already running under our hierarchy.
1340 * If someone is running, return false.
1342 static bool mem_cgroup_oom_lock(struct mem_cgroup
*mem
)
1346 mem_cgroup_walk_tree(mem
, &lock_count
, mem_cgroup_oom_lock_cb
);
1348 if (lock_count
== 1)
1353 static int mem_cgroup_oom_unlock_cb(struct mem_cgroup
*mem
, void *data
)
1356 * When a new child is created while the hierarchy is under oom,
1357 * mem_cgroup_oom_lock() may not be called. We have to use
1358 * atomic_add_unless() here.
1360 atomic_add_unless(&mem
->oom_lock
, -1, 0);
1364 static void mem_cgroup_oom_unlock(struct mem_cgroup
*mem
)
1366 mem_cgroup_walk_tree(mem
, NULL
, mem_cgroup_oom_unlock_cb
);
1369 static DEFINE_MUTEX(memcg_oom_mutex
);
1370 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq
);
1372 struct oom_wait_info
{
1373 struct mem_cgroup
*mem
;
1377 static int memcg_oom_wake_function(wait_queue_t
*wait
,
1378 unsigned mode
, int sync
, void *arg
)
1380 struct mem_cgroup
*wake_mem
= (struct mem_cgroup
*)arg
;
1381 struct oom_wait_info
*oom_wait_info
;
1383 oom_wait_info
= container_of(wait
, struct oom_wait_info
, wait
);
1385 if (oom_wait_info
->mem
== wake_mem
)
1387 /* if no hierarchy, no match */
1388 if (!oom_wait_info
->mem
->use_hierarchy
|| !wake_mem
->use_hierarchy
)
1391 * Both of oom_wait_info->mem and wake_mem are stable under us.
1392 * Then we can use css_is_ancestor without taking care of RCU.
1394 if (!css_is_ancestor(&oom_wait_info
->mem
->css
, &wake_mem
->css
) &&
1395 !css_is_ancestor(&wake_mem
->css
, &oom_wait_info
->mem
->css
))
1399 return autoremove_wake_function(wait
, mode
, sync
, arg
);
1402 static void memcg_wakeup_oom(struct mem_cgroup
*mem
)
1404 /* for filtering, pass "mem" as argument. */
1405 __wake_up(&memcg_oom_waitq
, TASK_NORMAL
, 0, mem
);
1408 static void memcg_oom_recover(struct mem_cgroup
*mem
)
1410 if (mem
&& atomic_read(&mem
->oom_lock
))
1411 memcg_wakeup_oom(mem
);
1415 * try to call OOM killer. returns false if we should exit memory-reclaim loop.
1417 bool mem_cgroup_handle_oom(struct mem_cgroup
*mem
, gfp_t mask
)
1419 struct oom_wait_info owait
;
1420 bool locked
, need_to_kill
;
1423 owait
.wait
.flags
= 0;
1424 owait
.wait
.func
= memcg_oom_wake_function
;
1425 owait
.wait
.private = current
;
1426 INIT_LIST_HEAD(&owait
.wait
.task_list
);
1427 need_to_kill
= true;
1428 /* At first, try to OOM lock hierarchy under mem.*/
1429 mutex_lock(&memcg_oom_mutex
);
1430 locked
= mem_cgroup_oom_lock(mem
);
1432 * Even if signal_pending(), we can't quit charge() loop without
1433 * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
1434 * under OOM is always welcomed, use TASK_KILLABLE here.
1436 prepare_to_wait(&memcg_oom_waitq
, &owait
.wait
, TASK_KILLABLE
);
1437 if (!locked
|| mem
->oom_kill_disable
)
1438 need_to_kill
= false;
1440 mem_cgroup_oom_notify(mem
);
1441 mutex_unlock(&memcg_oom_mutex
);
1444 finish_wait(&memcg_oom_waitq
, &owait
.wait
);
1445 mem_cgroup_out_of_memory(mem
, mask
);
1448 finish_wait(&memcg_oom_waitq
, &owait
.wait
);
1450 mutex_lock(&memcg_oom_mutex
);
1451 mem_cgroup_oom_unlock(mem
);
1452 memcg_wakeup_oom(mem
);
1453 mutex_unlock(&memcg_oom_mutex
);
1455 if (test_thread_flag(TIF_MEMDIE
) || fatal_signal_pending(current
))
1457 /* Give chance to dying process */
1458 schedule_timeout(1);
1463 * Currently used to update mapped file statistics, but the routine can be
1464 * generalized to update other statistics as well.
1466 void mem_cgroup_update_file_mapped(struct page
*page
, int val
)
1468 struct mem_cgroup
*mem
;
1469 struct page_cgroup
*pc
;
1471 pc
= lookup_page_cgroup(page
);
1475 lock_page_cgroup(pc
);
1476 mem
= pc
->mem_cgroup
;
1477 if (!mem
|| !PageCgroupUsed(pc
))
1481 * Preemption is already disabled. We can use __this_cpu_xxx
1484 __this_cpu_inc(mem
->stat
->count
[MEM_CGROUP_STAT_FILE_MAPPED
]);
1485 SetPageCgroupFileMapped(pc
);
1487 __this_cpu_dec(mem
->stat
->count
[MEM_CGROUP_STAT_FILE_MAPPED
]);
1488 ClearPageCgroupFileMapped(pc
);
1492 unlock_page_cgroup(pc
);
1496 * size of first charge trial. "32" comes from vmscan.c's magic value.
1497 * TODO: maybe necessary to use big numbers in big irons.
1499 #define CHARGE_SIZE (32 * PAGE_SIZE)
1500 struct memcg_stock_pcp
{
1501 struct mem_cgroup
*cached
; /* this never be root cgroup */
1503 struct work_struct work
;
1505 static DEFINE_PER_CPU(struct memcg_stock_pcp
, memcg_stock
);
1506 static atomic_t memcg_drain_count
;
1509 * Try to consume stocked charge on this cpu. If success, PAGE_SIZE is consumed
1510 * from local stock and true is returned. If the stock is 0 or charges from a
1511 * cgroup which is not current target, returns false. This stock will be
1514 static bool consume_stock(struct mem_cgroup
*mem
)
1516 struct memcg_stock_pcp
*stock
;
1519 stock
= &get_cpu_var(memcg_stock
);
1520 if (mem
== stock
->cached
&& stock
->charge
)
1521 stock
->charge
-= PAGE_SIZE
;
1522 else /* need to call res_counter_charge */
1524 put_cpu_var(memcg_stock
);
1529 * Returns stocks cached in percpu to res_counter and reset cached information.
1531 static void drain_stock(struct memcg_stock_pcp
*stock
)
1533 struct mem_cgroup
*old
= stock
->cached
;
1535 if (stock
->charge
) {
1536 res_counter_uncharge(&old
->res
, stock
->charge
);
1537 if (do_swap_account
)
1538 res_counter_uncharge(&old
->memsw
, stock
->charge
);
1540 stock
->cached
= NULL
;
1545 * This must be called under preempt disabled or must be called by
1546 * a thread which is pinned to local cpu.
1548 static void drain_local_stock(struct work_struct
*dummy
)
1550 struct memcg_stock_pcp
*stock
= &__get_cpu_var(memcg_stock
);
1555 * Cache charges(val) which is from res_counter, to local per_cpu area.
1556 * This will be consumed by consume_stock() function, later.
1558 static void refill_stock(struct mem_cgroup
*mem
, int val
)
1560 struct memcg_stock_pcp
*stock
= &get_cpu_var(memcg_stock
);
1562 if (stock
->cached
!= mem
) { /* reset if necessary */
1564 stock
->cached
= mem
;
1566 stock
->charge
+= val
;
1567 put_cpu_var(memcg_stock
);
1571 * Tries to drain stocked charges in other cpus. This function is asynchronous
1572 * and just put a work per cpu for draining localy on each cpu. Caller can
1573 * expects some charges will be back to res_counter later but cannot wait for
1576 static void drain_all_stock_async(void)
1579 /* This function is for scheduling "drain" in asynchronous way.
1580 * The result of "drain" is not directly handled by callers. Then,
1581 * if someone is calling drain, we don't have to call drain more.
1582 * Anyway, WORK_STRUCT_PENDING check in queue_work_on() will catch if
1583 * there is a race. We just do loose check here.
1585 if (atomic_read(&memcg_drain_count
))
1587 /* Notify other cpus that system-wide "drain" is running */
1588 atomic_inc(&memcg_drain_count
);
1590 for_each_online_cpu(cpu
) {
1591 struct memcg_stock_pcp
*stock
= &per_cpu(memcg_stock
, cpu
);
1592 schedule_work_on(cpu
, &stock
->work
);
1595 atomic_dec(&memcg_drain_count
);
1596 /* We don't wait for flush_work */
1599 /* This is a synchronous drain interface. */
1600 static void drain_all_stock_sync(void)
1602 /* called when force_empty is called */
1603 atomic_inc(&memcg_drain_count
);
1604 schedule_on_each_cpu(drain_local_stock
);
1605 atomic_dec(&memcg_drain_count
);
1608 static int __cpuinit
memcg_stock_cpu_callback(struct notifier_block
*nb
,
1609 unsigned long action
,
1612 int cpu
= (unsigned long)hcpu
;
1613 struct memcg_stock_pcp
*stock
;
1615 if (action
!= CPU_DEAD
)
1617 stock
= &per_cpu(memcg_stock
, cpu
);
1623 /* See __mem_cgroup_try_charge() for details */
1625 CHARGE_OK
, /* success */
1626 CHARGE_RETRY
, /* need to retry but retry is not bad */
1627 CHARGE_NOMEM
, /* we can't do more. return -ENOMEM */
1628 CHARGE_WOULDBLOCK
, /* GFP_WAIT wasn't set and no enough res. */
1629 CHARGE_OOM_DIE
, /* the current is killed because of OOM */
1632 static int __mem_cgroup_do_charge(struct mem_cgroup
*mem
, gfp_t gfp_mask
,
1633 int csize
, bool oom_check
)
1635 struct mem_cgroup
*mem_over_limit
;
1636 struct res_counter
*fail_res
;
1637 unsigned long flags
= 0;
1640 ret
= res_counter_charge(&mem
->res
, csize
, &fail_res
);
1643 if (!do_swap_account
)
1645 ret
= res_counter_charge(&mem
->memsw
, csize
, &fail_res
);
1649 mem_over_limit
= mem_cgroup_from_res_counter(fail_res
, memsw
);
1650 flags
|= MEM_CGROUP_RECLAIM_NOSWAP
;
1652 mem_over_limit
= mem_cgroup_from_res_counter(fail_res
, res
);
1654 if (csize
> PAGE_SIZE
) /* change csize and retry */
1655 return CHARGE_RETRY
;
1657 if (!(gfp_mask
& __GFP_WAIT
))
1658 return CHARGE_WOULDBLOCK
;
1660 ret
= mem_cgroup_hierarchical_reclaim(mem_over_limit
, NULL
,
1663 * try_to_free_mem_cgroup_pages() might not give us a full
1664 * picture of reclaim. Some pages are reclaimed and might be
1665 * moved to swap cache or just unmapped from the cgroup.
1666 * Check the limit again to see if the reclaim reduced the
1667 * current usage of the cgroup before giving up
1669 if (ret
|| mem_cgroup_check_under_limit(mem_over_limit
))
1670 return CHARGE_RETRY
;
1673 * At task move, charge accounts can be doubly counted. So, it's
1674 * better to wait until the end of task_move if something is going on.
1676 if (mem_cgroup_wait_acct_move(mem_over_limit
))
1677 return CHARGE_RETRY
;
1679 /* If we don't need to call oom-killer at el, return immediately */
1681 return CHARGE_NOMEM
;
1683 if (!mem_cgroup_handle_oom(mem_over_limit
, gfp_mask
))
1684 return CHARGE_OOM_DIE
;
1686 return CHARGE_RETRY
;
1690 * Unlike exported interface, "oom" parameter is added. if oom==true,
1691 * oom-killer can be invoked.
1693 static int __mem_cgroup_try_charge(struct mm_struct
*mm
,
1694 gfp_t gfp_mask
, struct mem_cgroup
**memcg
, bool oom
)
1696 int nr_oom_retries
= MEM_CGROUP_RECLAIM_RETRIES
;
1697 struct mem_cgroup
*mem
= NULL
;
1699 int csize
= CHARGE_SIZE
;
1702 * Unlike gloval-vm's OOM-kill, we're not in memory shortage
1703 * in system level. So, allow to go ahead dying process in addition to
1706 if (unlikely(test_thread_flag(TIF_MEMDIE
)
1707 || fatal_signal_pending(current
)))
1711 * We always charge the cgroup the mm_struct belongs to.
1712 * The mm_struct's mem_cgroup changes on task migration if the
1713 * thread group leader migrates. It's possible that mm is not
1714 * set, if so charge the init_mm (happens for pagecache usage).
1719 if (*memcg
) { /* css should be a valid one */
1721 VM_BUG_ON(css_is_removed(&mem
->css
));
1722 if (mem_cgroup_is_root(mem
))
1724 if (consume_stock(mem
))
1728 struct task_struct
*p
;
1731 p
= rcu_dereference(mm
->owner
);
1734 * because we don't have task_lock(), "p" can exit while
1735 * we're here. In that case, "mem" can point to root
1736 * cgroup but never be NULL. (and task_struct itself is freed
1737 * by RCU, cgroup itself is RCU safe.) Then, we have small
1738 * risk here to get wrong cgroup. But such kind of mis-account
1739 * by race always happens because we don't have cgroup_mutex().
1740 * It's overkill and we allow that small race, here.
1742 mem
= mem_cgroup_from_task(p
);
1744 if (mem_cgroup_is_root(mem
)) {
1748 if (consume_stock(mem
)) {
1750 * It seems dagerous to access memcg without css_get().
1751 * But considering how consume_stok works, it's not
1752 * necessary. If consume_stock success, some charges
1753 * from this memcg are cached on this cpu. So, we
1754 * don't need to call css_get()/css_tryget() before
1755 * calling consume_stock().
1760 /* after here, we may be blocked. we need to get refcnt */
1761 if (!css_tryget(&mem
->css
)) {
1771 /* If killed, bypass charge */
1772 if (fatal_signal_pending(current
)) {
1778 if (oom
&& !nr_oom_retries
) {
1780 nr_oom_retries
= MEM_CGROUP_RECLAIM_RETRIES
;
1783 ret
= __mem_cgroup_do_charge(mem
, gfp_mask
, csize
, oom_check
);
1788 case CHARGE_RETRY
: /* not in OOM situation but retry */
1793 case CHARGE_WOULDBLOCK
: /* !__GFP_WAIT */
1796 case CHARGE_NOMEM
: /* OOM routine works */
1801 /* If oom, we never return -ENOMEM */
1804 case CHARGE_OOM_DIE
: /* Killed by OOM Killer */
1808 } while (ret
!= CHARGE_OK
);
1810 if (csize
> PAGE_SIZE
)
1811 refill_stock(mem
, csize
- PAGE_SIZE
);
1825 * Somemtimes we have to undo a charge we got by try_charge().
1826 * This function is for that and do uncharge, put css's refcnt.
1827 * gotten by try_charge().
1829 static void __mem_cgroup_cancel_charge(struct mem_cgroup
*mem
,
1830 unsigned long count
)
1832 if (!mem_cgroup_is_root(mem
)) {
1833 res_counter_uncharge(&mem
->res
, PAGE_SIZE
* count
);
1834 if (do_swap_account
)
1835 res_counter_uncharge(&mem
->memsw
, PAGE_SIZE
* count
);
1839 static void mem_cgroup_cancel_charge(struct mem_cgroup
*mem
)
1841 __mem_cgroup_cancel_charge(mem
, 1);
1845 * A helper function to get mem_cgroup from ID. must be called under
1846 * rcu_read_lock(). The caller must check css_is_removed() or some if
1847 * it's concern. (dropping refcnt from swap can be called against removed
1850 static struct mem_cgroup
*mem_cgroup_lookup(unsigned short id
)
1852 struct cgroup_subsys_state
*css
;
1854 /* ID 0 is unused ID */
1857 css
= css_lookup(&mem_cgroup_subsys
, id
);
1860 return container_of(css
, struct mem_cgroup
, css
);
1863 struct mem_cgroup
*try_get_mem_cgroup_from_page(struct page
*page
)
1865 struct mem_cgroup
*mem
= NULL
;
1866 struct page_cgroup
*pc
;
1870 VM_BUG_ON(!PageLocked(page
));
1872 pc
= lookup_page_cgroup(page
);
1873 lock_page_cgroup(pc
);
1874 if (PageCgroupUsed(pc
)) {
1875 mem
= pc
->mem_cgroup
;
1876 if (mem
&& !css_tryget(&mem
->css
))
1878 } else if (PageSwapCache(page
)) {
1879 ent
.val
= page_private(page
);
1880 id
= lookup_swap_cgroup(ent
);
1882 mem
= mem_cgroup_lookup(id
);
1883 if (mem
&& !css_tryget(&mem
->css
))
1887 unlock_page_cgroup(pc
);
1892 * commit a charge got by __mem_cgroup_try_charge() and makes page_cgroup to be
1893 * USED state. If already USED, uncharge and return.
1896 static void __mem_cgroup_commit_charge(struct mem_cgroup
*mem
,
1897 struct page_cgroup
*pc
,
1898 enum charge_type ctype
)
1900 /* try_charge() can return NULL to *memcg, taking care of it. */
1904 lock_page_cgroup(pc
);
1905 if (unlikely(PageCgroupUsed(pc
))) {
1906 unlock_page_cgroup(pc
);
1907 mem_cgroup_cancel_charge(mem
);
1911 pc
->mem_cgroup
= mem
;
1913 * We access a page_cgroup asynchronously without lock_page_cgroup().
1914 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
1915 * is accessed after testing USED bit. To make pc->mem_cgroup visible
1916 * before USED bit, we need memory barrier here.
1917 * See mem_cgroup_add_lru_list(), etc.
1921 case MEM_CGROUP_CHARGE_TYPE_CACHE
:
1922 case MEM_CGROUP_CHARGE_TYPE_SHMEM
:
1923 SetPageCgroupCache(pc
);
1924 SetPageCgroupUsed(pc
);
1926 case MEM_CGROUP_CHARGE_TYPE_MAPPED
:
1927 ClearPageCgroupCache(pc
);
1928 SetPageCgroupUsed(pc
);
1934 mem_cgroup_charge_statistics(mem
, pc
, true);
1936 unlock_page_cgroup(pc
);
1938 * "charge_statistics" updated event counter. Then, check it.
1939 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
1940 * if they exceeds softlimit.
1942 memcg_check_events(mem
, pc
->page
);
1946 * __mem_cgroup_move_account - move account of the page
1947 * @pc: page_cgroup of the page.
1948 * @from: mem_cgroup which the page is moved from.
1949 * @to: mem_cgroup which the page is moved to. @from != @to.
1950 * @uncharge: whether we should call uncharge and css_put against @from.
1952 * The caller must confirm following.
1953 * - page is not on LRU (isolate_page() is useful.)
1954 * - the pc is locked, used, and ->mem_cgroup points to @from.
1956 * This function doesn't do "charge" nor css_get to new cgroup. It should be
1957 * done by a caller(__mem_cgroup_try_charge would be usefull). If @uncharge is
1958 * true, this function does "uncharge" from old cgroup, but it doesn't if
1959 * @uncharge is false, so a caller should do "uncharge".
1962 static void __mem_cgroup_move_account(struct page_cgroup
*pc
,
1963 struct mem_cgroup
*from
, struct mem_cgroup
*to
, bool uncharge
)
1965 VM_BUG_ON(from
== to
);
1966 VM_BUG_ON(PageLRU(pc
->page
));
1967 VM_BUG_ON(!PageCgroupLocked(pc
));
1968 VM_BUG_ON(!PageCgroupUsed(pc
));
1969 VM_BUG_ON(pc
->mem_cgroup
!= from
);
1971 if (PageCgroupFileMapped(pc
)) {
1972 /* Update mapped_file data for mem_cgroup */
1974 __this_cpu_dec(from
->stat
->count
[MEM_CGROUP_STAT_FILE_MAPPED
]);
1975 __this_cpu_inc(to
->stat
->count
[MEM_CGROUP_STAT_FILE_MAPPED
]);
1978 mem_cgroup_charge_statistics(from
, pc
, false);
1980 /* This is not "cancel", but cancel_charge does all we need. */
1981 mem_cgroup_cancel_charge(from
);
1983 /* caller should have done css_get */
1984 pc
->mem_cgroup
= to
;
1985 mem_cgroup_charge_statistics(to
, pc
, true);
1987 * We charges against "to" which may not have any tasks. Then, "to"
1988 * can be under rmdir(). But in current implementation, caller of
1989 * this function is just force_empty() and move charge, so it's
1990 * garanteed that "to" is never removed. So, we don't check rmdir
1996 * check whether the @pc is valid for moving account and call
1997 * __mem_cgroup_move_account()
1999 static int mem_cgroup_move_account(struct page_cgroup
*pc
,
2000 struct mem_cgroup
*from
, struct mem_cgroup
*to
, bool uncharge
)
2003 lock_page_cgroup(pc
);
2004 if (PageCgroupUsed(pc
) && pc
->mem_cgroup
== from
) {
2005 __mem_cgroup_move_account(pc
, from
, to
, uncharge
);
2008 unlock_page_cgroup(pc
);
2012 memcg_check_events(to
, pc
->page
);
2013 memcg_check_events(from
, pc
->page
);
2018 * move charges to its parent.
2021 static int mem_cgroup_move_parent(struct page_cgroup
*pc
,
2022 struct mem_cgroup
*child
,
2025 struct page
*page
= pc
->page
;
2026 struct cgroup
*cg
= child
->css
.cgroup
;
2027 struct cgroup
*pcg
= cg
->parent
;
2028 struct mem_cgroup
*parent
;
2036 if (!get_page_unless_zero(page
))
2038 if (isolate_lru_page(page
))
2041 parent
= mem_cgroup_from_cont(pcg
);
2042 ret
= __mem_cgroup_try_charge(NULL
, gfp_mask
, &parent
, false);
2046 ret
= mem_cgroup_move_account(pc
, child
, parent
, true);
2048 mem_cgroup_cancel_charge(parent
);
2050 putback_lru_page(page
);
2058 * Charge the memory controller for page usage.
2060 * 0 if the charge was successful
2061 * < 0 if the cgroup is over its limit
2063 static int mem_cgroup_charge_common(struct page
*page
, struct mm_struct
*mm
,
2064 gfp_t gfp_mask
, enum charge_type ctype
)
2066 struct mem_cgroup
*mem
= NULL
;
2067 struct page_cgroup
*pc
;
2070 pc
= lookup_page_cgroup(page
);
2071 /* can happen at boot */
2076 ret
= __mem_cgroup_try_charge(mm
, gfp_mask
, &mem
, true);
2080 __mem_cgroup_commit_charge(mem
, pc
, ctype
);
2084 int mem_cgroup_newpage_charge(struct page
*page
,
2085 struct mm_struct
*mm
, gfp_t gfp_mask
)
2087 if (mem_cgroup_disabled())
2089 if (PageCompound(page
))
2092 * If already mapped, we don't have to account.
2093 * If page cache, page->mapping has address_space.
2094 * But page->mapping may have out-of-use anon_vma pointer,
2095 * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
2098 if (page_mapped(page
) || (page
->mapping
&& !PageAnon(page
)))
2102 return mem_cgroup_charge_common(page
, mm
, gfp_mask
,
2103 MEM_CGROUP_CHARGE_TYPE_MAPPED
);
2107 __mem_cgroup_commit_charge_swapin(struct page
*page
, struct mem_cgroup
*ptr
,
2108 enum charge_type ctype
);
2110 int mem_cgroup_cache_charge(struct page
*page
, struct mm_struct
*mm
,
2115 if (mem_cgroup_disabled())
2117 if (PageCompound(page
))
2120 * Corner case handling. This is called from add_to_page_cache()
2121 * in usual. But some FS (shmem) precharges this page before calling it
2122 * and call add_to_page_cache() with GFP_NOWAIT.
2124 * For GFP_NOWAIT case, the page may be pre-charged before calling
2125 * add_to_page_cache(). (See shmem.c) check it here and avoid to call
2126 * charge twice. (It works but has to pay a bit larger cost.)
2127 * And when the page is SwapCache, it should take swap information
2128 * into account. This is under lock_page() now.
2130 if (!(gfp_mask
& __GFP_WAIT
)) {
2131 struct page_cgroup
*pc
;
2133 pc
= lookup_page_cgroup(page
);
2136 lock_page_cgroup(pc
);
2137 if (PageCgroupUsed(pc
)) {
2138 unlock_page_cgroup(pc
);
2141 unlock_page_cgroup(pc
);
2147 if (page_is_file_cache(page
))
2148 return mem_cgroup_charge_common(page
, mm
, gfp_mask
,
2149 MEM_CGROUP_CHARGE_TYPE_CACHE
);
2152 if (PageSwapCache(page
)) {
2153 struct mem_cgroup
*mem
= NULL
;
2155 ret
= mem_cgroup_try_charge_swapin(mm
, page
, gfp_mask
, &mem
);
2157 __mem_cgroup_commit_charge_swapin(page
, mem
,
2158 MEM_CGROUP_CHARGE_TYPE_SHMEM
);
2160 ret
= mem_cgroup_charge_common(page
, mm
, gfp_mask
,
2161 MEM_CGROUP_CHARGE_TYPE_SHMEM
);
2167 * While swap-in, try_charge -> commit or cancel, the page is locked.
2168 * And when try_charge() successfully returns, one refcnt to memcg without
2169 * struct page_cgroup is acquired. This refcnt will be consumed by
2170 * "commit()" or removed by "cancel()"
2172 int mem_cgroup_try_charge_swapin(struct mm_struct
*mm
,
2174 gfp_t mask
, struct mem_cgroup
**ptr
)
2176 struct mem_cgroup
*mem
;
2179 if (mem_cgroup_disabled())
2182 if (!do_swap_account
)
2185 * A racing thread's fault, or swapoff, may have already updated
2186 * the pte, and even removed page from swap cache: in those cases
2187 * do_swap_page()'s pte_same() test will fail; but there's also a
2188 * KSM case which does need to charge the page.
2190 if (!PageSwapCache(page
))
2192 mem
= try_get_mem_cgroup_from_page(page
);
2196 ret
= __mem_cgroup_try_charge(NULL
, mask
, ptr
, true);
2202 return __mem_cgroup_try_charge(mm
, mask
, ptr
, true);
2206 __mem_cgroup_commit_charge_swapin(struct page
*page
, struct mem_cgroup
*ptr
,
2207 enum charge_type ctype
)
2209 struct page_cgroup
*pc
;
2211 if (mem_cgroup_disabled())
2215 cgroup_exclude_rmdir(&ptr
->css
);
2216 pc
= lookup_page_cgroup(page
);
2217 mem_cgroup_lru_del_before_commit_swapcache(page
);
2218 __mem_cgroup_commit_charge(ptr
, pc
, ctype
);
2219 mem_cgroup_lru_add_after_commit_swapcache(page
);
2221 * Now swap is on-memory. This means this page may be
2222 * counted both as mem and swap....double count.
2223 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
2224 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
2225 * may call delete_from_swap_cache() before reach here.
2227 if (do_swap_account
&& PageSwapCache(page
)) {
2228 swp_entry_t ent
= {.val
= page_private(page
)};
2230 struct mem_cgroup
*memcg
;
2232 id
= swap_cgroup_record(ent
, 0);
2234 memcg
= mem_cgroup_lookup(id
);
2237 * This recorded memcg can be obsolete one. So, avoid
2238 * calling css_tryget
2240 if (!mem_cgroup_is_root(memcg
))
2241 res_counter_uncharge(&memcg
->memsw
, PAGE_SIZE
);
2242 mem_cgroup_swap_statistics(memcg
, false);
2243 mem_cgroup_put(memcg
);
2248 * At swapin, we may charge account against cgroup which has no tasks.
2249 * So, rmdir()->pre_destroy() can be called while we do this charge.
2250 * In that case, we need to call pre_destroy() again. check it here.
2252 cgroup_release_and_wakeup_rmdir(&ptr
->css
);
2255 void mem_cgroup_commit_charge_swapin(struct page
*page
, struct mem_cgroup
*ptr
)
2257 __mem_cgroup_commit_charge_swapin(page
, ptr
,
2258 MEM_CGROUP_CHARGE_TYPE_MAPPED
);
2261 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup
*mem
)
2263 if (mem_cgroup_disabled())
2267 mem_cgroup_cancel_charge(mem
);
2271 __do_uncharge(struct mem_cgroup
*mem
, const enum charge_type ctype
)
2273 struct memcg_batch_info
*batch
= NULL
;
2274 bool uncharge_memsw
= true;
2275 /* If swapout, usage of swap doesn't decrease */
2276 if (!do_swap_account
|| ctype
== MEM_CGROUP_CHARGE_TYPE_SWAPOUT
)
2277 uncharge_memsw
= false;
2279 batch
= ¤t
->memcg_batch
;
2281 * In usual, we do css_get() when we remember memcg pointer.
2282 * But in this case, we keep res->usage until end of a series of
2283 * uncharges. Then, it's ok to ignore memcg's refcnt.
2288 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
2289 * In those cases, all pages freed continously can be expected to be in
2290 * the same cgroup and we have chance to coalesce uncharges.
2291 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
2292 * because we want to do uncharge as soon as possible.
2295 if (!batch
->do_batch
|| test_thread_flag(TIF_MEMDIE
))
2296 goto direct_uncharge
;
2299 * In typical case, batch->memcg == mem. This means we can
2300 * merge a series of uncharges to an uncharge of res_counter.
2301 * If not, we uncharge res_counter ony by one.
2303 if (batch
->memcg
!= mem
)
2304 goto direct_uncharge
;
2305 /* remember freed charge and uncharge it later */
2306 batch
->bytes
+= PAGE_SIZE
;
2308 batch
->memsw_bytes
+= PAGE_SIZE
;
2311 res_counter_uncharge(&mem
->res
, PAGE_SIZE
);
2313 res_counter_uncharge(&mem
->memsw
, PAGE_SIZE
);
2314 if (unlikely(batch
->memcg
!= mem
))
2315 memcg_oom_recover(mem
);
2320 * uncharge if !page_mapped(page)
2322 static struct mem_cgroup
*
2323 __mem_cgroup_uncharge_common(struct page
*page
, enum charge_type ctype
)
2325 struct page_cgroup
*pc
;
2326 struct mem_cgroup
*mem
= NULL
;
2328 if (mem_cgroup_disabled())
2331 if (PageSwapCache(page
))
2335 * Check if our page_cgroup is valid
2337 pc
= lookup_page_cgroup(page
);
2338 if (unlikely(!pc
|| !PageCgroupUsed(pc
)))
2341 lock_page_cgroup(pc
);
2343 mem
= pc
->mem_cgroup
;
2345 if (!PageCgroupUsed(pc
))
2349 case MEM_CGROUP_CHARGE_TYPE_MAPPED
:
2350 case MEM_CGROUP_CHARGE_TYPE_DROP
:
2351 /* See mem_cgroup_prepare_migration() */
2352 if (page_mapped(page
) || PageCgroupMigration(pc
))
2355 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT
:
2356 if (!PageAnon(page
)) { /* Shared memory */
2357 if (page
->mapping
&& !page_is_file_cache(page
))
2359 } else if (page_mapped(page
)) /* Anon */
2366 mem_cgroup_charge_statistics(mem
, pc
, false);
2368 ClearPageCgroupUsed(pc
);
2370 * pc->mem_cgroup is not cleared here. It will be accessed when it's
2371 * freed from LRU. This is safe because uncharged page is expected not
2372 * to be reused (freed soon). Exception is SwapCache, it's handled by
2373 * special functions.
2376 unlock_page_cgroup(pc
);
2378 * even after unlock, we have mem->res.usage here and this memcg
2379 * will never be freed.
2381 memcg_check_events(mem
, page
);
2382 if (do_swap_account
&& ctype
== MEM_CGROUP_CHARGE_TYPE_SWAPOUT
) {
2383 mem_cgroup_swap_statistics(mem
, true);
2384 mem_cgroup_get(mem
);
2386 if (!mem_cgroup_is_root(mem
))
2387 __do_uncharge(mem
, ctype
);
2392 unlock_page_cgroup(pc
);
2396 void mem_cgroup_uncharge_page(struct page
*page
)
2399 if (page_mapped(page
))
2401 if (page
->mapping
&& !PageAnon(page
))
2403 __mem_cgroup_uncharge_common(page
, MEM_CGROUP_CHARGE_TYPE_MAPPED
);
2406 void mem_cgroup_uncharge_cache_page(struct page
*page
)
2408 VM_BUG_ON(page_mapped(page
));
2409 VM_BUG_ON(page
->mapping
);
2410 __mem_cgroup_uncharge_common(page
, MEM_CGROUP_CHARGE_TYPE_CACHE
);
2414 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
2415 * In that cases, pages are freed continuously and we can expect pages
2416 * are in the same memcg. All these calls itself limits the number of
2417 * pages freed at once, then uncharge_start/end() is called properly.
2418 * This may be called prural(2) times in a context,
2421 void mem_cgroup_uncharge_start(void)
2423 current
->memcg_batch
.do_batch
++;
2424 /* We can do nest. */
2425 if (current
->memcg_batch
.do_batch
== 1) {
2426 current
->memcg_batch
.memcg
= NULL
;
2427 current
->memcg_batch
.bytes
= 0;
2428 current
->memcg_batch
.memsw_bytes
= 0;
2432 void mem_cgroup_uncharge_end(void)
2434 struct memcg_batch_info
*batch
= ¤t
->memcg_batch
;
2436 if (!batch
->do_batch
)
2440 if (batch
->do_batch
) /* If stacked, do nothing. */
2446 * This "batch->memcg" is valid without any css_get/put etc...
2447 * bacause we hide charges behind us.
2450 res_counter_uncharge(&batch
->memcg
->res
, batch
->bytes
);
2451 if (batch
->memsw_bytes
)
2452 res_counter_uncharge(&batch
->memcg
->memsw
, batch
->memsw_bytes
);
2453 memcg_oom_recover(batch
->memcg
);
2454 /* forget this pointer (for sanity check) */
2455 batch
->memcg
= NULL
;
2460 * called after __delete_from_swap_cache() and drop "page" account.
2461 * memcg information is recorded to swap_cgroup of "ent"
2464 mem_cgroup_uncharge_swapcache(struct page
*page
, swp_entry_t ent
, bool swapout
)
2466 struct mem_cgroup
*memcg
;
2467 int ctype
= MEM_CGROUP_CHARGE_TYPE_SWAPOUT
;
2469 if (!swapout
) /* this was a swap cache but the swap is unused ! */
2470 ctype
= MEM_CGROUP_CHARGE_TYPE_DROP
;
2472 memcg
= __mem_cgroup_uncharge_common(page
, ctype
);
2475 * record memcg information, if swapout && memcg != NULL,
2476 * mem_cgroup_get() was called in uncharge().
2478 if (do_swap_account
&& swapout
&& memcg
)
2479 swap_cgroup_record(ent
, css_id(&memcg
->css
));
2483 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
2485 * called from swap_entry_free(). remove record in swap_cgroup and
2486 * uncharge "memsw" account.
2488 void mem_cgroup_uncharge_swap(swp_entry_t ent
)
2490 struct mem_cgroup
*memcg
;
2493 if (!do_swap_account
)
2496 id
= swap_cgroup_record(ent
, 0);
2498 memcg
= mem_cgroup_lookup(id
);
2501 * We uncharge this because swap is freed.
2502 * This memcg can be obsolete one. We avoid calling css_tryget
2504 if (!mem_cgroup_is_root(memcg
))
2505 res_counter_uncharge(&memcg
->memsw
, PAGE_SIZE
);
2506 mem_cgroup_swap_statistics(memcg
, false);
2507 mem_cgroup_put(memcg
);
2513 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
2514 * @entry: swap entry to be moved
2515 * @from: mem_cgroup which the entry is moved from
2516 * @to: mem_cgroup which the entry is moved to
2517 * @need_fixup: whether we should fixup res_counters and refcounts.
2519 * It succeeds only when the swap_cgroup's record for this entry is the same
2520 * as the mem_cgroup's id of @from.
2522 * Returns 0 on success, -EINVAL on failure.
2524 * The caller must have charged to @to, IOW, called res_counter_charge() about
2525 * both res and memsw, and called css_get().
2527 static int mem_cgroup_move_swap_account(swp_entry_t entry
,
2528 struct mem_cgroup
*from
, struct mem_cgroup
*to
, bool need_fixup
)
2530 unsigned short old_id
, new_id
;
2532 old_id
= css_id(&from
->css
);
2533 new_id
= css_id(&to
->css
);
2535 if (swap_cgroup_cmpxchg(entry
, old_id
, new_id
) == old_id
) {
2536 mem_cgroup_swap_statistics(from
, false);
2537 mem_cgroup_swap_statistics(to
, true);
2539 * This function is only called from task migration context now.
2540 * It postpones res_counter and refcount handling till the end
2541 * of task migration(mem_cgroup_clear_mc()) for performance
2542 * improvement. But we cannot postpone mem_cgroup_get(to)
2543 * because if the process that has been moved to @to does
2544 * swap-in, the refcount of @to might be decreased to 0.
2548 if (!mem_cgroup_is_root(from
))
2549 res_counter_uncharge(&from
->memsw
, PAGE_SIZE
);
2550 mem_cgroup_put(from
);
2552 * we charged both to->res and to->memsw, so we should
2555 if (!mem_cgroup_is_root(to
))
2556 res_counter_uncharge(&to
->res
, PAGE_SIZE
);
2563 static inline int mem_cgroup_move_swap_account(swp_entry_t entry
,
2564 struct mem_cgroup
*from
, struct mem_cgroup
*to
, bool need_fixup
)
2571 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
2574 int mem_cgroup_prepare_migration(struct page
*page
,
2575 struct page
*newpage
, struct mem_cgroup
**ptr
)
2577 struct page_cgroup
*pc
;
2578 struct mem_cgroup
*mem
= NULL
;
2579 enum charge_type ctype
;
2582 if (mem_cgroup_disabled())
2585 pc
= lookup_page_cgroup(page
);
2586 lock_page_cgroup(pc
);
2587 if (PageCgroupUsed(pc
)) {
2588 mem
= pc
->mem_cgroup
;
2591 * At migrating an anonymous page, its mapcount goes down
2592 * to 0 and uncharge() will be called. But, even if it's fully
2593 * unmapped, migration may fail and this page has to be
2594 * charged again. We set MIGRATION flag here and delay uncharge
2595 * until end_migration() is called
2597 * Corner Case Thinking
2599 * When the old page was mapped as Anon and it's unmap-and-freed
2600 * while migration was ongoing.
2601 * If unmap finds the old page, uncharge() of it will be delayed
2602 * until end_migration(). If unmap finds a new page, it's
2603 * uncharged when it make mapcount to be 1->0. If unmap code
2604 * finds swap_migration_entry, the new page will not be mapped
2605 * and end_migration() will find it(mapcount==0).
2608 * When the old page was mapped but migraion fails, the kernel
2609 * remaps it. A charge for it is kept by MIGRATION flag even
2610 * if mapcount goes down to 0. We can do remap successfully
2611 * without charging it again.
2614 * The "old" page is under lock_page() until the end of
2615 * migration, so, the old page itself will not be swapped-out.
2616 * If the new page is swapped out before end_migraton, our
2617 * hook to usual swap-out path will catch the event.
2620 SetPageCgroupMigration(pc
);
2622 unlock_page_cgroup(pc
);
2624 * If the page is not charged at this point,
2631 ret
= __mem_cgroup_try_charge(NULL
, GFP_KERNEL
, ptr
, false);
2632 css_put(&mem
->css
);/* drop extra refcnt */
2633 if (ret
|| *ptr
== NULL
) {
2634 if (PageAnon(page
)) {
2635 lock_page_cgroup(pc
);
2636 ClearPageCgroupMigration(pc
);
2637 unlock_page_cgroup(pc
);
2639 * The old page may be fully unmapped while we kept it.
2641 mem_cgroup_uncharge_page(page
);
2646 * We charge new page before it's used/mapped. So, even if unlock_page()
2647 * is called before end_migration, we can catch all events on this new
2648 * page. In the case new page is migrated but not remapped, new page's
2649 * mapcount will be finally 0 and we call uncharge in end_migration().
2651 pc
= lookup_page_cgroup(newpage
);
2653 ctype
= MEM_CGROUP_CHARGE_TYPE_MAPPED
;
2654 else if (page_is_file_cache(page
))
2655 ctype
= MEM_CGROUP_CHARGE_TYPE_CACHE
;
2657 ctype
= MEM_CGROUP_CHARGE_TYPE_SHMEM
;
2658 __mem_cgroup_commit_charge(mem
, pc
, ctype
);
2662 /* remove redundant charge if migration failed*/
2663 void mem_cgroup_end_migration(struct mem_cgroup
*mem
,
2664 struct page
*oldpage
, struct page
*newpage
)
2666 struct page
*used
, *unused
;
2667 struct page_cgroup
*pc
;
2671 /* blocks rmdir() */
2672 cgroup_exclude_rmdir(&mem
->css
);
2673 /* at migration success, oldpage->mapping is NULL. */
2674 if (oldpage
->mapping
) {
2682 * We disallowed uncharge of pages under migration because mapcount
2683 * of the page goes down to zero, temporarly.
2684 * Clear the flag and check the page should be charged.
2686 pc
= lookup_page_cgroup(oldpage
);
2687 lock_page_cgroup(pc
);
2688 ClearPageCgroupMigration(pc
);
2689 unlock_page_cgroup(pc
);
2691 __mem_cgroup_uncharge_common(unused
, MEM_CGROUP_CHARGE_TYPE_FORCE
);
2694 * If a page is a file cache, radix-tree replacement is very atomic
2695 * and we can skip this check. When it was an Anon page, its mapcount
2696 * goes down to 0. But because we added MIGRATION flage, it's not
2697 * uncharged yet. There are several case but page->mapcount check
2698 * and USED bit check in mem_cgroup_uncharge_page() will do enough
2699 * check. (see prepare_charge() also)
2702 mem_cgroup_uncharge_page(used
);
2704 * At migration, we may charge account against cgroup which has no
2706 * So, rmdir()->pre_destroy() can be called while we do this charge.
2707 * In that case, we need to call pre_destroy() again. check it here.
2709 cgroup_release_and_wakeup_rmdir(&mem
->css
);
2713 * A call to try to shrink memory usage on charge failure at shmem's swapin.
2714 * Calling hierarchical_reclaim is not enough because we should update
2715 * last_oom_jiffies to prevent pagefault_out_of_memory from invoking global OOM.
2716 * Moreover considering hierarchy, we should reclaim from the mem_over_limit,
2717 * not from the memcg which this page would be charged to.
2718 * try_charge_swapin does all of these works properly.
2720 int mem_cgroup_shmem_charge_fallback(struct page
*page
,
2721 struct mm_struct
*mm
,
2724 struct mem_cgroup
*mem
= NULL
;
2727 if (mem_cgroup_disabled())
2730 ret
= mem_cgroup_try_charge_swapin(mm
, page
, gfp_mask
, &mem
);
2732 mem_cgroup_cancel_charge_swapin(mem
); /* it does !mem check */
2737 static DEFINE_MUTEX(set_limit_mutex
);
2739 static int mem_cgroup_resize_limit(struct mem_cgroup
*memcg
,
2740 unsigned long long val
)
2743 u64 memswlimit
, memlimit
;
2745 int children
= mem_cgroup_count_children(memcg
);
2746 u64 curusage
, oldusage
;
2750 * For keeping hierarchical_reclaim simple, how long we should retry
2751 * is depends on callers. We set our retry-count to be function
2752 * of # of children which we should visit in this loop.
2754 retry_count
= MEM_CGROUP_RECLAIM_RETRIES
* children
;
2756 oldusage
= res_counter_read_u64(&memcg
->res
, RES_USAGE
);
2759 while (retry_count
) {
2760 if (signal_pending(current
)) {
2765 * Rather than hide all in some function, I do this in
2766 * open coded manner. You see what this really does.
2767 * We have to guarantee mem->res.limit < mem->memsw.limit.
2769 mutex_lock(&set_limit_mutex
);
2770 memswlimit
= res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
);
2771 if (memswlimit
< val
) {
2773 mutex_unlock(&set_limit_mutex
);
2777 memlimit
= res_counter_read_u64(&memcg
->res
, RES_LIMIT
);
2781 ret
= res_counter_set_limit(&memcg
->res
, val
);
2783 if (memswlimit
== val
)
2784 memcg
->memsw_is_minimum
= true;
2786 memcg
->memsw_is_minimum
= false;
2788 mutex_unlock(&set_limit_mutex
);
2793 mem_cgroup_hierarchical_reclaim(memcg
, NULL
, GFP_KERNEL
,
2794 MEM_CGROUP_RECLAIM_SHRINK
);
2795 curusage
= res_counter_read_u64(&memcg
->res
, RES_USAGE
);
2796 /* Usage is reduced ? */
2797 if (curusage
>= oldusage
)
2800 oldusage
= curusage
;
2802 if (!ret
&& enlarge
)
2803 memcg_oom_recover(memcg
);
2808 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup
*memcg
,
2809 unsigned long long val
)
2812 u64 memlimit
, memswlimit
, oldusage
, curusage
;
2813 int children
= mem_cgroup_count_children(memcg
);
2817 /* see mem_cgroup_resize_res_limit */
2818 retry_count
= children
* MEM_CGROUP_RECLAIM_RETRIES
;
2819 oldusage
= res_counter_read_u64(&memcg
->memsw
, RES_USAGE
);
2820 while (retry_count
) {
2821 if (signal_pending(current
)) {
2826 * Rather than hide all in some function, I do this in
2827 * open coded manner. You see what this really does.
2828 * We have to guarantee mem->res.limit < mem->memsw.limit.
2830 mutex_lock(&set_limit_mutex
);
2831 memlimit
= res_counter_read_u64(&memcg
->res
, RES_LIMIT
);
2832 if (memlimit
> val
) {
2834 mutex_unlock(&set_limit_mutex
);
2837 memswlimit
= res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
);
2838 if (memswlimit
< val
)
2840 ret
= res_counter_set_limit(&memcg
->memsw
, val
);
2842 if (memlimit
== val
)
2843 memcg
->memsw_is_minimum
= true;
2845 memcg
->memsw_is_minimum
= false;
2847 mutex_unlock(&set_limit_mutex
);
2852 mem_cgroup_hierarchical_reclaim(memcg
, NULL
, GFP_KERNEL
,
2853 MEM_CGROUP_RECLAIM_NOSWAP
|
2854 MEM_CGROUP_RECLAIM_SHRINK
);
2855 curusage
= res_counter_read_u64(&memcg
->memsw
, RES_USAGE
);
2856 /* Usage is reduced ? */
2857 if (curusage
>= oldusage
)
2860 oldusage
= curusage
;
2862 if (!ret
&& enlarge
)
2863 memcg_oom_recover(memcg
);
2867 unsigned long mem_cgroup_soft_limit_reclaim(struct zone
*zone
, int order
,
2870 unsigned long nr_reclaimed
= 0;
2871 struct mem_cgroup_per_zone
*mz
, *next_mz
= NULL
;
2872 unsigned long reclaimed
;
2874 struct mem_cgroup_tree_per_zone
*mctz
;
2875 unsigned long long excess
;
2880 mctz
= soft_limit_tree_node_zone(zone_to_nid(zone
), zone_idx(zone
));
2882 * This loop can run a while, specially if mem_cgroup's continuously
2883 * keep exceeding their soft limit and putting the system under
2890 mz
= mem_cgroup_largest_soft_limit_node(mctz
);
2894 reclaimed
= mem_cgroup_hierarchical_reclaim(mz
->mem
, zone
,
2896 MEM_CGROUP_RECLAIM_SOFT
);
2897 nr_reclaimed
+= reclaimed
;
2898 spin_lock(&mctz
->lock
);
2901 * If we failed to reclaim anything from this memory cgroup
2902 * it is time to move on to the next cgroup
2908 * Loop until we find yet another one.
2910 * By the time we get the soft_limit lock
2911 * again, someone might have aded the
2912 * group back on the RB tree. Iterate to
2913 * make sure we get a different mem.
2914 * mem_cgroup_largest_soft_limit_node returns
2915 * NULL if no other cgroup is present on
2919 __mem_cgroup_largest_soft_limit_node(mctz
);
2920 if (next_mz
== mz
) {
2921 css_put(&next_mz
->mem
->css
);
2923 } else /* next_mz == NULL or other memcg */
2927 __mem_cgroup_remove_exceeded(mz
->mem
, mz
, mctz
);
2928 excess
= res_counter_soft_limit_excess(&mz
->mem
->res
);
2930 * One school of thought says that we should not add
2931 * back the node to the tree if reclaim returns 0.
2932 * But our reclaim could return 0, simply because due
2933 * to priority we are exposing a smaller subset of
2934 * memory to reclaim from. Consider this as a longer
2937 /* If excess == 0, no tree ops */
2938 __mem_cgroup_insert_exceeded(mz
->mem
, mz
, mctz
, excess
);
2939 spin_unlock(&mctz
->lock
);
2940 css_put(&mz
->mem
->css
);
2943 * Could not reclaim anything and there are no more
2944 * mem cgroups to try or we seem to be looping without
2945 * reclaiming anything.
2947 if (!nr_reclaimed
&&
2949 loop
> MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS
))
2951 } while (!nr_reclaimed
);
2953 css_put(&next_mz
->mem
->css
);
2954 return nr_reclaimed
;
2958 * This routine traverse page_cgroup in given list and drop them all.
2959 * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
2961 static int mem_cgroup_force_empty_list(struct mem_cgroup
*mem
,
2962 int node
, int zid
, enum lru_list lru
)
2965 struct mem_cgroup_per_zone
*mz
;
2966 struct page_cgroup
*pc
, *busy
;
2967 unsigned long flags
, loop
;
2968 struct list_head
*list
;
2971 zone
= &NODE_DATA(node
)->node_zones
[zid
];
2972 mz
= mem_cgroup_zoneinfo(mem
, node
, zid
);
2973 list
= &mz
->lists
[lru
];
2975 loop
= MEM_CGROUP_ZSTAT(mz
, lru
);
2976 /* give some margin against EBUSY etc...*/
2981 spin_lock_irqsave(&zone
->lru_lock
, flags
);
2982 if (list_empty(list
)) {
2983 spin_unlock_irqrestore(&zone
->lru_lock
, flags
);
2986 pc
= list_entry(list
->prev
, struct page_cgroup
, lru
);
2988 list_move(&pc
->lru
, list
);
2990 spin_unlock_irqrestore(&zone
->lru_lock
, flags
);
2993 spin_unlock_irqrestore(&zone
->lru_lock
, flags
);
2995 ret
= mem_cgroup_move_parent(pc
, mem
, GFP_KERNEL
);
2999 if (ret
== -EBUSY
|| ret
== -EINVAL
) {
3000 /* found lock contention or "pc" is obsolete. */
3007 if (!ret
&& !list_empty(list
))
3013 * make mem_cgroup's charge to be 0 if there is no task.
3014 * This enables deleting this mem_cgroup.
3016 static int mem_cgroup_force_empty(struct mem_cgroup
*mem
, bool free_all
)
3019 int node
, zid
, shrink
;
3020 int nr_retries
= MEM_CGROUP_RECLAIM_RETRIES
;
3021 struct cgroup
*cgrp
= mem
->css
.cgroup
;
3026 /* should free all ? */
3032 if (cgroup_task_count(cgrp
) || !list_empty(&cgrp
->children
))
3035 if (signal_pending(current
))
3037 /* This is for making all *used* pages to be on LRU. */
3038 lru_add_drain_all();
3039 drain_all_stock_sync();
3041 for_each_node_state(node
, N_HIGH_MEMORY
) {
3042 for (zid
= 0; !ret
&& zid
< MAX_NR_ZONES
; zid
++) {
3045 ret
= mem_cgroup_force_empty_list(mem
,
3054 memcg_oom_recover(mem
);
3055 /* it seems parent cgroup doesn't have enough mem */
3059 /* "ret" should also be checked to ensure all lists are empty. */
3060 } while (mem
->res
.usage
> 0 || ret
);
3066 /* returns EBUSY if there is a task or if we come here twice. */
3067 if (cgroup_task_count(cgrp
) || !list_empty(&cgrp
->children
) || shrink
) {
3071 /* we call try-to-free pages for make this cgroup empty */
3072 lru_add_drain_all();
3073 /* try to free all pages in this cgroup */
3075 while (nr_retries
&& mem
->res
.usage
> 0) {
3078 if (signal_pending(current
)) {
3082 progress
= try_to_free_mem_cgroup_pages(mem
, GFP_KERNEL
,
3083 false, get_swappiness(mem
));
3086 /* maybe some writeback is necessary */
3087 congestion_wait(BLK_RW_ASYNC
, HZ
/10);
3092 /* try move_account...there may be some *locked* pages. */
3096 int mem_cgroup_force_empty_write(struct cgroup
*cont
, unsigned int event
)
3098 return mem_cgroup_force_empty(mem_cgroup_from_cont(cont
), true);
3102 static u64
mem_cgroup_hierarchy_read(struct cgroup
*cont
, struct cftype
*cft
)
3104 return mem_cgroup_from_cont(cont
)->use_hierarchy
;
3107 static int mem_cgroup_hierarchy_write(struct cgroup
*cont
, struct cftype
*cft
,
3111 struct mem_cgroup
*mem
= mem_cgroup_from_cont(cont
);
3112 struct cgroup
*parent
= cont
->parent
;
3113 struct mem_cgroup
*parent_mem
= NULL
;
3116 parent_mem
= mem_cgroup_from_cont(parent
);
3120 * If parent's use_hierarchy is set, we can't make any modifications
3121 * in the child subtrees. If it is unset, then the change can
3122 * occur, provided the current cgroup has no children.
3124 * For the root cgroup, parent_mem is NULL, we allow value to be
3125 * set if there are no children.
3127 if ((!parent_mem
|| !parent_mem
->use_hierarchy
) &&
3128 (val
== 1 || val
== 0)) {
3129 if (list_empty(&cont
->children
))
3130 mem
->use_hierarchy
= val
;
3140 struct mem_cgroup_idx_data
{
3142 enum mem_cgroup_stat_index idx
;
3146 mem_cgroup_get_idx_stat(struct mem_cgroup
*mem
, void *data
)
3148 struct mem_cgroup_idx_data
*d
= data
;
3149 d
->val
+= mem_cgroup_read_stat(mem
, d
->idx
);
3154 mem_cgroup_get_recursive_idx_stat(struct mem_cgroup
*mem
,
3155 enum mem_cgroup_stat_index idx
, s64
*val
)
3157 struct mem_cgroup_idx_data d
;
3160 mem_cgroup_walk_tree(mem
, &d
, mem_cgroup_get_idx_stat
);
3164 static inline u64
mem_cgroup_usage(struct mem_cgroup
*mem
, bool swap
)
3168 if (!mem_cgroup_is_root(mem
)) {
3170 return res_counter_read_u64(&mem
->res
, RES_USAGE
);
3172 return res_counter_read_u64(&mem
->memsw
, RES_USAGE
);
3175 mem_cgroup_get_recursive_idx_stat(mem
, MEM_CGROUP_STAT_CACHE
, &idx_val
);
3177 mem_cgroup_get_recursive_idx_stat(mem
, MEM_CGROUP_STAT_RSS
, &idx_val
);
3181 mem_cgroup_get_recursive_idx_stat(mem
,
3182 MEM_CGROUP_STAT_SWAPOUT
, &idx_val
);
3186 return val
<< PAGE_SHIFT
;
3189 static u64
mem_cgroup_read(struct cgroup
*cont
, struct cftype
*cft
)
3191 struct mem_cgroup
*mem
= mem_cgroup_from_cont(cont
);
3195 type
= MEMFILE_TYPE(cft
->private);
3196 name
= MEMFILE_ATTR(cft
->private);
3199 if (name
== RES_USAGE
)
3200 val
= mem_cgroup_usage(mem
, false);
3202 val
= res_counter_read_u64(&mem
->res
, name
);
3205 if (name
== RES_USAGE
)
3206 val
= mem_cgroup_usage(mem
, true);
3208 val
= res_counter_read_u64(&mem
->memsw
, name
);
3217 * The user of this function is...
3220 static int mem_cgroup_write(struct cgroup
*cont
, struct cftype
*cft
,
3223 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cont
);
3225 unsigned long long val
;
3228 type
= MEMFILE_TYPE(cft
->private);
3229 name
= MEMFILE_ATTR(cft
->private);
3232 if (mem_cgroup_is_root(memcg
)) { /* Can't set limit on root */
3236 /* This function does all necessary parse...reuse it */
3237 ret
= res_counter_memparse_write_strategy(buffer
, &val
);
3241 ret
= mem_cgroup_resize_limit(memcg
, val
);
3243 ret
= mem_cgroup_resize_memsw_limit(memcg
, val
);
3245 case RES_SOFT_LIMIT
:
3246 ret
= res_counter_memparse_write_strategy(buffer
, &val
);
3250 * For memsw, soft limits are hard to implement in terms
3251 * of semantics, for now, we support soft limits for
3252 * control without swap
3255 ret
= res_counter_set_soft_limit(&memcg
->res
, val
);
3260 ret
= -EINVAL
; /* should be BUG() ? */
3266 static void memcg_get_hierarchical_limit(struct mem_cgroup
*memcg
,
3267 unsigned long long *mem_limit
, unsigned long long *memsw_limit
)
3269 struct cgroup
*cgroup
;
3270 unsigned long long min_limit
, min_memsw_limit
, tmp
;
3272 min_limit
= res_counter_read_u64(&memcg
->res
, RES_LIMIT
);
3273 min_memsw_limit
= res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
);
3274 cgroup
= memcg
->css
.cgroup
;
3275 if (!memcg
->use_hierarchy
)
3278 while (cgroup
->parent
) {
3279 cgroup
= cgroup
->parent
;
3280 memcg
= mem_cgroup_from_cont(cgroup
);
3281 if (!memcg
->use_hierarchy
)
3283 tmp
= res_counter_read_u64(&memcg
->res
, RES_LIMIT
);
3284 min_limit
= min(min_limit
, tmp
);
3285 tmp
= res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
);
3286 min_memsw_limit
= min(min_memsw_limit
, tmp
);
3289 *mem_limit
= min_limit
;
3290 *memsw_limit
= min_memsw_limit
;
3294 static int mem_cgroup_reset(struct cgroup
*cont
, unsigned int event
)
3296 struct mem_cgroup
*mem
;
3299 mem
= mem_cgroup_from_cont(cont
);
3300 type
= MEMFILE_TYPE(event
);
3301 name
= MEMFILE_ATTR(event
);
3305 res_counter_reset_max(&mem
->res
);
3307 res_counter_reset_max(&mem
->memsw
);
3311 res_counter_reset_failcnt(&mem
->res
);
3313 res_counter_reset_failcnt(&mem
->memsw
);
3320 static u64
mem_cgroup_move_charge_read(struct cgroup
*cgrp
,
3323 return mem_cgroup_from_cont(cgrp
)->move_charge_at_immigrate
;
3327 static int mem_cgroup_move_charge_write(struct cgroup
*cgrp
,
3328 struct cftype
*cft
, u64 val
)
3330 struct mem_cgroup
*mem
= mem_cgroup_from_cont(cgrp
);
3332 if (val
>= (1 << NR_MOVE_TYPE
))
3335 * We check this value several times in both in can_attach() and
3336 * attach(), so we need cgroup lock to prevent this value from being
3340 mem
->move_charge_at_immigrate
= val
;
3346 static int mem_cgroup_move_charge_write(struct cgroup
*cgrp
,
3347 struct cftype
*cft
, u64 val
)
3354 /* For read statistics */
3370 struct mcs_total_stat
{
3371 s64 stat
[NR_MCS_STAT
];
3377 } memcg_stat_strings
[NR_MCS_STAT
] = {
3378 {"cache", "total_cache"},
3379 {"rss", "total_rss"},
3380 {"mapped_file", "total_mapped_file"},
3381 {"pgpgin", "total_pgpgin"},
3382 {"pgpgout", "total_pgpgout"},
3383 {"swap", "total_swap"},
3384 {"inactive_anon", "total_inactive_anon"},
3385 {"active_anon", "total_active_anon"},
3386 {"inactive_file", "total_inactive_file"},
3387 {"active_file", "total_active_file"},
3388 {"unevictable", "total_unevictable"}
3392 static int mem_cgroup_get_local_stat(struct mem_cgroup
*mem
, void *data
)
3394 struct mcs_total_stat
*s
= data
;
3398 val
= mem_cgroup_read_stat(mem
, MEM_CGROUP_STAT_CACHE
);
3399 s
->stat
[MCS_CACHE
] += val
* PAGE_SIZE
;
3400 val
= mem_cgroup_read_stat(mem
, MEM_CGROUP_STAT_RSS
);
3401 s
->stat
[MCS_RSS
] += val
* PAGE_SIZE
;
3402 val
= mem_cgroup_read_stat(mem
, MEM_CGROUP_STAT_FILE_MAPPED
);
3403 s
->stat
[MCS_FILE_MAPPED
] += val
* PAGE_SIZE
;
3404 val
= mem_cgroup_read_stat(mem
, MEM_CGROUP_STAT_PGPGIN_COUNT
);
3405 s
->stat
[MCS_PGPGIN
] += val
;
3406 val
= mem_cgroup_read_stat(mem
, MEM_CGROUP_STAT_PGPGOUT_COUNT
);
3407 s
->stat
[MCS_PGPGOUT
] += val
;
3408 if (do_swap_account
) {
3409 val
= mem_cgroup_read_stat(mem
, MEM_CGROUP_STAT_SWAPOUT
);
3410 s
->stat
[MCS_SWAP
] += val
* PAGE_SIZE
;
3414 val
= mem_cgroup_get_local_zonestat(mem
, LRU_INACTIVE_ANON
);
3415 s
->stat
[MCS_INACTIVE_ANON
] += val
* PAGE_SIZE
;
3416 val
= mem_cgroup_get_local_zonestat(mem
, LRU_ACTIVE_ANON
);
3417 s
->stat
[MCS_ACTIVE_ANON
] += val
* PAGE_SIZE
;
3418 val
= mem_cgroup_get_local_zonestat(mem
, LRU_INACTIVE_FILE
);
3419 s
->stat
[MCS_INACTIVE_FILE
] += val
* PAGE_SIZE
;
3420 val
= mem_cgroup_get_local_zonestat(mem
, LRU_ACTIVE_FILE
);
3421 s
->stat
[MCS_ACTIVE_FILE
] += val
* PAGE_SIZE
;
3422 val
= mem_cgroup_get_local_zonestat(mem
, LRU_UNEVICTABLE
);
3423 s
->stat
[MCS_UNEVICTABLE
] += val
* PAGE_SIZE
;
3428 mem_cgroup_get_total_stat(struct mem_cgroup
*mem
, struct mcs_total_stat
*s
)
3430 mem_cgroup_walk_tree(mem
, s
, mem_cgroup_get_local_stat
);
3433 static int mem_control_stat_show(struct cgroup
*cont
, struct cftype
*cft
,
3434 struct cgroup_map_cb
*cb
)
3436 struct mem_cgroup
*mem_cont
= mem_cgroup_from_cont(cont
);
3437 struct mcs_total_stat mystat
;
3440 memset(&mystat
, 0, sizeof(mystat
));
3441 mem_cgroup_get_local_stat(mem_cont
, &mystat
);
3443 for (i
= 0; i
< NR_MCS_STAT
; i
++) {
3444 if (i
== MCS_SWAP
&& !do_swap_account
)
3446 cb
->fill(cb
, memcg_stat_strings
[i
].local_name
, mystat
.stat
[i
]);
3449 /* Hierarchical information */
3451 unsigned long long limit
, memsw_limit
;
3452 memcg_get_hierarchical_limit(mem_cont
, &limit
, &memsw_limit
);
3453 cb
->fill(cb
, "hierarchical_memory_limit", limit
);
3454 if (do_swap_account
)
3455 cb
->fill(cb
, "hierarchical_memsw_limit", memsw_limit
);
3458 memset(&mystat
, 0, sizeof(mystat
));
3459 mem_cgroup_get_total_stat(mem_cont
, &mystat
);
3460 for (i
= 0; i
< NR_MCS_STAT
; i
++) {
3461 if (i
== MCS_SWAP
&& !do_swap_account
)
3463 cb
->fill(cb
, memcg_stat_strings
[i
].total_name
, mystat
.stat
[i
]);
3466 #ifdef CONFIG_DEBUG_VM
3467 cb
->fill(cb
, "inactive_ratio", calc_inactive_ratio(mem_cont
, NULL
));
3471 struct mem_cgroup_per_zone
*mz
;
3472 unsigned long recent_rotated
[2] = {0, 0};
3473 unsigned long recent_scanned
[2] = {0, 0};
3475 for_each_online_node(nid
)
3476 for (zid
= 0; zid
< MAX_NR_ZONES
; zid
++) {
3477 mz
= mem_cgroup_zoneinfo(mem_cont
, nid
, zid
);
3479 recent_rotated
[0] +=
3480 mz
->reclaim_stat
.recent_rotated
[0];
3481 recent_rotated
[1] +=
3482 mz
->reclaim_stat
.recent_rotated
[1];
3483 recent_scanned
[0] +=
3484 mz
->reclaim_stat
.recent_scanned
[0];
3485 recent_scanned
[1] +=
3486 mz
->reclaim_stat
.recent_scanned
[1];
3488 cb
->fill(cb
, "recent_rotated_anon", recent_rotated
[0]);
3489 cb
->fill(cb
, "recent_rotated_file", recent_rotated
[1]);
3490 cb
->fill(cb
, "recent_scanned_anon", recent_scanned
[0]);
3491 cb
->fill(cb
, "recent_scanned_file", recent_scanned
[1]);
3498 static u64
mem_cgroup_swappiness_read(struct cgroup
*cgrp
, struct cftype
*cft
)
3500 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
3502 return get_swappiness(memcg
);
3505 static int mem_cgroup_swappiness_write(struct cgroup
*cgrp
, struct cftype
*cft
,
3508 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
3509 struct mem_cgroup
*parent
;
3514 if (cgrp
->parent
== NULL
)
3517 parent
= mem_cgroup_from_cont(cgrp
->parent
);
3521 /* If under hierarchy, only empty-root can set this value */
3522 if ((parent
->use_hierarchy
) ||
3523 (memcg
->use_hierarchy
&& !list_empty(&cgrp
->children
))) {
3528 spin_lock(&memcg
->reclaim_param_lock
);
3529 memcg
->swappiness
= val
;
3530 spin_unlock(&memcg
->reclaim_param_lock
);
3537 static void __mem_cgroup_threshold(struct mem_cgroup
*memcg
, bool swap
)
3539 struct mem_cgroup_threshold_ary
*t
;
3545 t
= rcu_dereference(memcg
->thresholds
.primary
);
3547 t
= rcu_dereference(memcg
->memsw_thresholds
.primary
);
3552 usage
= mem_cgroup_usage(memcg
, swap
);
3555 * current_threshold points to threshold just below usage.
3556 * If it's not true, a threshold was crossed after last
3557 * call of __mem_cgroup_threshold().
3559 i
= t
->current_threshold
;
3562 * Iterate backward over array of thresholds starting from
3563 * current_threshold and check if a threshold is crossed.
3564 * If none of thresholds below usage is crossed, we read
3565 * only one element of the array here.
3567 for (; i
>= 0 && unlikely(t
->entries
[i
].threshold
> usage
); i
--)
3568 eventfd_signal(t
->entries
[i
].eventfd
, 1);
3570 /* i = current_threshold + 1 */
3574 * Iterate forward over array of thresholds starting from
3575 * current_threshold+1 and check if a threshold is crossed.
3576 * If none of thresholds above usage is crossed, we read
3577 * only one element of the array here.
3579 for (; i
< t
->size
&& unlikely(t
->entries
[i
].threshold
<= usage
); i
++)
3580 eventfd_signal(t
->entries
[i
].eventfd
, 1);
3582 /* Update current_threshold */
3583 t
->current_threshold
= i
- 1;
3588 static void mem_cgroup_threshold(struct mem_cgroup
*memcg
)
3591 __mem_cgroup_threshold(memcg
, false);
3592 if (do_swap_account
)
3593 __mem_cgroup_threshold(memcg
, true);
3595 memcg
= parent_mem_cgroup(memcg
);
3599 static int compare_thresholds(const void *a
, const void *b
)
3601 const struct mem_cgroup_threshold
*_a
= a
;
3602 const struct mem_cgroup_threshold
*_b
= b
;
3604 return _a
->threshold
- _b
->threshold
;
3607 static int mem_cgroup_oom_notify_cb(struct mem_cgroup
*mem
, void *data
)
3609 struct mem_cgroup_eventfd_list
*ev
;
3611 list_for_each_entry(ev
, &mem
->oom_notify
, list
)
3612 eventfd_signal(ev
->eventfd
, 1);
3616 static void mem_cgroup_oom_notify(struct mem_cgroup
*mem
)
3618 mem_cgroup_walk_tree(mem
, NULL
, mem_cgroup_oom_notify_cb
);
3621 static int mem_cgroup_usage_register_event(struct cgroup
*cgrp
,
3622 struct cftype
*cft
, struct eventfd_ctx
*eventfd
, const char *args
)
3624 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
3625 struct mem_cgroup_thresholds
*thresholds
;
3626 struct mem_cgroup_threshold_ary
*new;
3627 int type
= MEMFILE_TYPE(cft
->private);
3628 u64 threshold
, usage
;
3631 ret
= res_counter_memparse_write_strategy(args
, &threshold
);
3635 mutex_lock(&memcg
->thresholds_lock
);
3638 thresholds
= &memcg
->thresholds
;
3639 else if (type
== _MEMSWAP
)
3640 thresholds
= &memcg
->memsw_thresholds
;
3644 usage
= mem_cgroup_usage(memcg
, type
== _MEMSWAP
);
3646 /* Check if a threshold crossed before adding a new one */
3647 if (thresholds
->primary
)
3648 __mem_cgroup_threshold(memcg
, type
== _MEMSWAP
);
3650 size
= thresholds
->primary
? thresholds
->primary
->size
+ 1 : 1;
3652 /* Allocate memory for new array of thresholds */
3653 new = kmalloc(sizeof(*new) + size
* sizeof(struct mem_cgroup_threshold
),
3661 /* Copy thresholds (if any) to new array */
3662 if (thresholds
->primary
) {
3663 memcpy(new->entries
, thresholds
->primary
->entries
, (size
- 1) *
3664 sizeof(struct mem_cgroup_threshold
));
3667 /* Add new threshold */
3668 new->entries
[size
- 1].eventfd
= eventfd
;
3669 new->entries
[size
- 1].threshold
= threshold
;
3671 /* Sort thresholds. Registering of new threshold isn't time-critical */
3672 sort(new->entries
, size
, sizeof(struct mem_cgroup_threshold
),
3673 compare_thresholds
, NULL
);
3675 /* Find current threshold */
3676 new->current_threshold
= -1;
3677 for (i
= 0; i
< size
; i
++) {
3678 if (new->entries
[i
].threshold
< usage
) {
3680 * new->current_threshold will not be used until
3681 * rcu_assign_pointer(), so it's safe to increment
3684 ++new->current_threshold
;
3688 /* Free old spare buffer and save old primary buffer as spare */
3689 kfree(thresholds
->spare
);
3690 thresholds
->spare
= thresholds
->primary
;
3692 rcu_assign_pointer(thresholds
->primary
, new);
3694 /* To be sure that nobody uses thresholds */
3698 mutex_unlock(&memcg
->thresholds_lock
);
3703 static void mem_cgroup_usage_unregister_event(struct cgroup
*cgrp
,
3704 struct cftype
*cft
, struct eventfd_ctx
*eventfd
)
3706 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
3707 struct mem_cgroup_thresholds
*thresholds
;
3708 struct mem_cgroup_threshold_ary
*new;
3709 int type
= MEMFILE_TYPE(cft
->private);
3713 mutex_lock(&memcg
->thresholds_lock
);
3715 thresholds
= &memcg
->thresholds
;
3716 else if (type
== _MEMSWAP
)
3717 thresholds
= &memcg
->memsw_thresholds
;
3722 * Something went wrong if we trying to unregister a threshold
3723 * if we don't have thresholds
3725 BUG_ON(!thresholds
);
3727 usage
= mem_cgroup_usage(memcg
, type
== _MEMSWAP
);
3729 /* Check if a threshold crossed before removing */
3730 __mem_cgroup_threshold(memcg
, type
== _MEMSWAP
);
3732 /* Calculate new number of threshold */
3734 for (i
= 0; i
< thresholds
->primary
->size
; i
++) {
3735 if (thresholds
->primary
->entries
[i
].eventfd
!= eventfd
)
3739 new = thresholds
->spare
;
3741 /* Set thresholds array to NULL if we don't have thresholds */
3750 /* Copy thresholds and find current threshold */
3751 new->current_threshold
= -1;
3752 for (i
= 0, j
= 0; i
< thresholds
->primary
->size
; i
++) {
3753 if (thresholds
->primary
->entries
[i
].eventfd
== eventfd
)
3756 new->entries
[j
] = thresholds
->primary
->entries
[i
];
3757 if (new->entries
[j
].threshold
< usage
) {
3759 * new->current_threshold will not be used
3760 * until rcu_assign_pointer(), so it's safe to increment
3763 ++new->current_threshold
;
3769 /* Swap primary and spare array */
3770 thresholds
->spare
= thresholds
->primary
;
3771 rcu_assign_pointer(thresholds
->primary
, new);
3773 /* To be sure that nobody uses thresholds */
3776 mutex_unlock(&memcg
->thresholds_lock
);
3779 static int mem_cgroup_oom_register_event(struct cgroup
*cgrp
,
3780 struct cftype
*cft
, struct eventfd_ctx
*eventfd
, const char *args
)
3782 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
3783 struct mem_cgroup_eventfd_list
*event
;
3784 int type
= MEMFILE_TYPE(cft
->private);
3786 BUG_ON(type
!= _OOM_TYPE
);
3787 event
= kmalloc(sizeof(*event
), GFP_KERNEL
);
3791 mutex_lock(&memcg_oom_mutex
);
3793 event
->eventfd
= eventfd
;
3794 list_add(&event
->list
, &memcg
->oom_notify
);
3796 /* already in OOM ? */
3797 if (atomic_read(&memcg
->oom_lock
))
3798 eventfd_signal(eventfd
, 1);
3799 mutex_unlock(&memcg_oom_mutex
);
3804 static void mem_cgroup_oom_unregister_event(struct cgroup
*cgrp
,
3805 struct cftype
*cft
, struct eventfd_ctx
*eventfd
)
3807 struct mem_cgroup
*mem
= mem_cgroup_from_cont(cgrp
);
3808 struct mem_cgroup_eventfd_list
*ev
, *tmp
;
3809 int type
= MEMFILE_TYPE(cft
->private);
3811 BUG_ON(type
!= _OOM_TYPE
);
3813 mutex_lock(&memcg_oom_mutex
);
3815 list_for_each_entry_safe(ev
, tmp
, &mem
->oom_notify
, list
) {
3816 if (ev
->eventfd
== eventfd
) {
3817 list_del(&ev
->list
);
3822 mutex_unlock(&memcg_oom_mutex
);
3825 static int mem_cgroup_oom_control_read(struct cgroup
*cgrp
,
3826 struct cftype
*cft
, struct cgroup_map_cb
*cb
)
3828 struct mem_cgroup
*mem
= mem_cgroup_from_cont(cgrp
);
3830 cb
->fill(cb
, "oom_kill_disable", mem
->oom_kill_disable
);
3832 if (atomic_read(&mem
->oom_lock
))
3833 cb
->fill(cb
, "under_oom", 1);
3835 cb
->fill(cb
, "under_oom", 0);
3839 static int mem_cgroup_oom_control_write(struct cgroup
*cgrp
,
3840 struct cftype
*cft
, u64 val
)
3842 struct mem_cgroup
*mem
= mem_cgroup_from_cont(cgrp
);
3843 struct mem_cgroup
*parent
;
3845 /* cannot set to root cgroup and only 0 and 1 are allowed */
3846 if (!cgrp
->parent
|| !((val
== 0) || (val
== 1)))
3849 parent
= mem_cgroup_from_cont(cgrp
->parent
);
3852 /* oom-kill-disable is a flag for subhierarchy. */
3853 if ((parent
->use_hierarchy
) ||
3854 (mem
->use_hierarchy
&& !list_empty(&cgrp
->children
))) {
3858 mem
->oom_kill_disable
= val
;
3860 memcg_oom_recover(mem
);
3865 static struct cftype mem_cgroup_files
[] = {
3867 .name
= "usage_in_bytes",
3868 .private = MEMFILE_PRIVATE(_MEM
, RES_USAGE
),
3869 .read_u64
= mem_cgroup_read
,
3870 .register_event
= mem_cgroup_usage_register_event
,
3871 .unregister_event
= mem_cgroup_usage_unregister_event
,
3874 .name
= "max_usage_in_bytes",
3875 .private = MEMFILE_PRIVATE(_MEM
, RES_MAX_USAGE
),
3876 .trigger
= mem_cgroup_reset
,
3877 .read_u64
= mem_cgroup_read
,
3880 .name
= "limit_in_bytes",
3881 .private = MEMFILE_PRIVATE(_MEM
, RES_LIMIT
),
3882 .write_string
= mem_cgroup_write
,
3883 .read_u64
= mem_cgroup_read
,
3886 .name
= "soft_limit_in_bytes",
3887 .private = MEMFILE_PRIVATE(_MEM
, RES_SOFT_LIMIT
),
3888 .write_string
= mem_cgroup_write
,
3889 .read_u64
= mem_cgroup_read
,
3893 .private = MEMFILE_PRIVATE(_MEM
, RES_FAILCNT
),
3894 .trigger
= mem_cgroup_reset
,
3895 .read_u64
= mem_cgroup_read
,
3899 .read_map
= mem_control_stat_show
,
3902 .name
= "force_empty",
3903 .trigger
= mem_cgroup_force_empty_write
,
3906 .name
= "use_hierarchy",
3907 .write_u64
= mem_cgroup_hierarchy_write
,
3908 .read_u64
= mem_cgroup_hierarchy_read
,
3911 .name
= "swappiness",
3912 .read_u64
= mem_cgroup_swappiness_read
,
3913 .write_u64
= mem_cgroup_swappiness_write
,
3916 .name
= "move_charge_at_immigrate",
3917 .read_u64
= mem_cgroup_move_charge_read
,
3918 .write_u64
= mem_cgroup_move_charge_write
,
3921 .name
= "oom_control",
3922 .read_map
= mem_cgroup_oom_control_read
,
3923 .write_u64
= mem_cgroup_oom_control_write
,
3924 .register_event
= mem_cgroup_oom_register_event
,
3925 .unregister_event
= mem_cgroup_oom_unregister_event
,
3926 .private = MEMFILE_PRIVATE(_OOM_TYPE
, OOM_CONTROL
),
3930 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3931 static struct cftype memsw_cgroup_files
[] = {
3933 .name
= "memsw.usage_in_bytes",
3934 .private = MEMFILE_PRIVATE(_MEMSWAP
, RES_USAGE
),
3935 .read_u64
= mem_cgroup_read
,
3936 .register_event
= mem_cgroup_usage_register_event
,
3937 .unregister_event
= mem_cgroup_usage_unregister_event
,
3940 .name
= "memsw.max_usage_in_bytes",
3941 .private = MEMFILE_PRIVATE(_MEMSWAP
, RES_MAX_USAGE
),
3942 .trigger
= mem_cgroup_reset
,
3943 .read_u64
= mem_cgroup_read
,
3946 .name
= "memsw.limit_in_bytes",
3947 .private = MEMFILE_PRIVATE(_MEMSWAP
, RES_LIMIT
),
3948 .write_string
= mem_cgroup_write
,
3949 .read_u64
= mem_cgroup_read
,
3952 .name
= "memsw.failcnt",
3953 .private = MEMFILE_PRIVATE(_MEMSWAP
, RES_FAILCNT
),
3954 .trigger
= mem_cgroup_reset
,
3955 .read_u64
= mem_cgroup_read
,
3959 static int register_memsw_files(struct cgroup
*cont
, struct cgroup_subsys
*ss
)
3961 if (!do_swap_account
)
3963 return cgroup_add_files(cont
, ss
, memsw_cgroup_files
,
3964 ARRAY_SIZE(memsw_cgroup_files
));
3967 static int register_memsw_files(struct cgroup
*cont
, struct cgroup_subsys
*ss
)
3973 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup
*mem
, int node
)
3975 struct mem_cgroup_per_node
*pn
;
3976 struct mem_cgroup_per_zone
*mz
;
3978 int zone
, tmp
= node
;
3980 * This routine is called against possible nodes.
3981 * But it's BUG to call kmalloc() against offline node.
3983 * TODO: this routine can waste much memory for nodes which will
3984 * never be onlined. It's better to use memory hotplug callback
3987 if (!node_state(node
, N_NORMAL_MEMORY
))
3989 pn
= kmalloc_node(sizeof(*pn
), GFP_KERNEL
, tmp
);
3993 mem
->info
.nodeinfo
[node
] = pn
;
3994 memset(pn
, 0, sizeof(*pn
));
3996 for (zone
= 0; zone
< MAX_NR_ZONES
; zone
++) {
3997 mz
= &pn
->zoneinfo
[zone
];
3999 INIT_LIST_HEAD(&mz
->lists
[l
]);
4000 mz
->usage_in_excess
= 0;
4001 mz
->on_tree
= false;
4007 static void free_mem_cgroup_per_zone_info(struct mem_cgroup
*mem
, int node
)
4009 kfree(mem
->info
.nodeinfo
[node
]);
4012 static struct mem_cgroup
*mem_cgroup_alloc(void)
4014 struct mem_cgroup
*mem
;
4015 int size
= sizeof(struct mem_cgroup
);
4017 /* Can be very big if MAX_NUMNODES is very big */
4018 if (size
< PAGE_SIZE
)
4019 mem
= kmalloc(size
, GFP_KERNEL
);
4021 mem
= vmalloc(size
);
4026 memset(mem
, 0, size
);
4027 mem
->stat
= alloc_percpu(struct mem_cgroup_stat_cpu
);
4029 if (size
< PAGE_SIZE
)
4039 * At destroying mem_cgroup, references from swap_cgroup can remain.
4040 * (scanning all at force_empty is too costly...)
4042 * Instead of clearing all references at force_empty, we remember
4043 * the number of reference from swap_cgroup and free mem_cgroup when
4044 * it goes down to 0.
4046 * Removal of cgroup itself succeeds regardless of refs from swap.
4049 static void __mem_cgroup_free(struct mem_cgroup
*mem
)
4053 mem_cgroup_remove_from_trees(mem
);
4054 free_css_id(&mem_cgroup_subsys
, &mem
->css
);
4056 for_each_node_state(node
, N_POSSIBLE
)
4057 free_mem_cgroup_per_zone_info(mem
, node
);
4059 free_percpu(mem
->stat
);
4060 if (sizeof(struct mem_cgroup
) < PAGE_SIZE
)
4066 static void mem_cgroup_get(struct mem_cgroup
*mem
)
4068 atomic_inc(&mem
->refcnt
);
4071 static void __mem_cgroup_put(struct mem_cgroup
*mem
, int count
)
4073 if (atomic_sub_and_test(count
, &mem
->refcnt
)) {
4074 struct mem_cgroup
*parent
= parent_mem_cgroup(mem
);
4075 __mem_cgroup_free(mem
);
4077 mem_cgroup_put(parent
);
4081 static void mem_cgroup_put(struct mem_cgroup
*mem
)
4083 __mem_cgroup_put(mem
, 1);
4087 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
4089 static struct mem_cgroup
*parent_mem_cgroup(struct mem_cgroup
*mem
)
4091 if (!mem
->res
.parent
)
4093 return mem_cgroup_from_res_counter(mem
->res
.parent
, res
);
4096 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4097 static void __init
enable_swap_cgroup(void)
4099 if (!mem_cgroup_disabled() && really_do_swap_account
)
4100 do_swap_account
= 1;
4103 static void __init
enable_swap_cgroup(void)
4108 static int mem_cgroup_soft_limit_tree_init(void)
4110 struct mem_cgroup_tree_per_node
*rtpn
;
4111 struct mem_cgroup_tree_per_zone
*rtpz
;
4112 int tmp
, node
, zone
;
4114 for_each_node_state(node
, N_POSSIBLE
) {
4116 if (!node_state(node
, N_NORMAL_MEMORY
))
4118 rtpn
= kzalloc_node(sizeof(*rtpn
), GFP_KERNEL
, tmp
);
4122 soft_limit_tree
.rb_tree_per_node
[node
] = rtpn
;
4124 for (zone
= 0; zone
< MAX_NR_ZONES
; zone
++) {
4125 rtpz
= &rtpn
->rb_tree_per_zone
[zone
];
4126 rtpz
->rb_root
= RB_ROOT
;
4127 spin_lock_init(&rtpz
->lock
);
4133 static struct cgroup_subsys_state
* __ref
4134 mem_cgroup_create(struct cgroup_subsys
*ss
, struct cgroup
*cont
)
4136 struct mem_cgroup
*mem
, *parent
;
4137 long error
= -ENOMEM
;
4140 mem
= mem_cgroup_alloc();
4142 return ERR_PTR(error
);
4144 for_each_node_state(node
, N_POSSIBLE
)
4145 if (alloc_mem_cgroup_per_zone_info(mem
, node
))
4149 if (cont
->parent
== NULL
) {
4151 enable_swap_cgroup();
4153 root_mem_cgroup
= mem
;
4154 if (mem_cgroup_soft_limit_tree_init())
4156 for_each_possible_cpu(cpu
) {
4157 struct memcg_stock_pcp
*stock
=
4158 &per_cpu(memcg_stock
, cpu
);
4159 INIT_WORK(&stock
->work
, drain_local_stock
);
4161 hotcpu_notifier(memcg_stock_cpu_callback
, 0);
4163 parent
= mem_cgroup_from_cont(cont
->parent
);
4164 mem
->use_hierarchy
= parent
->use_hierarchy
;
4165 mem
->oom_kill_disable
= parent
->oom_kill_disable
;
4168 if (parent
&& parent
->use_hierarchy
) {
4169 res_counter_init(&mem
->res
, &parent
->res
);
4170 res_counter_init(&mem
->memsw
, &parent
->memsw
);
4172 * We increment refcnt of the parent to ensure that we can
4173 * safely access it on res_counter_charge/uncharge.
4174 * This refcnt will be decremented when freeing this
4175 * mem_cgroup(see mem_cgroup_put).
4177 mem_cgroup_get(parent
);
4179 res_counter_init(&mem
->res
, NULL
);
4180 res_counter_init(&mem
->memsw
, NULL
);
4182 mem
->last_scanned_child
= 0;
4183 spin_lock_init(&mem
->reclaim_param_lock
);
4184 INIT_LIST_HEAD(&mem
->oom_notify
);
4187 mem
->swappiness
= get_swappiness(parent
);
4188 atomic_set(&mem
->refcnt
, 1);
4189 mem
->move_charge_at_immigrate
= 0;
4190 mutex_init(&mem
->thresholds_lock
);
4193 __mem_cgroup_free(mem
);
4194 root_mem_cgroup
= NULL
;
4195 return ERR_PTR(error
);
4198 static int mem_cgroup_pre_destroy(struct cgroup_subsys
*ss
,
4199 struct cgroup
*cont
)
4201 struct mem_cgroup
*mem
= mem_cgroup_from_cont(cont
);
4203 return mem_cgroup_force_empty(mem
, false);
4206 static void mem_cgroup_destroy(struct cgroup_subsys
*ss
,
4207 struct cgroup
*cont
)
4209 struct mem_cgroup
*mem
= mem_cgroup_from_cont(cont
);
4211 mem_cgroup_put(mem
);
4214 static int mem_cgroup_populate(struct cgroup_subsys
*ss
,
4215 struct cgroup
*cont
)
4219 ret
= cgroup_add_files(cont
, ss
, mem_cgroup_files
,
4220 ARRAY_SIZE(mem_cgroup_files
));
4223 ret
= register_memsw_files(cont
, ss
);
4228 /* Handlers for move charge at task migration. */
4229 #define PRECHARGE_COUNT_AT_ONCE 256
4230 static int mem_cgroup_do_precharge(unsigned long count
)
4233 int batch_count
= PRECHARGE_COUNT_AT_ONCE
;
4234 struct mem_cgroup
*mem
= mc
.to
;
4236 if (mem_cgroup_is_root(mem
)) {
4237 mc
.precharge
+= count
;
4238 /* we don't need css_get for root */
4241 /* try to charge at once */
4243 struct res_counter
*dummy
;
4245 * "mem" cannot be under rmdir() because we've already checked
4246 * by cgroup_lock_live_cgroup() that it is not removed and we
4247 * are still under the same cgroup_mutex. So we can postpone
4250 if (res_counter_charge(&mem
->res
, PAGE_SIZE
* count
, &dummy
))
4252 if (do_swap_account
&& res_counter_charge(&mem
->memsw
,
4253 PAGE_SIZE
* count
, &dummy
)) {
4254 res_counter_uncharge(&mem
->res
, PAGE_SIZE
* count
);
4257 mc
.precharge
+= count
;
4261 /* fall back to one by one charge */
4263 if (signal_pending(current
)) {
4267 if (!batch_count
--) {
4268 batch_count
= PRECHARGE_COUNT_AT_ONCE
;
4271 ret
= __mem_cgroup_try_charge(NULL
, GFP_KERNEL
, &mem
, false);
4273 /* mem_cgroup_clear_mc() will do uncharge later */
4281 * is_target_pte_for_mc - check a pte whether it is valid for move charge
4282 * @vma: the vma the pte to be checked belongs
4283 * @addr: the address corresponding to the pte to be checked
4284 * @ptent: the pte to be checked
4285 * @target: the pointer the target page or swap ent will be stored(can be NULL)
4288 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
4289 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
4290 * move charge. if @target is not NULL, the page is stored in target->page
4291 * with extra refcnt got(Callers should handle it).
4292 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
4293 * target for charge migration. if @target is not NULL, the entry is stored
4296 * Called with pte lock held.
4303 enum mc_target_type
{
4304 MC_TARGET_NONE
, /* not used */
4309 static struct page
*mc_handle_present_pte(struct vm_area_struct
*vma
,
4310 unsigned long addr
, pte_t ptent
)
4312 struct page
*page
= vm_normal_page(vma
, addr
, ptent
);
4314 if (!page
|| !page_mapped(page
))
4316 if (PageAnon(page
)) {
4317 /* we don't move shared anon */
4318 if (!move_anon() || page_mapcount(page
) > 2)
4320 } else if (!move_file())
4321 /* we ignore mapcount for file pages */
4323 if (!get_page_unless_zero(page
))
4329 static struct page
*mc_handle_swap_pte(struct vm_area_struct
*vma
,
4330 unsigned long addr
, pte_t ptent
, swp_entry_t
*entry
)
4333 struct page
*page
= NULL
;
4334 swp_entry_t ent
= pte_to_swp_entry(ptent
);
4336 if (!move_anon() || non_swap_entry(ent
))
4338 usage_count
= mem_cgroup_count_swap_user(ent
, &page
);
4339 if (usage_count
> 1) { /* we don't move shared anon */
4344 if (do_swap_account
)
4345 entry
->val
= ent
.val
;
4350 static struct page
*mc_handle_file_pte(struct vm_area_struct
*vma
,
4351 unsigned long addr
, pte_t ptent
, swp_entry_t
*entry
)
4353 struct page
*page
= NULL
;
4354 struct inode
*inode
;
4355 struct address_space
*mapping
;
4358 if (!vma
->vm_file
) /* anonymous vma */
4363 inode
= vma
->vm_file
->f_path
.dentry
->d_inode
;
4364 mapping
= vma
->vm_file
->f_mapping
;
4365 if (pte_none(ptent
))
4366 pgoff
= linear_page_index(vma
, addr
);
4367 else /* pte_file(ptent) is true */
4368 pgoff
= pte_to_pgoff(ptent
);
4370 /* page is moved even if it's not RSS of this task(page-faulted). */
4371 if (!mapping_cap_swap_backed(mapping
)) { /* normal file */
4372 page
= find_get_page(mapping
, pgoff
);
4373 } else { /* shmem/tmpfs file. we should take account of swap too. */
4375 mem_cgroup_get_shmem_target(inode
, pgoff
, &page
, &ent
);
4376 if (do_swap_account
)
4377 entry
->val
= ent
.val
;
4383 static int is_target_pte_for_mc(struct vm_area_struct
*vma
,
4384 unsigned long addr
, pte_t ptent
, union mc_target
*target
)
4386 struct page
*page
= NULL
;
4387 struct page_cgroup
*pc
;
4389 swp_entry_t ent
= { .val
= 0 };
4391 if (pte_present(ptent
))
4392 page
= mc_handle_present_pte(vma
, addr
, ptent
);
4393 else if (is_swap_pte(ptent
))
4394 page
= mc_handle_swap_pte(vma
, addr
, ptent
, &ent
);
4395 else if (pte_none(ptent
) || pte_file(ptent
))
4396 page
= mc_handle_file_pte(vma
, addr
, ptent
, &ent
);
4398 if (!page
&& !ent
.val
)
4401 pc
= lookup_page_cgroup(page
);
4403 * Do only loose check w/o page_cgroup lock.
4404 * mem_cgroup_move_account() checks the pc is valid or not under
4407 if (PageCgroupUsed(pc
) && pc
->mem_cgroup
== mc
.from
) {
4408 ret
= MC_TARGET_PAGE
;
4410 target
->page
= page
;
4412 if (!ret
|| !target
)
4415 /* There is a swap entry and a page doesn't exist or isn't charged */
4416 if (ent
.val
&& !ret
&&
4417 css_id(&mc
.from
->css
) == lookup_swap_cgroup(ent
)) {
4418 ret
= MC_TARGET_SWAP
;
4425 static int mem_cgroup_count_precharge_pte_range(pmd_t
*pmd
,
4426 unsigned long addr
, unsigned long end
,
4427 struct mm_walk
*walk
)
4429 struct vm_area_struct
*vma
= walk
->private;
4433 pte
= pte_offset_map_lock(vma
->vm_mm
, pmd
, addr
, &ptl
);
4434 for (; addr
!= end
; pte
++, addr
+= PAGE_SIZE
)
4435 if (is_target_pte_for_mc(vma
, addr
, *pte
, NULL
))
4436 mc
.precharge
++; /* increment precharge temporarily */
4437 pte_unmap_unlock(pte
- 1, ptl
);
4443 static unsigned long mem_cgroup_count_precharge(struct mm_struct
*mm
)
4445 unsigned long precharge
;
4446 struct vm_area_struct
*vma
;
4448 down_read(&mm
->mmap_sem
);
4449 for (vma
= mm
->mmap
; vma
; vma
= vma
->vm_next
) {
4450 struct mm_walk mem_cgroup_count_precharge_walk
= {
4451 .pmd_entry
= mem_cgroup_count_precharge_pte_range
,
4455 if (is_vm_hugetlb_page(vma
))
4457 walk_page_range(vma
->vm_start
, vma
->vm_end
,
4458 &mem_cgroup_count_precharge_walk
);
4460 up_read(&mm
->mmap_sem
);
4462 precharge
= mc
.precharge
;
4468 static int mem_cgroup_precharge_mc(struct mm_struct
*mm
)
4470 return mem_cgroup_do_precharge(mem_cgroup_count_precharge(mm
));
4473 static void mem_cgroup_clear_mc(void)
4475 struct mem_cgroup
*from
= mc
.from
;
4476 struct mem_cgroup
*to
= mc
.to
;
4478 /* we must uncharge all the leftover precharges from mc.to */
4480 __mem_cgroup_cancel_charge(mc
.to
, mc
.precharge
);
4484 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
4485 * we must uncharge here.
4487 if (mc
.moved_charge
) {
4488 __mem_cgroup_cancel_charge(mc
.from
, mc
.moved_charge
);
4489 mc
.moved_charge
= 0;
4491 /* we must fixup refcnts and charges */
4492 if (mc
.moved_swap
) {
4493 /* uncharge swap account from the old cgroup */
4494 if (!mem_cgroup_is_root(mc
.from
))
4495 res_counter_uncharge(&mc
.from
->memsw
,
4496 PAGE_SIZE
* mc
.moved_swap
);
4497 __mem_cgroup_put(mc
.from
, mc
.moved_swap
);
4499 if (!mem_cgroup_is_root(mc
.to
)) {
4501 * we charged both to->res and to->memsw, so we should
4504 res_counter_uncharge(&mc
.to
->res
,
4505 PAGE_SIZE
* mc
.moved_swap
);
4507 /* we've already done mem_cgroup_get(mc.to) */
4511 spin_lock(&mc
.lock
);
4514 mc
.moving_task
= NULL
;
4515 spin_unlock(&mc
.lock
);
4516 memcg_oom_recover(from
);
4517 memcg_oom_recover(to
);
4518 wake_up_all(&mc
.waitq
);
4521 static int mem_cgroup_can_attach(struct cgroup_subsys
*ss
,
4522 struct cgroup
*cgroup
,
4523 struct task_struct
*p
,
4527 struct mem_cgroup
*mem
= mem_cgroup_from_cont(cgroup
);
4529 if (mem
->move_charge_at_immigrate
) {
4530 struct mm_struct
*mm
;
4531 struct mem_cgroup
*from
= mem_cgroup_from_task(p
);
4533 VM_BUG_ON(from
== mem
);
4535 mm
= get_task_mm(p
);
4538 /* We move charges only when we move a owner of the mm */
4539 if (mm
->owner
== p
) {
4542 VM_BUG_ON(mc
.precharge
);
4543 VM_BUG_ON(mc
.moved_charge
);
4544 VM_BUG_ON(mc
.moved_swap
);
4545 VM_BUG_ON(mc
.moving_task
);
4546 spin_lock(&mc
.lock
);
4550 mc
.moved_charge
= 0;
4552 mc
.moving_task
= current
;
4553 spin_unlock(&mc
.lock
);
4555 ret
= mem_cgroup_precharge_mc(mm
);
4557 mem_cgroup_clear_mc();
4564 static void mem_cgroup_cancel_attach(struct cgroup_subsys
*ss
,
4565 struct cgroup
*cgroup
,
4566 struct task_struct
*p
,
4569 mem_cgroup_clear_mc();
4572 static int mem_cgroup_move_charge_pte_range(pmd_t
*pmd
,
4573 unsigned long addr
, unsigned long end
,
4574 struct mm_walk
*walk
)
4577 struct vm_area_struct
*vma
= walk
->private;
4582 pte
= pte_offset_map_lock(vma
->vm_mm
, pmd
, addr
, &ptl
);
4583 for (; addr
!= end
; addr
+= PAGE_SIZE
) {
4584 pte_t ptent
= *(pte
++);
4585 union mc_target target
;
4588 struct page_cgroup
*pc
;
4594 type
= is_target_pte_for_mc(vma
, addr
, ptent
, &target
);
4596 case MC_TARGET_PAGE
:
4598 if (isolate_lru_page(page
))
4600 pc
= lookup_page_cgroup(page
);
4601 if (!mem_cgroup_move_account(pc
,
4602 mc
.from
, mc
.to
, false)) {
4604 /* we uncharge from mc.from later. */
4607 putback_lru_page(page
);
4608 put
: /* is_target_pte_for_mc() gets the page */
4611 case MC_TARGET_SWAP
:
4613 if (!mem_cgroup_move_swap_account(ent
,
4614 mc
.from
, mc
.to
, false)) {
4616 /* we fixup refcnts and charges later. */
4624 pte_unmap_unlock(pte
- 1, ptl
);
4629 * We have consumed all precharges we got in can_attach().
4630 * We try charge one by one, but don't do any additional
4631 * charges to mc.to if we have failed in charge once in attach()
4634 ret
= mem_cgroup_do_precharge(1);
4642 static void mem_cgroup_move_charge(struct mm_struct
*mm
)
4644 struct vm_area_struct
*vma
;
4646 lru_add_drain_all();
4647 down_read(&mm
->mmap_sem
);
4648 for (vma
= mm
->mmap
; vma
; vma
= vma
->vm_next
) {
4650 struct mm_walk mem_cgroup_move_charge_walk
= {
4651 .pmd_entry
= mem_cgroup_move_charge_pte_range
,
4655 if (is_vm_hugetlb_page(vma
))
4657 ret
= walk_page_range(vma
->vm_start
, vma
->vm_end
,
4658 &mem_cgroup_move_charge_walk
);
4661 * means we have consumed all precharges and failed in
4662 * doing additional charge. Just abandon here.
4666 up_read(&mm
->mmap_sem
);
4669 static void mem_cgroup_move_task(struct cgroup_subsys
*ss
,
4670 struct cgroup
*cont
,
4671 struct cgroup
*old_cont
,
4672 struct task_struct
*p
,
4675 struct mm_struct
*mm
;
4678 /* no need to move charge */
4681 mm
= get_task_mm(p
);
4683 mem_cgroup_move_charge(mm
);
4686 mem_cgroup_clear_mc();
4688 #else /* !CONFIG_MMU */
4689 static int mem_cgroup_can_attach(struct cgroup_subsys
*ss
,
4690 struct cgroup
*cgroup
,
4691 struct task_struct
*p
,
4696 static void mem_cgroup_cancel_attach(struct cgroup_subsys
*ss
,
4697 struct cgroup
*cgroup
,
4698 struct task_struct
*p
,
4702 static void mem_cgroup_move_task(struct cgroup_subsys
*ss
,
4703 struct cgroup
*cont
,
4704 struct cgroup
*old_cont
,
4705 struct task_struct
*p
,
4711 struct cgroup_subsys mem_cgroup_subsys
= {
4713 .subsys_id
= mem_cgroup_subsys_id
,
4714 .create
= mem_cgroup_create
,
4715 .pre_destroy
= mem_cgroup_pre_destroy
,
4716 .destroy
= mem_cgroup_destroy
,
4717 .populate
= mem_cgroup_populate
,
4718 .can_attach
= mem_cgroup_can_attach
,
4719 .cancel_attach
= mem_cgroup_cancel_attach
,
4720 .attach
= mem_cgroup_move_task
,
4725 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4727 static int __init
disable_swap_account(char *s
)
4729 really_do_swap_account
= 0;
4732 __setup("noswapaccount", disable_swap_account
);